blob: b4b6675301a655ae4a147f631ba924734493e0aa [file] [log] [blame]
ehmaldonado3ff7a952017-03-29 09:42:32 -07001#!/usr/bin/env python
2
3# Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
4#
5# Use of this source code is governed by a BSD-style license
6# that can be found in the LICENSE file in the root of the source
7# tree. An additional intellectual property rights grant can be found
8# in the file PATENTS. All contributing project authors may
9# be found in the AUTHORS file in the root of the source tree.
10
kjellanderdd460e22017-04-12 12:06:13 -070011# pylint: disable=invalid-name
ehmaldonado3ff7a952017-03-29 09:42:32 -070012"""
13This script acts as an interface between the Chromium infrastructure and
14gtest-parallel, renaming options and translating environment variables into
15flags. Developers should execute gtest-parallel directly.
16
17In particular, this translates the GTEST_SHARD_INDEX and GTEST_TOTAL_SHARDS
Yves Gereyea766fa2018-09-25 15:34:27 +020018environment variables to the --shard_index and --shard_count flags, renames
19the --isolated-script-test-output flag to --dump_json_test_results,
20and interprets e.g. --workers=2x as 2 workers per core.
ehmaldonado3ff7a952017-03-29 09:42:32 -070021
Oleh Prypin69c02222018-05-23 15:18:12 +020022Flags before '--' will be attempted to be understood as arguments to
23gtest-parallel. If gtest-parallel doesn't recognize the flag or the flag is
24after '--', the flag will be passed on to the test executable.
Edward Lemurc2b6cf32017-10-10 14:00:35 +020025
26If the --store-test-artifacts flag is set, an --output_dir must be also
27specified.
28The test artifacts will then be stored in a 'test_artifacts' subdirectory of the
29output dir, and will be compressed into a zip file once the test finishes
30executing.
31This is useful when running the tests in swarming, since the output directory
32is not known beforehand.
33
ehmaldonado76e60e92017-05-04 06:18:26 -070034For example:
ehmaldonado3ff7a952017-03-29 09:42:32 -070035
36 gtest-parallel-wrapper.py some_test \
ehmaldonado76e60e92017-05-04 06:18:26 -070037 --some_flag=some_value \
38 --another_flag \
Oleh Prypin69c02222018-05-23 15:18:12 +020039 --output_dir=SOME_OUTPUT_DIR \
Edward Lemurc2b6cf32017-10-10 14:00:35 +020040 --store-test-artifacts
41 --isolated-script-test-output=SOME_DIR \
42 --isolated-script-test-perf-output=SOME_OTHER_DIR \
Oleh Prypin69c02222018-05-23 15:18:12 +020043 -- \
ehmaldonado76e60e92017-05-04 06:18:26 -070044 --foo=bar \
45 --baz
ehmaldonado3ff7a952017-03-29 09:42:32 -070046
ehmaldonado76e60e92017-05-04 06:18:26 -070047Will be converted into:
ehmaldonado3ff7a952017-03-29 09:42:32 -070048
Oleh Prypin69c02222018-05-23 15:18:12 +020049 python gtest-parallel \
ehmaldonado3ff7a952017-03-29 09:42:32 -070050 --shard_index 0 \
Oleh Prypin69c02222018-05-23 15:18:12 +020051 --shard_count 1 \
Edward Lemurc2b6cf32017-10-10 14:00:35 +020052 --output_dir=SOME_OUTPUT_DIR \
53 --dump_json_test_results=SOME_DIR \
Oleh Prypin69c02222018-05-23 15:18:12 +020054 some_test \
ehmaldonado3ff7a952017-03-29 09:42:32 -070055 -- \
Edward Lemurc2b6cf32017-10-10 14:00:35 +020056 --test_artifacts_dir=SOME_OUTPUT_DIR/test_artifacts \
Oleh Prypin69c02222018-05-23 15:18:12 +020057 --some_flag=some_value \
58 --another_flag \
59 --isolated-script-test-perf-output=SOME_OTHER_DIR \
Edward Lemurc2b6cf32017-10-10 14:00:35 +020060 --foo=bar \
ehmaldonado76e60e92017-05-04 06:18:26 -070061 --baz
62
ehmaldonado3ff7a952017-03-29 09:42:32 -070063"""
64
65import argparse
Edward Lemurc2b6cf32017-10-10 14:00:35 +020066import collections
Yves Gereyea766fa2018-09-25 15:34:27 +020067import multiprocessing
ehmaldonado3ff7a952017-03-29 09:42:32 -070068import os
Edward Lemurc2b6cf32017-10-10 14:00:35 +020069import shutil
ehmaldonado3ff7a952017-03-29 09:42:32 -070070import subprocess
71import sys
72
ehmaldonado3ff7a952017-03-29 09:42:32 -070073
Edward Lemurc2b6cf32017-10-10 14:00:35 +020074Args = collections.namedtuple('Args',
75 ['gtest_parallel_args', 'test_env', 'output_dir',
76 'test_artifacts_dir'])
77
78
79def _CatFiles(file_list, output_file):
ehmaldonado03184632017-03-30 03:33:19 -070080 with open(output_file, 'w') as output_file:
81 for filename in file_list:
82 with open(filename) as input_file:
83 output_file.write(input_file.read())
84 os.remove(filename)
ehmaldonado3ff7a952017-03-29 09:42:32 -070085
Yves Gereyea766fa2018-09-25 15:34:27 +020086def _ParseWorkersOption(workers):
87 """Interpret Nx syntax as N * cpu_count. Int value is left as is."""
88 base = float(workers.rstrip('x'))
89 if workers.endswith('x'):
90 result = int(base * multiprocessing.cpu_count())
91 else:
92 result = int(base)
93 return max(result, 1) # Sanitize when using e.g. '0.5x'.
94
ehmaldonado3ff7a952017-03-29 09:42:32 -070095
Oleh Prypin69c02222018-05-23 15:18:12 +020096class ReconstructibleArgumentGroup(object):
97 """An argument group that can be converted back into a command line.
98
99 This acts like ArgumentParser.add_argument_group, but names of arguments added
100 to it are also kept in a list, so that parsed options from
101 ArgumentParser.parse_args can be reconstructed back into a command line (list
102 of args) based on the list of wanted keys."""
103 def __init__(self, parser, *args, **kwargs):
104 self._group = parser.add_argument_group(*args, **kwargs)
105 self._keys = []
106
107 def AddArgument(self, *args, **kwargs):
108 arg = self._group.add_argument(*args, **kwargs)
109 self._keys.append(arg.dest)
110
111 def RemakeCommandLine(self, options):
112 result = []
113 for key in self._keys:
114 value = getattr(options, key)
115 if value is True:
116 result.append('--%s' % key)
117 elif value is not None:
118 result.append('--%s=%s' % (key, value))
119 return result
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200120
121
Oleh Prypin69c02222018-05-23 15:18:12 +0200122def ParseArgs(argv=None):
123 parser = argparse.ArgumentParser(argv)
ehmaldonado76e60e92017-05-04 06:18:26 -0700124
Oleh Prypin69c02222018-05-23 15:18:12 +0200125 gtest_group = ReconstructibleArgumentGroup(parser,
126 'Arguments to gtest-parallel')
127 # These options will be passed unchanged to gtest-parallel.
128 gtest_group.AddArgument('-d', '--output_dir')
129 gtest_group.AddArgument('-r', '--repeat')
130 gtest_group.AddArgument('--retry_failed')
Oleh Prypin69c02222018-05-23 15:18:12 +0200131 gtest_group.AddArgument('--gtest_color')
132 gtest_group.AddArgument('--gtest_filter')
133 gtest_group.AddArgument('--gtest_also_run_disabled_tests',
134 action='store_true', default=None)
135 gtest_group.AddArgument('--timeout')
ehmaldonado76e60e92017-05-04 06:18:26 -0700136
Yves Gereyea766fa2018-09-25 15:34:27 +0200137 # Syntax 'Nx' will be interpreted as N * number of cpu cores.
138 gtest_group.AddArgument('-w', '--workers', type=_ParseWorkersOption)
139
ehmaldonado76e60e92017-05-04 06:18:26 -0700140 # --isolated-script-test-output is used to upload results to the flakiness
141 # dashboard. This translation is made because gtest-parallel expects the flag
142 # to be called --dump_json_test_results instead.
Oleh Prypin69c02222018-05-23 15:18:12 +0200143 gtest_group.AddArgument('--isolated-script-test-output',
144 dest='dump_json_test_results')
ehmaldonado3ff7a952017-03-29 09:42:32 -0700145
Oleh Prypin69c02222018-05-23 15:18:12 +0200146 # Needed when the test wants to store test artifacts, because it doesn't know
147 # what will be the swarming output dir.
148 parser.add_argument('--store-test-artifacts', action='store_true')
149
150 # No-sandbox is a Chromium-specific flag, ignore it.
151 # TODO(oprypin): Remove (bugs.webrtc.org/8115)
152 parser.add_argument('--no-sandbox', action='store_true',
153 help=argparse.SUPPRESS)
154
155 parser.add_argument('executable')
156 parser.add_argument('executable_args', nargs='*')
157
158 options, unrecognized_args = parser.parse_known_args(argv)
159
Mirko Bonadei2ab97f62019-07-18 13:44:12 +0200160 webrtc_flags_to_change = {
161 '--isolated-script-test-perf-output': '--isolated_script_test_perf_output',
162 '--isolated-script-test-output': '--isolated_script_test_output',
163 }
164 args_to_pass = []
165 for arg in unrecognized_args:
166 if any(arg.startswith(k) for k in webrtc_flags_to_change.keys()):
167 arg_split = arg.split('=')
168 args_to_pass.append(
169 webrtc_flags_to_change[arg_split[0]] + '=' + arg_split[1])
170 else:
171 args_to_pass.append(arg)
172
173 executable_args = options.executable_args + args_to_pass
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200174
175 if options.store_test_artifacts:
Oleh Prypin69c02222018-05-23 15:18:12 +0200176 assert options.output_dir, (
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200177 '--output_dir must be specified for storing test artifacts.')
Oleh Prypin69c02222018-05-23 15:18:12 +0200178 test_artifacts_dir = os.path.join(options.output_dir, 'test_artifacts')
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200179
Oleh Prypin69c02222018-05-23 15:18:12 +0200180 executable_args.insert(0, '--test_artifacts_dir=%s' % test_artifacts_dir)
181 else:
182 test_artifacts_dir = None
183
184 gtest_parallel_args = gtest_group.RemakeCommandLine(options)
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200185
ehmaldonado03184632017-03-30 03:33:19 -0700186 # GTEST_SHARD_INDEX and GTEST_TOTAL_SHARDS must be removed from the
187 # environment. Otherwise it will be picked up by the binary, causing a bug
188 # where only tests in the first shard are executed.
189 test_env = os.environ.copy()
190 gtest_shard_index = test_env.pop('GTEST_SHARD_INDEX', '0')
191 gtest_total_shards = test_env.pop('GTEST_TOTAL_SHARDS', '1')
ehmaldonado3ff7a952017-03-29 09:42:32 -0700192
Oleh Prypin69c02222018-05-23 15:18:12 +0200193 gtest_parallel_args.insert(0, '--shard_index=%s' % gtest_shard_index)
194 gtest_parallel_args.insert(1, '--shard_count=%s' % gtest_total_shards)
ehmaldonado3ff7a952017-03-29 09:42:32 -0700195
Oleh Prypin69c02222018-05-23 15:18:12 +0200196 gtest_parallel_args.append(options.executable)
197 if executable_args:
198 gtest_parallel_args += ['--'] + executable_args
199
200 return Args(gtest_parallel_args, test_env, options.output_dir,
201 test_artifacts_dir)
ehmaldonado76e60e92017-05-04 06:18:26 -0700202
203
204def main():
205 webrtc_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
206 gtest_parallel_path = os.path.join(
207 webrtc_root, 'third_party', 'gtest-parallel', 'gtest-parallel')
208
Oleh Prypin69c02222018-05-23 15:18:12 +0200209 gtest_parallel_args, test_env, output_dir, test_artifacts_dir = ParseArgs()
ehmaldonado3ff7a952017-03-29 09:42:32 -0700210
ehmaldonado03184632017-03-30 03:33:19 -0700211 command = [
212 sys.executable,
213 gtest_parallel_path,
Oleh Prypin69c02222018-05-23 15:18:12 +0200214 ] + gtest_parallel_args
ehmaldonado3ff7a952017-03-29 09:42:32 -0700215
Oleh Prypin69c02222018-05-23 15:18:12 +0200216 if output_dir and not os.path.isdir(output_dir):
217 os.makedirs(output_dir)
218 if test_artifacts_dir and not os.path.isdir(test_artifacts_dir):
219 os.makedirs(test_artifacts_dir)
Mirko Bonadei738d11b2018-02-19 12:15:45 +0100220
ehmaldonado03184632017-03-30 03:33:19 -0700221 print 'gtest-parallel-wrapper: Executing command %s' % ' '.join(command)
222 sys.stdout.flush()
223
Oleh Prypin69c02222018-05-23 15:18:12 +0200224 exit_code = subprocess.call(command, env=test_env, cwd=os.getcwd())
ehmaldonado03184632017-03-30 03:33:19 -0700225
Oleh Prypin69c02222018-05-23 15:18:12 +0200226 if output_dir:
ehmaldonado950614e2017-05-02 05:52:57 -0700227 for test_status in 'passed', 'failed', 'interrupted':
Oleh Prypin69c02222018-05-23 15:18:12 +0200228 logs_dir = os.path.join(output_dir, 'gtest-parallel-logs', test_status)
ehmaldonado950614e2017-05-02 05:52:57 -0700229 if not os.path.isdir(logs_dir):
230 continue
231 logs = [os.path.join(logs_dir, log) for log in os.listdir(logs_dir)]
Oleh Prypin69c02222018-05-23 15:18:12 +0200232 log_file = os.path.join(output_dir, '%s-tests.log' % test_status)
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200233 _CatFiles(logs, log_file)
ehmaldonado950614e2017-05-02 05:52:57 -0700234 os.rmdir(logs_dir)
ehmaldonado03184632017-03-30 03:33:19 -0700235
Oleh Prypin69c02222018-05-23 15:18:12 +0200236 if test_artifacts_dir:
237 shutil.make_archive(test_artifacts_dir, 'zip', test_artifacts_dir)
238 shutil.rmtree(test_artifacts_dir)
Edward Lemurc2b6cf32017-10-10 14:00:35 +0200239
ehmaldonado03184632017-03-30 03:33:19 -0700240 return exit_code
241
242
243if __name__ == '__main__':
244 sys.exit(main())