blob: baa126ba5f6b909aa152ec1acb77133b30338597 [file] [log] [blame]
Craig Tillerc2c79212015-02-16 12:00:01 -08001# Copyright 2015, Google Inc.
2# All rights reserved.
3#
4# Redistribution and use in source and binary forms, with or without
5# modification, are permitted provided that the following conditions are
6# met:
7#
8# * Redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer.
10# * Redistributions in binary form must reproduce the above
11# copyright notice, this list of conditions and the following disclaimer
12# in the documentation and/or other materials provided with the
13# distribution.
14# * Neither the name of Google Inc. nor the names of its
15# contributors may be used to endorse or promote products derived from
16# this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
Nicolas Nobleddef2462015-01-06 18:08:25 -080030"""Run a group of subprocesses and then finish."""
31
Craig Tiller71735182015-01-15 17:07:13 -080032import hashlib
Nicolas Nobleddef2462015-01-06 18:08:25 -080033import multiprocessing
Craig Tiller71735182015-01-15 17:07:13 -080034import os
Craig Tiller5058c692015-04-08 09:42:04 -070035import platform
Craig Tiller336ad502015-02-24 14:46:02 -080036import signal
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +020037import string
Nicolas Nobleddef2462015-01-06 18:08:25 -080038import subprocess
39import sys
ctiller3040cb72015-01-07 12:13:17 -080040import tempfile
41import time
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +020042import xml.etree.cElementTree as ET
Nicolas Nobleddef2462015-01-06 18:08:25 -080043
ctiller3040cb72015-01-07 12:13:17 -080044
ctiller94e5dde2015-01-09 10:41:59 -080045_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Nicolas Nobleddef2462015-01-06 18:08:25 -080046
47
Craig Tiller336ad502015-02-24 14:46:02 -080048# setup a signal handler so that signal.pause registers 'something'
49# when a child finishes
50# not using futures and threading to avoid a dependency on subprocess32
Craig Tiller5058c692015-04-08 09:42:04 -070051if platform.system() == "Windows":
52 pass
53else:
54 have_alarm = False
55 def alarm_handler(unused_signum, unused_frame):
56 global have_alarm
57 have_alarm = False
58
59 signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None)
60 signal.signal(signal.SIGALRM, alarm_handler)
Craig Tiller336ad502015-02-24 14:46:02 -080061
62
ctiller3040cb72015-01-07 12:13:17 -080063_SUCCESS = object()
64_FAILURE = object()
65_RUNNING = object()
66_KILLED = object()
67
68
Craig Tiller3b083062015-01-12 13:51:28 -080069_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080070 'red': [ 31, 0 ],
71 'green': [ 32, 0 ],
72 'yellow': [ 33, 0 ],
73 'lightgray': [ 37, 0],
74 'gray': [ 30, 1 ],
Craig Tiller3b083062015-01-12 13:51:28 -080075 }
76
77
78_BEGINNING_OF_LINE = '\x1b[0G'
79_CLEAR_LINE = '\x1b[2K'
80
81
82_TAG_COLOR = {
83 'FAILED': 'red',
Craig Tillere1d0d1c2015-02-27 08:54:23 -080084 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -080085 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080086 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080087 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080088 'SUCCESS': 'green',
89 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080090 }
91
92
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +020093def message(tag, msg, explanatory_text=None, do_newline=False):
94 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
95 return
96 message.old_tag = tag
97 message.old_msg = msg
vjpaia29d2d72015-07-08 10:31:15 -070098 if platform.system() == 'Windows' or not sys.stdout.isatty():
Craig Tiller5058c692015-04-08 09:42:04 -070099 if explanatory_text:
100 print explanatory_text
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200101 print '%s: %s' % (tag, msg)
Craig Tiller5058c692015-04-08 09:42:04 -0700102 return
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800103 try:
vjpaia29d2d72015-07-08 10:31:15 -0700104 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
105 _BEGINNING_OF_LINE,
106 _CLEAR_LINE,
107 '\n%s' % explanatory_text if explanatory_text is not None else '',
108 _COLORS[_TAG_COLOR[tag]][1],
109 _COLORS[_TAG_COLOR[tag]][0],
110 tag,
111 msg,
112 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800113 sys.stdout.flush()
114 except:
115 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800116
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200117message.old_tag = ""
118message.old_msg = ""
Craig Tiller3b083062015-01-12 13:51:28 -0800119
Craig Tiller71735182015-01-15 17:07:13 -0800120def which(filename):
121 if '/' in filename:
122 return filename
123 for path in os.environ['PATH'].split(os.pathsep):
124 if os.path.exists(os.path.join(path, filename)):
125 return os.path.join(path, filename)
126 raise Exception('%s not found' % filename)
127
128
Craig Tiller547db2b2015-01-30 14:08:39 -0800129class JobSpec(object):
130 """Specifies what to run for a job."""
131
Jan Tattermusche8243592015-04-17 14:14:01 -0700132 def __init__(self, cmdline, shortname=None, environ=None, hash_targets=None, cwd=None, shell=False):
Craig Tiller547db2b2015-01-30 14:08:39 -0800133 """
134 Arguments:
135 cmdline: a list of arguments to pass as the command line
136 environ: a dictionary of environment variables to set in the child process
137 hash_targets: which files to include in the hash representing the jobs version
138 (or empty, indicating the job should not be hashed)
139 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800140 if environ is None:
141 environ = {}
142 if hash_targets is None:
143 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800144 self.cmdline = cmdline
145 self.environ = environ
146 self.shortname = cmdline[0] if shortname is None else shortname
147 self.hash_targets = hash_targets or []
Craig Tiller5058c692015-04-08 09:42:04 -0700148 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700149 self.shell = shell
Craig Tiller547db2b2015-01-30 14:08:39 -0800150
151 def identity(self):
152 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
153
154 def __hash__(self):
155 return hash(self.identity())
156
157 def __cmp__(self, other):
158 return self.identity() == other.identity()
159
160
ctiller3040cb72015-01-07 12:13:17 -0800161class Job(object):
162 """Manages one job."""
163
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200164 def __init__(self, spec, bin_hash, newline_on_success, travis, xml_report):
Craig Tiller547db2b2015-01-30 14:08:39 -0800165 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800166 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -0800167 self._tempfile = tempfile.TemporaryFile()
Craig Tiller547db2b2015-01-30 14:08:39 -0800168 env = os.environ.copy()
169 for k, v in spec.environ.iteritems():
170 env[k] = v
Craig Tiller9d6139a2015-02-26 15:24:43 -0800171 self._start = time.time()
Craig Tiller547db2b2015-01-30 14:08:39 -0800172 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800173 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800174 stdout=self._tempfile,
Craig Tiller5058c692015-04-08 09:42:04 -0700175 cwd=spec.cwd,
Jan Tattermusche8243592015-04-17 14:14:01 -0700176 shell=spec.shell,
Craig Tiller547db2b2015-01-30 14:08:39 -0800177 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800178 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800179 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100180 self._travis = travis
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200181 self._xml_test = ET.SubElement(xml_report, 'testcase',
182 name=self._spec.shortname) if xml_report is not None else None
Craig Tillerb84728d2015-02-26 15:40:39 -0800183 message('START', spec.shortname, do_newline=self._travis)
ctiller3040cb72015-01-07 12:13:17 -0800184
Craig Tiller71735182015-01-15 17:07:13 -0800185 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800186 """Poll current state of the job. Prints messages at completion."""
187 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800188 elapsed = time.time() - self._start
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200189 self._tempfile.seek(0)
190 stdout = self._tempfile.read()
191 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
192 if self._xml_test is not None:
193 self._xml_test.set('time', str(elapsed))
194 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
ctiller3040cb72015-01-07 12:13:17 -0800195 if self._process.returncode != 0:
196 self._state = _FAILURE
Craig Tillerd0ffe142015-05-19 21:51:13 -0700197 message('FAILED', '%s [ret=%d, pid=%d]' % (
198 self._spec.shortname, self._process.returncode, self._process.pid),
199 stdout, do_newline=True)
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200200 if self._xml_test is not None:
201 ET.SubElement(self._xml_test, 'failure', message='Failure').text
ctiller3040cb72015-01-07 12:13:17 -0800202 else:
203 self._state = _SUCCESS
Craig Tiller9d6139a2015-02-26 15:24:43 -0800204 message('PASSED', '%s [time=%.1fsec]' % (self._spec.shortname, elapsed),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100205 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800206 if self._bin_hash:
207 update_cache.finished(self._spec.identity(), self._bin_hash)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800208 elif self._state == _RUNNING and time.time() - self._start > 300:
Craig Tiller84216782015-05-12 09:43:54 -0700209 self._tempfile.seek(0)
210 stdout = self._tempfile.read()
211 message('TIMEOUT', self._spec.shortname, stdout, do_newline=True)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800212 self.kill()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200213 if self._xml_test is not None:
214 ET.SubElement(self._xml_test, 'system-out').text = stdout
215 ET.SubElement(self._xml_test, 'error', message='Timeout')
ctiller3040cb72015-01-07 12:13:17 -0800216 return self._state
217
218 def kill(self):
219 if self._state == _RUNNING:
220 self._state = _KILLED
221 self._process.terminate()
222
223
Nicolas Nobleddef2462015-01-06 18:08:25 -0800224class Jobset(object):
225 """Manages one run of jobs."""
226
Craig Tiller533b1a22015-05-29 08:41:29 -0700227 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200228 stop_on_failure, cache, xml_report):
ctiller3040cb72015-01-07 12:13:17 -0800229 self._running = set()
230 self._check_cancelled = check_cancelled
231 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800232 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800233 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800234 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800235 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100236 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800237 self._cache = cache
Craig Tiller533b1a22015-05-29 08:41:29 -0700238 self._stop_on_failure = stop_on_failure
Craig Tiller74e770d2015-06-11 09:38:09 -0700239 self._hashes = {}
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200240 self._xml_report = xml_report
Nicolas Nobleddef2462015-01-06 18:08:25 -0800241
Craig Tiller547db2b2015-01-30 14:08:39 -0800242 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800243 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800244 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800245 if self.cancelled(): return False
246 self.reap()
247 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800248 if spec.hash_targets:
Craig Tiller74e770d2015-06-11 09:38:09 -0700249 if spec.identity() in self._hashes:
250 bin_hash = self._hashes[spec.identity()]
251 else:
252 bin_hash = hashlib.sha1()
253 for fn in spec.hash_targets:
254 with open(which(fn)) as f:
255 bin_hash.update(f.read())
256 bin_hash = bin_hash.hexdigest()
257 self._hashes[spec.identity()] = bin_hash
Craig Tiller547db2b2015-01-30 14:08:39 -0800258 should_run = self._cache.should_run(spec.identity(), bin_hash)
259 else:
260 bin_hash = None
261 should_run = True
262 if should_run:
Craig Tiller5058c692015-04-08 09:42:04 -0700263 try:
264 self._running.add(Job(spec,
265 bin_hash,
266 self._newline_on_success,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200267 self._travis,
268 self._xml_report))
Craig Tiller5058c692015-04-08 09:42:04 -0700269 except:
270 message('FAILED', spec.shortname)
271 self._cancelled = True
272 return False
ctiller3040cb72015-01-07 12:13:17 -0800273 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800274
ctiller3040cb72015-01-07 12:13:17 -0800275 def reap(self):
276 """Collect the dead jobs."""
277 while self._running:
278 dead = set()
279 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800280 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800281 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700282 if st == _FAILURE or st == _KILLED:
283 self._failures += 1
284 if self._stop_on_failure:
285 self._cancelled = True
286 for job in self._running:
287 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800288 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700289 break
ctiller3040cb72015-01-07 12:13:17 -0800290 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800291 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800292 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800293 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100294 if (not self._travis):
295 message('WAITING', '%d jobs running, %d complete, %d failed' % (
296 len(self._running), self._completed, self._failures))
Craig Tiller5058c692015-04-08 09:42:04 -0700297 if platform.system() == 'Windows':
298 time.sleep(0.1)
299 else:
300 global have_alarm
301 if not have_alarm:
302 have_alarm = True
303 signal.alarm(10)
304 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800305
306 def cancelled(self):
307 """Poll for cancellation."""
308 if self._cancelled: return True
309 if not self._check_cancelled(): return False
310 for job in self._running:
311 job.kill()
312 self._cancelled = True
313 return True
314
315 def finish(self):
316 while self._running:
317 if self.cancelled(): pass # poll cancellation
318 self.reap()
319 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800320
321
ctiller3040cb72015-01-07 12:13:17 -0800322def _never_cancelled():
323 return False
324
325
Craig Tiller71735182015-01-15 17:07:13 -0800326# cache class that caches nothing
327class NoCache(object):
328 def should_run(self, cmdline, bin_hash):
329 return True
330
331 def finished(self, cmdline, bin_hash):
332 pass
333
334
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800335def run(cmdlines,
336 check_cancelled=_never_cancelled,
337 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800338 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100339 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700340 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700341 stop_on_failure=False,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200342 cache=None,
343 xml_report=None):
ctiller94e5dde2015-01-09 10:41:59 -0800344 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800345 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tiller533b1a22015-05-29 08:41:29 -0700346 newline_on_success, travis, stop_on_failure,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200347 cache if cache is not None else NoCache(),
348 xml_report)
Craig Tillerb84728d2015-02-26 15:40:39 -0800349 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800350 if not js.start(cmdline):
351 break
352 return js.finish()