chiark / gitweb /
implement close command (!)
[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 cmd_close(c, ce):
63         cmdnumargs(c, ce)
64         if not downtmp: bomb("`close' when not open")
65         cleanup()
66
67 def execute_raw(what, instr, *popenargs, **popenargsk):
68         debug(" ++ %s" % string.join(popenargs[0]))
69         sp = subprocess.Popen(*popenargs, **popenargsk)
70         if instr is None: popenargsk['stdin'] = devnull_read
71         (out, err) = sp.communicate(instr)
72         if err: bomb("%s unexpectedly produced stderr output `%s'" %
73                         (what, err))
74         status = sp.wait()
75         return (status, out)
76
77 def execute(cmd_string, cmd_list=[], downp=False, outp=False):
78         cmdl = cmd_string.split()
79
80         if downp: perhaps_down = down
81         else: downp = []
82
83         if outp: stdout = subprocess.PIPE
84         else: stdout = None
85
86         cmd = cmdl + cmd_list
87         if len(perhaps_down): cmd = perhaps_down + [' '.join(cmd)]
88
89         (status, out) = execute_raw(cmdl[0], None, cmd, stdout=stdout)
90
91         if status: bomb("%s%s failed (exit status %d)" %
92                         ((downp and "(down) " or ""), cmdl[0], status))
93
94         if outp and out and out[-1]=='\n': out = out[:-1]
95         return out
96
97 def cmd_open(c, ce):
98         global downtmp
99         cmdnumargs(c, ce)
100         if downtmp: bomb("`open' when already open")
101         downtmp = caller.hook_open()
102         return [downtmp]
103
104 def cmd_reset(c, ce):
105         cmdnumargs(c, ce)
106         if not downtmp: bomb("`reset' when not open")
107         if not 'revert' in caller.hook_capabilities():
108                 bomb("`reset' when `revert' not advertised")
109         caller.hook_reset()
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         print string.join(r)
260
261 def cleanup():
262         global downtmp, cleaning
263         cleaning = True
264         if downtmp: caller.hook_cleanup()
265         cleaning = False
266         downtmp = False
267
268 def error_cleanup():
269         try:
270                 ok = False
271                 try:
272                         cleanup()
273                         ok = True
274                 except Quit, q:
275                         print >> sys.stderr, q.m
276                 except:
277                         print >> sys.stderr, "Unexpected cleanup error:"
278                         traceback.print_exc()
279                         print >> sys.stderr, ''
280                 if not ok:
281                         print >> sys.stderr, ("while cleaning up"
282                                 " because of another error:")
283         except:
284                 pass
285
286 def prepare():
287         global downtmp, cleaning
288         downtmp = None
289         signal_list = [ signal.SIGHUP, signal.SIGTERM,
290                         signal.SIGINT, signal.SIGPIPE ]
291         def sethandlers(f):
292                 for signum in signal_list: signal.signal(signum, f)
293         def handler(sig, *any):
294                 sethandlers(signal.SIG_DFL)
295                 cleanup()
296                 os.kill(os.getpid(), sig)
297         sethandlers(handler)
298
299 def mainloop():
300         try:
301                 while True: command()
302         except Quit, q:
303                 error_cleanup()
304                 if q.m: print >> sys.stderr, q.m
305                 sys.exit(q.ec)
306         except:
307                 error_cleanup()
308                 print >> sys.stderr, "Unexpected error:"
309                 traceback.print_exc()
310                 sys.exit(16)
311
312 def main():
313         debug("down = %s" % string.join(down))
314         ok()
315         prepare()
316         mainloop()