blob: b84eb3b5d7e50263bb0cbcdeb9518eb9d7ade827 [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 ],
Matt Kwong5c691c62016-10-20 17:11:18 -070099 'cyan': [ 36, 0 ]
Craig Tiller3b083062015-01-12 13:51:28 -0800100 }
101
102
103_BEGINNING_OF_LINE = '\x1b[0G'
104_CLEAR_LINE = '\x1b[2K'
105
106
107_TAG_COLOR = {
108 'FAILED': 'red',
Craig Tillerd7e09c32015-09-25 11:33:39 -0700109 'FLAKE': 'purple',
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700110 'TIMEOUT_FLAKE': 'purple',
Masood Malekghassemie5f70022015-06-29 09:20:26 -0700111 'WARNING': 'yellow',
Craig Tillere1d0d1c2015-02-27 08:54:23 -0800112 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -0800113 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -0800114 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -0800115 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -0800116 'SUCCESS': 'green',
117 'IDLE': 'gray',
Matt Kwong5c691c62016-10-20 17:11:18 -0700118 'SKIPPED': 'cyan'
Craig Tiller3b083062015-01-12 13:51:28 -0800119 }
120
121
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200122def message(tag, msg, explanatory_text=None, do_newline=False):
123 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
124 return
125 message.old_tag = tag
126 message.old_msg = msg
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800127 try:
Nicolas "Pixel" Noblef72d7b52015-12-03 03:07:43 +0100128 if platform_string() == 'windows' or not sys.stdout.isatty():
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700129 if explanatory_text:
siddharthshukla0589e532016-07-07 16:08:01 +0200130 print(explanatory_text)
131 print('%s: %s' % (tag, msg))
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700132 return
vjpaia29d2d72015-07-08 10:31:15 -0700133 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
134 _BEGINNING_OF_LINE,
135 _CLEAR_LINE,
136 '\n%s' % explanatory_text if explanatory_text is not None else '',
137 _COLORS[_TAG_COLOR[tag]][1],
138 _COLORS[_TAG_COLOR[tag]][0],
139 tag,
140 msg,
141 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800142 sys.stdout.flush()
143 except:
144 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800145
Adele Zhoue4c35612015-10-16 15:34:23 -0700146message.old_tag = ''
147message.old_msg = ''
Craig Tiller3b083062015-01-12 13:51:28 -0800148
Craig Tiller71735182015-01-15 17:07:13 -0800149def which(filename):
150 if '/' in filename:
151 return filename
152 for path in os.environ['PATH'].split(os.pathsep):
153 if os.path.exists(os.path.join(path, filename)):
154 return os.path.join(path, filename)
155 raise Exception('%s not found' % filename)
156
157
Craig Tiller547db2b2015-01-30 14:08:39 -0800158class JobSpec(object):
159 """Specifies what to run for a job."""
160
Craig Tiller74189cd2016-06-23 15:39:06 -0700161 def __init__(self, cmdline, shortname=None, environ=None,
Craig Tiller95cc07b2015-09-28 13:41:30 -0700162 cwd=None, shell=False, timeout_seconds=5*60, flake_retries=0,
Jan Tattermuschb2758442016-03-28 09:32:20 -0700163 timeout_retries=0, kill_handler=None, cpu_cost=1.0,
164 verbose_success=False):
Craig Tiller547db2b2015-01-30 14:08:39 -0800165 """
166 Arguments:
167 cmdline: a list of arguments to pass as the command line
168 environ: a dictionary of environment variables to set in the child process
Jan Tattermusche2686282015-10-08 16:27:07 -0700169 kill_handler: a handler that will be called whenever job.kill() is invoked
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800170 cpu_cost: number of cores per second this job needs
Craig Tiller547db2b2015-01-30 14:08:39 -0800171 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800172 if environ is None:
173 environ = {}
Craig Tiller547db2b2015-01-30 14:08:39 -0800174 self.cmdline = cmdline
175 self.environ = environ
176 self.shortname = cmdline[0] if shortname is None else shortname
Craig Tiller5058c692015-04-08 09:42:04 -0700177 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700178 self.shell = shell
Jan Tattermusch725835a2015-08-01 21:02:35 -0700179 self.timeout_seconds = timeout_seconds
Craig Tiller91318bc2015-09-24 08:58:39 -0700180 self.flake_retries = flake_retries
Craig Tillerbfc8a062015-09-28 14:40:21 -0700181 self.timeout_retries = timeout_retries
Jan Tattermusche2686282015-10-08 16:27:07 -0700182 self.kill_handler = kill_handler
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800183 self.cpu_cost = cpu_cost
Jan Tattermuschb2758442016-03-28 09:32:20 -0700184 self.verbose_success = verbose_success
Craig Tiller547db2b2015-01-30 14:08:39 -0800185
186 def identity(self):
Craig Tiller74189cd2016-06-23 15:39:06 -0700187 return '%r %r' % (self.cmdline, self.environ)
Craig Tiller547db2b2015-01-30 14:08:39 -0800188
189 def __hash__(self):
190 return hash(self.identity())
191
192 def __cmp__(self, other):
193 return self.identity() == other.identity()
Craig Tillerdb218992016-01-05 09:28:46 -0800194
Jan Tattermusch2dd156e2015-12-04 18:26:17 -0800195 def __repr__(self):
196 return 'JobSpec(shortname=%s, cmdline=%s)' % (self.shortname, self.cmdline)
Craig Tiller547db2b2015-01-30 14:08:39 -0800197
198
Adele Zhoue4c35612015-10-16 15:34:23 -0700199class JobResult(object):
200 def __init__(self):
201 self.state = 'UNKNOWN'
202 self.returncode = -1
203 self.elapsed_time = 0
Adele Zhoud5fffa52015-10-23 15:51:42 -0700204 self.num_failures = 0
Adele Zhoue4c35612015-10-16 15:34:23 -0700205 self.retries = 0
206 self.message = ''
Craig Tillerdb218992016-01-05 09:28:46 -0800207
Adele Zhoue4c35612015-10-16 15:34:23 -0700208
ctiller3040cb72015-01-07 12:13:17 -0800209class Job(object):
210 """Manages one job."""
211
Craig Tiller74189cd2016-06-23 15:39:06 -0700212 def __init__(self, spec, newline_on_success, travis, add_env):
Craig Tiller547db2b2015-01-30 14:08:39 -0800213 self._spec = spec
Nicolas Noble044db742015-01-14 16:57:24 -0800214 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100215 self._travis = travis
Craig Tiller91318bc2015-09-24 08:58:39 -0700216 self._add_env = add_env.copy()
Craig Tiller91318bc2015-09-24 08:58:39 -0700217 self._retries = 0
Craig Tiller95cc07b2015-09-28 13:41:30 -0700218 self._timeout_retries = 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700219 self._suppress_failure_message = False
Craig Tillerb84728d2015-02-26 15:40:39 -0800220 message('START', spec.shortname, do_newline=self._travis)
Adele Zhoue4c35612015-10-16 15:34:23 -0700221 self.result = JobResult()
Craig Tiller91318bc2015-09-24 08:58:39 -0700222 self.start()
223
Adele Zhoue4c35612015-10-16 15:34:23 -0700224 def GetSpec(self):
225 return self._spec
226
Craig Tiller91318bc2015-09-24 08:58:39 -0700227 def start(self):
228 self._tempfile = tempfile.TemporaryFile()
229 env = dict(os.environ)
230 env.update(self._spec.environ)
231 env.update(self._add_env)
Masood Malekghassemi768b1db2016-06-06 16:45:19 -0700232 env = sanitized_environment(env)
Craig Tiller91318bc2015-09-24 08:58:39 -0700233 self._start = time.time()
Craig Tiller5f735a62016-01-20 09:31:15 -0800234 cmdline = self._spec.cmdline
235 if measure_cpu_costs:
236 cmdline = ['time', '--portability'] + cmdline
237 try_start = lambda: subprocess.Popen(args=cmdline,
Craig Tiller60078bb2015-11-04 16:39:54 -0800238 stderr=subprocess.STDOUT,
239 stdout=self._tempfile,
240 cwd=self._spec.cwd,
241 shell=self._spec.shell,
242 env=env)
243 delay = 0.3
244 for i in range(0, 4):
245 try:
246 self._process = try_start()
247 break
248 except OSError:
249 message('WARNING', 'Failed to start %s, retrying in %f seconds' % (self._spec.shortname, delay))
250 time.sleep(delay)
251 delay *= 2
252 else:
253 self._process = try_start()
Craig Tiller91318bc2015-09-24 08:58:39 -0700254 self._state = _RUNNING
ctiller3040cb72015-01-07 12:13:17 -0800255
Craig Tiller74189cd2016-06-23 15:39:06 -0700256 def state(self):
ctiller3040cb72015-01-07 12:13:17 -0800257 """Poll current state of the job. Prints messages at completion."""
Craig Tillerdb218992016-01-05 09:28:46 -0800258 def stdout(self=self):
259 self._tempfile.seek(0)
260 stdout = self._tempfile.read()
261 self.result.message = stdout[-_MAX_RESULT_SIZE:]
262 return stdout
ctiller3040cb72015-01-07 12:13:17 -0800263 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800264 elapsed = time.time() - self._start
Adele Zhoue4c35612015-10-16 15:34:23 -0700265 self.result.elapsed_time = elapsed
ctiller3040cb72015-01-07 12:13:17 -0800266 if self._process.returncode != 0:
Craig Tiller91318bc2015-09-24 08:58:39 -0700267 if self._retries < self._spec.flake_retries:
268 message('FLAKE', '%s [ret=%d, pid=%d]' % (
Craig Tillerd0ffe142015-05-19 21:51:13 -0700269 self._spec.shortname, self._process.returncode, self._process.pid),
Craig Tillerdb218992016-01-05 09:28:46 -0800270 stdout(), do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700271 self._retries += 1
Adele Zhoud5fffa52015-10-23 15:51:42 -0700272 self.result.num_failures += 1
Adele Zhoue4c35612015-10-16 15:34:23 -0700273 self.result.retries = self._timeout_retries + self._retries
Craig Tiller91318bc2015-09-24 08:58:39 -0700274 self.start()
275 else:
276 self._state = _FAILURE
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700277 if not self._suppress_failure_message:
278 message('FAILED', '%s [ret=%d, pid=%d]' % (
279 self._spec.shortname, self._process.returncode, self._process.pid),
Craig Tillerdb218992016-01-05 09:28:46 -0800280 stdout(), do_newline=True)
Adele Zhoue4c35612015-10-16 15:34:23 -0700281 self.result.state = 'FAILED'
Adele Zhoud5fffa52015-10-23 15:51:42 -0700282 self.result.num_failures += 1
Adele Zhoue4c35612015-10-16 15:34:23 -0700283 self.result.returncode = self._process.returncode
ctiller3040cb72015-01-07 12:13:17 -0800284 else:
285 self._state = _SUCCESS
Craig Tiller5f735a62016-01-20 09:31:15 -0800286 measurement = ''
287 if measure_cpu_costs:
288 m = re.search(r'real ([0-9.]+)\nuser ([0-9.]+)\nsys ([0-9.]+)', stdout())
289 real = float(m.group(1))
290 user = float(m.group(2))
291 sys = float(m.group(3))
292 if real > 0.5:
293 cores = (user + sys) / real
Craig Tillerbfe69362016-01-20 09:38:21 -0800294 measurement = '; cpu_cost=%.01f; estimated=%.01f' % (cores, self._spec.cpu_cost)
Craig Tiller5f735a62016-01-20 09:31:15 -0800295 message('PASSED', '%s [time=%.1fsec; retries=%d:%d%s]' % (
Jan Tattermuschb2758442016-03-28 09:32:20 -0700296 self._spec.shortname, elapsed, self._retries, self._timeout_retries, measurement),
297 stdout() if self._spec.verbose_success else None,
Craig Tiller95cc07b2015-09-28 13:41:30 -0700298 do_newline=self._newline_on_success or self._travis)
Adele Zhoue4c35612015-10-16 15:34:23 -0700299 self.result.state = 'PASSED'
Craig Tiller5f735a62016-01-20 09:31:15 -0800300 elif (self._state == _RUNNING and
301 self._spec.timeout_seconds is not None and
Craig Tiller590105a2016-01-19 13:03:46 -0800302 time.time() - self._start > self._spec.timeout_seconds):
Craig Tiller95cc07b2015-09-28 13:41:30 -0700303 if self._timeout_retries < self._spec.timeout_retries:
Craig Tillerdb218992016-01-05 09:28:46 -0800304 message('TIMEOUT_FLAKE', '%s [pid=%d]' % (self._spec.shortname, self._process.pid), stdout(), do_newline=True)
Craig Tiller95cc07b2015-09-28 13:41:30 -0700305 self._timeout_retries += 1
Adele Zhoud5fffa52015-10-23 15:51:42 -0700306 self.result.num_failures += 1
Adele Zhoue4c35612015-10-16 15:34:23 -0700307 self.result.retries = self._timeout_retries + self._retries
Jan Tattermusch39e3cb32015-10-22 18:21:08 -0700308 if self._spec.kill_handler:
309 self._spec.kill_handler(self)
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700310 self._process.terminate()
311 self.start()
312 else:
Craig Tillerdb218992016-01-05 09:28:46 -0800313 message('TIMEOUT', '%s [pid=%d]' % (self._spec.shortname, self._process.pid), stdout(), do_newline=True)
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700314 self.kill()
Adele Zhoue4c35612015-10-16 15:34:23 -0700315 self.result.state = 'TIMEOUT'
Adele Zhoud5fffa52015-10-23 15:51:42 -0700316 self.result.num_failures += 1
ctiller3040cb72015-01-07 12:13:17 -0800317 return self._state
318
319 def kill(self):
320 if self._state == _RUNNING:
321 self._state = _KILLED
Jan Tattermusche2686282015-10-08 16:27:07 -0700322 if self._spec.kill_handler:
323 self._spec.kill_handler(self)
ctiller3040cb72015-01-07 12:13:17 -0800324 self._process.terminate()
325
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700326 def suppress_failure_message(self):
327 self._suppress_failure_message = True
Craig Tillerdb218992016-01-05 09:28:46 -0800328
ctiller3040cb72015-01-07 12:13:17 -0800329
Nicolas Nobleddef2462015-01-06 18:08:25 -0800330class Jobset(object):
331 """Manages one run of jobs."""
332
Craig Tiller533b1a22015-05-29 08:41:29 -0700333 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Craig Tiller74189cd2016-06-23 15:39:06 -0700334 stop_on_failure, add_env):
ctiller3040cb72015-01-07 12:13:17 -0800335 self._running = set()
336 self._check_cancelled = check_cancelled
337 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800338 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800339 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800340 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800341 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100342 self._travis = travis
Craig Tiller533b1a22015-05-29 08:41:29 -0700343 self._stop_on_failure = stop_on_failure
Craig Tillerf53d9c82015-08-04 14:19:43 -0700344 self._add_env = add_env
Adele Zhoue4c35612015-10-16 15:34:23 -0700345 self.resultset = {}
Craig Tiller6364dcb2015-11-24 16:29:06 -0800346 self._remaining = None
Craig Tillered735102016-04-06 12:59:23 -0700347 self._start_time = time.time()
Craig Tiller6364dcb2015-11-24 16:29:06 -0800348
349 def set_remaining(self, remaining):
350 self._remaining = remaining
351
Adele Zhoue4c35612015-10-16 15:34:23 -0700352 def get_num_failures(self):
Craig Tiller6364dcb2015-11-24 16:29:06 -0800353 return self._failures
Nicolas Nobleddef2462015-01-06 18:08:25 -0800354
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800355 def cpu_cost(self):
356 c = 0
357 for job in self._running:
358 c += job._spec.cpu_cost
359 return c
360
Craig Tiller547db2b2015-01-30 14:08:39 -0800361 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800362 """Start a job. Return True on success, False on failure."""
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800363 while True:
ctiller3040cb72015-01-07 12:13:17 -0800364 if self.cancelled(): return False
Craig Tiller56c6b6a2016-01-20 08:27:37 -0800365 current_cpu_cost = self.cpu_cost()
366 if current_cpu_cost == 0: break
Craig Tiller3e301a32016-01-27 15:36:52 -0800367 if current_cpu_cost + spec.cpu_cost <= self._maxjobs: break
ctiller3040cb72015-01-07 12:13:17 -0800368 self.reap()
369 if self.cancelled(): return False
Craig Tiller74189cd2016-06-23 15:39:06 -0700370 job = Job(spec,
371 self._newline_on_success,
372 self._travis,
373 self._add_env)
374 self._running.add(job)
siddharthshukla0589e532016-07-07 16:08:01 +0200375 if job.GetSpec().shortname not in self.resultset:
Craig Tiller74189cd2016-06-23 15:39:06 -0700376 self.resultset[job.GetSpec().shortname] = []
Craig Tillerddf02c12016-06-24 14:04:01 -0700377 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800378
ctiller3040cb72015-01-07 12:13:17 -0800379 def reap(self):
380 """Collect the dead jobs."""
381 while self._running:
382 dead = set()
383 for job in self._running:
Craig Tiller74189cd2016-06-23 15:39:06 -0700384 st = job.state()
ctiller3040cb72015-01-07 12:13:17 -0800385 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700386 if st == _FAILURE or st == _KILLED:
387 self._failures += 1
388 if self._stop_on_failure:
389 self._cancelled = True
390 for job in self._running:
391 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800392 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700393 break
ctiller3040cb72015-01-07 12:13:17 -0800394 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800395 self._completed += 1
Adele Zhoud5fffa52015-10-23 15:51:42 -0700396 self.resultset[job.GetSpec().shortname].append(job.result)
ctiller3040cb72015-01-07 12:13:17 -0800397 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800398 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100399 if (not self._travis):
Craig Tiller2c23ad52015-12-04 06:50:38 -0800400 rstr = '' if self._remaining is None else '%d queued, ' % self._remaining
Craig Tillered735102016-04-06 12:59:23 -0700401 if self._remaining is not None and self._completed > 0:
402 now = time.time()
403 sofar = now - self._start_time
404 remaining = sofar / self._completed * (self._remaining + len(self._running))
405 rstr = 'ETA %.1f sec; %s' % (remaining, rstr)
Craig Tiller2c23ad52015-12-04 06:50:38 -0800406 message('WAITING', '%s%d jobs running, %d complete, %d failed' % (
407 rstr, len(self._running), self._completed, self._failures))
Nicolas "Pixel" Noblef72d7b52015-12-03 03:07:43 +0100408 if platform_string() == 'windows':
Craig Tiller5058c692015-04-08 09:42:04 -0700409 time.sleep(0.1)
410 else:
411 global have_alarm
412 if not have_alarm:
413 have_alarm = True
414 signal.alarm(10)
415 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800416
417 def cancelled(self):
418 """Poll for cancellation."""
419 if self._cancelled: return True
420 if not self._check_cancelled(): return False
421 for job in self._running:
422 job.kill()
423 self._cancelled = True
424 return True
425
426 def finish(self):
427 while self._running:
428 if self.cancelled(): pass # poll cancellation
429 self.reap()
430 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800431
432
ctiller3040cb72015-01-07 12:13:17 -0800433def _never_cancelled():
434 return False
435
436
Craig Tiller6364dcb2015-11-24 16:29:06 -0800437def tag_remaining(xs):
438 staging = []
439 for x in xs:
440 staging.append(x)
Craig Tillered735102016-04-06 12:59:23 -0700441 if len(staging) > 5000:
Craig Tiller6364dcb2015-11-24 16:29:06 -0800442 yield (staging.pop(0), None)
443 n = len(staging)
444 for i, x in enumerate(staging):
445 yield (x, n - i - 1)
446
447
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800448def run(cmdlines,
449 check_cancelled=_never_cancelled,
450 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800451 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100452 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700453 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700454 stop_on_failure=False,
Matt Kwong5c691c62016-10-20 17:11:18 -0700455 add_env={},
456 skip_jobs=False):
457 if skip_jobs:
458 results = {}
459 skipped_job_result = JobResult()
460 skipped_job_result.state = 'SKIPPED'
461 for job in cmdlines:
462 message('SKIPPED', job.shortname, do_newline=True)
463 results[job.shortname] = [skipped_job_result]
464 return results
ctiller94e5dde2015-01-09 10:41:59 -0800465 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800466 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tiller74189cd2016-06-23 15:39:06 -0700467 newline_on_success, travis, stop_on_failure, add_env)
Craig Tiller6364dcb2015-11-24 16:29:06 -0800468 for cmdline, remaining in tag_remaining(cmdlines):
ctiller3040cb72015-01-07 12:13:17 -0800469 if not js.start(cmdline):
470 break
Craig Tiller6364dcb2015-11-24 16:29:06 -0800471 if remaining is not None:
472 js.set_remaining(remaining)
473 js.finish()
Adele Zhoue4c35612015-10-16 15:34:23 -0700474 return js.get_num_failures(), js.resultset