forked from docker-archive/docker-registry
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimages.py
486 lines (431 loc) · 17.8 KB
/
images.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
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# -*- coding: utf-8 -*-
import datetime
import functools
import logging
import time
import flask
from docker_registry.core import compat
from docker_registry.core import exceptions
json = compat.json
from . import storage
from . import toolkit
from .app import app
from .app import cfg
from .lib import cache
from .lib import checksums
from .lib import layers
from .lib import mirroring
# this is our monkey patched snippet from python v2.7.6 'tarfile'
# with xattr support
from .lib.xtarfile import tarfile
store = storage.load()
logger = logging.getLogger(__name__)
def require_completion(f):
"""This make sure that the image push correctly finished."""
@functools.wraps(f)
def wrapper(*args, **kwargs):
if store.exists(store.image_mark_path(kwargs['image_id'])):
return toolkit.api_error('Image is being uploaded, retry later')
return f(*args, **kwargs)
return wrapper
def set_cache_headers(f):
"""Returns HTTP headers suitable for caching."""
@functools.wraps(f)
def wrapper(*args, **kwargs):
# Set TTL to 1 year by default
ttl = 31536000
expires = datetime.datetime.fromtimestamp(int(time.time()) + ttl)
expires = expires.strftime('%a, %d %b %Y %H:%M:%S GMT')
headers = {
'Cache-Control': 'public, max-age={0}'.format(ttl),
'Expires': expires,
'Last-Modified': 'Thu, 01 Jan 1970 00:00:00 GMT',
}
if 'If-Modified-Since' in flask.request.headers:
return flask.Response(status=304, headers=headers)
kwargs['headers'] = headers
# Prevent the Cookie to be sent when the object is cacheable
return f(*args, **kwargs)
return wrapper
def _get_image_layer(image_id, headers=None, bytes_range=None):
if headers is None:
headers = {}
headers['Content-Type'] = 'application/octet-stream'
accel_uri_prefix = cfg.nginx_x_accel_redirect
path = store.image_layer_path(image_id)
if accel_uri_prefix:
if store.scheme == 'file':
accel_uri = '/'.join([accel_uri_prefix, path])
headers['X-Accel-Redirect'] = accel_uri
logger.debug('send accelerated {0} ({1})'.format(
accel_uri, headers))
return flask.Response('', headers=headers)
else:
logger.warn('nginx_x_accel_redirect config set,'
' but storage is not LocalStorage')
# If store allows us to just redirect the client let's do that, we'll
# offload a lot of expensive I/O and get faster I/O
if cfg.storage_redirect:
try:
content_redirect_url = store.content_redirect_url(path)
if content_redirect_url:
return flask.redirect(content_redirect_url, 302)
except IOError as e:
logger.debug(str(e))
status = None
layer_size = 0
if not store.exists(path):
raise exceptions.FileNotFoundError("Image layer absent from store")
try:
layer_size = store.get_size(path)
except exceptions.FileNotFoundError:
# XXX why would that fail given we know the layer exists?
pass
if bytes_range and bytes_range[1] == -1 and not layer_size == 0:
bytes_range = (bytes_range[0], layer_size)
if bytes_range:
content_length = bytes_range[1] - bytes_range[0] + 1
if not _valid_bytes_range(bytes_range):
return flask.Response(status=416, headers=headers)
status = 206
content_range = (bytes_range[0], bytes_range[1], layer_size)
headers['Content-Range'] = '{0}-{1}/{2}'.format(*content_range)
headers['Content-Length'] = content_length
elif layer_size > 0:
headers['Content-Length'] = layer_size
else:
return flask.Response(status=416, headers=headers)
return flask.Response(store.stream_read(path, bytes_range),
headers=headers, status=status)
def _get_image_json(image_id, headers=None):
if headers is None:
headers = {}
data = store.get_content(store.image_json_path(image_id))
try:
size = store.get_size(store.image_layer_path(image_id))
headers['X-Docker-Size'] = str(size)
except exceptions.FileNotFoundError:
pass
try:
csums = load_checksums(image_id)
headers['X-Docker-Payload-Checksum'] = csums
except exceptions.FileNotFoundError:
pass
return toolkit.response(data, headers=headers, raw=True)
def _parse_bytes_range():
headers = flask.request.headers
range_header = headers.get('range')
if not range_header:
return
log_msg = ('_parse_bytes_range: Malformed bytes range request header: '
'{0}'.format(range_header))
if not range_header.startswith('bytes='):
logger.debug(log_msg)
return
bytes_range = range_header[6:].split('-')
if len(bytes_range) != 2 and not range_header[-1] == '-':
logger.debug(log_msg)
return
if len(bytes_range) == 1 or bytes_range[1] == '':
bytes_range = (bytes_range[0], -1)
try:
return (int(bytes_range[0]), -1)
except ValueError:
logger.debug(log_msg)
try:
return (int(bytes_range[0]), int(bytes_range[1]))
except ValueError:
logger.debug(log_msg)
def _valid_bytes_range(bytes_range):
length = bytes_range[1] - bytes_range[0] + 1
if bytes_range[0] < 0 or bytes_range[1] < 1:
return False
if length < 2:
return False
return True
@app.route('/v1/private_images/<image_id>/layer', methods=['GET'])
@toolkit.requires_auth
@require_completion
def get_private_image_layer(image_id):
try:
headers = None
bytes_range = None
if store.supports_bytes_range:
headers['Accept-Ranges'] = 'bytes'
bytes_range = _parse_bytes_range()
repository = toolkit.get_repository()
if not repository:
# No auth token found, either standalone registry or privileged
# access. In both cases, private images are "disabled"
return toolkit.api_error('Image not found', 404)
if not store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
return _get_image_layer(image_id, headers, bytes_range)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
@app.route('/v1/images/<image_id>/layer', methods=['GET'])
@toolkit.requires_auth
@require_completion
@set_cache_headers
@mirroring.source_lookup(cache=True, stream=True)
def get_image_layer(image_id, headers):
try:
bytes_range = None
if store.supports_bytes_range:
headers['Accept-Ranges'] = 'bytes'
bytes_range = _parse_bytes_range()
repository = toolkit.get_repository()
if repository and store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
# If no auth token found, either standalone registry or privileged
# access. In both cases, access is always "public".
return _get_image_layer(image_id, headers, bytes_range)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
@app.route('/v1/images/<image_id>/layer', methods=['PUT'])
@toolkit.requires_auth
def put_image_layer(image_id):
try:
json_data = store.get_content(store.image_json_path(image_id))
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
layer_path = store.image_layer_path(image_id)
mark_path = store.image_mark_path(image_id)
if store.exists(layer_path) and not store.exists(mark_path):
return toolkit.api_error('Image already exists', 409)
input_stream = flask.request.stream
if flask.request.headers.get('transfer-encoding') == 'chunked':
# Careful, might work only with WSGI servers supporting chunked
# encoding (Gunicorn)
input_stream = flask.request.environ['wsgi.input']
# compute checksums
csums = []
sr = toolkit.SocketReader(input_stream)
if toolkit.DockerVersion() < '0.10':
tmp, store_hndlr = storage.temp_store_handler()
sr.add_handler(store_hndlr)
h, sum_hndlr = checksums.simple_checksum_handler(json_data)
sr.add_handler(sum_hndlr)
store.stream_write(layer_path, sr)
csums.append('sha256:{0}'.format(h.hexdigest()))
if toolkit.DockerVersion() < '0.10':
# NOTE(samalba): After docker 0.10, the tarsum is not used to ensure
# the image has been transfered correctly.
logger.debug('put_image_layer: Tarsum is enabled')
tar = None
tarsum = checksums.TarSum(json_data)
try:
tmp.seek(0)
tar = tarfile.open(mode='r|*', fileobj=tmp)
tarfilesinfo = layers.TarFilesInfo()
for member in tar:
tarsum.append(member, tar)
tarfilesinfo.append(member)
layers.set_image_files_cache(image_id, tarfilesinfo.json())
except (IOError, tarfile.TarError) as e:
logger.debug('put_image_layer: Error when reading Tar stream '
'tarsum. Disabling TarSum, TarFilesInfo. '
'Error: {0}'.format(e))
finally:
if tar:
tar.close()
# All data have been consumed from the tempfile
csums.append(tarsum.compute())
tmp.close()
# We store the computed checksums for a later check
save_checksums(image_id, csums)
return toolkit.response()
@app.route('/v1/images/<image_id>/checksum', methods=['PUT'])
@toolkit.requires_auth
def put_image_checksum(image_id):
if toolkit.DockerVersion() < '0.10':
checksum = flask.request.headers.get('X-Docker-Checksum')
else:
checksum = flask.request.headers.get('X-Docker-Checksum-Payload')
if not checksum:
return toolkit.api_error('Missing Image\'s checksum')
if not store.exists(store.image_json_path(image_id)):
return toolkit.api_error('Image not found', 404)
mark_path = store.image_mark_path(image_id)
if not store.exists(mark_path):
return toolkit.api_error('Cannot set this image checksum', 409)
checksums = load_checksums(image_id)
if checksum not in checksums:
logger.debug('put_image_checksum: Wrong checksum. '
'Provided: {0}; Expected: {1}'.format(
checksum, checksums))
return toolkit.api_error('Checksum mismatch')
# Checksum is ok, we remove the marker
store.remove(mark_path)
# We trigger a task on the diff worker if it's running
layers.enqueue_diff(image_id)
return toolkit.response()
@app.route('/v1/private_images/<image_id>/json', methods=['GET'])
@toolkit.requires_auth
@require_completion
def get_private_image_json(image_id):
repository = toolkit.get_repository()
if not repository:
# No auth token found, either standalone registry or privileged access
# In both cases, private images are "disabled"
return toolkit.api_error('Image not found', 404)
try:
if not store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
return _get_image_json(image_id)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
@app.route('/v1/images/<image_id>/json', methods=['GET'])
@toolkit.requires_auth
@require_completion
@set_cache_headers
@mirroring.source_lookup(cache=True, stream=False)
def get_image_json(image_id, headers):
try:
repository = toolkit.get_repository()
if repository and store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
# If no auth token found, either standalone registry or privileged
# access. In both cases, access is always "public".
return _get_image_json(image_id, headers)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
@app.route('/v1/images/<image_id>/ancestry', methods=['GET'])
@toolkit.requires_auth
@require_completion
@set_cache_headers
@mirroring.source_lookup(cache=True, stream=False)
def get_image_ancestry(image_id, headers):
ancestry_path = store.image_ancestry_path(image_id)
try:
# Note(dmp): unicode patch
data = store.get_json(ancestry_path)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
return toolkit.response(data, headers=headers)
def check_images_list(image_id):
if cfg.disable_token_auth is True or cfg.standalone is True:
# We enforce the check only when auth is enabled so we have a token.
return True
repository = toolkit.get_repository()
try:
path = store.images_list_path(*repository)
# Note(dmp): unicode patch
images_list = store.get_json(path)
except exceptions.FileNotFoundError:
return False
return (image_id in images_list)
def save_checksums(image_id, checksums):
for checksum in checksums:
checksum_parts = checksum.split(':')
if len(checksum_parts) != 2:
return 'Invalid checksum format'
# We store the checksum
checksum_path = store.image_checksum_path(image_id)
store.put_content(checksum_path, json.dumps(checksums))
def load_checksums(image_id):
checksum_path = store.image_checksum_path(image_id)
data = store.get_content(checksum_path)
try:
# Note(dmp): unicode patch NOT applied here
return json.loads(data)
except ValueError:
# NOTE(sam): For backward compatibility only, existing data may not be
# a valid json but a simple string.
return [data]
@app.route('/v1/images/<image_id>/json', methods=['PUT'])
@toolkit.requires_auth
def put_image_json(image_id):
data = None
try:
# Note(dmp): unicode patch
data = json.loads(flask.request.data.decode('utf8'))
except ValueError:
pass
if not data or not isinstance(data, dict):
return toolkit.api_error('Invalid JSON')
if 'id' not in data:
return toolkit.api_error('Missing key `id\' in JSON')
if image_id != data['id']:
return toolkit.api_error('JSON data contains invalid id')
if check_images_list(image_id) is False:
return toolkit.api_error('This image does not belong to the '
'repository')
parent_id = data.get('parent')
if parent_id and not store.exists(store.image_json_path(data['parent'])):
return toolkit.api_error('Image depends on a non existing parent')
elif parent_id and not toolkit.validate_parent_access(parent_id):
return toolkit.api_error('Image depends on an unauthorized parent')
json_path = store.image_json_path(image_id)
mark_path = store.image_mark_path(image_id)
if store.exists(json_path) and not store.exists(mark_path):
return toolkit.api_error('Image already exists', 409)
# If we reach that point, it means that this is a new image or a retry
# on a failed push
store.put_content(mark_path, 'true')
# We cleanup any old checksum in case it's a retry after a fail
try:
store.remove(store.image_checksum_path(image_id))
except Exception:
pass
store.put_content(json_path, flask.request.data)
layers.generate_ancestry(image_id, parent_id)
return toolkit.response()
@app.route('/v1/private_images/<image_id>/files', methods=['GET'])
@toolkit.requires_auth
@require_completion
def get_private_image_files(image_id, headers):
repository = toolkit.get_repository()
if not repository:
# No auth token found, either standalone registry or privileged access
# In both cases, private images are "disabled"
return toolkit.api_error('Image not found', 404)
try:
if not store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
data = layers.get_image_files_json(image_id)
return toolkit.response(data, headers=headers, raw=True)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
except tarfile.TarError:
return toolkit.api_error('Layer format not supported', 400)
@app.route('/v1/images/<image_id>/files', methods=['GET'])
@toolkit.requires_auth
@require_completion
@set_cache_headers
def get_image_files(image_id, headers):
try:
repository = toolkit.get_repository()
if repository and store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
# If no auth token found, either standalone registry or privileged
# access. In both cases, access is always "public".
data = layers.get_image_files_json(image_id)
return toolkit.response(data, headers=headers, raw=True)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
except tarfile.TarError:
return toolkit.api_error('Layer format not supported', 400)
@app.route('/v1/images/<image_id>/diff', methods=['GET'])
@toolkit.requires_auth
@require_completion
@set_cache_headers
def get_image_diff(image_id, headers):
try:
if not cache.redis_conn:
return toolkit.api_error('Diff queue is disabled', 400)
repository = toolkit.get_repository()
if repository and store.is_private(*repository):
return toolkit.api_error('Image not found', 404)
# first try the cache
diff_json = layers.get_image_diff_cache(image_id)
# it the cache misses, request a diff from a worker
if not diff_json:
layers.diff_queue.push(image_id)
# empty response
diff_json = ""
return toolkit.response(diff_json, headers=headers, raw=True)
except exceptions.FileNotFoundError:
return toolkit.api_error('Image not found', 404)
except tarfile.TarError:
return toolkit.api_error('Layer format not supported', 400)