-
Notifications
You must be signed in to change notification settings - Fork 61
/
util.py
2017 lines (1626 loc) · 73.8 KB
/
util.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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright (c) 2015-2022 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from dataclasses import dataclass
import typing
import _hashlib
import hashlib
from datetime import datetime
from itertools import chain
import json
import io
import os
import re
import requests
from requests.exceptions import SSLError, HTTPError, RetryError
import tempfile
from typing import Any, Final, Iterator, Sequence, Dict, Union, List, BinaryIO, Tuple, Optional
import logging
import uuid
import yaml
import string
import signal
import tarfile
from collections import namedtuple
from copy import deepcopy
from base64 import b64decode
from pathlib import Path
from typing import Callable
from urllib.parse import urlparse
if typing.TYPE_CHECKING:
from atomic_reactor.inner import DockerBuildWorkflow, ImageBuildWorkflowData
import atomic_reactor.utils.retries
from atomic_reactor.constants import (DOCKERFILE_FILENAME, REPO_CONTAINER_CONFIG, TOOLS_USED,
IMAGE_TYPE_DOCKER_ARCHIVE, IMAGE_TYPE_OCI, IMAGE_TYPE_OCI_TAR,
MEDIA_TYPE_DOCKER_V2_SCHEMA1, MEDIA_TYPE_DOCKER_V2_SCHEMA2,
MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST, MEDIA_TYPE_OCI_V1,
MEDIA_TYPE_OCI_V1_INDEX,
PLUGIN_CHECK_AND_SET_PLATFORMS_KEY,
PLUGIN_KOJI_PARENT_KEY,
PARENT_IMAGE_BUILDS_KEY, PARENT_IMAGES_KOJI_BUILDS,
BASE_IMAGE_KOJI_BUILD, BASE_IMAGE_BUILD_ID_KEY,
PARENT_IMAGES_KEY, SCRATCH_FROM,
DOCKERIGNORE, DEFAULT_DOWNLOAD_BLOCK_SIZE,
REPO_CONTENT_SETS_CONFIG,
REPO_FETCH_ARTIFACTS_URL,
REPO_FETCH_ARTIFACTS_PNC,
USER_CONFIG_FILES, REPO_FETCH_ARTIFACTS_KOJI)
from atomic_reactor.auth import HTTPRegistryAuth
from atomic_reactor.types import ISerializer, ImageInspectionData
from importlib import import_module
from requests.utils import guess_json_utf
from osbs.api import OSBS
from osbs.exceptions import OsbsException
from osbs.utils import Labels, ImageName
from osbs.utils import yaml as osbs_yaml
from tempfile import NamedTemporaryFile
from faulthandler import dump_traceback
@dataclass
class Output:
filename: str
metadata: Dict[str, Any]
logger = logging.getLogger(__name__)
# Should be a member of 'util' module for backwards compatibility
get_retrying_requests_session = atomic_reactor.utils.retries.get_retrying_requests_session
def figure_out_build_file(absolute_path, local_path=None):
"""
try to figure out the build file (Dockerfile or just a container.yaml) from provided
path and optionally from relative local path this is meant to be used with
git repo: absolute_path is path to git repo, local_path is path to dockerfile
within git repo
:param absolute_path:
:param local_path:
:return: tuple, (dockerfile_path, dir_with_dockerfile_path)
"""
logger.info("searching for dockerfile in '%s' (local path %s)", absolute_path, local_path)
logger.debug("abs path = '%s', local path = '%s'", absolute_path, local_path)
if local_path:
if local_path.endswith(DOCKERFILE_FILENAME) or local_path.endswith(REPO_CONTAINER_CONFIG):
git_build_file_dir = os.path.dirname(local_path)
build_file_dir = os.path.abspath(os.path.join(absolute_path, git_build_file_dir))
else:
build_file_dir = os.path.abspath(os.path.join(absolute_path, local_path))
else:
build_file_dir = os.path.abspath(absolute_path)
if not os.path.isdir(build_file_dir):
raise IOError("Directory '%s' doesn't exist." % build_file_dir)
build_file_path = os.path.join(build_file_dir, DOCKERFILE_FILENAME)
if os.path.isfile(build_file_path):
logger.debug("Dockerfile found: '%s'", build_file_path)
return build_file_path, build_file_dir
build_file_path = os.path.join(build_file_dir, REPO_CONTAINER_CONFIG)
if os.path.isfile(build_file_path):
logger.debug("container.yaml found: '%s'", build_file_path)
# Without this check, there would be a confusing 'Dockerfile has not yet been generated'
# exception later.
with open(build_file_path) as f:
data = yaml.safe_load(f)
if data is None or 'flatpak' not in data:
raise RuntimeError("container.yaml found, but no accompanying Dockerfile")
return build_file_path, build_file_dir
raise IOError("Dockerfile '%s' doesn't exist." % os.path.join(build_file_dir,
DOCKERFILE_FILENAME))
class CommandResult(object):
def __init__(self):
self._logs = []
self._parsed_logs = []
self._error = None
self._error_detail = None
def parse_item(self, item):
"""
:param item: dict, decoded log data
"""
# append here just in case .get bellow fails
self._parsed_logs.append(item)
# make sure the log item is a dictionary object
if isinstance(item, dict):
lines = item.get("stream", "")
else:
lines = item
item = None
for line in lines.splitlines():
line = line.strip()
self._logs.append(line)
if line:
logger.debug(line)
if item is not None:
self._error = item.get("error", None)
self._error_detail = item.get("errorDetail", None)
if self._error:
logger.error(item)
@property
def parsed_logs(self):
return self._parsed_logs
@property
def logs(self):
return self._logs
@property
def error(self):
return self._error
@property
def error_detail(self):
return self._error_detail
def is_failed(self):
return bool(self.error) or bool(self.error_detail)
def wait_for_command(logs_generator):
"""
Create a CommandResult from given iterator
:return: CommandResult
"""
logger.info("wait_for_command")
cr = CommandResult()
for item in logs_generator:
cr.parse_item(item)
logger.info("no more logs")
return cr
def escape_dollar(v):
try:
str_type = unicode
except NameError:
str_type = str
if isinstance(v, str_type):
return v.replace('$', r'\$')
else:
return v
def render_yum_repo(repo, escape_dollars=True):
repo.setdefault("name", str(uuid.uuid4().hex[:6]))
repo_name = repo["name"]
logger.info("rendering repo '%s'", repo_name)
rendered_repo = '[%s]\n' % repo_name
for key, value in repo.items():
if escape_dollars:
value = escape_dollar(value)
rendered_repo += "%s=%s\n" % (key, value)
logger.info("rendered repo: %r", rendered_repo)
return rendered_repo
def process_substitutions(mapping, substitutions):
"""Process `substitutions` for given `mapping` (modified in place)
:param mapping: a dict
:param substitutions: either a dict {key: value} or a list of ["key=value"] strings
keys can use dotted notation to change to nested dicts
Note: Plugin substitutions are processed differently - they are accepted in form of
plugin_type.plugin_name.arg_name, even though that doesn't reflect the actual
structure of given mapping.
Also note: For non-plugin substitutions, additional dicts/key/value pairs
are created on the way if they're missing. For plugin substitutions, only
existing values can be changed.
"""
def parse_val(v):
if v.lower() == 'true':
return True
elif v.lower() == 'false':
return False
elif v.lower() == 'none':
return None
return v
if isinstance(substitutions, list):
# if we got a list, get a {key: val} dict out of it
substitutions = dict([s.split('=', 1) for s in substitutions])
for key, val in substitutions.items():
cur_dict = mapping
key_parts = key.split('.')
if key_parts[0].endswith('_plugins'):
_process_plugin_substitution(mapping, key_parts, val)
else:
key_parts_without_last = key_parts[:-1]
# now go down mapping, following the dotted path; create empty dicts on way
for k in key_parts_without_last:
if k in cur_dict:
if not isinstance(cur_dict[k], dict):
cur_dict[k] = {}
else:
cur_dict[k] = {}
cur_dict = cur_dict[k]
cur_dict[key_parts[-1]] = parse_val(val)
def _process_plugin_substitution(mapping, key_parts, value):
try:
plugin_type, plugin_name, arg_name = key_parts
except ValueError as exc:
logger.error("invalid absolute path '%s': it requires exactly three parts: "
"plugin type, plugin name, argument name (dot separated)",
key_parts)
raise ValueError(
"invalid absolute path to plugin, "
"it should be plugin_type.plugin_name.argument_name"
) from exc
logger.debug("getting plugin conf for '%s' with type '%s'",
plugin_name, plugin_type)
plugins_of_a_type = mapping.get(plugin_type, None)
if plugins_of_a_type is None:
logger.warning("there are no plugins with type '%s'",
plugin_type)
return
plugin_conf = [x for x in plugins_of_a_type if x['name'] == plugin_name]
plugins_num = len(plugin_conf)
if plugins_num == 1:
if arg_name not in plugin_conf[0]['args']:
logger.warning("no configuration value '%s' for plugin '%s', skipping",
arg_name, plugin_name)
return
logger.info("changing value '%s' of plugin '%s': '%s' -> '%s'",
arg_name, plugin_name, plugin_conf[0]['args'][arg_name], value)
plugin_conf[0]['args'][arg_name] = value
elif plugins_num <= 0:
logger.warning("there is no configuration for plugin '%s', skipping substitution",
plugin_name)
else:
logger.error("there is no configuration for plugin '%s'",
plugin_name)
raise RuntimeError("plugin '%s' was specified multiple (%d) times, can't pick one" %
(plugin_name, plugins_num))
def _compute_checksums(
fd: BinaryIO, hash_objs: List[_hashlib.HASH], blocksize: int = 65536
) -> None:
"""
Compute file checksums in given hash objects.
:param fd: file-like object
:param hash_objs: list, hashlib hash objects for each algorithm to be calculated
:param blocksize: block size used to read fd
"""
buf = fd.read(blocksize)
while len(buf) > 0:
for hash_object in hash_objs:
hash_object.update(buf)
buf = fd.read(blocksize)
def get_checksums(filename: Union[str, BinaryIO], algorithms: List[str]) -> Dict[str, str]:
"""
Compute a checksum(s) of given file using specified algorithms.
:param filename: path to file or file-like object
:param algorithms: list of cryptographic hash functions, currently supported: md5, sha256
:return: dictionary
"""
if not algorithms:
return {}
allowed_algorithms = ['md5', 'sha256']
if not all(elem in allowed_algorithms for elem in algorithms):
raise ValueError('Algorithms supported {}. Found {}'.format(allowed_algorithms, algorithms))
hash_objs = [getattr(hashlib, algorithm)() for algorithm in algorithms]
if isinstance(filename, str):
with open(filename, mode='rb') as f:
_compute_checksums(f, hash_objs)
else:
_compute_checksums(filename, hash_objs)
checksums = {}
for hash_obj in hash_objs:
sum_name = '{}sum'.format(hash_obj.name)
checksums[sum_name] = hash_obj.hexdigest()
logger.debug('%s: %s', sum_name, checksums[sum_name])
return checksums
def get_exported_image_metadata(path, image_type) -> Dict[str, Union[str, int]]:
logger.info('getting metadata for exported image %s (%s)', path, image_type)
metadata = {'path': path, 'type': image_type}
if image_type != IMAGE_TYPE_OCI:
metadata['size'] = os.path.getsize(path)
logger.debug('size: %d bytes', metadata['size'])
metadata.update(get_checksums(path, ['md5', 'sha256']))
return metadata
def get_image_upload_filename(image_type, image_id, platform):
if image_type == IMAGE_TYPE_DOCKER_ARCHIVE:
base_name = 'docker-image'
elif image_type == IMAGE_TYPE_OCI_TAR:
base_name = 'oci-image'
else:
raise ValueError("Unhandled image type for upload: {}".format(image_type))
ext = 'tar.gz'
name_fmt = '{base_name}-{id}.{platform}.{ext}'
return name_fmt.format(base_name=base_name, id=image_id,
platform=platform, ext=ext)
def get_pipeline_run_start_time(osbs: OSBS, pipeline_run_name: str) -> datetime:
build_info = osbs.get_build(pipeline_run_name)
start_time_str = build_info['status']['startTime']
start_time = datetime.strptime(start_time_str, '%Y-%m-%dT%H:%M:%SZ')
return start_time
def get_version_of_tools():
"""
get versions of tools reactor is using (specified in constants.TOOLS_USED)
:returns list of dicts, [{"name": "docker-py", "version": "1.2.3"}, ...]
"""
response = []
for tool in TOOLS_USED:
pkg_name = tool["pkg_name"]
try:
tool_module = import_module(pkg_name)
except ImportError as ex:
logger.warning("can't import module %s: %s", pkg_name, ex)
else:
version = getattr(tool_module, "__version__", None)
if version is None:
logger.warning("tool %s doesn't have __version__", pkg_name)
else:
response.append({
"name": tool.get("display_name", pkg_name),
"version": version,
"path": tool_module.__file__,
})
return response
def print_version_of_tools():
"""
print versions of used tools to logger
"""
logger.info("Using these tools:")
for tool in get_version_of_tools():
logger.info("%s-%s at %s", tool["name"], tool["version"], tool["path"])
def is_scratch_build(workflow):
return workflow.user_params.get('scratch', False)
def is_isolated_build(workflow):
return workflow.user_params.get('isolated', False)
def is_flatpak_build(workflow):
return workflow.user_params.get('flatpak', False)
def base_image_is_scratch(base_image_name):
return SCRATCH_FROM == base_image_name
def base_image_is_custom(base_image_name: str) -> bool:
return bool(re.match('^koji/image-build(:.*)?$', base_image_name))
def get_platforms(workflow_data: "ImageBuildWorkflowData") -> List[str]:
koji_platforms = workflow_data.plugins_results.get(PLUGIN_CHECK_AND_SET_PLATFORMS_KEY)
if koji_platforms:
return koji_platforms
return []
# copypasted and slightly modified from
# http://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size/1094933#1094933
def human_size(num, suffix='B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.2f %s%s" % (num, unit, suffix)
num /= 1024.0
return "%.2f %s%s" % (num, 'Yi', suffix)
def registry_hostname(registry):
"""
Strip a reference to a registry to just the hostname:port
"""
if registry.startswith('http:') or registry.startswith('https:'):
return urlparse(registry).netloc
else:
return registry
class Dockercfg(object):
def __init__(self, secret_path):
"""
Create a new Dockercfg object from a .dockercfg/.dockerconfigjson file whose
containing directory is secret_path.
:param secret_path: str, dirname of .dockercfg/.dockerconfigjson location
"""
if os.path.exists(os.path.join(secret_path, '.dockercfg')):
self.json_secret_path = os.path.join(secret_path, '.dockercfg')
elif os.path.exists(os.path.join(secret_path, '.dockerconfigjson')):
self.json_secret_path = os.path.join(secret_path, '.dockerconfigjson')
elif os.path.exists(secret_path):
self.json_secret_path = secret_path
else:
raise RuntimeError("The registry secret was not found on the filesystem, "
"either .dockercfg or .dockerconfigjson are supported")
try:
with open(self.json_secret_path) as fp:
self.json_secret = json.load(fp)
# If the auths key exist then we have a dockerconfigjson secret.
if 'auths' in self.json_secret:
self.json_secret = self.json_secret.get('auths')
except Exception as exc:
msg = "failed to read registry secret"
logger.error(msg, exc_info=True)
raise RuntimeError(msg) from exc
def get_credentials(self, registry):
# For maximal robustness we check the host:port of the passed in
# registry against the host:port of the items in the secret. This is
# somewhat similar to what the Docker CLI does.
#
registry = registry_hostname(registry)
try:
return self.json_secret[registry]
except KeyError:
for reg, creds in self.json_secret.items():
if registry_hostname(reg) == registry:
return creds
logger.warning('%s not found in .dockercfg', registry)
return {}
def unpack_auth_b64(self, docker_registry):
"""Decode and unpack base64 'auth' credentials from config file.
:param docker_registry: str, registry reference in config file
:return: namedtuple, UnpackedAuth (or None if no 'auth' is available)
"""
UnpackedAuth = namedtuple('UnpackedAuth', ['raw_str', 'username', 'password'])
credentials = self.get_credentials(docker_registry)
auth_b64 = credentials.get('auth')
if auth_b64:
raw_str = b64decode(auth_b64).decode('utf-8')
unpacked_credentials = raw_str.split(':', 1)
if len(unpacked_credentials) == 2:
return UnpackedAuth(raw_str, *unpacked_credentials)
else:
raise ValueError("Failed to parse 'auth' in '%s'" % self.json_secret_path)
class RegistrySession(object):
def __init__(self, registry, insecure=False, dockercfg_path=None, access=None):
self.registry = registry
self._resolved = None
self.insecure = insecure
self.dockercfg_path = dockercfg_path
username = None
password = None
auth_b64 = None
if dockercfg_path:
dockercfg = Dockercfg(dockercfg_path).get_credentials(registry)
username = dockercfg.get('username')
password = dockercfg.get('password')
auth_b64 = dockercfg.get('auth')
self.auth = HTTPRegistryAuth(username, password, access=access, auth_b64=auth_b64)
self._fallback = None
if re.match('http(s)?://', self.registry):
self._base = self.registry
else:
self._base = 'https://{}'.format(self.registry)
if insecure:
# In the insecure case, if the registry is just a hostname:port, we
# don't know whether to talk HTTPS or HTTP to it, so we try first
# with https then fallback
self._fallback = 'http://{}'.format(self.registry)
self.session = get_retrying_requests_session()
@classmethod
def create_from_config(cls, config, registry=None, access=None):
"""
Create a session for the specified registry based on configuration in reactor config map.
If the registry is configured in source_registry or pull_registries,
use that configuration. Otherwise an error is thrown.
:param config: Configuration, contains configuration for registries
:param registry: str, registry to create session for (as hostname[:port], no http(s))
If not specified, the default source_registry will be used
:param access: List of actions this session is allowed to perform, e.g. ('push', 'pull')
:return: RegistrySession for the specified registry
"""
try:
source_registry = config.source_registry
except KeyError:
source_registry = None
pull_registries = config.pull_registries
if source_registry:
pull_registries.append(source_registry)
if registry is None:
if source_registry is not None:
matched_registry = source_registry
else:
msg = "No source_registry configured, cannot create default session"
raise RuntimeError(msg)
else:
# Try to match a registry in pull_registries and source_registry
match_registry = [reg for reg in pull_registries if reg['uri'].docker_uri == registry]
matched_registry = match_registry[0] if match_registry else None
if matched_registry is None:
msg = ('{}: No match in pull_registries or source_registry'
.format(registry))
raise RuntimeError(msg)
return cls(matched_registry['uri'].uri,
insecure=matched_registry['insecure'],
dockercfg_path=matched_registry['dockercfg_path'],
access=access)
def _do(self, f, relative_url, *args, **kwargs):
kwargs['auth'] = self.auth
kwargs['verify'] = not self.insecure
if self._fallback:
try:
res = f(self._base + relative_url, *args, **kwargs)
self._fallback = None # don't fallback after one success
return res
except (SSLError, requests.ConnectionError):
self._base = self._fallback
self._fallback = None
return f(self._base + relative_url, *args, **kwargs)
def get(self, relative_url, data=None, **kwargs):
return self._do(self.session.get, relative_url, **kwargs)
def head(self, relative_url, data=None, **kwargs):
return self._do(self.session.head, relative_url, **kwargs)
def post(self, relative_url, data=None, **kwargs):
return self._do(self.session.post, relative_url, data=data, **kwargs)
def put(self, relative_url, data=None, **kwargs):
return self._do(self.session.put, relative_url, data=data, **kwargs)
def delete(self, relative_url, **kwargs):
return self._do(self.session.delete, relative_url, **kwargs)
class RegistryClient(object):
"""
Registry client, provides methods for looking up image digests and configs
in container registries.
Methods that accept the `image` parameter expect that the registry of the
image matches the one of the client instance, but they do not check whether
that is true.
To create a client for a specific registry (configured in config map), use
>>> session = RegistrySession.create_from_config(...)
>>> client = RegistryClient(session)
"""
def __init__(self, registry_session):
self._session = registry_session
@property
def insecure(self):
return self._session.insecure
@property
def dockercfg_path(self):
return self._session.dockercfg_path
def get_manifest(
self, image: ImageName, version: str
) -> Tuple[Optional[requests.Response], Optional[Exception]]:
saved_not_found = None
media_type = get_manifest_media_type(version)
try:
response = query_registry(self._session, image, digest=None, version=version)
except (HTTPError, RetryError) as ex:
if ex.response is None:
raise
if ex.response.status_code == requests.codes.unauthorized:
logger.warning('Requested parent/base image "%s" not found', image.to_str())
raise RuntimeError('Unable to fetch image: "{}"'
' (Does the image exist?)'.format(image.to_str())) from ex
if ex.response.status_code == requests.codes.not_found:
saved_not_found = ex
# If the registry has a v2 manifest that can't be converted into a v1
# manifest, the registry fails with status=400 (BAD_REQUEST), and an error code of
# MANIFEST_INVALID. Note that if the registry has v2 manifest and
# you ask for an OCI manifest, the registry will try to convert the
# v2 manifest into a v1 manifest as the default type, so the same
# thing occurs.
if version != 'v2' and ex.response.status_code == requests.codes.bad_request:
logger.warning('Unable to fetch digest for %s, got error %s',
media_type, ex.response.status_code)
return None, saved_not_found
# Returned if the manifest could not be retrieved for the given
# media type
elif (ex.response.status_code == requests.codes.not_found or
ex.response.status_code == requests.codes.not_acceptable):
logger.debug("skipping version %s due to status code %s",
version, ex.response.status_code)
return None, saved_not_found
else:
raise
if not manifest_is_media_type(response, media_type):
logger.warning("content does not match expected media type")
return None, saved_not_found
logger.debug("content matches expected media type")
return response, saved_not_found
def get_manifest_digests(self,
image,
versions=('v1', 'v2', 'v2_list', 'oci', 'oci_index'),
require_digest=True):
"""Return manifest digest for image.
:param image: ImageName, the remote image to inspect
:param versions: tuple, which manifest schema versions to fetch digest
:param require_digest: bool, when True exception is thrown if no digest is
set in the headers.
:return: dict, versions mapped to their digest
"""
digests = {}
# If all of the media types return a 404 NOT_FOUND status, then we rethrow
# an exception, if all of the media types fail for some other reason - like
# bad headers - then we return a ManifestDigest object with no digests.
# This is interesting for the Pulp "retry until the manifest shows up" case.
all_not_found = True
saved_not_found = None
for version in versions:
media_type = get_manifest_media_type(version)
response, saved_not_found = self.get_manifest(image, version)
if saved_not_found is None:
all_not_found = False
if not response:
continue
# set it to truthy value so that koji_import would know pulp supports these digests
digests[version] = True
if not response.headers.get('Docker-Content-Digest'):
logger.warning('Unable to fetch digest for %s, no Docker-Content-Digest header',
media_type)
continue
digests[version] = response.headers['Docker-Content-Digest']
context = '/'.join([x for x in [image.namespace, image.repo] if x])
tag = image.tag
logger.debug('Image %s:%s has %s manifest digest: %s',
context, tag, version, digests[version])
if not digests:
if all_not_found and len(versions) > 0:
raise saved_not_found # pylint: disable=raising-bad-type
if require_digest:
raise RuntimeError('No digests found for {}'.format(image))
return ManifestDigest(**digests)
def get_manifest_list(self, image: ImageName) -> Optional[requests.Response]:
"""Return manifest list for image.
:param image: ImageName, the remote image to inspect
:return: response, or None, with manifest list
"""
version = 'v2_list'
response, _ = self.get_manifest(image, version)
return response
def get_manifest_index(self, image: ImageName) -> Optional[requests.Response]:
"""Return manifest index for image.
:param image: ImageName, the remote image to inspect
:return: response, or None, with manifest list
"""
version = 'oci_index'
response, _ = self.get_manifest(image, version)
return response
def get_manifest_list_digest(self, image):
"""Return manifest list digest for image
:param image:
:return:
"""
response = self.get_manifest_list(image)
if response is None:
raise RuntimeError('Unable to fetch v2.manifest_list for {}'.format(image.to_str()))
digest_dict = get_checksums(io.BytesIO(response.content), ['sha256'])
return 'sha256:{}'.format(digest_dict['sha256sum'])
def get_all_manifests(
self, image: ImageName, versions: Sequence[str] = ('v1', 'v2', 'v2_list', 'oci_index')
) -> Dict[str, requests.Response]:
"""Return manifest digests for image.
:param image: ImageName, the remote image to inspect
:param versions: tuple, for which manifest schema versions to fetch manifests
:return: dict of successful responses, with versions as keys
"""
digests = {}
for version in versions:
response, _ = self.get_manifest(image, version)
if response:
digests[version] = response
return digests
def get_inspect_for_image(
self, image: ImageName, arch: Optional[str] = None
) -> ImageInspectionData:
"""Return inspect for image.
:param image: The remote image to inspect
:param arch: The architecture of the image to inspect. If not specified, will inspect any
architecture. If an architecture *is* specified and cannot be inspected (e.g. no such
arch in the manifest list, or the image is not a list and doesn't have the right
architecture), the method will fail. Uses GOARCH names (e.g. amd64, not x86_64).
:return: dict of inspected image
"""
all_man_digests = self.get_all_manifests(image)
config_digest: Optional[str]
# we have manifest list
if 'v2_list' in all_man_digests:
manifest_list = all_man_digests['v2_list'].json()
blob_config, config_digest = self._config_and_id_from_manifest_list(
image, manifest_list, arch
)
elif 'oci_index' in all_man_digests:
manifest_list = all_man_digests['oci_index'].json()
blob_config, config_digest = self._config_and_id_from_manifest_list(
image, manifest_list, arch
)
# get config for v2 digest
elif 'v2' in all_man_digests:
v2_json = all_man_digests['v2'].json()
config_digest = v2_json['config']['digest']
assert isinstance(config_digest, str)
blob_config = self._blob_config_by_digest(image, config_digest)
# read config from v1
elif 'v1' in all_man_digests:
v1_json = all_man_digests['v1'].json()
config_digest = None # no way to get useful config digest for v1 images
blob_config = json.loads(v1_json['history'][0]['v1Compatibility'])
else:
raise RuntimeError("Image {image_name} not found: No v2 schema 1 image, "
"or v2 schema 2 image or list, found".format(image_name=image))
if not blob_config:
raise RuntimeError(f"Image {image}: Couldn't get inspect data from digest config")
if arch and blob_config['architecture'] != arch:
raise RuntimeError(
f"Image {image}: Has architecture {blob_config['architecture']}, "
f"which does not match specified architecture {arch}"
)
image_inspect: ImageInspectionData = {
# set Id, which isn't in config blob
# Won't be set for v1,as for that image has to be pulled
'Id': config_digest,
'Architecture': blob_config['architecture'],
'Os': blob_config['os'],
# According to OCI spec, 'created' and 'config' are optional
'Created': blob_config.get('created'),
'Config': blob_config.get('config') or {},
}
# only v2 has rootfs, not v1
if rootfs := blob_config.get('rootfs'):
image_inspect['RootFS'] = {'Type': rootfs['type'], 'Layers': rootfs['diff_ids']}
return image_inspect
def _blob_config_by_digest(self, image: ImageName, config_digest: str) -> dict:
config_response = query_registry(self._session, image, digest=config_digest, is_blob=True)
blob_config = config_response.json()
return blob_config
def _config_and_id_from_manifest_list(
self, image: ImageName, manifest_list: dict, arch: Optional[str]
) -> Tuple[dict, str]:
"""Get the config blob and image ID from the manifest list.
If no architecture is specified, inspect the first image in the list. Otherwise, check
that the list has exactly one image matching the specified architecture and inspect that
image.
"""
manifests = manifest_list["manifests"]
if not manifests:
logger.error("Empty manifest list: %r", manifest_list)
raise RuntimeError(f"Image {image}: Manifest list is empty")
if not arch:
manifest = manifests[0]
else:
arch_manifests = [
m for m in manifests if m.get("platform", {}).get("architecture") == arch
]
if len(arch_manifests) != 1:
logger.error(
"Expected one %s manifest in manifest list, got %r", arch, arch_manifests
)
raise RuntimeError(
f"Image {image}: Expected exactly one manifest for {arch} architecture in "
f"manifest list, got {len(arch_manifests)}"
)
manifest = arch_manifests[0]
if (manifest["mediaType"] != MEDIA_TYPE_DOCKER_V2_SCHEMA2 and
manifest["mediaType"] != MEDIA_TYPE_OCI_V1):
raise RuntimeError(f"Image {image}: v2 schema 1 in manifest list, "
f"oci in image index is missing")
image_digest = manifest["digest"]
if manifest["mediaType"] == MEDIA_TYPE_DOCKER_V2_SCHEMA2:
return self.get_config_and_id_from_registry(image, image_digest, version='v2')
else:
return self.get_config_and_id_from_registry(image, image_digest, version='oci')
def get_config_and_id_from_registry(self, image, digest: str, version='v2') -> Tuple[Dict, str]:
"""Return image config by digest
:param image: ImageName, the remote image to inspect
:param digest: str, digest of the image manifest
:param version: str, which manifest schema versions to fetch digest
:return: dict, versions mapped to their digest
"""
response = query_registry(self._session, image, digest=digest, version=version)
manifest_config = response.json()
config_digest = manifest_config['config']['digest']
blob_config = self._blob_config_by_digest(image, config_digest)
context = '/'.join([x for x in [image.namespace, image.repo] if x])
tag = image.tag
logger.debug('Image %s:%s has config:\n%s', context, tag, blob_config)
return blob_config, config_digest
def get_config_from_registry(self, image, digest, version='v2'):
"""Return image config by digest
:param image: ImageName, the remote image to inspect
:param digest: str, digest of the image manifest
:param version: str, which manifest schema versions to fetch digest
:return: dict, versions mapped to their digest
"""
blob_config, _ = self.get_config_and_id_from_registry(image, digest, version=version)
return blob_config
class ManifestDigest(dict):
"""Wrapper for digests for a docker manifest."""
NOT_SET: Final = None
content_type = {
'v1': MEDIA_TYPE_DOCKER_V2_SCHEMA1,
'v2': MEDIA_TYPE_DOCKER_V2_SCHEMA2,
'v2_list': MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST,
'oci': MEDIA_TYPE_OCI_V1,
'oci_index': MEDIA_TYPE_OCI_V1_INDEX,
}
@property
def default(self):
"""Return the default manifest schema version.
Depending on the docker version, <= 1.9, used to push
the image to the registry, v2 schema may not be available.
In such case, the v1 schema should be used when interacting
with the registry. An OCI digest will only be present when
the manifest was pushed as an OCI digest.
"""
return self.v2_list or self.oci_index or self.oci or self.v2 or self.v1
def __getattr__(self, attr):
if attr not in self.content_type:
raise AttributeError("Unknown version: %s" % attr)
else:
return self.get(attr, self.NOT_SET)
def is_manifest_list(version):
return version == MEDIA_TYPE_DOCKER_V2_MANIFEST_LIST or version == MEDIA_TYPE_OCI_V1_INDEX
def get_manifest_media_type(version: str) -> str:
try:
return ManifestDigest.content_type[version]
except KeyError as exc:
raise RuntimeError("Unknown manifest schema type") from exc
def get_manifest_media_version(digest):
found_version = None
for version in ManifestDigest.content_type:
if digest.default and getattr(digest, version) == digest.default: