blob: 26caf031c3a5f8b5d6a71371e58e270734824f88 [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
murgatroid99132ce6a2015-03-04 17:29:14 -0800139 def __init__(self, cmdline, shortname=None, environ=None, hash_targets=None):
Craig Tiller547db2b2015-01-30 14:08:39 -0800140 """
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 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800147 if environ is None:
148 environ = {}
149 if hash_targets is None:
150 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800151 self.cmdline = cmdline
152 self.environ = environ
153 self.shortname = cmdline[0] if shortname is None else shortname
154 self.hash_targets = hash_targets or []
155
156 def identity(self):
157 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
158
159 def __hash__(self):
160 return hash(self.identity())
161
162 def __cmp__(self, other):
163 return self.identity() == other.identity()
164
165
ctiller3040cb72015-01-07 12:13:17 -0800166class Job(object):
167 """Manages one job."""
168
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100169 def __init__(self, spec, bin_hash, newline_on_success, travis):
Craig Tiller547db2b2015-01-30 14:08:39 -0800170 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800171 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -0800172 self._tempfile = tempfile.TemporaryFile()
Craig Tiller547db2b2015-01-30 14:08:39 -0800173 env = os.environ.copy()
174 for k, v in spec.environ.iteritems():
175 env[k] = v
Craig Tiller9d6139a2015-02-26 15:24:43 -0800176 self._start = time.time()
Craig Tiller547db2b2015-01-30 14:08:39 -0800177 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800178 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800179 stdout=self._tempfile,
180 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800181 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800182 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100183 self._travis = travis
Craig Tillerb84728d2015-02-26 15:40:39 -0800184 message('START', spec.shortname, do_newline=self._travis)
ctiller3040cb72015-01-07 12:13:17 -0800185
Craig Tiller71735182015-01-15 17:07:13 -0800186 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800187 """Poll current state of the job. Prints messages at completion."""
188 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800189 elapsed = time.time() - self._start
ctiller3040cb72015-01-07 12:13:17 -0800190 if self._process.returncode != 0:
191 self._state = _FAILURE
192 self._tempfile.seek(0)
193 stdout = self._tempfile.read()
Craig Tiller71735182015-01-15 17:07:13 -0800194 message('FAILED', '%s [ret=%d]' % (
Craig Tiller547db2b2015-01-30 14:08:39 -0800195 self._spec.shortname, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -0800196 else:
197 self._state = _SUCCESS
Craig Tiller9d6139a2015-02-26 15:24:43 -0800198 message('PASSED', '%s [time=%.1fsec]' % (self._spec.shortname, elapsed),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100199 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800200 if self._bin_hash:
201 update_cache.finished(self._spec.identity(), self._bin_hash)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800202 elif self._state == _RUNNING and time.time() - self._start > 300:
203 message('TIMEOUT', self._spec.shortname, do_newline=self._travis)
204 self.kill()
ctiller3040cb72015-01-07 12:13:17 -0800205 return self._state
206
207 def kill(self):
208 if self._state == _RUNNING:
209 self._state = _KILLED
210 self._process.terminate()
211
212
Nicolas Nobleddef2462015-01-06 18:08:25 -0800213class Jobset(object):
214 """Manages one run of jobs."""
215
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100216 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis, cache):
ctiller3040cb72015-01-07 12:13:17 -0800217 self._running = set()
218 self._check_cancelled = check_cancelled
219 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800220 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800221 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800222 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800223 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100224 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800225 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800226
Craig Tiller547db2b2015-01-30 14:08:39 -0800227 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800228 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800229 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800230 if self.cancelled(): return False
231 self.reap()
232 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800233 if spec.hash_targets:
234 bin_hash = hashlib.sha1()
235 for fn in spec.hash_targets:
236 with open(which(fn)) as f:
237 bin_hash.update(f.read())
238 bin_hash = bin_hash.hexdigest()
239 should_run = self._cache.should_run(spec.identity(), bin_hash)
240 else:
241 bin_hash = None
242 should_run = True
243 if should_run:
244 self._running.add(Job(spec,
245 bin_hash,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100246 self._newline_on_success,
247 self._travis))
ctiller3040cb72015-01-07 12:13:17 -0800248 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800249
ctiller3040cb72015-01-07 12:13:17 -0800250 def reap(self):
251 """Collect the dead jobs."""
252 while self._running:
253 dead = set()
254 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800255 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800256 if st == _RUNNING: continue
257 if st == _FAILURE: self._failures += 1
Craig Tiller9b3cc742015-02-26 22:25:03 -0800258 if st == _KILLED: self._failures += 1
ctiller3040cb72015-01-07 12:13:17 -0800259 dead.add(job)
260 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800261 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800262 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800263 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100264 if (not self._travis):
265 message('WAITING', '%d jobs running, %d complete, %d failed' % (
266 len(self._running), self._completed, self._failures))
Craig Tiller9b3cc742015-02-26 22:25:03 -0800267 global have_alarm
268 if not have_alarm:
269 have_alarm = True
270 signal.alarm(10)
Craig Tiller336ad502015-02-24 14:46:02 -0800271 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800272
273 def cancelled(self):
274 """Poll for cancellation."""
275 if self._cancelled: return True
276 if not self._check_cancelled(): return False
277 for job in self._running:
278 job.kill()
279 self._cancelled = True
280 return True
281
282 def finish(self):
283 while self._running:
284 if self.cancelled(): pass # poll cancellation
285 self.reap()
286 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800287
288
ctiller3040cb72015-01-07 12:13:17 -0800289def _never_cancelled():
290 return False
291
292
Craig Tiller71735182015-01-15 17:07:13 -0800293# cache class that caches nothing
294class NoCache(object):
295 def should_run(self, cmdline, bin_hash):
296 return True
297
298 def finished(self, cmdline, bin_hash):
299 pass
300
301
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800302def run(cmdlines,
303 check_cancelled=_never_cancelled,
304 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800305 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100306 travis=False,
Craig Tiller71735182015-01-15 17:07:13 -0800307 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800308 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800309 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100310 newline_on_success, travis,
Craig Tiller71735182015-01-15 17:07:13 -0800311 cache if cache is not None else NoCache())
Craig Tillerb84728d2015-02-26 15:40:39 -0800312 if not travis:
313 cmdlines = shuffle_iteratable(cmdlines)
314 else:
Craig Tiller904da8c2015-02-26 15:59:15 -0800315 cmdlines = sorted(cmdlines, key=lambda x: x.shortname)
Craig Tillerb84728d2015-02-26 15:40:39 -0800316 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800317 if not js.start(cmdline):
318 break
319 return js.finish()