2 # Copyright 2017 gRPC authors.
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
8 # http://www.apache.org/licenses/LICENSE-2.0
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."""
17 from __future__ import print_function
21 import multiprocessing
28 # Language Runtime Matrix
31 python_util_dir = os.path.abspath(
32 os.path.join(os.path.dirname(__file__), '../run_tests/python_utils'))
33 sys.path.append(python_util_dir)
37 _IMAGE_BUILDER = 'tools/run_tests/dockerize/build_interop_image.sh'
38 _LANGUAGES = client_matrix.LANG_RUNTIME_MATRIX.keys()
39 # All gRPC release tags, flattened, deduped and sorted.
43 for release_dict in client_matrix.LANG_RELEASE_MATRIX.values()
44 for release in release_dict.keys())))
46 # Destination directory inside docker image to keep extra info from build time.
47 _BUILD_INFO = '/var/local/build_info'
49 argp = argparse.ArgumentParser(description='Run interop tests.')
50 argp.add_argument('--gcr_path',
51 default='gcr.io/grpc-testing',
52 help='Path of docker images in Google Container Registry')
54 argp.add_argument('--release',
56 choices=['all', 'master'] + _RELEASES,
57 help='github commit tag to checkout. When building all '
58 'releases defined in client_matrix.py, use "all". Valid only '
59 'with --git_checkout.')
61 argp.add_argument('-l',
63 choices=['all'] + sorted(_LANGUAGES),
66 help='Test languages to build docker images for.')
68 argp.add_argument('--git_checkout',
70 help='Use a separate git clone tree for building grpc stack. '
71 'Required when using --release flag. By default, current'
72 'tree and the sibling will be used for building grpc stack.')
74 argp.add_argument('--git_checkout_root',
75 default='/export/hda3/tmp/grpc_matrix',
76 help='Directory under which grpc-go/java/main repo will be '
77 'cloned. Valid only with --git_checkout.')
79 argp.add_argument('--keep',
81 help='keep the created local images after uploading to GCR')
83 argp.add_argument('--reuse_git_root',
87 help='reuse the repo dir. If False, the existing git root '
88 'directory will removed before a clean checkout, because '
89 'reusing the repo can cause git checkout error if you switch '
95 help='If set, images will be uploaded to container registry after building.'
98 args = argp.parse_args()
101 def add_files_to_image(image, with_files, label=None):
102 """Add files to a docker image.
104 image: docker image name, i.e. grpc_interop_java:26328ad8
105 with_files: additional files to include in the docker image.
106 label: label string to attach to the image.
108 tag_idx = image.find(':')
110 jobset.message('FAILED',
111 'invalid docker image %s' % image,
114 orig_tag = '%s_' % image
115 subprocess.check_output(['docker', 'tag', image, orig_tag])
117 lines = ['FROM ' + orig_tag]
119 lines.append('LABEL %s' % label)
121 temp_dir = tempfile.mkdtemp()
122 atexit.register(lambda: subprocess.call(['rm', '-rf', temp_dir]))
124 # Copy with_files inside the tmp directory, which will be the docker build
127 shutil.copy(f, temp_dir)
128 lines.append('COPY %s %s/' % (os.path.basename(f), _BUILD_INFO))
130 # Create a Dockerfile.
131 with open(os.path.join(temp_dir, 'Dockerfile'), 'w') as f:
132 f.write('\n'.join(lines))
134 jobset.message('START', 'Repackaging %s' % image, do_newline=True)
135 build_cmd = ['docker', 'build', '--rm', '--tag', image, temp_dir]
136 subprocess.check_output(build_cmd)
137 dockerjob.remove_image(orig_tag, skip_nonexistent=True)
140 def build_image_jobspec(runtime, env, gcr_tag, stack_base):
141 """Build interop docker image for a language with runtime.
143 runtime: a <lang><version> string, for example go1.8.
144 env: dictionary of env to passed to the build script.
145 gcr_tag: the tag for the docker image (i.e. v1.3.0).
146 stack_base: the local gRPC repo path.
148 basename = 'grpc_interop_%s' % runtime
149 tag = '%s/%s:%s' % (args.gcr_path, basename, gcr_tag)
150 build_env = {'INTEROP_IMAGE': tag, 'BASE_NAME': basename, 'TTY_FLAG': '-t'}
151 build_env.update(env)
152 image_builder_path = _IMAGE_BUILDER
153 if client_matrix.should_build_docker_interop_image_from_release_tag(lang):
154 image_builder_path = os.path.join(stack_base, _IMAGE_BUILDER)
155 build_job = jobset.JobSpec(cmdline=[image_builder_path],
157 shortname='build_docker_%s' % runtime,
158 timeout_seconds=30 * 60)
163 def build_all_images_for_lang(lang):
164 """Build all docker images for a language across releases and runtimes."""
165 if not args.git_checkout:
166 if args.release != 'master':
168 'Cannot use --release without also enabling --git_checkout.\n')
170 releases = [args.release]
172 if args.release == 'all':
173 releases = client_matrix.get_release_tags(lang)
175 # Build a particular release.
176 if args.release not in ['master'
177 ] + client_matrix.get_release_tags(lang):
178 jobset.message('SKIPPED',
179 '%s for %s is not defined' %
180 (args.release, lang),
183 releases = [args.release]
186 for release in releases:
187 images += build_all_images_for_release(lang, release)
188 jobset.message('SUCCESS',
189 'All docker images built for %s at %s.' % (lang, releases),
194 def build_all_images_for_release(lang, release):
195 """Build all docker images for a release across all runtimes."""
200 # If we not using current tree or the sibling for grpc stack, do checkout.
202 if args.git_checkout:
203 stack_base = checkout_grpc_stack(lang, release)
205 'go': 'GRPC_GO_ROOT',
206 'java': 'GRPC_JAVA_ROOT',
207 'node': 'GRPC_NODE_ROOT'
208 }.get(lang, 'GRPC_ROOT')
209 env[var] = stack_base
211 for runtime in client_matrix.get_runtimes_for_lang_release(lang, release):
212 job = build_image_jobspec(runtime, env, release, stack_base)
213 docker_images.append(job.tag)
214 build_jobs.append(job)
216 jobset.message('START', 'Building interop docker images.', do_newline=True)
217 print('Jobs to run: \n%s\n' % '\n'.join(str(j) for j in build_jobs))
219 num_failures, _ = jobset.run(build_jobs,
220 newline_on_success=True,
221 maxjobs=multiprocessing.cpu_count())
223 jobset.message('FAILED',
224 'Failed to build interop docker images.',
226 docker_images_cleanup.extend(docker_images)
229 jobset.message('SUCCESS',
230 'All docker images built for %s at %s.' % (lang, release),
233 if release != 'master':
234 commit_log = os.path.join(stack_base, 'commit_log')
235 if os.path.exists(commit_log):
236 for image in docker_images:
237 add_files_to_image(image, [commit_log], 'release=%s' % release)
243 for image in docker_images_cleanup:
244 dockerjob.remove_image(image, skip_nonexistent=True)
247 docker_images_cleanup = []
248 atexit.register(cleanup)
251 def maybe_apply_patches_on_git_tag(stack_base, lang, release):
254 release_info = client_matrix.LANG_RELEASE_MATRIX[lang].get(release)
256 files_to_patch = release_info.patch
257 if not files_to_patch:
259 patch_file_relative_path = 'patches/%s_%s/git_repo.patch' % (lang, release)
260 patch_file = os.path.abspath(
261 os.path.join(os.path.dirname(__file__), patch_file_relative_path))
262 if not os.path.exists(patch_file):
263 jobset.message('FAILED',
264 'expected patch file |%s| to exist' % patch_file)
266 subprocess.check_output(['git', 'apply', patch_file],
268 stderr=subprocess.STDOUT)
270 # TODO(jtattermusch): this really would need simplification and refactoring
271 # - "git add" and "git commit" can easily be done in a single command
272 # - it looks like the only reason for the existence of the "files_to_patch"
273 # entry is to perform "git add" - which is clumsy and fragile.
274 # - we only allow a single patch with name "git_repo.patch". A better design
275 # would be to allow multiple patches that can have more descriptive names.
276 for repo_relative_path in files_to_patch:
277 subprocess.check_output(['git', 'add', repo_relative_path],
279 stderr=subprocess.STDOUT)
280 subprocess.check_output([
281 'git', 'commit', '-m',
282 ('Hack performed on top of %s git '
283 'tag in order to build and run the %s '
284 'interop tests on that tag.' % (lang, release))
287 stderr=subprocess.STDOUT)
290 def checkout_grpc_stack(lang, release):
291 """Invokes 'git check' for the lang/release and returns directory created."""
292 assert args.git_checkout and args.git_checkout_root
294 if not os.path.exists(args.git_checkout_root):
295 os.makedirs(args.git_checkout_root)
297 repo = client_matrix.get_github_repo(lang)
298 # Get the subdir name part of repo
299 # For example, 'git@github.com:grpc/grpc-go.git' should use 'grpc-go'.
300 repo_dir = os.path.splitext(os.path.basename(repo))[0]
301 stack_base = os.path.join(args.git_checkout_root, repo_dir)
303 # Clean up leftover repo dir if necessary.
304 if not args.reuse_git_root and os.path.exists(stack_base):
305 jobset.message('START', 'Removing git checkout root.', do_newline=True)
306 shutil.rmtree(stack_base)
308 if not os.path.exists(stack_base):
309 subprocess.check_call(['git', 'clone', '--recursive', repo],
310 cwd=os.path.dirname(stack_base))
313 jobset.message('START',
314 'git checkout %s from %s' % (release, stack_base),
316 # We should NEVER do checkout on current tree !!!
317 assert not os.path.dirname(__file__).startswith(stack_base)
318 output = subprocess.check_output(['git', 'checkout', release],
320 stderr=subprocess.STDOUT)
321 maybe_apply_patches_on_git_tag(stack_base, lang, release)
322 commit_log = subprocess.check_output(['git', 'log', '-1'], cwd=stack_base)
323 jobset.message('SUCCESS',
325 '%s: %s' % (str(output), commit_log),
328 # git submodule update
329 jobset.message('START',
330 'git submodule update --init at %s from %s' %
331 (release, stack_base),
333 subprocess.check_call(['git', 'submodule', 'update', '--init'],
335 stderr=subprocess.STDOUT)
336 jobset.message('SUCCESS',
337 'git submodule update --init',
338 '%s: %s' % (str(output), commit_log),
341 # Write git log to commit_log so it can be packaged with the docker image.
342 with open(os.path.join(stack_base, 'commit_log'), 'wb') as f:
347 languages = args.language if args.language != ['all'] else _LANGUAGES
348 for lang in languages:
349 docker_images = build_all_images_for_lang(lang)
350 for image in docker_images:
351 if args.upload_images:
352 jobset.message('START', 'Uploading %s' % image, do_newline=True)
353 # docker image name must be in the format <gcr_path>/<image>:<gcr_tag>
354 assert image.startswith(args.gcr_path) and image.find(':') != -1
355 subprocess.call(['gcloud', 'docker', '--', 'push', image])
357 # Uploading (and overwriting images) by default can easily break things.
359 'Not uploading image %s, run with --upload_images to upload.' %