| 1 |
#!/usr/bin/python |
| 2 |
# |
| 3 |
# Copyright 2016 Red Hat | Ansible |
| 4 |
# GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
DOCUMENTATION = r""" |
| 10 |
module: docker_image_load |
| 11 |
|
| 12 |
short_description: Load docker image(s) from archives |
| 13 |
|
| 14 |
version_added: 1.3.0 |
| 15 |
|
| 16 |
description: |
| 17 |
- Load one or multiple Docker images from a C(.tar) archive, and return information on the loaded image(s). |
| 18 |
extends_documentation_fragment: |
| 19 |
- community.docker._docker.api_documentation |
| 20 |
- community.docker._attributes |
| 21 |
- community.docker._attributes.actiongroup_docker |
| 22 |
|
| 23 |
attributes: |
| 24 |
check_mode: |
| 25 |
support: none |
| 26 |
diff_mode: |
| 27 |
support: none |
| 28 |
idempotent: |
| 29 |
support: none |
| 30 |
|
| 31 |
options: |
| 32 |
path: |
| 33 |
description: |
| 34 |
- The path to the C(.tar) archive to load Docker image(s) from. |
| 35 |
type: path |
| 36 |
required: true |
| 37 |
|
| 38 |
requirements: |
| 39 |
- "Docker API >= 1.25" |
| 40 |
|
| 41 |
author: |
| 42 |
- Felix Fontein (@felixfontein) |
| 43 |
|
| 44 |
seealso: |
| 45 |
- module: community.docker.docker_image_export |
| 46 |
- module: community.docker.docker_image_push |
| 47 |
- module: community.docker.docker_image_remove |
| 48 |
- module: community.docker.docker_image_tag |
| 49 |
""" |
| 50 |
|
| 51 |
EXAMPLES = r""" |
| 52 |
--- |
| 53 |
- name: Load all image(s) from the given tar file |
| 54 |
community.docker.docker_image_load: |
| 55 |
path: /path/to/images.tar |
| 56 |
register: result |
| 57 |
|
| 58 |
- name: Print the loaded image names |
| 59 |
ansible.builtin.debug: |
| 60 |
msg: "Loaded the following images: {{ result.image_names | join(', ') }}" |
| 61 |
""" |
| 62 |
|
| 63 |
RETURN = r""" |
| 64 |
image_names: |
| 65 |
description: List of image names and IDs loaded from the archive. |
| 66 |
returned: success |
| 67 |
type: list |
| 68 |
elements: str |
| 69 |
sample: |
| 70 |
- 'hello-world:latest' |
| 71 |
- 'sha256:e004c2cc521c95383aebb1fb5893719aa7a8eae2e7a71f316a4410784edb00a9' |
| 72 |
images: |
| 73 |
description: Image inspection results for the loaded images. |
| 74 |
returned: success |
| 75 |
type: list |
| 76 |
elements: dict |
| 77 |
sample: [] |
| 78 |
""" |
| 79 |
|
| 80 |
import errno |
| 81 |
import traceback |
| 82 |
import typing as t |
| 83 |
|
| 84 |
from ansible_collections.community.docker.plugins.module_utils._api.errors import ( |
| 85 |
DockerException, |
| 86 |
) |
| 87 |
from ansible_collections.community.docker.plugins.module_utils._common_api import ( |
| 88 |
AnsibleDockerClient, |
| 89 |
RequestException, |
| 90 |
) |
| 91 |
from ansible_collections.community.docker.plugins.module_utils._util import ( |
| 92 |
DockerBaseClass, |
| 93 |
is_image_name_id, |
| 94 |
) |
| 95 |
|
| 96 |
|
| 97 |
class ImageManager(DockerBaseClass): |
| 98 |
def __init__(self, client: AnsibleDockerClient, results: dict[str, t.Any]) -> None: |
| 99 |
super().__init__() |
| 100 |
|
| 101 |
self.client = client |
| 102 |
self.results = results |
| 103 |
parameters = self.client.module.params |
| 104 |
self.check_mode = self.client.check_mode |
| 105 |
|
| 106 |
self.path = parameters["path"] |
| 107 |
|
| 108 |
self.load_images() |
| 109 |
|
| 110 |
@staticmethod |
| 111 |
def _extract_output_line(line: dict[str, t.Any], output: list[str]) -> None: |
| 112 |
""" |
| 113 |
Extract text line from stream output and, if found, adds it to output. |
| 114 |
""" |
| 115 |
if "stream" in line or "status" in line: |
| 116 |
# Make sure we have a string (assuming that line['stream'] and |
| 117 |
# line['status'] are either not defined, falsish, or a string) |
| 118 |
text_line = line.get("stream") or line.get("status") or "" |
| 119 |
output.extend(text_line.splitlines()) |
| 120 |
|
| 121 |
def load_images(self) -> None: |
| 122 |
""" |
| 123 |
Load images from a .tar archive |
| 124 |
""" |
| 125 |
# Load image(s) from file |
| 126 |
load_output: list[str] = [] |
| 127 |
try: |
| 128 |
self.log(f"Opening image {self.path}") |
| 129 |
with open(self.path, "rb") as image_tar: |
| 130 |
self.log(f"Loading images from {self.path}") |
| 131 |
res = self.client._post( |
| 132 |
self.client._url("/images/load"), data=image_tar, stream=True |
| 133 |
) |
| 134 |
for line in self.client._stream_helper(res, decode=True): |
| 135 |
self.log(line, pretty_print=True) |
| 136 |
self._extract_output_line(line, load_output) |
| 137 |
except EnvironmentError as exc: |
| 138 |
if exc.errno == errno.ENOENT: |
| 139 |
self.client.fail(f"Error opening archive {self.path} - {exc}") |
| 140 |
self.client.fail( |
| 141 |
f"Error loading archive {self.path} - {exc}", |
| 142 |
stdout="\n".join(load_output), |
| 143 |
) |
| 144 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 145 |
self.client.fail( |
| 146 |
f"Error loading archive {self.path} - {exc}", |
| 147 |
stdout="\n".join(load_output), |
| 148 |
) |
| 149 |
|
| 150 |
# Collect loaded images |
| 151 |
loaded_images = [] |
| 152 |
for line in load_output: |
| 153 |
if line.startswith("Loaded image:"): |
| 154 |
loaded_images.append(line[len("Loaded image:") :].strip()) |
| 155 |
if line.startswith("Loaded image ID:"): |
| 156 |
loaded_images.append(line[len("Loaded image ID:") :].strip()) |
| 157 |
|
| 158 |
if not loaded_images: |
| 159 |
self.client.fail( |
| 160 |
"Detected no loaded images. Archive potentially corrupt?", |
| 161 |
stdout="\n".join(load_output), |
| 162 |
) |
| 163 |
|
| 164 |
images = [] |
| 165 |
for image_name in loaded_images: |
| 166 |
if is_image_name_id(image_name): |
| 167 |
images.append(self.client.find_image_by_id(image_name)) |
| 168 |
elif ":" in image_name: |
| 169 |
image_name, tag = image_name.rsplit(":", 1) |
| 170 |
images.append(self.client.find_image(image_name, tag)) |
| 171 |
else: |
| 172 |
self.client.module.warn( |
| 173 |
f'Image name "{image_name}" is neither ID nor has a tag' |
| 174 |
) |
| 175 |
|
| 176 |
self.results["image_names"] = loaded_images |
| 177 |
self.results["images"] = images |
| 178 |
self.results["changed"] = True |
| 179 |
self.results["stdout"] = "\n".join(load_output) |
| 180 |
|
| 181 |
|
| 182 |
def main() -> None: |
| 183 |
client = AnsibleDockerClient( |
| 184 |
argument_spec={ |
| 185 |
"path": {"type": "path", "required": True}, |
| 186 |
}, |
| 187 |
supports_check_mode=False, |
| 188 |
) |
| 189 |
|
| 190 |
try: |
| 191 |
results: dict[str, t.Any] = { |
| 192 |
"image_names": [], |
| 193 |
"images": [], |
| 194 |
} |
| 195 |
|
| 196 |
ImageManager(client, results) |
| 197 |
client.module.exit_json(**results) |
| 198 |
except DockerException as e: |
| 199 |
client.fail( |
| 200 |
f"An unexpected Docker error occurred: {e}", |
| 201 |
exception=traceback.format_exc(), |
| 202 |
) |
| 203 |
except RequestException as e: |
| 204 |
client.fail( |
| 205 |
f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}", |
| 206 |
exception=traceback.format_exc(), |
| 207 |
) |
| 208 |
|
| 209 |
|
| 210 |
if __name__ == "__main__": |
| 211 |
main() |