blob: 22d24c124cd9585db2450a0f174fe291685abc82 [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 Tiller336ad502015-02-24 14:46:02 -080046# setup a signal handler so that signal.pause registers 'something'
47# when a child finishes
48# not using futures and threading to avoid a dependency on subprocess32
49signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None)
50
51
Nicolas Nobleddef2462015-01-06 18:08:25 -080052def shuffle_iteratable(it):
53 """Return an iterable that randomly walks it"""
54 # take a random sampling from the passed in iterable
55 # we take an element with probablity 1/p and rapidly increase
56 # p as we take elements - this gives us a somewhat random set of values before
57 # we've seen all the values, but starts producing values without having to
58 # compute ALL of them at once, allowing tests to start a little earlier
59 nextit = []
60 p = 1
61 for val in it:
62 if random.randint(0, p) == 0:
ctiller3040cb72015-01-07 12:13:17 -080063 p = min(p*2, 100)
Nicolas Nobleddef2462015-01-06 18:08:25 -080064 yield val
65 else:
66 nextit.append(val)
67 # after taking a random sampling, we shuffle the rest of the elements and
68 # yield them
69 random.shuffle(nextit)
70 for val in nextit:
71 yield val
72
73
ctiller3040cb72015-01-07 12:13:17 -080074_SUCCESS = object()
75_FAILURE = object()
76_RUNNING = object()
77_KILLED = object()
78
79
Craig Tiller3b083062015-01-12 13:51:28 -080080_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080081 'red': [ 31, 0 ],
82 'green': [ 32, 0 ],
83 'yellow': [ 33, 0 ],
84 'lightgray': [ 37, 0],
85 'gray': [ 30, 1 ],
Craig Tiller3b083062015-01-12 13:51:28 -080086 }
87
88
89_BEGINNING_OF_LINE = '\x1b[0G'
90_CLEAR_LINE = '\x1b[2K'
91
92
93_TAG_COLOR = {
94 'FAILED': 'red',
95 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080096 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080097 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080098 'SUCCESS': 'green',
99 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800100 }
101
102
Nicolas Noble044db742015-01-14 16:57:24 -0800103def message(tag, message, explanatory_text=None, do_newline=False):
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800104 try:
105 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
106 _BEGINNING_OF_LINE,
107 _CLEAR_LINE,
108 '\n%s' % explanatory_text if explanatory_text is not None else '',
109 _COLORS[_TAG_COLOR[tag]][1],
110 _COLORS[_TAG_COLOR[tag]][0],
111 tag,
112 message,
113 '\n' if do_newline or explanatory_text is not None else ''))
114 sys.stdout.flush()
115 except:
116 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800117
118
Craig Tiller71735182015-01-15 17:07:13 -0800119def which(filename):
120 if '/' in filename:
121 return filename
122 for path in os.environ['PATH'].split(os.pathsep):
123 if os.path.exists(os.path.join(path, filename)):
124 return os.path.join(path, filename)
125 raise Exception('%s not found' % filename)
126
127
Craig Tiller547db2b2015-01-30 14:08:39 -0800128class JobSpec(object):
129 """Specifies what to run for a job."""
130
131 def __init__(self, cmdline, shortname=None, environ={}, hash_targets=[]):
132 """
133 Arguments:
134 cmdline: a list of arguments to pass as the command line
135 environ: a dictionary of environment variables to set in the child process
136 hash_targets: which files to include in the hash representing the jobs version
137 (or empty, indicating the job should not be hashed)
138 """
139 self.cmdline = cmdline
140 self.environ = environ
141 self.shortname = cmdline[0] if shortname is None else shortname
142 self.hash_targets = hash_targets or []
143
144 def identity(self):
145 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
146
147 def __hash__(self):
148 return hash(self.identity())
149
150 def __cmp__(self, other):
151 return self.identity() == other.identity()
152
153
ctiller3040cb72015-01-07 12:13:17 -0800154class Job(object):
155 """Manages one job."""
156
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100157 def __init__(self, spec, bin_hash, newline_on_success, travis):
Craig Tiller547db2b2015-01-30 14:08:39 -0800158 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800159 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -0800160 self._tempfile = tempfile.TemporaryFile()
Craig Tiller547db2b2015-01-30 14:08:39 -0800161 env = os.environ.copy()
162 for k, v in spec.environ.iteritems():
163 env[k] = v
Craig Tiller9d6139a2015-02-26 15:24:43 -0800164 self._start = time.time()
Craig Tiller547db2b2015-01-30 14:08:39 -0800165 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800166 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800167 stdout=self._tempfile,
168 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800169 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800170 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100171 self._travis = travis
172 if not travis:
173 message('START', spec.shortname)
ctiller3040cb72015-01-07 12:13:17 -0800174
Craig Tiller71735182015-01-15 17:07:13 -0800175 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800176 """Poll current state of the job. Prints messages at completion."""
177 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800178 elapsed = time.time() - self._start
ctiller3040cb72015-01-07 12:13:17 -0800179 if self._process.returncode != 0:
180 self._state = _FAILURE
181 self._tempfile.seek(0)
182 stdout = self._tempfile.read()
Craig Tiller71735182015-01-15 17:07:13 -0800183 message('FAILED', '%s [ret=%d]' % (
Craig Tiller547db2b2015-01-30 14:08:39 -0800184 self._spec.shortname, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -0800185 else:
186 self._state = _SUCCESS
Craig Tiller9d6139a2015-02-26 15:24:43 -0800187 message('PASSED', '%s [time=%.1fsec]' % (self._spec.shortname, elapsed),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100188 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800189 if self._bin_hash:
190 update_cache.finished(self._spec.identity(), self._bin_hash)
ctiller3040cb72015-01-07 12:13:17 -0800191 return self._state
192
193 def kill(self):
194 if self._state == _RUNNING:
195 self._state = _KILLED
196 self._process.terminate()
197
198
Nicolas Nobleddef2462015-01-06 18:08:25 -0800199class Jobset(object):
200 """Manages one run of jobs."""
201
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100202 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis, cache):
ctiller3040cb72015-01-07 12:13:17 -0800203 self._running = set()
204 self._check_cancelled = check_cancelled
205 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800206 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800207 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800208 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800209 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100210 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800211 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800212
Craig Tiller547db2b2015-01-30 14:08:39 -0800213 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800214 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800215 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800216 if self.cancelled(): return False
217 self.reap()
218 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800219 if spec.hash_targets:
220 bin_hash = hashlib.sha1()
221 for fn in spec.hash_targets:
222 with open(which(fn)) as f:
223 bin_hash.update(f.read())
224 bin_hash = bin_hash.hexdigest()
225 should_run = self._cache.should_run(spec.identity(), bin_hash)
226 else:
227 bin_hash = None
228 should_run = True
229 if should_run:
230 self._running.add(Job(spec,
231 bin_hash,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100232 self._newline_on_success,
233 self._travis))
ctiller3040cb72015-01-07 12:13:17 -0800234 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800235
ctiller3040cb72015-01-07 12:13:17 -0800236 def reap(self):
237 """Collect the dead jobs."""
238 while self._running:
239 dead = set()
240 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800241 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800242 if st == _RUNNING: continue
243 if st == _FAILURE: self._failures += 1
244 dead.add(job)
245 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800246 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800247 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800248 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100249 if (not self._travis):
250 message('WAITING', '%d jobs running, %d complete, %d failed' % (
251 len(self._running), self._completed, self._failures))
Craig Tiller336ad502015-02-24 14:46:02 -0800252 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800253
254 def cancelled(self):
255 """Poll for cancellation."""
256 if self._cancelled: return True
257 if not self._check_cancelled(): return False
258 for job in self._running:
259 job.kill()
260 self._cancelled = True
261 return True
262
263 def finish(self):
264 while self._running:
265 if self.cancelled(): pass # poll cancellation
266 self.reap()
267 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800268
269
ctiller3040cb72015-01-07 12:13:17 -0800270def _never_cancelled():
271 return False
272
273
Craig Tiller71735182015-01-15 17:07:13 -0800274# cache class that caches nothing
275class NoCache(object):
276 def should_run(self, cmdline, bin_hash):
277 return True
278
279 def finished(self, cmdline, bin_hash):
280 pass
281
282
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800283def run(cmdlines,
284 check_cancelled=_never_cancelled,
285 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800286 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100287 travis=False,
Craig Tiller71735182015-01-15 17:07:13 -0800288 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800289 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800290 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100291 newline_on_success, travis,
Craig Tiller71735182015-01-15 17:07:13 -0800292 cache if cache is not None else NoCache())
ctiller3040cb72015-01-07 12:13:17 -0800293 for cmdline in shuffle_iteratable(cmdlines):
294 if not js.start(cmdline):
295 break
296 return js.finish()