Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_image_export.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2023, Felix Fontein <[email protected]>
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_export
11
12 short_description: Export (archive) Docker images
13
14 version_added: 3.7.0
15
16 description:
17 - Creates an archive (tarball) from one or more Docker images.
18 - This can be copied to another machine and loaded with M(community.docker.docker_image_load).
19 extends_documentation_fragment:
20 - community.docker._docker.api_documentation
21 - community.docker._attributes
22 - community.docker._attributes.actiongroup_docker
23
24 attributes:
25 check_mode:
26 support: full
27 diff_mode:
28 support: none
29 idempotent:
30 support: partial
31 details:
32 - Whether the module is idempotent depends on the storage API used for images,
33 which determines how the image ID is computed. The idempotency check needs
34 the image ID to equal the ID stored in archive's C(manifest.json).
35 This seemed to have worked fine with the default storage backend up to Docker 28,
36 but seems to have changed in Docker 29.
37 - This module is B(not idempotent) when used with multi-architecture images,
38 regardless of Docker version.
39 - Full idempotency requires Docker 28 or earlier B(and) a single-architecture image.
40
41 options:
42 names:
43 description:
44 - 'One or more image names. Name format will be one of: C(name), C(repository/name), C(registry_server:port/name). When
45 pushing or pulling an image the name can optionally include the tag by appending C(:tag_name).'
46 - Note that image IDs (hashes) can also be used.
47 type: list
48 elements: str
49 required: true
50 aliases:
51 - name
52 tag:
53 description:
54 - Tag for the image name O(name) that is to be tagged.
55 - If O(name)'s format is C(name:tag), then the tag value from O(name) will take precedence.
56 type: str
57 default: latest
58 path:
59 description:
60 - The C(.tar) file the image should be exported to.
61 type: path
62 force:
63 description:
64 - Export the image even if the C(.tar) file already exists and seems to contain the right image.
65 type: bool
66 default: false
67 platform:
68 description:
69 - Ask for this specific platform when exporting.
70 - For example, C(linux/amd64), C(linux/arm64).
71 - Requires Docker API 1.48 or newer.
72 type: str
73 version_added: 5.2.0
74
75 requirements:
76 - "Docker API >= 1.25"
77
78 author:
79 - Felix Fontein (@felixfontein)
80
81 seealso:
82 - module: community.docker.docker_image
83 - module: community.docker.docker_image_info
84 - module: community.docker.docker_image_load
85 """
86
87 EXAMPLES = r"""
88 ---
89 - name: Export an image
90 community.docker.docker_image_export:
91 name: pacur/centos-7
92 path: /tmp/centos-7.tar
93
94 - name: Export multiple images
95 community.docker.docker_image_export:
96 names:
97 - hello-world:latest
98 - pacur/centos-7:latest
99 path: /tmp/various.tar
100 """
101
102 RETURN = r"""
103 images:
104 description: Image inspection results for the affected images.
105 returned: success
106 type: list
107 elements: dict
108 sample: []
109 """
110
111 import json
112 import traceback
113 import typing as t
114
115 from ansible_collections.community.docker.plugins.module_utils._api.constants import (
116 DEFAULT_DATA_CHUNK_SIZE,
117 )
118 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
119 DockerException,
120 )
121 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
122 parse_repository_tag,
123 )
124 from ansible_collections.community.docker.plugins.module_utils._common_api import (
125 AnsibleDockerClient,
126 RequestException,
127 )
128 from ansible_collections.community.docker.plugins.module_utils._image_archive import (
129 ImageArchiveInvalidException,
130 api_image_id,
131 load_archived_image_manifest,
132 )
133 from ansible_collections.community.docker.plugins.module_utils._platform import (
134 _Platform,
135 )
136 from ansible_collections.community.docker.plugins.module_utils._util import (
137 DockerBaseClass,
138 is_image_name_id,
139 is_valid_tag,
140 )
141
142
143 class ImageExportManager(DockerBaseClass):
144 def __init__(self, client: AnsibleDockerClient) -> None:
145 super().__init__()
146
147 self.client = client
148 parameters = self.client.module.params
149 self.check_mode = self.client.check_mode
150
151 self.path = parameters["path"]
152 self.force = parameters["force"]
153 self.tag = parameters["tag"]
154 self.platform = parameters["platform"]
155
156 if not is_valid_tag(self.tag, allow_empty=True):
157 self.fail(f'"{self.tag}" is not a valid docker tag')
158
159 # If name contains a tag, it takes precedence over tag parameter.
160 self.names = []
161 for name in parameters["names"]:
162 if is_image_name_id(name):
163 self.names.append({"id": name, "joined": name})
164 else:
165 repo, repo_tag = parse_repository_tag(name)
166 if not repo_tag:
167 repo_tag = self.tag
168 self.names.append(
169 {"name": repo, "tag": repo_tag, "joined": f"{repo}:{repo_tag}"}
170 )
171
172 if not self.names:
173 self.fail("At least one image name must be specified")
174
175 def fail(self, msg: str) -> t.NoReturn:
176 self.client.fail(msg)
177
178 def get_export_reason(self) -> str | None:
179 if self.force:
180 return "Exporting since force=true"
181
182 try:
183 archived_images = load_archived_image_manifest(self.path)
184 if archived_images is None:
185 return "Overwriting since no image is present in archive"
186 except ImageArchiveInvalidException as exc:
187 self.log(f"Unable to extract manifest summary from archive: {exc}")
188 return "Overwriting an unreadable archive file"
189
190 left_names = list(self.names)
191 for archived_image in archived_images:
192 found = False
193 for i, name in enumerate(left_names):
194 if (
195 name["id"] == api_image_id(archived_image.image_id)
196 and [name["joined"]] == archived_image.repo_tags
197 ):
198 del left_names[i]
199 found = True
200 break
201 if not found:
202 return f"Overwriting archive since it contains unexpected image {archived_image.image_id} named {', '.join(archived_image.repo_tags)}"
203 if left_names:
204 return f"Overwriting archive since it is missing image(s) {', '.join([name['joined'] for name in left_names])}"
205
206 return None
207
208 def write_chunks(self, chunks: t.Generator[bytes]) -> None:
209 try:
210 with open(self.path, "wb") as fd:
211 for chunk in chunks:
212 fd.write(chunk)
213 except Exception as exc: # pylint: disable=broad-exception-caught
214 self.fail(f"Error writing image archive {self.path} - {exc}")
215
216 def _platform_param(self) -> str:
217 platform = _Platform.parse_platform_string(self.platform)
218 platform_spec: dict[str, str] = {}
219 if platform.os:
220 platform_spec["os"] = platform.os
221 if platform.arch:
222 platform_spec["architecture"] = platform.arch
223 if platform.variant:
224 platform_spec["variant"] = platform.variant
225 return json.dumps(platform_spec)
226
227 def export_images(self) -> None:
228 image_names = [name["joined"] for name in self.names]
229 image_names_str = ", ".join(image_names)
230 if len(image_names) == 1:
231 self.log(f"Getting archive of image {image_names[0]}")
232 params: dict[str, t.Any] = {}
233 if self.platform:
234 params["platform"] = self._platform_param()
235 try:
236 chunks = self.client._stream_raw_result(
237 self.client._get(
238 self.client._url("/images/{0}/get", image_names[0]),
239 stream=True,
240 params=params,
241 ),
242 chunk_size=DEFAULT_DATA_CHUNK_SIZE,
243 decode=False,
244 )
245 except Exception as exc: # pylint: disable=broad-exception-caught
246 self.fail(f"Error getting image {image_names[0]} - {exc}")
247 else:
248 self.log(f"Getting archive of images {image_names_str}")
249 params = {"names": image_names}
250 if self.platform:
251 params["platform"] = self._platform_param()
252 try:
253 chunks = self.client._stream_raw_result(
254 self.client._get(
255 self.client._url("/images/get"),
256 stream=True,
257 params=params,
258 ),
259 chunk_size=DEFAULT_DATA_CHUNK_SIZE,
260 decode=False,
261 )
262 except Exception as exc: # pylint: disable=broad-exception-caught
263 self.fail(f"Error getting images {image_names_str} - {exc}")
264
265 self.write_chunks(chunks)
266
267 def run(self) -> dict[str, t.Any]:
268 tag = self.tag
269 if not tag:
270 tag = "latest"
271
272 images = []
273 for name in self.names:
274 if "id" in name:
275 image = self.client.find_image_by_id(
276 name["id"], accept_missing_image=True
277 )
278 else:
279 image = self.client.find_image(name=name["name"], tag=name["tag"])
280 if not image:
281 self.fail(f"Image {name['joined']} not found")
282 images.append(image)
283
284 # Will have a 'sha256:' prefix
285 name["id"] = image["Id"]
286
287 results = {
288 "changed": False,
289 "images": images,
290 }
291
292 reason = self.get_export_reason()
293 if reason is not None:
294 results["msg"] = reason
295 results["changed"] = True
296
297 if not self.check_mode:
298 self.export_images()
299
300 return results
301
302
303 def main() -> None:
304 argument_spec = {
305 "path": {"type": "path"},
306 "force": {"type": "bool", "default": False},
307 "names": {
308 "type": "list",
309 "elements": "str",
310 "required": True,
311 "aliases": ["name"],
312 },
313 "tag": {"type": "str", "default": "latest"},
314 "platform": {"type": "str"},
315 }
316
317 option_minimal_versions = {
318 "platform": {"docker_api_version": "1.48"},
319 }
320
321 client = AnsibleDockerClient(
322 argument_spec=argument_spec,
323 supports_check_mode=True,
324 option_minimal_versions=option_minimal_versions,
325 )
326
327 try:
328 results = ImageExportManager(client).run()
329 client.module.exit_json(**results)
330 except DockerException as e:
331 client.fail(
332 f"An unexpected Docker error occurred: {e}",
333 exception=traceback.format_exc(),
334 )
335 except RequestException as e:
336 client.fail(
337 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
338 exception=traceback.format_exc(),
339 )
340
341
342 if __name__ == "__main__":
343 main()