blob: 87be703b4cdfa6d1a3b859db603801b32a461717 [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 Tiller95cc07b2015-09-28 13:41:30 -0700137 cwd=None, shell=False, timeout_seconds=5*60, flake_retries=0,
138 timeout_retries=0):
Craig Tiller547db2b2015-01-30 14:08:39 -0800139 """
140 Arguments:
141 cmdline: a list of arguments to pass as the command line
142 environ: a dictionary of environment variables to set in the child process
143 hash_targets: which files to include in the hash representing the jobs version
144 (or empty, indicating the job should not be hashed)
145 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800146 if environ is None:
147 environ = {}
148 if hash_targets is None:
149 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800150 self.cmdline = cmdline
151 self.environ = environ
152 self.shortname = cmdline[0] if shortname is None else shortname
153 self.hash_targets = hash_targets or []
Craig Tiller5058c692015-04-08 09:42:04 -0700154 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700155 self.shell = shell
Jan Tattermusch725835a2015-08-01 21:02:35 -0700156 self.timeout_seconds = timeout_seconds
Craig Tiller91318bc2015-09-24 08:58:39 -0700157 self.flake_retries = flake_retries
Craig Tillerbfc8a062015-09-28 14:40:21 -0700158 self.timeout_retries = timeout_retries
Craig Tiller547db2b2015-01-30 14:08:39 -0800159
160 def identity(self):
161 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
162
163 def __hash__(self):
164 return hash(self.identity())
165
166 def __cmp__(self, other):
167 return self.identity() == other.identity()
168
169
ctiller3040cb72015-01-07 12:13:17 -0800170class Job(object):
171 """Manages one job."""
172
Craig Tillerf53d9c82015-08-04 14:19:43 -0700173 def __init__(self, spec, bin_hash, newline_on_success, travis, add_env, xml_report):
Craig Tiller547db2b2015-01-30 14:08:39 -0800174 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800175 self._bin_hash = bin_hash
Nicolas Noble044db742015-01-14 16:57:24 -0800176 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100177 self._travis = travis
Craig Tiller91318bc2015-09-24 08:58:39 -0700178 self._add_env = add_env.copy()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200179 self._xml_test = ET.SubElement(xml_report, 'testcase',
180 name=self._spec.shortname) if xml_report is not None else None
Craig Tiller91318bc2015-09-24 08:58:39 -0700181 self._retries = 0
Craig Tiller95cc07b2015-09-28 13:41:30 -0700182 self._timeout_retries = 0
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700183 self._suppress_failure_message = False
Craig Tillerb84728d2015-02-26 15:40:39 -0800184 message('START', spec.shortname, do_newline=self._travis)
Craig Tiller91318bc2015-09-24 08:58:39 -0700185 self.start()
186
187 def start(self):
188 self._tempfile = tempfile.TemporaryFile()
189 env = dict(os.environ)
190 env.update(self._spec.environ)
191 env.update(self._add_env)
192 self._start = time.time()
193 self._process = subprocess.Popen(args=self._spec.cmdline,
194 stderr=subprocess.STDOUT,
195 stdout=self._tempfile,
196 cwd=self._spec.cwd,
197 shell=self._spec.shell,
198 env=env)
199 self._state = _RUNNING
ctiller3040cb72015-01-07 12:13:17 -0800200
Craig Tiller71735182015-01-15 17:07:13 -0800201 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800202 """Poll current state of the job. Prints messages at completion."""
203 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800204 elapsed = time.time() - self._start
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200205 self._tempfile.seek(0)
206 stdout = self._tempfile.read()
207 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Nicolas "Pixel" Noble4a5a8f32015-08-13 19:43:00 +0200208 # TODO: looks like jenkins master is slow because parsing the junit results XMLs is not
209 # implemented efficiently. This is an experiment to workaround the issue by making sure
210 # results.xml file is small enough.
211 filtered_stdout = filtered_stdout[-128:]
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200212 if self._xml_test is not None:
213 self._xml_test.set('time', str(elapsed))
214 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
ctiller3040cb72015-01-07 12:13:17 -0800215 if self._process.returncode != 0:
Craig Tiller91318bc2015-09-24 08:58:39 -0700216 if self._retries < self._spec.flake_retries:
217 message('FLAKE', '%s [ret=%d, pid=%d]' % (
Craig Tillerd0ffe142015-05-19 21:51:13 -0700218 self._spec.shortname, self._process.returncode, self._process.pid),
219 stdout, do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700220 self._retries += 1
221 self.start()
222 else:
223 self._state = _FAILURE
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700224 if not self._suppress_failure_message:
225 message('FAILED', '%s [ret=%d, pid=%d]' % (
226 self._spec.shortname, self._process.returncode, self._process.pid),
227 stdout, do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700228 if self._xml_test is not None:
229 ET.SubElement(self._xml_test, 'failure', message='Failure').text
ctiller3040cb72015-01-07 12:13:17 -0800230 else:
231 self._state = _SUCCESS
Craig Tiller95cc07b2015-09-28 13:41:30 -0700232 message('PASSED', '%s [time=%.1fsec; retries=%d;%d]' % (
233 self._spec.shortname, elapsed, self._retries, self._timeout_retries),
234 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800235 if self._bin_hash:
236 update_cache.finished(self._spec.identity(), self._bin_hash)
Jan Tattermusch725835a2015-08-01 21:02:35 -0700237 elif self._state == _RUNNING and time.time() - self._start > self._spec.timeout_seconds:
Craig Tiller84216782015-05-12 09:43:54 -0700238 self._tempfile.seek(0)
239 stdout = self._tempfile.read()
Nicolas "Pixel" Noblef716c0c2015-07-12 01:26:17 +0200240 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Craig Tiller95cc07b2015-09-28 13:41:30 -0700241 if self._timeout_retries < self._spec.timeout_retries:
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700242 message('TIMEOUT_FLAKE', self._spec.shortname, stdout, do_newline=True)
Craig Tiller95cc07b2015-09-28 13:41:30 -0700243 self._timeout_retries += 1
Craig Tiller3dc1e4f2015-09-25 11:46:56 -0700244 self._process.terminate()
245 self.start()
246 else:
247 message('TIMEOUT', self._spec.shortname, stdout, do_newline=True)
248 self.kill()
249 if self._xml_test is not None:
250 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
251 ET.SubElement(self._xml_test, 'error', message='Timeout')
ctiller3040cb72015-01-07 12:13:17 -0800252 return self._state
253
254 def kill(self):
255 if self._state == _RUNNING:
256 self._state = _KILLED
257 self._process.terminate()
258
Jan Tattermusch91ad0182015-10-01 09:22:03 -0700259 def suppress_failure_message(self):
260 self._suppress_failure_message = True
261
ctiller3040cb72015-01-07 12:13:17 -0800262
Nicolas Nobleddef2462015-01-06 18:08:25 -0800263class Jobset(object):
264 """Manages one run of jobs."""
265
Craig Tiller533b1a22015-05-29 08:41:29 -0700266 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700267 stop_on_failure, add_env, cache, xml_report):
ctiller3040cb72015-01-07 12:13:17 -0800268 self._running = set()
269 self._check_cancelled = check_cancelled
270 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800271 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800272 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800273 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800274 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100275 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800276 self._cache = cache
Craig Tiller533b1a22015-05-29 08:41:29 -0700277 self._stop_on_failure = stop_on_failure
Craig Tiller74e770d2015-06-11 09:38:09 -0700278 self._hashes = {}
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200279 self._xml_report = xml_report
Craig Tillerf53d9c82015-08-04 14:19:43 -0700280 self._add_env = add_env
Nicolas Nobleddef2462015-01-06 18:08:25 -0800281
Craig Tiller547db2b2015-01-30 14:08:39 -0800282 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800283 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800284 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800285 if self.cancelled(): return False
286 self.reap()
287 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800288 if spec.hash_targets:
Craig Tiller74e770d2015-06-11 09:38:09 -0700289 if spec.identity() in self._hashes:
290 bin_hash = self._hashes[spec.identity()]
291 else:
292 bin_hash = hashlib.sha1()
293 for fn in spec.hash_targets:
294 with open(which(fn)) as f:
295 bin_hash.update(f.read())
296 bin_hash = bin_hash.hexdigest()
297 self._hashes[spec.identity()] = bin_hash
Craig Tiller547db2b2015-01-30 14:08:39 -0800298 should_run = self._cache.should_run(spec.identity(), bin_hash)
299 else:
300 bin_hash = None
301 should_run = True
302 if should_run:
Craig Tillerf53d9c82015-08-04 14:19:43 -0700303 self._running.add(Job(spec,
304 bin_hash,
305 self._newline_on_success,
306 self._travis,
307 self._add_env,
308 self._xml_report))
ctiller3040cb72015-01-07 12:13:17 -0800309 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800310
ctiller3040cb72015-01-07 12:13:17 -0800311 def reap(self):
312 """Collect the dead jobs."""
313 while self._running:
314 dead = set()
315 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800316 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800317 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700318 if st == _FAILURE or st == _KILLED:
319 self._failures += 1
320 if self._stop_on_failure:
321 self._cancelled = True
322 for job in self._running:
323 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800324 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700325 break
ctiller3040cb72015-01-07 12:13:17 -0800326 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800327 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800328 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800329 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100330 if (not self._travis):
331 message('WAITING', '%d jobs running, %d complete, %d failed' % (
332 len(self._running), self._completed, self._failures))
Craig Tiller5058c692015-04-08 09:42:04 -0700333 if platform.system() == 'Windows':
334 time.sleep(0.1)
335 else:
336 global have_alarm
337 if not have_alarm:
338 have_alarm = True
339 signal.alarm(10)
340 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800341
342 def cancelled(self):
343 """Poll for cancellation."""
344 if self._cancelled: return True
345 if not self._check_cancelled(): return False
346 for job in self._running:
347 job.kill()
348 self._cancelled = True
349 return True
350
351 def finish(self):
352 while self._running:
353 if self.cancelled(): pass # poll cancellation
354 self.reap()
355 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800356
357
ctiller3040cb72015-01-07 12:13:17 -0800358def _never_cancelled():
359 return False
360
361
Craig Tiller71735182015-01-15 17:07:13 -0800362# cache class that caches nothing
363class NoCache(object):
364 def should_run(self, cmdline, bin_hash):
365 return True
366
367 def finished(self, cmdline, bin_hash):
368 pass
369
370
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800371def run(cmdlines,
372 check_cancelled=_never_cancelled,
373 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800374 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100375 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700376 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700377 stop_on_failure=False,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200378 cache=None,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700379 xml_report=None,
380 add_env={}):
ctiller94e5dde2015-01-09 10:41:59 -0800381 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800382 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700383 newline_on_success, travis, stop_on_failure, add_env,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200384 cache if cache is not None else NoCache(),
385 xml_report)
Craig Tillerb84728d2015-02-26 15:40:39 -0800386 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800387 if not js.start(cmdline):
388 break
389 return js.finish()