blob: 8b29b827911e3d312bf812fdd732c133a933d3f6 [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
91 os.close(w)
92 log = open(output, 'w')
93 f = os.fdopen(r, 'r')
94 for line in iter(f.readline, ''):
95 # Tee straight to file
96 log.write(line)
97 log.flush()
98 # Prepend stdout with the tag
99 print tag + ' : ' + line,
100 sys.stdout.flush()
101 log.close()
102 os._exit(0)
mblighb0fab822007-07-25 16:40:19 +0000103
104
105class subcommand:
jadmanski0afbb632008-06-06 21:10:57 +0000106 def __init__(self, func, args, subdir = None, stdprint = True):
107 # func(args) - the subcommand to run
108 # subdir - the subdirectory to log results in
109 # stdprint - whether to print results to stdout/stderr
110 if subdir:
111 self.subdir = os.path.abspath(subdir)
112 if not os.path.exists(self.subdir):
113 os.mkdir(self.subdir)
114 self.debug = os.path.join(self.subdir, 'debug')
115 if not os.path.exists(self.debug):
116 os.mkdir(self.debug)
117 self.stdout = os.path.join(self.debug, 'stdout')
118 self.stderr = os.path.join(self.debug, 'stderr')
119 else:
120 self.subdir = None
121 self.debug = '/dev/null'
122 self.stdout = '/dev/null'
123 self.stderr = '/dev/null'
mblighd7685d32007-08-10 22:08:42 +0000124
jadmanski0afbb632008-06-06 21:10:57 +0000125 self.func = func
126 self.args = args
127 self.lambda_function = lambda: func(*args)
128 self.pid = None
129 self.stdprint = stdprint
mblighb0fab822007-07-25 16:40:19 +0000130
131
jadmanski0afbb632008-06-06 21:10:57 +0000132 def redirect_output(self):
133 if self.stdprint:
134 if self.subdir:
135 tag = os.path.basename(self.subdir)
136 _redirect_stream_tee(1, self.stdout, tag)
137 _redirect_stream_tee(2, self.stderr, tag)
138 else:
139 _redirect_stream(1, self.stdout)
140 _redirect_stream(2, self.stderr)
mblighb0fab822007-07-25 16:40:19 +0000141
142
jadmanski0afbb632008-06-06 21:10:57 +0000143 def fork_start(self):
144 sys.stdout.flush()
145 sys.stderr.flush()
146 self.pid = os.fork()
mblighb0fab822007-07-25 16:40:19 +0000147
jadmanski0afbb632008-06-06 21:10:57 +0000148 if self.pid: # I am the parent
149 return
mblighb0fab822007-07-25 16:40:19 +0000150
jadmanski0afbb632008-06-06 21:10:57 +0000151 # We are the child from this point on. Never return.
152 signal.signal(signal.SIGTERM, signal.SIG_DFL) # clear handler
153 if self.subdir:
154 os.chdir(self.subdir)
155 self.redirect_output()
mblighb0fab822007-07-25 16:40:19 +0000156
jadmanski0afbb632008-06-06 21:10:57 +0000157 try:
158 self.lambda_function()
mblighb0fab822007-07-25 16:40:19 +0000159
jadmanski0afbb632008-06-06 21:10:57 +0000160 except:
161 traceback.print_exc()
162 sys.stdout.flush()
163 sys.stderr.flush()
164 os._exit(1)
mblighb0fab822007-07-25 16:40:19 +0000165
jadmanski0afbb632008-06-06 21:10:57 +0000166 sys.stdout.flush()
167 sys.stderr.flush()
168 os._exit(0)
mblighb0fab822007-07-25 16:40:19 +0000169
170
jadmanski0afbb632008-06-06 21:10:57 +0000171 def fork_waitfor(self, timeout=None):
172 if not timeout:
173 (pid, status) = os.waitpid(self.pid, 0)
174 else:
175 pid = None
176 start_time = time.time()
177 while time.time() <= start_time + timeout:
178 (pid, status) = os.waitpid(self.pid, os.WNOHANG)
179 if pid:
180 break
181 time.sleep(1)
mblighc3aee0f2008-01-17 16:26:39 +0000182
jadmanski0afbb632008-06-06 21:10:57 +0000183 if not pid:
184 utils.nuke_pid(self.pid)
185 print "subcommand failed pid %d" % self.pid
186 print "%s" % (self.func,)
187 print "timeout after %ds" % timeout
188 print
189 return None
mblighb0fab822007-07-25 16:40:19 +0000190
jadmanski0afbb632008-06-06 21:10:57 +0000191 if status != 0:
192 print "subcommand failed pid %d" % pid
193 print "%s" % (self.func,)
194 print "rc=%d" % status
195 print
196 if os.path.exists(self.stderr):
197 for line in open(self.stderr).readlines():
198 print line,
199 print "\n--------------------------------------------\n"
200 raise error.AutoservSubcommandError(self.func, status)
201 return status