blob: e696a0e9698faa2cdefe971b1067edabf2b9267e [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 Tiller3b083062015-01-12 13:51:28 -080075 }
76
77
78_BEGINNING_OF_LINE = '\x1b[0G'
79_CLEAR_LINE = '\x1b[2K'
80
81
82_TAG_COLOR = {
83 'FAILED': 'red',
Craig Tiller91318bc2015-09-24 08:58:39 -070084 'FLAKE': 'red',
Masood Malekghassemie5f70022015-06-29 09:20:26 -070085 'WARNING': 'yellow',
Craig Tillere1d0d1c2015-02-27 08:54:23 -080086 'TIMEOUT': 'red',
Craig Tiller3b083062015-01-12 13:51:28 -080087 'PASSED': 'green',
Nicolas Noble044db742015-01-14 16:57:24 -080088 'START': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080089 'WAITING': 'yellow',
Nicolas Noble044db742015-01-14 16:57:24 -080090 'SUCCESS': 'green',
91 'IDLE': 'gray',
Craig Tiller3b083062015-01-12 13:51:28 -080092 }
93
94
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +020095def message(tag, msg, explanatory_text=None, do_newline=False):
96 if message.old_tag == tag and message.old_msg == msg and not explanatory_text:
97 return
98 message.old_tag = tag
99 message.old_msg = msg
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800100 try:
Craig Tiller9f3b2d72015-08-25 11:50:57 -0700101 if platform.system() == 'Windows' or not sys.stdout.isatty():
102 if explanatory_text:
103 print explanatory_text
104 print '%s: %s' % (tag, msg)
105 return
vjpaia29d2d72015-07-08 10:31:15 -0700106 sys.stdout.write('%s%s%s\x1b[%d;%dm%s\x1b[0m: %s%s' % (
107 _BEGINNING_OF_LINE,
108 _CLEAR_LINE,
109 '\n%s' % explanatory_text if explanatory_text is not None else '',
110 _COLORS[_TAG_COLOR[tag]][1],
111 _COLORS[_TAG_COLOR[tag]][0],
112 tag,
113 msg,
114 '\n' if do_newline or explanatory_text is not None else ''))
Craig Tiller23d2f3f2015-02-24 15:23:32 -0800115 sys.stdout.flush()
116 except:
117 pass
Craig Tiller3b083062015-01-12 13:51:28 -0800118
Nicolas "Pixel" Noble99768ac2015-05-13 02:34:06 +0200119message.old_tag = ""
120message.old_msg = ""
Craig Tiller3b083062015-01-12 13:51:28 -0800121
Craig Tiller71735182015-01-15 17:07:13 -0800122def which(filename):
123 if '/' in filename:
124 return filename
125 for path in os.environ['PATH'].split(os.pathsep):
126 if os.path.exists(os.path.join(path, filename)):
127 return os.path.join(path, filename)
128 raise Exception('%s not found' % filename)
129
130
Craig Tiller547db2b2015-01-30 14:08:39 -0800131class JobSpec(object):
132 """Specifies what to run for a job."""
133
Jan Tattermusch725835a2015-08-01 21:02:35 -0700134 def __init__(self, cmdline, shortname=None, environ=None, hash_targets=None,
Craig Tiller91318bc2015-09-24 08:58:39 -0700135 cwd=None, shell=False, timeout_seconds=5*60, flake_retries=5):
Craig Tiller547db2b2015-01-30 14:08:39 -0800136 """
137 Arguments:
138 cmdline: a list of arguments to pass as the command line
139 environ: a dictionary of environment variables to set in the child process
140 hash_targets: which files to include in the hash representing the jobs version
141 (or empty, indicating the job should not be hashed)
142 """
murgatroid99132ce6a2015-03-04 17:29:14 -0800143 if environ is None:
144 environ = {}
145 if hash_targets is None:
146 hash_targets = []
Craig Tiller547db2b2015-01-30 14:08:39 -0800147 self.cmdline = cmdline
148 self.environ = environ
149 self.shortname = cmdline[0] if shortname is None else shortname
150 self.hash_targets = hash_targets or []
Craig Tiller5058c692015-04-08 09:42:04 -0700151 self.cwd = cwd
Jan Tattermusche8243592015-04-17 14:14:01 -0700152 self.shell = shell
Jan Tattermusch725835a2015-08-01 21:02:35 -0700153 self.timeout_seconds = timeout_seconds
Craig Tiller91318bc2015-09-24 08:58:39 -0700154 self.flake_retries = flake_retries
Craig Tiller547db2b2015-01-30 14:08:39 -0800155
156 def identity(self):
157 return '%r %r %r' % (self.cmdline, self.environ, self.hash_targets)
158
159 def __hash__(self):
160 return hash(self.identity())
161
162 def __cmp__(self, other):
163 return self.identity() == other.identity()
164
165
ctiller3040cb72015-01-07 12:13:17 -0800166class Job(object):
167 """Manages one job."""
168
Craig Tillerf53d9c82015-08-04 14:19:43 -0700169 def __init__(self, spec, bin_hash, newline_on_success, travis, add_env, xml_report):
Craig Tiller547db2b2015-01-30 14:08:39 -0800170 self._spec = spec
Craig Tiller71735182015-01-15 17:07:13 -0800171 self._bin_hash = bin_hash
Nicolas Noble044db742015-01-14 16:57:24 -0800172 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100173 self._travis = travis
Craig Tiller91318bc2015-09-24 08:58:39 -0700174 self._add_env = add_env.copy()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200175 self._xml_test = ET.SubElement(xml_report, 'testcase',
176 name=self._spec.shortname) if xml_report is not None else None
Craig Tiller91318bc2015-09-24 08:58:39 -0700177 self._retries = 0
Craig Tillerb84728d2015-02-26 15:40:39 -0800178 message('START', spec.shortname, do_newline=self._travis)
Craig Tiller91318bc2015-09-24 08:58:39 -0700179 self.start()
180
181 def start(self):
182 self._tempfile = tempfile.TemporaryFile()
183 env = dict(os.environ)
184 env.update(self._spec.environ)
185 env.update(self._add_env)
186 self._start = time.time()
187 self._process = subprocess.Popen(args=self._spec.cmdline,
188 stderr=subprocess.STDOUT,
189 stdout=self._tempfile,
190 cwd=self._spec.cwd,
191 shell=self._spec.shell,
192 env=env)
193 self._state = _RUNNING
ctiller3040cb72015-01-07 12:13:17 -0800194
Craig Tiller71735182015-01-15 17:07:13 -0800195 def state(self, update_cache):
ctiller3040cb72015-01-07 12:13:17 -0800196 """Poll current state of the job. Prints messages at completion."""
197 if self._state == _RUNNING and self._process.poll() is not None:
Craig Tiller9d6139a2015-02-26 15:24:43 -0800198 elapsed = time.time() - self._start
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200199 self._tempfile.seek(0)
200 stdout = self._tempfile.read()
201 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Nicolas "Pixel" Noble4a5a8f32015-08-13 19:43:00 +0200202 # TODO: looks like jenkins master is slow because parsing the junit results XMLs is not
203 # implemented efficiently. This is an experiment to workaround the issue by making sure
204 # results.xml file is small enough.
205 filtered_stdout = filtered_stdout[-128:]
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200206 if self._xml_test is not None:
207 self._xml_test.set('time', str(elapsed))
208 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
ctiller3040cb72015-01-07 12:13:17 -0800209 if self._process.returncode != 0:
Craig Tiller91318bc2015-09-24 08:58:39 -0700210 if self._retries < self._spec.flake_retries:
211 message('FLAKE', '%s [ret=%d, pid=%d]' % (
Craig Tillerd0ffe142015-05-19 21:51:13 -0700212 self._spec.shortname, self._process.returncode, self._process.pid),
213 stdout, do_newline=True)
Craig Tiller91318bc2015-09-24 08:58:39 -0700214 self._retries += 1
215 self.start()
216 else:
217 self._state = _FAILURE
218 message('FAILED', '%s [ret=%d, pid=%d]' % (
219 self._spec.shortname, self._process.returncode, self._process.pid),
220 stdout, do_newline=True)
221 if self._xml_test is not None:
222 ET.SubElement(self._xml_test, 'failure', message='Failure').text
ctiller3040cb72015-01-07 12:13:17 -0800223 else:
224 self._state = _SUCCESS
Craig Tiller91318bc2015-09-24 08:58:39 -0700225 message('PASSED', '%s [time=%.1fsec; retries=%d]' % (self._spec.shortname, elapsed, self._retries),
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100226 do_newline=self._newline_on_success or self._travis)
Craig Tiller547db2b2015-01-30 14:08:39 -0800227 if self._bin_hash:
228 update_cache.finished(self._spec.identity(), self._bin_hash)
Jan Tattermusch725835a2015-08-01 21:02:35 -0700229 elif self._state == _RUNNING and time.time() - self._start > self._spec.timeout_seconds:
Craig Tiller84216782015-05-12 09:43:54 -0700230 self._tempfile.seek(0)
231 stdout = self._tempfile.read()
Nicolas "Pixel" Noblef716c0c2015-07-12 01:26:17 +0200232 filtered_stdout = filter(lambda x: x in string.printable, stdout.decode(errors='ignore'))
Craig Tiller84216782015-05-12 09:43:54 -0700233 message('TIMEOUT', self._spec.shortname, stdout, do_newline=True)
Craig Tiller9b3cc742015-02-26 22:25:03 -0800234 self.kill()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200235 if self._xml_test is not None:
Nicolas "Pixel" Noblef716c0c2015-07-12 01:26:17 +0200236 ET.SubElement(self._xml_test, 'system-out').text = filtered_stdout
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200237 ET.SubElement(self._xml_test, 'error', message='Timeout')
ctiller3040cb72015-01-07 12:13:17 -0800238 return self._state
239
240 def kill(self):
241 if self._state == _RUNNING:
242 self._state = _KILLED
243 self._process.terminate()
244
245
Nicolas Nobleddef2462015-01-06 18:08:25 -0800246class Jobset(object):
247 """Manages one run of jobs."""
248
Craig Tiller533b1a22015-05-29 08:41:29 -0700249 def __init__(self, check_cancelled, maxjobs, newline_on_success, travis,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700250 stop_on_failure, add_env, cache, xml_report):
ctiller3040cb72015-01-07 12:13:17 -0800251 self._running = set()
252 self._check_cancelled = check_cancelled
253 self._cancelled = False
Nicolas Nobleddef2462015-01-06 18:08:25 -0800254 self._failures = 0
Craig Tiller738c3342015-01-12 14:28:33 -0800255 self._completed = 0
ctiller94e5dde2015-01-09 10:41:59 -0800256 self._maxjobs = maxjobs
Nicolas Noble044db742015-01-14 16:57:24 -0800257 self._newline_on_success = newline_on_success
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100258 self._travis = travis
Craig Tiller71735182015-01-15 17:07:13 -0800259 self._cache = cache
Craig Tiller533b1a22015-05-29 08:41:29 -0700260 self._stop_on_failure = stop_on_failure
Craig Tiller74e770d2015-06-11 09:38:09 -0700261 self._hashes = {}
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200262 self._xml_report = xml_report
Craig Tillerf53d9c82015-08-04 14:19:43 -0700263 self._add_env = add_env
Nicolas Nobleddef2462015-01-06 18:08:25 -0800264
Craig Tiller547db2b2015-01-30 14:08:39 -0800265 def start(self, spec):
ctiller3040cb72015-01-07 12:13:17 -0800266 """Start a job. Return True on success, False on failure."""
ctiller94e5dde2015-01-09 10:41:59 -0800267 while len(self._running) >= self._maxjobs:
ctiller3040cb72015-01-07 12:13:17 -0800268 if self.cancelled(): return False
269 self.reap()
270 if self.cancelled(): return False
Craig Tiller547db2b2015-01-30 14:08:39 -0800271 if spec.hash_targets:
Craig Tiller74e770d2015-06-11 09:38:09 -0700272 if spec.identity() in self._hashes:
273 bin_hash = self._hashes[spec.identity()]
274 else:
275 bin_hash = hashlib.sha1()
276 for fn in spec.hash_targets:
277 with open(which(fn)) as f:
278 bin_hash.update(f.read())
279 bin_hash = bin_hash.hexdigest()
280 self._hashes[spec.identity()] = bin_hash
Craig Tiller547db2b2015-01-30 14:08:39 -0800281 should_run = self._cache.should_run(spec.identity(), bin_hash)
282 else:
283 bin_hash = None
284 should_run = True
285 if should_run:
Craig Tillerf53d9c82015-08-04 14:19:43 -0700286 self._running.add(Job(spec,
287 bin_hash,
288 self._newline_on_success,
289 self._travis,
290 self._add_env,
291 self._xml_report))
ctiller3040cb72015-01-07 12:13:17 -0800292 return True
Nicolas Nobleddef2462015-01-06 18:08:25 -0800293
ctiller3040cb72015-01-07 12:13:17 -0800294 def reap(self):
295 """Collect the dead jobs."""
296 while self._running:
297 dead = set()
298 for job in self._running:
Craig Tiller71735182015-01-15 17:07:13 -0800299 st = job.state(self._cache)
ctiller3040cb72015-01-07 12:13:17 -0800300 if st == _RUNNING: continue
Craig Tiller533b1a22015-05-29 08:41:29 -0700301 if st == _FAILURE or st == _KILLED:
302 self._failures += 1
303 if self._stop_on_failure:
304 self._cancelled = True
305 for job in self._running:
306 job.kill()
ctiller3040cb72015-01-07 12:13:17 -0800307 dead.add(job)
Craig Tiller74e770d2015-06-11 09:38:09 -0700308 break
ctiller3040cb72015-01-07 12:13:17 -0800309 for job in dead:
Craig Tiller738c3342015-01-12 14:28:33 -0800310 self._completed += 1
ctiller3040cb72015-01-07 12:13:17 -0800311 self._running.remove(job)
Craig Tiller3b083062015-01-12 13:51:28 -0800312 if dead: return
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100313 if (not self._travis):
314 message('WAITING', '%d jobs running, %d complete, %d failed' % (
315 len(self._running), self._completed, self._failures))
Craig Tiller5058c692015-04-08 09:42:04 -0700316 if platform.system() == 'Windows':
317 time.sleep(0.1)
318 else:
319 global have_alarm
320 if not have_alarm:
321 have_alarm = True
322 signal.alarm(10)
323 signal.pause()
ctiller3040cb72015-01-07 12:13:17 -0800324
325 def cancelled(self):
326 """Poll for cancellation."""
327 if self._cancelled: return True
328 if not self._check_cancelled(): return False
329 for job in self._running:
330 job.kill()
331 self._cancelled = True
332 return True
333
334 def finish(self):
335 while self._running:
336 if self.cancelled(): pass # poll cancellation
337 self.reap()
338 return not self.cancelled() and self._failures == 0
Nicolas Nobleddef2462015-01-06 18:08:25 -0800339
340
ctiller3040cb72015-01-07 12:13:17 -0800341def _never_cancelled():
342 return False
343
344
Craig Tiller71735182015-01-15 17:07:13 -0800345# cache class that caches nothing
346class NoCache(object):
347 def should_run(self, cmdline, bin_hash):
348 return True
349
350 def finished(self, cmdline, bin_hash):
351 pass
352
353
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800354def run(cmdlines,
355 check_cancelled=_never_cancelled,
356 maxjobs=None,
Craig Tiller71735182015-01-15 17:07:13 -0800357 newline_on_success=False,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100358 travis=False,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700359 infinite_runs=False,
Craig Tiller533b1a22015-05-29 08:41:29 -0700360 stop_on_failure=False,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200361 cache=None,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700362 xml_report=None,
363 add_env={}):
ctiller94e5dde2015-01-09 10:41:59 -0800364 js = Jobset(check_cancelled,
Nicolas Noble044db742015-01-14 16:57:24 -0800365 maxjobs if maxjobs is not None else _DEFAULT_MAX_JOBS,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700366 newline_on_success, travis, stop_on_failure, add_env,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200367 cache if cache is not None else NoCache(),
368 xml_report)
Craig Tillerb84728d2015-02-26 15:40:39 -0800369 for cmdline in cmdlines:
ctiller3040cb72015-01-07 12:13:17 -0800370 if not js.start(cmdline):
371 break
372 return js.finish()