blob: 7a6d979ba30bef94fd4f0680e99a71af72a605f2 [file] [log] [blame]
Nicolas Nobleddef2462015-01-06 18:08:25 -08001"""Run a group of subprocesses and then finish."""
2
Craig Tiller71735182015-01-15 17:07:13 -08003import hashlib
Nicolas Nobleddef2462015-01-06 18:08:25 -08004import multiprocessing
Craig Tiller71735182015-01-15 17:07:13 -08005import os
Nicolas Nobleddef2462015-01-06 18:08:25 -08006import random
7import subprocess
8import sys
ctiller3040cb72015-01-07 12:13:17 -08009import tempfile
10import time
Nicolas Nobleddef2462015-01-06 18:08:25 -080011
ctiller3040cb72015-01-07 12:13:17 -080012
ctiller94e5dde2015-01-09 10:41:59 -080013_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Nicolas Nobleddef2462015-01-06 18:08:25 -080014
15
16def shuffle_iteratable(it):
17 """Return an iterable that randomly walks it"""
18 # take a random sampling from the passed in iterable
19 # we take an element with probablity 1/p and rapidly increase
20 # p as we take elements - this gives us a somewhat random set of values before
21 # we've seen all the values, but starts producing values without having to
22 # compute ALL of them at once, allowing tests to start a little earlier
23 nextit = []
24 p = 1
25 for val in it:
26 if random.randint(0, p) == 0:
ctiller3040cb72015-01-07 12:13:17 -080027 p = min(p*2, 100)
Nicolas Nobleddef2462015-01-06 18:08:25 -080028 yield val
29 else:
30 nextit.append(val)
31 # after taking a random sampling, we shuffle the rest of the elements and
32 # yield them
33 random.shuffle(nextit)
34 for val in nextit:
35 yield val
36
37
ctiller3040cb72015-01-07 12:13:17 -080038_SUCCESS = object()
39_FAILURE = object()
40_RUNNING = object()
41_KILLED = object()
42
43
Craig Tiller3b083062015-01-12 13:51:28 -080044_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080045 'red': [ 31, 0 ],
46 'green': [ 32, 0 ],
47 'yellow': [ 33, 0 ],
48 'lightgray': [ 37, 0],
49 'gray': [ 30, 1 ],
Craig Tiller3b083062015-01-12 13:51:28 -080050 }
51
52
53_BEGINNING_OF_LINE = '\x1b[0G'
54_CLEAR_LINE = '\x1b[2K'
55
56
57_TAG_COLOR = {
58 'FAILED': 'red',
59 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080060 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080061 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080062 'SUCCESS': 'green',
63 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080064 }
65
66
Nicolas Noble044db742015-01-14 16:57:24 -080067def message(tag, message, explanatory_text=None, do_newline=False):
68 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
Craig Tiller3b083062015-01-12 13:51:28 -080069 _BEGINNING_OF_LINE,
70 _CLEAR_LINE,
Nicolas Noble044db742015-01-14 16:57:24 -080071 '\n%s' % explanatory_text if explanatory_text is not None else '',
72 _COLORS[_TAG_COLOR[tag]][1],
73 _COLORS[_TAG_COLOR[tag]][0],
Craig Tiller3b083062015-01-12 13:51:28 -080074 tag,
75 message,
Nicolas Noble044db742015-01-14 16:57:24 -080076 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller3b083062015-01-12 13:51:28 -080077 sys.stdout.flush()
78
79
Craig Tiller71735182015-01-15 17:07:13 -080080def which(filename):
81 if '/' in filename:
82 return filename
83 for path in os.environ['PATH'].split(os.pathsep):
84 if os.path.exists(os.path.join(path, filename)):
85 return os.path.join(path, filename)
86 raise Exception('%s not found' % filename)
87
88
ctiller3040cb72015-01-07 12:13:17 -080089class Job(object):
90 """Manages one job."""
91
Craig Tiller71735182015-01-15 17:07:13 -080092 def __init__(self, cmdline, bin_hash, newline_on_success):
93 self._cmdline = cmdline
94 self._bin_hash = bin_hash
ctiller3040cb72015-01-07 12:13:17 -080095 self._tempfile = tempfile.TemporaryFile()
96 self._process = subprocess.Popen(args=cmdline,
97 stderr=subprocess.STDOUT,
98 stdout=self._tempfile)
99 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -0800100 self._newline_on_success = newline_on_success
Craig Tiller71735182015-01-15 17:07:13 -0800101 message('START', ' '.join(self._cmdline))
ctiller3040cb72015-01-07 12:13:17 -0800102
Craig Tiller71735182015-01-15 17:07:13 -0800103 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800104 """Poll current state of the job. Prints messages at completion."""
105 if self._state == _RUNNING and self._process.poll() is not None:
106 if self._process.returncode != 0:
107 self._state = _FAILURE
108 self._tempfile.seek(0)
109 stdout = self._tempfile.read()
Craig Tiller71735182015-01-15 17:07:13 -0800110 message('FAILED', '%s [ret=%d]' % (
111 ' '.join(self._cmdline), self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -0800112 else:
113 self._state = _SUCCESS
Craig Tiller71735182015-01-15 17:07:13 -0800114 message('PASSED', '%s' % ' '.join(self._cmdline),
115 do_newline=self._newline_on_success)
116 update_cache.finished(self._cmdline, self._bin_hash)
ctiller3040cb72015-01-07 12:13:17 -0800117 return self._state
118
119 def kill(self):
120 if self._state == _RUNNING:
121 self._state = _KILLED
122 self._process.terminate()
123
124
Nicolas Nobleddef2462015-01-06 18:08:25 -0800125class Jobset(object):
126 """Manages one run of jobs."""
127
Craig Tiller71735182015-01-15 17:07:13 -0800128 def __init__(self, check_cancelled, maxjobs, newline_on_success, cache):
ctiller3040cb72015-01-07 12:13:17 -0800129 self._running = set()
130 self._check_cancelled = check_cancelled
131 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800132 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800133 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800134 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800135 self._newline_on_success = newline_on_success
Craig Tiller71735182015-01-15 17:07:13 -0800136 self._cache = cache
Nicolas Nobleddef2462015-01-06 18:08:25 -0800137
ctiller3040cb72015-01-07 12:13:17 -0800138 def start(self, cmdline):
139 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800140 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800141 if self.cancelled(): return False
142 self.reap()
143 if self.cancelled(): return False
Craig Tiller71735182015-01-15 17:07:13 -0800144 with open(which(cmdline[0])) as f:
145 bin_hash = hashlib.sha1(f.read()).hexdigest()
146 if self._cache.should_run(cmdline, bin_hash):
147 self._running.add(Job(cmdline, bin_hash, self._newline_on_success))
ctiller3040cb72015-01-07 12:13:17 -0800148 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800149
ctiller3040cb72015-01-07 12:13:17 -0800150 def reap(self):
151 """Collect the dead jobs."""
152 while self._running:
153 dead = set()
154 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800155 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800156 if st == _RUNNING: continue
157 if st == _FAILURE: self._failures += 1
158 dead.add(job)
159 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800160 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800161 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800162 if dead: return
Craig Tiller738c3342015-01-12 14:28:33 -0800163 message('WAITING', '%d jobs running, %d complete' % (
164 len(self._running), self._completed))
ctiller3040cb72015-01-07 12:13:17 -0800165 time.sleep(0.1)
166
167 def cancelled(self):
168 """Poll for cancellation."""
169 if self._cancelled: return True
170 if not self._check_cancelled(): return False
171 for job in self._running:
172 job.kill()
173 self._cancelled = True
174 return True
175
176 def finish(self):
177 while self._running:
178 if self.cancelled(): pass # poll cancellation
179 self.reap()
180 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800181
182
ctiller3040cb72015-01-07 12:13:17 -0800183def _never_cancelled():
184 return False
185
186
Craig Tiller71735182015-01-15 17:07:13 -0800187# cache class that caches nothing
188class NoCache(object):
189 def should_run(self, cmdline, bin_hash):
190 return True
191
192 def finished(self, cmdline, bin_hash):
193 pass
194
195
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800196def run(cmdlines,
197 check_cancelled=_never_cancelled,
198 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800199 newline_on_success=False,
200 cache=None):
ctiller94e5dde2015-01-09 10:41:59 -0800201 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800202 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tiller71735182015-01-15 17:07:13 -0800203 newline_on_success,
204 cache if cache is not None else NoCache())
ctiller3040cb72015-01-07 12:13:17 -0800205 for cmdline in shuffle_iteratable(cmdlines):
206 if not js.start(cmdline):
207 break
208 return js.finish()