blob: b7bcb7b02c11a031af7af22c2091eb382bd75988 [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
Craig Tiller738c3342015-01-12 14:28:33 -080011_MAX_JOBS = 3
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
Craig Tiller738c3342015-01-12 14:28:33 -0800111 self._completed = 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800112
ctiller3040cb72015-01-07 12:13:17 -0800113 def start(self, cmdline):
114 """Start a job. Return True on success, False on failure."""
115 while len(self._running) >= _MAX_JOBS:
116 if self.cancelled(): return False
117 self.reap()
118 if self.cancelled(): return False
119 self._running.add(Job(cmdline))
120 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800121
ctiller3040cb72015-01-07 12:13:17 -0800122 def reap(self):
123 """Collect the dead jobs."""
124 while self._running:
125 dead = set()
126 for job in self._running:
127 st = job.state()
128 if st == _RUNNING: continue
129 if st == _FAILURE: self._failures += 1
130 dead.add(job)
131 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800132 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800133 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800134 if dead: return
Craig Tiller738c3342015-01-12 14:28:33 -0800135 message('WAITING', '%d jobs running, %d complete' % (
136 len(self._running), self._completed))
ctiller3040cb72015-01-07 12:13:17 -0800137 time.sleep(0.1)
138
139 def cancelled(self):
140 """Poll for cancellation."""
141 if self._cancelled: return True
142 if not self._check_cancelled(): return False
143 for job in self._running:
144 job.kill()
145 self._cancelled = True
146 return True
147
148 def finish(self):
149 while self._running:
150 if self.cancelled(): pass # poll cancellation
151 self.reap()
152 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800153
154
ctiller3040cb72015-01-07 12:13:17 -0800155def _never_cancelled():
156 return False
157
158
159def run(cmdlines, check_cancelled=_never_cancelled):
160 js = Jobset(check_cancelled)
161 for cmdline in shuffle_iteratable(cmdlines):
162 if not js.start(cmdline):
163 break
164 return js.finish()
Nicolas Nobleddef2462015-01-06 18:08:25 -0800165