Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_common_cli.py

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
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 abc
11 import json
12 import shlex
13 import typing as t
14
15 from ansible.module_utils.basic import AnsibleModule, env_fallback
16 from ansible.module_utils.common.process import get_bin_path
17 from ansible.module_utils.common.text.converters import to_text
18
19 from ansible_collections.community.docker.plugins.module_utils._api.auth import (
20 resolve_repository_name,
21 )
22 from ansible_collections.community.docker.plugins.module_utils._util import (
23 DEFAULT_DOCKER_HOST,
24 DEFAULT_TLS,
25 DEFAULT_TLS_VERIFY,
26 DOCKER_MUTUALLY_EXCLUSIVE,
27 DOCKER_REQUIRED_TOGETHER,
28 sanitize_result,
29 )
30 from ansible_collections.community.docker.plugins.module_utils._version import (
31 LooseVersion,
32 )
33
34 if t.TYPE_CHECKING:
35 from collections.abc import Mapping, Sequence
36
37
38 DOCKER_COMMON_ARGS = {
39 "docker_cli": {"type": "path"},
40 "docker_host": {
41 "type": "str",
42 "fallback": (env_fallback, ["DOCKER_HOST"]),
43 "aliases": ["docker_url"],
44 },
45 "tls_hostname": {
46 "type": "str",
47 "fallback": (env_fallback, ["DOCKER_TLS_HOSTNAME"]),
48 },
49 "api_version": {
50 "type": "str",
51 "default": "auto",
52 "fallback": (env_fallback, ["DOCKER_API_VERSION"]),
53 "aliases": ["docker_api_version"],
54 },
55 "ca_path": {"type": "path", "aliases": ["ca_cert", "tls_ca_cert", "cacert_path"]},
56 "client_cert": {"type": "path", "aliases": ["tls_client_cert", "cert_path"]},
57 "client_key": {"type": "path", "aliases": ["tls_client_key", "key_path"]},
58 "tls": {
59 "type": "bool",
60 "default": DEFAULT_TLS,
61 "fallback": (env_fallback, ["DOCKER_TLS"]),
62 },
63 "validate_certs": {
64 "type": "bool",
65 "default": DEFAULT_TLS_VERIFY,
66 "fallback": (env_fallback, ["DOCKER_TLS_VERIFY"]),
67 "aliases": ["tls_verify"],
68 },
69 # "debug": {"type": "bool", "default: False},
70 "cli_context": {"type": "str"},
71 }
72
73
74 class DockerException(Exception):
75 pass
76
77
78 class AnsibleDockerClientBase:
79 docker_api_version_str: str | None
80 docker_api_version: LooseVersion | None
81
82 def __init__(
83 self,
84 common_args: dict[str, t.Any],
85 min_docker_api_version: str | None = None,
86 needs_api_version: bool = True,
87 ) -> None:
88 self._environment: dict[str, str] = {}
89 if common_args["tls_hostname"]:
90 self._environment["DOCKER_TLS_HOSTNAME"] = common_args["tls_hostname"]
91 if common_args["api_version"] and common_args["api_version"] != "auto":
92 self._environment["DOCKER_API_VERSION"] = common_args["api_version"]
93 cli = common_args.get("docker_cli")
94 if cli is None:
95 try:
96 cli = get_bin_path("docker")
97 except ValueError:
98 self.fail(
99 "Cannot find docker CLI in path. Please provide it explicitly with the docker_cli parameter"
100 )
101 self._cli = cli
102 self._cli_base = [self._cli]
103 docker_host = common_args["docker_host"]
104 if not docker_host and not common_args["cli_context"]:
105 docker_host = DEFAULT_DOCKER_HOST
106 if docker_host:
107 self._cli_base.extend(["--host", docker_host])
108 if common_args["validate_certs"]:
109 self._cli_base.append("--tlsverify")
110 elif common_args["tls"]:
111 self._cli_base.append("--tls")
112 if common_args["ca_path"]:
113 self._cli_base.extend(["--tlscacert", common_args["ca_path"]])
114 if common_args["client_cert"]:
115 self._cli_base.extend(["--tlscert", common_args["client_cert"]])
116 if common_args["client_key"]:
117 self._cli_base.extend(["--tlskey", common_args["client_key"]])
118 if common_args["cli_context"]:
119 self._cli_base.extend(["--context", common_args["cli_context"]])
120
121 # `--format json` was only added as a shorthand for `--format {{ json . }}` in Docker 23.0
122 dummy, self._version, dummy2 = self.call_cli_json(
123 "version", "--format", "{{ json . }}", check_rc=True
124 )
125 self._info: dict[str, t.Any] | None = None
126
127 if needs_api_version:
128 api_version_string = self._version["Server"].get(
129 "ApiVersion"
130 ) or self._version["Server"].get("APIVersion")
131 if not isinstance(self._version.get("Server"), dict) or not isinstance(
132 api_version_string, str
133 ):
134 self.fail(
135 "Cannot determine Docker Daemon information. Are you maybe using podman instead of docker?"
136 )
137 self.docker_api_version_str = to_text(api_version_string)
138 self.docker_api_version = LooseVersion(self.docker_api_version_str)
139 min_docker_api_version = min_docker_api_version or "1.25"
140 if self.docker_api_version < LooseVersion(min_docker_api_version):
141 self.fail(
142 f"Docker API version is {self.docker_api_version_str}. Minimum version required is {min_docker_api_version}."
143 )
144 else:
145 self.docker_api_version_str = None
146 self.docker_api_version = None
147 if min_docker_api_version is not None:
148 self.fail(
149 "Internal error: cannot have needs_api_version=False with min_docker_api_version not None"
150 )
151
152 def log(self, msg: str, pretty_print: bool = False) -> None:
153 pass
154 # if self.debug:
155 # from .util import log_debug
156 # log_debug(msg, pretty_print=pretty_print)
157
158 def get_cli(self) -> str:
159 return self._cli
160
161 def get_version_info(self) -> str:
162 return self._version
163
164 def _compose_cmd(self, args: t.Sequence[str]) -> list[str]:
165 return self._cli_base + list(args)
166
167 def _compose_cmd_str(self, args: t.Sequence[str]) -> str:
168 return " ".join(shlex.quote(a) for a in self._compose_cmd(args))
169
170 @abc.abstractmethod
171 def call_cli(
172 self,
173 *args: str,
174 check_rc: bool = False,
175 data: bytes | None = None,
176 cwd: str | None = None,
177 environ_update: dict[str, str] | None = None,
178 ) -> tuple[int, bytes, bytes]:
179 pass
180
181 def call_cli_json(
182 self,
183 *args: str,
184 check_rc: bool = False,
185 data: bytes | None = None,
186 cwd: str | None = None,
187 environ_update: dict[str, str] | None = None,
188 warn_on_stderr: bool = False,
189 ) -> tuple[int, t.Any, bytes]:
190 rc, stdout, stderr = self.call_cli(
191 *args, check_rc=check_rc, data=data, cwd=cwd, environ_update=environ_update
192 )
193 if warn_on_stderr and stderr:
194 self.warn(to_text(stderr))
195 try:
196 data = json.loads(stdout)
197 except Exception as exc: # pylint: disable=broad-exception-caught
198 self.fail(
199 f"Error while parsing JSON output of {self._compose_cmd_str(args)}: {exc}\nJSON output: {to_text(stdout)}\n\nError output:\n{to_text(stderr)}",
200 cmd=self._compose_cmd_str(args),
201 rc=rc,
202 stdout=stdout,
203 stderr=stderr,
204 )
205 return rc, data, stderr
206
207 def call_cli_json_stream(
208 self,
209 *args: str,
210 check_rc: bool = False,
211 data: bytes | None = None,
212 cwd: str | None = None,
213 environ_update: dict[str, str] | None = None,
214 warn_on_stderr: bool = False,
215 ) -> tuple[int, list[t.Any], bytes]:
216 rc, stdout, stderr = self.call_cli(
217 *args, check_rc=check_rc, data=data, cwd=cwd, environ_update=environ_update
218 )
219 if warn_on_stderr and stderr:
220 self.warn(to_text(stderr))
221 result = []
222 try:
223 for line in stdout.splitlines():
224 line = line.strip()
225 if line.startswith(b"{"):
226 result.append(json.loads(line))
227 except Exception as exc: # pylint: disable=broad-exception-caught
228 self.fail(
229 f"Error while parsing JSON output of {self._compose_cmd_str(args)}: {exc}\nJSON output: {to_text(stdout)}\n\nError output:\n{to_text(stderr)}",
230 cmd=self._compose_cmd_str(args),
231 rc=rc,
232 stdout=stdout,
233 stderr=stderr,
234 )
235 return rc, result, stderr
236
237 @abc.abstractmethod
238 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
239 pass
240
241 @abc.abstractmethod
242 def warn(self, msg: str) -> None:
243 pass
244
245 @abc.abstractmethod
246 def deprecate(
247 self,
248 msg: str,
249 version: str | None = None,
250 date: str | None = None,
251 collection_name: str | None = None,
252 ) -> None:
253 pass
254
255 def get_cli_info(self) -> dict[str, t.Any]:
256 if self._info is None:
257 dummy, self._info, dummy2 = self.call_cli_json(
258 "info", "--format", "{{ json . }}", check_rc=True
259 )
260 return self._info
261
262 def get_client_plugin_info(self, component: str) -> dict[str, t.Any] | None:
263 cli_info = self.get_cli_info()
264 if not isinstance(cli_info.get("ClientInfo"), dict):
265 self.fail(
266 "Cannot determine Docker client information. Are you maybe using podman instead of docker?"
267 )
268 for plugin in cli_info["ClientInfo"].get("Plugins") or []:
269 if plugin.get("Name") == component:
270 return plugin
271 return None
272
273 def _image_lookup(self, name: str, tag: str) -> list[dict[str, t.Any]]:
274 """
275 Including a tag in the name parameter sent to the Docker SDK for Python images method
276 does not work consistently. Instead, get the result set for name and manually check
277 if the tag exists.
278 """
279 dummy, images, dummy2 = self.call_cli_json_stream(
280 "image",
281 "ls",
282 "--format",
283 "{{ json . }}",
284 "--no-trunc",
285 "--filter",
286 f"reference={name}",
287 check_rc=True,
288 )
289 if tag:
290 response = images
291 images = []
292 for image in response:
293 if image.get("Tag") == tag or image.get("Digest") == tag:
294 images = [image]
295 break
296 return images
297
298 @t.overload
299 def find_image(self, name: None, tag: str) -> None: ...
300
301 @t.overload
302 def find_image(self, name: str, tag: str) -> dict[str, t.Any] | None: ...
303
304 def find_image(self, name: str | None, tag: str) -> dict[str, t.Any] | None:
305 """
306 Lookup an image (by name and tag) and return the inspection results.
307 """
308 if not name:
309 return None
310
311 self.log(f"Find image {name}:{tag}")
312 images = self._image_lookup(name, tag)
313 if not images:
314 # In API <= 1.20 seeing 'docker.io/<name>' as the name of images pulled from docker hub
315 registry, repo_name = resolve_repository_name(name)
316 if registry == "docker.io":
317 # If docker.io is explicitly there in name, the image
318 # is not found in some cases (#41509)
319 self.log(f"Check for docker.io image: {repo_name}")
320 images = self._image_lookup(repo_name, tag)
321 if not images and repo_name.startswith("library/"):
322 # Sometimes library/xxx images are not found
323 lookup = repo_name[len("library/") :]
324 self.log(f"Check for docker.io image: {lookup}")
325 images = self._image_lookup(lookup, tag)
326 if not images:
327 # Last case for some Docker versions: if docker.io was not there,
328 # it can be that the image was not found either
329 # (https://github.com/ansible/ansible/pull/15586)
330 lookup = f"{registry}/{repo_name}"
331 self.log(f"Check for docker.io image: {lookup}")
332 images = self._image_lookup(lookup, tag)
333 if not images and "/" not in repo_name:
334 # This seems to be happening with podman-docker
335 # (https://github.com/ansible-collections/community.docker/issues/291)
336 lookup = f"{registry}/library/{repo_name}"
337 self.log(f"Check for docker.io image: {lookup}")
338 images = self._image_lookup(lookup, tag)
339
340 if len(images) > 1:
341 self.fail(f"Daemon returned more than one result for {name}:{tag}")
342
343 if len(images) == 1:
344 rc, image, stderr = self.call_cli_json("image", "inspect", images[0]["ID"])
345 if not image:
346 self.log(f"Image {name}:{tag} not found.")
347 return None
348 if rc != 0:
349 self.fail(f"Error inspecting image {name}:{tag} - {to_text(stderr)}")
350 return image[0]
351
352 self.log(f"Image {name}:{tag} not found.")
353 return None
354
355 @t.overload
356 def find_image_by_id(
357 self, image_id: None, accept_missing_image: bool = False
358 ) -> None: ...
359
360 @t.overload
361 def find_image_by_id(
362 self, image_id: str | None, accept_missing_image: bool = False
363 ) -> dict[str, t.Any] | None: ...
364
365 def find_image_by_id(
366 self, image_id: str | None, accept_missing_image: bool = False
367 ) -> dict[str, t.Any] | None:
368 """
369 Lookup an image (by ID) and return the inspection results.
370 """
371 if not image_id:
372 return None
373
374 self.log(f"Find image {image_id} (by ID)")
375 rc, image, stderr = self.call_cli_json("image", "inspect", image_id)
376 if not image:
377 if not accept_missing_image:
378 self.fail(f"Error inspecting image ID {image_id} - {to_text(stderr)}")
379 self.log(f"Image {image_id} not found.")
380 return None
381 if rc != 0:
382 self.fail(f"Error inspecting image ID {image_id} - {to_text(stderr)}")
383 return image[0]
384
385
386 class AnsibleModuleDockerClient(AnsibleDockerClientBase):
387 def __init__(
388 self,
389 argument_spec: dict[str, t.Any] | None = None,
390 supports_check_mode: bool = False,
391 mutually_exclusive: Sequence[Sequence[str]] | None = None,
392 required_together: Sequence[Sequence[str]] | None = None,
393 required_if: (
394 Sequence[
395 tuple[str, t.Any, Sequence[str]]
396 | tuple[str, t.Any, Sequence[str], bool]
397 ]
398 | None
399 ) = None,
400 required_one_of: Sequence[Sequence[str]] | None = None,
401 required_by: Mapping[str, Sequence[str]] | None = None,
402 min_docker_api_version: str | None = None,
403 fail_results: dict[str, t.Any] | None = None,
404 needs_api_version: bool = True,
405 ) -> None:
406 # Modules can put information in here which will always be returned
407 # in case client.fail() is called.
408 self.fail_results = fail_results or {}
409
410 merged_arg_spec = {}
411 merged_arg_spec.update(DOCKER_COMMON_ARGS)
412 if argument_spec:
413 merged_arg_spec.update(argument_spec)
414 self.arg_spec = merged_arg_spec
415
416 mutually_exclusive_params: list[Sequence[str]] = [
417 ("docker_host", "cli_context")
418 ]
419 mutually_exclusive_params += DOCKER_MUTUALLY_EXCLUSIVE
420 if mutually_exclusive:
421 mutually_exclusive_params += mutually_exclusive
422
423 required_together_params: list[Sequence[str]] = []
424 required_together_params += DOCKER_REQUIRED_TOGETHER
425 if required_together:
426 required_together_params += required_together
427
428 self.module = AnsibleModule(
429 argument_spec=merged_arg_spec,
430 supports_check_mode=supports_check_mode,
431 mutually_exclusive=mutually_exclusive_params,
432 required_together=required_together_params,
433 required_if=required_if,
434 required_one_of=required_one_of,
435 required_by=required_by or {},
436 )
437
438 self.debug = False # self.module.params['debug']
439 self.check_mode = self.module.check_mode
440 self.diff = self.module._diff
441
442 common_args = dict((k, self.module.params[k]) for k in DOCKER_COMMON_ARGS)
443 super().__init__(
444 common_args,
445 min_docker_api_version=min_docker_api_version,
446 needs_api_version=needs_api_version,
447 )
448
449 def call_cli(
450 self,
451 *args: str,
452 check_rc: bool = False,
453 data: bytes | None = None,
454 cwd: str | None = None,
455 environ_update: dict[str, str] | None = None,
456 ) -> tuple[int, bytes, bytes]:
457 environment = self._environment.copy()
458 if environ_update:
459 environment.update(environ_update)
460 rc, stdout, stderr = self.module.run_command(
461 self._compose_cmd(args),
462 binary_data=True,
463 check_rc=check_rc,
464 cwd=cwd,
465 data=data,
466 encoding=None,
467 environ_update=environment,
468 expand_user_and_vars=False,
469 ignore_invalid_cwd=False,
470 )
471 return rc, stdout, stderr
472
473 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
474 self.fail_results.update(kwargs)
475 self.module.fail_json(msg=msg, **sanitize_result(self.fail_results))
476
477 def warn(self, msg: str) -> None:
478 self.module.warn(msg)
479
480 def deprecate(
481 self,
482 msg: str,
483 version: str | None = None,
484 date: str | None = None,
485 collection_name: str | None = None,
486 ) -> None:
487 self.module.deprecate(
488 msg, version=version, date=date, collection_name=collection_name
489 )