blob: 4fb365239239de20566b87ca7fc6a306cea4c293 [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']
Kenneth Russell384a1732019-03-16 02:36:02790 # Handle certain specialized named GPUs.
791 if gpu.startswith('nvidia-quadro-p400'):
792 gpu = ['10de', '1cb3']
793 elif gpu.startswith('intel-hd-630'):
794 gpu = ['8086', '5912']
Brian Sheedyf9387db7b2019-08-05 19:26:10795 elif gpu.startswith('intel-uhd-630'):
796 gpu = ['8086', '3e92']
Kenneth Russell384a1732019-03-16 02:36:02797 else:
798 gpu = gpu.split('-')[0].split(':')
Kenneth Russell8a386d42018-06-02 09:48:01799 substitutions['gpu_vendor_id'] = gpu[0]
800 substitutions['gpu_device_id'] = gpu[1]
801 return [string.Template(arg).safe_substitute(substitutions) for arg in args]
802
803 def generate_gpu_telemetry_test(self, waterfall, tester_name, tester_config,
Bo Liu555a0f92019-03-29 12:11:56804 test_name, test_config, is_android_webview):
Kenneth Russell8a386d42018-06-02 09:48:01805 # These are all just specializations of isolated script tests with
806 # a bunch of boilerplate command line arguments added.
807
808 # The step name must end in 'test' or 'tests' in order for the
809 # results to automatically show up on the flakiness dashboard.
810 # (At least, this was true some time ago.) Continue to use this
811 # naming convention for the time being to minimize changes.
812 step_name = test_config.get('name', test_name)
813 if not (step_name.endswith('test') or step_name.endswith('tests')):
814 step_name = '%s_tests' % step_name
815 result = self.generate_isolated_script_test(
816 waterfall, tester_name, tester_config, step_name, test_config)
817 if not result:
818 return None
Chong Gub75754b32020-03-13 16:39:20819 result['isolate_name'] = test_config.get(
820 'isolate_name', 'telemetry_gpu_integration_test')
Chan Liab7d8dd82020-04-24 23:42:19821
Chan Lia3ad1502020-04-28 05:32:11822 # Populate test_id_prefix.
Chan Liab7d8dd82020-04-24 23:42:19823 gn_entry = (
824 self.gn_isolate_map.get(result['isolate_name']) or
825 self.gn_isolate_map.get('telemetry_gpu_integration_test'))
Chan Lia3ad1502020-04-28 05:32:11826 result['test_id_prefix'] = 'ninja:%s/%s/' % (gn_entry['label'], step_name)
Chan Liab7d8dd82020-04-24 23:42:19827
Kenneth Russell8a386d42018-06-02 09:48:01828 args = result.get('args', [])
829 test_to_run = result.pop('telemetry_test_name', test_name)
erikchen6da2d9b2018-08-03 23:01:14830
831 # These tests upload and download results from cloud storage and therefore
832 # aren't idempotent yet. https://crbug.com/549140.
833 result['swarming']['idempotent'] = False
834
Kenneth Russell44910c32018-12-03 23:35:11835 # The GPU tests act much like integration tests for the entire browser, and
836 # tend to uncover flakiness bugs more readily than other test suites. In
837 # order to surface any flakiness more readily to the developer of the CL
838 # which is introducing it, we disable retries with patch on the commit
839 # queue.
840 result['should_retry_with_patch'] = False
841
Bo Liu555a0f92019-03-29 12:11:56842 browser = ('android-webview-instrumentation'
843 if is_android_webview else tester_config['browser_config'])
Kenneth Russell8a386d42018-06-02 09:48:01844 args = [
Bo Liu555a0f92019-03-29 12:11:56845 test_to_run,
846 '--show-stdout',
847 '--browser=%s' % browser,
848 # --passthrough displays more of the logging in Telemetry when
849 # run via typ, in particular some of the warnings about tests
850 # being expected to fail, but passing.
851 '--passthrough',
852 '-v',
853 '--extra-browser-args=--enable-logging=stderr --js-flags=--expose-gc',
Kenneth Russell8a386d42018-06-02 09:48:01854 ] + args
855 result['args'] = self.maybe_fixup_args_array(self.substitute_gpu_args(
Stephen Martinis2a0667022018-09-25 22:31:14856 tester_config, result['swarming'], args))
Kenneth Russell8a386d42018-06-02 09:48:01857 return result
858
Kenneth Russelleb60cbd22017-12-05 07:54:28859 def get_test_generator_map(self):
860 return {
Bo Liu555a0f92019-03-29 12:11:56861 'android_webview_gpu_telemetry_tests':
862 GPUTelemetryTestGenerator(self, is_android_webview=True),
863 'cts_tests':
864 CTSGenerator(self),
865 'gpu_telemetry_tests':
866 GPUTelemetryTestGenerator(self),
867 'gtest_tests':
868 GTestGenerator(self),
869 'instrumentation_tests':
870 InstrumentationTestGenerator(self),
871 'isolated_scripts':
872 IsolatedScriptTestGenerator(self),
873 'junit_tests':
874 JUnitGenerator(self),
875 'scripts':
876 ScriptGenerator(self),
Kenneth Russelleb60cbd22017-12-05 07:54:28877 }
878
Kenneth Russell8a386d42018-06-02 09:48:01879 def get_test_type_remapper(self):
880 return {
881 # These are a specialization of isolated_scripts with a bunch of
882 # boilerplate command line arguments added to each one.
Bo Liu555a0f92019-03-29 12:11:56883 'android_webview_gpu_telemetry_tests': 'isolated_scripts',
Kenneth Russell8a386d42018-06-02 09:48:01884 'gpu_telemetry_tests': 'isolated_scripts',
885 }
886
Jeff Yoon67c3e832020-02-08 07:39:38887 def check_composition_type_test_suites(self, test_type,
888 additional_validators=None):
889 """Pre-pass to catch errors reliabily for compound/matrix suites"""
890 validators = [check_compound_references,
891 check_basic_references,
892 check_conflicting_definitions]
893 if additional_validators:
894 validators += additional_validators
895
896 target_suites = self.test_suites.get(test_type, {})
897 other_test_type = ('compound_suites'
898 if test_type == 'matrix_compound_suites'
899 else 'matrix_compound_suites')
900 other_suites = self.test_suites.get(other_test_type, {})
Jeff Yoon8154e582019-12-03 23:30:01901 basic_suites = self.test_suites.get('basic_suites', {})
902
Jeff Yoon67c3e832020-02-08 07:39:38903 for suite, suite_def in target_suites.iteritems():
Jeff Yoon8154e582019-12-03 23:30:01904 if suite in basic_suites:
905 raise BBGenErr('%s names may not duplicate basic test suite names '
906 '(error found while processsing %s)'
907 % (test_type, suite))
Nodir Turakulov28232afd2019-12-17 18:02:01908
Jeff Yoon67c3e832020-02-08 07:39:38909 seen_tests = {}
910 for sub_suite in suite_def:
911 for validator in validators:
912 validator(
913 basic_suites=basic_suites,
914 other_test_suites=other_suites,
915 seen_tests=seen_tests,
916 sub_suite=sub_suite,
917 suite=suite,
918 suite_def=suite_def,
919 target_test_suites=target_suites,
920 test_type=test_type,
Jeff Yoonda581c32020-03-06 03:56:05921 all_variants=self.variants
Jeff Yoon67c3e832020-02-08 07:39:38922 )
Kenneth Russelleb60cbd22017-12-05 07:54:28923
Stephen Martinis54d64ad2018-09-21 22:16:20924 def flatten_test_suites(self):
925 new_test_suites = {}
Jeff Yoon8154e582019-12-03 23:30:01926 test_types = ['basic_suites', 'compound_suites', 'matrix_compound_suites']
927 for category in test_types:
928 for name, value in self.test_suites.get(category, {}).iteritems():
929 new_test_suites[name] = value
Stephen Martinis54d64ad2018-09-21 22:16:20930 self.test_suites = new_test_suites
931
Chan Lia3ad1502020-04-28 05:32:11932 def resolve_test_id_prefixes(self):
Nodir Turakulovfce34292019-12-18 17:05:41933 for suite in self.test_suites['basic_suites'].itervalues():
934 for key, test in suite.iteritems():
935 if not isinstance(test, dict):
936 # Some test definitions are just strings, such as CTS.
937 # Skip them.
938 continue
939
940 # This assumes the recipe logic which prefers 'test' to 'isolate_name'
941 # https://source.chromium.org/chromium/chromium/tools/build/+/master:scripts/slave/recipe_modules/chromium_tests/generators.py;l=89;drc=14c062ba0eb418d3c4623dde41a753241b9df06b
942 # TODO(crbug.com/1035124): clean this up.
943 isolate_name = test.get('test') or test.get('isolate_name') or key
944 gn_entry = self.gn_isolate_map.get(isolate_name)
945 if gn_entry:
Corentin Wallez55b8e772020-04-24 17:39:28946 label = gn_entry['label']
947
948 if label.count(':') != 1:
949 raise BBGenErr(
950 'Malformed GN label "%s" in gn_isolate_map for key "%s",'
951 ' implicit names (like //f/b meaning //f/b:b) are disallowed.' %
952 (label, isolate_name))
953 if label.split(':')[1] != isolate_name:
954 raise BBGenErr(
955 'gn_isolate_map key name "%s" doesn\'t match GN target name in'
956 ' label "%s" see http://crbug.com/1071091 for details.' %
957 (isolate_name, label))
958
Chan Lia3ad1502020-04-28 05:32:11959 test['test_id_prefix'] = 'ninja:%s/' % label
Nodir Turakulovfce34292019-12-18 17:05:41960 else: # pragma: no cover
961 # Some tests do not have an entry gn_isolate_map.pyl, such as
962 # telemetry tests.
963 # TODO(crbug.com/1035304): require an entry in gn_isolate_map.
964 pass
965
Kenneth Russelleb60cbd22017-12-05 07:54:28966 def resolve_composition_test_suites(self):
Jeff Yoon8154e582019-12-03 23:30:01967 self.check_composition_type_test_suites('compound_suites')
Stephen Martinis54d64ad2018-09-21 22:16:20968
Jeff Yoon8154e582019-12-03 23:30:01969 compound_suites = self.test_suites.get('compound_suites', {})
970 # check_composition_type_test_suites() checks that all basic suites
971 # referenced by compound suites exist.
972 basic_suites = self.test_suites.get('basic_suites')
973
974 for name, value in compound_suites.iteritems():
975 # Resolve this to a dictionary.
976 full_suite = {}
977 for entry in value:
978 suite = basic_suites[entry]
979 full_suite.update(suite)
980 compound_suites[name] = full_suite
981
Jeff Yoon67c3e832020-02-08 07:39:38982 def resolve_variants(self, basic_test_definition, variants):
983 """ Merge variant-defined configurations to each test case definition in a
984 test suite.
985
986 The output maps a unique test name to an array of configurations because
987 there may exist more than one definition for a test name using variants. The
988 test name is referenced while mapping machines to test suites, so unpacking
989 the array is done by the generators.
990
991 Args:
992 basic_test_definition: a {} defined test suite in the format
993 test_name:test_config
994 variants: an [] of {} defining configurations to be applied to each test
995 case in the basic test_definition
996
997 Return:
998 a {} of test_name:[{}], where each {} is a merged configuration
999 """
1000
1001 # Each test in a basic test suite will have a definition per variant.
1002 test_suite = {}
1003 for test_name, test_config in basic_test_definition.iteritems():
1004 definitions = []
1005 for variant in variants:
Jeff Yoonda581c32020-03-06 03:56:051006 # Unpack the variant from variants.pyl if it's string based.
1007 if isinstance(variant, str):
1008 variant = self.variants[variant]
1009
Jeff Yoon67c3e832020-02-08 07:39:381010 # Clone a copy of test_config so that we can have a uniquely updated
1011 # version of it per variant
1012 cloned_config = copy.deepcopy(test_config)
1013 # The variant definition needs to be re-used for each test, so we'll
1014 # create a clone and work with it as well.
1015 cloned_variant = copy.deepcopy(variant)
1016
1017 cloned_config['args'] = (cloned_config.get('args', []) +
1018 cloned_variant.get('args', []))
1019 cloned_config['mixins'] = (cloned_config.get('mixins', []) +
1020 cloned_variant.get('mixins', []))
1021
1022 basic_swarming_def = cloned_config.get('swarming', {})
1023 variant_swarming_def = cloned_variant.get('swarming', {})
1024 if basic_swarming_def and variant_swarming_def:
1025 if ('dimension_sets' in basic_swarming_def and
1026 'dimension_sets' in variant_swarming_def):
1027 # Retain swarming dimension set merge behavior when both variant and
1028 # the basic test configuration both define it
1029 self.dictionary_merge(basic_swarming_def, variant_swarming_def)
1030 # Remove dimension_sets from the variant definition, so that it does
1031 # not replace what's been done by dictionary_merge in the update
1032 # call below.
1033 del variant_swarming_def['dimension_sets']
1034
1035 # Update the swarming definition with whatever is defined for swarming
1036 # by the variant.
1037 basic_swarming_def.update(variant_swarming_def)
1038 cloned_config['swarming'] = basic_swarming_def
1039
1040 # The identifier is used to make the name of the test unique.
1041 # Generators in the recipe uniquely identify a test by it's name, so we
1042 # don't want to have the same name for each variant.
1043 cloned_config['name'] = '{}_{}'.format(test_name,
1044 cloned_variant['identifier'])
Jeff Yoon67c3e832020-02-08 07:39:381045 definitions.append(cloned_config)
1046 test_suite[test_name] = definitions
1047 return test_suite
1048
Jeff Yoon8154e582019-12-03 23:30:011049 def resolve_matrix_compound_test_suites(self):
Jeff Yoon67c3e832020-02-08 07:39:381050 self.check_composition_type_test_suites('matrix_compound_suites',
1051 [check_matrix_identifier])
Jeff Yoon8154e582019-12-03 23:30:011052
1053 matrix_compound_suites = self.test_suites.get('matrix_compound_suites', {})
Jeff Yoon67c3e832020-02-08 07:39:381054 # check_composition_type_test_suites() checks that all basic suites are
Jeff Yoon8154e582019-12-03 23:30:011055 # referenced by matrix suites exist.
1056 basic_suites = self.test_suites.get('basic_suites')
1057
Jeff Yoon67c3e832020-02-08 07:39:381058 for test_name, matrix_config in matrix_compound_suites.iteritems():
Jeff Yoon8154e582019-12-03 23:30:011059 full_suite = {}
Jeff Yoon67c3e832020-02-08 07:39:381060
1061 for test_suite, mtx_test_suite_config in matrix_config.iteritems():
1062 basic_test_def = copy.deepcopy(basic_suites[test_suite])
1063
1064 if 'variants' in mtx_test_suite_config:
1065 result = self.resolve_variants(basic_test_def,
1066 mtx_test_suite_config['variants'])
1067 full_suite.update(result)
1068 matrix_compound_suites[test_name] = full_suite
Kenneth Russelleb60cbd22017-12-05 07:54:281069
1070 def link_waterfalls_to_test_suites(self):
1071 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431072 for tester_name, tester in waterfall['machines'].iteritems():
1073 for suite, value in tester.get('test_suites', {}).iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281074 if not value in self.test_suites:
1075 # Hard / impossible to cover this in the unit test.
1076 raise self.unknown_test_suite(
1077 value, tester_name, waterfall['name']) # pragma: no cover
1078 tester['test_suites'][suite] = self.test_suites[value]
1079
1080 def load_configuration_files(self):
1081 self.waterfalls = self.load_pyl_file('waterfalls.pyl')
1082 self.test_suites = self.load_pyl_file('test_suites.pyl')
1083 self.exceptions = self.load_pyl_file('test_suite_exceptions.pyl')
Stephen Martinisb72f6d22018-10-04 23:29:011084 self.mixins = self.load_pyl_file('mixins.pyl')
Nodir Turakulovfce34292019-12-18 17:05:411085 self.gn_isolate_map = self.load_pyl_file('gn_isolate_map.pyl')
Jeff Yoonda581c32020-03-06 03:56:051086 self.variants = self.load_pyl_file('variants.pyl')
Kenneth Russelleb60cbd22017-12-05 07:54:281087
1088 def resolve_configuration_files(self):
Chan Lia3ad1502020-04-28 05:32:111089 self.resolve_test_id_prefixes()
Kenneth Russelleb60cbd22017-12-05 07:54:281090 self.resolve_composition_test_suites()
Jeff Yoon8154e582019-12-03 23:30:011091 self.resolve_matrix_compound_test_suites()
1092 self.flatten_test_suites()
Kenneth Russelleb60cbd22017-12-05 07:54:281093 self.link_waterfalls_to_test_suites()
1094
Nico Weberd18b8962018-05-16 19:39:381095 def unknown_bot(self, bot_name, waterfall_name):
1096 return BBGenErr(
1097 'Unknown bot name "%s" on waterfall "%s"' % (bot_name, waterfall_name))
1098
Kenneth Russelleb60cbd22017-12-05 07:54:281099 def unknown_test_suite(self, suite_name, bot_name, waterfall_name):
1100 return BBGenErr(
Nico Weberd18b8962018-05-16 19:39:381101 'Test suite %s from machine %s on waterfall %s not present in '
Kenneth Russelleb60cbd22017-12-05 07:54:281102 'test_suites.pyl' % (suite_name, bot_name, waterfall_name))
1103
1104 def unknown_test_suite_type(self, suite_type, bot_name, waterfall_name):
1105 return BBGenErr(
1106 'Unknown test suite type ' + suite_type + ' in bot ' + bot_name +
1107 ' on waterfall ' + waterfall_name)
1108
Stephen Martinisb72f6d22018-10-04 23:29:011109 def apply_all_mixins(self, test, waterfall, builder_name, builder):
Stephen Martinis0382bc12018-09-17 22:29:071110 """Applies all present swarming mixins to the test for a given builder.
Stephen Martinisb6a50492018-09-12 23:59:321111
1112 Checks in the waterfall, builder, and test objects for mixins.
1113 """
1114 def valid_mixin(mixin_name):
1115 """Asserts that the mixin is valid."""
Stephen Martinisb72f6d22018-10-04 23:29:011116 if mixin_name not in self.mixins:
Stephen Martinisb6a50492018-09-12 23:59:321117 raise BBGenErr("bad mixin %s" % mixin_name)
Jeff Yoon67c3e832020-02-08 07:39:381118
Stephen Martinisb6a50492018-09-12 23:59:321119 def must_be_list(mixins, typ, name):
1120 """Asserts that given mixins are a list."""
1121 if not isinstance(mixins, list):
1122 raise BBGenErr("'%s' in %s '%s' must be a list" % (mixins, typ, name))
1123
Brian Sheedy7658c982020-01-08 02:27:581124 test_name = test.get('name')
1125 remove_mixins = set()
1126 if 'remove_mixins' in builder:
1127 must_be_list(builder['remove_mixins'], 'builder', builder_name)
1128 for rm in builder['remove_mixins']:
1129 valid_mixin(rm)
1130 remove_mixins.add(rm)
1131 if 'remove_mixins' in test:
1132 must_be_list(test['remove_mixins'], 'test', test_name)
1133 for rm in test['remove_mixins']:
1134 valid_mixin(rm)
1135 remove_mixins.add(rm)
1136 del test['remove_mixins']
1137
Stephen Martinisb72f6d22018-10-04 23:29:011138 if 'mixins' in waterfall:
1139 must_be_list(waterfall['mixins'], 'waterfall', waterfall['name'])
1140 for mixin in waterfall['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 'mixins' in builder:
1147 must_be_list(builder['mixins'], 'builder', builder_name)
1148 for mixin in builder['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581149 if mixin in remove_mixins:
1150 continue
Stephen Martinisb6a50492018-09-12 23:59:321151 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011152 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321153
Stephen Martinisb72f6d22018-10-04 23:29:011154 if not 'mixins' in test:
Stephen Martinis0382bc12018-09-17 22:29:071155 return test
1156
Stephen Martinis2a0667022018-09-25 22:31:141157 if not test_name:
1158 test_name = test.get('test')
1159 if not test_name: # pragma: no cover
1160 # Not the best name, but we should say something.
1161 test_name = str(test)
Stephen Martinisb72f6d22018-10-04 23:29:011162 must_be_list(test['mixins'], 'test', test_name)
1163 for mixin in test['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581164 # We don't bother checking if the given mixin is in remove_mixins here
1165 # since this is already the lowest level, so if a mixin is added here that
1166 # we don't want, we can just delete its entry.
Stephen Martinis0382bc12018-09-17 22:29:071167 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011168 test = self.apply_mixin(self.mixins[mixin], test)
Jeff Yoon67c3e832020-02-08 07:39:381169 del test['mixins']
Stephen Martinis0382bc12018-09-17 22:29:071170 return test
Stephen Martinisb6a50492018-09-12 23:59:321171
Stephen Martinisb72f6d22018-10-04 23:29:011172 def apply_mixin(self, mixin, test):
1173 """Applies a mixin to a test.
Stephen Martinisb6a50492018-09-12 23:59:321174
Stephen Martinis0382bc12018-09-17 22:29:071175 Mixins will not override an existing key. This is to ensure exceptions can
1176 override a setting a mixin applies.
1177
Stephen Martinisb72f6d22018-10-04 23:29:011178 Swarming dimensions are handled in a special way. Instead of specifying
Stephen Martinisb6a50492018-09-12 23:59:321179 'dimension_sets', which is how normal test suites specify their dimensions,
1180 you specify a 'dimensions' key, which maps to a dictionary. This dictionary
1181 is then applied to every dimension set in the test.
Stephen Martinisb72f6d22018-10-04 23:29:011182
Stephen Martinisb6a50492018-09-12 23:59:321183 """
1184 new_test = copy.deepcopy(test)
1185 mixin = copy.deepcopy(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011186 if 'swarming' in mixin:
1187 swarming_mixin = mixin['swarming']
1188 new_test.setdefault('swarming', {})
1189 if 'dimensions' in swarming_mixin:
1190 new_test['swarming'].setdefault('dimension_sets', [{}])
1191 for dimension_set in new_test['swarming']['dimension_sets']:
1192 dimension_set.update(swarming_mixin['dimensions'])
1193 del swarming_mixin['dimensions']
Stephen Martinisb72f6d22018-10-04 23:29:011194 # python dict update doesn't do recursion at all. Just hard code the
1195 # nested update we need (mixin['swarming'] shouldn't clobber
1196 # test['swarming'], but should update it).
1197 new_test['swarming'].update(swarming_mixin)
1198 del mixin['swarming']
1199
Wezc0e835b702018-10-30 00:38:411200 if '$mixin_append' in mixin:
1201 # Values specified under $mixin_append should be appended to existing
1202 # lists, rather than replacing them.
1203 mixin_append = mixin['$mixin_append']
1204 for key in mixin_append:
1205 new_test.setdefault(key, [])
1206 if not isinstance(mixin_append[key], list):
1207 raise BBGenErr(
1208 'Key "' + key + '" in $mixin_append must be a list.')
1209 if not isinstance(new_test[key], list):
1210 raise BBGenErr(
1211 'Cannot apply $mixin_append to non-list "' + key + '".')
1212 new_test[key].extend(mixin_append[key])
1213 if 'args' in mixin_append:
1214 new_test['args'] = self.maybe_fixup_args_array(new_test['args'])
1215 del mixin['$mixin_append']
1216
Stephen Martinisb72f6d22018-10-04 23:29:011217 new_test.update(mixin)
Stephen Martinisb6a50492018-09-12 23:59:321218 return new_test
1219
Greg Gutermanf60eb052020-03-12 17:40:011220 def generate_output_tests(self, waterfall):
1221 """Generates the tests for a waterfall.
1222
1223 Args:
1224 waterfall: a dictionary parsed from a master pyl file
1225 Returns:
1226 A dictionary mapping builders to test specs
1227 """
1228 return {
1229 name: self.get_tests_for_config(waterfall, name, config)
1230 for name, config
1231 in waterfall['machines'].iteritems()
1232 }
1233
1234 def get_tests_for_config(self, waterfall, name, config):
Greg Guterman5c6144152020-02-28 20:08:531235 generator_map = self.get_test_generator_map()
1236 test_type_remapper = self.get_test_type_remapper()
Kenneth Russelleb60cbd22017-12-05 07:54:281237
Greg Gutermanf60eb052020-03-12 17:40:011238 tests = {}
1239 # Copy only well-understood entries in the machine's configuration
1240 # verbatim into the generated JSON.
1241 if 'additional_compile_targets' in config:
1242 tests['additional_compile_targets'] = config[
1243 'additional_compile_targets']
1244 for test_type, input_tests in config.get('test_suites', {}).iteritems():
1245 if test_type not in generator_map:
1246 raise self.unknown_test_suite_type(
1247 test_type, name, waterfall['name']) # pragma: no cover
1248 test_generator = generator_map[test_type]
1249 # Let multiple kinds of generators generate the same kinds
1250 # of tests. For example, gpu_telemetry_tests are a
1251 # specialization of isolated_scripts.
1252 new_tests = test_generator.generate(
1253 waterfall, name, config, input_tests)
1254 remapped_test_type = test_type_remapper.get(test_type, test_type)
1255 tests[remapped_test_type] = test_generator.sort(
1256 tests.get(remapped_test_type, []) + new_tests)
1257
1258 return tests
1259
1260 def jsonify(self, all_tests):
1261 return json.dumps(
1262 all_tests, indent=2, separators=(',', ': '),
1263 sort_keys=True) + '\n'
1264
1265 def generate_outputs(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281266 self.load_configuration_files()
1267 self.resolve_configuration_files()
1268 filters = self.args.waterfall_filters
Greg Gutermanf60eb052020-03-12 17:40:011269 result = collections.defaultdict(dict)
1270
1271 required_fields = ('project', 'bucket', 'name')
1272 for waterfall in self.waterfalls:
1273 for field in required_fields:
1274 # Verify required fields
1275 if field not in waterfall:
1276 raise BBGenErr("Waterfall %s has no %s" % (waterfall['name'], field))
1277
1278 # Handle filter flag, if specified
1279 if filters and waterfall['name'] not in filters:
1280 continue
1281
1282 # Join config files and hardcoded values together
1283 all_tests = self.generate_output_tests(waterfall)
1284 result[waterfall['name']] = all_tests
1285
1286 # Deduce per-bucket mappings
1287 # This will be the standard after masternames are gone
1288 bucket_filename = waterfall['project'] + '.' + waterfall['bucket']
1289 for buildername in waterfall['machines'].keys():
1290 result[bucket_filename][buildername] = all_tests[buildername]
1291
1292 # Add do not edit warning
1293 for tests in result.values():
1294 tests['AAAAA1 AUTOGENERATED FILE DO NOT EDIT'] = {}
1295 tests['AAAAA2 See generate_buildbot_json.py to make changes'] = {}
1296
1297 return result
1298
1299 def write_json_result(self, result): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281300 suffix = '.json'
1301 if self.args.new_files:
1302 suffix = '.new' + suffix
Greg Gutermanf60eb052020-03-12 17:40:011303
1304 for filename, contents in result.items():
1305 jsonstr = self.jsonify(contents)
1306 self.write_file(self.pyl_file_path(filename + suffix), jsonstr)
Kenneth Russelleb60cbd22017-12-05 07:54:281307
Nico Weberd18b8962018-05-16 19:39:381308 def get_valid_bot_names(self):
John Budorick699282e2019-02-13 01:27:331309 # Extract bot names from infra/config/luci-milo.cfg.
Stephen Martinis26627cf2018-12-19 01:51:421310 # NOTE: This reference can cause issues; if a file changes there, the
1311 # presubmit here won't be run by default. A manually maintained list there
1312 # tries to run presubmit here when luci-milo.cfg is changed. If any other
1313 # references to configs outside of this directory are added, please change
1314 # their presubmit to run `generate_buildbot_json.py -c`, so that the tree
1315 # never ends up in an invalid state.
Garrett Beaty2a02de3c2020-05-15 13:57:351316 project_star = glob.glob(
1317 os.path.join(self.args.infra_config_dir, 'project.star'))
1318 if project_star:
1319 is_master_pattern = re.compile('is_master\s*=\s*(True|False)')
1320 for l in self.read_file(project_star[0]).splitlines():
1321 match = is_master_pattern.search(l)
1322 if match:
1323 if match.group(1) == 'False':
1324 return None
1325 break
Nico Weberd18b8962018-05-16 19:39:381326 bot_names = set()
Garrett Beatyd5ca75962020-05-07 16:58:311327 milo_configs = glob.glob(
1328 os.path.join(self.args.infra_config_dir, 'generated', 'luci-milo*.cfg'))
John Budorickc12abd12018-08-14 19:37:431329 for c in milo_configs:
1330 for l in self.read_file(c).splitlines():
1331 if (not 'name: "buildbucket/luci.chromium.' in l and
Garrett Beatyd5ca75962020-05-07 16:58:311332 not 'name: "buildbucket/luci.chrome.' in l):
John Budorickc12abd12018-08-14 19:37:431333 continue
1334 # l looks like
1335 # `name: "buildbucket/luci.chromium.try/win_chromium_dbg_ng"`
1336 # Extract win_chromium_dbg_ng part.
1337 bot_names.add(l[l.rindex('/') + 1:l.rindex('"')])
Nico Weberd18b8962018-05-16 19:39:381338 return bot_names
1339
Ben Pastene9a010082019-09-25 20:41:371340 def get_builders_that_do_not_actually_exist(self):
Kenneth Russell8a386d42018-06-02 09:48:011341 # Some of the bots on the chromium.gpu.fyi waterfall in particular
1342 # are defined only to be mirrored into trybots, and don't actually
1343 # exist on any of the waterfalls or consoles.
1344 return [
Michael Spangeb07eba62019-05-14 22:22:581345 'GPU FYI Fuchsia Builder',
Yuly Novikoveb26b812019-07-26 02:08:191346 'ANGLE GPU Android Release (Nexus 5X)',
Jamie Madillda894ce2019-04-08 17:19:171347 'ANGLE GPU Linux Release (Intel HD 630)',
1348 'ANGLE GPU Linux Release (NVIDIA)',
1349 'ANGLE GPU Mac Release (Intel)',
1350 'ANGLE GPU Mac Retina Release (AMD)',
1351 'ANGLE GPU Mac Retina Release (NVIDIA)',
Yuly Novikovbc1ccff2019-08-03 00:05:491352 'ANGLE GPU Win10 x64 Release (Intel HD 630)',
1353 'ANGLE GPU Win10 x64 Release (NVIDIA)',
Kenneth Russell8a386d42018-06-02 09:48:011354 'Optional Android Release (Nexus 5X)',
1355 'Optional Linux Release (Intel HD 630)',
1356 'Optional Linux Release (NVIDIA)',
1357 'Optional Mac Release (Intel)',
1358 'Optional Mac Retina Release (AMD)',
1359 'Optional Mac Retina Release (NVIDIA)',
Yuly Novikovbc1ccff2019-08-03 00:05:491360 'Optional Win10 x64 Release (Intel HD 630)',
1361 'Optional Win10 x64 Release (NVIDIA)',
Kenneth Russell8a386d42018-06-02 09:48:011362 'Win7 ANGLE Tryserver (AMD)',
Nico Weber7fc8b9da2018-06-08 19:22:081363 # chromium.fyi
Dirk Pranke85369442018-06-16 02:01:291364 'linux-blink-rel-dummy',
Ilia Samsonov53f1acc2020-05-22 00:57:051365 'linux-blink-optional-highdpi-rel-dummy',
Dirk Pranke85369442018-06-16 02:01:291366 'mac10.10-blink-rel-dummy',
1367 'mac10.11-blink-rel-dummy',
1368 'mac10.12-blink-rel-dummy',
Kenneth Russell911da0d32018-07-17 21:39:201369 'mac10.13_retina-blink-rel-dummy',
Dirk Pranke85369442018-06-16 02:01:291370 'mac10.13-blink-rel-dummy',
John Chenad978322019-12-16 18:07:211371 'mac10.14-blink-rel-dummy',
Ilia Samsonov7efe05e2020-05-07 19:00:461372 'mac10.15-blink-rel-dummy',
Dirk Pranke85369442018-06-16 02:01:291373 'win7-blink-rel-dummy',
1374 'win10-blink-rel-dummy',
Nico Weber7fc8b9da2018-06-08 19:22:081375 'Dummy WebKit Mac10.13',
Philip Rogers639990262018-12-08 00:13:331376 'WebKit Linux composite_after_paint Dummy Builder',
Scott Violet744e04662019-08-19 23:51:531377 'WebKit Linux layout_ng_disabled Builder',
Stephen Martinis769b25112018-08-30 18:52:061378 # chromium, due to https://crbug.com/878915
1379 'win-dbg',
1380 'win32-dbg',
Stephen Martinis47d771352019-04-24 23:51:331381 'win-archive-dbg',
1382 'win32-archive-dbg',
Sajjad Mirza2924a012019-12-20 03:46:541383 # TODO(crbug.com/1033753) Delete these when coverage is enabled by default
1384 # on Windows tryjobs.
1385 'GPU Win x64 Builder Code Coverage',
1386 'Win x64 Builder Code Coverage',
1387 'Win10 Tests x64 Code Coverage',
1388 'Win10 x64 Release (NVIDIA) Code Coverage',
Sajjad Mirzafa15665e2020-02-10 23:41:041389 # TODO(crbug.com/1024915) Delete these when coverage is enabled by default
1390 # on Mac OS tryjobs.
1391 'Mac Builder Code Coverage',
1392 'Mac10.13 Tests Code Coverage',
1393 'GPU Mac Builder Code Coverage',
1394 'Mac Release (Intel) Code Coverage',
1395 'Mac Retina Release (AMD) Code Coverage',
Kenneth Russell8a386d42018-06-02 09:48:011396 ]
1397
Ben Pastene9a010082019-09-25 20:41:371398 def get_internal_waterfalls(self):
1399 # Similar to get_builders_that_do_not_actually_exist above, but for
1400 # waterfalls defined in internal configs.
Jeff Yoon8acfdce2020-04-20 22:38:071401 return ['chrome', 'chrome.pgo']
Ben Pastene9a010082019-09-25 20:41:371402
Stephen Martinisf83893722018-09-19 00:02:181403 def check_input_file_consistency(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201404 self.check_input_files_sorting(verbose)
1405
Kenneth Russelleb60cbd22017-12-05 07:54:281406 self.load_configuration_files()
Jeff Yoon8154e582019-12-03 23:30:011407 self.check_composition_type_test_suites('compound_suites')
Jeff Yoon67c3e832020-02-08 07:39:381408 self.check_composition_type_test_suites('matrix_compound_suites',
1409 [check_matrix_identifier])
Chan Lia3ad1502020-04-28 05:32:111410 self.resolve_test_id_prefixes()
Stephen Martinis54d64ad2018-09-21 22:16:201411 self.flatten_test_suites()
Nico Weberd18b8962018-05-16 19:39:381412
1413 # All bots should exist.
1414 bot_names = self.get_valid_bot_names()
Ben Pastene9a010082019-09-25 20:41:371415 builders_that_dont_exist = self.get_builders_that_do_not_actually_exist()
Garrett Beaty2a02de3c2020-05-15 13:57:351416 if bot_names is not None:
1417 internal_waterfalls = self.get_internal_waterfalls()
1418 for waterfall in self.waterfalls:
1419 # TODO(crbug.com/991417): Remove the need for this exception.
1420 if waterfall['name'] in internal_waterfalls:
Kenneth Russell8a386d42018-06-02 09:48:011421 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351422 for bot_name in waterfall['machines']:
1423 if bot_name in builders_that_dont_exist:
Kenneth Russell78fd8702018-05-17 01:15:521424 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351425 if bot_name not in bot_names:
1426 if waterfall['name'] in ['client.v8.chromium', 'client.v8.fyi']:
1427 # TODO(thakis): Remove this once these bots move to luci.
1428 continue # pragma: no cover
1429 if waterfall['name'] in ['tryserver.webrtc',
1430 'webrtc.chromium.fyi.experimental']:
1431 # These waterfalls have their bot configs in a different repo.
1432 # so we don't know about their bot names.
1433 continue # pragma: no cover
1434 if waterfall['name'] in ['client.devtools-frontend.integration',
1435 'tryserver.devtools-frontend',
1436 'chromium.devtools-frontend']:
1437 continue # pragma: no cover
1438 raise self.unknown_bot(bot_name, waterfall['name'])
Nico Weberd18b8962018-05-16 19:39:381439
Kenneth Russelleb60cbd22017-12-05 07:54:281440 # All test suites must be referenced.
1441 suites_seen = set()
1442 generator_map = self.get_test_generator_map()
1443 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431444 for bot_name, tester in waterfall['machines'].iteritems():
1445 for suite_type, suite in tester.get('test_suites', {}).iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281446 if suite_type not in generator_map:
1447 raise self.unknown_test_suite_type(suite_type, bot_name,
1448 waterfall['name'])
1449 if suite not in self.test_suites:
1450 raise self.unknown_test_suite(suite, bot_name, waterfall['name'])
1451 suites_seen.add(suite)
1452 # Since we didn't resolve the configuration files, this set
1453 # includes both composition test suites and regular ones.
1454 resolved_suites = set()
1455 for suite_name in suites_seen:
1456 suite = self.test_suites[suite_name]
Jeff Yoon8154e582019-12-03 23:30:011457 for sub_suite in suite:
1458 resolved_suites.add(sub_suite)
Kenneth Russelleb60cbd22017-12-05 07:54:281459 resolved_suites.add(suite_name)
1460 # At this point, every key in test_suites.pyl should be referenced.
1461 missing_suites = set(self.test_suites.keys()) - resolved_suites
1462 if missing_suites:
1463 raise BBGenErr('The following test suites were unreferenced by bots on '
1464 'the waterfalls: ' + str(missing_suites))
1465
1466 # All test suite exceptions must refer to bots on the waterfall.
1467 all_bots = set()
1468 missing_bots = set()
1469 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431470 for bot_name, tester in waterfall['machines'].iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281471 all_bots.add(bot_name)
Kenneth Russell8ceeabf2017-12-11 17:53:281472 # In order to disambiguate between bots with the same name on
1473 # different waterfalls, support has been added to various
1474 # exceptions for concatenating the waterfall name after the bot
1475 # name.
1476 all_bots.add(bot_name + ' ' + waterfall['name'])
Kenneth Russelleb60cbd22017-12-05 07:54:281477 for exception in self.exceptions.itervalues():
Nico Weberd18b8962018-05-16 19:39:381478 removals = (exception.get('remove_from', []) +
1479 exception.get('remove_gtest_from', []) +
1480 exception.get('modifications', {}).keys())
1481 for removal in removals:
Kenneth Russelleb60cbd22017-12-05 07:54:281482 if removal not in all_bots:
1483 missing_bots.add(removal)
Stephen Martiniscc70c962018-07-31 21:22:411484
Ben Pastene9a010082019-09-25 20:41:371485 missing_bots = missing_bots - set(builders_that_dont_exist)
Kenneth Russelleb60cbd22017-12-05 07:54:281486 if missing_bots:
1487 raise BBGenErr('The following nonexistent machines were referenced in '
1488 'the test suite exceptions: ' + str(missing_bots))
1489
Stephen Martinis0382bc12018-09-17 22:29:071490 # All mixins must be referenced
1491 seen_mixins = set()
1492 for waterfall in self.waterfalls:
Stephen Martinisb72f6d22018-10-04 23:29:011493 seen_mixins = seen_mixins.union(waterfall.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071494 for bot_name, tester in waterfall['machines'].iteritems():
Stephen Martinisb72f6d22018-10-04 23:29:011495 seen_mixins = seen_mixins.union(tester.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071496 for suite in self.test_suites.values():
1497 if isinstance(suite, list):
1498 # Don't care about this, it's a composition, which shouldn't include a
1499 # swarming mixin.
1500 continue
1501
1502 for test in suite.values():
1503 if not isinstance(test, dict):
1504 # Some test suites have top level keys, which currently can't be
1505 # swarming mixin entries. Ignore them
1506 continue
1507
Stephen Martinisb72f6d22018-10-04 23:29:011508 seen_mixins = seen_mixins.union(test.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071509
Stephen Martinisb72f6d22018-10-04 23:29:011510 missing_mixins = set(self.mixins.keys()) - seen_mixins
Stephen Martinis0382bc12018-09-17 22:29:071511 if missing_mixins:
1512 raise BBGenErr('The following mixins are unreferenced: %s. They must be'
1513 ' referenced in a waterfall, machine, or test suite.' % (
1514 str(missing_mixins)))
1515
Jeff Yoonda581c32020-03-06 03:56:051516 # All variant references must be referenced
1517 seen_variants = set()
1518 for suite in self.test_suites.values():
1519 if isinstance(suite, list):
1520 continue
1521
1522 for test in suite.values():
1523 if isinstance(test, dict):
1524 for variant in test.get('variants', []):
1525 if isinstance(variant, str):
1526 seen_variants.add(variant)
1527
1528 missing_variants = set(self.variants.keys()) - seen_variants
1529 if missing_variants:
1530 raise BBGenErr('The following variants were unreferenced: %s. They must '
1531 'be referenced in a matrix test suite under the variants '
1532 'key.' % str(missing_variants))
1533
Stephen Martinis54d64ad2018-09-21 22:16:201534
1535 def type_assert(self, node, typ, filename, verbose=False):
1536 """Asserts that the Python AST node |node| is of type |typ|.
1537
1538 If verbose is set, it prints out some helpful context lines, showing where
1539 exactly the error occurred in the file.
1540 """
1541 if not isinstance(node, typ):
1542 if verbose:
1543 lines = [""] + self.read_file(filename).splitlines()
1544
1545 context = 2
1546 lines_start = max(node.lineno - context, 0)
1547 # Add one to include the last line
1548 lines_end = min(node.lineno + context, len(lines)) + 1
1549 lines = (
1550 ['== %s ==\n' % filename] +
1551 ["<snip>\n"] +
1552 ['%d %s' % (lines_start + i, line) for i, line in enumerate(
1553 lines[lines_start:lines_start + context])] +
1554 ['-' * 80 + '\n'] +
1555 ['%d %s' % (node.lineno, lines[node.lineno])] +
1556 ['-' * (node.col_offset + 3) + '^' + '-' * (
1557 80 - node.col_offset - 4) + '\n'] +
1558 ['%d %s' % (node.lineno + 1 + i, line) for i, line in enumerate(
1559 lines[node.lineno + 1:lines_end])] +
1560 ["<snip>\n"]
1561 )
1562 # Print out a useful message when a type assertion fails.
1563 for l in lines:
1564 self.print_line(l.strip())
1565
1566 node_dumped = ast.dump(node, annotate_fields=False)
1567 # If the node is huge, truncate it so everything fits in a terminal
1568 # window.
1569 if len(node_dumped) > 60: # pragma: no cover
1570 node_dumped = node_dumped[:30] + ' <SNIP> ' + node_dumped[-30:]
1571 raise BBGenErr(
1572 'Invalid .pyl file %r. Python AST node %r on line %s expected to'
1573 ' be %s, is %s' % (
1574 filename, node_dumped,
1575 node.lineno, typ, type(node)))
1576
Stephen Martinis5bef0fc42020-01-06 22:47:531577 def check_ast_list_formatted(self, keys, filename, verbose,
Stephen Martinis1384ff92020-01-07 19:52:151578 check_sorting=True):
Stephen Martinis5bef0fc42020-01-06 22:47:531579 """Checks if a list of ast keys are correctly formatted.
Stephen Martinis54d64ad2018-09-21 22:16:201580
Stephen Martinis5bef0fc42020-01-06 22:47:531581 Currently only checks to ensure they're correctly sorted, and that there
1582 are no duplicates.
1583
1584 Args:
1585 keys: An python list of AST nodes.
1586
1587 It's a list of AST nodes instead of a list of strings because
1588 when verbose is set, it tries to print out context of where the
1589 diffs are in the file.
1590 filename: The name of the file this node is from.
1591 verbose: If set, print out diff information about how the keys are
1592 incorrectly formatted.
1593 check_sorting: If true, checks if the list is sorted.
1594 Returns:
1595 If the keys are correctly formatted.
1596 """
1597 if not keys:
1598 return True
1599
1600 assert isinstance(keys[0], ast.Str)
1601
1602 keys_strs = [k.s for k in keys]
1603 # Keys to diff against. Used below.
1604 keys_to_diff_against = None
1605 # If the list is properly formatted.
1606 list_formatted = True
1607
1608 # Duplicates are always bad.
1609 if len(set(keys_strs)) != len(keys_strs):
1610 list_formatted = False
1611 keys_to_diff_against = list(collections.OrderedDict.fromkeys(keys_strs))
1612
1613 if check_sorting and sorted(keys_strs) != keys_strs:
1614 list_formatted = False
1615 if list_formatted:
1616 return True
1617
1618 if verbose:
1619 line_num = keys[0].lineno
1620 keys = [k.s for k in keys]
1621 if check_sorting:
1622 # If we have duplicates, sorting this will take care of it anyways.
1623 keys_to_diff_against = sorted(set(keys))
1624 # else, keys_to_diff_against is set above already
1625
1626 self.print_line('=' * 80)
1627 self.print_line('(First line of keys is %s)' % line_num)
1628 for line in difflib.context_diff(
1629 keys, keys_to_diff_against,
1630 fromfile='current (%r)' % filename, tofile='sorted', lineterm=''):
1631 self.print_line(line)
1632 self.print_line('=' * 80)
1633
1634 return False
1635
Stephen Martinis1384ff92020-01-07 19:52:151636 def check_ast_dict_formatted(self, node, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531637 """Checks if an ast dictionary's keys are correctly formatted.
1638
1639 Just a simple wrapper around check_ast_list_formatted.
1640 Args:
1641 node: An AST node. Assumed to be a dictionary.
1642 filename: The name of the file this node is from.
1643 verbose: If set, print out diff information about how the keys are
1644 incorrectly formatted.
1645 check_sorting: If true, checks if the list is sorted.
1646 Returns:
1647 If the dictionary is correctly formatted.
1648 """
Stephen Martinis54d64ad2018-09-21 22:16:201649 keys = []
1650 # The keys of this dict are ordered as ordered in the file; normal python
1651 # dictionary keys are given an arbitrary order, but since we parsed the
1652 # file itself, the order as given in the file is preserved.
1653 for key in node.keys:
1654 self.type_assert(key, ast.Str, filename, verbose)
Stephen Martinis5bef0fc42020-01-06 22:47:531655 keys.append(key)
Stephen Martinis54d64ad2018-09-21 22:16:201656
Stephen Martinis1384ff92020-01-07 19:52:151657 return self.check_ast_list_formatted(keys, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181658
1659 def check_input_files_sorting(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201660 # TODO(https://crbug.com/886993): Add the ability for this script to
1661 # actually format the files, rather than just complain if they're
1662 # incorrectly formatted.
1663 bad_files = set()
Stephen Martinis5bef0fc42020-01-06 22:47:531664 def parse_file(filename):
1665 """Parses and validates a .pyl file.
Stephen Martinis54d64ad2018-09-21 22:16:201666
Stephen Martinis5bef0fc42020-01-06 22:47:531667 Returns an AST node representing the value in the pyl file."""
Stephen Martinisf83893722018-09-19 00:02:181668 parsed = ast.parse(self.read_file(self.pyl_file_path(filename)))
1669
Stephen Martinisf83893722018-09-19 00:02:181670 # Must be a module.
Stephen Martinis54d64ad2018-09-21 22:16:201671 self.type_assert(parsed, ast.Module, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181672 module = parsed.body
1673
1674 # Only one expression in the module.
Stephen Martinis54d64ad2018-09-21 22:16:201675 self.type_assert(module, list, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181676 if len(module) != 1: # pragma: no cover
1677 raise BBGenErr('Invalid .pyl file %s' % filename)
1678 expr = module[0]
Stephen Martinis54d64ad2018-09-21 22:16:201679 self.type_assert(expr, ast.Expr, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181680
Stephen Martinis5bef0fc42020-01-06 22:47:531681 return expr.value
1682
1683 # Handle this separately
1684 filename = 'waterfalls.pyl'
1685 value = parse_file(filename)
1686 # Value should be a list.
1687 self.type_assert(value, ast.List, filename, verbose)
1688
1689 keys = []
1690 for val in value.elts:
1691 self.type_assert(val, ast.Dict, filename, verbose)
1692 waterfall_name = None
1693 for key, val in zip(val.keys, val.values):
1694 self.type_assert(key, ast.Str, filename, verbose)
1695 if key.s == 'machines':
1696 if not self.check_ast_dict_formatted(val, filename, verbose):
1697 bad_files.add(filename)
1698
1699 if key.s == "name":
1700 self.type_assert(val, ast.Str, filename, verbose)
1701 waterfall_name = val
1702 assert waterfall_name
1703 keys.append(waterfall_name)
1704
Stephen Martinis1384ff92020-01-07 19:52:151705 if not self.check_ast_list_formatted(keys, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531706 bad_files.add(filename)
1707
1708 for filename in (
1709 'mixins.pyl',
1710 'test_suites.pyl',
1711 'test_suite_exceptions.pyl',
1712 ):
1713 value = parse_file(filename)
Stephen Martinisf83893722018-09-19 00:02:181714 # Value should be a dictionary.
Stephen Martinis54d64ad2018-09-21 22:16:201715 self.type_assert(value, ast.Dict, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181716
Stephen Martinis5bef0fc42020-01-06 22:47:531717 if not self.check_ast_dict_formatted(
1718 value, filename, verbose):
1719 bad_files.add(filename)
1720
Stephen Martinis54d64ad2018-09-21 22:16:201721 if filename == 'test_suites.pyl':
Jeff Yoon8154e582019-12-03 23:30:011722 expected_keys = ['basic_suites',
1723 'compound_suites',
1724 'matrix_compound_suites']
Stephen Martinis54d64ad2018-09-21 22:16:201725 actual_keys = [node.s for node in value.keys]
1726 assert all(key in expected_keys for key in actual_keys), (
1727 'Invalid %r file; expected keys %r, got %r' % (
1728 filename, expected_keys, actual_keys))
1729 suite_dicts = [node for node in value.values]
1730 # Only two keys should mean only 1 or 2 values
Jeff Yoon8154e582019-12-03 23:30:011731 assert len(suite_dicts) <= 3
Stephen Martinis54d64ad2018-09-21 22:16:201732 for suite_group in suite_dicts:
Stephen Martinis5bef0fc42020-01-06 22:47:531733 if not self.check_ast_dict_formatted(
Stephen Martinis54d64ad2018-09-21 22:16:201734 suite_group, filename, verbose):
1735 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181736
Stephen Martinis5bef0fc42020-01-06 22:47:531737 for key, suite in zip(value.keys, value.values):
1738 # The compound suites are checked in
1739 # 'check_composition_type_test_suites()'
1740 if key.s == 'basic_suites':
1741 for group in suite.values:
Stephen Martinis1384ff92020-01-07 19:52:151742 if not self.check_ast_dict_formatted(group, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531743 bad_files.add(filename)
1744 break
Stephen Martinis54d64ad2018-09-21 22:16:201745
Stephen Martinis5bef0fc42020-01-06 22:47:531746 elif filename == 'test_suite_exceptions.pyl':
1747 # Check the values for each test.
1748 for test in value.values:
1749 for kind, node in zip(test.keys, test.values):
1750 if isinstance(node, ast.Dict):
Stephen Martinis1384ff92020-01-07 19:52:151751 if not self.check_ast_dict_formatted(node, filename, verbose):
Stephen Martinis5bef0fc42020-01-06 22:47:531752 bad_files.add(filename)
1753 elif kind.s == 'remove_from':
1754 # Don't care about sorting; these are usually grouped, since the
1755 # same bug can affect multiple builders. Do want to make sure
1756 # there aren't duplicates.
1757 if not self.check_ast_list_formatted(node.elts, filename, verbose,
1758 check_sorting=False):
1759 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181760
1761 if bad_files:
1762 raise BBGenErr(
Stephen Martinis54d64ad2018-09-21 22:16:201763 'The following files have invalid keys: %s\n. They are either '
Stephen Martinis5bef0fc42020-01-06 22:47:531764 'unsorted, or have duplicates. Re-run this with --verbose to see '
1765 'more details.' % ', '.join(bad_files))
Stephen Martinisf83893722018-09-19 00:02:181766
Kenneth Russelleb60cbd22017-12-05 07:54:281767 def check_output_file_consistency(self, verbose=False):
1768 self.load_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011769 # All waterfalls/bucket .json files must have been written
1770 # by this script already.
Kenneth Russelleb60cbd22017-12-05 07:54:281771 self.resolve_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011772 ungenerated_files = set()
1773 for filename, expected_contents in self.generate_outputs().items():
1774 expected = self.jsonify(expected_contents)
1775 file_path = filename + '.json'
Zhiling Huangbe008172018-03-08 19:13:111776 current = self.read_file(self.pyl_file_path(file_path))
Kenneth Russelleb60cbd22017-12-05 07:54:281777 if expected != current:
Greg Gutermanf60eb052020-03-12 17:40:011778 ungenerated_files.add(filename)
John Budorick826d5ed2017-12-28 19:27:321779 if verbose: # pragma: no cover
Greg Gutermanf60eb052020-03-12 17:40:011780 self.print_line('File ' + filename +
1781 '.json did not have the following expected '
John Budorick826d5ed2017-12-28 19:27:321782 'contents:')
1783 for line in difflib.unified_diff(
1784 expected.splitlines(),
Stephen Martinis7eb8b612018-09-21 00:17:501785 current.splitlines(),
1786 fromfile='expected', tofile='current'):
1787 self.print_line(line)
Greg Gutermanf60eb052020-03-12 17:40:011788
1789 if ungenerated_files:
1790 raise BBGenErr(
1791 'The following files have not been properly '
1792 'autogenerated by generate_buildbot_json.py: ' +
1793 ', '.join([filename + '.json' for filename in ungenerated_files]))
Kenneth Russelleb60cbd22017-12-05 07:54:281794
1795 def check_consistency(self, verbose=False):
Stephen Martinis7eb8b612018-09-21 00:17:501796 self.check_input_file_consistency(verbose) # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281797 self.check_output_file_consistency(verbose) # pragma: no cover
1798
1799 def parse_args(self, argv): # pragma: no cover
Karen Qiane24b7ee2019-02-12 23:37:061800
1801 # RawTextHelpFormatter allows for styling of help statement
1802 parser = argparse.ArgumentParser(formatter_class=
1803 argparse.RawTextHelpFormatter)
1804
1805 group = parser.add_mutually_exclusive_group()
1806 group.add_argument(
Kenneth Russelleb60cbd22017-12-05 07:54:281807 '-c', '--check', action='store_true', help=
1808 'Do consistency checks of configuration and generated files and then '
1809 'exit. Used during presubmit. Causes the tool to not generate any files.')
Karen Qiane24b7ee2019-02-12 23:37:061810 group.add_argument(
1811 '--query', type=str, help=
1812 ("Returns raw JSON information of buildbots and tests.\n" +
1813 "Examples:\n" +
1814 " List all bots (all info):\n" +
1815 " --query bots\n\n" +
1816 " List all bots and only their associated tests:\n" +
1817 " --query bots/tests\n\n" +
1818 " List all information about 'bot1' " +
1819 "(make sure you have quotes):\n" +
1820 " --query bot/'bot1'\n\n" +
1821 " List tests running for 'bot1' (make sure you have quotes):\n" +
1822 " --query bot/'bot1'/tests\n\n" +
1823 " List all tests:\n" +
1824 " --query tests\n\n" +
1825 " List all tests and the bots running them:\n" +
1826 " --query tests/bots\n\n"+
1827 " List all tests that satisfy multiple parameters\n" +
1828 " (separation of parameters by '&' symbol):\n" +
1829 " --query tests/'device_os:Android&device_type:hammerhead'\n\n" +
1830 " List all tests that run with a specific flag:\n" +
1831 " --query bots/'--test-launcher-print-test-studio=always'\n\n" +
1832 " List specific test (make sure you have quotes):\n"
1833 " --query test/'test1'\n\n"
1834 " List all bots running 'test1' " +
1835 "(make sure you have quotes):\n" +
1836 " --query test/'test1'/bots" ))
Kenneth Russelleb60cbd22017-12-05 07:54:281837 parser.add_argument(
1838 '-n', '--new-files', action='store_true', help=
1839 'Write output files as .new.json. Useful during development so old and '
1840 'new files can be looked at side-by-side.')
1841 parser.add_argument(
Stephen Martinis7eb8b612018-09-21 00:17:501842 '-v', '--verbose', action='store_true', help=
1843 'Increases verbosity. Affects consistency checks.')
1844 parser.add_argument(
Kenneth Russelleb60cbd22017-12-05 07:54:281845 'waterfall_filters', metavar='waterfalls', type=str, nargs='*',
1846 help='Optional list of waterfalls to generate.')
Zhiling Huangbe008172018-03-08 19:13:111847 parser.add_argument(
1848 '--pyl-files-dir', type=os.path.realpath,
1849 help='Path to the directory containing the input .pyl files.')
Karen Qiane24b7ee2019-02-12 23:37:061850 parser.add_argument(
1851 '--json', help=
1852 ("Outputs results into a json file. Only works with query function.\n" +
1853 "Examples:\n" +
1854 " Outputs file into specified json file: \n" +
1855 " --json <file-name-here.json>"))
Garrett Beatyd5ca75962020-05-07 16:58:311856 parser.add_argument(
1857 '--infra-config-dir',
1858 help='Path to the LUCI services configuration directory',
1859 default=os.path.abspath(
1860 os.path.join(os.path.dirname(__file__),
1861 '..', '..', 'infra', 'config')))
Kenneth Russelleb60cbd22017-12-05 07:54:281862 self.args = parser.parse_args(argv)
Karen Qiane24b7ee2019-02-12 23:37:061863 if self.args.json and not self.args.query:
1864 parser.error("The --json flag can only be used with --query.")
Garrett Beatyd5ca75962020-05-07 16:58:311865 self.args.infra_config_dir = os.path.abspath(self.args.infra_config_dir)
Karen Qiane24b7ee2019-02-12 23:37:061866
1867 def does_test_match(self, test_info, params_dict):
1868 """Checks to see if the test matches the parameters given.
1869
1870 Compares the provided test_info with the params_dict to see
1871 if the bot matches the parameters given. If so, returns True.
1872 Else, returns false.
1873
1874 Args:
1875 test_info (dict): Information about a specific bot provided
1876 in the format shown in waterfalls.pyl
1877 params_dict (dict): Dictionary of parameters and their values
1878 to look for in the bot
1879 Ex: {
1880 'device_os':'android',
1881 '--flag':True,
1882 'mixins': ['mixin1', 'mixin2'],
1883 'ex_key':'ex_value'
1884 }
1885
1886 """
1887 DIMENSION_PARAMS = ['device_os', 'device_type', 'os',
1888 'kvm', 'pool', 'integrity'] # dimension parameters
1889 SWARMING_PARAMS = ['shards', 'hard_timeout', 'idempotent',
1890 'can_use_on_swarming_builders']
1891 for param in params_dict:
1892 # if dimension parameter
1893 if param in DIMENSION_PARAMS or param in SWARMING_PARAMS:
1894 if not 'swarming' in test_info:
1895 return False
1896 swarming = test_info['swarming']
1897 if param in SWARMING_PARAMS:
1898 if not param in swarming:
1899 return False
1900 if not str(swarming[param]) == params_dict[param]:
1901 return False
1902 else:
1903 if not 'dimension_sets' in swarming:
1904 return False
1905 d_set = swarming['dimension_sets']
1906 # only looking at the first dimension set
1907 if not param in d_set[0]:
1908 return False
1909 if not d_set[0][param] == params_dict[param]:
1910 return False
1911
1912 # if flag
1913 elif param.startswith('--'):
1914 if not 'args' in test_info:
1915 return False
1916 if not param in test_info['args']:
1917 return False
1918
1919 # not dimension parameter/flag/mixin
1920 else:
1921 if not param in test_info:
1922 return False
1923 if not test_info[param] == params_dict[param]:
1924 return False
1925 return True
1926 def error_msg(self, msg):
1927 """Prints an error message.
1928
1929 In addition to a catered error message, also prints
1930 out where the user can find more help. Then, program exits.
1931 """
1932 self.print_line(msg + (' If you need more information, ' +
1933 'please run with -h or --help to see valid commands.'))
1934 sys.exit(1)
1935
1936 def find_bots_that_run_test(self, test, bots):
1937 matching_bots = []
1938 for bot in bots:
1939 bot_info = bots[bot]
1940 tests = self.flatten_tests_for_bot(bot_info)
1941 for test_info in tests:
1942 test_name = ""
1943 if 'name' in test_info:
1944 test_name = test_info['name']
1945 elif 'test' in test_info:
1946 test_name = test_info['test']
1947 if not test_name == test:
1948 continue
1949 matching_bots.append(bot)
1950 return matching_bots
1951
1952 def find_tests_with_params(self, tests, params_dict):
1953 matching_tests = []
1954 for test_name in tests:
1955 test_info = tests[test_name]
1956 if not self.does_test_match(test_info, params_dict):
1957 continue
1958 if not test_name in matching_tests:
1959 matching_tests.append(test_name)
1960 return matching_tests
1961
1962 def flatten_waterfalls_for_query(self, waterfalls):
1963 bots = {}
1964 for waterfall in waterfalls:
Greg Gutermanf60eb052020-03-12 17:40:011965 waterfall_tests = self.generate_output_tests(waterfall)
1966 for bot in waterfall_tests:
1967 bot_info = waterfall_tests[bot]
1968 bots[bot] = bot_info
Karen Qiane24b7ee2019-02-12 23:37:061969 return bots
1970
1971 def flatten_tests_for_bot(self, bot_info):
1972 """Returns a list of flattened tests.
1973
1974 Returns a list of tests not grouped by test category
1975 for a specific bot.
1976 """
1977 TEST_CATS = self.get_test_generator_map().keys()
1978 tests = []
1979 for test_cat in TEST_CATS:
1980 if not test_cat in bot_info:
1981 continue
1982 test_cat_tests = bot_info[test_cat]
1983 tests = tests + test_cat_tests
1984 return tests
1985
1986 def flatten_tests_for_query(self, test_suites):
1987 """Returns a flattened dictionary of tests.
1988
1989 Returns a dictionary of tests associate with their
1990 configuration, not grouped by their test suite.
1991 """
1992 tests = {}
1993 for test_suite in test_suites.itervalues():
1994 for test in test_suite:
1995 test_info = test_suite[test]
1996 test_name = test
1997 if 'name' in test_info:
1998 test_name = test_info['name']
1999 tests[test_name] = test_info
2000 return tests
2001
2002 def parse_query_filter_params(self, params):
2003 """Parses the filter parameters.
2004
2005 Creates a dictionary from the parameters provided
2006 to filter the bot array.
2007 """
2008 params_dict = {}
2009 for p in params:
2010 # flag
2011 if p.startswith("--"):
2012 params_dict[p] = True
2013 else:
2014 pair = p.split(":")
2015 if len(pair) != 2:
2016 self.error_msg('Invalid command.')
2017 # regular parameters
2018 if pair[1].lower() == "true":
2019 params_dict[pair[0]] = True
2020 elif pair[1].lower() == "false":
2021 params_dict[pair[0]] = False
2022 else:
2023 params_dict[pair[0]] = pair[1]
2024 return params_dict
2025
2026 def get_test_suites_dict(self, bots):
2027 """Returns a dictionary of bots and their tests.
2028
2029 Returns a dictionary of bots and a list of their associated tests.
2030 """
2031 test_suite_dict = dict()
2032 for bot in bots:
2033 bot_info = bots[bot]
2034 tests = self.flatten_tests_for_bot(bot_info)
2035 test_suite_dict[bot] = tests
2036 return test_suite_dict
2037
2038 def output_query_result(self, result, json_file=None):
2039 """Outputs the result of the query.
2040
2041 If a json file parameter name is provided, then
2042 the result is output into the json file. If not,
2043 then the result is printed to the console.
2044 """
2045 output = json.dumps(result, indent=2)
2046 if json_file:
2047 self.write_file(json_file, output)
2048 else:
2049 self.print_line(output)
2050 return
2051
2052 def query(self, args):
2053 """Queries tests or bots.
2054
2055 Depending on the arguments provided, outputs a json of
2056 tests or bots matching the appropriate optional parameters provided.
2057 """
2058 # split up query statement
2059 query = args.query.split('/')
2060 self.load_configuration_files()
2061 self.resolve_configuration_files()
2062
2063 # flatten bots json
2064 tests = self.test_suites
2065 bots = self.flatten_waterfalls_for_query(self.waterfalls)
2066
2067 cmd_class = query[0]
2068
2069 # For queries starting with 'bots'
2070 if cmd_class == "bots":
2071 if len(query) == 1:
2072 return self.output_query_result(bots, args.json)
2073 # query with specific parameters
2074 elif len(query) == 2:
2075 if query[1] == 'tests':
2076 test_suites_dict = self.get_test_suites_dict(bots)
2077 return self.output_query_result(test_suites_dict, args.json)
2078 else:
2079 self.error_msg("This query should be in the format: bots/tests.")
2080
2081 else:
2082 self.error_msg("This query should have 0 or 1 '/', found %s instead."
2083 % str(len(query)-1))
2084
2085 # For queries starting with 'bot'
2086 elif cmd_class == "bot":
2087 if not len(query) == 2 and not len(query) == 3:
2088 self.error_msg("Command should have 1 or 2 '/', found %s instead."
2089 % str(len(query)-1))
2090 bot_id = query[1]
2091 if not bot_id in bots:
2092 self.error_msg("No bot named '" + bot_id + "' found.")
2093 bot_info = bots[bot_id]
2094 if len(query) == 2:
2095 return self.output_query_result(bot_info, args.json)
2096 if not query[2] == 'tests':
2097 self.error_msg("The query should be in the format:" +
2098 "bot/<bot-name>/tests.")
2099
2100 bot_tests = self.flatten_tests_for_bot(bot_info)
2101 return self.output_query_result(bot_tests, args.json)
2102
2103 # For queries starting with 'tests'
2104 elif cmd_class == "tests":
2105 if not len(query) == 1 and not len(query) == 2:
2106 self.error_msg("The query should have 0 or 1 '/', found %s instead."
2107 % str(len(query)-1))
2108 flattened_tests = self.flatten_tests_for_query(tests)
2109 if len(query) == 1:
2110 return self.output_query_result(flattened_tests, args.json)
2111
2112 # create params dict
2113 params = query[1].split('&')
2114 params_dict = self.parse_query_filter_params(params)
2115 matching_bots = self.find_tests_with_params(flattened_tests, params_dict)
2116 return self.output_query_result(matching_bots)
2117
2118 # For queries starting with 'test'
2119 elif cmd_class == "test":
2120 if not len(query) == 2 and not len(query) == 3:
2121 self.error_msg("The query should have 1 or 2 '/', found %s instead."
2122 % str(len(query)-1))
2123 test_id = query[1]
2124 if len(query) == 2:
2125 flattened_tests = self.flatten_tests_for_query(tests)
2126 for test in flattened_tests:
2127 if test == test_id:
2128 return self.output_query_result(flattened_tests[test], args.json)
2129 self.error_msg("There is no test named %s." % test_id)
2130 if not query[2] == 'bots':
2131 self.error_msg("The query should be in the format: " +
2132 "test/<test-name>/bots")
2133 bots_for_test = self.find_bots_that_run_test(test_id, bots)
2134 return self.output_query_result(bots_for_test)
2135
2136 else:
2137 self.error_msg("Your command did not match any valid commands." +
2138 "Try starting with 'bots', 'bot', 'tests', or 'test'.")
Kenneth Russelleb60cbd22017-12-05 07:54:282139
2140 def main(self, argv): # pragma: no cover
2141 self.parse_args(argv)
2142 if self.args.check:
Stephen Martinis7eb8b612018-09-21 00:17:502143 self.check_consistency(verbose=self.args.verbose)
Karen Qiane24b7ee2019-02-12 23:37:062144 elif self.args.query:
2145 self.query(self.args)
Kenneth Russelleb60cbd22017-12-05 07:54:282146 else:
Greg Gutermanf60eb052020-03-12 17:40:012147 self.write_json_result(self.generate_outputs())
Kenneth Russelleb60cbd22017-12-05 07:54:282148 return 0
2149
2150if __name__ == "__main__": # pragma: no cover
2151 generator = BBJSONGenerator()
John Budorick699282e2019-02-13 01:27:332152 sys.exit(generator.main(sys.argv[1:]))