run_interop_matrix_tests.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. #!/usr/bin/env python3
  2. # Copyright 2017 gRPC authors.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Run tests using docker images in Google Container Registry per matrix."""
  16. from __future__ import print_function
  17. import argparse
  18. import atexit
  19. import json
  20. import multiprocessing
  21. import os
  22. import re
  23. import subprocess
  24. import sys
  25. import uuid
  26. # Language Runtime Matrix
  27. import client_matrix
  28. python_util_dir = os.path.abspath(
  29. os.path.join(os.path.dirname(__file__), '../run_tests/python_utils'))
  30. sys.path.append(python_util_dir)
  31. import dockerjob
  32. import jobset
  33. import report_utils
  34. import upload_test_results
  35. _TEST_TIMEOUT_SECONDS = 60
  36. _PULL_IMAGE_TIMEOUT_SECONDS = 15 * 60
  37. _MAX_PARALLEL_DOWNLOADS = 6
  38. _LANGUAGES = list(client_matrix.LANG_RUNTIME_MATRIX.keys())
  39. # All gRPC release tags, flattened, deduped and sorted.
  40. _RELEASES = sorted(
  41. list(
  42. set(release
  43. for release_dict in list(client_matrix.LANG_RELEASE_MATRIX.values())
  44. for release in list(release_dict.keys()))))
  45. argp = argparse.ArgumentParser(description='Run interop tests.')
  46. argp.add_argument('-j', '--jobs', default=multiprocessing.cpu_count(), type=int)
  47. argp.add_argument('--gcr_path',
  48. default='gcr.io/grpc-testing',
  49. help='Path of docker images in Google Container Registry')
  50. argp.add_argument('--release',
  51. default='all',
  52. choices=['all'] + _RELEASES,
  53. help='Release tags to test. When testing all '
  54. 'releases defined in client_matrix.py, use "all".')
  55. argp.add_argument('-l',
  56. '--language',
  57. choices=['all'] + sorted(_LANGUAGES),
  58. nargs='+',
  59. default=['all'],
  60. help='Languages to test')
  61. argp.add_argument(
  62. '--keep',
  63. action='store_true',
  64. help='keep the created local images after finishing the tests.')
  65. argp.add_argument('--report_file',
  66. default='report.xml',
  67. help='The result file to create.')
  68. argp.add_argument('--allow_flakes',
  69. default=False,
  70. action='store_const',
  71. const=True,
  72. help=('Allow flaky tests to show as passing (re-runs failed '
  73. 'tests up to five times)'))
  74. argp.add_argument('--bq_result_table',
  75. default='',
  76. type=str,
  77. nargs='?',
  78. help='Upload test results to a specified BQ table.')
  79. # Requests will be routed through specified VIP by default.
  80. # See go/grpc-interop-tests (internal-only) for details.
  81. argp.add_argument('--server_host',
  82. default='74.125.206.210',
  83. type=str,
  84. nargs='?',
  85. help='The gateway to backend services.')
  86. def _get_test_images_for_lang(lang, release_arg, image_path_prefix):
  87. """Find docker images for a language across releases and runtimes.
  88. Returns dictionary of list of (<tag>, <image-full-path>) keyed by runtime.
  89. """
  90. if release_arg == 'all':
  91. # Use all defined releases for given language
  92. releases = client_matrix.get_release_tags(lang)
  93. else:
  94. # Look for a particular release.
  95. if release_arg not in client_matrix.get_release_tags(lang):
  96. jobset.message('SKIPPED',
  97. 'release %s for %s is not defined' %
  98. (release_arg, lang),
  99. do_newline=True)
  100. return {}
  101. releases = [release_arg]
  102. # Image tuples keyed by runtime.
  103. images = {}
  104. for tag in releases:
  105. for runtime in client_matrix.get_runtimes_for_lang_release(lang, tag):
  106. image_name = '%s/grpc_interop_%s:%s' % (image_path_prefix, runtime,
  107. tag)
  108. image_tuple = (tag, image_name)
  109. if runtime not in images:
  110. images[runtime] = []
  111. images[runtime].append(image_tuple)
  112. return images
  113. def _read_test_cases_file(lang, runtime, release):
  114. """Read test cases from a bash-like file and return a list of commands"""
  115. # Check to see if we need to use a particular version of test cases.
  116. release_info = client_matrix.LANG_RELEASE_MATRIX[lang].get(release)
  117. if release_info:
  118. testcases_file = release_info.testcases_file
  119. if not testcases_file:
  120. # TODO(jtattermusch): remove the double-underscore, it is pointless
  121. testcases_file = '%s__master' % lang
  122. # For csharp, the testcases file used depends on the runtime
  123. # TODO(jtattermusch): remove this odd specialcase
  124. if lang == 'csharp' and runtime == 'csharpcoreclr':
  125. testcases_file = testcases_file.replace('csharp_', 'csharpcoreclr_')
  126. testcases_filepath = os.path.join(os.path.dirname(__file__), 'testcases',
  127. testcases_file)
  128. lines = []
  129. with open(testcases_filepath) as f:
  130. for line in f.readlines():
  131. line = re.sub('\\#.*$', '', line) # remove hash comments
  132. line = line.strip()
  133. if line and not line.startswith('echo'):
  134. # Each non-empty line is a treated as a test case command
  135. lines.append(line)
  136. return lines
  137. def _cleanup_docker_image(image):
  138. jobset.message('START', 'Cleanup docker image %s' % image, do_newline=True)
  139. dockerjob.remove_image(image, skip_nonexistent=True)
  140. args = argp.parse_args()
  141. # caches test cases (list of JobSpec) loaded from file. Keyed by lang and runtime.
  142. def _generate_test_case_jobspecs(lang, runtime, release, suite_name):
  143. """Returns the list of test cases from testcase files per lang/release."""
  144. testcase_lines = _read_test_cases_file(lang, runtime, release)
  145. job_spec_list = []
  146. for line in testcase_lines:
  147. print("Creating jobspec with cmdline '{}'".format(line))
  148. # TODO(jtattermusch): revisit the logic for updating test case commands
  149. # what it currently being done seems fragile.
  150. # Extract test case name from the command line
  151. m = re.search(r'--test_case=(\w+)', line)
  152. testcase_name = m.group(1) if m else 'unknown_test'
  153. # Extract the server name from the command line
  154. if '--server_host_override=' in line:
  155. m = re.search(
  156. r'--server_host_override=((.*).sandbox.googleapis.com)', line)
  157. else:
  158. m = re.search(r'--server_host=((.*).sandbox.googleapis.com)', line)
  159. server = m.group(1) if m else 'unknown_server'
  160. server_short = m.group(2) if m else 'unknown_server'
  161. # replace original server_host argument
  162. assert '--server_host=' in line
  163. line = re.sub(r'--server_host=[^ ]*',
  164. r'--server_host=%s' % args.server_host, line)
  165. # some interop tests don't set server_host_override (see #17407),
  166. # but we need to use it if different host is set via cmdline args.
  167. if args.server_host != server and not '--server_host_override=' in line:
  168. line = re.sub(r'(--server_host=[^ ]*)',
  169. r'\1 --server_host_override=%s' % server, line)
  170. spec = jobset.JobSpec(cmdline=line,
  171. shortname='%s:%s:%s:%s' %
  172. (suite_name, lang, server_short, testcase_name),
  173. timeout_seconds=_TEST_TIMEOUT_SECONDS,
  174. shell=True,
  175. flake_retries=5 if args.allow_flakes else 0)
  176. job_spec_list.append(spec)
  177. return job_spec_list
  178. def _pull_image_for_lang(lang, image, release):
  179. """Pull an image for a given language form the image registry."""
  180. cmdline = [
  181. 'time gcloud docker -- pull %s && time docker run --rm=true %s /bin/true'
  182. % (image, image)
  183. ]
  184. return jobset.JobSpec(cmdline=cmdline,
  185. shortname='pull_image_{}'.format(image),
  186. timeout_seconds=_PULL_IMAGE_TIMEOUT_SECONDS,
  187. shell=True,
  188. flake_retries=2)
  189. def _test_release(lang, runtime, release, image, xml_report_tree, skip_tests):
  190. total_num_failures = 0
  191. suite_name = '%s__%s_%s' % (lang, runtime, release)
  192. job_spec_list = _generate_test_case_jobspecs(lang, runtime, release,
  193. suite_name)
  194. if not job_spec_list:
  195. jobset.message('FAILED', 'No test cases were found.', do_newline=True)
  196. total_num_failures += 1
  197. else:
  198. num_failures, resultset = jobset.run(job_spec_list,
  199. newline_on_success=True,
  200. add_env={'docker_image': image},
  201. maxjobs=args.jobs,
  202. skip_jobs=skip_tests)
  203. if args.bq_result_table and resultset:
  204. upload_test_results.upload_interop_results_to_bq(
  205. resultset, args.bq_result_table)
  206. if skip_tests:
  207. jobset.message('FAILED', 'Tests were skipped', do_newline=True)
  208. total_num_failures += 1
  209. if num_failures:
  210. total_num_failures += num_failures
  211. report_utils.append_junit_xml_results(xml_report_tree, resultset,
  212. 'grpc_interop_matrix', suite_name,
  213. str(uuid.uuid4()))
  214. return total_num_failures
  215. def _run_tests_for_lang(lang, runtime, images, xml_report_tree):
  216. """Find and run all test cases for a language.
  217. images is a list of (<release-tag>, <image-full-path>) tuple.
  218. """
  219. skip_tests = False
  220. total_num_failures = 0
  221. max_pull_jobs = min(args.jobs, _MAX_PARALLEL_DOWNLOADS)
  222. max_chunk_size = max_pull_jobs
  223. chunk_count = (len(images) + max_chunk_size) // max_chunk_size
  224. for chunk_index in range(chunk_count):
  225. chunk_start = chunk_index * max_chunk_size
  226. chunk_size = min(max_chunk_size, len(images) - chunk_start)
  227. chunk_end = chunk_start + chunk_size
  228. pull_specs = []
  229. if not skip_tests:
  230. for release, image in images[chunk_start:chunk_end]:
  231. pull_specs.append(_pull_image_for_lang(lang, image, release))
  232. # NOTE(rbellevi): We batch docker pull operations to maximize
  233. # parallelism, without letting the disk usage grow unbounded.
  234. pull_failures, _ = jobset.run(pull_specs,
  235. newline_on_success=True,
  236. maxjobs=max_pull_jobs)
  237. if pull_failures:
  238. jobset.message(
  239. 'FAILED',
  240. 'Image download failed. Skipping tests for language "%s"' %
  241. lang,
  242. do_newline=True)
  243. skip_tests = True
  244. for release, image in images[chunk_start:chunk_end]:
  245. total_num_failures += _test_release(lang, runtime, release, image,
  246. xml_report_tree, skip_tests)
  247. if not args.keep:
  248. for _, image in images[chunk_start:chunk_end]:
  249. _cleanup_docker_image(image)
  250. if not total_num_failures:
  251. jobset.message('SUCCESS',
  252. 'All {} tests passed'.format(lang),
  253. do_newline=True)
  254. else:
  255. jobset.message('FAILED',
  256. 'Some {} tests failed'.format(lang),
  257. do_newline=True)
  258. return total_num_failures
  259. languages = args.language if args.language != ['all'] else _LANGUAGES
  260. total_num_failures = 0
  261. _xml_report_tree = report_utils.new_junit_xml_tree()
  262. for lang in languages:
  263. docker_images = _get_test_images_for_lang(lang, args.release, args.gcr_path)
  264. for runtime in sorted(docker_images.keys()):
  265. total_num_failures += _run_tests_for_lang(lang, runtime,
  266. docker_images[runtime],
  267. _xml_report_tree)
  268. report_utils.create_xml_report_file(_xml_report_tree, args.report_file)
  269. if total_num_failures:
  270. sys.exit(1)
  271. sys.exit(0)