1 # VirtSubproc is part of autopkgtest
2 # autopkgtest is a tool for testing Debian binary packages
4 # autopkgtest is Copyright (C) 2006 Canonical Ltd.
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.
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.
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.
20 # See the file CREDITS for a full list of credits information (often
21 # installed as /usr/share/doc/autopkgtest/CREDITS).
34 progname = "<VirtSubproc>"
35 devnull_read = file('/dev/null','r')
39 def __init__(q,ec,m): q.ec = ec; q.m = m
42 if not debuglevel: return
43 print >> sys.stderr, progname+": debug:", m
46 raise Quit(12, progname+": failure: %s" % m)
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])
54 def cmd_capabilities(c, ce):
56 return caller.hook_capabilities()
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'" %
72 def execute(cmd_string, cmd_list=[], downp=False, outp=False):
73 cmdl = cmd_string.split()
75 if downp: perhaps_down = down
78 if outp: stdout = subprocess.PIPE
82 if len(perhaps_down): cmd = perhaps_down + [' '.join(cmd)]
84 (status, out) = execute_raw(cmdl[0], None, cmd, stdout=stdout)
86 if status: bomb("%s%s failed (exit status %d)" %
87 ((downp and "(down) " or ""), cmdl[0], status))
89 if outp and out and out[-1]=='\n': out = out[:-1]
95 if downtmp: bomb("`open' when already open")
96 downtmp = caller.hook_open()
101 if not downtmp: bomb("`reset' when not open")
102 if not 'revert' in caller.hook_capabilities():
103 bomb("`reset' when `revert' not advertised")
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.
112 script = ( "import urllib\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"
122 script += ( " os.environ['TMPDIR']= urllib.unquote('%s')\n" %
123 urllib.quote(downtmp) )
124 script += ( " os.chdir(os.environ['TMPDIR'])\n" )
128 debug("+P ...\n"+script)
130 scripte = urllib.quote(script)
131 cmdl = down + ['python','-c',
132 "'import urllib; s = urllib.unquote(%s); exec s'" %
136 def cmd_execute(c, ce):
138 gobody = " import sys\n"
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"
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"
157 cmdl = down_python_script(gobody)
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)
165 def copyupdown(c, ce, upp):
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)
182 deststdout = devnull_read
183 srcstdin = devnull_read
184 preexecfns = [None, None]
188 deststdout = file(sd[idst], 'w')
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"
198 gobody = " dir = urllib.unquote('%s')\n" % sde[iremote]
200 try: os.mkdir(sd[ilocal])
202 if oe.errno != errno.EEXIST: raise
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";
218 downcmdl = down_python_script(gobody, functions)
220 if upp: cmdls = (downcmdl, localcmdl)
221 else: cmdls = (localcmdl, downcmdl)
223 debug(`["cmdls", `cmdls`]`)
224 debug(`["srcstdin", `srcstdin`, "deststdout", `deststdout`, "devnull_read", devnull_read]`)
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])
234 status = subprocs[sdn].wait()
235 if status: bomb("%s %s failed, status %d" %
236 (wh, ['source','destination'][sdn], status))
238 def cmd_copydown(c, ce): copyupdown(c, ce, False)
239 def cmd_copyup(c, ce): copyupdown(c, ce, True)
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])
257 global downtmp, cleaning
259 if downtmp: caller.hook_cleanup()
270 print >> sys.stderr, q.m
272 print >> sys.stderr, "Unexpected cleanup error:"
273 traceback.print_exc()
274 print >> sys.stderr, ''
276 print >> sys.stderr, ("while cleaning up"
277 " because of another error:")
282 global downtmp, cleaning
284 signal_list = [ signal.SIGHUP, signal.SIGTERM,
285 signal.SIGINT, signal.SIGPIPE ]
287 for signum in signal_list: signal.signal(signum, f)
288 def handler(sig, *any):
289 sethandlers(signal.SIG_DFL)
291 os.kill(os.getpid(), sig)
296 while True: command()
299 if q.m: print >> sys.stderr, q.m
303 print >> sys.stderr, "Unexpected error:"
304 traceback.print_exc()
308 debug("down = %s" % string.join(down))