blob: 6ddc4d29bc5da03e7de203c79155df24c1b40577 [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',
Masood Malekghassemie5f70022015-06-29 09:20:26 -070086 'WARNING': 'yellow',
Craig Tillere1d0d1c2015-02-27 08:54:23 -080087 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -080088 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080089 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080090 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080091 'SUCCESS': 'green',
92 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080093 }
94
95
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +020096def message(tag, msg, explanatory_text=None, do_newline=False):
97 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
98 return
99 message.old_tag = tag
100 message.old_msg = msg
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800101 try:
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700102 if platform.system() == 'Windows' or not sys.stdout.isatty():
103 if explanatory_text:
104 print explanatory_text
105 print '%s: %s' % (tag, msg)
106 return
vjpaia29d2d72015-07-08 10:31:15 -0700107 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
108 _BEGINNING_OF_LINE,
109 _CLEAR_LINE,
110 '\n%s' % explanatory_text if explanatory_text is not None else '',
111 _COLORS[_TAG_COLOR[tag]][1],
112 _COLORS[_TAG_COLOR[tag]][0],
113 tag,
114 msg,
115 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800116 sys.stdout.flush()
117 except:
118 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800119
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200120message.old_tag = ""
121message.old_msg = ""
Craig Tiller3b083062015-01-12 13:51:28 -0800122
Craig Tiller71735182015-01-15 17:07:13 -0800123def which(filename):
124 if '/' in filename:
125 return filename
126 for path in os.environ['PATH'].split(os.pathsep):
127 if os.path.exists(os.path.join(path, filename)):
128 return os.path.join(path, filename)
129 raise Exception('%s not found' % filename)
130
131
Craig Tiller547db2b2015-01-30 14:08:39 -0800132class JobSpec(object):
133 """Specifies what to run for a job."""
134
Jan Tattermusch725835a2015-08-01 21:02:35 -0700135 def __init__(self, cmdline, shortname=None, environ=None, hash_targets=None,
Craig Tiller91318bc2015-09-24 08:58:39 -0700136 cwd=None, shell=False, timeout_seconds=5*60, flake_retries=5):
Craig Tiller547db2b2015-01-30 14:08:39 -0800137 """
138 Arguments:
139 cmdline: a list of arguments to pass as the command line
140 environ: a dictionary of environment variables to set in the child process
141 hash_targets: which files to include in the hash representing the jobs version
142 (or empty, indicating the job should not be hashed)
143 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800144 if environ is None:
145 environ = {}
146 if hash_targets is None:
147 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800148 self.cmdline = cmdline
149 self.environ = environ
150 self.shortname = cmdline[0] if shortname is None else shortname
151 self.hash_targets = hash_targets or []
Craig Tiller5058c692015-04-08 09:42:04 -0700152 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700153 self.shell = shell
Jan Tattermusch725835a2015-08-01 21:02:35 -0700154 self.timeout_seconds = timeout_seconds
Craig Tiller91318bc2015-09-24 08:58:39 -0700155 self.flake_retries = flake_retries
Craig Tiller547db2b2015-01-30 14:08:39 -0800156
157 def identity(self):
158 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
159
160 def __hash__(self):
161 return hash(self.identity())
162
163 def __cmp__(self, other):
164 return self.identity() == other.identity()
165
166
ctiller3040cb72015-01-07 12:13:17 -0800167class Job(object):
168 """Manages one job."""
169
Craig Tillerf53d9c82015-08-04 14:19:43 -0700170 def __init__(self, spec, bin_hash, newline_on_success, travis, add_env, xml_report):
Craig Tiller547db2b2015-01-30 14:08:39 -0800171 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800172 self._bin_hash = bin_hash
Nicolas Noble044db742015-01-14 16:57:24 -0800173 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100174 self._travis = travis
Craig Tiller91318bc2015-09-24 08:58:39 -0700175 self._add_env = add_env.copy()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200176 self._xml_test = ET.SubElement(xml_report, 'testcase',
177 name=self._spec.shortname) if xml_report is not None else None
Craig Tiller91318bc2015-09-24 08:58:39 -0700178 self._retries = 0
Craig Tillerb84728d2015-02-26 15:40:39 -0800179 message('START', spec.shortname, do_newline=self._travis)
Craig Tiller91318bc2015-09-24 08:58:39 -0700180 self.start()
181
182 def start(self):
183 self._tempfile = tempfile.TemporaryFile()
184 env = dict(os.environ)
185 env.update(self._spec.environ)
186 env.update(self._add_env)
187 self._start = time.time()
188 self._process = subprocess.Popen(args=self._spec.cmdline,
189 stderr=subprocess.STDOUT,
190 stdout=self._tempfile,
191 cwd=self._spec.cwd,
192 shell=self._spec.shell,
193 env=env)
194 self._state = _RUNNING
ctiller3040cb72015-01-07 12:13:17 -0800195
Craig Tiller71735182015-01-15 17:07:13 -0800196 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800197 """Poll current state of the job. Prints messages at completion."""
198 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800199 elapsed = time.time() - self._start
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200200 self._tempfile.seek(0)
201 stdout = self._tempfile.read()
202 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Nicolas "Pixel" Noble4a5a8f32015-08-13 19:43:00 +0200203 # TODO: looks like jenkins master is slow because parsing the junit results XMLs is not
204 # implemented efficiently. This is an experiment to workaround the issue by making sure
205 # results.xml file is small enough.
206 filtered_stdout = filtered_stdout[-128:]
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200207 if self._xml_test is not None:
208 self._xml_test.set('time', str(elapsed))
209 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
ctiller3040cb72015-01-07 12:13:17 -0800210 if self._process.returncode != 0:
Craig Tiller91318bc2015-09-24 08:58:39 -0700211 if self._retries < self._spec.flake_retries:
212 message('FLAKE', '%s [ret=%d, pid=%d]' % (
Craig Tillerd0ffe142015-05-19 21:51:13 -0700213 self._spec.shortname, self._process.returncode, self._process.pid),
214 stdout, do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700215 self._retries += 1
216 self.start()
217 else:
218 self._state = _FAILURE
219 message('FAILED', '%s [ret=%d, pid=%d]' % (
220 self._spec.shortname, self._process.returncode, self._process.pid),
221 stdout, do_newline=True)
222 if self._xml_test is not None:
223 ET.SubElement(self._xml_test, 'failure', message='Failure').text
ctiller3040cb72015-01-07 12:13:17 -0800224 else:
225 self._state = _SUCCESS
Craig Tiller91318bc2015-09-24 08:58:39 -0700226 message('PASSED', '%s [time=%.1fsec; retries=%d]' % (self._spec.shortname, elapsed, self._retries),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100227 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800228 if self._bin_hash:
229 update_cache.finished(self._spec.identity(), self._bin_hash)
Jan Tattermusch725835a2015-08-01 21:02:35 -0700230 elif self._state == _RUNNING and time.time() - self._start > self._spec.timeout_seconds:
Craig Tiller84216782015-05-12 09:43:54 -0700231 self._tempfile.seek(0)
232 stdout = self._tempfile.read()
Nicolas "Pixel" Noblef716c0c2015-07-12 01:26:17 +0200233 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Craig Tiller84216782015-05-12 09:43:54 -0700234 message('TIMEOUT', self._spec.shortname, stdout, do_newline=True)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800235 self.kill()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200236 if self._xml_test is not None:
Nicolas "Pixel" Noblef716c0c2015-07-12 01:26:17 +0200237 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200238 ET.SubElement(self._xml_test, 'error', message='Timeout')
ctiller3040cb72015-01-07 12:13:17 -0800239 return self._state
240
241 def kill(self):
242 if self._state == _RUNNING:
243 self._state = _KILLED
244 self._process.terminate()
245
246
Nicolas Nobleddef2462015-01-06 18:08:25 -0800247class Jobset(object):
248 """Manages one run of jobs."""
249
Craig Tiller533b1a22015-05-29 08:41:29 -0700250 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700251 stop_on_failure, add_env, cache, xml_report):
ctiller3040cb72015-01-07 12:13:17 -0800252 self._running = set()
253 self._check_cancelled = check_cancelled
254 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800255 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800256 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800257 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800258 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100259 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800260 self._cache = cache
Craig Tiller533b1a22015-05-29 08:41:29 -0700261 self._stop_on_failure = stop_on_failure
Craig Tiller74e770d2015-06-11 09:38:09 -0700262 self._hashes = {}
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200263 self._xml_report = xml_report
Craig Tillerf53d9c82015-08-04 14:19:43 -0700264 self._add_env = add_env
Nicolas Nobleddef2462015-01-06 18:08:25 -0800265
Craig Tiller547db2b2015-01-30 14:08:39 -0800266 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800267 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800268 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800269 if self.cancelled(): return False
270 self.reap()
271 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800272 if spec.hash_targets:
Craig Tiller74e770d2015-06-11 09:38:09 -0700273 if spec.identity() in self._hashes:
274 bin_hash = self._hashes[spec.identity()]
275 else:
276 bin_hash = hashlib.sha1()
277 for fn in spec.hash_targets:
278 with open(which(fn)) as f:
279 bin_hash.update(f.read())
280 bin_hash = bin_hash.hexdigest()
281 self._hashes[spec.identity()] = bin_hash
Craig Tiller547db2b2015-01-30 14:08:39 -0800282 should_run = self._cache.should_run(spec.identity(), bin_hash)
283 else:
284 bin_hash = None
285 should_run = True
286 if should_run:
Craig Tillerf53d9c82015-08-04 14:19:43 -0700287 self._running.add(Job(spec,
288 bin_hash,
289 self._newline_on_success,
290 self._travis,
291 self._add_env,
292 self._xml_report))
ctiller3040cb72015-01-07 12:13:17 -0800293 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800294
ctiller3040cb72015-01-07 12:13:17 -0800295 def reap(self):
296 """Collect the dead jobs."""
297 while self._running:
298 dead = set()
299 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800300 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800301 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700302 if st == _FAILURE or st == _KILLED:
303 self._failures += 1
304 if self._stop_on_failure:
305 self._cancelled = True
306 for job in self._running:
307 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800308 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700309 break
ctiller3040cb72015-01-07 12:13:17 -0800310 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800311 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800312 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800313 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100314 if (not self._travis):
315 message('WAITING', '%d jobs running, %d complete, %d failed' % (
316 len(self._running), self._completed, self._failures))
Craig Tiller5058c692015-04-08 09:42:04 -0700317 if platform.system() == 'Windows':
318 time.sleep(0.1)
319 else:
320 global have_alarm
321 if not have_alarm:
322 have_alarm = True
323 signal.alarm(10)
324 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800325
326 def cancelled(self):
327 """Poll for cancellation."""
328 if self._cancelled: return True
329 if not self._check_cancelled(): return False
330 for job in self._running:
331 job.kill()
332 self._cancelled = True
333 return True
334
335 def finish(self):
336 while self._running:
337 if self.cancelled(): pass # poll cancellation
338 self.reap()
339 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800340
341
ctiller3040cb72015-01-07 12:13:17 -0800342def _never_cancelled():
343 return False
344
345
Craig Tiller71735182015-01-15 17:07:13 -0800346# cache class that caches nothing
347class NoCache(object):
348 def should_run(self, cmdline, bin_hash):
349 return True
350
351 def finished(self, cmdline, bin_hash):
352 pass
353
354
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800355def run(cmdlines,
356 check_cancelled=_never_cancelled,
357 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800358 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100359 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700360 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700361 stop_on_failure=False,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200362 cache=None,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700363 xml_report=None,
364 add_env={}):
ctiller94e5dde2015-01-09 10:41:59 -0800365 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800366 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700367 newline_on_success, travis, stop_on_failure, add_env,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200368 cache if cache is not None else NoCache(),
369 xml_report)
Craig Tillerb84728d2015-02-26 15:40:39 -0800370 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800371 if not js.start(cmdline):
372 break
373 return js.finish()