create_matrix_images.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. """Build and upload docker images to Google Container Registry per matrix."""
  16. from __future__ import print_function
  17. import argparse
  18. import atexit
  19. import multiprocessing
  20. import os
  21. import shutil
  22. import subprocess
  23. import sys
  24. import tempfile
  25. # Language Runtime Matrix
  26. import client_matrix
  27. python_util_dir = os.path.abspath(
  28. os.path.join(os.path.dirname(__file__), '../run_tests/python_utils'))
  29. sys.path.append(python_util_dir)
  30. import dockerjob
  31. import jobset
  32. _IMAGE_BUILDER = 'tools/run_tests/dockerize/build_interop_image.sh'
  33. _LANGUAGES = list(client_matrix.LANG_RUNTIME_MATRIX.keys())
  34. # All gRPC release tags, flattened, deduped and sorted.
  35. _RELEASES = sorted(
  36. list(
  37. set(release
  38. for release_dict in list(client_matrix.LANG_RELEASE_MATRIX.values())
  39. for release in list(release_dict.keys()))))
  40. # Destination directory inside docker image to keep extra info from build time.
  41. _BUILD_INFO = '/var/local/build_info'
  42. argp = argparse.ArgumentParser(description='Run interop tests.')
  43. argp.add_argument('--gcr_path',
  44. default='gcr.io/grpc-testing',
  45. help='Path of docker images in Google Container Registry')
  46. argp.add_argument('--release',
  47. default='master',
  48. choices=['all', 'master'] + _RELEASES,
  49. help='github commit tag to checkout. When building all '
  50. 'releases defined in client_matrix.py, use "all". Valid only '
  51. 'with --git_checkout.')
  52. argp.add_argument('-l',
  53. '--language',
  54. choices=['all'] + sorted(_LANGUAGES),
  55. nargs='+',
  56. default=['all'],
  57. help='Test languages to build docker images for.')
  58. argp.add_argument('--git_checkout',
  59. action='store_true',
  60. help='Use a separate git clone tree for building grpc stack. '
  61. 'Required when using --release flag. By default, current'
  62. 'tree and the sibling will be used for building grpc stack.')
  63. argp.add_argument('--git_checkout_root',
  64. default='/export/hda3/tmp/grpc_matrix',
  65. help='Directory under which grpc-go/java/main repo will be '
  66. 'cloned. Valid only with --git_checkout.')
  67. argp.add_argument('--keep',
  68. action='store_true',
  69. help='keep the created local images after uploading to GCR')
  70. argp.add_argument('--reuse_git_root',
  71. default=False,
  72. action='store_const',
  73. const=True,
  74. help='reuse the repo dir. If False, the existing git root '
  75. 'directory will removed before a clean checkout, because '
  76. 'reusing the repo can cause git checkout error if you switch '
  77. 'between releases.')
  78. argp.add_argument(
  79. '--upload_images',
  80. action='store_true',
  81. help='If set, images will be uploaded to container registry after building.'
  82. )
  83. args = argp.parse_args()
  84. def add_files_to_image(image, with_files, label=None):
  85. """Add files to a docker image.
  86. image: docker image name, i.e. grpc_interop_java:26328ad8
  87. with_files: additional files to include in the docker image.
  88. label: label string to attach to the image.
  89. """
  90. tag_idx = image.find(':')
  91. if tag_idx == -1:
  92. jobset.message('FAILED',
  93. 'invalid docker image %s' % image,
  94. do_newline=True)
  95. sys.exit(1)
  96. orig_tag = '%s_' % image
  97. subprocess.check_output(['docker', 'tag', image, orig_tag])
  98. lines = ['FROM ' + orig_tag]
  99. if label:
  100. lines.append('LABEL %s' % label)
  101. temp_dir = tempfile.mkdtemp()
  102. atexit.register(lambda: subprocess.call(['rm', '-rf', temp_dir]))
  103. # Copy with_files inside the tmp directory, which will be the docker build
  104. # context.
  105. for f in with_files:
  106. shutil.copy(f, temp_dir)
  107. lines.append('COPY %s %s/' % (os.path.basename(f), _BUILD_INFO))
  108. # Create a Dockerfile.
  109. with open(os.path.join(temp_dir, 'Dockerfile'), 'w') as f:
  110. f.write('\n'.join(lines))
  111. jobset.message('START', 'Repackaging %s' % image, do_newline=True)
  112. build_cmd = ['docker', 'build', '--rm', '--tag', image, temp_dir]
  113. subprocess.check_output(build_cmd)
  114. dockerjob.remove_image(orig_tag, skip_nonexistent=True)
  115. def build_image_jobspec(runtime, env, gcr_tag, stack_base):
  116. """Build interop docker image for a language with runtime.
  117. runtime: a <lang><version> string, for example go1.8.
  118. env: dictionary of env to passed to the build script.
  119. gcr_tag: the tag for the docker image (i.e. v1.3.0).
  120. stack_base: the local gRPC repo path.
  121. """
  122. basename = 'grpc_interop_%s' % runtime
  123. tag = '%s/%s:%s' % (args.gcr_path, basename, gcr_tag)
  124. build_env = {'INTEROP_IMAGE': tag, 'BASE_NAME': basename}
  125. build_env.update(env)
  126. image_builder_path = _IMAGE_BUILDER
  127. if client_matrix.should_build_docker_interop_image_from_release_tag(lang):
  128. image_builder_path = os.path.join(stack_base, _IMAGE_BUILDER)
  129. build_job = jobset.JobSpec(cmdline=[image_builder_path],
  130. environ=build_env,
  131. shortname='build_docker_%s' % runtime,
  132. timeout_seconds=30 * 60)
  133. build_job.tag = tag
  134. return build_job
  135. def build_all_images_for_lang(lang):
  136. """Build all docker images for a language across releases and runtimes."""
  137. if not args.git_checkout:
  138. if args.release != 'master':
  139. print(
  140. 'Cannot use --release without also enabling --git_checkout.\n')
  141. sys.exit(1)
  142. releases = [args.release]
  143. else:
  144. if args.release == 'all':
  145. releases = client_matrix.get_release_tags(lang)
  146. else:
  147. # Build a particular release.
  148. if args.release not in ['master'
  149. ] + client_matrix.get_release_tags(lang):
  150. jobset.message('SKIPPED',
  151. '%s for %s is not defined' %
  152. (args.release, lang),
  153. do_newline=True)
  154. return []
  155. releases = [args.release]
  156. images = []
  157. for release in releases:
  158. images += build_all_images_for_release(lang, release)
  159. jobset.message('SUCCESS',
  160. 'All docker images built for %s at %s.' % (lang, releases),
  161. do_newline=True)
  162. return images
  163. def build_all_images_for_release(lang, release):
  164. """Build all docker images for a release across all runtimes."""
  165. docker_images = []
  166. build_jobs = []
  167. env = {}
  168. # If we not using current tree or the sibling for grpc stack, do checkout.
  169. stack_base = ''
  170. if args.git_checkout:
  171. stack_base = checkout_grpc_stack(lang, release)
  172. var = {
  173. 'go': 'GRPC_GO_ROOT',
  174. 'java': 'GRPC_JAVA_ROOT',
  175. 'node': 'GRPC_NODE_ROOT'
  176. }.get(lang, 'GRPC_ROOT')
  177. env[var] = stack_base
  178. for runtime in client_matrix.get_runtimes_for_lang_release(lang, release):
  179. job = build_image_jobspec(runtime, env, release, stack_base)
  180. docker_images.append(job.tag)
  181. build_jobs.append(job)
  182. jobset.message('START', 'Building interop docker images.', do_newline=True)
  183. print('Jobs to run: \n%s\n' % '\n'.join(str(j) for j in build_jobs))
  184. num_failures, _ = jobset.run(build_jobs,
  185. newline_on_success=True,
  186. maxjobs=multiprocessing.cpu_count())
  187. if num_failures:
  188. jobset.message('FAILED',
  189. 'Failed to build interop docker images.',
  190. do_newline=True)
  191. docker_images_cleanup.extend(docker_images)
  192. sys.exit(1)
  193. jobset.message('SUCCESS',
  194. 'All docker images built for %s at %s.' % (lang, release),
  195. do_newline=True)
  196. if release != 'master':
  197. commit_log = os.path.join(stack_base, 'commit_log')
  198. if os.path.exists(commit_log):
  199. for image in docker_images:
  200. add_files_to_image(image, [commit_log], 'release=%s' % release)
  201. return docker_images
  202. def cleanup():
  203. if not args.keep:
  204. for image in docker_images_cleanup:
  205. dockerjob.remove_image(image, skip_nonexistent=True)
  206. docker_images_cleanup = []
  207. atexit.register(cleanup)
  208. def maybe_apply_patches_on_git_tag(stack_base, lang, release):
  209. files_to_patch = []
  210. release_info = client_matrix.LANG_RELEASE_MATRIX[lang].get(release)
  211. if release_info:
  212. files_to_patch = release_info.patch
  213. if not files_to_patch:
  214. return
  215. patch_file_relative_path = 'patches/%s_%s/git_repo.patch' % (lang, release)
  216. patch_file = os.path.abspath(
  217. os.path.join(os.path.dirname(__file__), patch_file_relative_path))
  218. if not os.path.exists(patch_file):
  219. jobset.message('FAILED',
  220. 'expected patch file |%s| to exist' % patch_file)
  221. sys.exit(1)
  222. subprocess.check_output(['git', 'apply', patch_file],
  223. cwd=stack_base,
  224. stderr=subprocess.STDOUT)
  225. # TODO(jtattermusch): this really would need simplification and refactoring
  226. # - "git add" and "git commit" can easily be done in a single command
  227. # - it looks like the only reason for the existence of the "files_to_patch"
  228. # entry is to perform "git add" - which is clumsy and fragile.
  229. # - we only allow a single patch with name "git_repo.patch". A better design
  230. # would be to allow multiple patches that can have more descriptive names.
  231. for repo_relative_path in files_to_patch:
  232. subprocess.check_output(['git', 'add', repo_relative_path],
  233. cwd=stack_base,
  234. stderr=subprocess.STDOUT)
  235. subprocess.check_output([
  236. 'git', 'commit', '-m',
  237. ('Hack performed on top of %s git '
  238. 'tag in order to build and run the %s '
  239. 'interop tests on that tag.' % (lang, release))
  240. ],
  241. cwd=stack_base,
  242. stderr=subprocess.STDOUT)
  243. def checkout_grpc_stack(lang, release):
  244. """Invokes 'git check' for the lang/release and returns directory created."""
  245. assert args.git_checkout and args.git_checkout_root
  246. if not os.path.exists(args.git_checkout_root):
  247. os.makedirs(args.git_checkout_root)
  248. repo = client_matrix.get_github_repo(lang)
  249. # Get the subdir name part of repo
  250. # For example, 'git@github.com:grpc/grpc-go.git' should use 'grpc-go'.
  251. repo_dir = os.path.splitext(os.path.basename(repo))[0]
  252. stack_base = os.path.join(args.git_checkout_root, repo_dir)
  253. # Clean up leftover repo dir if necessary.
  254. if not args.reuse_git_root and os.path.exists(stack_base):
  255. jobset.message('START', 'Removing git checkout root.', do_newline=True)
  256. shutil.rmtree(stack_base)
  257. if not os.path.exists(stack_base):
  258. subprocess.check_call(['git', 'clone', '--recursive', repo],
  259. cwd=os.path.dirname(stack_base))
  260. # git checkout.
  261. jobset.message('START',
  262. 'git checkout %s from %s' % (release, stack_base),
  263. do_newline=True)
  264. # We should NEVER do checkout on current tree !!!
  265. assert not os.path.dirname(__file__).startswith(stack_base)
  266. output = subprocess.check_output(['git', 'checkout', release],
  267. cwd=stack_base,
  268. stderr=subprocess.STDOUT)
  269. maybe_apply_patches_on_git_tag(stack_base, lang, release)
  270. commit_log = subprocess.check_output(['git', 'log', '-1'], cwd=stack_base)
  271. jobset.message('SUCCESS',
  272. 'git checkout',
  273. '%s: %s' % (str(output), commit_log),
  274. do_newline=True)
  275. # git submodule update
  276. jobset.message('START',
  277. 'git submodule update --init at %s from %s' %
  278. (release, stack_base),
  279. do_newline=True)
  280. subprocess.check_call(['git', 'submodule', 'update', '--init'],
  281. cwd=stack_base,
  282. stderr=subprocess.STDOUT)
  283. jobset.message('SUCCESS',
  284. 'git submodule update --init',
  285. '%s: %s' % (str(output), commit_log),
  286. do_newline=True)
  287. # Write git log to commit_log so it can be packaged with the docker image.
  288. with open(os.path.join(stack_base, 'commit_log'), 'wb') as f:
  289. f.write(commit_log)
  290. return stack_base
  291. languages = args.language if args.language != ['all'] else _LANGUAGES
  292. for lang in languages:
  293. docker_images = build_all_images_for_lang(lang)
  294. for image in docker_images:
  295. if args.upload_images:
  296. jobset.message('START', 'Uploading %s' % image, do_newline=True)
  297. # docker image name must be in the format <gcr_path>/<image>:<gcr_tag>
  298. assert image.startswith(args.gcr_path) and image.find(':') != -1
  299. subprocess.call(['gcloud', 'docker', '--', 'push', image])
  300. else:
  301. # Uploading (and overwriting images) by default can easily break things.
  302. print(
  303. 'Not uploading image %s, run with --upload_images to upload.' %
  304. image)