You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

244 lines
8.4 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. #!/usr/bin/env python
  2. # Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  3. #
  4. # Use of this source code is governed by a BSD-style license
  5. # that can be found in the LICENSE file in the root of the source
  6. # tree. An additional intellectual property rights grant can be found
  7. # in the file PATENTS. All contributing project authors may
  8. # be found in the AUTHORS file in the root of the source tree.
  9. # pylint: disable=invalid-name
  10. """
  11. This script acts as an interface between the Chromium infrastructure and
  12. gtest-parallel, renaming options and translating environment variables into
  13. flags. Developers should execute gtest-parallel directly.
  14. In particular, this translates the GTEST_SHARD_INDEX and GTEST_TOTAL_SHARDS
  15. environment variables to the --shard_index and --shard_count flags, renames
  16. the --isolated-script-test-output flag to --dump_json_test_results,
  17. and interprets e.g. --workers=2x as 2 workers per core.
  18. Flags before '--' will be attempted to be understood as arguments to
  19. gtest-parallel. If gtest-parallel doesn't recognize the flag or the flag is
  20. after '--', the flag will be passed on to the test executable.
  21. If the --store-test-artifacts flag is set, an --output_dir must be also
  22. specified.
  23. The test artifacts will then be stored in a 'test_artifacts' subdirectory of the
  24. output dir, and will be compressed into a zip file once the test finishes
  25. executing.
  26. This is useful when running the tests in swarming, since the output directory
  27. is not known beforehand.
  28. For example:
  29. gtest-parallel-wrapper.py some_test \
  30. --some_flag=some_value \
  31. --another_flag \
  32. --output_dir=SOME_OUTPUT_DIR \
  33. --store-test-artifacts
  34. --isolated-script-test-output=SOME_DIR \
  35. --isolated-script-test-perf-output=SOME_OTHER_DIR \
  36. -- \
  37. --foo=bar \
  38. --baz
  39. Will be converted into:
  40. python gtest-parallel \
  41. --shard_index 0 \
  42. --shard_count 1 \
  43. --output_dir=SOME_OUTPUT_DIR \
  44. --dump_json_test_results=SOME_DIR \
  45. some_test \
  46. -- \
  47. --test_artifacts_dir=SOME_OUTPUT_DIR/test_artifacts \
  48. --some_flag=some_value \
  49. --another_flag \
  50. --isolated-script-test-perf-output=SOME_OTHER_DIR \
  51. --foo=bar \
  52. --baz
  53. """
  54. import argparse
  55. import collections
  56. import multiprocessing
  57. import os
  58. import shutil
  59. import subprocess
  60. import sys
  61. Args = collections.namedtuple('Args',
  62. ['gtest_parallel_args', 'test_env', 'output_dir',
  63. 'test_artifacts_dir'])
  64. def _CatFiles(file_list, output_file):
  65. with open(output_file, 'w') as output_file:
  66. for filename in file_list:
  67. with open(filename) as input_file:
  68. output_file.write(input_file.read())
  69. os.remove(filename)
  70. def _ParseWorkersOption(workers):
  71. """Interpret Nx syntax as N * cpu_count. Int value is left as is."""
  72. base = float(workers.rstrip('x'))
  73. if workers.endswith('x'):
  74. result = int(base * multiprocessing.cpu_count())
  75. else:
  76. result = int(base)
  77. return max(result, 1) # Sanitize when using e.g. '0.5x'.
  78. class ReconstructibleArgumentGroup(object):
  79. """An argument group that can be converted back into a command line.
  80. This acts like ArgumentParser.add_argument_group, but names of arguments added
  81. to it are also kept in a list, so that parsed options from
  82. ArgumentParser.parse_args can be reconstructed back into a command line (list
  83. of args) based on the list of wanted keys."""
  84. def __init__(self, parser, *args, **kwargs):
  85. self._group = parser.add_argument_group(*args, **kwargs)
  86. self._keys = []
  87. def AddArgument(self, *args, **kwargs):
  88. arg = self._group.add_argument(*args, **kwargs)
  89. self._keys.append(arg.dest)
  90. def RemakeCommandLine(self, options):
  91. result = []
  92. for key in self._keys:
  93. value = getattr(options, key)
  94. if value is True:
  95. result.append('--%s' % key)
  96. elif value is not None:
  97. result.append('--%s=%s' % (key, value))
  98. return result
  99. def ParseArgs(argv=None):
  100. parser = argparse.ArgumentParser(argv)
  101. gtest_group = ReconstructibleArgumentGroup(parser,
  102. 'Arguments to gtest-parallel')
  103. # These options will be passed unchanged to gtest-parallel.
  104. gtest_group.AddArgument('-d', '--output_dir')
  105. gtest_group.AddArgument('-r', '--repeat')
  106. gtest_group.AddArgument('--retry_failed')
  107. gtest_group.AddArgument('--gtest_color')
  108. gtest_group.AddArgument('--gtest_filter')
  109. gtest_group.AddArgument('--gtest_also_run_disabled_tests',
  110. action='store_true', default=None)
  111. gtest_group.AddArgument('--timeout')
  112. # Syntax 'Nx' will be interpreted as N * number of cpu cores.
  113. gtest_group.AddArgument('-w', '--workers', type=_ParseWorkersOption)
  114. # --isolated-script-test-output is used to upload results to the flakiness
  115. # dashboard. This translation is made because gtest-parallel expects the flag
  116. # to be called --dump_json_test_results instead.
  117. gtest_group.AddArgument('--isolated-script-test-output',
  118. dest='dump_json_test_results')
  119. # Needed when the test wants to store test artifacts, because it doesn't know
  120. # what will be the swarming output dir.
  121. parser.add_argument('--store-test-artifacts', action='store_true')
  122. # No-sandbox is a Chromium-specific flag, ignore it.
  123. # TODO(oprypin): Remove (bugs.webrtc.org/8115)
  124. parser.add_argument('--no-sandbox', action='store_true',
  125. help=argparse.SUPPRESS)
  126. parser.add_argument('executable')
  127. parser.add_argument('executable_args', nargs='*')
  128. options, unrecognized_args = parser.parse_known_args(argv)
  129. webrtc_flags_to_change = {
  130. '--isolated-script-test-perf-output': '--isolated_script_test_perf_output',
  131. '--isolated-script-test-output': '--isolated_script_test_output',
  132. }
  133. args_to_pass = []
  134. for arg in unrecognized_args:
  135. if any(arg.startswith(k) for k in webrtc_flags_to_change.keys()):
  136. arg_split = arg.split('=')
  137. args_to_pass.append(
  138. webrtc_flags_to_change[arg_split[0]] + '=' + arg_split[1])
  139. else:
  140. args_to_pass.append(arg)
  141. executable_args = options.executable_args + args_to_pass
  142. if options.store_test_artifacts:
  143. assert options.output_dir, (
  144. '--output_dir must be specified for storing test artifacts.')
  145. test_artifacts_dir = os.path.join(options.output_dir, 'test_artifacts')
  146. executable_args.insert(0, '--test_artifacts_dir=%s' % test_artifacts_dir)
  147. else:
  148. test_artifacts_dir = None
  149. gtest_parallel_args = gtest_group.RemakeCommandLine(options)
  150. # GTEST_SHARD_INDEX and GTEST_TOTAL_SHARDS must be removed from the
  151. # environment. Otherwise it will be picked up by the binary, causing a bug
  152. # where only tests in the first shard are executed.
  153. test_env = os.environ.copy()
  154. gtest_shard_index = test_env.pop('GTEST_SHARD_INDEX', '0')
  155. gtest_total_shards = test_env.pop('GTEST_TOTAL_SHARDS', '1')
  156. gtest_parallel_args.insert(0, '--shard_index=%s' % gtest_shard_index)
  157. gtest_parallel_args.insert(1, '--shard_count=%s' % gtest_total_shards)
  158. gtest_parallel_args.append(options.executable)
  159. if executable_args:
  160. gtest_parallel_args += ['--'] + executable_args
  161. return Args(gtest_parallel_args, test_env, options.output_dir,
  162. test_artifacts_dir)
  163. def main():
  164. webrtc_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  165. gtest_parallel_path = os.path.join(
  166. webrtc_root, 'third_party', 'gtest-parallel', 'gtest-parallel')
  167. gtest_parallel_args, test_env, output_dir, test_artifacts_dir = ParseArgs()
  168. command = [
  169. sys.executable,
  170. gtest_parallel_path,
  171. ] + gtest_parallel_args
  172. if output_dir and not os.path.isdir(output_dir):
  173. os.makedirs(output_dir)
  174. if test_artifacts_dir and not os.path.isdir(test_artifacts_dir):
  175. os.makedirs(test_artifacts_dir)
  176. print 'gtest-parallel-wrapper: Executing command %s' % ' '.join(command)
  177. sys.stdout.flush()
  178. exit_code = subprocess.call(command, env=test_env, cwd=os.getcwd())
  179. if output_dir:
  180. for test_status in 'passed', 'failed', 'interrupted':
  181. logs_dir = os.path.join(output_dir, 'gtest-parallel-logs', test_status)
  182. if not os.path.isdir(logs_dir):
  183. continue
  184. logs = [os.path.join(logs_dir, log) for log in os.listdir(logs_dir)]
  185. log_file = os.path.join(output_dir, '%s-tests.log' % test_status)
  186. _CatFiles(logs, log_file)
  187. os.rmdir(logs_dir)
  188. if test_artifacts_dir:
  189. shutil.make_archive(test_artifacts_dir, 'zip', test_artifacts_dir)
  190. shutil.rmtree(test_artifacts_dir)
  191. return exit_code
  192. if __name__ == '__main__':
  193. sys.exit(main())