Debian Codegraph @

src/buildstream_plugins/sources/docker.py

raw
1 #
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at
5 #
6 # http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13 #
14 # Authors:
15 # Sam Thursfield <[email protected]>
16 # Chandan Singh <[email protected]>
17
18 #
19 # This plugin was originally developped in the https://gitlab.com/BuildStream/bst-plugins-container/
20 # repository and was copied from 192aa75a62161b655b051d5b69f17d9233cf4dfe
21 #
22
23 """
24 docker - stage files from Docker/OCI images
25 ===========================================
26
27 **Usage:**
28
29 .. code:: yaml
30
31 # Specify the docker source kind
32 kind: docker
33
34 # Specify the registry endpoint, defaults to Docker Hub (optional)
35 registry-url: https://registry.hub.docker.com
36
37 # Image path
38 image: library/alpine
39
40 # Alternatively, you can specify a full url, the registry endpoint
41 # is assumed to be at the root of the domain
42 # url: https://registry.hub.docker.com/library/alpine
43
44 # Image tag to follow (optional)
45 track: latest
46
47 # Specify the digest of the exact image to use (required)
48 ref: 6c9f6f68a131ec6381da82f2bff978083ed7f4f7991d931bfa767b7965ebc94b
49
50 # Some images are built for multiple platforms. When tracking a tag, we
51 # will choose which image to use based on these settings. Default values
52 # are chosen based on the output of `uname -m` and `uname -s`, but you
53 # can override them.
54 #
55 # architecture: arm64
56 # os: linux
57 #
58 # **Since**: 2.0.1
59
60 # Specify the version to be reported as the *guess_version* when reporting
61 # SourceInfo
62 #
63 # Since: 2.5
64 #
65 version: 1.2
66
67 Note that Docker images may contain device nodes. BuildStream elements cannot
68 contain device nodes so those will be dropped. Any regular files in the /dev
69 directory will also be dropped.
70
71 See `built-in functionality doumentation
72 <https://docs.buildstream.build/master/buildstream.source.html#core-source-builtins>`_ for
73 details on common configuration options for sources.
74
75
76 Reporting `SourceInfo <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfo>`_
77 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
78 The docker source reports the URL of the docker registry as the *url*.
79
80 Further, the docker source reports the `SourceInfoMedium.OCI_IMAGE
81 <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceInfoMedium.OCI_IMAGE>`_
82 *medium* and the `SourceVersionType.OCI_DIGEST
83 <https://docs.buildstream.build/master/buildstream.source.html#buildstream.source.SourceVersionType.OCI_DIGEST>`_
84 *version_type*, for which it reports the content digest of the docker image as the *version*.
85
86 Additionally, the docker source reports the docker image name through
87 the ``image-name`` key of the *extra_data*.
88
89 As such, after removing the scheme from the URL (i.e. remove ``https://``) the same docker
90 image can be obtained by calling:
91
92 .. code:: bash
93
94 docker pull <url-without-scheme>/<image-name>@<version>
95
96 Since the docker source does not have any way to guess what tag is associated
97 to the digest, or what release version that would mean; the docker source exposes
98 the ``version`` configuration attribute to allow explicit specification of the
99 *guess_version*.
100 """
101
102 import hashlib
103 import json
104 import os
105 import platform
106 import shutil
107 import tarfile
108 import urllib.parse
109
110 from collections import OrderedDict
111
112 import requests
113
114 from buildstream import Source, SourceError
115 from buildstream.utils import (
116 save_file_atomic,
117 sha256sum,
118 link_files,
119 move_atomic,
120 get_umask,
121 )
122
123 #
124 # Soft import of buildstream symbols only available in newer versions
125 #
126 # The BST_MIN_VERSION will provide a better user experience.
127 #
128 try:
129 from buildstream import SourceInfoMedium, SourceVersionType
130 except ImportError:
131 pass
132
133 _DOCKER_HUB_URL = "https://registry.hub.docker.com"
134
135
136 def parse_bearer_authorization_challenge(text):
137 # Hand-written and probably broken parsing of the Www-Authenticate
138 # response. I can't find a built-in way to parse this, but I probably
139 # didn't look hard enough.
140 if not text.startswith("Bearer "):
141 raise SourceError("Unexpected Www-Authenticate response: %{}".format(text))
142
143 pairs = {}
144 text = text[len("Bearer ") :]
145 for pair in text.split(","):
146 key, value = pair.split("=")
147 pairs[key] = value[1:-1]
148 return pairs
149
150
151 def default_architecture():
152 machine = platform.machine()
153 if machine == "x86_64":
154 return "amd64"
155 elif machine == "aarch64":
156 return "arm64"
157 else:
158 return machine
159
160
161 def default_os():
162 return platform.system().lower()
163
164
165 # Variant of urllib.parse.urljoin() allowing multiple path components at once.
166 def urljoin(url, *args):
167 for arg in args:
168 if not url.endswith("/"):
169 url += "/"
170 url = urllib.parse.urljoin(url, arg.lstrip("/"))
171 return url
172
173
174 # Handles authentication with a bearer token
175 class BearerAuth(requests.auth.AuthBase):
176 def __init__(self, api_timeout=3):
177 self.token = None
178 self.api_timeout = api_timeout
179
180 def __call__(self, r):
181 if self.token:
182 r.headers["Authorization"] = "Bearer {}".format(self.token)
183 return r
184
185 def refresh_token(self, auth_challenge):
186 auth_vars = parse_bearer_authorization_challenge(auth_challenge)
187 # Respond to an Www-Authenticate challenge by requesting the necessary
188 # token from the 'realm' (endpoint) that we were given in the challenge.
189 request_url = "{realm}?service={service}&scope={scope}".format(**auth_vars)
190 response = requests.get(request_url, timeout=self.api_timeout)
191 response.raise_for_status()
192 self.token = response.json()["token"]
193
194
195 # DockerManifestError
196 #
197 # Raised if something goes wrong while querying an image manifest from a remote
198 # registry.
199 #
200 class DockerManifestError(SourceError):
201 def __init__(self, message, manifest=None):
202 super().__init__(message)
203 self.manifest = manifest
204
205
206 class DockerRegistryV2Client:
207 def __init__(self, endpoint, api_timeout=3):
208 self.endpoint = endpoint
209 self.api_timeout = api_timeout
210
211 self.auth = BearerAuth(api_timeout)
212
213 def _request(self, subpath, extra_headers=None, stream=False, _reauthorized=False):
214 if not extra_headers:
215 extra_headers = {}
216
217 headers = {"content-type": "application/json"}
218 headers.update(extra_headers)
219
220 url = urljoin(self.endpoint, "v2", subpath)
221 response = requests.get(url, headers=headers, stream=stream, timeout=self.api_timeout, auth=self.auth)
222
223 if response.status_code == requests.codes["unauthorized"] and not _reauthorized:
224 # This request requires (re)authorization. See:
225 # https://docs.docker.com/registry/spec/auth/token/
226 auth_challenge = response.headers["Www-Authenticate"]
227 self.auth.refresh_token(auth_challenge)
228 return self._request(subpath, extra_headers=extra_headers, _reauthorized=True)
229 else:
230 response.raise_for_status()
231
232 return response
233
234 # digest():
235 #
236 # Calculate a Docker-compatible digest of an arbitrary string of bytes.
237 #
238 # Args:
239 # content (bytes): Content to hash
240 #
241 # Returns:
242 # (str) A Docker-compatible digest of 'content'
243 @staticmethod
244 def digest(content):
245 digest_hash = hashlib.sha256()
246 digest_hash.update(content)
247 return "sha256:" + digest_hash.hexdigest()
248
249 # manifest():
250 #
251 # Fetches the image manifest for a given image from the remote registry.
252 #
253 # If this is a "fat" (multiplatform) image, the 'artitecture' and 'os'
254 # parameters control which of the available images is chosen.
255 #
256 # The manifest is returned verbatim, so you need to parse it yourself
257 # with json.loads() to get at its contents. The verbatim text can be used
258 # to recalculate the content digest, just encode it and pass to .digest().
259 # If we returned only the parsed JSON data you wouldn't be able to do this.
260 #
261 # Args:
262 # image_path (str): Relative path to the image, e.g. library/alpine
263 # reference (str): Either a tag name (such as 'latest') or the content
264 # digest of an exact version of the image.
265 # architecture (str): Architecture name (amd64, arm64, etc.)
266 # os_ (str): OS name (e.g. linux)
267 #
268 # Raises:
269 # requests.RequestException, if network errors occur
270 #
271 # Returns:
272 # (str, str): A tuple of the manifest content as text, and its content hash
273 def manifest(
274 self,
275 image_path,
276 reference,
277 architecture,
278 os_,
279 ):
280 # pylint: disable=too-many-locals
281
282 accept_types = [
283 "application/vnd.docker.distribution.manifest.v2+json",
284 "application/vnd.docker.distribution.manifest.list.v2+json",
285 "application/vnd.oci.image.index.v1+json",
286 "application/vnd.oci.image.manifest.v1+json",
287 ]
288
289 manifest_url = urljoin(image_path, "manifests", urllib.parse.quote(reference))
290 response = self._request(manifest_url, extra_headers={"Accept": ",".join(accept_types)})
291
292 try:
293 manifest = json.loads(response.text)
294 except json.JSONDecodeError as e:
295 raise DockerManifestError(
296 "Server did not return a valid manifest: {}".format(e),
297 manifest=response.text,
298 ) from e
299
300 schema_version = manifest.get("schemaVersion")
301 if schema_version == 1:
302 raise DockerManifestError("Schema version 1 is unsupported.", manifest=response.text)
303 if schema_version is None:
304 raise DockerManifestError(
305 "Manifest did not include the schemaVersion key.",
306 manifest=response.text,
307 )
308
309 our_digest = self.digest(response.text.encode("utf8"))
310 their_digest = response.headers.get("Docker-Content-Digest")
311
312 if not their_digest:
313 raise DockerManifestError(
314 "Server did not set the Docker-Content-Digest header.",
315 manifest=response.text,
316 )
317 if our_digest != their_digest:
318 raise DockerManifestError(
319 "Server returned a non-matching content digest. "
320 "Our digest: {}, their digest: {}".format(our_digest, their_digest),
321 manifest=response.text,
322 )
323
324 if manifest["mediaType"] in (
325 "application/vnd.docker.distribution.manifest.list.v2+json",
326 "application/vnd.oci.image.index.v1+json",
327 ):
328 # This is a "fat manifest", we need to narrow down to a specific
329 # architecture.
330 for sub in manifest["manifests"]:
331 if sub["platform"]["architecture"] == architecture and sub["platform"]["os"]:
332 sub_digest = sub["digest"]
333 return self.manifest(
334 image_path,
335 sub_digest,
336 architecture=architecture,
337 os_=os_,
338 )
339 raise DockerManifestError(
340 "No images found for architecture {}, OS {}".format(architecture, os_),
341 manifest=response.text,
342 )
343 if manifest["mediaType"] in (
344 "application/vnd.docker.distribution.manifest.v2+json",
345 "application/vnd.oci.image.manifest.v1+json",
346 ):
347 return response.text, our_digest
348 else:
349 raise DockerManifestError(
350 "Unsupported manifest type {}".format(manifest["mediaType"]),
351 manifest=response.text,
352 )
353
354 # blob():
355 #
356 # Fetch a blob from the remote registry. This is used for getting each
357 # layer of an image in tar.gz format.
358 #
359 # Raises:
360 # requests.RequestException, if network errors occur
361 #
362 # Args:
363 # image_path (str): Relative path to the image, e.g. library/alpine
364 # blob_digest (str): Content hash of the blob.
365 # download_to (str): Path to a file where the content will be written.
366 def blob(self, image_path, blob_digest, download_to):
367 blob_url = urljoin(image_path, "blobs", urllib.parse.quote(blob_digest))
368
369 response = self._request(blob_url, stream=True)
370
371 with save_file_atomic(download_to, "wb") as f:
372 shutil.copyfileobj(response.raw, f)
373
374
375 class ReadableTarInfo(tarfile.TarInfo):
376 """
377 The goal is to override `TarFile`'s `extractall` semantics by ensuring that on extraction, the
378 files are readable by the owner of the file. This is done by overriding the accessor for the
379 `mode` attribute in `TarInfo`, the class that encapsulates the internal meta-data of the tarball,
380 so that the owner-read bit is always set.
381 """
382
383 # https://github.com/python/mypy/issues/4125
384 @property # type: ignore
385 def mode(self):
386 # Respect umask instead of the file mode stored in the archive.
387 # The only bit used from the embedded mode is the executable bit for files.
388 umask = get_umask()
389 if self.isdir() or bool(self.__permission & 0o100):
390 return 0o777 & ~umask
391 else:
392 return 0o666 & ~umask
393
394 @mode.setter
395 def mode(self, permission):
396 self.__permission = permission # pylint: disable=attribute-defined-outside-init
397
398
399 class DockerSource(Source):
400 # pylint: disable=too-many-instance-attributes
401
402 BST_MIN_VERSION = "2.5"
403
404 # Docker identifies images by a content digest calculated from the image's
405 # manifest. This corresponds well with the concept of a 'ref' in
406 # BuildStream. However, Docker theoretically supports multiple hash
407 # methods while BuildStream does not. Right now every Docker registry
408 # uses sha256 so let's ignore that issue for the time being.
409 @staticmethod
410 def _digest_to_ref(digest):
411 if digest.startswith("sha256:"):
412 return digest[len("sha256:") :]
413 else:
414 method = digest.split(":")[0]
415 raise SourceError("Unsupported digest method: {}".format(method))
416
417 @staticmethod
418 def _ref_to_digest(ref):
419 return "sha256:" + ref
420
421 def configure(self, node):
422 # url is deprecated, but accept it as a valid key so that we can raise
423 # a nicer warning.
424 node.validate_keys(
425 Source.COMMON_CONFIG_KEYS
426 + ["architecture", "registry-url", "image", "os", "ref", "track", "url", "version"]
427 )
428
429 if "url" in node and ("image" in node or "registry-url" in node):
430 raise SourceError("{}: May specify either 'url', or 'image' and 'registry-url'".format(self))
431
432 if "url" not in node and "image" not in node:
433 raise SourceError("{}: Must define either 'url' or 'image'".format(self))
434
435 if "url" in node:
436 self.url = node.get_str("url")
437 translated_url = self.translate_url(self.url)
438 scheme, netloc, path, _, _ = urllib.parse.urlsplit(translated_url)
439 self.registry_url = urllib.parse.urlunsplit((scheme, netloc, "", "", ""))
440 self.image = path
441
442 if "image" in node:
443 self.url = None
444 self.image = node.get_str("image")
445 self.original_registry_url = node.get_str("registry-url", _DOCKER_HUB_URL)
446 self.registry_url = self.translate_url(self.original_registry_url)
447
448 self.tag = node.get_str("track", "") or None
449
450 self.architecture = node.get_str("architecture", "") or default_architecture()
451 self.os = node.get_str("os", "") or default_os()
452 self.version = node.get_str("version", None)
453
454 self.digest = None
455 self.load_ref(node)
456
457 self.client = DockerRegistryV2Client(self.registry_url)
458
459 self.manifest = None
460
461 def load_ref(self, node):
462 ref = node.get_str("ref", None)
463 if ref is not None:
464 self.digest = self._ref_to_digest(ref)
465
466 def preflight(self):
467 return
468
469 def get_unique_key(self):
470 if self.url is not None:
471 unique_key = [self.url, self.digest]
472 else:
473 unique_key = [self.original_registry_url, self.image, self.digest]
474
475 # Backwards compatible method of supporting configuration
476 # attributes which affect SourceInfo generation.
477 if self.version is not None:
478 unique_key.append(self.version)
479
480 return unique_key
481
482 def get_ref(self):
483 return None if self.digest is None else self._digest_to_ref(self.digest)
484
485 def set_ref(self, ref, node):
486 node["ref"] = ref
487 self.digest = self._ref_to_digest(ref)
488
489 def track(self):
490 # pylint: disable=arguments-differ
491
492 # If the tracking ref is not specified it's not an error, just silently return
493 if not self.tag:
494 return None
495
496 with self.timed_activity(
497 "Fetching image manifest for image: '{}:{}' from: {}".format(self.image, self.tag, self.registry_url)
498 ):
499 try:
500 _, digest = self.client.manifest(self.image, self.tag, self.architecture, self.os)
501 except DockerManifestError as e:
502 self.log("Problem downloading manifest", detail=e.manifest)
503 raise
504 except (OSError, requests.RequestException) as e:
505 raise SourceError(e) from e
506
507 return self._digest_to_ref(digest)
508
509 def is_resolved(self):
510 return self.digest is not None
511
512 def is_cached(self):
513 mirror_dir = self.get_mirror_directory()
514 try:
515 manifest = self._load_manifest()
516
517 for layer in manifest["layers"]:
518 layer_digest = layer["digest"]
519 blob_path = os.path.join(mirror_dir, layer_digest + ".tar.gz")
520 try:
521 self._verify_blob(blob_path, expected_digest=layer_digest)
522 except FileNotFoundError:
523 # digest fetched, but some layer blob not fetched
524 return False
525 return True
526 except (FileNotFoundError, SourceError):
527 return False
528
529 def _load_manifest(self):
530 manifest_file = os.path.join(self.get_mirror_directory(), self.digest + ".manifest.json")
531
532 with open(manifest_file, "rb") as f:
533 text = f.read()
534
535 real_digest = self.client.digest(text)
536 if real_digest != self.digest:
537 raise SourceError("Manifest {} is corrupt; got content hash of {}".format(manifest_file, real_digest))
538
539 return json.loads(text.decode("utf-8"))
540
541 def _save_manifest(self, text, path):
542 manifest_file = os.path.join(path, self.digest + ".manifest.json")
543 with save_file_atomic(manifest_file, "wb") as f:
544 f.write(text.encode("utf-8"))
545
546 @staticmethod
547 def _verify_blob(path, expected_digest):
548 blob_digest = "sha256:" + sha256sum(path)
549 if expected_digest != blob_digest:
550 raise SourceError("Blob {} is corrupt; got content hash of {}.".format(path, blob_digest))
551
552 def fetch(self):
553 # pylint: disable=arguments-differ
554
555 with self.timed_activity(
556 "Fetching image {}:{} with digest {}".format(self.image, self.tag, self.digest),
557 silent_nested=True,
558 ):
559 with self.tempdir() as tmpdir:
560 # move all files to a tmpdir
561 try:
562 manifest = self._load_manifest()
563 except FileNotFoundError as e:
564 try:
565 manifest_text, digest = self.client.manifest(
566 self.image,
567 self.digest,
568 self.architecture,
569 self.os,
570 )
571 except requests.RequestException as ee:
572 raise SourceError(ee) from ee
573
574 if digest != self.digest:
575 raise SourceError(
576 "Requested image {}, got manifest with digest {}".format(self.digest, digest)
577 ) from e
578 self._save_manifest(manifest_text, tmpdir)
579 manifest = json.loads(manifest_text)
580 except DockerManifestError as e:
581 self.log("Unexpected manifest", detail=e.manifest)
582 raise
583 except (OSError, requests.RequestException) as e:
584 raise SourceError(e) from e
585
586 for layer in manifest["layers"]:
587 if layer["mediaType"] not in (
588 "application/vnd.docker.image.rootfs.diff.tar.gzip",
589 "application/vnd.oci.image.layer.v1.tar+gzip",
590 ):
591 raise SourceError("Unsupported layer type: {}".format(layer["mediaType"]))
592
593 layer_digest = layer["digest"]
594 blob_path = os.path.join(tmpdir, layer_digest + ".tar.gz")
595
596 if not os.path.exists(blob_path):
597 try:
598 self.client.blob(self.image, layer_digest, download_to=blob_path)
599 except (OSError, requests.RequestException) as e:
600 if os.path.exists(blob_path):
601 shutil.rmtree(blob_path)
602 raise SourceError(e) from e
603
604 self._verify_blob(blob_path, expected_digest=layer_digest)
605
606 # Only if all sources are successfully fetched, move files to staging directory
607
608 # As both the manifest and blobs are content addressable, we can optimize space by having
609 # a flat mirror directory. We check one-by-one if there is any need to copy a file out of the tmpdir.
610 for fetched_file in os.listdir(tmpdir):
611 move_atomic(
612 os.path.join(tmpdir, fetched_file),
613 os.path.join(self.get_mirror_directory(), fetched_file),
614 )
615
616 def stage(self, directory):
617 mirror_dir = self.get_mirror_directory()
618
619 try:
620 manifest = self._load_manifest()
621 except (OSError, SourceError) as e:
622 raise SourceError("Unable to load manifest: {}".format(e)) from e
623
624 try:
625 layer_members = []
626
627 # Create a list of members to extract from each layer
628 for layer in manifest["layers"]:
629 layer_digest = layer["digest"]
630 blob_path = os.path.join(mirror_dir, layer_digest + ".tar.gz")
631
632 self._verify_blob(blob_path, expected_digest=layer_digest)
633
634 members_dict, whiteout_paths, opaque_whiteout_dirs = self._get_members_and_whiteout_paths(blob_path)
635
636 # Process opaque whiteouts: remove members under the corresponding directories from previous layers
637 for _, prev_members_dict in layer_members:
638 members_to_remove = []
639 for member_path in prev_members_dict:
640 # Check if this member should be removed by any opaque whiteout
641 for opaque_whiteout_dir in opaque_whiteout_dirs:
642 if member_path.startswith(opaque_whiteout_dir):
643 members_to_remove.append(member_path)
644 break
645 for member_path in members_to_remove:
646 del prev_members_dict[member_path]
647
648 # Process whiteouts: remove corresponding members from previous layers
649 for _, prev_members_dict in layer_members:
650 for whiteout_path in whiteout_paths:
651 prev_members_dict.pop(whiteout_path, None)
652
653 layer_members.append((blob_path, members_dict))
654
655 # Extract files for each layer
656 for blob_path, members_dict in layer_members:
657 if not members_dict:
658 # No files to extract from this layer
659 continue
660
661 # Extract files for the current layer
662 with tarfile.open(blob_path, tarinfo=ReadableTarInfo) as tar:
663 with self.tempdir() as td:
664 members = list(members_dict.values())
665
666 if hasattr(tarfile, "tar_filter"):
667 # Python 3.12+ (and older versions with backports)
668 tar.extraction_filter = tarfile.tar_filter
669 else:
670 for member in members:
671 self._assert_tarinfo_safe(member, td)
672 tar.extractall(path=td, members=members)
673 link_files(td, directory)
674
675 except (OSError, SourceError, tarfile.TarError) as e:
676 raise SourceError("{}: Error staging source: {}".format(self, e)) from e
677
678 def collect_source_info(self):
679
680 # If the image was configured with "url" only rather
681 # than "registry-url" and "image", then self.image
682 # at this point will have a leading forward slash "/".
683 #
684 # Lets just normalize that problem here, as changing
685 # the self.image itself can break cache keys.
686 #
687 image_name = self.image.lstrip("/")
688
689 return [
690 self.create_source_info(
691 self.registry_url,
692 SourceInfoMedium.OCI_IMAGE,
693 SourceVersionType.OCI_DIGEST,
694 self.digest,
695 version_guess=self.version,
696 extra_data={"image-name": image_name},
697 )
698 ]
699
700 @staticmethod
701 def _get_members_and_whiteout_paths(layer_tar_path):
702 """Return the set of files to remove and extract for a given layer
703
704 :param layer_tar_path: The path to the layer tar.gz file
705 :return: Tuple of (members_dict, whiteout_paths, opaque_whiteout_dirs)
706 - members_dict: OrderedDict of TarInfo members to extract into staging directory
707 - whiteout_paths: list of file paths that should be removed from previous layers
708 - opaque_whiteout_dirs: list of directory paths whose contents should be removed from previous layers
709
710 """
711
712 def strip_wh(white_out_file):
713 """Strip the prefixing .wh. for given file
714
715 :param white_out_file: path of file
716 :return: path without white-out prefix
717 """
718 # whiteout files have the syntax of `*/.wh.*`
719 file_name = os.path.basename(white_out_file)
720 path = os.path.join(os.path.dirname(white_out_file), file_name.split(".wh.", maxsplit=1)[1])
721 return path
722
723 def is_regular_file(info):
724 """Check if file is a non-device file
725
726 :param info: tar member metadata
727 :return: if the file is a non-device file
728 """
729 return not (info.name.startswith("dev/") or info.isdev())
730
731 with tarfile.open(layer_tar_path, tarinfo=ReadableTarInfo) as tar:
732 members_dict = OrderedDict()
733 whiteout_paths = []
734 opaque_whiteout_dirs = []
735
736 for member in tar.getmembers():
737 member_basename = os.path.basename(member.name)
738 if member_basename == ".wh..wh..opq":
739 # Opaque whiteout file
740 opaque_whiteout_dir = os.path.dirname(member.name)
741 if opaque_whiteout_dir != "":
742 # Add "/" to facilitate path prefix matching
743 opaque_whiteout_dir += "/"
744 opaque_whiteout_dirs.append(opaque_whiteout_dir)
745 elif member_basename.startswith(".wh."):
746 # Whiteout file
747 whiteout_paths.append(strip_wh(member.name))
748 elif is_regular_file(member):
749 members_dict[member.name] = member
750
751 return members_dict, whiteout_paths, opaque_whiteout_dirs
752
753 # Assert that a tarfile is safe to extract; specifically, make
754 # sure that we don't do anything outside of the target
755 # directory (this is possible, if, say, someone engineered a
756 # tarfile to contain paths that start with ..).
757 def _assert_tarinfo_safe(self, member: tarfile.TarInfo, target_dir: str):
758 final_path = os.path.abspath(os.path.join(target_dir, member.path))
759 if not final_path.startswith(target_dir):
760 raise SourceError(
761 "{}: Tarfile attempts to extract outside the staging area: "
762 "{} -> {}".format(self, member.path, final_path)
763 )
764
765 if member.islnk():
766 linked_path = os.path.abspath(os.path.join(target_dir, member.linkname))
767 if not linked_path.startswith(target_dir):
768 raise SourceError(
769 "{}: Tarfile attempts to hardlink outside the staging area: "
770 "{} -> {}".format(self, member.path, final_path)
771 )
772
773 # Don't need to worry about symlinks because they're just
774 # files here and won't be able to do much harm once we are
775 # in a sandbox.
776
777
778 # Plugin entry point
779 def setup():
780 return DockerSource