chiark / gitweb /
make adt-virt-xenlvm work again
[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         return caller.hook_capabilities()
57
58 def cmd_quit(c, ce):
59         cmdnumargs(c, ce)
60         raise Quit(0, '')
61
62 def execute_raw(what, instr, *popenargs, **popenargsk):
63         debug(" ++ %s" % string.join(popenargs[0]))
64         sp = subprocess.Popen(*popenargs, **popenargsk)
65         if instr is None: popenargsk['stdin'] = devnull_read
66         (out, err) = sp.communicate(instr)
67         if err: bomb("%s unexpectedly produced stderr output `%s'" %
68                         (what, err))
69         status = sp.wait()
70         return (status, out)
71
72 def execute(cmd_string, cmd_list=[], downp=False, outp=False):
73         cmdl = cmd_string.split()
74
75         if downp: perhaps_down = down
76         else: downp = []
77
78         if outp: stdout = subprocess.PIPE
79         else: stdout = None
80
81         cmd = cmdl + cmd_list
82         if len(perhaps_down): cmd = perhaps_down + [' '.join(cmd)]
83
84         (status, out) = execute_raw(cmdl[0], None, cmd, stdout=stdout)
85
86         if status: bomb("%s%s failed (exit status %d)" %
87                         ((downp and "(down) " or ""), cmdl[0], status))
88
89         if outp and out and out[-1]=='\n': out = out[:-1]
90         return out
91
92 def cmd_open(c, ce):
93         global downtmp
94         cmdnumargs(c, ce)
95         if downtmp: bomb("`open' when already open")
96         downtmp = caller.hook_open()
97         return [downtmp]
98
99 def cmd_reset(c, ce):
100         cmdnumargs(c, ce)
101         if not downtmp: bomb("`reset' when not open")
102         if not 'revert' in caller.hook_capabilities():
103                 bomb("`reset' when `revert' not advertised")
104         caller.hook_reset()
105
106 def down_python_script(gobody, functions=''):
107         # Many things are made much harder by the inability of
108         # dchroot, ssh, et al, to cope without mangling the arguments.
109         # So we run a sub-python on the testbed and feed it a script
110         # on stdin.  The sub-python decodes the arguments.
111
112         script = (      "import urllib\n"
113                         "import os\n"
114                         "def setfd(fd,fnamee,write,mode=0666):\n"
115                         "       fname = urllib.unquote(fnamee)\n"
116                         "       if write: rw = os.O_WRONLY|os.O_CREAT\n"
117                         "       else: rw = os.O_RDONLY\n"
118                         "       nfd = os.open(fname, rw, mode)\n"
119                         "       os.dup2(nfd,fd)\n"
120                         + functions +
121                         "def go():\n" )
122         script += (     "       os.environ['TMPDIR']= urllib.unquote('%s')\n" %
123                                 urllib.quote(downtmp)   )
124         script += (     "       os.chdir(os.environ['TMPDIR'])\n" )
125         script += (     gobody +
126                         "go()\n" )
127
128         debug("+P ...\n"+script)
129
130         scripte = urllib.quote(script)
131         cmdl = down + ['python','-c',
132                 "'import urllib; s = urllib.unquote(%s); exec s'" %
133                         ('"%s"' % scripte)]
134         return cmdl
135
136 def cmd_execute(c, ce):
137         cmdnumargs(c, ce, 5)
138         gobody = "      import sys\n"
139         for ioe in range(3):
140                 gobody += "     setfd(%d,'%s',%d)\n" % (
141                         ioe, ce[ioe+2], ioe>0 )
142         gobody += "     os.chdir(urllib.unquote('" + ce[5] +"'))\n"
143         gobody += "     cmd = '%s'\n" % ce[1]
144         gobody += ("    cmd = cmd.split(',')\n"
145                 "       cmd = map(urllib.unquote, cmd)\n"
146                 "       c0 = cmd[0]\n"
147                 "       if '/' in c0:\n"
148                 "               if not os.access(c0, os.X_OK):\n"
149                 "                       status = os.stat(c0)\n"
150                 "                       mode = status.st_mode | 0111\n"
151                 "                       os.chmod(c0, mode)\n"
152                 "       try: os.execvp(c0, cmd)\n"
153                 "       except OSError, e:\n"
154                 "               print >>sys.stderr, \"%s: %s\" % (\n"
155                 "                       (c0, os.strerror(e.errno)))\n"
156                 "               os._exit(127)\n")
157         cmdl = down_python_script(gobody)
158
159         (status, out) = execute_raw('sub-python', None, cmdl,
160                                 stdin=devnull_read, stderr=subprocess.PIPE)
161         if out: bomb("sub-python unexpected produced stdout"
162                         " visible to us `%s'" % out)
163         return [`status`]
164
165 def copyupdown(c, ce, upp):
166         cmdnumargs(c, ce, 2)
167         isrc = 0
168         idst = 1
169         ilocal = 0 + upp
170         iremote = 1 - upp
171         wh = ce[0]
172         sd = c[1:]
173         sde = ce[1:]
174         if not sd[0] or not sd[1]:
175                 bomb("%s paths must be nonempty" % wh)
176         dirsp = sd[0][-1]=='/'
177         functions = "import errno\n"
178         if dirsp != (sd[1][-1]=='/'):
179                 bomb("% paths must agree about directoryness"
180                         " (presence or absence of trailing /)" % wh)
181         localfd = None
182         deststdout = devnull_read
183         srcstdin = devnull_read
184         preexecfns = [None, None]
185         if not dirsp:
186                 modestr = ''
187                 if upp:
188                         deststdout = file(sd[idst], 'w')
189                 else:
190                         srcstdin = file(sd[isrc], 'r')
191                         status = os.fstat(srcstdin.fileno())
192                         if status.st_mode & 0111: modestr = ',0777'
193                 gobody = "      setfd(%s,'%s',%s%s)\n" % (
194                                         1-upp, sde[iremote], not upp, modestr)
195                 gobody += "     os.execvp('cat', ['cat'])\n"
196                 localcmdl = ['cat']
197         else:
198                 gobody = "      dir = urllib.unquote('%s')\n" % sde[iremote]
199                 if upp:
200                         try: os.mkdir(sd[ilocal])
201                         except OSError, oe:
202                                 if oe.errno != errno.EEXIST: raise
203                 else:
204                         gobody += ("    try: os.mkdir(dir)\n"
205                                 "       except OSError, oe:\n"
206                                 "               if oe.errno != errno.EEXIST: raise\n")
207                 gobody +=( "    os.chdir(dir)\n"
208                         "       tarcmd = 'tar -f -'.split()\n")
209                 localcmdl = 'tar -f -'.split()
210                 taropts = [None, None]
211                 taropts[isrc] = '-c .'
212                 taropts[idst] = '-p -x --no-same-owner'
213                 gobody += "     tarcmd += '%s'.split()\n" % taropts[iremote]
214                 localcmdl += ['-C',sd[ilocal]]
215                 localcmdl += taropts[ilocal].split()
216                 gobody += "     os.execvp('tar', tarcmd)\n";
217
218         downcmdl = down_python_script(gobody, functions)
219
220         if upp: cmdls = (downcmdl, localcmdl)
221         else: cmdls = (localcmdl, downcmdl)
222
223         debug(`["cmdls", `cmdls`]`)
224         debug(`["srcstdin", `srcstdin`, "deststdout", `deststdout`, "devnull_read", devnull_read]`)
225
226         subprocs = [None,None]
227         debug(" +< %s" % string.join(cmdls[0]))
228         subprocs[0] = subprocess.Popen(cmdls[0], stdin=srcstdin,
229                         stdout=subprocess.PIPE, preexec_fn=preexecfns[0])
230         debug(" +> %s" % string.join(cmdls[1]))
231         subprocs[1] = subprocess.Popen(cmdls[1], stdin=subprocs[0].stdout,
232                         stdout=deststdout, preexec_fn=preexecfns[1])
233         for sdn in [1,0]:
234                 status = subprocs[sdn].wait()
235                 if status: bomb("%s %s failed, status %d" %
236                         (wh, ['source','destination'][sdn], status))
237
238 def cmd_copydown(c, ce): copyupdown(c, ce, False)
239 def cmd_copyup(c, ce): copyupdown(c, ce, True)
240
241 def command():
242         sys.stdout.flush()
243         ce = sys.stdin.readline()
244         if not ce: bomb('end of file - caller quit?')
245         ce = ce.rstrip().split()
246         c = map(urllib.unquote, ce)
247         if not c: bomb('empty commands are not permitted')
248         debug('executing '+string.join(ce))
249         try: f = globals()['cmd_'+c[0]]
250         except KeyError: bomb("unknown command `%s'" % ce[0])
251         r = f(c, ce)
252         if not r: r = []
253         r.insert(0, 'ok')
254         print string.join(r)
255
256 def cleanup():
257         global downtmp, cleaning
258         cleaning = True
259         if downtmp: caller.hook_cleanup()
260         cleaning = False
261         downtmp = False
262
263 def error_cleanup():
264         try:
265                 ok = False
266                 try:
267                         cleanup()
268                         ok = True
269                 except Quit, q:
270                         print >> sys.stderr, q.m
271                 except:
272                         print >> sys.stderr, "Unexpected cleanup error:"
273                         traceback.print_exc()
274                         print >> sys.stderr, ''
275                 if not ok:
276                         print >> sys.stderr, ("while cleaning up"
277                                 " because of another error:")
278         except:
279                 pass
280
281 def prepare():
282         global downtmp, cleaning
283         downtmp = None
284         signal_list = [ signal.SIGHUP, signal.SIGTERM,
285                         signal.SIGINT, signal.SIGPIPE ]
286         def sethandlers(f):
287                 for signum in signal_list: signal.signal(signum, f)
288         def handler(sig, *any):
289                 sethandlers(signal.SIG_DFL)
290                 cleanup()
291                 os.kill(os.getpid(), sig)
292         sethandlers(handler)
293
294 def mainloop():
295         try:
296                 while True: command()
297         except Quit, q:
298                 error_cleanup()
299                 if q.m: print >> sys.stderr, q.m
300                 sys.exit(q.ec)
301         except:
302                 error_cleanup()
303                 print >> sys.stderr, "Unexpected error:"
304                 traceback.print_exc()
305                 sys.exit(16)
306
307 def main():
308         debug("down = %s" % string.join(down))
309         ok()
310         prepare()
311         mainloop()