blob: b0cb37cba2d41afd8678066437d69f535a69e2cb [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
jadmanski550fdc22008-11-20 16:32:08 +0000106class subcommand(object):
107 fork_hooks, join_hooks = [], []
108
jadmanski0afbb632008-06-06 21:10:57 +0000109 def __init__(self, func, args, subdir = None, stdprint = True):
110 # func(args) - the subcommand to run
111 # subdir - the subdirectory to log results in
112 # stdprint - whether to print results to stdout/stderr
113 if subdir:
114 self.subdir = os.path.abspath(subdir)
115 if not os.path.exists(self.subdir):
116 os.mkdir(self.subdir)
117 self.debug = os.path.join(self.subdir, 'debug')
118 if not os.path.exists(self.debug):
119 os.mkdir(self.debug)
120 self.stdout = os.path.join(self.debug, 'stdout')
121 self.stderr = os.path.join(self.debug, 'stderr')
122 else:
123 self.subdir = None
124 self.debug = '/dev/null'
125 self.stdout = '/dev/null'
126 self.stderr = '/dev/null'
mblighd7685d32007-08-10 22:08:42 +0000127
jadmanski0afbb632008-06-06 21:10:57 +0000128 self.func = func
129 self.args = args
130 self.lambda_function = lambda: func(*args)
131 self.pid = None
132 self.stdprint = stdprint
mblighb0fab822007-07-25 16:40:19 +0000133
134
jadmanski550fdc22008-11-20 16:32:08 +0000135 @classmethod
136 def register_fork_hook(cls, hook):
137 """ Register a function to be called from the child process after
138 forking. """
139 cls.fork_hooks.append(hook)
140
141
142 @classmethod
143 def register_join_hook(cls, hook):
144 """ Register a function to be called when from the child process
145 just before the child process terminates (joins to the parent). """
146 cls.join_hooks.append(hook)
147
148
jadmanski0afbb632008-06-06 21:10:57 +0000149 def redirect_output(self):
150 if self.stdprint:
151 if self.subdir:
152 tag = os.path.basename(self.subdir)
153 _redirect_stream_tee(1, self.stdout, tag)
154 _redirect_stream_tee(2, self.stderr, tag)
155 else:
156 _redirect_stream(1, self.stdout)
157 _redirect_stream(2, self.stderr)
mblighb0fab822007-07-25 16:40:19 +0000158
159
jadmanski0afbb632008-06-06 21:10:57 +0000160 def fork_start(self):
161 sys.stdout.flush()
162 sys.stderr.flush()
163 self.pid = os.fork()
mblighb0fab822007-07-25 16:40:19 +0000164
jadmanski0afbb632008-06-06 21:10:57 +0000165 if self.pid: # I am the parent
166 return
mblighb0fab822007-07-25 16:40:19 +0000167
jadmanski0afbb632008-06-06 21:10:57 +0000168 # We are the child from this point on. Never return.
169 signal.signal(signal.SIGTERM, signal.SIG_DFL) # clear handler
170 if self.subdir:
171 os.chdir(self.subdir)
172 self.redirect_output()
mblighb0fab822007-07-25 16:40:19 +0000173
jadmanski0afbb632008-06-06 21:10:57 +0000174 try:
jadmanski550fdc22008-11-20 16:32:08 +0000175 for hook in self.fork_hooks:
176 hook(self)
jadmanski0afbb632008-06-06 21:10:57 +0000177 self.lambda_function()
jadmanski0afbb632008-06-06 21:10:57 +0000178 except:
179 traceback.print_exc()
jadmanski550fdc22008-11-20 16:32:08 +0000180 exit_code = 1
181 else:
182 exit_code = 0
183
184 try:
185 for hook in self.join_hooks:
186 hook(self)
187 finally:
jadmanski0afbb632008-06-06 21:10:57 +0000188 sys.stdout.flush()
189 sys.stderr.flush()
jadmanski550fdc22008-11-20 16:32:08 +0000190 os._exit(exit_code)
mblighb0fab822007-07-25 16:40:19 +0000191
192
jadmanski0afbb632008-06-06 21:10:57 +0000193 def fork_waitfor(self, timeout=None):
194 if not timeout:
195 (pid, status) = os.waitpid(self.pid, 0)
196 else:
197 pid = None
198 start_time = time.time()
199 while time.time() <= start_time + timeout:
200 (pid, status) = os.waitpid(self.pid, os.WNOHANG)
201 if pid:
202 break
203 time.sleep(1)
mblighc3aee0f2008-01-17 16:26:39 +0000204
jadmanski0afbb632008-06-06 21:10:57 +0000205 if not pid:
206 utils.nuke_pid(self.pid)
207 print "subcommand failed pid %d" % self.pid
208 print "%s" % (self.func,)
209 print "timeout after %ds" % timeout
210 print
211 return None
mblighb0fab822007-07-25 16:40:19 +0000212
jadmanski0afbb632008-06-06 21:10:57 +0000213 if status != 0:
214 print "subcommand failed pid %d" % pid
215 print "%s" % (self.func,)
216 print "rc=%d" % status
217 print
218 if os.path.exists(self.stderr):
219 for line in open(self.stderr).readlines():
220 print line,
221 print "\n--------------------------------------------\n"
222 raise error.AutoservSubcommandError(self.func, status)
223 return status