blob: 569cb5bac2090719d6e0cff3d0b57d0fe935ed48 [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
Craig Tiller547db2b2015-01-30 14:08:39 -0800157 def __init__(self, spec, bin_hash, newline_on_success):
158 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
164 self._process = subprocess.Popen(args=spec.cmdline,
ctiller3040cb72015-01-07 12:13:17 -0800165 stderr=subprocess.STDOUT,
Craig Tiller547db2b2015-01-30 14:08:39 -0800166 stdout=self._tempfile,
167 env=env)
ctiller3040cb72015-01-07 12:13:17 -0800168 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800169 self._newline_on_success = newline_on_success
Craig Tiller547db2b2015-01-30 14:08:39 -0800170 message('START', spec.shortname)
ctiller3040cb72015-01-07 12:13:17 -0800171
Craig Tiller71735182015-01-15 17:07:13 -0800172 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800173 """Poll current state of the job. Prints messages at completion."""
174 if self._state == _RUNNING and self._process.poll() is not None:
175 if self._process.returncode != 0:
176 self._state = _FAILURE
177 self._tempfile.seek(0)
178 stdout = self._tempfile.read()
Craig Tiller71735182015-01-15 17:07:13 -0800179 message('FAILED', '%s [ret=%d]' % (
Craig Tiller547db2b2015-01-30 14:08:39 -0800180 self._spec.shortname, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -0800181 else:
182 self._state = _SUCCESS
Craig Tiller547db2b2015-01-30 14:08:39 -0800183 message('PASSED', self._spec.shortname,
Craig Tiller71735182015-01-15 17:07:13 -0800184 do_newline=self._newline_on_success)
Craig Tiller547db2b2015-01-30 14:08:39 -0800185 if self._bin_hash:
186 update_cache.finished(self._spec.identity(), self._bin_hash)
ctiller3040cb72015-01-07 12:13:17 -0800187 return self._state
188
189 def kill(self):
190 if self._state == _RUNNING:
191 self._state = _KILLED
192 self._process.terminate()
193
194
Nicolas Nobleddef2462015-01-06 18:08:25 -0800195class Jobset(object):
196 """Manages one run of jobs."""
197
Craig Tiller71735182015-01-15 17:07:13 -0800198 def __init__(self, check_cancelled, maxjobs, newline_on_success, cache):
ctiller3040cb72015-01-07 12:13:17 -0800199 self._running = set()
200 self._check_cancelled = check_cancelled
201 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800202 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800203 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800204 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800205 self._newline_on_success = newline_on_success
Craig Tiller71735182015-01-15 17:07:13 -0800206 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800207
Craig Tiller547db2b2015-01-30 14:08:39 -0800208 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800209 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800210 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800211 if self.cancelled(): return False
212 self.reap()
213 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800214 if spec.hash_targets:
215 bin_hash = hashlib.sha1()
216 for fn in spec.hash_targets:
217 with open(which(fn)) as f:
218 bin_hash.update(f.read())
219 bin_hash = bin_hash.hexdigest()
220 should_run = self._cache.should_run(spec.identity(), bin_hash)
221 else:
222 bin_hash = None
223 should_run = True
224 if should_run:
225 self._running.add(Job(spec,
226 bin_hash,
227 self._newline_on_success))
ctiller3040cb72015-01-07 12:13:17 -0800228 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800229
ctiller3040cb72015-01-07 12:13:17 -0800230 def reap(self):
231 """Collect the dead jobs."""
232 while self._running:
233 dead = set()
234 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800235 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800236 if st == _RUNNING: continue
237 if st == _FAILURE: self._failures += 1
238 dead.add(job)
239 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800240 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800241 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800242 if dead: return
Craig Tiller6f5e2c42015-01-21 18:05:31 -0800243 message('WAITING', '%d jobs running, %d complete, %d failed' % (
244 len(self._running), self._completed, self._failures))
Craig Tiller336ad502015-02-24 14:46:02 -0800245 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800246
247 def cancelled(self):
248 """Poll for cancellation."""
249 if self._cancelled: return True
250 if not self._check_cancelled(): return False
251 for job in self._running:
252 job.kill()
253 self._cancelled = True
254 return True
255
256 def finish(self):
257 while self._running:
258 if self.cancelled(): pass # poll cancellation
259 self.reap()
260 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800261
262
ctiller3040cb72015-01-07 12:13:17 -0800263def _never_cancelled():
264 return False
265
266
Craig Tiller71735182015-01-15 17:07:13 -0800267# cache class that caches nothing
268class NoCache(object):
269 def should_run(self, cmdline, bin_hash):
270 return True
271
272 def finished(self, cmdline, bin_hash):
273 pass
274
275
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800276def run(cmdlines,
277 check_cancelled=_never_cancelled,
278 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800279 newline_on_success=False,
280 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800281 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800282 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tiller71735182015-01-15 17:07:13 -0800283 newline_on_success,
284 cache if cache is not None else NoCache())
ctiller3040cb72015-01-07 12:13:17 -0800285 for cmdline in shuffle_iteratable(cmdlines):
286 if not js.start(cmdline):
287 break
288 return js.finish()