chiark / gitweb /
=== modified file 'debian/changelog'
[autopkgtest.git] / virt-subproc / VirtSubproc.py
1 # VirtSubproc is part of autopkgtest
2 # autopkgtest is a tool for testing Debian binary packages
3 #
4 # autopkgtest is Copyright (C) 2006 Canonical Ltd.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 #
20 # See the file CREDITS for a full list of credits information (often
21 # installed as /usr/share/doc/autopkgtest/CREDITS).
22
23 import __main__
24
25 import sys
26 import os
27 import string
28 import urllib
29 import signal
30 import subprocess
31 import traceback
32
33 debuglevel = None
34 progname = "<VirtSubproc>"
35 devnull_read = file('/dev/null','r')
36 caller = __main__
37
38 class Quit:
39         def __init__(q,ec,m): q.ec = ec; q.m = m
40
41 def debug(m):
42         if not debuglevel: return
43         print >> sys.stderr, progname+": debug:", m
44
45 def bomb(m):
46         raise Quit(12, progname+": failure: %s" % m)
47
48 def ok(): print 'ok'
49
50 def cmdnumargs(c, ce, nargs=0):
51         if len(c) == nargs + 1: return
52         bomb("wrong number of arguments to command `%s'" % ce[0])
53
54 def cmd_capabilities(c, ce):
55         cmdnumargs(c, ce)
56
57 def cmd_quit(c, ce):
58         cmdnumargs(c, ce)
59         raise Quit(0, '')
60
61 def execute_raw(what, instr, *popenargs, **popenargsk):
62         debug(" ++ %s" % string.join(popenargs[0]))
63         sp = subprocess.Popen(*popenargs, **popenargsk)
64         if instr is None: popenargsk['stdin'] = devnull_read
65         (out, err) = sp.communicate(instr)
66         if err: bomb("%s unexpectedly produced stderr output `%s'" %
67                         (what, err))
68         status = sp.wait()
69         return (status, out)
70
71 def execute(cmd_string, cmd_list=[], downp=False, outp=False):
72         cmdl = cmd_string.split()
73
74         if downp: perhaps_down = down
75         else: downp = []
76
77         if outp: stdout = subprocess.PIPE
78         else: stdout = None
79
80         cmd = cmdl + cmd_list
81         if len(perhaps_down): cmd = perhaps_down + [' '.join(cmd)]
82
83         (status, out) = execute_raw(cmdl[0], None, cmd, stdout=stdout)
84
85         if status: bomb("%s%s failed (exit status %d)" %
86                         ((downp and "(down) " or ""), cmdl[0], status))
87
88         if outp and out and out[-1]=='\n': out = out[:-1]
89         return out
90
91 def cmd_open(c, ce):
92         global downtmp
93         cmdnumargs(c, ce)
94         if downtmp: bomb("`open' when already open")
95         downtmp = caller.hook_open()
96         return [downtmp]
97
98 def cmd_close(c, ce):
99         global downtmp
100         cmdnumargs(c, ce)
101         if not downtmp: bomb("`close' when not open")
102         cleanup()
103
104 def cmd_stop(c, ce):
105         global downtmp
106         cmdnumargs(c, ce, 1)
107         if not downtmp: bomb("`stop' when not open")
108         caller.hook_stop()
109         cleanup()
110
111 def down_python_script(gobody, functions=''):
112         # Many things are made much harder by the inability of
113         # dchroot, ssh, et al, to cope without mangling the arguments.
114         # So we run a sub-python on the testbed and feed it a script
115         # on stdin.  The sub-python decodes the arguments.
116
117         script = (      "import urllib\n"
118                         "import os\n"
119                         "def setfd(fd,fnamee,write,mode=0666):\n"
120                         "       fname = urllib.unquote(fnamee)\n"
121                         "       if write: rw = os.O_WRONLY|os.O_CREAT\n"
122                         "       else: rw = os.O_RDONLY\n"
123                         "       nfd = os.open(fname, rw, mode)\n"
124                         "       os.dup2(nfd,fd)\n"
125                         + functions +
126                         "def go():\n" )
127         script += (     "       os.environ['TMPDIR']= urllib.unquote('%s')\n" %
128                                 urllib.quote(downtmp)   )
129         script += (     "       os.chdir(os.environ['TMPDIR'])\n" )
130         script += (     gobody +
131                         "go()\n" )
132
133         debug("+P ...\n"+script)
134
135         scripte = urllib.quote(script)
136         cmdl = down + ['python','-c',
137                 "'import urllib; s = urllib.unquote(%s); exec s'" %
138                         ('"%s"' % scripte)]
139         return cmdl
140
141 def cmd_execute(c, ce):
142         cmdnumargs(c, ce, 5)
143         gobody = "      import sys\n"
144         for ioe in range(3):
145                 gobody += "     setfd(%d,'%s',%d)\n" % (
146                         ioe, ce[ioe+2], ioe>0 )
147         gobody += "     os.chdir(urllib.unquote('" + ce[5] +"'))\n"
148         gobody += "     cmd = '%s'\n" % ce[1]
149         gobody += ("    cmd = cmd.split(',')\n"
150                 "       cmd = map(urllib.unquote, cmd)\n"
151                 "       c0 = cmd[0]\n"
152                 "       if '/' in c0:\n"
153                 "               if not os.access(c0, os.X_OK):\n"
154                 "                       status = os.stat(c0)\n"
155                 "                       mode = status.st_mode | 0111\n"
156                 "                       os.chmod(c0, mode)\n"
157                 "       try: os.execvp(c0, cmd)\n"
158                 "       except OSError, e:\n"
159                 "               print >>sys.stderr, \"%s: %s\" % (\n"
160                 "                       (c0, os.strerror(e.errno)))\n"
161                 "               os._exit(127)\n")
162         cmdl = down_python_script(gobody)
163
164         (status, out) = execute_raw('sub-python', None, cmdl,
165                                 stdin=devnull_read, stderr=subprocess.PIPE)
166         if out: bomb("sub-python unexpected produced stdout"
167                         " visible to us `%s'" % out)
168         return [`status`]
169
170 def copyupdown(c, ce, upp):
171         cmdnumargs(c, ce, 2)
172         isrc = 0
173         idst = 1
174         ilocal = 0 + upp
175         iremote = 1 - upp
176         wh = ce[0]
177         sd = c[1:]
178         sde = ce[1:]
179         if not sd[0] or not sd[1]:
180                 bomb("%s paths must be nonempty" % wh)
181         dirsp = sd[0][-1]=='/'
182         functions = "import errno\n"
183         if dirsp != (sd[1][-1]=='/'):
184                 bomb("% paths must agree about directoryness"
185                         " (presence or absence of trailing /)" % wh)
186         localfd = None
187         deststdout = devnull_read
188         srcstdin = devnull_read
189         preexecfns = [None, None]
190         if not dirsp:
191                 modestr = ''
192                 if upp:
193                         deststdout = file(sd[idst], 'w')
194                 else:
195                         srcstdin = file(sd[isrc], 'r')
196                         status = os.fstat(srcstdin.fileno())
197                         if status.st_mode & 0111: modestr = ',0777'
198                 gobody = "      setfd(%s,'%s',%s%s)\n" % (
199                                         1-upp, sde[iremote], not upp, modestr)
200                 gobody += "     os.execvp('cat', ['cat'])\n"
201                 localcmdl = ['cat']
202         else:
203                 gobody = "      dir = urllib.unquote('%s')\n" % sde[iremote]
204                 if upp:
205                         try: os.mkdir(sd[ilocal])
206                         except OSError, oe:
207                                 if oe.errno != errno.EEXIST: raise
208                 else:
209                         gobody += ("    try: os.mkdir(dir)\n"
210                                 "       except OSError, oe:\n"
211                                 "               if oe.errno != errno.EEXIST: raise\n")
212                 gobody +=( "    os.chdir(dir)\n"
213                         "       tarcmd = 'tar -f -'.split()\n")
214                 localcmdl = 'tar -f -'.split()
215                 taropts = [None, None]
216                 taropts[isrc] = '-c .'
217                 taropts[idst] = '-p -x --no-same-owner'
218                 gobody += "     tarcmd += '%s'.split()\n" % taropts[iremote]
219                 localcmdl += ['-C',sd[ilocal]]
220                 localcmdl += taropts[ilocal].split()
221                 gobody += "     os.execvp('tar', tarcmd)\n";
222
223         downcmdl = down_python_script(gobody, functions)
224
225         if upp: cmdls = (downcmdl, localcmdl)
226         else: cmdls = (localcmdl, downcmdl)
227
228         debug(`["cmdls", `cmdls`]`)
229         debug(`["srcstdin", `srcstdin`, "deststdout", `deststdout`, "devnull_read", devnull_read]`)
230
231         subprocs = [None,None]
232         debug(" +< %s" % string.join(cmdls[0]))
233         subprocs[0] = subprocess.Popen(cmdls[0], stdin=srcstdin,
234                         stdout=subprocess.PIPE, preexec_fn=preexecfns[0])
235         debug(" +> %s" % string.join(cmdls[1]))
236         subprocs[1] = subprocess.Popen(cmdls[1], stdin=subprocs[0].stdout,
237                         stdout=deststdout, preexec_fn=preexecfns[1])
238         for sdn in [1,0]:
239                 status = subprocs[sdn].wait()
240                 if status: bomb("%s %s failed, status %d" %
241                         (wh, ['source','destination'][sdn], status))
242
243 def cmd_copydown(c, ce): copyupdown(c, ce, False)
244 def cmd_copyup(c, ce): copyupdown(c, ce, True)
245
246 def command():
247         sys.stdout.flush()
248         ce = sys.stdin.readline()
249         if not ce: bomb('end of file - caller quit?')
250         ce = ce.rstrip().split()
251         c = map(urllib.unquote, ce)
252         if not c: bomb('empty commands are not permitted')
253         debug('executing '+string.join(ce))
254         try: f = globals()['cmd_'+c[0]]
255         except KeyError: bomb("unknown command `%s'" % ce[0])
256         r = f(c, ce)
257         if not r: r = []
258         r.insert(0, 'ok')
259         ru = map(urllib.quote, r)
260         print string.join(ru)
261
262 def cleanup():
263         global downtmp, cleaning
264         cleaning = True
265         if downtmp: caller.hook_cleanup()
266         cleaning = False
267         downtmp = False
268
269 def error_cleanup():
270         try:
271                 ok = False
272                 try:
273                         cleanup()
274                         ok = True
275                 except Quit, q:
276                         print >> sys.stderr, q.m
277                 except:
278                         print >> sys.stderr, "Unexpected cleanup error:"
279                         traceback.print_exc()
280                         print >> sys.stderr, ''
281                 if not ok:
282                         print >> sys.stderr, ("while cleaning up"
283                                 " because of another error:")
284         except:
285                 pass
286
287 def prepare():
288         global downtmp, cleaning
289         downtmp = None
290         signal_list = [ signal.SIGHUP, signal.SIGTERM,
291                         signal.SIGINT, signal.SIGPIPE ]
292         def sethandlers(f):
293                 for signum in signal_list: signal.signal(signum, f)
294         def handler(sig, *any):
295                 sethandlers(signal.SIG_DFL)
296                 cleanup()
297                 os.kill(os.getpid(), sig)
298         sethandlers(handler)
299
300 def mainloop():
301         try:
302                 while True: command()
303         except Quit, q:
304                 error_cleanup()
305                 if q.m: print >> sys.stderr, q.m
306                 sys.exit(q.ec)
307         except:
308                 error_cleanup()
309                 print >> sys.stderr, "Unexpected error:"
310                 traceback.print_exc()
311                 sys.exit(16)
312
313 def main():
314         ok()
315         prepare()
316         mainloop()