-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathprivate.py
More file actions
242 lines (195 loc) · 7.44 KB
/
private.py
File metadata and controls
242 lines (195 loc) · 7.44 KB
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import cStringIO
import hashlib
import json
import requests
import tarfile
import urlparse
import uuid
from django.conf import settings
from docker.utils import utils
from api.utils import encode
def publish_release(source, config, target):
"""
Publish a new release as a Docker image
Given a source image and dictionary of last-mile configuration,
create a target Docker image on the registry.
For example::
publish_release('registry.local:5000/gabrtv/myapp:v22',
{'ENVVAR': 'values'},
'registry.local:5000/gabrtv/myapp:v23')
results in a new Docker image at 'registry.local:5000/gabrtv/myapp:v23' which
contains the new configuration as ENV entries.
"""
try:
repo, tag = utils.parse_repository_tag(source)
src_image = repo
src_tag = tag if tag is not None else 'latest'
nameparts = repo.rsplit('/', 1)
if len(nameparts) == 2:
if '/' in nameparts[0]:
# strip the hostname and just use the app name
src_image = '{}/{}'.format(nameparts[0].rsplit('/', 1)[1],
nameparts[1])
elif '.' in nameparts[0]:
# we got a name like registry.local:5000/registry
src_image = nameparts[1]
target_image = target.rsplit(':', 1)[0]
target_tag = target.rsplit(':', 1)[1]
image_id = _get_tag(src_image, src_tag)
except RuntimeError:
if src_tag == 'latest':
# no image exists yet, so let's build one!
_put_first_image(src_image)
image_id = _get_tag(src_image, src_tag)
else:
raise
image = _get_image(image_id)
# construct the new image
image['parent'] = image['id']
image['id'] = _new_id()
config['DEIS_APP'] = target_image
config['DEIS_RELEASE'] = target_tag
image['config']['Env'] = _construct_env(config)
# update and tag the new image
_commit(target_image, image, _empty_tar_archive(), target_tag)
# registry access
def _commit(repository_path, image, layer, tag):
_put_image(image)
cookies = _put_layer(image['id'], layer)
_put_checksum(image, cookies)
_put_tag(image['id'], repository_path, tag)
# point latest to the new tag
_put_tag(image['id'], repository_path, 'latest')
def _put_first_image(repository_path):
image = {
'id': _new_id(),
'parent': '',
'config': {
'Env': []
}
}
# tag as v0 in the registry
_commit(repository_path, image, _empty_tar_archive(), 'v0')
def _api_call(endpoint, data=None, headers={}, cookies=None, request_type='GET'):
# FIXME: update API calls for docker 0.10.0+
base_headers = {'user-agent': 'docker/0.9.0'}
r = None
if len(headers) > 0:
for header, value in headers.iteritems():
base_headers[header] = value
if request_type == 'GET':
r = requests.get(endpoint, headers=base_headers)
elif request_type == 'PUT':
r = requests.put(endpoint, data=data, headers=base_headers, cookies=cookies)
else:
raise AttributeError("request type not supported: {}".format(request_type))
return r
def _get_tag(repository, tag):
path = "/v1/repositories/{repository}/tags/{tag}".format(**locals())
url = urlparse.urljoin(settings.REGISTRY_URL, path)
r = _api_call(url)
if not r.status_code == 200:
raise RuntimeError("GET Image Error ({}: {})".format(r.status_code, r.text))
return r.json()
def _get_image(image_id):
path = "/v1/images/{image_id}/json".format(**locals())
url = urlparse.urljoin(settings.REGISTRY_URL, path)
r = _api_call(url)
if not r.status_code == 200:
raise RuntimeError("GET Image Error ({}: {})".format(r.status_code, r.text))
return r.json()
def _put_image(image):
path = "/v1/images/{id}/json".format(**image)
url = urlparse.urljoin(settings.REGISTRY_URL, path)
r = _api_call(url, data=json.dumps(image), request_type='PUT')
if not r.status_code == 200:
raise RuntimeError("PUT Image Error ({}: {})".format(r.status_code, r.text))
return r.json()
def _put_layer(image_id, layer_fileobj):
path = "/v1/images/{image_id}/layer".format(**locals())
url = urlparse.urljoin(settings.REGISTRY_URL, path)
r = _api_call(url, data=layer_fileobj.read(), request_type='PUT')
if not r.status_code == 200:
raise RuntimeError("PUT Layer Error ({}: {})".format(r.status_code, r.text))
return r.cookies
def _put_checksum(image, cookies):
path = "/v1/images/{id}/checksum".format(**image)
url = urlparse.urljoin(settings.REGISTRY_URL, path)
tarsum = TarSum(json.dumps(image)).compute()
headers = {'X-Docker-Checksum': tarsum}
r = _api_call(url, headers=headers, cookies=cookies, request_type='PUT')
if not r.status_code == 200:
raise RuntimeError("PUT Checksum Error ({}: {})".format(r.status_code, r.text))
print r.json()
def _put_tag(image_id, repository_path, tag):
path = "/v1/repositories/{repository_path}/tags/{tag}".format(**locals())
url = urlparse.urljoin(settings.REGISTRY_URL, path)
r = _api_call(url, data=json.dumps(image_id), request_type='PUT')
if not r.status_code == 200:
raise RuntimeError("PUT Tag Error ({}: {})".format(r.status_code, r.text))
print r.json()
# utility functions
def _construct_env(config):
"Update current environment with latest config"
new_env = []
# add config ENV items
for k, v in config.items():
new_env.append("{}={}".format(encode(k), encode(v)))
return new_env
def _new_id():
"Return 64-char UUID for use as Image ID"
return ''.join(uuid.uuid4().hex * 2)
def _empty_tar_archive():
"Return an empty tar archive (in memory)"
data = cStringIO.StringIO()
tar = tarfile.open(mode="w", fileobj=data)
tar.close()
data.seek(0)
return data
#
# Below adapted from https://github.com/dotcloud/docker-registry/blob/master/lib/checksums.py
#
def sha256_file(fp, data=None):
h = hashlib.sha256(data or '')
if not fp:
return h.hexdigest()
while True:
buf = fp.read(4096)
if not buf:
break
h.update(buf)
return h.hexdigest()
def sha256_string(s):
return hashlib.sha256(s).hexdigest()
class TarSum(object):
def __init__(self, json_data):
self.json_data = json_data
self.hashes = []
self.header_fields = ('name', 'mode', 'uid', 'gid', 'size', 'mtime',
'type', 'linkname', 'uname', 'gname', 'devmajor',
'devminor')
def append(self, member, tarobj):
header = ''
for field in self.header_fields:
value = getattr(member, field)
if field == 'type':
field = 'typeflag'
elif field == 'name':
if member.isdir() and not value.endswith('/'):
value += '/'
header += '{0}{1}'.format(field, value)
h = None
try:
if member.size > 0:
f = tarobj.extractfile(member)
h = sha256_file(f, header)
else:
h = sha256_string(header)
except KeyError:
h = sha256_string(header)
self.hashes.append(h)
def compute(self):
self.hashes.sort()
data = self.json_data + ''.join(self.hashes)
tarsum = 'tarsum+sha256:{0}'.format(sha256_string(data))
return tarsum