blob: a8dc2ad411ec8eb851ad216acc0edab7eb5e6b26 [file] [log] [blame]
mblighb0fab822007-07-25 16:40:19 +00001__author__ = """Copyright Andy Whitcroft, Martin J. Bligh - 2006, 2007"""
2
mbligh589bf322008-05-27 21:28:15 +00003import sys, os, subprocess, traceback, time, signal
jadmanskid93d7d22008-05-29 21:37:29 +00004
5from autotest_lib.client.common_lib import error, utils
mblighb0fab822007-07-25 16:40:19 +00006
7
mblighc3aee0f2008-01-17 16:26:39 +00008def parallel(tasklist, timeout=None):
jadmanski0afbb632008-06-06 21:10:57 +00009 """Run an set of predefined subcommands in parallel"""
10 pids = []
11 run_error = False
12 for task in tasklist:
13 task.fork_start()
mblighc3aee0f2008-01-17 16:26:39 +000014
jadmanski0afbb632008-06-06 21:10:57 +000015 remaining_timeout = None
16 if timeout:
17 endtime = time.time() + timeout
mblighc3aee0f2008-01-17 16:26:39 +000018
jadmanski0afbb632008-06-06 21:10:57 +000019 for task in tasklist:
20 if timeout:
21 remaining_timeout = max(endtime - time.time(), 1)
22 try:
23 status = task.fork_waitfor(remaining_timeout)
24 except error.AutoservSubcommandError:
25 run_error = True
26 else:
27 if status != 0:
28 run_error = True
mbligh158ba7b2008-03-07 18:29:12 +000029
jadmanski0afbb632008-06-06 21:10:57 +000030 if run_error:
31 raise error.AutoservError('One or more subcommands failed')
mblighb0fab822007-07-25 16:40:19 +000032
33
mblighc3aee0f2008-01-17 16:26:39 +000034def parallel_simple(function, arglist, log=True, timeout=None):
jadmanski0afbb632008-06-06 21:10:57 +000035 """Each element in the arglist used to create a subcommand object,
36 where that arg is used both as a subdir name, and a single argument
37 to pass to "function".
38 We create a subcommand object for each element in the list,
39 then execute those subcommand objects in parallel."""
mblighdd3235b2008-01-14 16:44:19 +000040
jadmanski0afbb632008-06-06 21:10:57 +000041 # Bypass the multithreading if only one machine.
42 if len (arglist) == 1:
43 function(arglist[0])
44 return
45
46 subcommands = []
47 for arg in arglist:
48 args = [arg]
49 if log:
50 subdir = str(arg)
51 else:
52 subdir = None
53 subcommands.append(subcommand(function, args, subdir))
54 parallel(subcommands, timeout)
mblighb0fab822007-07-25 16:40:19 +000055
56
mblighcee25b12007-08-31 08:53:05 +000057def _where_art_thy_filehandles():
jadmanski0afbb632008-06-06 21:10:57 +000058 os.system("ls -l /proc/%d/fd >> /dev/tty" % os.getpid())
mblighb0fab822007-07-25 16:40:19 +000059
mblighdc735a22007-08-02 16:54:37 +000060
mblighcee25b12007-08-31 08:53:05 +000061def _print_to_tty(string):
jadmanski0afbb632008-06-06 21:10:57 +000062 open('/dev/tty', 'w').write(string + '\n')
mblighb0fab822007-07-25 16:40:19 +000063
64
mblighcee25b12007-08-31 08:53:05 +000065def _redirect_stream(fd, output):
jadmanski0afbb632008-06-06 21:10:57 +000066 newfd = os.open(output, os.O_WRONLY | os.O_CREAT)
67 os.dup2(newfd, fd)
68 os.close(newfd)
69 if fd == 1:
70 sys.stdout = os.fdopen(fd, 'w')
71 if fd == 2:
72 sys.stderr = os.fdopen(fd, 'w')
mblighb0fab822007-07-25 16:40:19 +000073
74
mblighcee25b12007-08-31 08:53:05 +000075def _redirect_stream_tee(fd, output, tag):
jadmanski0afbb632008-06-06 21:10:57 +000076 """Use the low-level fork & pipe operations here to get a fd,
77 not a filehandle. This ensures that we get both the
78 filehandle and fd for stdout/stderr redirected correctly."""
79 r, w = os.pipe()
80 pid = os.fork()
81 if pid: # Parent
82 os.dup2(w, fd)
83 os.close(r)
84 os.close(w)
85 if fd == 1:
86 sys.stdout = os.fdopen(fd, 'w', 1)
87 if fd == 2:
88 sys.stderr = os.fdopen(fd, 'w', 1)
89 return
90 else: # Child
jadmanskif4a87ca2008-09-16 17:31:48 +000091 signal.signal(signal.SIGTERM, signal.SIG_DFL) # clear handler
jadmanski0afbb632008-06-06 21:10:57 +000092 os.close(w)
93 log = open(output, 'w')
94 f = os.fdopen(r, 'r')
95 for line in iter(f.readline, ''):
96 # Tee straight to file
97 log.write(line)
98 log.flush()
99 # Prepend stdout with the tag
100 print tag + ' : ' + line,
101 sys.stdout.flush()
102 log.close()
103 os._exit(0)
mblighb0fab822007-07-25 16:40:19 +0000104
105
106class subcommand:
jadmanski0afbb632008-06-06 21:10:57 +0000107 def __init__(self, func, args, subdir = None, stdprint = True):
108 # func(args) - the subcommand to run
109 # subdir - the subdirectory to log results in
110 # stdprint - whether to print results to stdout/stderr
111 if subdir:
112 self.subdir = os.path.abspath(subdir)
113 if not os.path.exists(self.subdir):
114 os.mkdir(self.subdir)
115 self.debug = os.path.join(self.subdir, 'debug')
116 if not os.path.exists(self.debug):
117 os.mkdir(self.debug)
118 self.stdout = os.path.join(self.debug, 'stdout')
119 self.stderr = os.path.join(self.debug, 'stderr')
120 else:
121 self.subdir = None
122 self.debug = '/dev/null'
123 self.stdout = '/dev/null'
124 self.stderr = '/dev/null'
mblighd7685d32007-08-10 22:08:42 +0000125
jadmanski0afbb632008-06-06 21:10:57 +0000126 self.func = func
127 self.args = args
128 self.lambda_function = lambda: func(*args)
129 self.pid = None
130 self.stdprint = stdprint
mblighb0fab822007-07-25 16:40:19 +0000131
132
jadmanski0afbb632008-06-06 21:10:57 +0000133 def redirect_output(self):
134 if self.stdprint:
135 if self.subdir:
136 tag = os.path.basename(self.subdir)
137 _redirect_stream_tee(1, self.stdout, tag)
138 _redirect_stream_tee(2, self.stderr, tag)
139 else:
140 _redirect_stream(1, self.stdout)
141 _redirect_stream(2, self.stderr)
mblighb0fab822007-07-25 16:40:19 +0000142
143
jadmanski0afbb632008-06-06 21:10:57 +0000144 def fork_start(self):
145 sys.stdout.flush()
146 sys.stderr.flush()
147 self.pid = os.fork()
mblighb0fab822007-07-25 16:40:19 +0000148
jadmanski0afbb632008-06-06 21:10:57 +0000149 if self.pid: # I am the parent
150 return
mblighb0fab822007-07-25 16:40:19 +0000151
jadmanski0afbb632008-06-06 21:10:57 +0000152 # We are the child from this point on. Never return.
153 signal.signal(signal.SIGTERM, signal.SIG_DFL) # clear handler
154 if self.subdir:
155 os.chdir(self.subdir)
156 self.redirect_output()
mblighb0fab822007-07-25 16:40:19 +0000157
jadmanski0afbb632008-06-06 21:10:57 +0000158 try:
159 self.lambda_function()
mblighb0fab822007-07-25 16:40:19 +0000160
jadmanski0afbb632008-06-06 21:10:57 +0000161 except:
162 traceback.print_exc()
163 sys.stdout.flush()
164 sys.stderr.flush()
165 os._exit(1)
mblighb0fab822007-07-25 16:40:19 +0000166
jadmanski0afbb632008-06-06 21:10:57 +0000167 sys.stdout.flush()
168 sys.stderr.flush()
169 os._exit(0)
mblighb0fab822007-07-25 16:40:19 +0000170
171
jadmanski0afbb632008-06-06 21:10:57 +0000172 def fork_waitfor(self, timeout=None):
173 if not timeout:
174 (pid, status) = os.waitpid(self.pid, 0)
175 else:
176 pid = None
177 start_time = time.time()
178 while time.time() <= start_time + timeout:
179 (pid, status) = os.waitpid(self.pid, os.WNOHANG)
180 if pid:
181 break
182 time.sleep(1)
mblighc3aee0f2008-01-17 16:26:39 +0000183
jadmanski0afbb632008-06-06 21:10:57 +0000184 if not pid:
185 utils.nuke_pid(self.pid)
186 print "subcommand failed pid %d" % self.pid
187 print "%s" % (self.func,)
188 print "timeout after %ds" % timeout
189 print
190 return None
mblighb0fab822007-07-25 16:40:19 +0000191
jadmanski0afbb632008-06-06 21:10:57 +0000192 if status != 0:
193 print "subcommand failed pid %d" % pid
194 print "%s" % (self.func,)
195 print "rc=%d" % status
196 print
197 if os.path.exists(self.stderr):
198 for line in open(self.stderr).readlines():
199 print line,
200 print "\n--------------------------------------------\n"
201 raise error.AutoservSubcommandError(self.func, status)
202 return status