-
Notifications
You must be signed in to change notification settings - Fork 3
/
docker_utils.py
210 lines (162 loc) · 6.96 KB
/
docker_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import base64
import contextlib
import shlex
import shutil
import subprocess
import sys
import tempfile
import boto3
IMAGE_TEMPLATE = "{account}.dkr.ecr.{region}.amazonaws.com/{image_name}:{version}"
def build_and_push_docker_image(repository_name, dockerfile='Dockerfile', build_args={}):
"""Builds a docker image from the specified dockerfile, and pushes it to
ECR. Handles things like ECR login, creating the repository.
Returns the name of the created docker image in ECR
"""
base_image = _find_base_image_in_dockerfile(dockerfile)
_ecr_login_if_needed(base_image)
_build_from_dockerfile(repository_name, dockerfile, build_args)
ecr_tag = push(repository_name)
return ecr_tag
def _build_from_dockerfile(repository_name, dockerfile='Dockerfile', build_args={}):
build_cmd = ['docker', 'build', '-t', repository_name, '-f', dockerfile, '.']
for k,v in build_args.items():
build_cmd += ['--build-arg', '%s=%s' % (k,v)]
print("Building docker image %s from %s" % (repository_name, dockerfile))
_execute(build_cmd)
print("Done building docker image %s" % repository_name)
def _find_base_image_in_dockerfile(dockerfile):
dockerfile_lines = open(dockerfile).readlines()
from_line = list(filter(lambda line: line.startswith("FROM "), dockerfile_lines))[0].rstrip()
base_image = from_line[5:]
return base_image
def push(tag, aws_account=None, aws_region=None):
"""
Push the builded tag to ECR.
Args:
tag (string): tag which you named your algo
aws_account (string): aws account of the ECR repo
aws_region (string): aws region where the repo is located
Returns:
(string): ECR repo image that was pushed
"""
session = boto3.Session()
aws_account = aws_account or session.client("sts").get_caller_identity()['Account']
aws_region = aws_region or session.region_name
try:
repository_name, version = tag.split(':')
except ValueError: # split failed because no :
repository_name = tag
version = "latest"
ecr_client = session.client('ecr', region_name=aws_region)
_create_ecr_repo(ecr_client, repository_name)
_ecr_login(ecr_client, aws_account)
ecr_tag = _push(aws_account, aws_region, tag)
return ecr_tag
def _push(aws_account, aws_region, tag):
ecr_repo = '%s.dkr.ecr.%s.amazonaws.com' % (aws_account, aws_region)
ecr_tag = '%s/%s' % (ecr_repo, tag)
_execute(['docker', 'tag', tag, ecr_tag])
print("Pushing docker image to ECR repository %s/%s\n" % (ecr_repo, tag))
_execute(['docker', 'push', ecr_tag])
print("Done pushing %s" % ecr_tag)
return ecr_tag
def _create_ecr_repo(ecr_client, repository_name):
"""
Create the repo if it doesn't already exist.
"""
try:
ecr_client.create_repository(repositoryName=repository_name)
print("Created new ECR repository: %s" % repository_name)
except ecr_client.exceptions.RepositoryAlreadyExistsException:
print("ECR repository already exists: %s" % repository_name)
def _ecr_login(ecr_client, aws_account):
auth = ecr_client.get_authorization_token(registryIds=[aws_account])
authorization_data = auth['authorizationData'][0]
raw_token = base64.b64decode(authorization_data['authorizationToken'])
token = raw_token.decode('utf-8').strip('AWS:')
ecr_url = auth['authorizationData'][0]['proxyEndpoint']
cmd = ['docker', 'login', '-u', 'AWS', '-p', token, ecr_url]
_execute(cmd, quiet=True)
print("Logged into ECR")
def _ecr_login_if_needed(image):
ecr_client = boto3.client('ecr')
# Only ECR images need login
if not ('dkr.ecr' in image and 'amazonaws.com' in image):
return
# do we have the image?
if _check_output('docker images -q %s' % image).strip():
return
aws_account = image.split('.')[0]
_ecr_login(ecr_client, aws_account)
@contextlib.contextmanager
def _tmpdir(suffix='', prefix='tmp', dir=None): # type: (str, str, str) -> None
"""Create a temporary directory with a context manager. The file is deleted when the context exits.
The prefix, suffix, and dir arguments are the same as for mkstemp().
Args:
suffix (str): If suffix is specified, the file name will end with that suffix, otherwise there will be no
suffix.
prefix (str): If prefix is specified, the file name will begin with that prefix; otherwise,
a default prefix is used.
dir (str): If dir is specified, the file will be created in that directory; otherwise, a default directory is
used.
Returns:
str: path to the directory
"""
tmp = tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=dir)
yield tmp
shutil.rmtree(tmp)
def _execute(command, quiet=False):
if not quiet:
print("$ %s" % ' '.join(command))
process = subprocess.Popen(command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
try:
_stream_output(process)
except RuntimeError as e:
# _stream_output() doesn't have the command line. We will handle the exception
# which contains the exit code and append the command line to it.
msg = "Failed to run: %s, %s" % (command, str(e))
raise RuntimeError(msg)
def _stream_output(process):
"""Stream the output of a process to stdout
This function takes an existing process that will be polled for output. Only stdout
will be polled and sent to sys.stdout.
Args:
process(subprocess.Popen): a process that has been started with
stdout=PIPE and stderr=STDOUT
Returns (int): process exit code
"""
exit_code = None
while exit_code is None:
stdout = process.stdout.readline().decode("utf-8")
sys.stdout.write(stdout)
exit_code = process.poll()
if exit_code != 0:
raise RuntimeError("Process exited with code: %s" % exit_code)
def _check_output(cmd, *popenargs, **kwargs):
if isinstance(cmd, str):
cmd = shlex.split(cmd)
success = True
try:
output = subprocess.check_output(cmd, *popenargs, **kwargs)
except subprocess.CalledProcessError as e:
output = e.output
success = False
output = output.decode("utf-8")
if not success:
print("Command output: %s" % output)
raise Exception("Failed to run %s" % ",".join(cmd))
return output