| 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 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 |
] |
| 286 |
|
| 287 |
manifest_url = urljoin(image_path, "manifests", urllib.parse.quote(reference)) |
| 288 |
response = self._request(manifest_url, extra_headers={"Accept": ",".join(accept_types)}) |
| 289 |
|
| 290 |
try: |
| 291 |
manifest = json.loads(response.text) |
| 292 |
except json.JSONDecodeError as e: |
| 293 |
raise DockerManifestError( |
| 294 |
"Server did not return a valid manifest: {}".format(e), |
| 295 |
manifest=response.text, |
| 296 |
) from e |
| 297 |
|
| 298 |
schema_version = manifest.get("schemaVersion") |
| 299 |
if schema_version == 1: |
| 300 |
raise DockerManifestError("Schema version 1 is unsupported.", manifest=response.text) |
| 301 |
if schema_version is None: |
| 302 |
raise DockerManifestError( |
| 303 |
"Manifest did not include the schemaVersion key.", |
| 304 |
manifest=response.text, |
| 305 |
) |
| 306 |
|
| 307 |
our_digest = self.digest(response.text.encode("utf8")) |
| 308 |
their_digest = response.headers.get("Docker-Content-Digest") |
| 309 |
|
| 310 |
if not their_digest: |
| 311 |
raise DockerManifestError( |
| 312 |
"Server did not set the Docker-Content-Digest header.", |
| 313 |
manifest=response.text, |
| 314 |
) |
| 315 |
if our_digest != their_digest: |
| 316 |
raise DockerManifestError( |
| 317 |
"Server returned a non-matching content digest. " |
| 318 |
"Our digest: {}, their digest: {}".format(our_digest, their_digest), |
| 319 |
manifest=response.text, |
| 320 |
) |
| 321 |
|
| 322 |
if manifest["mediaType"] == "application/vnd.docker.distribution.manifest.list.v2+json": |
| 323 |
# This is a "fat manifest", we need to narrow down to a specific |
| 324 |
# architecture. |
| 325 |
for sub in manifest["manifests"]: |
| 326 |
if sub["platform"]["architecture"] == architecture and sub["platform"]["os"]: |
| 327 |
sub_digest = sub["digest"] |
| 328 |
return self.manifest( |
| 329 |
image_path, |
| 330 |
sub_digest, |
| 331 |
architecture=architecture, |
| 332 |
os_=os_, |
| 333 |
) |
| 334 |
raise DockerManifestError( |
| 335 |
"No images found for architecture {}, OS {}".format(architecture, os_), |
| 336 |
manifest=response.text, |
| 337 |
) |
| 338 |
if manifest["mediaType"] == "application/vnd.docker.distribution.manifest.v2+json": |
| 339 |
return response.text, our_digest |
| 340 |
else: |
| 341 |
raise DockerManifestError( |
| 342 |
"Unsupported manifest type {}".format(manifest["mediaType"]), |
| 343 |
manifest=response.text, |
| 344 |
) |
| 345 |
|
| 346 |
# blob(): |
| 347 |
# |
| 348 |
# Fetch a blob from the remote registry. This is used for getting each |
| 349 |
# layer of an image in tar.gz format. |
| 350 |
# |
| 351 |
# Raises: |
| 352 |
# requests.RequestException, if network errors occur |
| 353 |
# |
| 354 |
# Args: |
| 355 |
# image_path (str): Relative path to the image, e.g. library/alpine |
| 356 |
# blob_digest (str): Content hash of the blob. |
| 357 |
# download_to (str): Path to a file where the content will be written. |
| 358 |
def blob(self, image_path, blob_digest, download_to): |
| 359 |
blob_url = urljoin(image_path, "blobs", urllib.parse.quote(blob_digest)) |
| 360 |
|
| 361 |
response = self._request(blob_url, stream=True) |
| 362 |
|
| 363 |
with save_file_atomic(download_to, "wb") as f: |
| 364 |
shutil.copyfileobj(response.raw, f) |
| 365 |
|
| 366 |
|
| 367 |
class ReadableTarInfo(tarfile.TarInfo): |
| 368 |
""" |
| 369 |
The goal is to override `TarFile`'s `extractall` semantics by ensuring that on extraction, the |
| 370 |
files are readable by the owner of the file. This is done by overriding the accessor for the |
| 371 |
`mode` attribute in `TarInfo`, the class that encapsulates the internal meta-data of the tarball, |
| 372 |
so that the owner-read bit is always set. |
| 373 |
""" |
| 374 |
|
| 375 |
# https://github.com/python/mypy/issues/4125 |
| 376 |
@property # type: ignore |
| 377 |
def mode(self): |
| 378 |
# Respect umask instead of the file mode stored in the archive. |
| 379 |
# The only bit used from the embedded mode is the executable bit for files. |
| 380 |
umask = get_umask() |
| 381 |
if self.isdir() or bool(self.__permission & 0o100): |
| 382 |
return 0o777 & ~umask |
| 383 |
else: |
| 384 |
return 0o666 & ~umask |
| 385 |
|
| 386 |
@mode.setter |
| 387 |
def mode(self, permission): |
| 388 |
self.__permission = permission # pylint: disable=attribute-defined-outside-init |
| 389 |
|
| 390 |
|
| 391 |
class DockerSource(Source): |
| 392 |
# pylint: disable=too-many-instance-attributes |
| 393 |
|
| 394 |
BST_MIN_VERSION = "2.5" |
| 395 |
|
| 396 |
# Docker identifies images by a content digest calculated from the image's |
| 397 |
# manifest. This corresponds well with the concept of a 'ref' in |
| 398 |
# BuildStream. However, Docker theoretically supports multiple hash |
| 399 |
# methods while BuildStream does not. Right now every Docker registry |
| 400 |
# uses sha256 so let's ignore that issue for the time being. |
| 401 |
@staticmethod |
| 402 |
def _digest_to_ref(digest): |
| 403 |
if digest.startswith("sha256:"): |
| 404 |
return digest[len("sha256:") :] |
| 405 |
else: |
| 406 |
method = digest.split(":")[0] |
| 407 |
raise SourceError("Unsupported digest method: {}".format(method)) |
| 408 |
|
| 409 |
@staticmethod |
| 410 |
def _ref_to_digest(ref): |
| 411 |
return "sha256:" + ref |
| 412 |
|
| 413 |
def configure(self, node): |
| 414 |
# url is deprecated, but accept it as a valid key so that we can raise |
| 415 |
# a nicer warning. |
| 416 |
node.validate_keys( |
| 417 |
Source.COMMON_CONFIG_KEYS |
| 418 |
+ ["architecture", "registry-url", "image", "os", "ref", "track", "url", "version"] |
| 419 |
) |
| 420 |
|
| 421 |
if "url" in node and ("image" in node or "registry-url" in node): |
| 422 |
raise SourceError("{}: May specify either 'url', or 'image' and 'registry-url'".format(self)) |
| 423 |
|
| 424 |
if "url" not in node and "image" not in node: |
| 425 |
raise SourceError("{}: Must define either 'url' or 'image'".format(self)) |
| 426 |
|
| 427 |
if "url" in node: |
| 428 |
self.url = node.get_str("url") |
| 429 |
translated_url = self.translate_url(self.url) |
| 430 |
scheme, netloc, path, _, _ = urllib.parse.urlsplit(translated_url) |
| 431 |
self.registry_url = urllib.parse.urlunsplit((scheme, netloc, "", "", "")) |
| 432 |
self.image = path |
| 433 |
|
| 434 |
if "image" in node: |
| 435 |
self.url = None |
| 436 |
self.image = node.get_str("image") |
| 437 |
self.original_registry_url = node.get_str("registry-url", _DOCKER_HUB_URL) |
| 438 |
self.registry_url = self.translate_url(self.original_registry_url) |
| 439 |
|
| 440 |
self.tag = node.get_str("track", "") or None |
| 441 |
|
| 442 |
self.architecture = node.get_str("architecture", "") or default_architecture() |
| 443 |
self.os = node.get_str("os", "") or default_os() |
| 444 |
self.version = node.get_str("version", None) |
| 445 |
|
| 446 |
self.digest = None |
| 447 |
self.load_ref(node) |
| 448 |
|
| 449 |
self.client = DockerRegistryV2Client(self.registry_url) |
| 450 |
|
| 451 |
self.manifest = None |
| 452 |
|
| 453 |
def load_ref(self, node): |
| 454 |
ref = node.get_str("ref", None) |
| 455 |
if ref is not None: |
| 456 |
self.digest = self._ref_to_digest(ref) |
| 457 |
|
| 458 |
def preflight(self): |
| 459 |
return |
| 460 |
|
| 461 |
def get_unique_key(self): |
| 462 |
if self.url is not None: |
| 463 |
unique_key = [self.url, self.digest] |
| 464 |
else: |
| 465 |
unique_key = [self.original_registry_url, self.image, self.digest] |
| 466 |
|
| 467 |
# Backwards compatible method of supporting configuration |
| 468 |
# attributes which affect SourceInfo generation. |
| 469 |
if self.version is not None: |
| 470 |
unique_key.append(self.version) |
| 471 |
|
| 472 |
return unique_key |
| 473 |
|
| 474 |
def get_ref(self): |
| 475 |
return None if self.digest is None else self._digest_to_ref(self.digest) |
| 476 |
|
| 477 |
def set_ref(self, ref, node): |
| 478 |
node["ref"] = ref |
| 479 |
self.digest = self._ref_to_digest(ref) |
| 480 |
|
| 481 |
def track(self): |
| 482 |
# pylint: disable=arguments-differ |
| 483 |
|
| 484 |
# If the tracking ref is not specified it's not an error, just silently return |
| 485 |
if not self.tag: |
| 486 |
return None |
| 487 |
|
| 488 |
with self.timed_activity( |
| 489 |
"Fetching image manifest for image: '{}:{}' from: {}".format(self.image, self.tag, self.registry_url) |
| 490 |
): |
| 491 |
try: |
| 492 |
_, digest = self.client.manifest(self.image, self.tag, self.architecture, self.os) |
| 493 |
except DockerManifestError as e: |
| 494 |
self.log("Problem downloading manifest", detail=e.manifest) |
| 495 |
raise |
| 496 |
except (OSError, requests.RequestException) as e: |
| 497 |
raise SourceError(e) from e |
| 498 |
|
| 499 |
return self._digest_to_ref(digest) |
| 500 |
|
| 501 |
def is_resolved(self): |
| 502 |
return self.digest is not None |
| 503 |
|
| 504 |
def is_cached(self): |
| 505 |
mirror_dir = self.get_mirror_directory() |
| 506 |
try: |
| 507 |
manifest = self._load_manifest() |
| 508 |
|
| 509 |
for layer in manifest["layers"]: |
| 510 |
layer_digest = layer["digest"] |
| 511 |
blob_path = os.path.join(mirror_dir, layer_digest + ".tar.gz") |
| 512 |
try: |
| 513 |
self._verify_blob(blob_path, expected_digest=layer_digest) |
| 514 |
except FileNotFoundError: |
| 515 |
# digest fetched, but some layer blob not fetched |
| 516 |
return False |
| 517 |
return True |
| 518 |
except (FileNotFoundError, SourceError): |
| 519 |
return False |
| 520 |
|
| 521 |
def _load_manifest(self): |
| 522 |
manifest_file = os.path.join(self.get_mirror_directory(), self.digest + ".manifest.json") |
| 523 |
|
| 524 |
with open(manifest_file, "rb") as f: |
| 525 |
text = f.read() |
| 526 |
|
| 527 |
real_digest = self.client.digest(text) |
| 528 |
if real_digest != self.digest: |
| 529 |
raise SourceError("Manifest {} is corrupt; got content hash of {}".format(manifest_file, real_digest)) |
| 530 |
|
| 531 |
return json.loads(text.decode("utf-8")) |
| 532 |
|
| 533 |
def _save_manifest(self, text, path): |
| 534 |
manifest_file = os.path.join(path, self.digest + ".manifest.json") |
| 535 |
with save_file_atomic(manifest_file, "wb") as f: |
| 536 |
f.write(text.encode("utf-8")) |
| 537 |
|
| 538 |
@staticmethod |
| 539 |
def _verify_blob(path, expected_digest): |
| 540 |
blob_digest = "sha256:" + sha256sum(path) |
| 541 |
if expected_digest != blob_digest: |
| 542 |
raise SourceError("Blob {} is corrupt; got content hash of {}.".format(path, blob_digest)) |
| 543 |
|
| 544 |
def fetch(self): |
| 545 |
# pylint: disable=arguments-differ |
| 546 |
|
| 547 |
with self.timed_activity( |
| 548 |
"Fetching image {}:{} with digest {}".format(self.image, self.tag, self.digest), |
| 549 |
silent_nested=True, |
| 550 |
): |
| 551 |
with self.tempdir() as tmpdir: |
| 552 |
# move all files to a tmpdir |
| 553 |
try: |
| 554 |
manifest = self._load_manifest() |
| 555 |
except FileNotFoundError as e: |
| 556 |
try: |
| 557 |
manifest_text, digest = self.client.manifest( |
| 558 |
self.image, |
| 559 |
self.digest, |
| 560 |
self.architecture, |
| 561 |
self.os, |
| 562 |
) |
| 563 |
except requests.RequestException as ee: |
| 564 |
raise SourceError(ee) from ee |
| 565 |
|
| 566 |
if digest != self.digest: |
| 567 |
raise SourceError( |
| 568 |
"Requested image {}, got manifest with digest {}".format(self.digest, digest) |
| 569 |
) from e |
| 570 |
self._save_manifest(manifest_text, tmpdir) |
| 571 |
manifest = json.loads(manifest_text) |
| 572 |
except DockerManifestError as e: |
| 573 |
self.log("Unexpected manifest", detail=e.manifest) |
| 574 |
raise |
| 575 |
except (OSError, requests.RequestException) as e: |
| 576 |
raise SourceError(e) from e |
| 577 |
|
| 578 |
for layer in manifest["layers"]: |
| 579 |
if layer["mediaType"] != "application/vnd.docker.image.rootfs.diff.tar.gzip": |
| 580 |
raise SourceError("Unsupported layer type: {}".format(layer["mediaType"])) |
| 581 |
|
| 582 |
layer_digest = layer["digest"] |
| 583 |
blob_path = os.path.join(tmpdir, layer_digest + ".tar.gz") |
| 584 |
|
| 585 |
if not os.path.exists(blob_path): |
| 586 |
try: |
| 587 |
self.client.blob(self.image, layer_digest, download_to=blob_path) |
| 588 |
except (OSError, requests.RequestException) as e: |
| 589 |
if os.path.exists(blob_path): |
| 590 |
shutil.rmtree(blob_path) |
| 591 |
raise SourceError(e) from e |
| 592 |
|
| 593 |
self._verify_blob(blob_path, expected_digest=layer_digest) |
| 594 |
|
| 595 |
# Only if all sources are successfully fetched, move files to staging directory |
| 596 |
|
| 597 |
# As both the manifest and blobs are content addressable, we can optimize space by having |
| 598 |
# a flat mirror directory. We check one-by-one if there is any need to copy a file out of the tmpdir. |
| 599 |
for fetched_file in os.listdir(tmpdir): |
| 600 |
move_atomic( |
| 601 |
os.path.join(tmpdir, fetched_file), |
| 602 |
os.path.join(self.get_mirror_directory(), fetched_file), |
| 603 |
) |
| 604 |
|
| 605 |
def stage(self, directory): |
| 606 |
mirror_dir = self.get_mirror_directory() |
| 607 |
|
| 608 |
try: |
| 609 |
manifest = self._load_manifest() |
| 610 |
except (OSError, SourceError) as e: |
| 611 |
raise SourceError("Unable to load manifest: {}".format(e)) from e |
| 612 |
|
| 613 |
try: |
| 614 |
layer_members = [] |
| 615 |
|
| 616 |
# Create a list of members to extract from each layer |
| 617 |
for layer in manifest["layers"]: |
| 618 |
layer_digest = layer["digest"] |
| 619 |
blob_path = os.path.join(mirror_dir, layer_digest + ".tar.gz") |
| 620 |
|
| 621 |
self._verify_blob(blob_path, expected_digest=layer_digest) |
| 622 |
|
| 623 |
members_dict, whiteout_paths, opaque_whiteout_dirs = self._get_members_and_whiteout_paths(blob_path) |
| 624 |
|
| 625 |
# Process opaque whiteouts: remove members under the corresponding directories from previous layers |
| 626 |
for _, prev_members_dict in layer_members: |
| 627 |
members_to_remove = [] |
| 628 |
for member_path in prev_members_dict: |
| 629 |
# Check if this member should be removed by any opaque whiteout |
| 630 |
for opaque_whiteout_dir in opaque_whiteout_dirs: |
| 631 |
if member_path.startswith(opaque_whiteout_dir): |
| 632 |
members_to_remove.append(member_path) |
| 633 |
break |
| 634 |
for member_path in members_to_remove: |
| 635 |
del prev_members_dict[member_path] |
| 636 |
|
| 637 |
# Process whiteouts: remove corresponding members from previous layers |
| 638 |
for _, prev_members_dict in layer_members: |
| 639 |
for whiteout_path in whiteout_paths: |
| 640 |
prev_members_dict.pop(whiteout_path, None) |
| 641 |
|
| 642 |
layer_members.append((blob_path, members_dict)) |
| 643 |
|
| 644 |
# Extract files for each layer |
| 645 |
for blob_path, members_dict in layer_members: |
| 646 |
if not members_dict: |
| 647 |
# No files to extract from this layer |
| 648 |
continue |
| 649 |
|
| 650 |
# Extract files for the current layer |
| 651 |
with tarfile.open(blob_path, tarinfo=ReadableTarInfo) as tar: |
| 652 |
with self.tempdir() as td: |
| 653 |
members = list(members_dict.values()) |
| 654 |
|
| 655 |
if hasattr(tarfile, "tar_filter"): |
| 656 |
# Python 3.12+ (and older versions with backports) |
| 657 |
tar.extraction_filter = tarfile.tar_filter |
| 658 |
else: |
| 659 |
for member in members: |
| 660 |
self._assert_tarinfo_safe(member, td) |
| 661 |
tar.extractall(path=td, members=members) |
| 662 |
link_files(td, directory) |
| 663 |
|
| 664 |
except (OSError, SourceError, tarfile.TarError) as e: |
| 665 |
raise SourceError("{}: Error staging source: {}".format(self, e)) from e |
| 666 |
|
| 667 |
def collect_source_info(self): |
| 668 |
|
| 669 |
# If the image was configured with "url" only rather |
| 670 |
# than "registry-url" and "image", then self.image |
| 671 |
# at this point will have a leading forward slash "/". |
| 672 |
# |
| 673 |
# Lets just normalize that problem here, as changing |
| 674 |
# the self.image itself can break cache keys. |
| 675 |
# |
| 676 |
image_name = self.image.lstrip("/") |
| 677 |
|
| 678 |
return [ |
| 679 |
self.create_source_info( |
| 680 |
self.registry_url, |
| 681 |
SourceInfoMedium.OCI_IMAGE, |
| 682 |
SourceVersionType.OCI_DIGEST, |
| 683 |
self.digest, |
| 684 |
version_guess=self.version, |
| 685 |
extra_data={"image-name": image_name}, |
| 686 |
) |
| 687 |
] |
| 688 |
|
| 689 |
@staticmethod |
| 690 |
def _get_members_and_whiteout_paths(layer_tar_path): |
| 691 |
"""Return the set of files to remove and extract for a given layer |
| 692 |
|
| 693 |
:param layer_tar_path: The path to the layer tar.gz file |
| 694 |
:return: Tuple of (members_dict, whiteout_paths, opaque_whiteout_dirs) |
| 695 |
- members_dict: OrderedDict of TarInfo members to extract into staging directory |
| 696 |
- whiteout_paths: list of file paths that should be removed from previous layers |
| 697 |
- opaque_whiteout_dirs: list of directory paths whose contents should be removed from previous layers |
| 698 |
|
| 699 |
""" |
| 700 |
|
| 701 |
def strip_wh(white_out_file): |
| 702 |
"""Strip the prefixing .wh. for given file |
| 703 |
|
| 704 |
:param white_out_file: path of file |
| 705 |
:return: path without white-out prefix |
| 706 |
""" |
| 707 |
# whiteout files have the syntax of `*/.wh.*` |
| 708 |
file_name = os.path.basename(white_out_file) |
| 709 |
path = os.path.join(os.path.dirname(white_out_file), file_name.split(".wh.", maxsplit=1)[1]) |
| 710 |
return path |
| 711 |
|
| 712 |
def is_regular_file(info): |
| 713 |
"""Check if file is a non-device file |
| 714 |
|
| 715 |
:param info: tar member metadata |
| 716 |
:return: if the file is a non-device file |
| 717 |
""" |
| 718 |
return not (info.name.startswith("dev/") or info.isdev()) |
| 719 |
|
| 720 |
with tarfile.open(layer_tar_path, tarinfo=ReadableTarInfo) as tar: |
| 721 |
members_dict = OrderedDict() |
| 722 |
whiteout_paths = [] |
| 723 |
opaque_whiteout_dirs = [] |
| 724 |
|
| 725 |
for member in tar.getmembers(): |
| 726 |
member_basename = os.path.basename(member.name) |
| 727 |
if member_basename == ".wh..wh..opq": |
| 728 |
# Opaque whiteout file |
| 729 |
opaque_whiteout_dir = os.path.dirname(member.name) |
| 730 |
if opaque_whiteout_dir != "": |
| 731 |
# Add "/" to facilitate path prefix matching |
| 732 |
opaque_whiteout_dir += "/" |
| 733 |
opaque_whiteout_dirs.append(opaque_whiteout_dir) |
| 734 |
elif member_basename.startswith(".wh."): |
| 735 |
# Whiteout file |
| 736 |
whiteout_paths.append(strip_wh(member.name)) |
| 737 |
elif is_regular_file(member): |
| 738 |
members_dict[member.name] = member |
| 739 |
|
| 740 |
return members_dict, whiteout_paths, opaque_whiteout_dirs |
| 741 |
|
| 742 |
# Assert that a tarfile is safe to extract; specifically, make |
| 743 |
# sure that we don't do anything outside of the target |
| 744 |
# directory (this is possible, if, say, someone engineered a |
| 745 |
# tarfile to contain paths that start with ..). |
| 746 |
def _assert_tarinfo_safe(self, member: tarfile.TarInfo, target_dir: str): |
| 747 |
final_path = os.path.abspath(os.path.join(target_dir, member.path)) |
| 748 |
if not final_path.startswith(target_dir): |
| 749 |
raise SourceError( |
| 750 |
"{}: Tarfile attempts to extract outside the staging area: " |
| 751 |
"{} -> {}".format(self, member.path, final_path) |
| 752 |
) |
| 753 |
|
| 754 |
if member.islnk(): |
| 755 |
linked_path = os.path.abspath(os.path.join(target_dir, member.linkname)) |
| 756 |
if not linked_path.startswith(target_dir): |
| 757 |
raise SourceError( |
| 758 |
"{}: Tarfile attempts to hardlink outside the staging area: " |
| 759 |
"{} -> {}".format(self, member.path, final_path) |
| 760 |
) |
| 761 |
|
| 762 |
# Don't need to worry about symlinks because they're just |
| 763 |
# files here and won't be able to do much harm once we are |
| 764 |
# in a sandbox. |
| 765 |
|
| 766 |
|
| 767 |
# Plugin entry point |
| 768 |
def setup(): |
| 769 |
return DockerSource |