blob: dceb969d5d0822d5a3439d4252cb643d0f808b93 [file] [log] [blame]
mblighb0fab822007-07-25 16:40:19 +00001__author__ = """Copyright Andy Whitcroft, Martin J. Bligh - 2006, 2007"""
2
mblighe1836812009-04-17 18:25:14 +00003import sys, os, subprocess, traceback, time, signal, pickle
jadmanskid93d7d22008-05-29 21:37:29 +00004
5from autotest_lib.client.common_lib import error, utils
mblighb0fab822007-07-25 16:40:19 +00006
7
showard75cdfee2009-06-10 17:40:41 +00008# entry points that use subcommand must set this to their logging manager
9# to get log redirection for subcommands
10logging_manager_object = None
11
12
mblighe1836812009-04-17 18:25:14 +000013def parallel(tasklist, timeout=None, return_results=False):
mbligh415dc212009-06-15 21:53:34 +000014 """
15 Run a set of predefined subcommands in parallel.
16
17 @param tasklist: A list of subcommand instances to execute.
18 @param timeout: Number of seconds after which the commands should timeout.
19 @param return_results: If True instead of an AutoServError being raised
20 on any error a list of the results|exceptions from the tasks is
21 returned. [default: False]
mblighe1836812009-04-17 18:25:14 +000022 """
jadmanski0afbb632008-06-06 21:10:57 +000023 pids = []
24 run_error = False
25 for task in tasklist:
26 task.fork_start()
mblighc3aee0f2008-01-17 16:26:39 +000027
jadmanski0afbb632008-06-06 21:10:57 +000028 remaining_timeout = None
29 if timeout:
30 endtime = time.time() + timeout
mblighc3aee0f2008-01-17 16:26:39 +000031
mblighe1836812009-04-17 18:25:14 +000032 results = []
jadmanski0afbb632008-06-06 21:10:57 +000033 for task in tasklist:
34 if timeout:
35 remaining_timeout = max(endtime - time.time(), 1)
36 try:
37 status = task.fork_waitfor(remaining_timeout)
38 except error.AutoservSubcommandError:
39 run_error = True
40 else:
41 if status != 0:
42 run_error = True
mbligh158ba7b2008-03-07 18:29:12 +000043
mblighe1836812009-04-17 18:25:14 +000044 results.append(pickle.load(task.result_pickle))
45 task.result_pickle.close()
46
47 if return_results:
48 return results
49 elif run_error:
jadmanski0afbb632008-06-06 21:10:57 +000050 raise error.AutoservError('One or more subcommands failed')
mblighb0fab822007-07-25 16:40:19 +000051
52
mbligh415dc212009-06-15 21:53:34 +000053def parallel_simple(function, arglist, log=True, timeout=None,
54 return_results=False):
55 """
56 Each element in the arglist used to create a subcommand object,
jadmanski0afbb632008-06-06 21:10:57 +000057 where that arg is used both as a subdir name, and a single argument
58 to pass to "function".
mblighdd3235b2008-01-14 16:44:19 +000059
mbligh415dc212009-06-15 21:53:34 +000060 We create a subcommand object for each element in the list,
61 then execute those subcommand objects in parallel.
62
63 NOTE: As an optimization, if len(arglist) == 1 a subcommand is not used.
64
65 @param function: A callable to run in parallel once per arg in arglist.
66 @param arglist: A list of single arguments to be used one per subcommand;
67 typically a list of machine names.
68 @param log: If True, output will be written to output in a subdirectory
69 named after each subcommand's arg.
70 @param timeout: Number of seconds after which the commands should timeout.
71 @param return_results: If True instead of an AutoServError being raised
72 on any error a list of the results|exceptions from the function
73 called on each arg is returned. [default: False]
74
75 @returns None or a list of results/exceptions.
76 """
jadmanski0afbb632008-06-06 21:10:57 +000077 # Bypass the multithreading if only one machine.
mbligh415dc212009-06-15 21:53:34 +000078 if len(arglist) == 1:
79 arg = arglist[0]
80 if return_results:
81 try:
82 result = function(arg)
83 except Exception, e:
84 return [e]
85 return [result]
86 else:
87 function(arg)
88 return
jadmanski0afbb632008-06-06 21:10:57 +000089
90 subcommands = []
91 for arg in arglist:
92 args = [arg]
93 if log:
94 subdir = str(arg)
95 else:
96 subdir = None
97 subcommands.append(subcommand(function, args, subdir))
mbligh415dc212009-06-15 21:53:34 +000098 return parallel(subcommands, timeout, return_results=return_results)
mblighb0fab822007-07-25 16:40:19 +000099
100
jadmanski550fdc22008-11-20 16:32:08 +0000101class subcommand(object):
102 fork_hooks, join_hooks = [], []
103
showard75cdfee2009-06-10 17:40:41 +0000104 def __init__(self, func, args, subdir = None):
jadmanski0afbb632008-06-06 21:10:57 +0000105 # func(args) - the subcommand to run
106 # subdir - the subdirectory to log results in
jadmanski0afbb632008-06-06 21:10:57 +0000107 if subdir:
108 self.subdir = os.path.abspath(subdir)
109 if not os.path.exists(self.subdir):
110 os.mkdir(self.subdir)
111 self.debug = os.path.join(self.subdir, 'debug')
112 if not os.path.exists(self.debug):
113 os.mkdir(self.debug)
jadmanski0afbb632008-06-06 21:10:57 +0000114 else:
115 self.subdir = None
showard75cdfee2009-06-10 17:40:41 +0000116 self.debug = None
mblighd7685d32007-08-10 22:08:42 +0000117
jadmanski0afbb632008-06-06 21:10:57 +0000118 self.func = func
119 self.args = args
120 self.lambda_function = lambda: func(*args)
121 self.pid = None
showardc408c5e2009-01-08 23:30:53 +0000122 self.returncode = None
mblighb0fab822007-07-25 16:40:19 +0000123
124
jadmanski550fdc22008-11-20 16:32:08 +0000125 @classmethod
126 def register_fork_hook(cls, hook):
127 """ Register a function to be called from the child process after
128 forking. """
129 cls.fork_hooks.append(hook)
130
131
132 @classmethod
133 def register_join_hook(cls, hook):
134 """ Register a function to be called when from the child process
135 just before the child process terminates (joins to the parent). """
136 cls.join_hooks.append(hook)
137
138
jadmanski0afbb632008-06-06 21:10:57 +0000139 def redirect_output(self):
showard75cdfee2009-06-10 17:40:41 +0000140 if self.subdir and logging_manager_object:
141 tag = os.path.basename(self.subdir)
142 logging_manager_object.tee_redirect_debug_dir(self.debug, tag=tag)
mblighb0fab822007-07-25 16:40:19 +0000143
144
jadmanski0afbb632008-06-06 21:10:57 +0000145 def fork_start(self):
146 sys.stdout.flush()
147 sys.stderr.flush()
mblighe1836812009-04-17 18:25:14 +0000148 r, w = os.pipe()
jadmanski77e8da82009-04-21 14:26:40 +0000149 self.returncode = None
jadmanski0afbb632008-06-06 21:10:57 +0000150 self.pid = os.fork()
mblighb0fab822007-07-25 16:40:19 +0000151
jadmanski0afbb632008-06-06 21:10:57 +0000152 if self.pid: # I am the parent
mblighe1836812009-04-17 18:25:14 +0000153 os.close(w)
154 self.result_pickle = os.fdopen(r, 'r')
jadmanski0afbb632008-06-06 21:10:57 +0000155 return
mblighe1836812009-04-17 18:25:14 +0000156 else:
157 os.close(r)
mblighb0fab822007-07-25 16:40:19 +0000158
jadmanski0afbb632008-06-06 21:10:57 +0000159 # We are the child from this point on. Never return.
160 signal.signal(signal.SIGTERM, signal.SIG_DFL) # clear handler
161 if self.subdir:
162 os.chdir(self.subdir)
163 self.redirect_output()
mblighb0fab822007-07-25 16:40:19 +0000164
jadmanski0afbb632008-06-06 21:10:57 +0000165 try:
jadmanski550fdc22008-11-20 16:32:08 +0000166 for hook in self.fork_hooks:
167 hook(self)
mblighe1836812009-04-17 18:25:14 +0000168 result = self.lambda_function()
169 os.write(w, pickle.dumps(result))
170 except Exception, e:
jadmanski0afbb632008-06-06 21:10:57 +0000171 traceback.print_exc()
jadmanski550fdc22008-11-20 16:32:08 +0000172 exit_code = 1
mblighe1836812009-04-17 18:25:14 +0000173 os.write(w, pickle.dumps(e))
jadmanski550fdc22008-11-20 16:32:08 +0000174 else:
175 exit_code = 0
176
177 try:
178 for hook in self.join_hooks:
179 hook(self)
180 finally:
jadmanski0afbb632008-06-06 21:10:57 +0000181 sys.stdout.flush()
182 sys.stderr.flush()
jadmanski550fdc22008-11-20 16:32:08 +0000183 os._exit(exit_code)
mblighb0fab822007-07-25 16:40:19 +0000184
185
showardc408c5e2009-01-08 23:30:53 +0000186 def _handle_exitstatus(self, sts):
187 """
188 This is partially borrowed from subprocess.Popen.
189 """
190 if os.WIFSIGNALED(sts):
191 self.returncode = -os.WTERMSIG(sts)
192 elif os.WIFEXITED(sts):
193 self.returncode = os.WEXITSTATUS(sts)
jadmanski0afbb632008-06-06 21:10:57 +0000194 else:
showardc408c5e2009-01-08 23:30:53 +0000195 # Should never happen
196 raise RuntimeError("Unknown child exit status!")
mblighc3aee0f2008-01-17 16:26:39 +0000197
showardc408c5e2009-01-08 23:30:53 +0000198 if self.returncode != 0:
199 print "subcommand failed pid %d" % self.pid
jadmanski0afbb632008-06-06 21:10:57 +0000200 print "%s" % (self.func,)
showardc408c5e2009-01-08 23:30:53 +0000201 print "rc=%d" % self.returncode
jadmanski0afbb632008-06-06 21:10:57 +0000202 print
showard75cdfee2009-06-10 17:40:41 +0000203 if self.debug:
204 stderr_file = os.path.join(self.debug, 'autoserv.stderr')
205 if os.path.exists(stderr_file):
206 for line in open(stderr_file).readlines():
207 print line,
jadmanski0afbb632008-06-06 21:10:57 +0000208 print "\n--------------------------------------------\n"
showardc408c5e2009-01-08 23:30:53 +0000209 raise error.AutoservSubcommandError(self.func, self.returncode)
210
211
212 def poll(self):
213 """
214 This is borrowed from subprocess.Popen.
215 """
216 if self.returncode is None:
217 try:
218 pid, sts = os.waitpid(self.pid, os.WNOHANG)
219 if pid == self.pid:
220 self._handle_exitstatus(sts)
221 except os.error:
222 pass
223 return self.returncode
224
225
226 def wait(self):
227 """
228 This is borrowed from subprocess.Popen.
229 """
230 if self.returncode is None:
231 pid, sts = os.waitpid(self.pid, 0)
232 self._handle_exitstatus(sts)
233 return self.returncode
234
235
236 def fork_waitfor(self, timeout=None):
237 if not timeout:
238 return self.wait()
239 else:
240 start_time = time.time()
241 while time.time() <= start_time + timeout:
242 self.poll()
243 if self.returncode is not None:
244 return self.returncode
245 time.sleep(1)
246
247 utils.nuke_pid(self.pid)
248 print "subcommand failed pid %d" % self.pid
249 print "%s" % (self.func,)
250 print "timeout after %ds" % timeout
251 print
252 return None