blob: b6fb6318e007e156e30ac2e9c3b6929abc947b20 [file] [log] [blame]
Craig Tiller6169d5f2016-03-31 07:46:18 -07001# Copyright 2015, Google Inc.
Craig Tillerc2c79212015-02-16 12:00:01 -08002# 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
siddharthshukla0589e532016-07-07 16:08:01 +020032from __future__ import print_function
33
Nicolas Nobleddef2462015-01-06 18:08:25 -080034import multiprocessing
Craig Tiller71735182015-01-15 17:07:13 -080035import os
Craig Tiller5058c692015-04-08 09:42:04 -070036import platform
Craig Tiller5f735a62016-01-20 09:31:15 -080037import re
Craig Tiller336ad502015-02-24 14:46:02 -080038import signal
Nicolas Nobleddef2462015-01-06 18:08:25 -080039import subprocess
40import sys
ctiller3040cb72015-01-07 12:13:17 -080041import tempfile
42import time
Nicolas Nobleddef2462015-01-06 18:08:25 -080043
ctiller3040cb72015-01-07 12:13:17 -080044
Craig Tiller5f735a62016-01-20 09:31:15 -080045# cpu cost measurement
46measure_cpu_costs = False
47
48
ctiller94e5dde2015-01-09 10:41:59 -080049_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Adele Zhoud01cbe32015-11-02 14:20:43 -080050_MAX_RESULT_SIZE = 8192
Nicolas Nobleddef2462015-01-06 18:08:25 -080051
Masood Malekghassemi768b1db2016-06-06 16:45:19 -070052def sanitized_environment(env):
53 sanitized = {}
54 for key, value in env.items():
55 sanitized[str(key).encode()] = str(value).encode()
56 return sanitized
57
Nicolas "Pixel" Noblef72d7b52015-12-03 03:07:43 +010058def platform_string():
59 if platform.system() == 'Windows':
60 return 'windows'
61 elif platform.system()[:7] == 'MSYS_NT':
62 return 'windows'
63 elif platform.system() == 'Darwin':
64 return 'mac'
65 elif platform.system() == 'Linux':
66 return 'linux'
67 else:
68 return 'posix'
69
Nicolas Nobleddef2462015-01-06 18:08:25 -080070
Craig Tiller336ad502015-02-24 14:46:02 -080071# setup a signal handler so that signal.pause registers 'something'
72# when a child finishes
73# not using futures and threading to avoid a dependency on subprocess32
Nicolas "Pixel" Noblef72d7b52015-12-03 03:07:43 +010074if platform_string() == 'windows':
Craig Tiller5058c692015-04-08 09:42:04 -070075 pass
76else:
77 have_alarm = False
78 def alarm_handler(unused_signum, unused_frame):
79 global have_alarm
80 have_alarm = False
81
82 signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None)
83 signal.signal(signal.SIGALRM, alarm_handler)
Craig Tiller336ad502015-02-24 14:46:02 -080084
85
ctiller3040cb72015-01-07 12:13:17 -080086_SUCCESS = object()
87_FAILURE = object()
88_RUNNING = object()
89_KILLED = object()
90
91
Craig Tiller3b083062015-01-12 13:51:28 -080092_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080093 'red': [ 31, 0 ],
94 'green': [ 32, 0 ],
95 'yellow': [ 33, 0 ],
96 'lightgray': [ 37, 0],
97 'gray': [ 30, 1 ],
Craig Tillerd7e09c32015-09-25 11:33:39 -070098 'purple': [ 35, 0 ],
Craig Tiller3b083062015-01-12 13:51:28 -080099 }
100
101
102_BEGINNING_OF_LINE = '\x1b[0G'
103_CLEAR_LINE = '\x1b[2K'
104
105
106_TAG_COLOR = {
107 'FAILED': 'red',
Craig Tillerd7e09c32015-09-25 11:33:39 -0700108 'FLAKE': 'purple',
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700109 'TIMEOUT_FLAKE': 'purple',
Masood Malekghassemie5f70022015-06-29 09:20:26 -0700110 'WARNING': 'yellow',
Craig Tillere1d0d1c2015-02-27 08:54:23 -0800111 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -0800112 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -0800113 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800114 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -0800115 'SUCCESS': 'green',
116 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800117 }
118
119
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200120def message(tag, msg, explanatory_text=None, do_newline=False):
121 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
122 return
123 message.old_tag = tag
124 message.old_msg = msg
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800125 try:
Nicolas "Pixel" Noblef72d7b52015-12-03 03:07:43 +0100126 if platform_string() == 'windows' or not sys.stdout.isatty():
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700127 if explanatory_text:
siddharthshukla0589e532016-07-07 16:08:01 +0200128 print(explanatory_text)
129 print('%s: %s' % (tag, msg))
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700130 return
vjpaia29d2d72015-07-08 10:31:15 -0700131 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
132 _BEGINNING_OF_LINE,
133 _CLEAR_LINE,
134 '\n%s' % explanatory_text if explanatory_text is not None else '',
135 _COLORS[_TAG_COLOR[tag]][1],
136 _COLORS[_TAG_COLOR[tag]][0],
137 tag,
138 msg,
139 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800140 sys.stdout.flush()
141 except:
142 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800143
Adele Zhoue4c35612015-10-16 15:34:23 -0700144message.old_tag = ''
145message.old_msg = ''
Craig Tiller3b083062015-01-12 13:51:28 -0800146
Craig Tiller71735182015-01-15 17:07:13 -0800147def which(filename):
148 if '/' in filename:
149 return filename
150 for path in os.environ['PATH'].split(os.pathsep):
151 if os.path.exists(os.path.join(path, filename)):
152 return os.path.join(path, filename)
153 raise Exception('%s not found' % filename)
154
155
Craig Tiller547db2b2015-01-30 14:08:39 -0800156class JobSpec(object):
157 """Specifies what to run for a job."""
158
Craig Tiller74189cd2016-06-23 15:39:06 -0700159 def __init__(self, cmdline, shortname=None, environ=None,
Craig Tiller95cc07b2015-09-28 13:41:30 -0700160 cwd=None, shell=False, timeout_seconds=5*60, flake_retries=0,
Jan Tattermuschb2758442016-03-28 09:32:20 -0700161 timeout_retries=0, kill_handler=None, cpu_cost=1.0,
162 verbose_success=False):
Craig Tiller547db2b2015-01-30 14:08:39 -0800163 """
164 Arguments:
165 cmdline: a list of arguments to pass as the command line
166 environ: a dictionary of environment variables to set in the child process
Jan Tattermusche2686282015-10-08 16:27:07 -0700167 kill_handler: a handler that will be called whenever job.kill() is invoked
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800168 cpu_cost: number of cores per second this job needs
Craig Tiller547db2b2015-01-30 14:08:39 -0800169 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800170 if environ is None:
171 environ = {}
Craig Tiller547db2b2015-01-30 14:08:39 -0800172 self.cmdline = cmdline
173 self.environ = environ
174 self.shortname = cmdline[0] if shortname is None else shortname
Craig Tiller5058c692015-04-08 09:42:04 -0700175 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700176 self.shell = shell
Jan Tattermusch725835a2015-08-01 21:02:35 -0700177 self.timeout_seconds = timeout_seconds
Craig Tiller91318bc2015-09-24 08:58:39 -0700178 self.flake_retries = flake_retries
Craig Tillerbfc8a062015-09-28 14:40:21 -0700179 self.timeout_retries = timeout_retries
Jan Tattermusche2686282015-10-08 16:27:07 -0700180 self.kill_handler = kill_handler
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800181 self.cpu_cost = cpu_cost
Jan Tattermuschb2758442016-03-28 09:32:20 -0700182 self.verbose_success = verbose_success
Craig Tiller547db2b2015-01-30 14:08:39 -0800183
184 def identity(self):
Craig Tiller74189cd2016-06-23 15:39:06 -0700185 return '%r %r' % (self.cmdline, self.environ)
Craig Tiller547db2b2015-01-30 14:08:39 -0800186
187 def __hash__(self):
188 return hash(self.identity())
189
190 def __cmp__(self, other):
191 return self.identity() == other.identity()
Craig Tillerdb218992016-01-05 09:28:46 -0800192
Jan Tattermusch2dd156e2015-12-04 18:26:17 -0800193 def __repr__(self):
194 return 'JobSpec(shortname=%s, cmdline=%s)' % (self.shortname, self.cmdline)
Craig Tiller547db2b2015-01-30 14:08:39 -0800195
196
Adele Zhoue4c35612015-10-16 15:34:23 -0700197class JobResult(object):
198 def __init__(self):
199 self.state = 'UNKNOWN'
200 self.returncode = -1
201 self.elapsed_time = 0
Adele Zhoud5fffa52015-10-23 15:51:42 -0700202 self.num_failures = 0
Adele Zhoue4c35612015-10-16 15:34:23 -0700203 self.retries = 0
204 self.message = ''
Craig Tillerdb218992016-01-05 09:28:46 -0800205
Adele Zhoue4c35612015-10-16 15:34:23 -0700206
ctiller3040cb72015-01-07 12:13:17 -0800207class Job(object):
208 """Manages one job."""
209
Craig Tiller74189cd2016-06-23 15:39:06 -0700210 def __init__(self, spec, newline_on_success, travis, add_env):
Craig Tiller547db2b2015-01-30 14:08:39 -0800211 self._spec = spec
Nicolas Noble044db742015-01-14 16:57:24 -0800212 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100213 self._travis = travis
Craig Tiller91318bc2015-09-24 08:58:39 -0700214 self._add_env = add_env.copy()
Craig Tiller91318bc2015-09-24 08:58:39 -0700215 self._retries = 0
Craig Tiller95cc07b2015-09-28 13:41:30 -0700216 self._timeout_retries = 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700217 self._suppress_failure_message = False
Craig Tillerb84728d2015-02-26 15:40:39 -0800218 message('START', spec.shortname, do_newline=self._travis)
Adele Zhoue4c35612015-10-16 15:34:23 -0700219 self.result = JobResult()
Craig Tiller91318bc2015-09-24 08:58:39 -0700220 self.start()
221
Adele Zhoue4c35612015-10-16 15:34:23 -0700222 def GetSpec(self):
223 return self._spec
224
Craig Tiller91318bc2015-09-24 08:58:39 -0700225 def start(self):
226 self._tempfile = tempfile.TemporaryFile()
227 env = dict(os.environ)
228 env.update(self._spec.environ)
229 env.update(self._add_env)
Masood Malekghassemi768b1db2016-06-06 16:45:19 -0700230 env = sanitized_environment(env)
Craig Tiller91318bc2015-09-24 08:58:39 -0700231 self._start = time.time()
Craig Tiller5f735a62016-01-20 09:31:15 -0800232 cmdline = self._spec.cmdline
233 if measure_cpu_costs:
234 cmdline = ['time', '--portability'] + cmdline
235 try_start = lambda: subprocess.Popen(args=cmdline,
Craig Tiller60078bb2015-11-04 16:39:54 -0800236 stderr=subprocess.STDOUT,
237 stdout=self._tempfile,
238 cwd=self._spec.cwd,
239 shell=self._spec.shell,
240 env=env)
241 delay = 0.3
242 for i in range(0, 4):
243 try:
244 self._process = try_start()
245 break
246 except OSError:
247 message('WARNING', 'Failed to start %s, retrying in %f seconds' % (self._spec.shortname, delay))
248 time.sleep(delay)
249 delay *= 2
250 else:
251 self._process = try_start()
Craig Tiller91318bc2015-09-24 08:58:39 -0700252 self._state = _RUNNING
ctiller3040cb72015-01-07 12:13:17 -0800253
Craig Tiller74189cd2016-06-23 15:39:06 -0700254 def state(self):
ctiller3040cb72015-01-07 12:13:17 -0800255 """Poll current state of the job. Prints messages at completion."""
Craig Tillerdb218992016-01-05 09:28:46 -0800256 def stdout(self=self):
257 self._tempfile.seek(0)
258 stdout = self._tempfile.read()
259 self.result.message = stdout[-_MAX_RESULT_SIZE:]
260 return stdout
ctiller3040cb72015-01-07 12:13:17 -0800261 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800262 elapsed = time.time() - self._start
Adele Zhoue4c35612015-10-16 15:34:23 -0700263 self.result.elapsed_time = elapsed
ctiller3040cb72015-01-07 12:13:17 -0800264 if self._process.returncode != 0:
Craig Tiller91318bc2015-09-24 08:58:39 -0700265 if self._retries < self._spec.flake_retries:
266 message('FLAKE', '%s [ret=%d, pid=%d]' % (
Craig Tillerd0ffe142015-05-19 21:51:13 -0700267 self._spec.shortname, self._process.returncode, self._process.pid),
Craig Tillerdb218992016-01-05 09:28:46 -0800268 stdout(), do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700269 self._retries += 1
Adele Zhoud5fffa52015-10-23 15:51:42 -0700270 self.result.num_failures += 1
Adele Zhoue4c35612015-10-16 15:34:23 -0700271 self.result.retries = self._timeout_retries + self._retries
Craig Tiller91318bc2015-09-24 08:58:39 -0700272 self.start()
273 else:
274 self._state = _FAILURE
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700275 if not self._suppress_failure_message:
276 message('FAILED', '%s [ret=%d, pid=%d]' % (
277 self._spec.shortname, self._process.returncode, self._process.pid),
Craig Tillerdb218992016-01-05 09:28:46 -0800278 stdout(), do_newline=True)
Adele Zhoue4c35612015-10-16 15:34:23 -0700279 self.result.state = 'FAILED'
Adele Zhoud5fffa52015-10-23 15:51:42 -0700280 self.result.num_failures += 1
Adele Zhoue4c35612015-10-16 15:34:23 -0700281 self.result.returncode = self._process.returncode
ctiller3040cb72015-01-07 12:13:17 -0800282 else:
283 self._state = _SUCCESS
Craig Tiller5f735a62016-01-20 09:31:15 -0800284 measurement = ''
285 if measure_cpu_costs:
286 m = re.search(r'real ([0-9.]+)\nuser ([0-9.]+)\nsys ([0-9.]+)', stdout())
287 real = float(m.group(1))
288 user = float(m.group(2))
289 sys = float(m.group(3))
290 if real > 0.5:
291 cores = (user + sys) / real
Craig Tillerbfe69362016-01-20 09:38:21 -0800292 measurement = '; cpu_cost=%.01f; estimated=%.01f' % (cores, self._spec.cpu_cost)
Craig Tiller5f735a62016-01-20 09:31:15 -0800293 message('PASSED', '%s [time=%.1fsec; retries=%d:%d%s]' % (
Jan Tattermuschb2758442016-03-28 09:32:20 -0700294 self._spec.shortname, elapsed, self._retries, self._timeout_retries, measurement),
295 stdout() if self._spec.verbose_success else None,
Craig Tiller95cc07b2015-09-28 13:41:30 -0700296 do_newline=self._newline_on_success or self._travis)
Adele Zhoue4c35612015-10-16 15:34:23 -0700297 self.result.state = 'PASSED'
Craig Tiller5f735a62016-01-20 09:31:15 -0800298 elif (self._state == _RUNNING and
299 self._spec.timeout_seconds is not None and
Craig Tiller590105a2016-01-19 13:03:46 -0800300 time.time() - self._start > self._spec.timeout_seconds):
Craig Tiller95cc07b2015-09-28 13:41:30 -0700301 if self._timeout_retries < self._spec.timeout_retries:
Craig Tillerdb218992016-01-05 09:28:46 -0800302 message('TIMEOUT_FLAKE', '%s [pid=%d]' % (self._spec.shortname, self._process.pid), stdout(), do_newline=True)
Craig Tiller95cc07b2015-09-28 13:41:30 -0700303 self._timeout_retries += 1
Adele Zhoud5fffa52015-10-23 15:51:42 -0700304 self.result.num_failures += 1
Adele Zhoue4c35612015-10-16 15:34:23 -0700305 self.result.retries = self._timeout_retries + self._retries
Jan Tattermusch39e3cb32015-10-22 18:21:08 -0700306 if self._spec.kill_handler:
307 self._spec.kill_handler(self)
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700308 self._process.terminate()
309 self.start()
310 else:
Craig Tillerdb218992016-01-05 09:28:46 -0800311 message('TIMEOUT', '%s [pid=%d]' % (self._spec.shortname, self._process.pid), stdout(), do_newline=True)
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700312 self.kill()
Adele Zhoue4c35612015-10-16 15:34:23 -0700313 self.result.state = 'TIMEOUT'
Adele Zhoud5fffa52015-10-23 15:51:42 -0700314 self.result.num_failures += 1
ctiller3040cb72015-01-07 12:13:17 -0800315 return self._state
316
317 def kill(self):
318 if self._state == _RUNNING:
319 self._state = _KILLED
Jan Tattermusche2686282015-10-08 16:27:07 -0700320 if self._spec.kill_handler:
321 self._spec.kill_handler(self)
ctiller3040cb72015-01-07 12:13:17 -0800322 self._process.terminate()
323
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700324 def suppress_failure_message(self):
325 self._suppress_failure_message = True
Craig Tillerdb218992016-01-05 09:28:46 -0800326
ctiller3040cb72015-01-07 12:13:17 -0800327
Nicolas Nobleddef2462015-01-06 18:08:25 -0800328class Jobset(object):
329 """Manages one run of jobs."""
330
Craig Tiller533b1a22015-05-29 08:41:29 -0700331 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Craig Tiller74189cd2016-06-23 15:39:06 -0700332 stop_on_failure, add_env):
ctiller3040cb72015-01-07 12:13:17 -0800333 self._running = set()
334 self._check_cancelled = check_cancelled
335 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800336 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800337 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800338 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800339 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100340 self._travis = travis
Craig Tiller533b1a22015-05-29 08:41:29 -0700341 self._stop_on_failure = stop_on_failure
Craig Tillerf53d9c82015-08-04 14:19:43 -0700342 self._add_env = add_env
Adele Zhoue4c35612015-10-16 15:34:23 -0700343 self.resultset = {}
Craig Tiller6364dcb2015-11-24 16:29:06 -0800344 self._remaining = None
Craig Tillered735102016-04-06 12:59:23 -0700345 self._start_time = time.time()
Craig Tiller6364dcb2015-11-24 16:29:06 -0800346
347 def set_remaining(self, remaining):
348 self._remaining = remaining
349
Adele Zhoue4c35612015-10-16 15:34:23 -0700350 def get_num_failures(self):
Craig Tiller6364dcb2015-11-24 16:29:06 -0800351 return self._failures
Nicolas Nobleddef2462015-01-06 18:08:25 -0800352
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800353 def cpu_cost(self):
354 c = 0
355 for job in self._running:
356 c += job._spec.cpu_cost
357 return c
358
Craig Tiller547db2b2015-01-30 14:08:39 -0800359 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800360 """Start a job. Return True on success, False on failure."""
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800361 while True:
ctiller3040cb72015-01-07 12:13:17 -0800362 if self.cancelled(): return False
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800363 current_cpu_cost = self.cpu_cost()
364 if current_cpu_cost == 0: break
Craig Tiller3e301a32016-01-27 15:36:52 -0800365 if current_cpu_cost + spec.cpu_cost <= self._maxjobs: break
ctiller3040cb72015-01-07 12:13:17 -0800366 self.reap()
367 if self.cancelled(): return False
Craig Tiller74189cd2016-06-23 15:39:06 -0700368 job = Job(spec,
369 self._newline_on_success,
370 self._travis,
371 self._add_env)
372 self._running.add(job)
siddharthshukla0589e532016-07-07 16:08:01 +0200373 if job.GetSpec().shortname not in self.resultset:
Craig Tiller74189cd2016-06-23 15:39:06 -0700374 self.resultset[job.GetSpec().shortname] = []
Craig Tillerddf02c12016-06-24 14:04:01 -0700375 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800376
ctiller3040cb72015-01-07 12:13:17 -0800377 def reap(self):
378 """Collect the dead jobs."""
379 while self._running:
380 dead = set()
381 for job in self._running:
Craig Tiller74189cd2016-06-23 15:39:06 -0700382 st = job.state()
ctiller3040cb72015-01-07 12:13:17 -0800383 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700384 if st == _FAILURE or st == _KILLED:
385 self._failures += 1
386 if self._stop_on_failure:
387 self._cancelled = True
388 for job in self._running:
389 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800390 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700391 break
ctiller3040cb72015-01-07 12:13:17 -0800392 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800393 self._completed += 1
Adele Zhoud5fffa52015-10-23 15:51:42 -0700394 self.resultset[job.GetSpec().shortname].append(job.result)
ctiller3040cb72015-01-07 12:13:17 -0800395 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800396 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100397 if (not self._travis):
Craig Tiller2c23ad52015-12-04 06:50:38 -0800398 rstr = '' if self._remaining is None else '%d queued, ' % self._remaining
Craig Tillered735102016-04-06 12:59:23 -0700399 if self._remaining is not None and self._completed > 0:
400 now = time.time()
401 sofar = now - self._start_time
402 remaining = sofar / self._completed * (self._remaining + len(self._running))
403 rstr = 'ETA %.1f sec; %s' % (remaining, rstr)
Craig Tiller2c23ad52015-12-04 06:50:38 -0800404 message('WAITING', '%s%d jobs running, %d complete, %d failed' % (
405 rstr, len(self._running), self._completed, self._failures))
Nicolas "Pixel" Noblef72d7b52015-12-03 03:07:43 +0100406 if platform_string() == 'windows':
Craig Tiller5058c692015-04-08 09:42:04 -0700407 time.sleep(0.1)
408 else:
409 global have_alarm
410 if not have_alarm:
411 have_alarm = True
412 signal.alarm(10)
413 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800414
415 def cancelled(self):
416 """Poll for cancellation."""
417 if self._cancelled: return True
418 if not self._check_cancelled(): return False
419 for job in self._running:
420 job.kill()
421 self._cancelled = True
422 return True
423
424 def finish(self):
425 while self._running:
426 if self.cancelled(): pass # poll cancellation
427 self.reap()
428 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800429
430
ctiller3040cb72015-01-07 12:13:17 -0800431def _never_cancelled():
432 return False
433
434
Craig Tiller6364dcb2015-11-24 16:29:06 -0800435def tag_remaining(xs):
436 staging = []
437 for x in xs:
438 staging.append(x)
Craig Tillered735102016-04-06 12:59:23 -0700439 if len(staging) > 5000:
Craig Tiller6364dcb2015-11-24 16:29:06 -0800440 yield (staging.pop(0), None)
441 n = len(staging)
442 for i, x in enumerate(staging):
443 yield (x, n - i - 1)
444
445
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800446def run(cmdlines,
447 check_cancelled=_never_cancelled,
448 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800449 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100450 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700451 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700452 stop_on_failure=False,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700453 add_env={}):
ctiller94e5dde2015-01-09 10:41:59 -0800454 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800455 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tiller74189cd2016-06-23 15:39:06 -0700456 newline_on_success, travis, stop_on_failure, add_env)
Craig Tiller6364dcb2015-11-24 16:29:06 -0800457 for cmdline, remaining in tag_remaining(cmdlines):
ctiller3040cb72015-01-07 12:13:17 -0800458 if not js.start(cmdline):
459 break
Craig Tiller6364dcb2015-11-24 16:29:06 -0800460 if remaining is not None:
461 js.set_remaining(remaining)
462 js.finish()
Adele Zhoue4c35612015-10-16 15:34:23 -0700463 return js.get_num_failures(), js.resultset