3 # Copyright 2017 The Chromium Authors
4 # Use of this source code is governed by a BSD-style license that can be
5 # found in the LICENSE file.
7 """Runs a gtest-based test on Swarming, optionally many times, collecting the
8 output of the runs into a directory. Useful for flake checking, and faster than
9 using trybots by avoiding repeated bot_update, compile, archive, etc. and
10 allowing greater parallelism.
12 To use, run in a new shell (it blocks until all Swarming jobs complete):
14 tools/run-swarmed.py out/rel base_unittests
16 The logs of the runs will be stored in results/ (or specify a results directory
17 with --results=some_dir). You can then do something like `grep -L SUCCESS
18 results/*` to find the tests that failed or otherwise process the log files.
20 See //docs/workflow/debugging-with-swarming.md for more details.
28 import multiprocessing.dummy
35 CHROMIUM_ROOT = os.path.join(os.path.dirname(__file__), os.pardir)
36 BUILD_DIR = os.path.join(CHROMIUM_ROOT, 'build')
38 if BUILD_DIR not in sys.path:
39 sys.path.insert(0, BUILD_DIR)
42 INTERNAL_ERROR_EXIT_CODE = -1000
44 DEFAULT_ANDROID_DEVICE_TYPE = "walleye"
48 """Triggers a swarming job. The arguments passed are:
49 - The index of the job;
50 - The command line arguments object;
51 - The digest of test files.
53 The return value is passed to a collect-style map() and consists of:
54 - The index of the job;
55 - The json file created by triggering and used to collect results;
56 - The command line arguments object.
60 except Exception as e:
66 index, args, cas_digest, swarming_command = args
68 json_file = os.path.join(args.results, '%d.json' % index)
70 'tools/luci-go/swarming',
73 'https://chromium-swarm.appspot.com',
78 '-tag=purpose:user-debug-run-swarmed',
80 if args.target_os == 'fuchsia':
87 elif args.target_os == 'android':
88 if args.arch == 'x86':
89 # No x86 Android devices are available in swarming. So assume we want to
90 # run on emulators when building for x86 on Android.
91 args.swarming_os = 'Linux'
92 args.pool = 'chromium.tests.avd'
93 # generic_android28 == Android P emulator. See //tools/android/avd/proto/
96 '--avd-config=../../tools/android/avd/proto/generic_android28.textpb')
97 elif args.device_type is None and args.device_os is None:
98 # The aliases for device type are stored here:
99 # luci/appengine/swarming/ui2/modules/alias.js
100 # for example 'blueline' = 'Pixel 3'
101 trigger_args += ['-d', 'device_type=' + DEFAULT_ANDROID_DEVICE_TYPE]
102 elif args.arch != 'detect':
109 trigger_args += ['-d', 'device_type=' + args.device_type]
112 trigger_args += ['-d', 'device_os=' + args.device_os]
114 if not args.no_test_flags:
115 # These flags are recognized by our test runners, but do not work
116 # when running custom scripts.
118 '--test-launcher-summary-output=${ISOLATED_OUTDIR}/output.json'
120 if 'junit' not in args.target_name:
121 runner_args += ['--system-log-file=${ISOLATED_OUTDIR}/system_log']
122 if args.gtest_filter:
123 runner_args.append('--gtest_filter=' + args.gtest_filter)
124 if args.gtest_repeat:
125 runner_args.append('--gtest_repeat=' + args.gtest_repeat)
126 if args.test_launcher_shard_index and args.test_launcher_total_shards:
127 runner_args.append('--test-launcher-shard-index=' +
128 args.test_launcher_shard_index)
129 runner_args.append('--test-launcher-total-shards=' +
130 args.test_launcher_total_shards)
131 elif args.target_os == 'fuchsia':
133 'testing/buildbot/filters/fuchsia.' + args.target_name + '.filter'
134 if os.path.isfile(filter_file):
135 runner_args.append('--test-launcher-filter-file=../../' + filter_file)
137 runner_args.extend(args.runner_args)
139 trigger_args.extend(['-d', 'os=' + args.swarming_os])
140 trigger_args.extend(['-d', 'pool=' + args.pool])
141 trigger_args.extend(['--relative-cwd', args.out_dir, '--'])
142 trigger_args.extend(swarming_command)
143 trigger_args.extend(runner_args)
145 with open(os.devnull, 'w') as nul:
146 subprocess.check_call(trigger_args, stdout=nul)
147 return (index, json_file, args)
150 def _Collect(spawn_result):
151 if spawn_result is None:
154 index, json_file, args = spawn_result
155 with open(json_file) as f:
156 task_json = json.load(f)
157 task_ids = [task['task_id'] for task in task_json['tasks']]
160 print('Task {}: https://chromium-swarm.appspot.com/task?id={}'.format(
162 p = subprocess.Popen(
164 'tools/luci-go/swarming',
167 'https://chromium-swarm.appspot.com',
168 '--task-output-stdout=console',
170 stdout=subprocess.PIPE,
171 stderr=subprocess.STDOUT)
172 stdout = p.communicate()[0]
173 if p.returncode != 0 and len(stdout) < 2**10 and 'Internal error!' in stdout:
174 exit_code = INTERNAL_ERROR_EXIT_CODE
175 file_suffix = '.INTERNAL_ERROR'
177 exit_code = p.returncode
178 file_suffix = '' if exit_code == 0 else '.FAILED'
179 filename = '%d%s.stdout.txt' % (index, file_suffix)
180 with open(os.path.join(args.results, filename), 'wb') as f:
186 parser = argparse.ArgumentParser()
187 parser.add_argument('--swarming-os', help='OS specifier for Swarming.')
188 parser.add_argument('--target-os', default='detect', help='gn target_os')
189 parser.add_argument('--arch', '-a', default='detect',
190 help='CPU architecture of the test binary.')
191 parser.add_argument('--build',
194 help='Build before isolating.')
195 parser.add_argument('--no-build',
197 action='store_false',
198 help='Do not build, just isolate (default).')
199 parser.add_argument('--isolate-map-file', '-i',
200 help='path to isolate map file if not using default')
201 parser.add_argument('--copies', '-n', type=int, default=1,
202 help='Number of copies to spawn.')
204 '--device-os', help='Run tests on the given version of Android.')
207 help='device_type specifier for Swarming'
208 ' from https://chromium-swarm.appspot.com/botlist .')
209 parser.add_argument('--pool',
210 default='chromium.tests',
211 help='Use the given swarming pool.')
212 parser.add_argument('--results', '-r', default='results',
213 help='Directory in which to store results.')
216 help='Deprecated. Pass as test runner arg instead, like \'-- '
217 '--gtest_filter="*#testFoo"\'')
220 help='Deprecated. Pass as test runner arg instead, like \'-- '
221 '--gtest_repeat=99\'')
223 '--test-launcher-shard-index',
224 help='Shard index to run. Use with --test-launcher-total-shards.')
225 parser.add_argument('--test-launcher-total-shards',
226 help='Number of shards to split the test into. Use with'
227 ' --test-launcher-shard-index.')
228 parser.add_argument('--no-test-flags', action='store_true',
229 help='Do not add --test-launcher-summary-output and '
230 '--system-log-file flags to the comment.')
231 parser.add_argument('out_dir', type=str, help='Build directory.')
232 parser.add_argument('target_name', type=str, help='Name of target to run.')
237 help='Arguments to pass to the test runner, e.g. gtest_filter and '
240 args = parser.parse_intermixed_args()
242 with open(os.path.join(args.out_dir, 'args.gn')) as f:
243 gn_args = gn_helpers.FromGNArgs(f.read())
245 if args.target_os == 'detect':
246 if 'target_os' in gn_args:
247 args.target_os = gn_args['target_os'].strip('"')
255 if args.swarming_os is None:
260 'android': 'Android',
264 if args.target_os == 'win' and args.target_name.endswith('.exe'):
265 # The machinery expects not to have a '.exe' suffix.
266 args.target_name = os.path.splitext(args.target_name)[0]
268 # Determine the CPU architecture of the test binary, if not specified.
269 if args.arch == 'detect':
270 if args.target_os not in ('android', 'mac', 'win'):
271 executable_info = subprocess.check_output(
272 ['file', os.path.join(args.out_dir, args.target_name)], text=True)
273 if 'ARM aarch64' in executable_info:
277 elif args.target_os == 'android':
278 args.arch = gn_args.get('target_cpu', 'detect')
280 # TODO(crbug.com/1268955): Use sys.executable and remove os-specific logic
281 # once mb.py is in python3
282 mb_cmd = ['tools/mb/mb', 'isolate']
284 mb_cmd.append('--no-build')
285 if args.isolate_map_file:
286 mb_cmd += ['--isolate-map-file', args.isolate_map_file]
287 mb_cmd += ['//' + args.out_dir, args.target_name]
288 subprocess.check_call(mb_cmd, shell=os.name == 'nt')
290 print('If you get authentication errors, follow:')
292 ' https://chromium.googlesource.com/chromium/src/+/HEAD/docs/workflow/debugging-with-swarming.md#authenticating'
295 print('Uploading to isolate server, this can take a while...')
296 isolate = os.path.join(args.out_dir, args.target_name + '.isolate')
297 archive_json = os.path.join(args.out_dir, args.target_name + '.archive.json')
298 subprocess.check_output([
299 'tools/luci-go/isolate', 'archive', '-cas-instance', 'chromium-swarm',
300 '-isolate', isolate, '-dump-json', archive_json
302 with open(archive_json) as f:
303 cas_digest = json.load(f).get(args.target_name)
305 # TODO(crbug.com/1268955): Use sys.executable and remove os-specific logic
306 # once mb.py is in python3
307 mb_cmd = ['tools/mb/mb', 'get-swarming-command', '--as-list']
309 mb_cmd.append('--no-build')
310 if args.isolate_map_file:
311 mb_cmd += ['--isolate-map-file', args.isolate_map_file]
312 mb_cmd += ['//' + args.out_dir, args.target_name]
313 mb_output = subprocess.check_output(mb_cmd, shell=os.name == 'nt')
314 swarming_cmd = json.loads(mb_output)
316 if os.path.isdir(args.results):
317 shutil.rmtree(args.results)
318 os.makedirs(args.results)
321 print('Triggering %d tasks...' % args.copies)
322 # Use dummy since threadpools give better exception messages
323 # than process pools do, and threads work fine for what we're doing.
324 pool = multiprocessing.dummy.Pool()
325 spawn_args = [(i, args, cas_digest, swarming_cmd)
326 for i in range(args.copies)]
327 spawn_results = pool.imap_unordered(_Spawn, spawn_args)
330 collect_results = pool.imap_unordered(_Collect, spawn_results)
331 for result in collect_results:
332 exit_codes.append(result)
333 successes = sum(1 for x in exit_codes if x == 0)
334 errors = sum(1 for x in exit_codes if x == INTERNAL_ERROR_EXIT_CODE)
335 failures = len(exit_codes) - successes - errors
336 clear_to_eol = '\033[K'
338 '\r[%d/%d] collected: '
339 '%d successes, %d failures, %d bot errors...%s' %
340 (len(exit_codes), args.copies, successes, failures, errors,
346 print('Results logs collected into', os.path.abspath(args.results) + '.')
353 if __name__ == '__main__':