blob: 39670f1898b47df82ff1e291afbdccfebb51d5eb [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):
104 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
Craig Tiller3b083062015-01-12 13:51:28 -0800105 _BEGINNING_OF_LINE,
106 _CLEAR_LINE,
Nicolas Noble044db742015-01-14 16:57:24 -0800107 '\n%s' % explanatory_text if explanatory_text is not None else '',
108 _COLORS[_TAG_COLOR[tag]][1],
109 _COLORS[_TAG_COLOR[tag]][0],
Craig Tiller3b083062015-01-12 13:51:28 -0800110 tag,
111 message,
Nicolas Noble044db742015-01-14 16:57:24 -0800112 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller3b083062015-01-12 13:51:28 -0800113 sys.stdout.flush()
114
115
Craig Tiller71735182015-01-15 17:07:13 -0800116def which(filename):
117 if '/' in filename:
118 return filename
119 for path in os.environ['PATH'].split(os.pathsep):
120 if os.path.exists(os.path.join(path, filename)):
121 return os.path.join(path, filename)
122 raise Exception('%s not found' % filename)
123
124
Craig Tiller547db2b2015-01-30 14:08:39 -0800125class JobSpec(object):
126 """Specifies what to run for a job."""
127
128 def __init__(self, cmdline, shortname=None, environ={}, hash_targets=[]):
129 """
130 Arguments:
131 cmdline: a list of arguments to pass as the command line
132 environ: a dictionary of environment variables to set in the child process
133 hash_targets: which files to include in the hash representing the jobs version
134 (or empty, indicating the job should not be hashed)
135 """
136 self.cmdline = cmdline
137 self.environ = environ
138 self.shortname = cmdline[0] if shortname is None else shortname
139 self.hash_targets = hash_targets or []
140
141 def identity(self):
142 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
143
144 def __hash__(self):
145 return hash(self.identity())
146
147 def __cmp__(self, other):
148 return self.identity() == other.identity()
149
150
ctiller3040cb72015-01-07 12:13:17 -0800151class Job(object):
152 """Manages one job."""
153
Craig Tiller547db2b2015-01-30 14:08:39 -0800154 def __init__(self, spec, bin_hash, newline_on_success):
155 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800156 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -0800157 self._tempfile = tempfile.TemporaryFile()
Craig Tiller547db2b2015-01-30 14:08:39 -0800158 env = os.environ.copy()
159 for k, v in spec.environ.iteritems():
160 env[k] = v
161 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800162 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800163 stdout=self._tempfile,
164 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800165 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800166 self._newline_on_success = newline_on_success
Craig Tiller547db2b2015-01-30 14:08:39 -0800167 message('START', spec.shortname)
ctiller3040cb72015-01-07 12:13:17 -0800168
Craig Tiller71735182015-01-15 17:07:13 -0800169 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800170 """Poll current state of the job. Prints messages at completion."""
171 if self._state == _RUNNING and self._process.poll() is not None:
172 if self._process.returncode != 0:
173 self._state = _FAILURE
174 self._tempfile.seek(0)
175 stdout = self._tempfile.read()
Craig Tiller71735182015-01-15 17:07:13 -0800176 message('FAILED', '%s [ret=%d]' % (
Craig Tiller547db2b2015-01-30 14:08:39 -0800177 self._spec.shortname, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -0800178 else:
179 self._state = _SUCCESS
Craig Tiller547db2b2015-01-30 14:08:39 -0800180 message('PASSED', self._spec.shortname,
Craig Tiller71735182015-01-15 17:07:13 -0800181 do_newline=self._newline_on_success)
Craig Tiller547db2b2015-01-30 14:08:39 -0800182 if self._bin_hash:
183 update_cache.finished(self._spec.identity(), self._bin_hash)
ctiller3040cb72015-01-07 12:13:17 -0800184 return self._state
185
186 def kill(self):
187 if self._state == _RUNNING:
188 self._state = _KILLED
189 self._process.terminate()
190
191
Nicolas Nobleddef2462015-01-06 18:08:25 -0800192class Jobset(object):
193 """Manages one run of jobs."""
194
Craig Tiller71735182015-01-15 17:07:13 -0800195 def __init__(self, check_cancelled, maxjobs, newline_on_success, cache):
ctiller3040cb72015-01-07 12:13:17 -0800196 self._running = set()
197 self._check_cancelled = check_cancelled
198 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800199 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800200 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800201 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800202 self._newline_on_success = newline_on_success
Craig Tiller71735182015-01-15 17:07:13 -0800203 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800204
Craig Tiller547db2b2015-01-30 14:08:39 -0800205 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800206 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800207 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800208 if self.cancelled(): return False
209 self.reap()
210 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800211 if spec.hash_targets:
212 bin_hash = hashlib.sha1()
213 for fn in spec.hash_targets:
214 with open(which(fn)) as f:
215 bin_hash.update(f.read())
216 bin_hash = bin_hash.hexdigest()
217 should_run = self._cache.should_run(spec.identity(), bin_hash)
218 else:
219 bin_hash = None
220 should_run = True
221 if should_run:
222 self._running.add(Job(spec,
223 bin_hash,
224 self._newline_on_success))
ctiller3040cb72015-01-07 12:13:17 -0800225 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800226
ctiller3040cb72015-01-07 12:13:17 -0800227 def reap(self):
228 """Collect the dead jobs."""
229 while self._running:
230 dead = set()
231 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800232 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800233 if st == _RUNNING: continue
234 if st == _FAILURE: self._failures += 1
235 dead.add(job)
236 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800237 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800238 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800239 if dead: return
Craig Tiller6f5e2c42015-01-21 18:05:31 -0800240 message('WAITING', '%d jobs running, %d complete, %d failed' % (
241 len(self._running), self._completed, self._failures))
Craig Tiller336ad502015-02-24 14:46:02 -0800242 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800243
244 def cancelled(self):
245 """Poll for cancellation."""
246 if self._cancelled: return True
247 if not self._check_cancelled(): return False
248 for job in self._running:
249 job.kill()
250 self._cancelled = True
251 return True
252
253 def finish(self):
254 while self._running:
255 if self.cancelled(): pass # poll cancellation
256 self.reap()
257 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800258
259
ctiller3040cb72015-01-07 12:13:17 -0800260def _never_cancelled():
261 return False
262
263
Craig Tiller71735182015-01-15 17:07:13 -0800264# cache class that caches nothing
265class NoCache(object):
266 def should_run(self, cmdline, bin_hash):
267 return True
268
269 def finished(self, cmdline, bin_hash):
270 pass
271
272
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800273def run(cmdlines,
274 check_cancelled=_never_cancelled,
275 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800276 newline_on_success=False,
277 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800278 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800279 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tiller71735182015-01-15 17:07:13 -0800280 newline_on_success,
281 cache if cache is not None else NoCache())
ctiller3040cb72015-01-07 12:13:17 -0800282 for cmdline in shuffle_iteratable(cmdlines):
283 if not js.start(cmdline):
284 break
285 return js.finish()