blob: c9e9db4d40c33bf07010cb25a98c8d2cc6eb46d3 [file] [log] [blame]
Kenneth Russelleb60cbd22017-12-05 07:54:281#!/usr/bin/env python
2# Copyright 2016 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Script to generate the majority of the JSON files in the src/testing/buildbot
7directory. Maintaining these files by hand is too unwieldy.
8"""
9
10import argparse
11import ast
12import collections
13import copy
John Budorick826d5ed2017-12-28 19:27:3214import difflib
Garrett Beatyd5ca75962020-05-07 16:58:3115import glob
Kenneth Russell8ceeabf2017-12-11 17:53:2816import itertools
Kenneth Russelleb60cbd22017-12-05 07:54:2817import json
18import os
Greg Gutermanf60eb052020-03-12 17:40:0119import re
Kenneth Russelleb60cbd22017-12-05 07:54:2820import string
21import sys
John Budorick826d5ed2017-12-28 19:27:3222import traceback
Kenneth Russelleb60cbd22017-12-05 07:54:2823
Brian Sheedya31578e2020-05-18 20:24:3624import buildbot_json_magic_substitutions as magic_substitutions
25
Kenneth Russelleb60cbd22017-12-05 07:54:2826THIS_DIR = os.path.dirname(os.path.abspath(__file__))
27
28
29class BBGenErr(Exception):
Nico Weber79dc5f6852018-07-13 19:38:4930 def __init__(self, message):
31 super(BBGenErr, self).__init__(message)
Kenneth Russelleb60cbd22017-12-05 07:54:2832
33
Kenneth Russell8ceeabf2017-12-11 17:53:2834# This class is only present to accommodate certain machines on
35# chromium.android.fyi which run certain tests as instrumentation
36# tests, but not as gtests. If this discrepancy were fixed then the
37# notion could be removed.
38class TestSuiteTypes(object):
39 GTEST = 'gtest'
40
41
Kenneth Russelleb60cbd22017-12-05 07:54:2842class BaseGenerator(object):
43 def __init__(self, bb_gen):
44 self.bb_gen = bb_gen
45
Kenneth Russell8ceeabf2017-12-11 17:53:2846 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:2847 raise NotImplementedError()
48
49 def sort(self, tests):
50 raise NotImplementedError()
51
52
Kenneth Russell8ceeabf2017-12-11 17:53:2853def cmp_tests(a, b):
54 # Prefer to compare based on the "test" key.
55 val = cmp(a['test'], b['test'])
56 if val != 0:
57 return val
58 if 'name' in a and 'name' in b:
59 return cmp(a['name'], b['name']) # pragma: no cover
60 if 'name' not in a and 'name' not in b:
61 return 0 # pragma: no cover
62 # Prefer to put variants of the same test after the first one.
63 if 'name' in a:
64 return 1
65 # 'name' is in b.
66 return -1 # pragma: no cover
67
68
Kenneth Russell8a386d42018-06-02 09:48:0169class GPUTelemetryTestGenerator(BaseGenerator):
Bo Liu555a0f92019-03-29 12:11:5670
71 def __init__(self, bb_gen, is_android_webview=False):
Kenneth Russell8a386d42018-06-02 09:48:0172 super(GPUTelemetryTestGenerator, self).__init__(bb_gen)
Bo Liu555a0f92019-03-29 12:11:5673 self._is_android_webview = is_android_webview
Kenneth Russell8a386d42018-06-02 09:48:0174
75 def generate(self, waterfall, tester_name, tester_config, input_tests):
76 isolated_scripts = []
77 for test_name, test_config in sorted(input_tests.iteritems()):
78 test = self.bb_gen.generate_gpu_telemetry_test(
Bo Liu555a0f92019-03-29 12:11:5679 waterfall, tester_name, tester_config, test_name, test_config,
80 self._is_android_webview)
Kenneth Russell8a386d42018-06-02 09:48:0181 if test:
82 isolated_scripts.append(test)
83 return isolated_scripts
84
85 def sort(self, tests):
86 return sorted(tests, key=lambda x: x['name'])
87
88
Kenneth Russelleb60cbd22017-12-05 07:54:2889class GTestGenerator(BaseGenerator):
90 def __init__(self, bb_gen):
91 super(GTestGenerator, self).__init__(bb_gen)
92
Kenneth Russell8ceeabf2017-12-11 17:53:2893 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:2894 # The relative ordering of some of the tests is important to
95 # minimize differences compared to the handwritten JSON files, since
96 # Python's sorts are stable and there are some tests with the same
97 # key (see gles2_conform_d3d9_test and similar variants). Avoid
98 # losing the order by avoiding coalescing the dictionaries into one.
99 gtests = []
100 for test_name, test_config in sorted(input_tests.iteritems()):
Jeff Yoon67c3e832020-02-08 07:39:38101 # Variants allow more than one definition for a given test, and is defined
102 # in array format from resolve_variants().
103 if not isinstance(test_config, list):
104 test_config = [test_config]
105
106 for config in test_config:
107 test = self.bb_gen.generate_gtest(
108 waterfall, tester_name, tester_config, test_name, config)
109 if test:
110 # generate_gtest may veto the test generation on this tester.
111 gtests.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28112 return gtests
113
114 def sort(self, tests):
Kenneth Russell8ceeabf2017-12-11 17:53:28115 return sorted(tests, cmp=cmp_tests)
Kenneth Russelleb60cbd22017-12-05 07:54:28116
117
118class IsolatedScriptTestGenerator(BaseGenerator):
119 def __init__(self, bb_gen):
120 super(IsolatedScriptTestGenerator, self).__init__(bb_gen)
121
Kenneth Russell8ceeabf2017-12-11 17:53:28122 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28123 isolated_scripts = []
124 for test_name, test_config in sorted(input_tests.iteritems()):
Jeff Yoonb8bfdbf32020-03-13 19:14:43125 # Variants allow more than one definition for a given test, and is defined
126 # in array format from resolve_variants().
127 if not isinstance(test_config, list):
128 test_config = [test_config]
129
130 for config in test_config:
131 test = self.bb_gen.generate_isolated_script_test(
132 waterfall, tester_name, tester_config, test_name, config)
133 if test:
134 isolated_scripts.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28135 return isolated_scripts
136
137 def sort(self, tests):
138 return sorted(tests, key=lambda x: x['name'])
139
140
141class ScriptGenerator(BaseGenerator):
142 def __init__(self, bb_gen):
143 super(ScriptGenerator, self).__init__(bb_gen)
144
Kenneth Russell8ceeabf2017-12-11 17:53:28145 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28146 scripts = []
147 for test_name, test_config in sorted(input_tests.iteritems()):
148 test = self.bb_gen.generate_script_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28149 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28150 if test:
151 scripts.append(test)
152 return scripts
153
154 def sort(self, tests):
155 return sorted(tests, key=lambda x: x['name'])
156
157
158class JUnitGenerator(BaseGenerator):
159 def __init__(self, bb_gen):
160 super(JUnitGenerator, self).__init__(bb_gen)
161
Kenneth Russell8ceeabf2017-12-11 17:53:28162 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28163 scripts = []
164 for test_name, test_config in sorted(input_tests.iteritems()):
165 test = self.bb_gen.generate_junit_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28166 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28167 if test:
168 scripts.append(test)
169 return scripts
170
171 def sort(self, tests):
172 return sorted(tests, key=lambda x: x['test'])
173
174
175class CTSGenerator(BaseGenerator):
176 def __init__(self, bb_gen):
177 super(CTSGenerator, self).__init__(bb_gen)
178
Kenneth Russell8ceeabf2017-12-11 17:53:28179 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28180 # These only contain one entry and it's the contents of the input tests'
181 # dictionary, verbatim.
182 cts_tests = []
183 cts_tests.append(input_tests)
184 return cts_tests
185
186 def sort(self, tests):
187 return tests
188
189
190class InstrumentationTestGenerator(BaseGenerator):
191 def __init__(self, bb_gen):
192 super(InstrumentationTestGenerator, self).__init__(bb_gen)
193
Kenneth Russell8ceeabf2017-12-11 17:53:28194 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28195 scripts = []
196 for test_name, test_config in sorted(input_tests.iteritems()):
197 test = self.bb_gen.generate_instrumentation_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28198 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28199 if test:
200 scripts.append(test)
201 return scripts
202
203 def sort(self, tests):
Kenneth Russell8ceeabf2017-12-11 17:53:28204 return sorted(tests, cmp=cmp_tests)
Kenneth Russelleb60cbd22017-12-05 07:54:28205
206
Jeff Yoon67c3e832020-02-08 07:39:38207def check_compound_references(other_test_suites=None,
208 sub_suite=None,
209 suite=None,
210 target_test_suites=None,
211 test_type=None,
212 **kwargs):
213 """Ensure comound reference's don't target other compounds"""
214 del kwargs
215 if sub_suite in other_test_suites or sub_suite in target_test_suites:
216 raise BBGenErr('%s may not refer to other composition type test '
217 'suites (error found while processing %s)'
218 % (test_type, suite))
219
220def check_basic_references(basic_suites=None,
221 sub_suite=None,
222 suite=None,
223 **kwargs):
224 """Ensure test has a basic suite reference"""
225 del kwargs
226 if sub_suite not in basic_suites:
227 raise BBGenErr('Unable to find reference to %s while processing %s'
228 % (sub_suite, suite))
229
230def check_conflicting_definitions(basic_suites=None,
231 seen_tests=None,
232 sub_suite=None,
233 suite=None,
234 test_type=None,
235 **kwargs):
236 """Ensure that if a test is reachable via multiple basic suites,
237 all of them have an identical definition of the tests.
238 """
239 del kwargs
240 for test_name in basic_suites[sub_suite]:
241 if (test_name in seen_tests and
242 basic_suites[sub_suite][test_name] !=
243 basic_suites[seen_tests[test_name]][test_name]):
244 raise BBGenErr('Conflicting test definitions for %s from %s '
245 'and %s in %s (error found while processing %s)'
246 % (test_name, seen_tests[test_name], sub_suite,
247 test_type, suite))
248 seen_tests[test_name] = sub_suite
249
250def check_matrix_identifier(sub_suite=None,
251 suite=None,
252 suite_def=None,
Jeff Yoonda581c32020-03-06 03:56:05253 all_variants=None,
Jeff Yoon67c3e832020-02-08 07:39:38254 **kwargs):
255 """Ensure 'idenfitier' is defined for each variant"""
256 del kwargs
257 sub_suite_config = suite_def[sub_suite]
258 for variant in sub_suite_config.get('variants', []):
Jeff Yoonda581c32020-03-06 03:56:05259 if isinstance(variant, str):
260 if variant not in all_variants:
261 raise BBGenErr('Missing variant definition for %s in variants.pyl'
262 % variant)
263 variant = all_variants[variant]
264
Jeff Yoon67c3e832020-02-08 07:39:38265 if not 'identifier' in variant:
266 raise BBGenErr('Missing required identifier field in matrix '
267 'compound suite %s, %s' % (suite, sub_suite))
268
269
Kenneth Russelleb60cbd22017-12-05 07:54:28270class BBJSONGenerator(object):
271 def __init__(self):
272 self.this_dir = THIS_DIR
273 self.args = None
274 self.waterfalls = None
275 self.test_suites = None
276 self.exceptions = None
Stephen Martinisb72f6d22018-10-04 23:29:01277 self.mixins = None
Nodir Turakulovfce34292019-12-18 17:05:41278 self.gn_isolate_map = None
Jeff Yoonda581c32020-03-06 03:56:05279 self.variants = None
Kenneth Russelleb60cbd22017-12-05 07:54:28280
281 def generate_abs_file_path(self, relative_path):
282 return os.path.join(self.this_dir, relative_path) # pragma: no cover
283
Stephen Martinis7eb8b612018-09-21 00:17:50284 def print_line(self, line):
285 # Exists so that tests can mock
286 print line # pragma: no cover
287
Kenneth Russelleb60cbd22017-12-05 07:54:28288 def read_file(self, relative_path):
289 with open(self.generate_abs_file_path(
290 relative_path)) as fp: # pragma: no cover
291 return fp.read() # pragma: no cover
292
293 def write_file(self, relative_path, contents):
294 with open(self.generate_abs_file_path(
295 relative_path), 'wb') as fp: # pragma: no cover
296 fp.write(contents) # pragma: no cover
297
Zhiling Huangbe008172018-03-08 19:13:11298 def pyl_file_path(self, filename):
299 if self.args and self.args.pyl_files_dir:
300 return os.path.join(self.args.pyl_files_dir, filename)
301 return filename
302
Kenneth Russelleb60cbd22017-12-05 07:54:28303 def load_pyl_file(self, filename):
304 try:
Zhiling Huangbe008172018-03-08 19:13:11305 return ast.literal_eval(self.read_file(
306 self.pyl_file_path(filename)))
Kenneth Russelleb60cbd22017-12-05 07:54:28307 except (SyntaxError, ValueError) as e: # pragma: no cover
308 raise BBGenErr('Failed to parse pyl file "%s": %s' %
309 (filename, e)) # pragma: no cover
310
Kenneth Russell8a386d42018-06-02 09:48:01311 # TOOD(kbr): require that os_type be specified for all bots in waterfalls.pyl.
312 # Currently it is only mandatory for bots which run GPU tests. Change these to
313 # use [] instead of .get().
Kenneth Russelleb60cbd22017-12-05 07:54:28314 def is_android(self, tester_config):
315 return tester_config.get('os_type') == 'android'
316
Ben Pastenea9e583b2019-01-16 02:57:26317 def is_chromeos(self, tester_config):
318 return tester_config.get('os_type') == 'chromeos'
319
Kenneth Russell8a386d42018-06-02 09:48:01320 def is_linux(self, tester_config):
321 return tester_config.get('os_type') == 'linux'
322
Kai Ninomiya40de9f52019-10-18 21:38:49323 def is_mac(self, tester_config):
324 return tester_config.get('os_type') == 'mac'
325
326 def is_win(self, tester_config):
327 return tester_config.get('os_type') == 'win'
328
329 def is_win64(self, tester_config):
330 return (tester_config.get('os_type') == 'win' and
331 tester_config.get('browser_config') == 'release_x64')
332
Kenneth Russelleb60cbd22017-12-05 07:54:28333 def get_exception_for_test(self, test_name, test_config):
334 # gtests may have both "test" and "name" fields, and usually, if the "name"
335 # field is specified, it means that the same test is being repurposed
336 # multiple times with different command line arguments. To handle this case,
337 # prefer to lookup per the "name" field of the test itself, as opposed to
338 # the "test_name", which is actually the "test" field.
339 if 'name' in test_config:
340 return self.exceptions.get(test_config['name'])
341 else:
342 return self.exceptions.get(test_name)
343
Nico Weberb0b3f5862018-07-13 18:45:15344 def should_run_on_tester(self, waterfall, tester_name,test_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28345 # Currently, the only reason a test should not run on a given tester is that
346 # it's in the exceptions. (Once the GPU waterfall generation script is
347 # incorporated here, the rules will become more complex.)
348 exception = self.get_exception_for_test(test_name, test_config)
349 if not exception:
350 return True
Kenneth Russell8ceeabf2017-12-11 17:53:28351 remove_from = None
Kenneth Russelleb60cbd22017-12-05 07:54:28352 remove_from = exception.get('remove_from')
Kenneth Russell8ceeabf2017-12-11 17:53:28353 if remove_from:
354 if tester_name in remove_from:
355 return False
356 # TODO(kbr): this code path was added for some tests (including
357 # android_webview_unittests) on one machine (Nougat Phone
358 # Tester) which exists with the same name on two waterfalls,
359 # chromium.android and chromium.fyi; the tests are run on one
360 # but not the other. Once the bots are all uniquely named (a
361 # different ongoing project) this code should be removed.
362 # TODO(kbr): add coverage.
363 return (tester_name + ' ' + waterfall['name']
364 not in remove_from) # pragma: no cover
365 return True
Kenneth Russelleb60cbd22017-12-05 07:54:28366
Nico Weber79dc5f6852018-07-13 19:38:49367 def get_test_modifications(self, test, test_name, tester_name):
Kenneth Russelleb60cbd22017-12-05 07:54:28368 exception = self.get_exception_for_test(test_name, test)
369 if not exception:
370 return None
Nico Weber79dc5f6852018-07-13 19:38:49371 return exception.get('modifications', {}).get(tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28372
Brian Sheedye6ea0ee2019-07-11 02:54:37373 def get_test_replacements(self, test, test_name, tester_name):
374 exception = self.get_exception_for_test(test_name, test)
375 if not exception:
376 return None
377 return exception.get('replacements', {}).get(tester_name)
378
Kenneth Russell8a386d42018-06-02 09:48:01379 def merge_command_line_args(self, arr, prefix, splitter):
380 prefix_len = len(prefix)
Kenneth Russell650995a2018-05-03 21:17:01381 idx = 0
382 first_idx = -1
Kenneth Russell8a386d42018-06-02 09:48:01383 accumulated_args = []
Kenneth Russell650995a2018-05-03 21:17:01384 while idx < len(arr):
385 flag = arr[idx]
386 delete_current_entry = False
Kenneth Russell8a386d42018-06-02 09:48:01387 if flag.startswith(prefix):
388 arg = flag[prefix_len:]
389 accumulated_args.extend(arg.split(splitter))
Kenneth Russell650995a2018-05-03 21:17:01390 if first_idx < 0:
391 first_idx = idx
392 else:
393 delete_current_entry = True
394 if delete_current_entry:
395 del arr[idx]
396 else:
397 idx += 1
398 if first_idx >= 0:
Kenneth Russell8a386d42018-06-02 09:48:01399 arr[first_idx] = prefix + splitter.join(accumulated_args)
400 return arr
401
402 def maybe_fixup_args_array(self, arr):
403 # The incoming array of strings may be an array of command line
404 # arguments. To make it easier to turn on certain features per-bot or
405 # per-test-suite, look specifically for certain flags and merge them
406 # appropriately.
407 # --enable-features=Feature1 --enable-features=Feature2
408 # are merged to:
409 # --enable-features=Feature1,Feature2
410 # and:
411 # --extra-browser-args=arg1 --extra-browser-args=arg2
412 # are merged to:
413 # --extra-browser-args=arg1 arg2
414 arr = self.merge_command_line_args(arr, '--enable-features=', ',')
415 arr = self.merge_command_line_args(arr, '--extra-browser-args=', ' ')
Kenneth Russell650995a2018-05-03 21:17:01416 return arr
417
Brian Sheedya31578e2020-05-18 20:24:36418 def substitute_magic_args(self, test_config):
419 """Substitutes any magic substitution args present in |test_config|.
420
421 Substitutions are done in-place.
422
423 See buildbot_json_magic_substitutions.py for more information on this
424 feature.
425
426 Args:
427 test_config: A dict containing a configuration for a specific test on
428 a specific builder, e.g. the output of update_and_cleanup_test.
429 """
430 substituted_array = []
431 for arg in test_config.get('args', []):
432 if arg.startswith(magic_substitutions.MAGIC_SUBSTITUTION_PREFIX):
433 function = arg.replace(
434 magic_substitutions.MAGIC_SUBSTITUTION_PREFIX, '')
435 if hasattr(magic_substitutions, function):
436 substituted_array.extend(
437 getattr(magic_substitutions, function)(test_config))
438 else:
439 raise BBGenErr(
440 'Magic substitution function %s does not exist' % function)
441 else:
442 substituted_array.append(arg)
443 if substituted_array:
444 test_config['args'] = self.maybe_fixup_args_array(substituted_array)
445
Kenneth Russelleb60cbd22017-12-05 07:54:28446 def dictionary_merge(self, a, b, path=None, update=True):
447 """http://stackoverflow.com/questions/7204805/
448 python-dictionaries-of-dictionaries-merge
449 merges b into a
450 """
451 if path is None:
452 path = []
453 for key in b:
454 if key in a:
455 if isinstance(a[key], dict) and isinstance(b[key], dict):
456 self.dictionary_merge(a[key], b[key], path + [str(key)])
457 elif a[key] == b[key]:
458 pass # same leaf value
459 elif isinstance(a[key], list) and isinstance(b[key], list):
Stephen Martinis3bed2ab2018-04-23 19:42:06460 # Args arrays are lists of strings. Just concatenate them,
461 # and don't sort them, in order to keep some needed
462 # arguments adjacent (like --time-out-ms [arg], etc.)
Kenneth Russell8ceeabf2017-12-11 17:53:28463 if all(isinstance(x, str)
464 for x in itertools.chain(a[key], b[key])):
Kenneth Russell650995a2018-05-03 21:17:01465 a[key] = self.maybe_fixup_args_array(a[key] + b[key])
Kenneth Russell8ceeabf2017-12-11 17:53:28466 else:
467 # TODO(kbr): this only works properly if the two arrays are
468 # the same length, which is currently always the case in the
469 # swarming dimension_sets that we have to merge. It will fail
470 # to merge / override 'args' arrays which are different
471 # length.
472 for idx in xrange(len(b[key])):
473 try:
474 a[key][idx] = self.dictionary_merge(a[key][idx], b[key][idx],
475 path + [str(key), str(idx)],
476 update=update)
Jeff Yoon8154e582019-12-03 23:30:01477 except (IndexError, TypeError):
478 raise BBGenErr('Error merging lists by key "%s" from source %s '
479 'into target %s at index %s. Verify target list '
480 'length is equal or greater than source'
481 % (str(key), str(b), str(a), str(idx)))
John Budorick5bc387fe2019-05-09 20:02:53482 elif update:
483 if b[key] is None:
484 del a[key]
485 else:
486 a[key] = b[key]
Kenneth Russelleb60cbd22017-12-05 07:54:28487 else:
488 raise BBGenErr('Conflict at %s' % '.'.join(
489 path + [str(key)])) # pragma: no cover
John Budorick5bc387fe2019-05-09 20:02:53490 elif b[key] is not None:
Kenneth Russelleb60cbd22017-12-05 07:54:28491 a[key] = b[key]
492 return a
493
John Budorickab108712018-09-01 00:12:21494 def initialize_args_for_test(
495 self, generated_test, tester_config, additional_arg_keys=None):
John Budorickab108712018-09-01 00:12:21496 args = []
497 args.extend(generated_test.get('args', []))
498 args.extend(tester_config.get('args', []))
John Budorickedfe7f872018-01-23 15:27:22499
Kenneth Russell8a386d42018-06-02 09:48:01500 def add_conditional_args(key, fn):
John Budorickab108712018-09-01 00:12:21501 val = generated_test.pop(key, [])
502 if fn(tester_config):
503 args.extend(val)
Kenneth Russell8a386d42018-06-02 09:48:01504
505 add_conditional_args('desktop_args', lambda cfg: not self.is_android(cfg))
506 add_conditional_args('linux_args', self.is_linux)
507 add_conditional_args('android_args', self.is_android)
Ben Pastene52890ace2019-05-24 20:03:36508 add_conditional_args('chromeos_args', self.is_chromeos)
Kai Ninomiya40de9f52019-10-18 21:38:49509 add_conditional_args('mac_args', self.is_mac)
510 add_conditional_args('win_args', self.is_win)
511 add_conditional_args('win64_args', self.is_win64)
Kenneth Russell8a386d42018-06-02 09:48:01512
John Budorickab108712018-09-01 00:12:21513 for key in additional_arg_keys or []:
514 args.extend(generated_test.pop(key, []))
515 args.extend(tester_config.get(key, []))
516
517 if args:
518 generated_test['args'] = self.maybe_fixup_args_array(args)
Kenneth Russell8a386d42018-06-02 09:48:01519
Kenneth Russelleb60cbd22017-12-05 07:54:28520 def initialize_swarming_dictionary_for_test(self, generated_test,
521 tester_config):
522 if 'swarming' not in generated_test:
523 generated_test['swarming'] = {}
Dirk Pranke81ff51c2017-12-09 19:24:28524 if not 'can_use_on_swarming_builders' in generated_test['swarming']:
525 generated_test['swarming'].update({
Jeff Yoon67c3e832020-02-08 07:39:38526 'can_use_on_swarming_builders': tester_config.get('use_swarming',
527 True)
Dirk Pranke81ff51c2017-12-09 19:24:28528 })
Kenneth Russelleb60cbd22017-12-05 07:54:28529 if 'swarming' in tester_config:
Ben Pastene796c62862018-06-13 02:40:03530 if ('dimension_sets' not in generated_test['swarming'] and
531 'dimension_sets' in tester_config['swarming']):
Kenneth Russelleb60cbd22017-12-05 07:54:28532 generated_test['swarming']['dimension_sets'] = copy.deepcopy(
533 tester_config['swarming']['dimension_sets'])
534 self.dictionary_merge(generated_test['swarming'],
535 tester_config['swarming'])
536 # Apply any Android-specific Swarming dimensions after the generic ones.
537 if 'android_swarming' in generated_test:
538 if self.is_android(tester_config): # pragma: no cover
539 self.dictionary_merge(
540 generated_test['swarming'],
541 generated_test['android_swarming']) # pragma: no cover
542 del generated_test['android_swarming'] # pragma: no cover
543
544 def clean_swarming_dictionary(self, swarming_dict):
545 # Clean out redundant entries from a test's "swarming" dictionary.
546 # This is really only needed to retain 100% parity with the
547 # handwritten JSON files, and can be removed once all the files are
548 # autogenerated.
549 if 'shards' in swarming_dict:
550 if swarming_dict['shards'] == 1: # pragma: no cover
551 del swarming_dict['shards'] # pragma: no cover
Kenneth Russellfbda3c532017-12-08 23:57:24552 if 'hard_timeout' in swarming_dict:
553 if swarming_dict['hard_timeout'] == 0: # pragma: no cover
554 del swarming_dict['hard_timeout'] # pragma: no cover
Stephen Martinisf5f4ea22018-09-20 01:07:43555 if not swarming_dict.get('can_use_on_swarming_builders', False):
Kenneth Russelleb60cbd22017-12-05 07:54:28556 # Remove all other keys.
557 for k in swarming_dict.keys(): # pragma: no cover
558 if k != 'can_use_on_swarming_builders': # pragma: no cover
559 del swarming_dict[k] # pragma: no cover
560
Stephen Martinis0382bc12018-09-17 22:29:07561 def update_and_cleanup_test(self, test, test_name, tester_name, tester_config,
562 waterfall):
563 # Apply swarming mixins.
Stephen Martinisb72f6d22018-10-04 23:29:01564 test = self.apply_all_mixins(
Stephen Martinis0382bc12018-09-17 22:29:07565 test, waterfall, tester_name, tester_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28566 # See if there are any exceptions that need to be merged into this
567 # test's specification.
Nico Weber79dc5f6852018-07-13 19:38:49568 modifications = self.get_test_modifications(test, test_name, tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28569 if modifications:
570 test = self.dictionary_merge(test, modifications)
Dirk Pranke1b767092017-12-07 04:44:23571 if 'swarming' in test:
572 self.clean_swarming_dictionary(test['swarming'])
Ben Pastenee012aea42019-05-14 22:32:28573 # Ensure all Android Swarming tests run only on userdebug builds if another
574 # build type was not specified.
575 if 'swarming' in test and self.is_android(tester_config):
576 for d in test['swarming'].get('dimension_sets', []):
Ben Pastened15aa8a2019-05-16 16:59:22577 if d.get('os') == 'Android' and not d.get('device_os_type'):
Ben Pastenee012aea42019-05-14 22:32:28578 d['device_os_type'] = 'userdebug'
Brian Sheedye6ea0ee2019-07-11 02:54:37579 self.replace_test_args(test, test_name, tester_name)
Ben Pastenee012aea42019-05-14 22:32:28580
Kenneth Russelleb60cbd22017-12-05 07:54:28581 return test
582
Brian Sheedye6ea0ee2019-07-11 02:54:37583 def replace_test_args(self, test, test_name, tester_name):
584 replacements = self.get_test_replacements(
585 test, test_name, tester_name) or {}
586 valid_replacement_keys = ['args', 'non_precommit_args', 'precommit_args']
587 for key, replacement_dict in replacements.iteritems():
588 if key not in valid_replacement_keys:
589 raise BBGenErr(
590 'Given replacement key %s for %s on %s is not in the list of valid '
591 'keys %s' % (key, test_name, tester_name, valid_replacement_keys))
592 for replacement_key, replacement_val in replacement_dict.iteritems():
593 found_key = False
594 for i, test_key in enumerate(test.get(key, [])):
595 # Handle both the key/value being replaced being defined as two
596 # separate items or as key=value.
597 if test_key == replacement_key:
598 found_key = True
599 # Handle flags without values.
600 if replacement_val == None:
601 del test[key][i]
602 else:
603 test[key][i+1] = replacement_val
604 break
605 elif test_key.startswith(replacement_key + '='):
606 found_key = True
607 if replacement_val == None:
608 del test[key][i]
609 else:
610 test[key][i] = '%s=%s' % (replacement_key, replacement_val)
611 break
612 if not found_key:
613 raise BBGenErr('Could not find %s in existing list of values for key '
614 '%s in %s on %s' % (replacement_key, key, test_name,
615 tester_name))
616
Shenghua Zhangaba8bad2018-02-07 02:12:09617 def add_common_test_properties(self, test, tester_config):
Brian Sheedy5ea8f6c62020-05-21 03:05:05618 if self.is_chromeos(tester_config) and tester_config.get('use_swarming',
Ben Pastenea9e583b2019-01-16 02:57:26619 True):
620 # The presence of the "device_type" dimension indicates that the tests
Brian Sheedy9493da892020-05-13 22:58:06621 # are targeting CrOS hardware and so need the special trigger script.
622 dimension_sets = test['swarming']['dimension_sets']
Ben Pastenea9e583b2019-01-16 02:57:26623 if all('device_type' in ds for ds in dimension_sets):
624 test['trigger_script'] = {
625 'script': '//testing/trigger_scripts/chromeos_device_trigger.py',
626 }
Shenghua Zhangaba8bad2018-02-07 02:12:09627
Ben Pastene858f4be2019-01-09 23:52:09628 def add_android_presentation_args(self, tester_config, test_name, result):
629 args = result.get('args', [])
John Budorick262ae112019-07-12 19:24:38630 bucket = tester_config.get('results_bucket', 'chromium-result-details')
631 args.append('--gs-results-bucket=%s' % bucket)
Ben Pastene858f4be2019-01-09 23:52:09632 if (result['swarming']['can_use_on_swarming_builders'] and not
633 tester_config.get('skip_merge_script', False)):
634 result['merge'] = {
635 'args': [
636 '--bucket',
John Budorick262ae112019-07-12 19:24:38637 bucket,
Ben Pastene858f4be2019-01-09 23:52:09638 '--test-name',
639 test_name
640 ],
641 'script': '//build/android/pylib/results/presentation/'
642 'test_results_presentation.py',
643 }
644 if not tester_config.get('skip_cipd_packages', False):
Ben Pastenee5949ea82019-01-10 21:45:26645 cipd_packages = result['swarming'].get('cipd_packages', [])
646 cipd_packages.append(
Ben Pastene858f4be2019-01-09 23:52:09647 {
648 'cipd_package': 'infra/tools/luci/logdog/butler/${platform}',
649 'location': 'bin',
650 'revision': 'git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c',
651 }
Ben Pastenee5949ea82019-01-10 21:45:26652 )
653 result['swarming']['cipd_packages'] = cipd_packages
Ben Pastene858f4be2019-01-09 23:52:09654 if not tester_config.get('skip_output_links', False):
655 result['swarming']['output_links'] = [
656 {
657 'link': [
658 'https://luci-logdog.appspot.com/v/?s',
659 '=android%2Fswarming%2Flogcats%2F',
660 '${TASK_ID}%2F%2B%2Funified_logcats',
661 ],
662 'name': 'shard #${SHARD_INDEX} logcats',
663 },
664 ]
665 if args:
666 result['args'] = args
667
Kenneth Russelleb60cbd22017-12-05 07:54:28668 def generate_gtest(self, waterfall, tester_name, tester_config, test_name,
669 test_config):
670 if not self.should_run_on_tester(
Nico Weberb0b3f5862018-07-13 18:45:15671 waterfall, tester_name, test_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28672 return None
673 result = copy.deepcopy(test_config)
674 if 'test' in result:
675 result['name'] = test_name
676 else:
677 result['test'] = test_name
678 self.initialize_swarming_dictionary_for_test(result, tester_config)
John Budorickab108712018-09-01 00:12:21679
680 self.initialize_args_for_test(
681 result, tester_config, additional_arg_keys=['gtest_args'])
Kenneth Russelleb60cbd22017-12-05 07:54:28682 if self.is_android(tester_config) and tester_config.get('use_swarming',
683 True):
Ben Pastene858f4be2019-01-09 23:52:09684 self.add_android_presentation_args(tester_config, test_name, result)
685 result['args'] = result.get('args', []) + ['--recover-devices']
Benjamin Pastene766d48f52017-12-18 21:47:42686
Stephen Martinis0382bc12018-09-17 22:29:07687 result = self.update_and_cleanup_test(
688 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09689 self.add_common_test_properties(result, tester_config)
Brian Sheedya31578e2020-05-18 20:24:36690 self.substitute_magic_args(result)
Stephen Martinisbc7b7772019-05-01 22:01:43691
692 if not result.get('merge'):
693 # TODO(https://crbug.com/958376): Consider adding the ability to not have
694 # this default.
695 result['merge'] = {
696 'script': '//testing/merge_scripts/standard_gtest_merge.py',
697 'args': [],
698 }
Kenneth Russelleb60cbd22017-12-05 07:54:28699 return result
700
701 def generate_isolated_script_test(self, waterfall, tester_name, tester_config,
702 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01703 if not self.should_run_on_tester(waterfall, tester_name, test_name,
704 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28705 return None
706 result = copy.deepcopy(test_config)
707 result['isolate_name'] = result.get('isolate_name', test_name)
Jeff Yoonb8bfdbf32020-03-13 19:14:43708 result['name'] = result.get('name', test_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28709 self.initialize_swarming_dictionary_for_test(result, tester_config)
Kenneth Russell8a386d42018-06-02 09:48:01710 self.initialize_args_for_test(result, tester_config)
Ben Pastene858f4be2019-01-09 23:52:09711 if tester_config.get('use_android_presentation', False):
712 self.add_android_presentation_args(tester_config, test_name, result)
Stephen Martinis0382bc12018-09-17 22:29:07713 result = self.update_and_cleanup_test(
714 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09715 self.add_common_test_properties(result, tester_config)
Brian Sheedya31578e2020-05-18 20:24:36716 self.substitute_magic_args(result)
Stephen Martinisf50047062019-05-06 22:26:17717
718 if not result.get('merge'):
719 # TODO(https://crbug.com/958376): Consider adding the ability to not have
720 # this default.
721 result['merge'] = {
722 'script': '//testing/merge_scripts/standard_isolated_script_merge.py',
723 'args': [],
724 }
Kenneth Russelleb60cbd22017-12-05 07:54:28725 return result
726
727 def generate_script_test(self, waterfall, tester_name, tester_config,
728 test_name, test_config):
Brian Sheedy158cd0f2019-04-26 01:12:44729 # TODO(https://crbug.com/953072): Remove this check whenever a better
730 # long-term solution is implemented.
731 if (waterfall.get('forbid_script_tests', False) or
732 waterfall['machines'][tester_name].get('forbid_script_tests', False)):
733 raise BBGenErr('Attempted to generate a script test on tester ' +
734 tester_name + ', which explicitly forbids script tests')
Kenneth Russell8a386d42018-06-02 09:48:01735 if not self.should_run_on_tester(waterfall, tester_name, test_name,
736 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28737 return None
738 result = {
739 'name': test_name,
740 'script': test_config['script']
741 }
Stephen Martinis0382bc12018-09-17 22:29:07742 result = self.update_and_cleanup_test(
743 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36744 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28745 return result
746
747 def generate_junit_test(self, waterfall, tester_name, tester_config,
748 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01749 if not self.should_run_on_tester(waterfall, tester_name, test_name,
750 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28751 return None
John Budorickdef6acb2019-09-17 22:51:09752 result = copy.deepcopy(test_config)
753 result.update({
John Budorickcadc4952019-09-16 23:51:37754 'name': test_name,
755 'test': test_config.get('test', test_name),
John Budorickdef6acb2019-09-17 22:51:09756 })
757 self.initialize_args_for_test(result, tester_config)
758 result = self.update_and_cleanup_test(
759 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36760 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28761 return result
762
763 def generate_instrumentation_test(self, waterfall, tester_name, tester_config,
764 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01765 if not self.should_run_on_tester(waterfall, tester_name, test_name,
766 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28767 return None
768 result = copy.deepcopy(test_config)
Kenneth Russell8ceeabf2017-12-11 17:53:28769 if 'test' in result and result['test'] != test_name:
770 result['name'] = test_name
771 else:
772 result['test'] = test_name
Stephen Martinis0382bc12018-09-17 22:29:07773 result = self.update_and_cleanup_test(
774 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36775 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28776 return result
777
Stephen Martinis2a0667022018-09-25 22:31:14778 def substitute_gpu_args(self, tester_config, swarming_config, args):
Kenneth Russell8a386d42018-06-02 09:48:01779 substitutions = {
780 # Any machine in waterfalls.pyl which desires to run GPU tests
781 # must provide the os_type key.
782 'os_type': tester_config['os_type'],
783 'gpu_vendor_id': '0',
784 'gpu_device_id': '0',
785 }
Stephen Martinis2a0667022018-09-25 22:31:14786 dimension_set = swarming_config['dimension_sets'][0]
Kenneth Russell8a386d42018-06-02 09:48:01787 if 'gpu' in dimension_set:
788 # First remove the driver version, then split into vendor and device.
789 gpu = dimension_set['gpu']
Brian Sheedy0e26c4e02020-05-28 22:09:09790 gpu = gpu.split('-')[0].split(':')
Kenneth Russell8a386d42018-06-02 09:48:01791 substitutions['gpu_vendor_id'] = gpu[0]
792 substitutions['gpu_device_id'] = gpu[1]
793 return [string.Template(arg).safe_substitute(substitutions) for arg in args]
794
795 def generate_gpu_telemetry_test(self, waterfall, tester_name, tester_config,
Bo Liu555a0f92019-03-29 12:11:56796 test_name, test_config, is_android_webview):
Kenneth Russell8a386d42018-06-02 09:48:01797 # These are all just specializations of isolated script tests with
798 # a bunch of boilerplate command line arguments added.
799
800 # The step name must end in 'test' or 'tests' in order for the
801 # results to automatically show up on the flakiness dashboard.
802 # (At least, this was true some time ago.) Continue to use this
803 # naming convention for the time being to minimize changes.
804 step_name = test_config.get('name', test_name)
805 if not (step_name.endswith('test') or step_name.endswith('tests')):
806 step_name = '%s_tests' % step_name
807 result = self.generate_isolated_script_test(
808 waterfall, tester_name, tester_config, step_name, test_config)
809 if not result:
810 return None
Chong Gub75754b32020-03-13 16:39:20811 result['isolate_name'] = test_config.get(
812 'isolate_name', 'telemetry_gpu_integration_test')
Chan Liab7d8dd82020-04-24 23:42:19813
Chan Lia3ad1502020-04-28 05:32:11814 # Populate test_id_prefix.
Chan Liab7d8dd82020-04-24 23:42:19815 gn_entry = (
816 self.gn_isolate_map.get(result['isolate_name']) or
817 self.gn_isolate_map.get('telemetry_gpu_integration_test'))
Chan Lia3ad1502020-04-28 05:32:11818 result['test_id_prefix'] = 'ninja:%s/%s/' % (gn_entry['label'], step_name)
Chan Liab7d8dd82020-04-24 23:42:19819
Kenneth Russell8a386d42018-06-02 09:48:01820 args = result.get('args', [])
821 test_to_run = result.pop('telemetry_test_name', test_name)
erikchen6da2d9b2018-08-03 23:01:14822
823 # These tests upload and download results from cloud storage and therefore
824 # aren't idempotent yet. https://crbug.com/549140.
825 result['swarming']['idempotent'] = False
826
Kenneth Russell44910c32018-12-03 23:35:11827 # The GPU tests act much like integration tests for the entire browser, and
828 # tend to uncover flakiness bugs more readily than other test suites. In
829 # order to surface any flakiness more readily to the developer of the CL
830 # which is introducing it, we disable retries with patch on the commit
831 # queue.
832 result['should_retry_with_patch'] = False
833
Bo Liu555a0f92019-03-29 12:11:56834 browser = ('android-webview-instrumentation'
835 if is_android_webview else tester_config['browser_config'])
Kenneth Russell8a386d42018-06-02 09:48:01836 args = [
Bo Liu555a0f92019-03-29 12:11:56837 test_to_run,
838 '--show-stdout',
839 '--browser=%s' % browser,
840 # --passthrough displays more of the logging in Telemetry when
841 # run via typ, in particular some of the warnings about tests
842 # being expected to fail, but passing.
843 '--passthrough',
844 '-v',
Brian Sheedy624f611c2020-06-08 19:18:33845 '--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc',
Kenneth Russell8a386d42018-06-02 09:48:01846 ] + args
847 result['args'] = self.maybe_fixup_args_array(self.substitute_gpu_args(
Stephen Martinis2a0667022018-09-25 22:31:14848 tester_config, result['swarming'], args))
Kenneth Russell8a386d42018-06-02 09:48:01849 return result
850
Kenneth Russelleb60cbd22017-12-05 07:54:28851 def get_test_generator_map(self):
852 return {
Bo Liu555a0f92019-03-29 12:11:56853 'android_webview_gpu_telemetry_tests':
854 GPUTelemetryTestGenerator(self, is_android_webview=True),
855 'cts_tests':
856 CTSGenerator(self),
857 'gpu_telemetry_tests':
858 GPUTelemetryTestGenerator(self),
859 'gtest_tests':
860 GTestGenerator(self),
861 'instrumentation_tests':
862 InstrumentationTestGenerator(self),
863 'isolated_scripts':
864 IsolatedScriptTestGenerator(self),
865 'junit_tests':
866 JUnitGenerator(self),
867 'scripts':
868 ScriptGenerator(self),
Kenneth Russelleb60cbd22017-12-05 07:54:28869 }
870
Kenneth Russell8a386d42018-06-02 09:48:01871 def get_test_type_remapper(self):
872 return {
873 # These are a specialization of isolated_scripts with a bunch of
874 # boilerplate command line arguments added to each one.
Bo Liu555a0f92019-03-29 12:11:56875 'android_webview_gpu_telemetry_tests': 'isolated_scripts',
Kenneth Russell8a386d42018-06-02 09:48:01876 'gpu_telemetry_tests': 'isolated_scripts',
877 }
878
Jeff Yoon67c3e832020-02-08 07:39:38879 def check_composition_type_test_suites(self, test_type,
880 additional_validators=None):
881 """Pre-pass to catch errors reliabily for compound/matrix suites"""
882 validators = [check_compound_references,
883 check_basic_references,
884 check_conflicting_definitions]
885 if additional_validators:
886 validators += additional_validators
887
888 target_suites = self.test_suites.get(test_type, {})
889 other_test_type = ('compound_suites'
890 if test_type == 'matrix_compound_suites'
891 else 'matrix_compound_suites')
892 other_suites = self.test_suites.get(other_test_type, {})
Jeff Yoon8154e582019-12-03 23:30:01893 basic_suites = self.test_suites.get('basic_suites', {})
894
Jeff Yoon67c3e832020-02-08 07:39:38895 for suite, suite_def in target_suites.iteritems():
Jeff Yoon8154e582019-12-03 23:30:01896 if suite in basic_suites:
897 raise BBGenErr('%s names may not duplicate basic test suite names '
898 '(error found while processsing %s)'
899 % (test_type, suite))
Nodir Turakulov28232afd2019-12-17 18:02:01900
Jeff Yoon67c3e832020-02-08 07:39:38901 seen_tests = {}
902 for sub_suite in suite_def:
903 for validator in validators:
904 validator(
905 basic_suites=basic_suites,
906 other_test_suites=other_suites,
907 seen_tests=seen_tests,
908 sub_suite=sub_suite,
909 suite=suite,
910 suite_def=suite_def,
911 target_test_suites=target_suites,
912 test_type=test_type,
Jeff Yoonda581c32020-03-06 03:56:05913 all_variants=self.variants
Jeff Yoon67c3e832020-02-08 07:39:38914 )
Kenneth Russelleb60cbd22017-12-05 07:54:28915
Stephen Martinis54d64ad2018-09-21 22:16:20916 def flatten_test_suites(self):
917 new_test_suites = {}
Jeff Yoon8154e582019-12-03 23:30:01918 test_types = ['basic_suites', 'compound_suites', 'matrix_compound_suites']
919 for category in test_types:
920 for name, value in self.test_suites.get(category, {}).iteritems():
921 new_test_suites[name] = value
Stephen Martinis54d64ad2018-09-21 22:16:20922 self.test_suites = new_test_suites
923
Chan Lia3ad1502020-04-28 05:32:11924 def resolve_test_id_prefixes(self):
Nodir Turakulovfce34292019-12-18 17:05:41925 for suite in self.test_suites['basic_suites'].itervalues():
926 for key, test in suite.iteritems():
927 if not isinstance(test, dict):
928 # Some test definitions are just strings, such as CTS.
929 # Skip them.
930 continue
931
932 # This assumes the recipe logic which prefers 'test' to 'isolate_name'
933 # https://source.chromium.org/chromium/chromium/tools/build/+/master:scripts/slave/recipe_modules/chromium_tests/generators.py;l=89;drc=14c062ba0eb418d3c4623dde41a753241b9df06b
934 # TODO(crbug.com/1035124): clean this up.
935 isolate_name = test.get('test') or test.get('isolate_name') or key
936 gn_entry = self.gn_isolate_map.get(isolate_name)
937 if gn_entry:
Corentin Wallez55b8e772020-04-24 17:39:28938 label = gn_entry['label']
939
940 if label.count(':') != 1:
941 raise BBGenErr(
942 'Malformed GN label "%s" in gn_isolate_map for key "%s",'
943 ' implicit names (like //f/b meaning //f/b:b) are disallowed.' %
944 (label, isolate_name))
945 if label.split(':')[1] != isolate_name:
946 raise BBGenErr(
947 'gn_isolate_map key name "%s" doesn\'t match GN target name in'
948 ' label "%s" see http://crbug.com/1071091 for details.' %
949 (isolate_name, label))
950
Chan Lia3ad1502020-04-28 05:32:11951 test['test_id_prefix'] = 'ninja:%s/' % label
Nodir Turakulovfce34292019-12-18 17:05:41952 else: # pragma: no cover
953 # Some tests do not have an entry gn_isolate_map.pyl, such as
954 # telemetry tests.
955 # TODO(crbug.com/1035304): require an entry in gn_isolate_map.
956 pass
957
Kenneth Russelleb60cbd22017-12-05 07:54:28958 def resolve_composition_test_suites(self):
Jeff Yoon8154e582019-12-03 23:30:01959 self.check_composition_type_test_suites('compound_suites')
Stephen Martinis54d64ad2018-09-21 22:16:20960
Jeff Yoon8154e582019-12-03 23:30:01961 compound_suites = self.test_suites.get('compound_suites', {})
962 # check_composition_type_test_suites() checks that all basic suites
963 # referenced by compound suites exist.
964 basic_suites = self.test_suites.get('basic_suites')
965
966 for name, value in compound_suites.iteritems():
967 # Resolve this to a dictionary.
968 full_suite = {}
969 for entry in value:
970 suite = basic_suites[entry]
971 full_suite.update(suite)
972 compound_suites[name] = full_suite
973
Jeff Yoon67c3e832020-02-08 07:39:38974 def resolve_variants(self, basic_test_definition, variants):
975 """ Merge variant-defined configurations to each test case definition in a
976 test suite.
977
978 The output maps a unique test name to an array of configurations because
979 there may exist more than one definition for a test name using variants. The
980 test name is referenced while mapping machines to test suites, so unpacking
981 the array is done by the generators.
982
983 Args:
984 basic_test_definition: a {} defined test suite in the format
985 test_name:test_config
986 variants: an [] of {} defining configurations to be applied to each test
987 case in the basic test_definition
988
989 Return:
990 a {} of test_name:[{}], where each {} is a merged configuration
991 """
992
993 # Each test in a basic test suite will have a definition per variant.
994 test_suite = {}
995 for test_name, test_config in basic_test_definition.iteritems():
996 definitions = []
997 for variant in variants:
Jeff Yoonda581c32020-03-06 03:56:05998 # Unpack the variant from variants.pyl if it's string based.
999 if isinstance(variant, str):
1000 variant = self.variants[variant]
1001
Jeff Yoon67c3e832020-02-08 07:39:381002 # Clone a copy of test_config so that we can have a uniquely updated
1003 # version of it per variant
1004 cloned_config = copy.deepcopy(test_config)
1005 # The variant definition needs to be re-used for each test, so we'll
1006 # create a clone and work with it as well.
1007 cloned_variant = copy.deepcopy(variant)
1008
1009 cloned_config['args'] = (cloned_config.get('args', []) +
1010 cloned_variant.get('args', []))
1011 cloned_config['mixins'] = (cloned_config.get('mixins', []) +
1012 cloned_variant.get('mixins', []))
1013
1014 basic_swarming_def = cloned_config.get('swarming', {})
1015 variant_swarming_def = cloned_variant.get('swarming', {})
1016 if basic_swarming_def and variant_swarming_def:
1017 if ('dimension_sets' in basic_swarming_def and
1018 'dimension_sets' in variant_swarming_def):
1019 # Retain swarming dimension set merge behavior when both variant and
1020 # the basic test configuration both define it
1021 self.dictionary_merge(basic_swarming_def, variant_swarming_def)
1022 # Remove dimension_sets from the variant definition, so that it does
1023 # not replace what's been done by dictionary_merge in the update
1024 # call below.
1025 del variant_swarming_def['dimension_sets']
1026
1027 # Update the swarming definition with whatever is defined for swarming
1028 # by the variant.
1029 basic_swarming_def.update(variant_swarming_def)
1030 cloned_config['swarming'] = basic_swarming_def
1031
1032 # The identifier is used to make the name of the test unique.
1033 # Generators in the recipe uniquely identify a test by it's name, so we
1034 # don't want to have the same name for each variant.
1035 cloned_config['name'] = '{}_{}'.format(test_name,
1036 cloned_variant['identifier'])
Jeff Yoon67c3e832020-02-08 07:39:381037 definitions.append(cloned_config)
1038 test_suite[test_name] = definitions
1039 return test_suite
1040
Jeff Yoon8154e582019-12-03 23:30:011041 def resolve_matrix_compound_test_suites(self):
Jeff Yoon67c3e832020-02-08 07:39:381042 self.check_composition_type_test_suites('matrix_compound_suites',
1043 [check_matrix_identifier])
Jeff Yoon8154e582019-12-03 23:30:011044
1045 matrix_compound_suites = self.test_suites.get('matrix_compound_suites', {})
Jeff Yoon67c3e832020-02-08 07:39:381046 # check_composition_type_test_suites() checks that all basic suites are
Jeff Yoon8154e582019-12-03 23:30:011047 # referenced by matrix suites exist.
1048 basic_suites = self.test_suites.get('basic_suites')
1049
Jeff Yoon67c3e832020-02-08 07:39:381050 for test_name, matrix_config in matrix_compound_suites.iteritems():
Jeff Yoon8154e582019-12-03 23:30:011051 full_suite = {}
Jeff Yoon67c3e832020-02-08 07:39:381052
1053 for test_suite, mtx_test_suite_config in matrix_config.iteritems():
1054 basic_test_def = copy.deepcopy(basic_suites[test_suite])
1055
1056 if 'variants' in mtx_test_suite_config:
1057 result = self.resolve_variants(basic_test_def,
1058 mtx_test_suite_config['variants'])
1059 full_suite.update(result)
1060 matrix_compound_suites[test_name] = full_suite
Kenneth Russelleb60cbd22017-12-05 07:54:281061
1062 def link_waterfalls_to_test_suites(self):
1063 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431064 for tester_name, tester in waterfall['machines'].iteritems():
1065 for suite, value in tester.get('test_suites', {}).iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281066 if not value in self.test_suites:
1067 # Hard / impossible to cover this in the unit test.
1068 raise self.unknown_test_suite(
1069 value, tester_name, waterfall['name']) # pragma: no cover
1070 tester['test_suites'][suite] = self.test_suites[value]
1071
1072 def load_configuration_files(self):
1073 self.waterfalls = self.load_pyl_file('waterfalls.pyl')
1074 self.test_suites = self.load_pyl_file('test_suites.pyl')
1075 self.exceptions = self.load_pyl_file('test_suite_exceptions.pyl')
Stephen Martinisb72f6d22018-10-04 23:29:011076 self.mixins = self.load_pyl_file('mixins.pyl')
Nodir Turakulovfce34292019-12-18 17:05:411077 self.gn_isolate_map = self.load_pyl_file('gn_isolate_map.pyl')
Jeff Yoonda581c32020-03-06 03:56:051078 self.variants = self.load_pyl_file('variants.pyl')
Kenneth Russelleb60cbd22017-12-05 07:54:281079
1080 def resolve_configuration_files(self):
Chan Lia3ad1502020-04-28 05:32:111081 self.resolve_test_id_prefixes()
Kenneth Russelleb60cbd22017-12-05 07:54:281082 self.resolve_composition_test_suites()
Jeff Yoon8154e582019-12-03 23:30:011083 self.resolve_matrix_compound_test_suites()
1084 self.flatten_test_suites()
Kenneth Russelleb60cbd22017-12-05 07:54:281085 self.link_waterfalls_to_test_suites()
1086
Nico Weberd18b8962018-05-16 19:39:381087 def unknown_bot(self, bot_name, waterfall_name):
1088 return BBGenErr(
1089 'Unknown bot name "%s" on waterfall "%s"' % (bot_name, waterfall_name))
1090
Kenneth Russelleb60cbd22017-12-05 07:54:281091 def unknown_test_suite(self, suite_name, bot_name, waterfall_name):
1092 return BBGenErr(
Nico Weberd18b8962018-05-16 19:39:381093 'Test suite %s from machine %s on waterfall %s not present in '
Kenneth Russelleb60cbd22017-12-05 07:54:281094 'test_suites.pyl' % (suite_name, bot_name, waterfall_name))
1095
1096 def unknown_test_suite_type(self, suite_type, bot_name, waterfall_name):
1097 return BBGenErr(
1098 'Unknown test suite type ' + suite_type + ' in bot ' + bot_name +
1099 ' on waterfall ' + waterfall_name)
1100
Stephen Martinisb72f6d22018-10-04 23:29:011101 def apply_all_mixins(self, test, waterfall, builder_name, builder):
Stephen Martinis0382bc12018-09-17 22:29:071102 """Applies all present swarming mixins to the test for a given builder.
Stephen Martinisb6a50492018-09-12 23:59:321103
1104 Checks in the waterfall, builder, and test objects for mixins.
1105 """
1106 def valid_mixin(mixin_name):
1107 """Asserts that the mixin is valid."""
Stephen Martinisb72f6d22018-10-04 23:29:011108 if mixin_name not in self.mixins:
Stephen Martinisb6a50492018-09-12 23:59:321109 raise BBGenErr("bad mixin %s" % mixin_name)
Jeff Yoon67c3e832020-02-08 07:39:381110
Stephen Martinisb6a50492018-09-12 23:59:321111 def must_be_list(mixins, typ, name):
1112 """Asserts that given mixins are a list."""
1113 if not isinstance(mixins, list):
1114 raise BBGenErr("'%s' in %s '%s' must be a list" % (mixins, typ, name))
1115
Brian Sheedy7658c982020-01-08 02:27:581116 test_name = test.get('name')
1117 remove_mixins = set()
1118 if 'remove_mixins' in builder:
1119 must_be_list(builder['remove_mixins'], 'builder', builder_name)
1120 for rm in builder['remove_mixins']:
1121 valid_mixin(rm)
1122 remove_mixins.add(rm)
1123 if 'remove_mixins' in test:
1124 must_be_list(test['remove_mixins'], 'test', test_name)
1125 for rm in test['remove_mixins']:
1126 valid_mixin(rm)
1127 remove_mixins.add(rm)
1128 del test['remove_mixins']
1129
Stephen Martinisb72f6d22018-10-04 23:29:011130 if 'mixins' in waterfall:
1131 must_be_list(waterfall['mixins'], 'waterfall', waterfall['name'])
1132 for mixin in waterfall['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581133 if mixin in remove_mixins:
1134 continue
Stephen Martinisb6a50492018-09-12 23:59:321135 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011136 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321137
Stephen Martinisb72f6d22018-10-04 23:29:011138 if 'mixins' in builder:
1139 must_be_list(builder['mixins'], 'builder', builder_name)
1140 for mixin in builder['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581141 if mixin in remove_mixins:
1142 continue
Stephen Martinisb6a50492018-09-12 23:59:321143 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011144 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321145
Stephen Martinisb72f6d22018-10-04 23:29:011146 if not 'mixins' in test:
Stephen Martinis0382bc12018-09-17 22:29:071147 return test
1148
Stephen Martinis2a0667022018-09-25 22:31:141149 if not test_name:
1150 test_name = test.get('test')
1151 if not test_name: # pragma: no cover
1152 # Not the best name, but we should say something.
1153 test_name = str(test)
Stephen Martinisb72f6d22018-10-04 23:29:011154 must_be_list(test['mixins'], 'test', test_name)
1155 for mixin in test['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581156 # We don't bother checking if the given mixin is in remove_mixins here
1157 # since this is already the lowest level, so if a mixin is added here that
1158 # we don't want, we can just delete its entry.
Stephen Martinis0382bc12018-09-17 22:29:071159 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011160 test = self.apply_mixin(self.mixins[mixin], test)
Jeff Yoon67c3e832020-02-08 07:39:381161 del test['mixins']
Stephen Martinis0382bc12018-09-17 22:29:071162 return test
Stephen Martinisb6a50492018-09-12 23:59:321163
Stephen Martinisb72f6d22018-10-04 23:29:011164 def apply_mixin(self, mixin, test):
1165 """Applies a mixin to a test.
Stephen Martinisb6a50492018-09-12 23:59:321166
Stephen Martinis0382bc12018-09-17 22:29:071167 Mixins will not override an existing key. This is to ensure exceptions can
1168 override a setting a mixin applies.
1169
Stephen Martinisb72f6d22018-10-04 23:29:011170 Swarming dimensions are handled in a special way. Instead of specifying
Stephen Martinisb6a50492018-09-12 23:59:321171 'dimension_sets', which is how normal test suites specify their dimensions,
1172 you specify a 'dimensions' key, which maps to a dictionary. This dictionary
1173 is then applied to every dimension set in the test.
Stephen Martinisb72f6d22018-10-04 23:29:011174
Stephen Martinisb6a50492018-09-12 23:59:321175 """
1176 new_test = copy.deepcopy(test)
1177 mixin = copy.deepcopy(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011178 if 'swarming' in mixin:
1179 swarming_mixin = mixin['swarming']
1180 new_test.setdefault('swarming', {})
Brian Sheedycae63b22020-06-10 22:52:111181 # Copy over any explicit dimension sets first so that they will be updated
1182 # by any subsequent 'dimensions' entries.
1183 if 'dimension_sets' in swarming_mixin:
1184 existing_dimension_sets = new_test['swarming'].setdefault(
1185 'dimension_sets', [])
1186 # Appending to the existing list could potentially result in different
1187 # behavior depending on the order the mixins were applied, but that's
1188 # already the case for other parts of mixins, so trust that the user
1189 # will verify that the generated output is correct before submitting.
1190 for dimension_set in swarming_mixin['dimension_sets']:
1191 if dimension_set not in existing_dimension_sets:
1192 existing_dimension_sets.append(dimension_set)
1193 del swarming_mixin['dimension_sets']
Stephen Martinisb72f6d22018-10-04 23:29:011194 if 'dimensions' in swarming_mixin:
1195 new_test['swarming'].setdefault('dimension_sets', [{}])
1196 for dimension_set in new_test['swarming']['dimension_sets']:
1197 dimension_set.update(swarming_mixin['dimensions'])
1198 del swarming_mixin['dimensions']
Stephen Martinisb72f6d22018-10-04 23:29:011199 # python dict update doesn't do recursion at all. Just hard code the
1200 # nested update we need (mixin['swarming'] shouldn't clobber
1201 # test['swarming'], but should update it).
1202 new_test['swarming'].update(swarming_mixin)
1203 del mixin['swarming']
1204
Wezc0e835b702018-10-30 00:38:411205 if '$mixin_append' in mixin:
1206 # Values specified under $mixin_append should be appended to existing
1207 # lists, rather than replacing them.
1208 mixin_append = mixin['$mixin_append']
1209 for key in mixin_append:
1210 new_test.setdefault(key, [])
1211 if not isinstance(mixin_append[key], list):
1212 raise BBGenErr(
1213 'Key "' + key + '" in $mixin_append must be a list.')
1214 if not isinstance(new_test[key], list):
1215 raise BBGenErr(
1216 'Cannot apply $mixin_append to non-list "' + key + '".')
1217 new_test[key].extend(mixin_append[key])
1218 if 'args' in mixin_append:
1219 new_test['args'] = self.maybe_fixup_args_array(new_test['args'])
1220 del mixin['$mixin_append']
1221
Stephen Martinisb72f6d22018-10-04 23:29:011222 new_test.update(mixin)
Stephen Martinisb6a50492018-09-12 23:59:321223 return new_test
1224
Greg Gutermanf60eb052020-03-12 17:40:011225 def generate_output_tests(self, waterfall):
1226 """Generates the tests for a waterfall.
1227
1228 Args:
1229 waterfall: a dictionary parsed from a master pyl file
1230 Returns:
1231 A dictionary mapping builders to test specs
1232 """
1233 return {
1234 name: self.get_tests_for_config(waterfall, name, config)
1235 for name, config
1236 in waterfall['machines'].iteritems()
1237 }
1238
1239 def get_tests_for_config(self, waterfall, name, config):
Greg Guterman5c6144152020-02-28 20:08:531240 generator_map = self.get_test_generator_map()
1241 test_type_remapper = self.get_test_type_remapper()
Kenneth Russelleb60cbd22017-12-05 07:54:281242
Greg Gutermanf60eb052020-03-12 17:40:011243 tests = {}
1244 # Copy only well-understood entries in the machine's configuration
1245 # verbatim into the generated JSON.
1246 if 'additional_compile_targets' in config:
1247 tests['additional_compile_targets'] = config[
1248 'additional_compile_targets']
1249 for test_type, input_tests in config.get('test_suites', {}).iteritems():
1250 if test_type not in generator_map:
1251 raise self.unknown_test_suite_type(
1252 test_type, name, waterfall['name']) # pragma: no cover
1253 test_generator = generator_map[test_type]
1254 # Let multiple kinds of generators generate the same kinds
1255 # of tests. For example, gpu_telemetry_tests are a
1256 # specialization of isolated_scripts.
1257 new_tests = test_generator.generate(
1258 waterfall, name, config, input_tests)
1259 remapped_test_type = test_type_remapper.get(test_type, test_type)
1260 tests[remapped_test_type] = test_generator.sort(
1261 tests.get(remapped_test_type, []) + new_tests)
1262
1263 return tests
1264
1265 def jsonify(self, all_tests):
1266 return json.dumps(
1267 all_tests, indent=2, separators=(',', ': '),
1268 sort_keys=True) + '\n'
1269
1270 def generate_outputs(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281271 self.load_configuration_files()
1272 self.resolve_configuration_files()
1273 filters = self.args.waterfall_filters
Greg Gutermanf60eb052020-03-12 17:40:011274 result = collections.defaultdict(dict)
1275
1276 required_fields = ('project', 'bucket', 'name')
1277 for waterfall in self.waterfalls:
1278 for field in required_fields:
1279 # Verify required fields
1280 if field not in waterfall:
1281 raise BBGenErr("Waterfall %s has no %s" % (waterfall['name'], field))
1282
1283 # Handle filter flag, if specified
1284 if filters and waterfall['name'] not in filters:
1285 continue
1286
1287 # Join config files and hardcoded values together
1288 all_tests = self.generate_output_tests(waterfall)
1289 result[waterfall['name']] = all_tests
1290
1291 # Deduce per-bucket mappings
1292 # This will be the standard after masternames are gone
1293 bucket_filename = waterfall['project'] + '.' + waterfall['bucket']
1294 for buildername in waterfall['machines'].keys():
1295 result[bucket_filename][buildername] = all_tests[buildername]
1296
1297 # Add do not edit warning
1298 for tests in result.values():
1299 tests['AAAAA1 AUTOGENERATED FILE DO NOT EDIT'] = {}
1300 tests['AAAAA2 See generate_buildbot_json.py to make changes'] = {}
1301
1302 return result
1303
1304 def write_json_result(self, result): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281305 suffix = '.json'
1306 if self.args.new_files:
1307 suffix = '.new' + suffix
Greg Gutermanf60eb052020-03-12 17:40:011308
1309 for filename, contents in result.items():
1310 jsonstr = self.jsonify(contents)
1311 self.write_file(self.pyl_file_path(filename + suffix), jsonstr)
Kenneth Russelleb60cbd22017-12-05 07:54:281312
Nico Weberd18b8962018-05-16 19:39:381313 def get_valid_bot_names(self):
John Budorick699282e2019-02-13 01:27:331314 # Extract bot names from infra/config/luci-milo.cfg.
Stephen Martinis26627cf2018-12-19 01:51:421315 # NOTE: This reference can cause issues; if a file changes there, the
1316 # presubmit here won't be run by default. A manually maintained list there
1317 # tries to run presubmit here when luci-milo.cfg is changed. If any other
1318 # references to configs outside of this directory are added, please change
1319 # their presubmit to run `generate_buildbot_json.py -c`, so that the tree
1320 # never ends up in an invalid state.
Garrett Beaty2a02de3c2020-05-15 13:57:351321 project_star = glob.glob(
1322 os.path.join(self.args.infra_config_dir, 'project.star'))
1323 if project_star:
1324 is_master_pattern = re.compile('is_master\s*=\s*(True|False)')
1325 for l in self.read_file(project_star[0]).splitlines():
1326 match = is_master_pattern.search(l)
1327 if match:
1328 if match.group(1) == 'False':
1329 return None
1330 break
Nico Weberd18b8962018-05-16 19:39:381331 bot_names = set()
Garrett Beatyd5ca75962020-05-07 16:58:311332 milo_configs = glob.glob(
1333 os.path.join(self.args.infra_config_dir, 'generated', 'luci-milo*.cfg'))
John Budorickc12abd12018-08-14 19:37:431334 for c in milo_configs:
1335 for l in self.read_file(c).splitlines():
1336 if (not 'name: "buildbucket/luci.chromium.' in l and
Garrett Beatyd5ca75962020-05-07 16:58:311337 not 'name: "buildbucket/luci.chrome.' in l):
John Budorickc12abd12018-08-14 19:37:431338 continue
1339 # l looks like
1340 # `name: "buildbucket/luci.chromium.try/win_chromium_dbg_ng"`
1341 # Extract win_chromium_dbg_ng part.
1342 bot_names.add(l[l.rindex('/') + 1:l.rindex('"')])
Nico Weberd18b8962018-05-16 19:39:381343 return bot_names
1344
Ben Pastene9a010082019-09-25 20:41:371345 def get_builders_that_do_not_actually_exist(self):
Kenneth Russell8a386d42018-06-02 09:48:011346 # Some of the bots on the chromium.gpu.fyi waterfall in particular
1347 # are defined only to be mirrored into trybots, and don't actually
1348 # exist on any of the waterfalls or consoles.
1349 return [
Michael Spangeb07eba62019-05-14 22:22:581350 'GPU FYI Fuchsia Builder',
Yuly Novikoveb26b812019-07-26 02:08:191351 'ANGLE GPU Android Release (Nexus 5X)',
Jamie Madillda894ce2019-04-08 17:19:171352 'ANGLE GPU Linux Release (Intel HD 630)',
1353 'ANGLE GPU Linux Release (NVIDIA)',
1354 'ANGLE GPU Mac Release (Intel)',
1355 'ANGLE GPU Mac Retina Release (AMD)',
1356 'ANGLE GPU Mac Retina Release (NVIDIA)',
Yuly Novikovbc1ccff2019-08-03 00:05:491357 'ANGLE GPU Win10 x64 Release (Intel HD 630)',
1358 'ANGLE GPU Win10 x64 Release (NVIDIA)',
Kenneth Russell8a386d42018-06-02 09:48:011359 'Optional Android Release (Nexus 5X)',
1360 'Optional Linux Release (Intel HD 630)',
1361 'Optional Linux Release (NVIDIA)',
1362 'Optional Mac Release (Intel)',
1363 'Optional Mac Retina Release (AMD)',
1364 'Optional Mac Retina Release (NVIDIA)',
Yuly Novikovbc1ccff2019-08-03 00:05:491365 'Optional Win10 x64 Release (Intel HD 630)',
1366 'Optional Win10 x64 Release (NVIDIA)',
Kenneth Russell8a386d42018-06-02 09:48:011367 'Win7 ANGLE Tryserver (AMD)',
Nico Weber7fc8b9da2018-06-08 19:22:081368 # chromium.fyi
Dirk Pranke85369442018-06-16 02:01:291369 'linux-blink-rel-dummy',
Ilia Samsonov53f1acc2020-05-22 00:57:051370 'linux-blink-optional-highdpi-rel-dummy',
Dirk Pranke85369442018-06-16 02:01:291371 'mac10.10-blink-rel-dummy',
1372 'mac10.11-blink-rel-dummy',
1373 'mac10.12-blink-rel-dummy',
Kenneth Russell911da0d32018-07-17 21:39:201374 'mac10.13_retina-blink-rel-dummy',
Dirk Pranke85369442018-06-16 02:01:291375 'mac10.13-blink-rel-dummy',
John Chenad978322019-12-16 18:07:211376 'mac10.14-blink-rel-dummy',
Ilia Samsonov7efe05e2020-05-07 19:00:461377 'mac10.15-blink-rel-dummy',
Dirk Pranke85369442018-06-16 02:01:291378 'win7-blink-rel-dummy',
1379 'win10-blink-rel-dummy',
Nico Weber7fc8b9da2018-06-08 19:22:081380 'Dummy WebKit Mac10.13',
Philip Rogers639990262018-12-08 00:13:331381 'WebKit Linux composite_after_paint Dummy Builder',
Scott Violet744e04662019-08-19 23:51:531382 'WebKit Linux layout_ng_disabled Builder',
Stephen Martinis769b25112018-08-30 18:52:061383 # chromium, due to https://crbug.com/878915
1384 'win-dbg',
1385 'win32-dbg',
Stephen Martinis47d771352019-04-24 23:51:331386 'win-archive-dbg',
1387 'win32-archive-dbg',
Sajjad Mirza2924a012019-12-20 03:46:541388 # TODO(crbug.com/1033753) Delete these when coverage is enabled by default
1389 # on Windows tryjobs.
1390 'GPU Win x64 Builder Code Coverage',
1391 'Win x64 Builder Code Coverage',
1392 'Win10 Tests x64 Code Coverage',
1393 'Win10 x64 Release (NVIDIA) Code Coverage',
Sajjad Mirzafa15665e2020-02-10 23:41:041394 # TODO(crbug.com/1024915) Delete these when coverage is enabled by default
1395 # on Mac OS tryjobs.
1396 'Mac Builder Code Coverage',
1397 'Mac10.13 Tests Code Coverage',
1398 'GPU Mac Builder Code Coverage',
1399 'Mac Release (Intel) Code Coverage',
1400 'Mac Retina Release (AMD) Code Coverage',
Kenneth Russell8a386d42018-06-02 09:48:011401 ]
1402
Ben Pastene9a010082019-09-25 20:41:371403 def get_internal_waterfalls(self):
1404 # Similar to get_builders_that_do_not_actually_exist above, but for
1405 # waterfalls defined in internal configs.
Jeff Yoon8acfdce2020-04-20 22:38:071406 return ['chrome', 'chrome.pgo']
Ben Pastene9a010082019-09-25 20:41:371407
Stephen Martinisf83893722018-09-19 00:02:181408 def check_input_file_consistency(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201409 self.check_input_files_sorting(verbose)
1410
Kenneth Russelleb60cbd22017-12-05 07:54:281411 self.load_configuration_files()
Jeff Yoon8154e582019-12-03 23:30:011412 self.check_composition_type_test_suites('compound_suites')
Jeff Yoon67c3e832020-02-08 07:39:381413 self.check_composition_type_test_suites('matrix_compound_suites',
1414 [check_matrix_identifier])
Chan Lia3ad1502020-04-28 05:32:111415 self.resolve_test_id_prefixes()
Stephen Martinis54d64ad2018-09-21 22:16:201416 self.flatten_test_suites()
Nico Weberd18b8962018-05-16 19:39:381417
1418 # All bots should exist.
1419 bot_names = self.get_valid_bot_names()
Ben Pastene9a010082019-09-25 20:41:371420 builders_that_dont_exist = self.get_builders_that_do_not_actually_exist()
Garrett Beaty2a02de3c2020-05-15 13:57:351421 if bot_names is not None:
1422 internal_waterfalls = self.get_internal_waterfalls()
1423 for waterfall in self.waterfalls:
1424 # TODO(crbug.com/991417): Remove the need for this exception.
1425 if waterfall['name'] in internal_waterfalls:
Kenneth Russell8a386d42018-06-02 09:48:011426 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351427 for bot_name in waterfall['machines']:
1428 if bot_name in builders_that_dont_exist:
Kenneth Russell78fd8702018-05-17 01:15:521429 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351430 if bot_name not in bot_names:
1431 if waterfall['name'] in ['client.v8.chromium', 'client.v8.fyi']:
1432 # TODO(thakis): Remove this once these bots move to luci.
1433 continue # pragma: no cover
1434 if waterfall['name'] in ['tryserver.webrtc',
1435 'webrtc.chromium.fyi.experimental']:
1436 # These waterfalls have their bot configs in a different repo.
1437 # so we don't know about their bot names.
1438 continue # pragma: no cover
1439 if waterfall['name'] in ['client.devtools-frontend.integration',
1440 'tryserver.devtools-frontend',
1441 'chromium.devtools-frontend']:
1442 continue # pragma: no cover
1443 raise self.unknown_bot(bot_name, waterfall['name'])
Nico Weberd18b8962018-05-16 19:39:381444
Kenneth Russelleb60cbd22017-12-05 07:54:281445 # All test suites must be referenced.
1446 suites_seen = set()
1447 generator_map = self.get_test_generator_map()
1448 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431449 for bot_name, tester in waterfall['machines'].iteritems():
1450 for suite_type, suite in tester.get('test_suites', {}).iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281451 if suite_type not in generator_map:
1452 raise self.unknown_test_suite_type(suite_type, bot_name,
1453 waterfall['name'])
1454 if suite not in self.test_suites:
1455 raise self.unknown_test_suite(suite, bot_name, waterfall['name'])
1456 suites_seen.add(suite)
1457 # Since we didn't resolve the configuration files, this set
1458 # includes both composition test suites and regular ones.
1459 resolved_suites = set()
1460 for suite_name in suites_seen:
1461 suite = self.test_suites[suite_name]
Jeff Yoon8154e582019-12-03 23:30:011462 for sub_suite in suite:
1463 resolved_suites.add(sub_suite)
Kenneth Russelleb60cbd22017-12-05 07:54:281464 resolved_suites.add(suite_name)
1465 # At this point, every key in test_suites.pyl should be referenced.
1466 missing_suites = set(self.test_suites.keys()) - resolved_suites
1467 if missing_suites:
1468 raise BBGenErr('The following test suites were unreferenced by bots on '
1469 'the waterfalls: ' + str(missing_suites))
1470
1471 # All test suite exceptions must refer to bots on the waterfall.
1472 all_bots = set()
1473 missing_bots = set()
1474 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431475 for bot_name, tester in waterfall['machines'].iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281476 all_bots.add(bot_name)
Kenneth Russell8ceeabf2017-12-11 17:53:281477 # In order to disambiguate between bots with the same name on
1478 # different waterfalls, support has been added to various
1479 # exceptions for concatenating the waterfall name after the bot
1480 # name.
1481 all_bots.add(bot_name + ' ' + waterfall['name'])
Kenneth Russelleb60cbd22017-12-05 07:54:281482 for exception in self.exceptions.itervalues():
Nico Weberd18b8962018-05-16 19:39:381483 removals = (exception.get('remove_from', []) +
1484 exception.get('remove_gtest_from', []) +
1485 exception.get('modifications', {}).keys())
1486 for removal in removals:
Kenneth Russelleb60cbd22017-12-05 07:54:281487 if removal not in all_bots:
1488 missing_bots.add(removal)
Stephen Martiniscc70c962018-07-31 21:22:411489
Ben Pastene9a010082019-09-25 20:41:371490 missing_bots = missing_bots - set(builders_that_dont_exist)
Kenneth Russelleb60cbd22017-12-05 07:54:281491 if missing_bots:
1492 raise BBGenErr('The following nonexistent machines were referenced in '
1493 'the test suite exceptions: ' + str(missing_bots))
1494
Stephen Martinis0382bc12018-09-17 22:29:071495 # All mixins must be referenced
1496 seen_mixins = set()
1497 for waterfall in self.waterfalls:
Stephen Martinisb72f6d22018-10-04 23:29:011498 seen_mixins = seen_mixins.union(waterfall.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071499 for bot_name, tester in waterfall['machines'].iteritems():
Stephen Martinisb72f6d22018-10-04 23:29:011500 seen_mixins = seen_mixins.union(tester.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071501 for suite in self.test_suites.values():
1502 if isinstance(suite, list):
1503 # Don't care about this, it's a composition, which shouldn't include a
1504 # swarming mixin.
1505 continue
1506
1507 for test in suite.values():
1508 if not isinstance(test, dict):
1509 # Some test suites have top level keys, which currently can't be
1510 # swarming mixin entries. Ignore them
1511 continue
1512
Stephen Martinisb72f6d22018-10-04 23:29:011513 seen_mixins = seen_mixins.union(test.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071514
Stephen Martinisb72f6d22018-10-04 23:29:011515 missing_mixins = set(self.mixins.keys()) - seen_mixins
Stephen Martinis0382bc12018-09-17 22:29:071516 if missing_mixins:
1517 raise BBGenErr('The following mixins are unreferenced: %s. They must be'
1518 ' referenced in a waterfall, machine, or test suite.' % (
1519 str(missing_mixins)))
1520
Jeff Yoonda581c32020-03-06 03:56:051521 # All variant references must be referenced
1522 seen_variants = set()
1523 for suite in self.test_suites.values():
1524 if isinstance(suite, list):
1525 continue
1526
1527 for test in suite.values():
1528 if isinstance(test, dict):
1529 for variant in test.get('variants', []):
1530 if isinstance(variant, str):
1531 seen_variants.add(variant)
1532
1533 missing_variants = set(self.variants.keys()) - seen_variants
1534 if missing_variants:
1535 raise BBGenErr('The following variants were unreferenced: %s. They must '
1536 'be referenced in a matrix test suite under the variants '
1537 'key.' % str(missing_variants))
1538
Stephen Martinis54d64ad2018-09-21 22:16:201539
1540 def type_assert(self, node, typ, filename, verbose=False):
1541 """Asserts that the Python AST node |node| is of type |typ|.
1542
1543 If verbose is set, it prints out some helpful context lines, showing where
1544 exactly the error occurred in the file.
1545 """
1546 if not isinstance(node, typ):
1547 if verbose:
1548 lines = [""] + self.read_file(filename).splitlines()
1549
1550 context = 2
1551 lines_start = max(node.lineno - context, 0)
1552 # Add one to include the last line
1553 lines_end = min(node.lineno + context, len(lines)) + 1
1554 lines = (
1555 ['== %s ==\n' % filename] +
1556 ["<snip>\n"] +
1557 ['%d %s' % (lines_start + i, line) for i, line in enumerate(
1558 lines[lines_start:lines_start + context])] +
1559 ['-' * 80 + '\n'] +
1560 ['%d %s' % (node.lineno, lines[node.lineno])] +
1561 ['-' * (node.col_offset + 3) + '^' + '-' * (
1562 80 - node.col_offset - 4) + '\n'] +
1563 ['%d %s' % (node.lineno + 1 + i, line) for i, line in enumerate(
1564 lines[node.lineno + 1:lines_end])] +
1565 ["<snip>\n"]
1566 )
1567 # Print out a useful message when a type assertion fails.
1568 for l in lines:
1569 self.print_line(l.strip())
1570
1571 node_dumped = ast.dump(node, annotate_fields=False)
1572 # If the node is huge, truncate it so everything fits in a terminal
1573 # window.
1574 if len(node_dumped) > 60: # pragma: no cover
1575 node_dumped = node_dumped[:30] + ' <SNIP> ' + node_dumped[-30:]
1576 raise BBGenErr(
1577 'Invalid .pyl file %r. Python AST node %r on line %s expected to'
1578 ' be %s, is %s' % (
1579 filename, node_dumped,
1580 node.lineno, typ, type(node)))
1581
Stephen Martinis5bef0fc42020-01-06 22:47:531582 def check_ast_list_formatted(self, keys, filename, verbose,
Stephen Martinis1384ff92020-01-07 19:52:151583 check_sorting=True):
Stephen Martinis5bef0fc42020-01-06 22:47:531584 """Checks if a list of ast keys are correctly formatted.
Stephen Martinis54d64ad2018-09-21 22:16:201585
Stephen Martinis5bef0fc42020-01-06 22:47:531586 Currently only checks to ensure they're correctly sorted, and that there
1587 are no duplicates.
1588
1589 Args:
1590 keys: An python list of AST nodes.
1591
1592 It's a list of AST nodes instead of a list of strings because
1593 when verbose is set, it tries to print out context of where the
1594 diffs are in the file.
1595 filename: The name of the file this node is from.
1596 verbose: If set, print out diff information about how the keys are
1597 incorrectly formatted.
1598 check_sorting: If true, checks if the list is sorted.
1599 Returns:
1600 If the keys are correctly formatted.
1601 """
1602 if not keys:
1603 return True
1604
1605 assert isinstance(keys[0], ast.Str)
1606
1607 keys_strs = [k.s for k in keys]
1608 # Keys to diff against. Used below.
1609 keys_to_diff_against = None
1610 # If the list is properly formatted.
1611 list_formatted = True
1612
1613 # Duplicates are always bad.
1614 if len(set(keys_strs)) != len(keys_strs):
1615 list_formatted = False
1616 keys_to_diff_against = list(collections.OrderedDict.fromkeys(keys_strs))
1617
1618 if check_sorting and sorted(keys_strs) != keys_strs:
1619 list_formatted = False
1620 if list_formatted:
1621 return True
1622
1623 if verbose:
1624 line_num = keys[0].lineno
1625 keys = [k.s for k in keys]
1626 if check_sorting:
1627 # If we have duplicates, sorting this will take care of it anyways.
1628 keys_to_diff_against = sorted(set(keys))
1629 # else, keys_to_diff_against is set above already
1630
1631 self.print_line('=' * 80)
1632 self.print_line('(First line of keys is %s)' % line_num)
1633 for line in difflib.context_diff(
1634 keys, keys_to_diff_against,
1635 fromfile='current (%r)' % filename, tofile='sorted', lineterm=''):
1636 self.print_line(line)
1637 self.print_line('=' * 80)
1638
1639 return False
1640
Stephen Martinis1384ff92020-01-07 19:52:151641 def check_ast_dict_formatted(self, node, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531642 """Checks if an ast dictionary's keys are correctly formatted.
1643
1644 Just a simple wrapper around check_ast_list_formatted.
1645 Args:
1646 node: An AST node. Assumed to be a dictionary.
1647 filename: The name of the file this node is from.
1648 verbose: If set, print out diff information about how the keys are
1649 incorrectly formatted.
1650 check_sorting: If true, checks if the list is sorted.
1651 Returns:
1652 If the dictionary is correctly formatted.
1653 """
Stephen Martinis54d64ad2018-09-21 22:16:201654 keys = []
1655 # The keys of this dict are ordered as ordered in the file; normal python
1656 # dictionary keys are given an arbitrary order, but since we parsed the
1657 # file itself, the order as given in the file is preserved.
1658 for key in node.keys:
1659 self.type_assert(key, ast.Str, filename, verbose)
Stephen Martinis5bef0fc42020-01-06 22:47:531660 keys.append(key)
Stephen Martinis54d64ad2018-09-21 22:16:201661
Stephen Martinis1384ff92020-01-07 19:52:151662 return self.check_ast_list_formatted(keys, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181663
1664 def check_input_files_sorting(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201665 # TODO(https://crbug.com/886993): Add the ability for this script to
1666 # actually format the files, rather than just complain if they're
1667 # incorrectly formatted.
1668 bad_files = set()
Stephen Martinis5bef0fc42020-01-06 22:47:531669 def parse_file(filename):
1670 """Parses and validates a .pyl file.
Stephen Martinis54d64ad2018-09-21 22:16:201671
Stephen Martinis5bef0fc42020-01-06 22:47:531672 Returns an AST node representing the value in the pyl file."""
Stephen Martinisf83893722018-09-19 00:02:181673 parsed = ast.parse(self.read_file(self.pyl_file_path(filename)))
1674
Stephen Martinisf83893722018-09-19 00:02:181675 # Must be a module.
Stephen Martinis54d64ad2018-09-21 22:16:201676 self.type_assert(parsed, ast.Module, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181677 module = parsed.body
1678
1679 # Only one expression in the module.
Stephen Martinis54d64ad2018-09-21 22:16:201680 self.type_assert(module, list, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181681 if len(module) != 1: # pragma: no cover
1682 raise BBGenErr('Invalid .pyl file %s' % filename)
1683 expr = module[0]
Stephen Martinis54d64ad2018-09-21 22:16:201684 self.type_assert(expr, ast.Expr, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181685
Stephen Martinis5bef0fc42020-01-06 22:47:531686 return expr.value
1687
1688 # Handle this separately
1689 filename = 'waterfalls.pyl'
1690 value = parse_file(filename)
1691 # Value should be a list.
1692 self.type_assert(value, ast.List, filename, verbose)
1693
1694 keys = []
1695 for val in value.elts:
1696 self.type_assert(val, ast.Dict, filename, verbose)
1697 waterfall_name = None
1698 for key, val in zip(val.keys, val.values):
1699 self.type_assert(key, ast.Str, filename, verbose)
1700 if key.s == 'machines':
1701 if not self.check_ast_dict_formatted(val, filename, verbose):
1702 bad_files.add(filename)
1703
1704 if key.s == "name":
1705 self.type_assert(val, ast.Str, filename, verbose)
1706 waterfall_name = val
1707 assert waterfall_name
1708 keys.append(waterfall_name)
1709
Stephen Martinis1384ff92020-01-07 19:52:151710 if not self.check_ast_list_formatted(keys, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531711 bad_files.add(filename)
1712
1713 for filename in (
1714 'mixins.pyl',
1715 'test_suites.pyl',
1716 'test_suite_exceptions.pyl',
1717 ):
1718 value = parse_file(filename)
Stephen Martinisf83893722018-09-19 00:02:181719 # Value should be a dictionary.
Stephen Martinis54d64ad2018-09-21 22:16:201720 self.type_assert(value, ast.Dict, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181721
Stephen Martinis5bef0fc42020-01-06 22:47:531722 if not self.check_ast_dict_formatted(
1723 value, filename, verbose):
1724 bad_files.add(filename)
1725
Stephen Martinis54d64ad2018-09-21 22:16:201726 if filename == 'test_suites.pyl':
Jeff Yoon8154e582019-12-03 23:30:011727 expected_keys = ['basic_suites',
1728 'compound_suites',
1729 'matrix_compound_suites']
Stephen Martinis54d64ad2018-09-21 22:16:201730 actual_keys = [node.s for node in value.keys]
1731 assert all(key in expected_keys for key in actual_keys), (
1732 'Invalid %r file; expected keys %r, got %r' % (
1733 filename, expected_keys, actual_keys))
1734 suite_dicts = [node for node in value.values]
1735 # Only two keys should mean only 1 or 2 values
Jeff Yoon8154e582019-12-03 23:30:011736 assert len(suite_dicts) <= 3
Stephen Martinis54d64ad2018-09-21 22:16:201737 for suite_group in suite_dicts:
Stephen Martinis5bef0fc42020-01-06 22:47:531738 if not self.check_ast_dict_formatted(
Stephen Martinis54d64ad2018-09-21 22:16:201739 suite_group, filename, verbose):
1740 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181741
Stephen Martinis5bef0fc42020-01-06 22:47:531742 for key, suite in zip(value.keys, value.values):
1743 # The compound suites are checked in
1744 # 'check_composition_type_test_suites()'
1745 if key.s == 'basic_suites':
1746 for group in suite.values:
Stephen Martinis1384ff92020-01-07 19:52:151747 if not self.check_ast_dict_formatted(group, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531748 bad_files.add(filename)
1749 break
Stephen Martinis54d64ad2018-09-21 22:16:201750
Stephen Martinis5bef0fc42020-01-06 22:47:531751 elif filename == 'test_suite_exceptions.pyl':
1752 # Check the values for each test.
1753 for test in value.values:
1754 for kind, node in zip(test.keys, test.values):
1755 if isinstance(node, ast.Dict):
Stephen Martinis1384ff92020-01-07 19:52:151756 if not self.check_ast_dict_formatted(node, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531757 bad_files.add(filename)
1758 elif kind.s == 'remove_from':
1759 # Don't care about sorting; these are usually grouped, since the
1760 # same bug can affect multiple builders. Do want to make sure
1761 # there aren't duplicates.
1762 if not self.check_ast_list_formatted(node.elts, filename, verbose,
1763 check_sorting=False):
1764 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181765
1766 if bad_files:
1767 raise BBGenErr(
Stephen Martinis54d64ad2018-09-21 22:16:201768 'The following files have invalid keys: %s\n. They are either '
Stephen Martinis5bef0fc42020-01-06 22:47:531769 'unsorted, or have duplicates. Re-run this with --verbose to see '
1770 'more details.' % ', '.join(bad_files))
Stephen Martinisf83893722018-09-19 00:02:181771
Kenneth Russelleb60cbd22017-12-05 07:54:281772 def check_output_file_consistency(self, verbose=False):
1773 self.load_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011774 # All waterfalls/bucket .json files must have been written
1775 # by this script already.
Kenneth Russelleb60cbd22017-12-05 07:54:281776 self.resolve_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011777 ungenerated_files = set()
1778 for filename, expected_contents in self.generate_outputs().items():
1779 expected = self.jsonify(expected_contents)
1780 file_path = filename + '.json'
Zhiling Huangbe008172018-03-08 19:13:111781 current = self.read_file(self.pyl_file_path(file_path))
Kenneth Russelleb60cbd22017-12-05 07:54:281782 if expected != current:
Greg Gutermanf60eb052020-03-12 17:40:011783 ungenerated_files.add(filename)
John Budorick826d5ed2017-12-28 19:27:321784 if verbose: # pragma: no cover
Greg Gutermanf60eb052020-03-12 17:40:011785 self.print_line('File ' + filename +
1786 '.json did not have the following expected '
John Budorick826d5ed2017-12-28 19:27:321787 'contents:')
1788 for line in difflib.unified_diff(
1789 expected.splitlines(),
Stephen Martinis7eb8b612018-09-21 00:17:501790 current.splitlines(),
1791 fromfile='expected', tofile='current'):
1792 self.print_line(line)
Greg Gutermanf60eb052020-03-12 17:40:011793
1794 if ungenerated_files:
1795 raise BBGenErr(
1796 'The following files have not been properly '
1797 'autogenerated by generate_buildbot_json.py: ' +
1798 ', '.join([filename + '.json' for filename in ungenerated_files]))
Kenneth Russelleb60cbd22017-12-05 07:54:281799
1800 def check_consistency(self, verbose=False):
Stephen Martinis7eb8b612018-09-21 00:17:501801 self.check_input_file_consistency(verbose) # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281802 self.check_output_file_consistency(verbose) # pragma: no cover
1803
1804 def parse_args(self, argv): # pragma: no cover
Karen Qiane24b7ee2019-02-12 23:37:061805
1806 # RawTextHelpFormatter allows for styling of help statement
1807 parser = argparse.ArgumentParser(formatter_class=
1808 argparse.RawTextHelpFormatter)
1809
1810 group = parser.add_mutually_exclusive_group()
1811 group.add_argument(
Kenneth Russelleb60cbd22017-12-05 07:54:281812 '-c', '--check', action='store_true', help=
1813 'Do consistency checks of configuration and generated files and then '
1814 'exit. Used during presubmit. Causes the tool to not generate any files.')
Karen Qiane24b7ee2019-02-12 23:37:061815 group.add_argument(
1816 '--query', type=str, help=
1817 ("Returns raw JSON information of buildbots and tests.\n" +
1818 "Examples:\n" +
1819 " List all bots (all info):\n" +
1820 " --query bots\n\n" +
1821 " List all bots and only their associated tests:\n" +
1822 " --query bots/tests\n\n" +
1823 " List all information about 'bot1' " +
1824 "(make sure you have quotes):\n" +
1825 " --query bot/'bot1'\n\n" +
1826 " List tests running for 'bot1' (make sure you have quotes):\n" +
1827 " --query bot/'bot1'/tests\n\n" +
1828 " List all tests:\n" +
1829 " --query tests\n\n" +
1830 " List all tests and the bots running them:\n" +
1831 " --query tests/bots\n\n"+
1832 " List all tests that satisfy multiple parameters\n" +
1833 " (separation of parameters by '&' symbol):\n" +
1834 " --query tests/'device_os:Android&device_type:hammerhead'\n\n" +
1835 " List all tests that run with a specific flag:\n" +
1836 " --query bots/'--test-launcher-print-test-studio=always'\n\n" +
1837 " List specific test (make sure you have quotes):\n"
1838 " --query test/'test1'\n\n"
1839 " List all bots running 'test1' " +
1840 "(make sure you have quotes):\n" +
1841 " --query test/'test1'/bots" ))
Kenneth Russelleb60cbd22017-12-05 07:54:281842 parser.add_argument(
1843 '-n', '--new-files', action='store_true', help=
1844 'Write output files as .new.json. Useful during development so old and '
1845 'new files can be looked at side-by-side.')
1846 parser.add_argument(
Stephen Martinis7eb8b612018-09-21 00:17:501847 '-v', '--verbose', action='store_true', help=
1848 'Increases verbosity. Affects consistency checks.')
1849 parser.add_argument(
Kenneth Russelleb60cbd22017-12-05 07:54:281850 'waterfall_filters', metavar='waterfalls', type=str, nargs='*',
1851 help='Optional list of waterfalls to generate.')
Zhiling Huangbe008172018-03-08 19:13:111852 parser.add_argument(
1853 '--pyl-files-dir', type=os.path.realpath,
1854 help='Path to the directory containing the input .pyl files.')
Karen Qiane24b7ee2019-02-12 23:37:061855 parser.add_argument(
1856 '--json', help=
1857 ("Outputs results into a json file. Only works with query function.\n" +
1858 "Examples:\n" +
1859 " Outputs file into specified json file: \n" +
1860 " --json <file-name-here.json>"))
Garrett Beatyd5ca75962020-05-07 16:58:311861 parser.add_argument(
1862 '--infra-config-dir',
1863 help='Path to the LUCI services configuration directory',
1864 default=os.path.abspath(
1865 os.path.join(os.path.dirname(__file__),
1866 '..', '..', 'infra', 'config')))
Kenneth Russelleb60cbd22017-12-05 07:54:281867 self.args = parser.parse_args(argv)
Karen Qiane24b7ee2019-02-12 23:37:061868 if self.args.json and not self.args.query:
1869 parser.error("The --json flag can only be used with --query.")
Garrett Beatyd5ca75962020-05-07 16:58:311870 self.args.infra_config_dir = os.path.abspath(self.args.infra_config_dir)
Karen Qiane24b7ee2019-02-12 23:37:061871
1872 def does_test_match(self, test_info, params_dict):
1873 """Checks to see if the test matches the parameters given.
1874
1875 Compares the provided test_info with the params_dict to see
1876 if the bot matches the parameters given. If so, returns True.
1877 Else, returns false.
1878
1879 Args:
1880 test_info (dict): Information about a specific bot provided
1881 in the format shown in waterfalls.pyl
1882 params_dict (dict): Dictionary of parameters and their values
1883 to look for in the bot
1884 Ex: {
1885 'device_os':'android',
1886 '--flag':True,
1887 'mixins': ['mixin1', 'mixin2'],
1888 'ex_key':'ex_value'
1889 }
1890
1891 """
1892 DIMENSION_PARAMS = ['device_os', 'device_type', 'os',
1893 'kvm', 'pool', 'integrity'] # dimension parameters
1894 SWARMING_PARAMS = ['shards', 'hard_timeout', 'idempotent',
1895 'can_use_on_swarming_builders']
1896 for param in params_dict:
1897 # if dimension parameter
1898 if param in DIMENSION_PARAMS or param in SWARMING_PARAMS:
1899 if not 'swarming' in test_info:
1900 return False
1901 swarming = test_info['swarming']
1902 if param in SWARMING_PARAMS:
1903 if not param in swarming:
1904 return False
1905 if not str(swarming[param]) == params_dict[param]:
1906 return False
1907 else:
1908 if not 'dimension_sets' in swarming:
1909 return False
1910 d_set = swarming['dimension_sets']
1911 # only looking at the first dimension set
1912 if not param in d_set[0]:
1913 return False
1914 if not d_set[0][param] == params_dict[param]:
1915 return False
1916
1917 # if flag
1918 elif param.startswith('--'):
1919 if not 'args' in test_info:
1920 return False
1921 if not param in test_info['args']:
1922 return False
1923
1924 # not dimension parameter/flag/mixin
1925 else:
1926 if not param in test_info:
1927 return False
1928 if not test_info[param] == params_dict[param]:
1929 return False
1930 return True
1931 def error_msg(self, msg):
1932 """Prints an error message.
1933
1934 In addition to a catered error message, also prints
1935 out where the user can find more help. Then, program exits.
1936 """
1937 self.print_line(msg + (' If you need more information, ' +
1938 'please run with -h or --help to see valid commands.'))
1939 sys.exit(1)
1940
1941 def find_bots_that_run_test(self, test, bots):
1942 matching_bots = []
1943 for bot in bots:
1944 bot_info = bots[bot]
1945 tests = self.flatten_tests_for_bot(bot_info)
1946 for test_info in tests:
1947 test_name = ""
1948 if 'name' in test_info:
1949 test_name = test_info['name']
1950 elif 'test' in test_info:
1951 test_name = test_info['test']
1952 if not test_name == test:
1953 continue
1954 matching_bots.append(bot)
1955 return matching_bots
1956
1957 def find_tests_with_params(self, tests, params_dict):
1958 matching_tests = []
1959 for test_name in tests:
1960 test_info = tests[test_name]
1961 if not self.does_test_match(test_info, params_dict):
1962 continue
1963 if not test_name in matching_tests:
1964 matching_tests.append(test_name)
1965 return matching_tests
1966
1967 def flatten_waterfalls_for_query(self, waterfalls):
1968 bots = {}
1969 for waterfall in waterfalls:
Greg Gutermanf60eb052020-03-12 17:40:011970 waterfall_tests = self.generate_output_tests(waterfall)
1971 for bot in waterfall_tests:
1972 bot_info = waterfall_tests[bot]
1973 bots[bot] = bot_info
Karen Qiane24b7ee2019-02-12 23:37:061974 return bots
1975
1976 def flatten_tests_for_bot(self, bot_info):
1977 """Returns a list of flattened tests.
1978
1979 Returns a list of tests not grouped by test category
1980 for a specific bot.
1981 """
1982 TEST_CATS = self.get_test_generator_map().keys()
1983 tests = []
1984 for test_cat in TEST_CATS:
1985 if not test_cat in bot_info:
1986 continue
1987 test_cat_tests = bot_info[test_cat]
1988 tests = tests + test_cat_tests
1989 return tests
1990
1991 def flatten_tests_for_query(self, test_suites):
1992 """Returns a flattened dictionary of tests.
1993
1994 Returns a dictionary of tests associate with their
1995 configuration, not grouped by their test suite.
1996 """
1997 tests = {}
1998 for test_suite in test_suites.itervalues():
1999 for test in test_suite:
2000 test_info = test_suite[test]
2001 test_name = test
2002 if 'name' in test_info:
2003 test_name = test_info['name']
2004 tests[test_name] = test_info
2005 return tests
2006
2007 def parse_query_filter_params(self, params):
2008 """Parses the filter parameters.
2009
2010 Creates a dictionary from the parameters provided
2011 to filter the bot array.
2012 """
2013 params_dict = {}
2014 for p in params:
2015 # flag
2016 if p.startswith("--"):
2017 params_dict[p] = True
2018 else:
2019 pair = p.split(":")
2020 if len(pair) != 2:
2021 self.error_msg('Invalid command.')
2022 # regular parameters
2023 if pair[1].lower() == "true":
2024 params_dict[pair[0]] = True
2025 elif pair[1].lower() == "false":
2026 params_dict[pair[0]] = False
2027 else:
2028 params_dict[pair[0]] = pair[1]
2029 return params_dict
2030
2031 def get_test_suites_dict(self, bots):
2032 """Returns a dictionary of bots and their tests.
2033
2034 Returns a dictionary of bots and a list of their associated tests.
2035 """
2036 test_suite_dict = dict()
2037 for bot in bots:
2038 bot_info = bots[bot]
2039 tests = self.flatten_tests_for_bot(bot_info)
2040 test_suite_dict[bot] = tests
2041 return test_suite_dict
2042
2043 def output_query_result(self, result, json_file=None):
2044 """Outputs the result of the query.
2045
2046 If a json file parameter name is provided, then
2047 the result is output into the json file. If not,
2048 then the result is printed to the console.
2049 """
2050 output = json.dumps(result, indent=2)
2051 if json_file:
2052 self.write_file(json_file, output)
2053 else:
2054 self.print_line(output)
2055 return
2056
2057 def query(self, args):
2058 """Queries tests or bots.
2059
2060 Depending on the arguments provided, outputs a json of
2061 tests or bots matching the appropriate optional parameters provided.
2062 """
2063 # split up query statement
2064 query = args.query.split('/')
2065 self.load_configuration_files()
2066 self.resolve_configuration_files()
2067
2068 # flatten bots json
2069 tests = self.test_suites
2070 bots = self.flatten_waterfalls_for_query(self.waterfalls)
2071
2072 cmd_class = query[0]
2073
2074 # For queries starting with 'bots'
2075 if cmd_class == "bots":
2076 if len(query) == 1:
2077 return self.output_query_result(bots, args.json)
2078 # query with specific parameters
2079 elif len(query) == 2:
2080 if query[1] == 'tests':
2081 test_suites_dict = self.get_test_suites_dict(bots)
2082 return self.output_query_result(test_suites_dict, args.json)
2083 else:
2084 self.error_msg("This query should be in the format: bots/tests.")
2085
2086 else:
2087 self.error_msg("This query should have 0 or 1 '/', found %s instead."
2088 % str(len(query)-1))
2089
2090 # For queries starting with 'bot'
2091 elif cmd_class == "bot":
2092 if not len(query) == 2 and not len(query) == 3:
2093 self.error_msg("Command should have 1 or 2 '/', found %s instead."
2094 % str(len(query)-1))
2095 bot_id = query[1]
2096 if not bot_id in bots:
2097 self.error_msg("No bot named '" + bot_id + "' found.")
2098 bot_info = bots[bot_id]
2099 if len(query) == 2:
2100 return self.output_query_result(bot_info, args.json)
2101 if not query[2] == 'tests':
2102 self.error_msg("The query should be in the format:" +
2103 "bot/<bot-name>/tests.")
2104
2105 bot_tests = self.flatten_tests_for_bot(bot_info)
2106 return self.output_query_result(bot_tests, args.json)
2107
2108 # For queries starting with 'tests'
2109 elif cmd_class == "tests":
2110 if not len(query) == 1 and not len(query) == 2:
2111 self.error_msg("The query should have 0 or 1 '/', found %s instead."
2112 % str(len(query)-1))
2113 flattened_tests = self.flatten_tests_for_query(tests)
2114 if len(query) == 1:
2115 return self.output_query_result(flattened_tests, args.json)
2116
2117 # create params dict
2118 params = query[1].split('&')
2119 params_dict = self.parse_query_filter_params(params)
2120 matching_bots = self.find_tests_with_params(flattened_tests, params_dict)
2121 return self.output_query_result(matching_bots)
2122
2123 # For queries starting with 'test'
2124 elif cmd_class == "test":
2125 if not len(query) == 2 and not len(query) == 3:
2126 self.error_msg("The query should have 1 or 2 '/', found %s instead."
2127 % str(len(query)-1))
2128 test_id = query[1]
2129 if len(query) == 2:
2130 flattened_tests = self.flatten_tests_for_query(tests)
2131 for test in flattened_tests:
2132 if test == test_id:
2133 return self.output_query_result(flattened_tests[test], args.json)
2134 self.error_msg("There is no test named %s." % test_id)
2135 if not query[2] == 'bots':
2136 self.error_msg("The query should be in the format: " +
2137 "test/<test-name>/bots")
2138 bots_for_test = self.find_bots_that_run_test(test_id, bots)
2139 return self.output_query_result(bots_for_test)
2140
2141 else:
2142 self.error_msg("Your command did not match any valid commands." +
2143 "Try starting with 'bots', 'bot', 'tests', or 'test'.")
Kenneth Russelleb60cbd22017-12-05 07:54:282144
2145 def main(self, argv): # pragma: no cover
2146 self.parse_args(argv)
2147 if self.args.check:
Stephen Martinis7eb8b612018-09-21 00:17:502148 self.check_consistency(verbose=self.args.verbose)
Karen Qiane24b7ee2019-02-12 23:37:062149 elif self.args.query:
2150 self.query(self.args)
Kenneth Russelleb60cbd22017-12-05 07:54:282151 else:
Greg Gutermanf60eb052020-03-12 17:40:012152 self.write_json_result(self.generate_outputs())
Kenneth Russelleb60cbd22017-12-05 07:54:282153 return 0
2154
2155if __name__ == "__main__": # pragma: no cover
2156 generator = BBJSONGenerator()
John Budorick699282e2019-02-13 01:27:332157 sys.exit(generator.main(sys.argv[1:]))