| 1 |
# Copyright 2022 Red Hat | Ansible |
| 2 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
|
| 5 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 6 |
# Do not use this from other collections or standalone plugins/modules! |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import json |
| 11 |
import os |
| 12 |
import tarfile |
| 13 |
|
| 14 |
|
| 15 |
class ImageArchiveManifestSummary: |
| 16 |
""" |
| 17 |
Represents data extracted from a manifest.json found in the tar archive output of the |
| 18 |
"docker image save some:tag > some.tar" command. |
| 19 |
""" |
| 20 |
|
| 21 |
def __init__(self, image_id: str, repo_tags: list[str]) -> None: |
| 22 |
""" |
| 23 |
:param image_id: File name portion of Config entry, e.g. abcde12345 from abcde12345.json |
| 24 |
:param repo_tags Docker image names, e.g. ["hello-world:latest"] |
| 25 |
""" |
| 26 |
|
| 27 |
self.image_id = image_id |
| 28 |
self.repo_tags = repo_tags |
| 29 |
|
| 30 |
|
| 31 |
class ImageArchiveInvalidException(Exception): |
| 32 |
pass |
| 33 |
|
| 34 |
|
| 35 |
def api_image_id(archive_image_id: str) -> str: |
| 36 |
""" |
| 37 |
Accepts an image hash in the format stored in manifest.json, and returns an equivalent identifier |
| 38 |
that represents the same image hash, but in the format presented by the Docker Engine API. |
| 39 |
|
| 40 |
:param archive_image_id: plain image hash |
| 41 |
:returns: Prefixed hash used by REST api |
| 42 |
""" |
| 43 |
|
| 44 |
return f"sha256:{archive_image_id}" |
| 45 |
|
| 46 |
|
| 47 |
def load_archived_image_manifest( |
| 48 |
archive_path: str, |
| 49 |
) -> list[ImageArchiveManifestSummary] | None: |
| 50 |
""" |
| 51 |
Attempts to get image IDs and image names from metadata stored in the image |
| 52 |
archive tar file. |
| 53 |
|
| 54 |
The tar should contain a file "manifest.json" with an array with one or more entries, |
| 55 |
and every entry should have a Config field with the image ID in its file name, as |
| 56 |
well as a RepoTags list, which typically has only one entry. |
| 57 |
|
| 58 |
:raises: |
| 59 |
ImageArchiveInvalidException: A file already exists at archive_path, but could not extract an image ID from it. |
| 60 |
|
| 61 |
:param archive_path: Tar file to read |
| 62 |
:return: None, if no file at archive_path, or a list of ImageArchiveManifestSummary objects. |
| 63 |
""" |
| 64 |
|
| 65 |
try: |
| 66 |
# FileNotFoundError does not exist in Python 2 |
| 67 |
if not os.path.isfile(archive_path): |
| 68 |
return None |
| 69 |
|
| 70 |
with tarfile.open(archive_path, "r") as tf: |
| 71 |
try: |
| 72 |
try: |
| 73 |
reader = tf.extractfile("manifest.json") |
| 74 |
if reader is None: |
| 75 |
raise ImageArchiveInvalidException( |
| 76 |
"Failed to read manifest.json" |
| 77 |
) |
| 78 |
with reader as ef: |
| 79 |
manifest = json.load(ef) |
| 80 |
except ImageArchiveInvalidException: |
| 81 |
raise |
| 82 |
except Exception as exc: |
| 83 |
raise ImageArchiveInvalidException( |
| 84 |
f"Failed to decode and deserialize manifest.json: {exc}" |
| 85 |
) from exc |
| 86 |
|
| 87 |
if len(manifest) == 0: |
| 88 |
raise ImageArchiveInvalidException( |
| 89 |
"Expected to have at least one entry in manifest.json but found none" |
| 90 |
) |
| 91 |
|
| 92 |
result = [] |
| 93 |
for index, meta in enumerate(manifest): |
| 94 |
try: |
| 95 |
config_file = meta["Config"] |
| 96 |
except KeyError as exc: |
| 97 |
raise ImageArchiveInvalidException( |
| 98 |
f"Failed to get Config entry from {index + 1}th manifest in manifest.json: {exc}" |
| 99 |
) from exc |
| 100 |
|
| 101 |
# Extracts hash without 'sha256:' prefix |
| 102 |
try: |
| 103 |
# Strip off .json filename extension, leaving just the hash. |
| 104 |
image_id = os.path.splitext(config_file)[0] |
| 105 |
except Exception as exc: |
| 106 |
raise ImageArchiveInvalidException( |
| 107 |
f"Failed to extract image id from config file name {config_file}: {exc}" |
| 108 |
) from exc |
| 109 |
|
| 110 |
for prefix in ("blobs/sha256/",): # Moby 25.0.0, Docker API 1.44 |
| 111 |
if image_id.startswith(prefix): |
| 112 |
image_id = image_id[len(prefix) :] |
| 113 |
|
| 114 |
try: |
| 115 |
repo_tags = meta["RepoTags"] |
| 116 |
except KeyError as exc: |
| 117 |
raise ImageArchiveInvalidException( |
| 118 |
f"Failed to get RepoTags entry from {index + 1}th manifest in manifest.json: {exc}" |
| 119 |
) from exc |
| 120 |
|
| 121 |
result.append( |
| 122 |
ImageArchiveManifestSummary( |
| 123 |
image_id=image_id, repo_tags=repo_tags |
| 124 |
) |
| 125 |
) |
| 126 |
return result |
| 127 |
|
| 128 |
except ImageArchiveInvalidException: |
| 129 |
raise |
| 130 |
except Exception as exc: |
| 131 |
raise ImageArchiveInvalidException( |
| 132 |
f"Failed to extract manifest.json from tar file {archive_path}: {exc}" |
| 133 |
) from exc |
| 134 |
|
| 135 |
except ImageArchiveInvalidException: |
| 136 |
raise |
| 137 |
except Exception as exc: |
| 138 |
raise ImageArchiveInvalidException( |
| 139 |
f"Failed to open tar file {archive_path}: {exc}" |
| 140 |
) from exc |
| 141 |
|
| 142 |
|
| 143 |
def archived_image_manifest(archive_path: str) -> ImageArchiveManifestSummary | None: |
| 144 |
""" |
| 145 |
Attempts to get Image.Id and image name from metadata stored in the image |
| 146 |
archive tar file. |
| 147 |
|
| 148 |
The tar should contain a file "manifest.json" with an array with a single entry, |
| 149 |
and the entry should have a Config field with the image ID in its file name, as |
| 150 |
well as a RepoTags list, which typically has only one entry. |
| 151 |
|
| 152 |
:raises: |
| 153 |
ImageArchiveInvalidException: A file already exists at archive_path, but could not extract an image ID from it. |
| 154 |
|
| 155 |
:param archive_path: Tar file to read |
| 156 |
:return: None, if no file at archive_path, or the extracted image ID, which will not have a sha256: prefix. |
| 157 |
""" |
| 158 |
|
| 159 |
results = load_archived_image_manifest(archive_path) |
| 160 |
if results is None: |
| 161 |
return None |
| 162 |
if len(results) == 1: |
| 163 |
return results[0] |
| 164 |
raise ImageArchiveInvalidException( |
| 165 |
f"Expected to have one entry in manifest.json but found {len(results)}" |
| 166 |
) |