blob: ad65da535b42bccf7ff642b61b092b27ecf808d4 [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
Nicolas Nobleddef2462015-01-06 18:08:25 -080035import random
Craig Tiller336ad502015-02-24 14:46:02 -080036import signal
Nicolas Nobleddef2462015-01-06 18:08:25 -080037import subprocess
38import sys
ctiller3040cb72015-01-07 12:13:17 -080039import tempfile
40import time
Nicolas Nobleddef2462015-01-06 18:08:25 -080041
ctiller3040cb72015-01-07 12:13:17 -080042
ctiller94e5dde2015-01-09 10:41:59 -080043_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Nicolas Nobleddef2462015-01-06 18:08:25 -080044
45
Craig Tiller9b3cc742015-02-26 22:25:03 -080046have_alarm = False
47def alarm_handler(unused_signum, unused_frame):
48 global have_alarm
49 have_alarm = False
50
51
Craig Tiller336ad502015-02-24 14:46:02 -080052# setup a signal handler so that signal.pause registers 'something'
53# when a child finishes
54# not using futures and threading to avoid a dependency on subprocess32
55signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None)
Craig Tiller9b3cc742015-02-26 22:25:03 -080056signal.signal(signal.SIGALRM, alarm_handler)
Craig Tiller336ad502015-02-24 14:46:02 -080057
58
Nicolas Nobleddef2462015-01-06 18:08:25 -080059def shuffle_iteratable(it):
60 """Return an iterable that randomly walks it"""
61 # take a random sampling from the passed in iterable
62 # we take an element with probablity 1/p and rapidly increase
63 # p as we take elements - this gives us a somewhat random set of values before
64 # we've seen all the values, but starts producing values without having to
65 # compute ALL of them at once, allowing tests to start a little earlier
66 nextit = []
67 p = 1
68 for val in it:
69 if random.randint(0, p) == 0:
ctiller3040cb72015-01-07 12:13:17 -080070 p = min(p*2, 100)
Nicolas Nobleddef2462015-01-06 18:08:25 -080071 yield val
72 else:
73 nextit.append(val)
74 # after taking a random sampling, we shuffle the rest of the elements and
75 # yield them
76 random.shuffle(nextit)
77 for val in nextit:
78 yield val
79
80
ctiller3040cb72015-01-07 12:13:17 -080081_SUCCESS = object()
82_FAILURE = object()
83_RUNNING = object()
84_KILLED = object()
85
86
Craig Tiller3b083062015-01-12 13:51:28 -080087_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080088 'red': [ 31, 0 ],
89 'green': [ 32, 0 ],
90 'yellow': [ 33, 0 ],
91 'lightgray': [ 37, 0],
92 'gray': [ 30, 1 ],
Craig Tiller3b083062015-01-12 13:51:28 -080093 }
94
95
96_BEGINNING_OF_LINE = '\x1b[0G'
97_CLEAR_LINE = '\x1b[2K'
98
99
100_TAG_COLOR = {
101 'FAILED': 'red',
Craig Tillere1d0d1c2015-02-27 08:54:23 -0800102 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -0800103 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -0800104 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800105 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -0800106 'SUCCESS': 'green',
107 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800108 }
109
110
Nicolas Noble044db742015-01-14 16:57:24 -0800111def message(tag, message, explanatory_text=None, do_newline=False):
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800112 try:
113 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
114 _BEGINNING_OF_LINE,
115 _CLEAR_LINE,
116 '\n%s' % explanatory_text if explanatory_text is not None else '',
117 _COLORS[_TAG_COLOR[tag]][1],
118 _COLORS[_TAG_COLOR[tag]][0],
119 tag,
120 message,
121 '\n' if do_newline or explanatory_text is not None else ''))
122 sys.stdout.flush()
123 except:
124 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800125
126
Craig Tiller71735182015-01-15 17:07:13 -0800127def which(filename):
128 if '/' in filename:
129 return filename
130 for path in os.environ['PATH'].split(os.pathsep):
131 if os.path.exists(os.path.join(path, filename)):
132 return os.path.join(path, filename)
133 raise Exception('%s not found' % filename)
134
135
Craig Tiller547db2b2015-01-30 14:08:39 -0800136class JobSpec(object):
137 """Specifies what to run for a job."""
138
139 def __init__(self, cmdline, shortname=None, environ={}, hash_targets=[]):
140 """
141 Arguments:
142 cmdline: a list of arguments to pass as the command line
143 environ: a dictionary of environment variables to set in the child process
144 hash_targets: which files to include in the hash representing the jobs version
145 (or empty, indicating the job should not be hashed)
146 """
147 self.cmdline = cmdline
148 self.environ = environ
149 self.shortname = cmdline[0] if shortname is None else shortname
150 self.hash_targets = hash_targets or []
151
152 def identity(self):
153 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
154
155 def __hash__(self):
156 return hash(self.identity())
157
158 def __cmp__(self, other):
159 return self.identity() == other.identity()
160
161
ctiller3040cb72015-01-07 12:13:17 -0800162class Job(object):
163 """Manages one job."""
164
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100165 def __init__(self, spec, bin_hash, newline_on_success, travis):
Craig Tiller547db2b2015-01-30 14:08:39 -0800166 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800167 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -0800168 self._tempfile = tempfile.TemporaryFile()
Craig Tiller547db2b2015-01-30 14:08:39 -0800169 env = os.environ.copy()
170 for k, v in spec.environ.iteritems():
171 env[k] = v
Craig Tiller9d6139a2015-02-26 15:24:43 -0800172 self._start = time.time()
Craig Tiller547db2b2015-01-30 14:08:39 -0800173 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800174 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800175 stdout=self._tempfile,
176 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800177 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800178 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100179 self._travis = travis
Craig Tillerb84728d2015-02-26 15:40:39 -0800180 message('START', spec.shortname, do_newline=self._travis)
ctiller3040cb72015-01-07 12:13:17 -0800181
Craig Tiller71735182015-01-15 17:07:13 -0800182 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800183 """Poll current state of the job. Prints messages at completion."""
184 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800185 elapsed = time.time() - self._start
ctiller3040cb72015-01-07 12:13:17 -0800186 if self._process.returncode != 0:
187 self._state = _FAILURE
188 self._tempfile.seek(0)
189 stdout = self._tempfile.read()
Craig Tiller71735182015-01-15 17:07:13 -0800190 message('FAILED', '%s [ret=%d]' % (
Craig Tiller547db2b2015-01-30 14:08:39 -0800191 self._spec.shortname, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -0800192 else:
193 self._state = _SUCCESS
Craig Tiller9d6139a2015-02-26 15:24:43 -0800194 message('PASSED', '%s [time=%.1fsec]' % (self._spec.shortname, elapsed),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100195 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800196 if self._bin_hash:
197 update_cache.finished(self._spec.identity(), self._bin_hash)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800198 elif self._state == _RUNNING and time.time() - self._start > 300:
199 message('TIMEOUT', self._spec.shortname, do_newline=self._travis)
200 self.kill()
ctiller3040cb72015-01-07 12:13:17 -0800201 return self._state
202
203 def kill(self):
204 if self._state == _RUNNING:
205 self._state = _KILLED
206 self._process.terminate()
207
208
Nicolas Nobleddef2462015-01-06 18:08:25 -0800209class Jobset(object):
210 """Manages one run of jobs."""
211
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100212 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis, cache):
ctiller3040cb72015-01-07 12:13:17 -0800213 self._running = set()
214 self._check_cancelled = check_cancelled
215 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800216 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800217 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800218 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800219 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100220 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800221 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800222
Craig Tiller547db2b2015-01-30 14:08:39 -0800223 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800224 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800225 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800226 if self.cancelled(): return False
227 self.reap()
228 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800229 if spec.hash_targets:
230 bin_hash = hashlib.sha1()
231 for fn in spec.hash_targets:
232 with open(which(fn)) as f:
233 bin_hash.update(f.read())
234 bin_hash = bin_hash.hexdigest()
235 should_run = self._cache.should_run(spec.identity(), bin_hash)
236 else:
237 bin_hash = None
238 should_run = True
239 if should_run:
240 self._running.add(Job(spec,
241 bin_hash,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100242 self._newline_on_success,
243 self._travis))
ctiller3040cb72015-01-07 12:13:17 -0800244 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800245
ctiller3040cb72015-01-07 12:13:17 -0800246 def reap(self):
247 """Collect the dead jobs."""
248 while self._running:
249 dead = set()
250 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800251 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800252 if st == _RUNNING: continue
253 if st == _FAILURE: self._failures += 1
Craig Tiller9b3cc742015-02-26 22:25:03 -0800254 if st == _KILLED: self._failures += 1
ctiller3040cb72015-01-07 12:13:17 -0800255 dead.add(job)
256 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800257 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800258 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800259 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100260 if (not self._travis):
261 message('WAITING', '%d jobs running, %d complete, %d failed' % (
262 len(self._running), self._completed, self._failures))
Craig Tiller9b3cc742015-02-26 22:25:03 -0800263 global have_alarm
264 if not have_alarm:
265 have_alarm = True
266 signal.alarm(10)
Craig Tiller336ad502015-02-24 14:46:02 -0800267 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800268
269 def cancelled(self):
270 """Poll for cancellation."""
271 if self._cancelled: return True
272 if not self._check_cancelled(): return False
273 for job in self._running:
274 job.kill()
275 self._cancelled = True
276 return True
277
278 def finish(self):
279 while self._running:
280 if self.cancelled(): pass # poll cancellation
281 self.reap()
282 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800283
284
ctiller3040cb72015-01-07 12:13:17 -0800285def _never_cancelled():
286 return False
287
288
Craig Tiller71735182015-01-15 17:07:13 -0800289# cache class that caches nothing
290class NoCache(object):
291 def should_run(self, cmdline, bin_hash):
292 return True
293
294 def finished(self, cmdline, bin_hash):
295 pass
296
297
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800298def run(cmdlines,
299 check_cancelled=_never_cancelled,
300 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800301 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100302 travis=False,
Craig Tiller71735182015-01-15 17:07:13 -0800303 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800304 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800305 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100306 newline_on_success, travis,
Craig Tiller71735182015-01-15 17:07:13 -0800307 cache if cache is not None else NoCache())
Craig Tillerb84728d2015-02-26 15:40:39 -0800308 if not travis:
309 cmdlines = shuffle_iteratable(cmdlines)
310 else:
Craig Tiller904da8c2015-02-26 15:59:15 -0800311 cmdlines = sorted(cmdlines, key=lambda x: x.shortname)
Craig Tillerb84728d2015-02-26 15:40:39 -0800312 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800313 if not js.start(cmdline):
314 break
315 return js.finish()