blob: 8e7dd06cad0051ecee16f70cadca5d0911b2967c [file] [log] [blame]
Nicolas Noblef3585732015-03-15 20:05:24 -07001#!/usr/bin/env python
Craig Tillerc2c79212015-02-16 12:00:01 -08002# Copyright 2015, Google Inc.
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met:
8#
9# * Redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer.
11# * Redistributions in binary form must reproduce the above
12# copyright notice, this list of conditions and the following disclaimer
13# in the documentation and/or other materials provided with the
14# distribution.
15# * Neither the name of Google Inc. nor the names of its
16# contributors may be used to endorse or promote products derived from
17# this software without specific prior written permission.
18#
19# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
Nicolas Nobleddef2462015-01-06 18:08:25 -080031"""Run tests in parallel."""
32
33import argparse
34import glob
Craig Tillerf53d9c82015-08-04 14:19:43 -070035import hashlib
Nicolas Nobleddef2462015-01-06 18:08:25 -080036import itertools
Craig Tiller261dd982015-01-16 16:41:45 -080037import json
Nicolas Nobleddef2462015-01-06 18:08:25 -080038import multiprocessing
Craig Tiller1cc11db2015-01-15 22:50:50 -080039import os
David Garcia Quintas79e389f2015-06-02 17:49:42 -070040import platform
41import random
Craig Tillerfe406ec2015-02-24 13:55:12 -080042import re
David Garcia Quintas79e389f2015-06-02 17:49:42 -070043import subprocess
Nicolas Nobleddef2462015-01-06 18:08:25 -080044import sys
ctiller3040cb72015-01-07 12:13:17 -080045import time
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +020046import xml.etree.cElementTree as ET
Craig Tillerf53d9c82015-08-04 14:19:43 -070047import urllib2
Nicolas Nobleddef2462015-01-06 18:08:25 -080048
49import jobset
ctiller3040cb72015-01-07 12:13:17 -080050import watch_dirs
Nicolas Nobleddef2462015-01-06 18:08:25 -080051
Craig Tiller2cc2b842015-02-27 11:38:31 -080052ROOT = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]), '../..'))
53os.chdir(ROOT)
54
55
Craig Tiller06805272015-06-11 14:46:47 -070056_FORCE_ENVIRON_FOR_WRAPPERS = {}
57
58
Craig Tillerd50993d2015-08-05 08:04:36 -070059def platform_string():
60 if platform.system() == 'Windows':
61 return 'windows'
62 elif platform.system() == 'Darwin':
63 return 'mac'
64 elif platform.system() == 'Linux':
65 return 'linux'
66 else:
67 return 'posix'
68
69
Craig Tiller738c3342015-01-12 14:28:33 -080070# SimpleConfig: just compile with CONFIG=config, and run the binary to test
71class SimpleConfig(object):
Craig Tillerb50d1662015-01-15 17:28:21 -080072
Craig Tillerb2ea0b92015-08-26 13:06:53 -070073 def __init__(self, config, environ=None, timeout_seconds=5*60):
murgatroid99132ce6a2015-03-04 17:29:14 -080074 if environ is None:
75 environ = {}
Craig Tiller738c3342015-01-12 14:28:33 -080076 self.build_config = config
Craig Tillerc7449162015-01-16 14:42:10 -080077 self.allow_hashing = (config != 'gcov')
Craig Tiller547db2b2015-01-30 14:08:39 -080078 self.environ = environ
murgatroid99132ce6a2015-03-04 17:29:14 -080079 self.environ['CONFIG'] = config
Craig Tillerb2ea0b92015-08-26 13:06:53 -070080 self.timeout_seconds = timeout_seconds
Craig Tiller738c3342015-01-12 14:28:33 -080081
Craig Tiller4fc90032015-05-21 10:39:52 -070082 def job_spec(self, cmdline, hash_targets, shortname=None, environ={}):
Craig Tiller49f61322015-03-03 13:02:11 -080083 """Construct a jobset.JobSpec for a test under this config
84
85 Args:
86 cmdline: a list of strings specifying the command line the test
87 would like to run
88 hash_targets: either None (don't do caching of test results), or
89 a list of strings specifying files to include in a
90 binary hash to check if a test has changed
91 -- if used, all artifacts needed to run the test must
92 be listed
93 """
Craig Tiller4fc90032015-05-21 10:39:52 -070094 actual_environ = self.environ.copy()
95 for k, v in environ.iteritems():
96 actual_environ[k] = v
Craig Tiller49f61322015-03-03 13:02:11 -080097 return jobset.JobSpec(cmdline=cmdline,
Jan Tattermusch9a7d30c2015-04-23 16:12:55 -070098 shortname=shortname,
Craig Tiller4fc90032015-05-21 10:39:52 -070099 environ=actual_environ,
Craig Tillerb2ea0b92015-08-26 13:06:53 -0700100 timeout_seconds=self.timeout_seconds,
Craig Tiller547db2b2015-01-30 14:08:39 -0800101 hash_targets=hash_targets
102 if self.allow_hashing else None)
Craig Tiller738c3342015-01-12 14:28:33 -0800103
104
105# ValgrindConfig: compile with some CONFIG=config, but use valgrind to run
106class ValgrindConfig(object):
Craig Tillerb50d1662015-01-15 17:28:21 -0800107
murgatroid99132ce6a2015-03-04 17:29:14 -0800108 def __init__(self, config, tool, args=None):
109 if args is None:
110 args = []
Craig Tiller738c3342015-01-12 14:28:33 -0800111 self.build_config = config
Craig Tiller2aa4d642015-01-14 15:59:44 -0800112 self.tool = tool
Craig Tiller1a305b12015-02-18 13:37:06 -0800113 self.args = args
Craig Tillerc7449162015-01-16 14:42:10 -0800114 self.allow_hashing = False
Craig Tiller738c3342015-01-12 14:28:33 -0800115
Craig Tiller49f61322015-03-03 13:02:11 -0800116 def job_spec(self, cmdline, hash_targets):
Craig Tiller1a305b12015-02-18 13:37:06 -0800117 return jobset.JobSpec(cmdline=['valgrind', '--tool=%s' % self.tool] +
Craig Tiller49f61322015-03-03 13:02:11 -0800118 self.args + cmdline,
Craig Tiller71ec6cb2015-06-03 00:51:11 -0700119 shortname='valgrind %s' % cmdline[0],
Craig Tiller1a305b12015-02-18 13:37:06 -0800120 hash_targets=None)
Craig Tiller738c3342015-01-12 14:28:33 -0800121
122
Craig Tillerc7449162015-01-16 14:42:10 -0800123class CLanguage(object):
124
Craig Tillere9c959d2015-01-18 10:23:26 -0800125 def __init__(self, make_target, test_lang):
Craig Tillerc7449162015-01-16 14:42:10 -0800126 self.make_target = make_target
Craig Tillerd50993d2015-08-05 08:04:36 -0700127 self.platform = platform_string()
Craig Tiller711bbe62015-08-19 12:35:16 -0700128 self.test_lang = test_lang
Craig Tillerc7449162015-01-16 14:42:10 -0800129
Nicolas "Pixel" Noble9db7c3b2015-02-27 06:03:00 +0100130 def test_specs(self, config, travis):
Craig Tiller547db2b2015-01-30 14:08:39 -0800131 out = []
Craig Tiller711bbe62015-08-19 12:35:16 -0700132 with open('tools/run_tests/tests.json') as f:
133 js = json.load(f)
134 platforms_str = 'ci_platforms' if travis else 'platforms'
135 binaries = [tgt
136 for tgt in js
137 if tgt['language'] == self.test_lang and
138 config.build_config not in tgt['exclude_configs'] and
139 platform_string() in tgt[platforms_str]]
140 for target in binaries:
Nicolas "Pixel" Noble9db7c3b2015-02-27 06:03:00 +0100141 if travis and target['flaky']:
142 continue
Nicolas Noblee1445362015-05-11 17:40:26 -0700143 if self.platform == 'windows':
Jan Tattermusch12e8a042015-06-15 17:07:14 -0700144 binary = 'vsprojects/test_bin/%s.exe' % (target['name'])
Nicolas Noblee1445362015-05-11 17:40:26 -0700145 else:
146 binary = 'bins/%s/%s' % (config.build_config, target['name'])
yang-g6c1fdc62015-08-18 11:57:42 -0700147 if os.path.isfile(binary):
148 out.append(config.job_spec([binary], [binary]))
149 else:
150 print "\nWARNING: binary not found, skipping", binary
Nicolas Noblee1445362015-05-11 17:40:26 -0700151 return sorted(out)
Craig Tillerc7449162015-01-16 14:42:10 -0800152
153 def make_targets(self):
Craig Tiller7552f0f2015-06-19 17:46:20 -0700154 return ['buildtests_%s' % self.make_target, 'tools_%s' % self.make_target]
Craig Tillerc7449162015-01-16 14:42:10 -0800155
156 def build_steps(self):
157 return []
158
murgatroid99132ce6a2015-03-04 17:29:14 -0800159 def supports_multi_config(self):
160 return True
161
162 def __str__(self):
163 return self.make_target
164
Craig Tiller99775822015-01-30 13:07:16 -0800165
murgatroid992c8d5162015-01-26 10:41:21 -0800166class NodeLanguage(object):
167
Nicolas "Pixel" Noble9db7c3b2015-02-27 06:03:00 +0100168 def test_specs(self, config, travis):
Craig Tiller4fc90032015-05-21 10:39:52 -0700169 return [config.job_spec(['tools/run_tests/run_node.sh'], None,
Craig Tiller06805272015-06-11 14:46:47 -0700170 environ=_FORCE_ENVIRON_FOR_WRAPPERS)]
murgatroid992c8d5162015-01-26 10:41:21 -0800171
172 def make_targets(self):
Craig Tilleraf7cf542015-05-22 10:07:34 -0700173 return ['static_c', 'shared_c']
murgatroid992c8d5162015-01-26 10:41:21 -0800174
175 def build_steps(self):
176 return [['tools/run_tests/build_node.sh']]
Craig Tillerc7449162015-01-16 14:42:10 -0800177
murgatroid99132ce6a2015-03-04 17:29:14 -0800178 def supports_multi_config(self):
179 return False
180
181 def __str__(self):
182 return 'node'
183
Craig Tiller99775822015-01-30 13:07:16 -0800184
Craig Tillerc7449162015-01-16 14:42:10 -0800185class PhpLanguage(object):
186
Nicolas "Pixel" Noble9db7c3b2015-02-27 06:03:00 +0100187 def test_specs(self, config, travis):
Craig Tiller4fc90032015-05-21 10:39:52 -0700188 return [config.job_spec(['src/php/bin/run_tests.sh'], None,
Craig Tiller06805272015-06-11 14:46:47 -0700189 environ=_FORCE_ENVIRON_FOR_WRAPPERS)]
Craig Tillerc7449162015-01-16 14:42:10 -0800190
191 def make_targets(self):
Craig Tilleraf7cf542015-05-22 10:07:34 -0700192 return ['static_c', 'shared_c']
Craig Tillerc7449162015-01-16 14:42:10 -0800193
194 def build_steps(self):
195 return [['tools/run_tests/build_php.sh']]
196
murgatroid99132ce6a2015-03-04 17:29:14 -0800197 def supports_multi_config(self):
198 return False
199
200 def __str__(self):
201 return 'php'
202
Craig Tillerc7449162015-01-16 14:42:10 -0800203
Nathaniel Manista840615e2015-01-22 20:31:47 +0000204class PythonLanguage(object):
205
Craig Tiller49f61322015-03-03 13:02:11 -0800206 def __init__(self):
Masood Malekghassemi2b841622015-07-28 17:39:02 -0700207 self._build_python_versions = ['2.7']
Masood Malekghassemie5f70022015-06-29 09:20:26 -0700208 self._has_python_versions = []
Craig Tiller49f61322015-03-03 13:02:11 -0800209
Nicolas "Pixel" Noble9db7c3b2015-02-27 06:03:00 +0100210 def test_specs(self, config, travis):
Masood Malekghassemi2b841622015-07-28 17:39:02 -0700211 environment = dict(_FORCE_ENVIRON_FOR_WRAPPERS)
212 environment['PYVER'] = '2.7'
213 return [config.job_spec(
214 ['tools/run_tests/run_python.sh'],
215 None,
216 environ=environment,
217 shortname='py.test',
218 )]
Nathaniel Manista840615e2015-01-22 20:31:47 +0000219
220 def make_targets(self):
Craig Tilleraf7cf542015-05-22 10:07:34 -0700221 return ['static_c', 'grpc_python_plugin', 'shared_c']
Nathaniel Manista840615e2015-01-22 20:31:47 +0000222
223 def build_steps(self):
Masood Malekghassemie5f70022015-06-29 09:20:26 -0700224 commands = []
225 for python_version in self._build_python_versions:
226 try:
227 with open(os.devnull, 'w') as output:
228 subprocess.check_call(['which', 'python' + python_version],
229 stdout=output, stderr=output)
230 commands.append(['tools/run_tests/build_python.sh', python_version])
231 self._has_python_versions.append(python_version)
232 except:
233 jobset.message('WARNING', 'Missing Python ' + python_version,
234 do_newline=True)
235 return commands
Nathaniel Manista840615e2015-01-22 20:31:47 +0000236
murgatroid99132ce6a2015-03-04 17:29:14 -0800237 def supports_multi_config(self):
238 return False
239
240 def __str__(self):
241 return 'python'
242
Craig Tillerd625d812015-04-08 15:52:35 -0700243
murgatroid996a4c4fa2015-02-27 12:08:57 -0800244class RubyLanguage(object):
245
246 def test_specs(self, config, travis):
Craig Tiller4fc90032015-05-21 10:39:52 -0700247 return [config.job_spec(['tools/run_tests/run_ruby.sh'], None,
Craig Tiller06805272015-06-11 14:46:47 -0700248 environ=_FORCE_ENVIRON_FOR_WRAPPERS)]
murgatroid996a4c4fa2015-02-27 12:08:57 -0800249
250 def make_targets(self):
murgatroid99a43c14f2015-07-30 13:31:23 -0700251 return ['static_c']
murgatroid996a4c4fa2015-02-27 12:08:57 -0800252
253 def build_steps(self):
254 return [['tools/run_tests/build_ruby.sh']]
255
murgatroid99132ce6a2015-03-04 17:29:14 -0800256 def supports_multi_config(self):
257 return False
258
259 def __str__(self):
260 return 'ruby'
261
Craig Tillerd625d812015-04-08 15:52:35 -0700262
Jan Tattermusch1970a5b2015-03-03 15:17:25 -0800263class CSharpLanguage(object):
Jan Tattermuschb00aa672015-06-01 15:48:03 -0700264 def __init__(self):
Craig Tillerd50993d2015-08-05 08:04:36 -0700265 self.platform = platform_string()
Jan Tattermuschb00aa672015-06-01 15:48:03 -0700266
Jan Tattermusch1970a5b2015-03-03 15:17:25 -0800267 def test_specs(self, config, travis):
Jan Tattermusch9a7d30c2015-04-23 16:12:55 -0700268 assemblies = ['Grpc.Core.Tests',
269 'Grpc.Examples.Tests',
Jan Tattermusch9d67d8d2015-08-01 20:39:16 -0700270 'Grpc.HealthCheck.Tests',
Jan Tattermusch9a7d30c2015-04-23 16:12:55 -0700271 'Grpc.IntegrationTesting']
Jan Tattermuschb00aa672015-06-01 15:48:03 -0700272 if self.platform == 'windows':
273 cmd = 'tools\\run_tests\\run_csharp.bat'
274 else:
275 cmd = 'tools/run_tests/run_csharp.sh'
276 return [config.job_spec([cmd, assembly],
Craig Tiller4fc90032015-05-21 10:39:52 -0700277 None, shortname=assembly,
Craig Tiller06805272015-06-11 14:46:47 -0700278 environ=_FORCE_ENVIRON_FOR_WRAPPERS)
Craig Tillerd50993d2015-08-05 08:04:36 -0700279 for assembly in assemblies]
Jan Tattermusch1970a5b2015-03-03 15:17:25 -0800280
281 def make_targets(self):
Jan Tattermuschb00aa672015-06-01 15:48:03 -0700282 # For Windows, this target doesn't really build anything,
283 # everything is build by buildall script later.
Craig Tillerd5904822015-08-31 21:30:58 -0700284 if self.platform == 'windows':
285 return []
286 else:
287 return ['grpc_csharp_ext']
Jan Tattermusch1970a5b2015-03-03 15:17:25 -0800288
289 def build_steps(self):
Jan Tattermuschb00aa672015-06-01 15:48:03 -0700290 if self.platform == 'windows':
291 return [['src\\csharp\\buildall.bat']]
292 else:
293 return [['tools/run_tests/build_csharp.sh']]
Nathaniel Manista840615e2015-01-22 20:31:47 +0000294
murgatroid99132ce6a2015-03-04 17:29:14 -0800295 def supports_multi_config(self):
296 return False
297
298 def __str__(self):
299 return 'csharp'
300
Craig Tillerd625d812015-04-08 15:52:35 -0700301
Jorge Canizalesa0b3bfa2015-07-30 19:25:52 -0700302class ObjCLanguage(object):
303
304 def test_specs(self, config, travis):
305 return [config.job_spec(['src/objective-c/tests/run_tests.sh'], None,
306 environ=_FORCE_ENVIRON_FOR_WRAPPERS)]
307
308 def make_targets(self):
Jorge Canizalesd0b32e92015-07-30 23:08:43 -0700309 return ['grpc_objective_c_plugin', 'interop_server']
Jorge Canizalesa0b3bfa2015-07-30 19:25:52 -0700310
311 def build_steps(self):
Jorge Canizalesd0b32e92015-07-30 23:08:43 -0700312 return [['src/objective-c/tests/build_tests.sh']]
Jorge Canizalesa0b3bfa2015-07-30 19:25:52 -0700313
314 def supports_multi_config(self):
315 return False
316
317 def __str__(self):
318 return 'objc'
319
320
Nicolas "Pixel" Noble9f728642015-03-24 18:50:30 +0100321class Sanity(object):
322
323 def test_specs(self, config, travis):
Craig Tillerf75fc122015-06-25 06:58:00 -0700324 return [config.job_spec('tools/run_tests/run_sanity.sh', None),
325 config.job_spec('tools/run_tests/check_sources_and_headers.py', None)]
Nicolas "Pixel" Noble9f728642015-03-24 18:50:30 +0100326
327 def make_targets(self):
328 return ['run_dep_checks']
329
330 def build_steps(self):
331 return []
332
333 def supports_multi_config(self):
334 return False
335
336 def __str__(self):
337 return 'sanity'
338
Nicolas "Pixel" Noblee55cd7f2015-04-14 17:59:13 +0200339
Nicolas "Pixel" Noblefd2b0932015-03-26 00:26:29 +0100340class Build(object):
341
342 def test_specs(self, config, travis):
343 return []
344
345 def make_targets(self):
Nicolas "Pixel" Noblec23827b2015-04-23 06:17:55 +0200346 return ['static']
Nicolas "Pixel" Noblefd2b0932015-03-26 00:26:29 +0100347
348 def build_steps(self):
349 return []
350
351 def supports_multi_config(self):
352 return True
353
354 def __str__(self):
355 return self.make_target
356
357
Craig Tiller738c3342015-01-12 14:28:33 -0800358# different configurations we can run under
359_CONFIGS = {
Craig Tillerb50d1662015-01-15 17:28:21 -0800360 'dbg': SimpleConfig('dbg'),
361 'opt': SimpleConfig('opt'),
Craig Tillerb2ea0b92015-08-26 13:06:53 -0700362 'tsan': SimpleConfig('tsan', timeout_seconds=10*60, environ={
Craig Tiller1ada6ad2015-07-16 16:19:14 -0700363 'TSAN_OPTIONS': 'suppressions=tools/tsan_suppressions.txt:halt_on_error=1:second_deadlock_stack=1'}),
Craig Tiller4a71ce22015-08-26 15:47:55 -0700364 'msan': SimpleConfig('msan', timeout_seconds=7*60),
Craig Tiller96bd5f62015-02-13 09:04:13 -0800365 'ubsan': SimpleConfig('ubsan'),
Craig Tillerb2ea0b92015-08-26 13:06:53 -0700366 'asan': SimpleConfig('asan', timeout_seconds=7*60, environ={
Craig Tillerd4b13622015-05-29 09:10:10 -0700367 'ASAN_OPTIONS': 'detect_leaks=1:color=always:suppressions=tools/tsan_suppressions.txt',
368 'LSAN_OPTIONS': 'report_objects=1'}),
Craig Tiller810725c2015-05-12 09:44:41 -0700369 'asan-noleaks': SimpleConfig('asan', environ={
370 'ASAN_OPTIONS': 'detect_leaks=0:color=always:suppressions=tools/tsan_suppressions.txt'}),
Craig Tillerb50d1662015-01-15 17:28:21 -0800371 'gcov': SimpleConfig('gcov'),
Craig Tiller1a305b12015-02-18 13:37:06 -0800372 'memcheck': ValgrindConfig('valgrind', 'memcheck', ['--leak-check=full']),
Craig Tillerb50d1662015-01-15 17:28:21 -0800373 'helgrind': ValgrindConfig('dbg', 'helgrind')
374 }
Craig Tiller738c3342015-01-12 14:28:33 -0800375
376
Nicolas "Pixel" Noble1fb5e822015-03-16 06:20:37 +0100377_DEFAULT = ['opt']
Craig Tillerc7449162015-01-16 14:42:10 -0800378_LANGUAGES = {
Craig Tillere9c959d2015-01-18 10:23:26 -0800379 'c++': CLanguage('cxx', 'c++'),
380 'c': CLanguage('c', 'c'),
murgatroid992c8d5162015-01-26 10:41:21 -0800381 'node': NodeLanguage(),
Nathaniel Manista840615e2015-01-22 20:31:47 +0000382 'php': PhpLanguage(),
383 'python': PythonLanguage(),
Jan Tattermusch1970a5b2015-03-03 15:17:25 -0800384 'ruby': RubyLanguage(),
Nicolas "Pixel" Noble9f728642015-03-24 18:50:30 +0100385 'csharp': CSharpLanguage(),
Jorge Canizalesa0b3bfa2015-07-30 19:25:52 -0700386 'objc' : ObjCLanguage(),
Nicolas "Pixel" Noble9f728642015-03-24 18:50:30 +0100387 'sanity': Sanity(),
Nicolas "Pixel" Noblefd2b0932015-03-26 00:26:29 +0100388 'build': Build(),
Craig Tillereb272bc2015-01-30 13:13:14 -0800389 }
Nicolas Nobleddef2462015-01-06 18:08:25 -0800390
391# parse command line
392argp = argparse.ArgumentParser(description='Run grpc tests.')
393argp.add_argument('-c', '--config',
Craig Tiller738c3342015-01-12 14:28:33 -0800394 choices=['all'] + sorted(_CONFIGS.keys()),
Nicolas Nobleddef2462015-01-06 18:08:25 -0800395 nargs='+',
Craig Tillerb29797b2015-01-12 13:51:54 -0800396 default=_DEFAULT)
David Garcia Quintase90cd372015-05-31 18:15:26 -0700397
398def runs_per_test_type(arg_str):
399 """Auxilary function to parse the "runs_per_test" flag.
400
401 Returns:
402 A positive integer or 0, the latter indicating an infinite number of
403 runs.
404
405 Raises:
406 argparse.ArgumentTypeError: Upon invalid input.
407 """
408 if arg_str == 'inf':
409 return 0
410 try:
411 n = int(arg_str)
412 if n <= 0: raise ValueError
Craig Tiller50e53e22015-06-01 20:18:21 -0700413 return n
David Garcia Quintase90cd372015-05-31 18:15:26 -0700414 except:
415 msg = "'{}' isn't a positive integer or 'inf'".format(arg_str)
416 raise argparse.ArgumentTypeError(msg)
417argp.add_argument('-n', '--runs_per_test', default=1, type=runs_per_test_type,
418 help='A positive integer or "inf". If "inf", all tests will run in an '
419 'infinite loop. Especially useful in combination with "-f"')
Craig Tillerfe406ec2015-02-24 13:55:12 -0800420argp.add_argument('-r', '--regex', default='.*', type=str)
Craig Tiller83762ac2015-05-22 14:04:06 -0700421argp.add_argument('-j', '--jobs', default=2 * multiprocessing.cpu_count(), type=int)
Craig Tiller8451e872015-02-27 09:25:51 -0800422argp.add_argument('-s', '--slowdown', default=1.0, type=float)
ctiller3040cb72015-01-07 12:13:17 -0800423argp.add_argument('-f', '--forever',
424 default=False,
425 action='store_const',
426 const=True)
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100427argp.add_argument('-t', '--travis',
428 default=False,
429 action='store_const',
430 const=True)
Nicolas Noble044db742015-01-14 16:57:24 -0800431argp.add_argument('--newline_on_success',
432 default=False,
433 action='store_const',
434 const=True)
Craig Tiller686fb262015-01-15 07:39:09 -0800435argp.add_argument('-l', '--language',
Craig Tiller60f15e62015-05-13 09:05:17 -0700436 choices=['all'] + sorted(_LANGUAGES.keys()),
Craig Tiller686fb262015-01-15 07:39:09 -0800437 nargs='+',
Craig Tiller60f15e62015-05-13 09:05:17 -0700438 default=['all'])
Craig Tillercd43da82015-05-29 08:41:29 -0700439argp.add_argument('-S', '--stop_on_failure',
440 default=False,
441 action='store_const',
442 const=True)
Craig Tiller234b6e72015-05-23 10:12:40 -0700443argp.add_argument('-a', '--antagonists', default=0, type=int)
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200444argp.add_argument('-x', '--xml_report', default=None, type=str,
445 help='Generates a JUnit-compatible XML report')
Nicolas Nobleddef2462015-01-06 18:08:25 -0800446args = argp.parse_args()
447
448# grab config
Craig Tiller738c3342015-01-12 14:28:33 -0800449run_configs = set(_CONFIGS[cfg]
450 for cfg in itertools.chain.from_iterable(
451 _CONFIGS.iterkeys() if x == 'all' else [x]
452 for x in args.config))
453build_configs = set(cfg.build_config for cfg in run_configs)
Craig Tillerf1973b02015-01-16 12:32:13 -0800454
Craig Tiller06805272015-06-11 14:46:47 -0700455if args.travis:
456 _FORCE_ENVIRON_FOR_WRAPPERS = {'GRPC_TRACE': 'surface,batch'}
457
Craig Tiller60f15e62015-05-13 09:05:17 -0700458languages = set(_LANGUAGES[l]
459 for l in itertools.chain.from_iterable(
460 _LANGUAGES.iterkeys() if x == 'all' else [x]
461 for x in args.language))
murgatroid99132ce6a2015-03-04 17:29:14 -0800462
463if len(build_configs) > 1:
464 for language in languages:
465 if not language.supports_multi_config():
466 print language, 'does not support multiple build configurations'
467 sys.exit(1)
468
Craig Tiller5058c692015-04-08 09:42:04 -0700469if platform.system() == 'Windows':
470 def make_jobspec(cfg, targets):
Jan Tattermusche8243592015-04-17 14:14:01 -0700471 return jobset.JobSpec(['make.bat', 'CONFIG=%s' % cfg] + targets,
Craig Tillere6942642015-08-25 14:24:28 -0700472 cwd='vsprojects', shell=True,
473 timeout_seconds=30*60)
Craig Tiller5058c692015-04-08 09:42:04 -0700474else:
475 def make_jobspec(cfg, targets):
Nicolas "Pixel" Noble4243ca82015-07-23 23:47:56 +0200476 return jobset.JobSpec([os.getenv('MAKE', 'make'),
Craig Tiller5058c692015-04-08 09:42:04 -0700477 '-j', '%d' % (multiprocessing.cpu_count() + 1),
Craig Tiller533b1a22015-05-29 08:41:29 -0700478 'EXTRA_DEFINES=GRPC_TEST_SLOWDOWN_MACHINE_FACTOR=%f' %
Craig Tiller5058c692015-04-08 09:42:04 -0700479 args.slowdown,
Craig Tillerdb0d2342015-08-05 07:47:35 -0700480 'CONFIG=%s' % cfg] + targets,
481 timeout_seconds=30*60)
Craig Tiller5058c692015-04-08 09:42:04 -0700482
Craig Tillerbd4e3782015-09-01 06:48:55 -0700483make_targets = list(set(itertools.chain.from_iterable(
484 l.make_targets() for l in languages)))
485build_steps = []
486if make_targets:
487 build_steps.extend(set(make_jobspec(cfg, make_targets)
488 for cfg in build_configs))
Craig Tiller5058c692015-04-08 09:42:04 -0700489build_steps.extend(set(
murgatroid99132ce6a2015-03-04 17:29:14 -0800490 jobset.JobSpec(cmdline, environ={'CONFIG': cfg})
491 for cfg in build_configs
Craig Tiller547db2b2015-01-30 14:08:39 -0800492 for l in languages
Craig Tiller533b1a22015-05-29 08:41:29 -0700493 for cmdline in l.build_steps()))
Craig Tillerf1973b02015-01-16 12:32:13 -0800494
Nicolas Nobleddef2462015-01-06 18:08:25 -0800495runs_per_test = args.runs_per_test
ctiller3040cb72015-01-07 12:13:17 -0800496forever = args.forever
Nicolas Nobleddef2462015-01-06 18:08:25 -0800497
Nicolas Nobleddef2462015-01-06 18:08:25 -0800498
Craig Tiller71735182015-01-15 17:07:13 -0800499class TestCache(object):
Craig Tillerb50d1662015-01-15 17:28:21 -0800500 """Cache for running tests."""
501
David Klempner25739582015-02-11 15:57:32 -0800502 def __init__(self, use_cache_results):
Craig Tiller71735182015-01-15 17:07:13 -0800503 self._last_successful_run = {}
David Klempner25739582015-02-11 15:57:32 -0800504 self._use_cache_results = use_cache_results
Craig Tiller69cd2372015-06-11 09:38:09 -0700505 self._last_save = time.time()
Craig Tiller71735182015-01-15 17:07:13 -0800506
507 def should_run(self, cmdline, bin_hash):
Craig Tiller71735182015-01-15 17:07:13 -0800508 if cmdline not in self._last_successful_run:
509 return True
510 if self._last_successful_run[cmdline] != bin_hash:
511 return True
David Klempner25739582015-02-11 15:57:32 -0800512 if not self._use_cache_results:
513 return True
Craig Tiller71735182015-01-15 17:07:13 -0800514 return False
515
516 def finished(self, cmdline, bin_hash):
Craig Tiller547db2b2015-01-30 14:08:39 -0800517 self._last_successful_run[cmdline] = bin_hash
Craig Tiller69cd2372015-06-11 09:38:09 -0700518 if time.time() - self._last_save > 1:
519 self.save()
Craig Tiller71735182015-01-15 17:07:13 -0800520
521 def dump(self):
Craig Tillerb50d1662015-01-15 17:28:21 -0800522 return [{'cmdline': k, 'hash': v}
523 for k, v in self._last_successful_run.iteritems()]
Craig Tiller71735182015-01-15 17:07:13 -0800524
525 def parse(self, exdump):
526 self._last_successful_run = dict((o['cmdline'], o['hash']) for o in exdump)
527
528 def save(self):
529 with open('.run_tests_cache', 'w') as f:
Craig Tiller261dd982015-01-16 16:41:45 -0800530 f.write(json.dumps(self.dump()))
Craig Tiller69cd2372015-06-11 09:38:09 -0700531 self._last_save = time.time()
Craig Tiller71735182015-01-15 17:07:13 -0800532
Craig Tiller1cc11db2015-01-15 22:50:50 -0800533 def maybe_load(self):
534 if os.path.exists('.run_tests_cache'):
535 with open('.run_tests_cache') as f:
Craig Tiller261dd982015-01-16 16:41:45 -0800536 self.parse(json.loads(f.read()))
Craig Tiller71735182015-01-15 17:07:13 -0800537
538
Craig Tillerf53d9c82015-08-04 14:19:43 -0700539def _start_port_server(port_server_port):
540 # check if a compatible port server is running
541 # if incompatible (version mismatch) ==> start a new one
542 # if not running ==> start a new one
543 # otherwise, leave it up
544 try:
Craig Tillerabd37fd2015-08-26 07:54:01 -0700545 version = urllib2.urlopen('http://localhost:%d/version' % port_server_port,
546 timeout=1).read()
Craig Tillerf53d9c82015-08-04 14:19:43 -0700547 running = True
548 except Exception:
549 running = False
550 if running:
551 with open('tools/run_tests/port_server.py') as f:
552 current_version = hashlib.sha1(f.read()).hexdigest()
553 running = (version == current_version)
554 if not running:
Craig Tilleref125592015-08-05 07:41:35 -0700555 urllib2.urlopen('http://localhost:%d/quit' % port_server_port).read()
556 time.sleep(1)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700557 if not running:
558 port_log = open('portlog.txt', 'w')
559 port_server = subprocess.Popen(
Craig Tiller9a0c10e2015-08-06 15:47:32 -0700560 ['python', 'tools/run_tests/port_server.py', '-p', '%d' % port_server_port],
Craig Tillerf53d9c82015-08-04 14:19:43 -0700561 stderr=subprocess.STDOUT,
562 stdout=port_log)
Craig Tiller8b5f4dc2015-08-26 08:02:01 -0700563 # ensure port server is up
Craig Tillerabd37fd2015-08-26 07:54:01 -0700564 waits = 0
Craig Tillerf53d9c82015-08-04 14:19:43 -0700565 while True:
Craig Tillerabd37fd2015-08-26 07:54:01 -0700566 if waits > 10:
567 port_server.kill()
568 print "port_server failed to start"
569 sys.exit(1)
Craig Tillerf53d9c82015-08-04 14:19:43 -0700570 try:
Craig Tillerabd37fd2015-08-26 07:54:01 -0700571 urllib2.urlopen('http://localhost:%d/get' % port_server_port,
572 timeout=1).read()
Craig Tillerf53d9c82015-08-04 14:19:43 -0700573 break
574 except urllib2.URLError:
Craig Tillerabd37fd2015-08-26 07:54:01 -0700575 print "waiting for port_server"
Craig Tillerf53d9c82015-08-04 14:19:43 -0700576 time.sleep(0.5)
Craig Tillerabd37fd2015-08-26 07:54:01 -0700577 waits += 1
Craig Tillerf53d9c82015-08-04 14:19:43 -0700578 except:
579 port_server.kill()
580 raise
581
582
583def _build_and_run(
584 check_cancelled, newline_on_success, travis, cache, xml_report=None):
ctiller3040cb72015-01-07 12:13:17 -0800585 """Do one pass of building & running tests."""
murgatroid99666450e2015-01-26 13:03:31 -0800586 # build latest sequentially
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100587 if not jobset.run(build_steps, maxjobs=1,
588 newline_on_success=newline_on_success, travis=travis):
Craig Tillerd86a3942015-01-14 12:48:54 -0800589 return 1
ctiller3040cb72015-01-07 12:13:17 -0800590
Craig Tiller234b6e72015-05-23 10:12:40 -0700591 # start antagonists
David Garcia Quintas79e389f2015-06-02 17:49:42 -0700592 antagonists = [subprocess.Popen(['tools/run_tests/antagonist.py'])
Craig Tiller234b6e72015-05-23 10:12:40 -0700593 for _ in range(0, args.antagonists)]
Craig Tillerf53d9c82015-08-04 14:19:43 -0700594 port_server_port = 9999
595 _start_port_server(port_server_port)
Craig Tiller234b6e72015-05-23 10:12:40 -0700596 try:
David Garcia Quintase90cd372015-05-31 18:15:26 -0700597 infinite_runs = runs_per_test == 0
yang-g6c1fdc62015-08-18 11:57:42 -0700598 one_run = set(
599 spec
600 for config in run_configs
601 for language in languages
602 for spec in language.test_specs(config, args.travis)
603 if re.search(args.regex, spec.shortname))
David Garcia Quintas79e389f2015-06-02 17:49:42 -0700604 # When running on travis, we want out test runs to be as similar as possible
605 # for reproducibility purposes.
606 if travis:
607 massaged_one_run = sorted(one_run, key=lambda x: x.shortname)
608 else:
609 # whereas otherwise, we want to shuffle things up to give all tests a
610 # chance to run.
611 massaged_one_run = list(one_run) # random.shuffle needs an indexable seq.
612 random.shuffle(massaged_one_run) # which it modifies in-place.
Craig Tillerf7b7c892015-06-22 14:33:25 -0700613 if infinite_runs:
614 assert len(massaged_one_run) > 0, 'Must have at least one test for a -n inf run'
David Garcia Quintas79e389f2015-06-02 17:49:42 -0700615 runs_sequence = (itertools.repeat(massaged_one_run) if infinite_runs
616 else itertools.repeat(massaged_one_run, runs_per_test))
David Garcia Quintase90cd372015-05-31 18:15:26 -0700617 all_runs = itertools.chain.from_iterable(runs_sequence)
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200618
619 root = ET.Element('testsuites') if xml_report else None
620 testsuite = ET.SubElement(root, 'testsuite', id='1', package='grpc', name='tests') if xml_report else None
621
Craig Tiller234b6e72015-05-23 10:12:40 -0700622 if not jobset.run(all_runs, check_cancelled,
623 newline_on_success=newline_on_success, travis=travis,
David Garcia Quintase90cd372015-05-31 18:15:26 -0700624 infinite_runs=infinite_runs,
Craig Tillerda2220a2015-05-27 07:50:53 -0700625 maxjobs=args.jobs,
Craig Tillercd43da82015-05-29 08:41:29 -0700626 stop_on_failure=args.stop_on_failure,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200627 cache=cache if not xml_report else None,
Craig Tillerf53d9c82015-08-04 14:19:43 -0700628 xml_report=testsuite,
629 add_env={'GRPC_TEST_PORT_SERVER': 'localhost:%d' % port_server_port}):
Craig Tiller234b6e72015-05-23 10:12:40 -0700630 return 2
631 finally:
632 for antagonist in antagonists:
633 antagonist.kill()
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200634 if xml_report:
635 tree = ET.ElementTree(root)
636 tree.write(xml_report, encoding='UTF-8')
Craig Tillerd86a3942015-01-14 12:48:54 -0800637
Craig Tiller69cd2372015-06-11 09:38:09 -0700638 if cache: cache.save()
639
Craig Tillerd86a3942015-01-14 12:48:54 -0800640 return 0
ctiller3040cb72015-01-07 12:13:17 -0800641
642
David Klempner25739582015-02-11 15:57:32 -0800643test_cache = TestCache(runs_per_test == 1)
Craig Tiller547db2b2015-01-30 14:08:39 -0800644test_cache.maybe_load()
Craig Tiller71735182015-01-15 17:07:13 -0800645
ctiller3040cb72015-01-07 12:13:17 -0800646if forever:
Nicolas Noble044db742015-01-14 16:57:24 -0800647 success = True
ctiller3040cb72015-01-07 12:13:17 -0800648 while True:
Craig Tiller42bc87c2015-02-23 08:50:19 -0800649 dw = watch_dirs.DirWatcher(['src', 'include', 'test', 'examples'])
ctiller3040cb72015-01-07 12:13:17 -0800650 initial_time = dw.most_recent_change()
651 have_files_changed = lambda: dw.most_recent_change() != initial_time
Nicolas Noble044db742015-01-14 16:57:24 -0800652 previous_success = success
Craig Tiller71735182015-01-15 17:07:13 -0800653 success = _build_and_run(check_cancelled=have_files_changed,
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800654 newline_on_success=False,
Craig Tiller9a5a9402015-04-16 10:39:50 -0700655 travis=args.travis,
Craig Tiller71735182015-01-15 17:07:13 -0800656 cache=test_cache) == 0
Nicolas Noble044db742015-01-14 16:57:24 -0800657 if not previous_success and success:
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800658 jobset.message('SUCCESS',
659 'All tests are now passing properly',
660 do_newline=True)
Nicolas Noble044db742015-01-14 16:57:24 -0800661 jobset.message('IDLE', 'No change detected')
ctiller3040cb72015-01-07 12:13:17 -0800662 while not have_files_changed():
663 time.sleep(1)
664else:
Craig Tiller71735182015-01-15 17:07:13 -0800665 result = _build_and_run(check_cancelled=lambda: False,
666 newline_on_success=args.newline_on_success,
Nicolas "Pixel" Noblea7df3f92015-02-26 22:07:04 +0100667 travis=args.travis,
Nicolas "Pixel" Noble5937b5b2015-06-26 02:04:12 +0200668 cache=test_cache,
669 xml_report=args.xml_report)
Nicolas Nobleb09078f2015-01-14 18:06:05 -0800670 if result == 0:
671 jobset.message('SUCCESS', 'All tests passed', do_newline=True)
672 else:
673 jobset.message('FAILED', 'Some tests failed', do_newline=True)
674 sys.exit(result)