blob: 0214e95ed363f5dde3ae40bd7c044035a5ecf114 [file] [log] [blame]
Nicolas Nobleddef2462015-01-06 18:08:25 -08001"""Run a group of subprocesses and then finish."""
2
3import multiprocessing
4import random
5import subprocess
6import sys
ctiller3040cb72015-01-07 12:13:17 -08007import tempfile
8import time
Nicolas Nobleddef2462015-01-06 18:08:25 -08009
ctiller3040cb72015-01-07 12:13:17 -080010
ctiller94e5dde2015-01-09 10:41:59 -080011_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Nicolas Nobleddef2462015-01-06 18:08:25 -080012
13
14def shuffle_iteratable(it):
15 """Return an iterable that randomly walks it"""
16 # take a random sampling from the passed in iterable
17 # we take an element with probablity 1/p and rapidly increase
18 # p as we take elements - this gives us a somewhat random set of values before
19 # we've seen all the values, but starts producing values without having to
20 # compute ALL of them at once, allowing tests to start a little earlier
21 nextit = []
22 p = 1
23 for val in it:
24 if random.randint(0, p) == 0:
ctiller3040cb72015-01-07 12:13:17 -080025 p = min(p*2, 100)
Nicolas Nobleddef2462015-01-06 18:08:25 -080026 yield val
27 else:
28 nextit.append(val)
29 # after taking a random sampling, we shuffle the rest of the elements and
30 # yield them
31 random.shuffle(nextit)
32 for val in nextit:
33 yield val
34
35
ctiller3040cb72015-01-07 12:13:17 -080036_SUCCESS = object()
37_FAILURE = object()
38_RUNNING = object()
39_KILLED = object()
40
41
Craig Tiller3b083062015-01-12 13:51:28 -080042_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080043 'red': [ 31, 0 ],
44 'green': [ 32, 0 ],
45 'yellow': [ 33, 0 ],
46 'lightgray': [ 37, 0],
47 'gray': [ 30, 1 ],
Craig Tiller3b083062015-01-12 13:51:28 -080048 }
49
50
51_BEGINNING_OF_LINE = '\x1b[0G'
52_CLEAR_LINE = '\x1b[2K'
53
54
55_TAG_COLOR = {
56 'FAILED': 'red',
57 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080058 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080059 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080060 'SUCCESS': 'green',
61 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080062 }
63
64
Nicolas Noble044db742015-01-14 16:57:24 -080065def message(tag, message, explanatory_text=None, do_newline=False):
66 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
Craig Tiller3b083062015-01-12 13:51:28 -080067 _BEGINNING_OF_LINE,
68 _CLEAR_LINE,
Nicolas Noble044db742015-01-14 16:57:24 -080069 '\n%s' % explanatory_text if explanatory_text is not None else '',
70 _COLORS[_TAG_COLOR[tag]][1],
71 _COLORS[_TAG_COLOR[tag]][0],
Craig Tiller3b083062015-01-12 13:51:28 -080072 tag,
73 message,
Nicolas Noble044db742015-01-14 16:57:24 -080074 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller3b083062015-01-12 13:51:28 -080075 sys.stdout.flush()
76
77
ctiller3040cb72015-01-07 12:13:17 -080078class Job(object):
79 """Manages one job."""
80
Nicolas Noble044db742015-01-14 16:57:24 -080081 def __init__(self, cmdline, newline_on_success):
ctiller3040cb72015-01-07 12:13:17 -080082 self._cmdline = ' '.join(cmdline)
83 self._tempfile = tempfile.TemporaryFile()
84 self._process = subprocess.Popen(args=cmdline,
85 stderr=subprocess.STDOUT,
86 stdout=self._tempfile)
87 self._state = _RUNNING
Nicolas Noble044db742015-01-14 16:57:24 -080088 self._newline_on_success = newline_on_success
Craig Tiller3b083062015-01-12 13:51:28 -080089 message('START', self._cmdline)
ctiller3040cb72015-01-07 12:13:17 -080090
91 def state(self):
92 """Poll current state of the job. Prints messages at completion."""
93 if self._state == _RUNNING and self._process.poll() is not None:
94 if self._process.returncode != 0:
95 self._state = _FAILURE
96 self._tempfile.seek(0)
97 stdout = self._tempfile.read()
Craig Tiller3b083062015-01-12 13:51:28 -080098 message('FAILED', '%s [ret=%d]' % (self._cmdline, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -080099 else:
100 self._state = _SUCCESS
Nicolas Noble044db742015-01-14 16:57:24 -0800101 message('PASSED', '%s' % self._cmdline, do_newline=self._newline_on_success)
ctiller3040cb72015-01-07 12:13:17 -0800102 return self._state
103
104 def kill(self):
105 if self._state == _RUNNING:
106 self._state = _KILLED
107 self._process.terminate()
108
109
Nicolas Nobleddef2462015-01-06 18:08:25 -0800110class Jobset(object):
111 """Manages one run of jobs."""
112
Nicolas Noble044db742015-01-14 16:57:24 -0800113 def __init__(self, check_cancelled, maxjobs, newline_on_success):
ctiller3040cb72015-01-07 12:13:17 -0800114 self._running = set()
115 self._check_cancelled = check_cancelled
116 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800117 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800118 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800119 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800120 self._newline_on_success = newline_on_success
Nicolas Nobleddef2462015-01-06 18:08:25 -0800121
ctiller3040cb72015-01-07 12:13:17 -0800122 def start(self, cmdline):
123 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800124 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800125 if self.cancelled(): return False
126 self.reap()
127 if self.cancelled(): return False
Nicolas Noble044db742015-01-14 16:57:24 -0800128 self._running.add(Job(cmdline, self._newline_on_success))
ctiller3040cb72015-01-07 12:13:17 -0800129 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800130
ctiller3040cb72015-01-07 12:13:17 -0800131 def reap(self):
132 """Collect the dead jobs."""
133 while self._running:
134 dead = set()
135 for job in self._running:
136 st = job.state()
137 if st == _RUNNING: continue
138 if st == _FAILURE: self._failures += 1
139 dead.add(job)
140 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800141 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800142 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800143 if dead: return
Craig Tiller738c3342015-01-12 14:28:33 -0800144 message('WAITING', '%d jobs running, %d complete' % (
145 len(self._running), self._completed))
ctiller3040cb72015-01-07 12:13:17 -0800146 time.sleep(0.1)
147
148 def cancelled(self):
149 """Poll for cancellation."""
150 if self._cancelled: return True
151 if not self._check_cancelled(): return False
152 for job in self._running:
153 job.kill()
154 self._cancelled = True
155 return True
156
157 def finish(self):
158 while self._running:
159 if self.cancelled(): pass # poll cancellation
160 self.reap()
161 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800162
163
ctiller3040cb72015-01-07 12:13:17 -0800164def _never_cancelled():
165 return False
166
167
Nicolas Noble044db742015-01-14 16:57:24 -0800168def run(cmdlines, check_cancelled=_never_cancelled, maxjobs=None, newline_on_success=False):
ctiller94e5dde2015-01-09 10:41:59 -0800169 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800170 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
171 newline_on_success)
ctiller3040cb72015-01-07 12:13:17 -0800172 for cmdline in shuffle_iteratable(cmdlines):
173 if not js.start(cmdline):
174 break
175 return js.finish()