blob: a58071ee35526973e73ff2a695f4209c292aca14 [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
Nicolas Nobleddef2462015-01-06 18:08:25 -080036import random
Craig Tiller336ad502015-02-24 14:46:02 -080037import signal
Nicolas Nobleddef2462015-01-06 18:08:25 -080038import subprocess
39import sys
ctiller3040cb72015-01-07 12:13:17 -080040import tempfile
41import time
Nicolas Nobleddef2462015-01-06 18:08:25 -080042
ctiller3040cb72015-01-07 12:13:17 -080043
ctiller94e5dde2015-01-09 10:41:59 -080044_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Nicolas Nobleddef2462015-01-06 18:08:25 -080045
46
Craig Tiller336ad502015-02-24 14:46:02 -080047# setup a signal handler so that signal.pause registers 'something'
48# when a child finishes
49# not using futures and threading to avoid a dependency on subprocess32
Craig Tiller5058c692015-04-08 09:42:04 -070050if platform.system() == "Windows":
51 pass
52else:
53 have_alarm = False
54 def alarm_handler(unused_signum, unused_frame):
55 global have_alarm
56 have_alarm = False
57
58 signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None)
59 signal.signal(signal.SIGALRM, alarm_handler)
Craig Tiller336ad502015-02-24 14:46:02 -080060
61
Nicolas Nobleddef2462015-01-06 18:08:25 -080062def shuffle_iteratable(it):
63 """Return an iterable that randomly walks it"""
64 # take a random sampling from the passed in iterable
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +020065 # we take an element with probability 1/p and rapidly increase
Nicolas Nobleddef2462015-01-06 18:08:25 -080066 # p as we take elements - this gives us a somewhat random set of values before
67 # we've seen all the values, but starts producing values without having to
68 # compute ALL of them at once, allowing tests to start a little earlier
69 nextit = []
70 p = 1
71 for val in it:
72 if random.randint(0, p) == 0:
ctiller3040cb72015-01-07 12:13:17 -080073 p = min(p*2, 100)
Nicolas Nobleddef2462015-01-06 18:08:25 -080074 yield val
75 else:
76 nextit.append(val)
77 # after taking a random sampling, we shuffle the rest of the elements and
78 # yield them
79 random.shuffle(nextit)
80 for val in nextit:
81 yield val
82
83
ctiller3040cb72015-01-07 12:13:17 -080084_SUCCESS = object()
85_FAILURE = object()
86_RUNNING = object()
87_KILLED = object()
88
89
Craig Tiller3b083062015-01-12 13:51:28 -080090_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080091 'red': [ 31, 0 ],
92 'green': [ 32, 0 ],
93 'yellow': [ 33, 0 ],
94 'lightgray': [ 37, 0],
95 'gray': [ 30, 1 ],
Craig Tiller3b083062015-01-12 13:51:28 -080096 }
97
98
99_BEGINNING_OF_LINE = '\x1b[0G'
100_CLEAR_LINE = '\x1b[2K'
101
102
103_TAG_COLOR = {
104 'FAILED': 'red',
Craig Tillere1d0d1c2015-02-27 08:54:23 -0800105 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -0800106 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -0800107 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800108 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -0800109 'SUCCESS': 'green',
110 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800111 }
112
113
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200114def message(tag, msg, explanatory_text=None, do_newline=False):
115 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
116 return
117 message.old_tag = tag
118 message.old_msg = msg
Craig Tiller5058c692015-04-08 09:42:04 -0700119 if platform.system() == 'Windows':
120 if explanatory_text:
121 print explanatory_text
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200122 print '%s: %s' % (tag, msg)
Craig Tiller5058c692015-04-08 09:42:04 -0700123 return
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800124 try:
125 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
126 _BEGINNING_OF_LINE,
127 _CLEAR_LINE,
128 '\n%s' % explanatory_text if explanatory_text is not None else '',
129 _COLORS[_TAG_COLOR[tag]][1],
130 _COLORS[_TAG_COLOR[tag]][0],
131 tag,
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200132 msg,
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800133 '\n' if do_newline or explanatory_text is not None else ''))
134 sys.stdout.flush()
135 except:
136 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800137
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200138message.old_tag = ""
139message.old_msg = ""
Craig Tiller3b083062015-01-12 13:51:28 -0800140
Craig Tiller71735182015-01-15 17:07:13 -0800141def which(filename):
142 if '/' in filename:
143 return filename
144 for path in os.environ['PATH'].split(os.pathsep):
145 if os.path.exists(os.path.join(path, filename)):
146 return os.path.join(path, filename)
147 raise Exception('%s not found' % filename)
148
149
Craig Tiller547db2b2015-01-30 14:08:39 -0800150class JobSpec(object):
151 """Specifies what to run for a job."""
152
Jan Tattermusche8243592015-04-17 14:14:01 -0700153 def __init__(self, cmdline, shortname=None, environ=None, hash_targets=None, cwd=None, shell=False):
Craig Tiller547db2b2015-01-30 14:08:39 -0800154 """
155 Arguments:
156 cmdline: a list of arguments to pass as the command line
157 environ: a dictionary of environment variables to set in the child process
158 hash_targets: which files to include in the hash representing the jobs version
159 (or empty, indicating the job should not be hashed)
160 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800161 if environ is None:
162 environ = {}
163 if hash_targets is None:
164 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800165 self.cmdline = cmdline
166 self.environ = environ
167 self.shortname = cmdline[0] if shortname is None else shortname
168 self.hash_targets = hash_targets or []
Craig Tiller5058c692015-04-08 09:42:04 -0700169 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700170 self.shell = shell
Craig Tiller547db2b2015-01-30 14:08:39 -0800171
172 def identity(self):
173 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
174
175 def __hash__(self):
176 return hash(self.identity())
177
178 def __cmp__(self, other):
179 return self.identity() == other.identity()
180
181
ctiller3040cb72015-01-07 12:13:17 -0800182class Job(object):
183 """Manages one job."""
184
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100185 def __init__(self, spec, bin_hash, newline_on_success, travis):
Craig Tiller547db2b2015-01-30 14:08:39 -0800186 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800187 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -0800188 self._tempfile = tempfile.TemporaryFile()
Craig Tiller547db2b2015-01-30 14:08:39 -0800189 env = os.environ.copy()
190 for k, v in spec.environ.iteritems():
191 env[k] = v
Craig Tiller9d6139a2015-02-26 15:24:43 -0800192 self._start = time.time()
Craig Tiller547db2b2015-01-30 14:08:39 -0800193 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800194 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800195 stdout=self._tempfile,
Craig Tiller5058c692015-04-08 09:42:04 -0700196 cwd=spec.cwd,
Jan Tattermusche8243592015-04-17 14:14:01 -0700197 shell=spec.shell,
Craig Tiller547db2b2015-01-30 14:08:39 -0800198 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800199 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800200 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100201 self._travis = travis
Craig Tillerb84728d2015-02-26 15:40:39 -0800202 message('START', spec.shortname, do_newline=self._travis)
ctiller3040cb72015-01-07 12:13:17 -0800203
Craig Tiller71735182015-01-15 17:07:13 -0800204 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800205 """Poll current state of the job. Prints messages at completion."""
206 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800207 elapsed = time.time() - self._start
ctiller3040cb72015-01-07 12:13:17 -0800208 if self._process.returncode != 0:
209 self._state = _FAILURE
210 self._tempfile.seek(0)
211 stdout = self._tempfile.read()
Craig Tillerd0ffe142015-05-19 21:51:13 -0700212 message('FAILED', '%s [ret=%d, pid=%d]' % (
213 self._spec.shortname, self._process.returncode, self._process.pid),
214 stdout, do_newline=True)
ctiller3040cb72015-01-07 12:13:17 -0800215 else:
216 self._state = _SUCCESS
Craig Tiller9d6139a2015-02-26 15:24:43 -0800217 message('PASSED', '%s [time=%.1fsec]' % (self._spec.shortname, elapsed),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100218 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800219 if self._bin_hash:
220 update_cache.finished(self._spec.identity(), self._bin_hash)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800221 elif self._state == _RUNNING and time.time() - self._start > 300:
Craig Tiller84216782015-05-12 09:43:54 -0700222 self._tempfile.seek(0)
223 stdout = self._tempfile.read()
224 message('TIMEOUT', self._spec.shortname, stdout, do_newline=True)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800225 self.kill()
ctiller3040cb72015-01-07 12:13:17 -0800226 return self._state
227
228 def kill(self):
229 if self._state == _RUNNING:
230 self._state = _KILLED
231 self._process.terminate()
232
233
Nicolas Nobleddef2462015-01-06 18:08:25 -0800234class Jobset(object):
235 """Manages one run of jobs."""
236
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100237 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis, cache):
ctiller3040cb72015-01-07 12:13:17 -0800238 self._running = set()
239 self._check_cancelled = check_cancelled
240 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800241 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800242 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800243 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800244 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100245 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800246 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800247
Craig Tiller547db2b2015-01-30 14:08:39 -0800248 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800249 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800250 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800251 if self.cancelled(): return False
252 self.reap()
253 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800254 if spec.hash_targets:
255 bin_hash = hashlib.sha1()
256 for fn in spec.hash_targets:
257 with open(which(fn)) as f:
258 bin_hash.update(f.read())
259 bin_hash = bin_hash.hexdigest()
260 should_run = self._cache.should_run(spec.identity(), bin_hash)
261 else:
262 bin_hash = None
263 should_run = True
264 if should_run:
Craig Tiller5058c692015-04-08 09:42:04 -0700265 try:
266 self._running.add(Job(spec,
267 bin_hash,
268 self._newline_on_success,
269 self._travis))
270 except:
271 message('FAILED', spec.shortname)
272 self._cancelled = True
273 return False
ctiller3040cb72015-01-07 12:13:17 -0800274 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800275
ctiller3040cb72015-01-07 12:13:17 -0800276 def reap(self):
277 """Collect the dead jobs."""
278 while self._running:
279 dead = set()
280 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800281 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800282 if st == _RUNNING: continue
283 if st == _FAILURE: self._failures += 1
Craig Tiller9b3cc742015-02-26 22:25:03 -0800284 if st == _KILLED: self._failures += 1
ctiller3040cb72015-01-07 12:13:17 -0800285 dead.add(job)
286 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800287 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800288 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800289 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100290 if (not self._travis):
291 message('WAITING', '%d jobs running, %d complete, %d failed' % (
292 len(self._running), self._completed, self._failures))
Craig Tiller5058c692015-04-08 09:42:04 -0700293 if platform.system() == 'Windows':
294 time.sleep(0.1)
295 else:
296 global have_alarm
297 if not have_alarm:
298 have_alarm = True
299 signal.alarm(10)
300 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800301
302 def cancelled(self):
303 """Poll for cancellation."""
304 if self._cancelled: return True
305 if not self._check_cancelled(): return False
306 for job in self._running:
307 job.kill()
308 self._cancelled = True
309 return True
310
311 def finish(self):
312 while self._running:
313 if self.cancelled(): pass # poll cancellation
314 self.reap()
315 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800316
317
ctiller3040cb72015-01-07 12:13:17 -0800318def _never_cancelled():
319 return False
320
321
Craig Tiller71735182015-01-15 17:07:13 -0800322# cache class that caches nothing
323class NoCache(object):
324 def should_run(self, cmdline, bin_hash):
325 return True
326
327 def finished(self, cmdline, bin_hash):
328 pass
329
330
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800331def run(cmdlines,
332 check_cancelled=_never_cancelled,
333 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800334 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100335 travis=False,
Craig Tiller71735182015-01-15 17:07:13 -0800336 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800337 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800338 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100339 newline_on_success, travis,
Craig Tiller71735182015-01-15 17:07:13 -0800340 cache if cache is not None else NoCache())
Craig Tillerb84728d2015-02-26 15:40:39 -0800341 if not travis:
342 cmdlines = shuffle_iteratable(cmdlines)
343 else:
Craig Tiller904da8c2015-02-26 15:59:15 -0800344 cmdlines = sorted(cmdlines, key=lambda x: x.shortname)
Craig Tillerb84728d2015-02-26 15:40:39 -0800345 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800346 if not js.start(cmdline):
347 break
348 return js.finish()