blob: 7e1ec366f96edea0f6c2cb1dc13cf387db5de576 [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
11_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 = {
43 'red': 31,
44 'green': 32,
45 'yellow': 33,
46 }
47
48
49_BEGINNING_OF_LINE = '\x1b[0G'
50_CLEAR_LINE = '\x1b[2K'
51
52
53_TAG_COLOR = {
54 'FAILED': 'red',
55 'PASSED': 'green',
56 'START': 'yellow',
57 'WAITING': 'yellow',
58 }
59
60
61def message(tag, message, explanatory_text=None):
62 sys.stdout.write('%s%s\x1b[%dm%s\x1b[0m: %s%s' % (
63 _BEGINNING_OF_LINE,
64 _CLEAR_LINE,
65 _COLORS[_TAG_COLOR[tag]],
66 tag,
67 message,
68 '\n%s\n' % explanatory_text if explanatory_text is not None else ''))
69 sys.stdout.flush()
70
71
ctiller3040cb72015-01-07 12:13:17 -080072class Job(object):
73 """Manages one job."""
74
75 def __init__(self, cmdline):
76 self._cmdline = ' '.join(cmdline)
77 self._tempfile = tempfile.TemporaryFile()
78 self._process = subprocess.Popen(args=cmdline,
79 stderr=subprocess.STDOUT,
80 stdout=self._tempfile)
81 self._state = _RUNNING
Craig Tiller3b083062015-01-12 13:51:28 -080082 message('START', self._cmdline)
ctiller3040cb72015-01-07 12:13:17 -080083
84 def state(self):
85 """Poll current state of the job. Prints messages at completion."""
86 if self._state == _RUNNING and self._process.poll() is not None:
87 if self._process.returncode != 0:
88 self._state = _FAILURE
89 self._tempfile.seek(0)
90 stdout = self._tempfile.read()
Craig Tiller3b083062015-01-12 13:51:28 -080091 message('FAILED', '%s [ret=%d]' % (self._cmdline, self._process.returncode), stdout)
ctiller3040cb72015-01-07 12:13:17 -080092 else:
93 self._state = _SUCCESS
Craig Tiller3b083062015-01-12 13:51:28 -080094 message('PASSED', '%s' % self._cmdline)
ctiller3040cb72015-01-07 12:13:17 -080095 return self._state
96
97 def kill(self):
98 if self._state == _RUNNING:
99 self._state = _KILLED
100 self._process.terminate()
101
102
Nicolas Nobleddef2462015-01-06 18:08:25 -0800103class Jobset(object):
104 """Manages one run of jobs."""
105
ctiller3040cb72015-01-07 12:13:17 -0800106 def __init__(self, check_cancelled):
107 self._running = set()
108 self._check_cancelled = check_cancelled
109 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800110 self._failures = 0
111
ctiller3040cb72015-01-07 12:13:17 -0800112 def start(self, cmdline):
113 """Start a job. Return True on success, False on failure."""
114 while len(self._running) >= _MAX_JOBS:
115 if self.cancelled(): return False
116 self.reap()
117 if self.cancelled(): return False
118 self._running.add(Job(cmdline))
119 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800120
ctiller3040cb72015-01-07 12:13:17 -0800121 def reap(self):
122 """Collect the dead jobs."""
123 while self._running:
124 dead = set()
125 for job in self._running:
126 st = job.state()
127 if st == _RUNNING: continue
128 if st == _FAILURE: self._failures += 1
129 dead.add(job)
130 for job in dead:
131 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800132 if dead: return
133 message('WAITING', '%d jobs left' % len(self._running))
ctiller3040cb72015-01-07 12:13:17 -0800134 time.sleep(0.1)
135
136 def cancelled(self):
137 """Poll for cancellation."""
138 if self._cancelled: return True
139 if not self._check_cancelled(): return False
140 for job in self._running:
141 job.kill()
142 self._cancelled = True
143 return True
144
145 def finish(self):
146 while self._running:
147 if self.cancelled(): pass # poll cancellation
148 self.reap()
149 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800150
151
ctiller3040cb72015-01-07 12:13:17 -0800152def _never_cancelled():
153 return False
154
155
156def run(cmdlines, check_cancelled=_never_cancelled):
157 js = Jobset(check_cancelled)
158 for cmdline in shuffle_iteratable(cmdlines):
159 if not js.start(cmdline):
160 break
161 return js.finish()
Nicolas Nobleddef2462015-01-06 18:08:25 -0800162