blob: f6fdc8059535e857cf56cc7e47d5ba856ee28429 [file] [log] [blame]
Craig Tillerc2c79212015-02-16 12:00:01 -08001# Copyright 2015, Google Inc.
2# 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
Craig Tiller71735182015-01-15 17:07:13 -080032import hashlib
Nicolas Nobleddef2462015-01-06 18:08:25 -080033import multiprocessing
Craig Tiller71735182015-01-15 17:07:13 -080034import os
Craig Tiller5058c692015-04-08 09:42:04 -070035import platform
Craig Tiller336ad502015-02-24 14:46:02 -080036import signal
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +020037import string
Nicolas Nobleddef2462015-01-06 18:08:25 -080038import subprocess
39import sys
ctiller3040cb72015-01-07 12:13:17 -080040import tempfile
41import time
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +020042import xml.etree.cElementTree as ET
Nicolas Nobleddef2462015-01-06 18:08:25 -080043
ctiller3040cb72015-01-07 12:13:17 -080044
ctiller94e5dde2015-01-09 10:41:59 -080045_DEFAULT_MAX_JOBS = 16 * multiprocessing.cpu_count()
Nicolas Nobleddef2462015-01-06 18:08:25 -080046
47
Craig Tiller336ad502015-02-24 14:46:02 -080048# setup a signal handler so that signal.pause registers 'something'
49# when a child finishes
50# not using futures and threading to avoid a dependency on subprocess32
Craig Tiller5058c692015-04-08 09:42:04 -070051if platform.system() == "Windows":
52 pass
53else:
54 have_alarm = False
55 def alarm_handler(unused_signum, unused_frame):
56 global have_alarm
57 have_alarm = False
58
59 signal.signal(signal.SIGCHLD, lambda unused_signum, unused_frame: None)
60 signal.signal(signal.SIGALRM, alarm_handler)
Craig Tiller336ad502015-02-24 14:46:02 -080061
62
ctiller3040cb72015-01-07 12:13:17 -080063_SUCCESS = object()
64_FAILURE = object()
65_RUNNING = object()
66_KILLED = object()
67
68
Craig Tiller3b083062015-01-12 13:51:28 -080069_COLORS = {
Nicolas Noble044db742015-01-14 16:57:24 -080070 'red': [ 31, 0 ],
71 'green': [ 32, 0 ],
72 'yellow': [ 33, 0 ],
73 'lightgray': [ 37, 0],
74 'gray': [ 30, 1 ],
Craig Tillerd7e09c32015-09-25 11:33:39 -070075 'purple': [ 35, 0 ],
Craig Tiller3b083062015-01-12 13:51:28 -080076 }
77
78
79_BEGINNING_OF_LINE = '\x1b[0G'
80_CLEAR_LINE = '\x1b[2K'
81
82
83_TAG_COLOR = {
84 'FAILED': 'red',
Craig Tillerd7e09c32015-09-25 11:33:39 -070085 'FLAKE': 'purple',
Craig Tiller3dc1e4f2015-09-25 11:46:56 -070086 'TIMEOUT_FLAKE': 'purple',
Masood Malekghassemie5f70022015-06-29 09:20:26 -070087 'WARNING': 'yellow',
Craig Tillere1d0d1c2015-02-27 08:54:23 -080088 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -080089 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080090 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080091 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080092 'SUCCESS': 'green',
93 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080094 }
95
96
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +020097def message(tag, msg, explanatory_text=None, do_newline=False):
98 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
99 return
100 message.old_tag = tag
101 message.old_msg = msg
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800102 try:
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700103 if platform.system() == 'Windows' or not sys.stdout.isatty():
104 if explanatory_text:
105 print explanatory_text
106 print '%s: %s' % (tag, msg)
107 return
vjpaia29d2d72015-07-08 10:31:15 -0700108 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
109 _BEGINNING_OF_LINE,
110 _CLEAR_LINE,
111 '\n%s' % explanatory_text if explanatory_text is not None else '',
112 _COLORS[_TAG_COLOR[tag]][1],
113 _COLORS[_TAG_COLOR[tag]][0],
114 tag,
115 msg,
116 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800117 sys.stdout.flush()
118 except:
119 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800120
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200121message.old_tag = ""
122message.old_msg = ""
Craig Tiller3b083062015-01-12 13:51:28 -0800123
Craig Tiller71735182015-01-15 17:07:13 -0800124def which(filename):
125 if '/' in filename:
126 return filename
127 for path in os.environ['PATH'].split(os.pathsep):
128 if os.path.exists(os.path.join(path, filename)):
129 return os.path.join(path, filename)
130 raise Exception('%s not found' % filename)
131
132
Craig Tiller547db2b2015-01-30 14:08:39 -0800133class JobSpec(object):
134 """Specifies what to run for a job."""
135
Jan Tattermusch725835a2015-08-01 21:02:35 -0700136 def __init__(self, cmdline, shortname=None, environ=None, hash_targets=None,
Craig Tiller91318bc2015-09-24 08:58:39 -0700137 cwd=None, shell=False, timeout_seconds=5*60, flake_retries=5):
Craig Tiller547db2b2015-01-30 14:08:39 -0800138 """
139 Arguments:
140 cmdline: a list of arguments to pass as the command line
141 environ: a dictionary of environment variables to set in the child process
142 hash_targets: which files to include in the hash representing the jobs version
143 (or empty, indicating the job should not be hashed)
144 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800145 if environ is None:
146 environ = {}
147 if hash_targets is None:
148 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800149 self.cmdline = cmdline
150 self.environ = environ
151 self.shortname = cmdline[0] if shortname is None else shortname
152 self.hash_targets = hash_targets or []
Craig Tiller5058c692015-04-08 09:42:04 -0700153 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700154 self.shell = shell
Jan Tattermusch725835a2015-08-01 21:02:35 -0700155 self.timeout_seconds = timeout_seconds
Craig Tiller91318bc2015-09-24 08:58:39 -0700156 self.flake_retries = flake_retries
Craig Tiller547db2b2015-01-30 14:08:39 -0800157
158 def identity(self):
159 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
160
161 def __hash__(self):
162 return hash(self.identity())
163
164 def __cmp__(self, other):
165 return self.identity() == other.identity()
166
167
ctiller3040cb72015-01-07 12:13:17 -0800168class Job(object):
169 """Manages one job."""
170
Craig Tillerf53d9c82015-08-04 14:19:43 -0700171 def __init__(self, spec, bin_hash, newline_on_success, travis, add_env, xml_report):
Craig Tiller547db2b2015-01-30 14:08:39 -0800172 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800173 self._bin_hash = bin_hash
Nicolas Noble044db742015-01-14 16:57:24 -0800174 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100175 self._travis = travis
Craig Tiller91318bc2015-09-24 08:58:39 -0700176 self._add_env = add_env.copy()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200177 self._xml_test = ET.SubElement(xml_report, 'testcase',
178 name=self._spec.shortname) if xml_report is not None else None
Craig Tiller91318bc2015-09-24 08:58:39 -0700179 self._retries = 0
Craig Tillerb84728d2015-02-26 15:40:39 -0800180 message('START', spec.shortname, do_newline=self._travis)
Craig Tiller91318bc2015-09-24 08:58:39 -0700181 self.start()
182
183 def start(self):
184 self._tempfile = tempfile.TemporaryFile()
185 env = dict(os.environ)
186 env.update(self._spec.environ)
187 env.update(self._add_env)
188 self._start = time.time()
189 self._process = subprocess.Popen(args=self._spec.cmdline,
190 stderr=subprocess.STDOUT,
191 stdout=self._tempfile,
192 cwd=self._spec.cwd,
193 shell=self._spec.shell,
194 env=env)
195 self._state = _RUNNING
ctiller3040cb72015-01-07 12:13:17 -0800196
Craig Tiller71735182015-01-15 17:07:13 -0800197 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800198 """Poll current state of the job. Prints messages at completion."""
199 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800200 elapsed = time.time() - self._start
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200201 self._tempfile.seek(0)
202 stdout = self._tempfile.read()
203 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Nicolas "Pixel" Noble4a5a8f32015-08-13 19:43:00 +0200204 # TODO: looks like jenkins master is slow because parsing the junit results XMLs is not
205 # implemented efficiently. This is an experiment to workaround the issue by making sure
206 # results.xml file is small enough.
207 filtered_stdout = filtered_stdout[-128:]
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200208 if self._xml_test is not None:
209 self._xml_test.set('time', str(elapsed))
210 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
ctiller3040cb72015-01-07 12:13:17 -0800211 if self._process.returncode != 0:
Craig Tiller91318bc2015-09-24 08:58:39 -0700212 if self._retries < self._spec.flake_retries:
213 message('FLAKE', '%s [ret=%d, pid=%d]' % (
Craig Tillerd0ffe142015-05-19 21:51:13 -0700214 self._spec.shortname, self._process.returncode, self._process.pid),
215 stdout, do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700216 self._retries += 1
217 self.start()
218 else:
219 self._state = _FAILURE
220 message('FAILED', '%s [ret=%d, pid=%d]' % (
221 self._spec.shortname, self._process.returncode, self._process.pid),
222 stdout, do_newline=True)
223 if self._xml_test is not None:
224 ET.SubElement(self._xml_test, 'failure', message='Failure').text
ctiller3040cb72015-01-07 12:13:17 -0800225 else:
226 self._state = _SUCCESS
Craig Tiller91318bc2015-09-24 08:58:39 -0700227 message('PASSED', '%s [time=%.1fsec; retries=%d]' % (self._spec.shortname, elapsed, self._retries),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100228 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800229 if self._bin_hash:
230 update_cache.finished(self._spec.identity(), self._bin_hash)
Jan Tattermusch725835a2015-08-01 21:02:35 -0700231 elif self._state == _RUNNING and time.time() - self._start > self._spec.timeout_seconds:
Craig Tiller84216782015-05-12 09:43:54 -0700232 self._tempfile.seek(0)
233 stdout = self._tempfile.read()
Nicolas "Pixel" Noblef716c0c2015-07-12 01:26:17 +0200234 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700235 if self._retries < self._spec.flake_retries:
236 message('TIMEOUT_FLAKE', self._spec.shortname, stdout, do_newline=True)
237 self._retries += 1
238 self._process.terminate()
239 self.start()
240 else:
241 message('TIMEOUT', self._spec.shortname, stdout, do_newline=True)
242 self.kill()
243 if self._xml_test is not None:
244 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
245 ET.SubElement(self._xml_test, 'error', message='Timeout')
ctiller3040cb72015-01-07 12:13:17 -0800246 return self._state
247
248 def kill(self):
249 if self._state == _RUNNING:
250 self._state = _KILLED
251 self._process.terminate()
252
253
Nicolas Nobleddef2462015-01-06 18:08:25 -0800254class Jobset(object):
255 """Manages one run of jobs."""
256
Craig Tiller533b1a22015-05-29 08:41:29 -0700257 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700258 stop_on_failure, add_env, cache, xml_report):
ctiller3040cb72015-01-07 12:13:17 -0800259 self._running = set()
260 self._check_cancelled = check_cancelled
261 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800262 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800263 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800264 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800265 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100266 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800267 self._cache = cache
Craig Tiller533b1a22015-05-29 08:41:29 -0700268 self._stop_on_failure = stop_on_failure
Craig Tiller74e770d2015-06-11 09:38:09 -0700269 self._hashes = {}
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200270 self._xml_report = xml_report
Craig Tillerf53d9c82015-08-04 14:19:43 -0700271 self._add_env = add_env
Nicolas Nobleddef2462015-01-06 18:08:25 -0800272
Craig Tiller547db2b2015-01-30 14:08:39 -0800273 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800274 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800275 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800276 if self.cancelled(): return False
277 self.reap()
278 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800279 if spec.hash_targets:
Craig Tiller74e770d2015-06-11 09:38:09 -0700280 if spec.identity() in self._hashes:
281 bin_hash = self._hashes[spec.identity()]
282 else:
283 bin_hash = hashlib.sha1()
284 for fn in spec.hash_targets:
285 with open(which(fn)) as f:
286 bin_hash.update(f.read())
287 bin_hash = bin_hash.hexdigest()
288 self._hashes[spec.identity()] = bin_hash
Craig Tiller547db2b2015-01-30 14:08:39 -0800289 should_run = self._cache.should_run(spec.identity(), bin_hash)
290 else:
291 bin_hash = None
292 should_run = True
293 if should_run:
Craig Tillerf53d9c82015-08-04 14:19:43 -0700294 self._running.add(Job(spec,
295 bin_hash,
296 self._newline_on_success,
297 self._travis,
298 self._add_env,
299 self._xml_report))
ctiller3040cb72015-01-07 12:13:17 -0800300 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800301
ctiller3040cb72015-01-07 12:13:17 -0800302 def reap(self):
303 """Collect the dead jobs."""
304 while self._running:
305 dead = set()
306 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800307 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800308 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700309 if st == _FAILURE or st == _KILLED:
310 self._failures += 1
311 if self._stop_on_failure:
312 self._cancelled = True
313 for job in self._running:
314 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800315 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700316 break
ctiller3040cb72015-01-07 12:13:17 -0800317 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800318 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800319 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800320 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100321 if (not self._travis):
322 message('WAITING', '%d jobs running, %d complete, %d failed' % (
323 len(self._running), self._completed, self._failures))
Craig Tiller5058c692015-04-08 09:42:04 -0700324 if platform.system() == 'Windows':
325 time.sleep(0.1)
326 else:
327 global have_alarm
328 if not have_alarm:
329 have_alarm = True
330 signal.alarm(10)
331 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800332
333 def cancelled(self):
334 """Poll for cancellation."""
335 if self._cancelled: return True
336 if not self._check_cancelled(): return False
337 for job in self._running:
338 job.kill()
339 self._cancelled = True
340 return True
341
342 def finish(self):
343 while self._running:
344 if self.cancelled(): pass # poll cancellation
345 self.reap()
346 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800347
348
ctiller3040cb72015-01-07 12:13:17 -0800349def _never_cancelled():
350 return False
351
352
Craig Tiller71735182015-01-15 17:07:13 -0800353# cache class that caches nothing
354class NoCache(object):
355 def should_run(self, cmdline, bin_hash):
356 return True
357
358 def finished(self, cmdline, bin_hash):
359 pass
360
361
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800362def run(cmdlines,
363 check_cancelled=_never_cancelled,
364 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800365 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100366 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700367 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700368 stop_on_failure=False,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200369 cache=None,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700370 xml_report=None,
371 add_env={}):
ctiller94e5dde2015-01-09 10:41:59 -0800372 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800373 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700374 newline_on_success, travis, stop_on_failure, add_env,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200375 cache if cache is not None else NoCache(),
376 xml_report)
Craig Tillerb84728d2015-02-26 15:40:39 -0800377 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800378 if not js.start(cmdline):
379 break
380 return js.finish()