Debian Codegraph @

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

raw
1 # Copyright 2016 Red Hat | Ansible
2 # Copyright (c) 2022 Felix Fontein <[email protected]>
3 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
4 # SPDX-License-Identifier: GPL-3.0-or-later
5
6 # Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time.
7 # Do not use this from other collections or standalone plugins/modules!
8
9 from __future__ import annotations
10
11 import abc
12 import os
13 import re
14 import typing as t
15 from collections.abc import Mapping, Sequence
16
17 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
18 from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
19
20 from ansible_collections.community.docker.plugins.module_utils._version import (
21 LooseVersion,
22 )
23
24 try:
25 from requests.exceptions import ( # noqa: F401, pylint: disable=unused-import
26 RequestException,
27 SSLError,
28 )
29 except ImportError:
30 # Define an exception class RequestException so that our code does not break.
31 class RequestException(Exception): # type: ignore
32 pass
33
34
35 from ansible_collections.community.docker.plugins.module_utils._api import auth
36 from ansible_collections.community.docker.plugins.module_utils._api.api.client import (
37 APIClient as Client,
38 )
39 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
40 APIError,
41 MissingRequirementException,
42 NotFound,
43 TLSParameterError,
44 )
45 from ansible_collections.community.docker.plugins.module_utils._api.tls import TLSConfig
46 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
47 convert_filters,
48 parse_repository_tag,
49 )
50 from ansible_collections.community.docker.plugins.module_utils._util import (
51 DEFAULT_DOCKER_HOST,
52 DEFAULT_TIMEOUT_SECONDS,
53 DEFAULT_TLS,
54 DEFAULT_TLS_VERIFY,
55 DOCKER_COMMON_ARGS,
56 DOCKER_MUTUALLY_EXCLUSIVE,
57 DOCKER_REQUIRED_TOGETHER,
58 sanitize_result,
59 update_tls_hostname,
60 )
61
62 if t.TYPE_CHECKING:
63 from collections.abc import Callable
64
65
66 def _get_tls_config(
67 fail_function: Callable[[str], t.NoReturn], **kwargs: t.Any
68 ) -> TLSConfig:
69 try:
70 return TLSConfig(**kwargs)
71 except TLSParameterError as exc:
72 fail_function(f"TLS config error: {exc}")
73
74
75 def is_using_tls(auth_data: dict[str, t.Any]) -> bool:
76 return auth_data["tls_verify"] or auth_data["tls"]
77
78
79 def get_connect_params(
80 auth_data: dict[str, t.Any], fail_function: Callable[[str], t.NoReturn]
81 ) -> dict[str, t.Any]:
82 if is_using_tls(auth_data):
83 auth_data["docker_host"] = auth_data["docker_host"].replace(
84 "tcp://", "https://"
85 )
86
87 result = {
88 "base_url": auth_data["docker_host"],
89 "version": auth_data["api_version"],
90 "timeout": auth_data["timeout"],
91 }
92
93 if auth_data["tls_verify"]:
94 # TLS with verification
95 tls_config = {
96 "verify": True,
97 "assert_hostname": auth_data["tls_hostname"],
98 "fail_function": fail_function,
99 }
100 if auth_data["cert_path"] and auth_data["key_path"]:
101 tls_config["client_cert"] = (auth_data["cert_path"], auth_data["key_path"])
102 if auth_data["cacert_path"]:
103 tls_config["ca_cert"] = auth_data["cacert_path"]
104 result["tls"] = _get_tls_config(**tls_config)
105 elif auth_data["tls"]:
106 # TLS without verification
107 tls_config = {
108 "verify": False,
109 "fail_function": fail_function,
110 }
111 if auth_data["cert_path"] and auth_data["key_path"]:
112 tls_config["client_cert"] = (auth_data["cert_path"], auth_data["key_path"])
113 result["tls"] = _get_tls_config(**tls_config)
114
115 if auth_data.get("use_ssh_client"):
116 result["use_ssh_client"] = True
117
118 # No TLS
119 return result
120
121
122 class AnsibleDockerClientBase(Client):
123 def __init__(self, min_docker_api_version: str | None = None) -> None:
124 self._connect_params = get_connect_params(
125 self.auth_params, fail_function=self.fail
126 )
127
128 try:
129 super().__init__(**self._connect_params)
130 self.docker_api_version_str = self.api_version
131 except MissingRequirementException as exc:
132 self.fail(
133 missing_required_lib(exc.requirement), exception=exc.import_exception
134 )
135 except APIError as exc:
136 self.fail(f"Docker API error: {exc}")
137 except Exception as exc: # pylint: disable=broad-exception-caught
138 self.fail(f"Error connecting: {exc}")
139
140 self.docker_api_version = LooseVersion(self.docker_api_version_str)
141 min_docker_api_version = min_docker_api_version or "1.25"
142 if self.docker_api_version < LooseVersion(min_docker_api_version):
143 self.fail(
144 f"Docker API version is {self.docker_api_version_str}. Minimum version required is {min_docker_api_version}."
145 )
146
147 def log(self, msg: t.Any, pretty_print: bool = False) -> None:
148 pass
149 # if self.debug:
150 # from .util import log_debug
151 # log_debug(msg, pretty_print=pretty_print)
152
153 @abc.abstractmethod
154 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
155 pass
156
157 @abc.abstractmethod
158 def deprecate(
159 self,
160 msg: str,
161 version: str | None = None,
162 date: str | None = None,
163 collection_name: str | None = None,
164 ) -> None:
165 pass
166
167 @staticmethod
168 def _get_value(
169 param_name: str,
170 param_value: t.Any,
171 env_variable: str | None,
172 default_value: t.Any | None,
173 value_type: t.Literal["str", "bool", "int"] = "str",
174 ) -> t.Any:
175 if param_value is not None:
176 # take module parameter value
177 if value_type == "bool":
178 if param_value in BOOLEANS_TRUE:
179 return True
180 if param_value in BOOLEANS_FALSE:
181 return False
182 return bool(param_value)
183 if value_type == "int":
184 return int(param_value)
185 return param_value
186
187 if env_variable is not None:
188 env_value = os.environ.get(env_variable)
189 if env_value is not None:
190 # take the env variable value
191 if param_name == "cert_path":
192 return os.path.join(env_value, "cert.pem")
193 if param_name == "cacert_path":
194 return os.path.join(env_value, "ca.pem")
195 if param_name == "key_path":
196 return os.path.join(env_value, "key.pem")
197 if value_type == "bool":
198 if env_value in BOOLEANS_TRUE:
199 return True
200 if env_value in BOOLEANS_FALSE:
201 return False
202 return bool(env_value)
203 if value_type == "int":
204 return int(env_value)
205 return env_value
206
207 # take the default
208 return default_value
209
210 @abc.abstractmethod
211 def _get_params(self) -> dict[str, t.Any]:
212 pass
213
214 @property
215 def auth_params(self) -> dict[str, t.Any]:
216 # Get authentication credentials.
217 # Precedence: module parameters-> environment variables-> defaults.
218
219 self.log("Getting credentials")
220
221 client_params = self._get_params()
222
223 params = {}
224 for key in DOCKER_COMMON_ARGS:
225 params[key] = client_params.get(key)
226
227 result = {
228 "docker_host": self._get_value(
229 "docker_host",
230 params["docker_host"],
231 "DOCKER_HOST",
232 DEFAULT_DOCKER_HOST,
233 value_type="str",
234 ),
235 "tls_hostname": self._get_value(
236 "tls_hostname",
237 params["tls_hostname"],
238 "DOCKER_TLS_HOSTNAME",
239 None,
240 value_type="str",
241 ),
242 "api_version": self._get_value(
243 "api_version",
244 params["api_version"],
245 "DOCKER_API_VERSION",
246 "auto",
247 value_type="str",
248 ),
249 "cacert_path": self._get_value(
250 "cacert_path",
251 params["ca_path"],
252 "DOCKER_CERT_PATH",
253 None,
254 value_type="str",
255 ),
256 "cert_path": self._get_value(
257 "cert_path",
258 params["client_cert"],
259 "DOCKER_CERT_PATH",
260 None,
261 value_type="str",
262 ),
263 "key_path": self._get_value(
264 "key_path",
265 params["client_key"],
266 "DOCKER_CERT_PATH",
267 None,
268 value_type="str",
269 ),
270 "tls": self._get_value(
271 "tls", params["tls"], "DOCKER_TLS", DEFAULT_TLS, value_type="bool"
272 ),
273 "tls_verify": self._get_value(
274 "validate_certs",
275 params["validate_certs"],
276 "DOCKER_TLS_VERIFY",
277 DEFAULT_TLS_VERIFY,
278 value_type="bool",
279 ),
280 "timeout": self._get_value(
281 "timeout",
282 params["timeout"],
283 "DOCKER_TIMEOUT",
284 DEFAULT_TIMEOUT_SECONDS,
285 value_type="int",
286 ),
287 "use_ssh_client": self._get_value(
288 "use_ssh_client",
289 params["use_ssh_client"],
290 None,
291 False,
292 value_type="bool",
293 ),
294 }
295
296 def depr(*args: t.Any, **kwargs: t.Any) -> None:
297 self.deprecate(*args, **kwargs)
298
299 update_tls_hostname(
300 result,
301 old_behavior=True,
302 deprecate_function=depr,
303 uses_tls=is_using_tls(result),
304 )
305
306 return result
307
308 def _handle_ssl_error(self, error: Exception) -> t.NoReturn:
309 match = re.match(r"hostname.*doesn\'t match (\'.*\')", str(error))
310 if match:
311 hostname = self.auth_params["tls_hostname"]
312 self.fail(
313 f"You asked for verification that Docker daemons certificate's hostname matches {hostname}. "
314 f"The actual certificate's hostname is {match.group(1)}. Most likely you need to set DOCKER_TLS_HOSTNAME "
315 f"or pass `tls_hostname` with a value of {match.group(1)}. You may also use TLS without verification by "
316 "setting the `tls` parameter to true."
317 )
318 self.fail(f"SSL Exception: {error}")
319
320 def get_container_by_id(self, container_id: str) -> dict[str, t.Any] | None:
321 try:
322 self.log(f"Inspecting container Id {container_id}")
323 result = self.get_json("/containers/{0}/json", container_id)
324 self.log("Completed container inspection")
325 return result
326 except NotFound:
327 return None
328 except Exception as exc: # pylint: disable=broad-exception-caught
329 self.fail(f"Error inspecting container: {exc}")
330
331 def get_container(self, name: str | None) -> dict[str, t.Any] | None:
332 """
333 Lookup a container and return the inspection results.
334 """
335 if name is None:
336 return None
337
338 search_name = name
339 if not name.startswith("/"):
340 search_name = "/" + name
341
342 result = None
343 try:
344 params = {
345 "limit": -1,
346 "all": 1,
347 "size": 0,
348 "trunc_cmd": 0,
349 }
350 containers = self.get_json("/containers/json", params=params)
351 for container in containers:
352 self.log(f"testing container: {container['Names']}")
353 if (
354 isinstance(container["Names"], list)
355 and search_name in container["Names"]
356 ):
357 result = container
358 break
359 if container["Id"].startswith(name):
360 result = container
361 break
362 if container["Id"] == name:
363 result = container
364 break
365 except SSLError as exc:
366 self._handle_ssl_error(exc)
367 except Exception as exc: # pylint: disable=broad-exception-caught
368 self.fail(f"Error retrieving container list: {exc}")
369
370 if result is None:
371 return None
372
373 return self.get_container_by_id(result["Id"])
374
375 def get_network(
376 self, name: str | None = None, network_id: str | None = None
377 ) -> dict[str, t.Any] | None:
378 """
379 Lookup a network and return the inspection results.
380 """
381 if name is None and network_id is None:
382 return None
383
384 result = None
385
386 if network_id is None:
387 try:
388 networks = self.get_json("/networks")
389 for network in networks:
390 self.log(f"testing network: {network['Name']}")
391 if name == network["Name"]:
392 result = network
393 break
394 if network["Id"].startswith(name):
395 result = network
396 break
397 except SSLError as exc:
398 self._handle_ssl_error(exc)
399 except Exception as exc: # pylint: disable=broad-exception-caught
400 self.fail(f"Error retrieving network list: {exc}")
401
402 if result is not None:
403 network_id = result["Id"]
404
405 if network_id is not None:
406 try:
407 self.log(f"Inspecting network Id {network_id}")
408 result = self.get_json("/networks/{0}", network_id)
409 self.log("Completed network inspection")
410 except NotFound:
411 return None
412 except Exception as exc: # pylint: disable=broad-exception-caught
413 self.fail(f"Error inspecting network: {exc}")
414
415 return result
416
417 def _image_lookup(self, name: str, tag: str | None) -> list[dict[str, t.Any]]:
418 """
419 Including a tag in the name parameter sent to the Docker SDK for Python images method
420 does not work consistently. Instead, get the result set for name and manually check
421 if the tag exists.
422 """
423 try:
424 params: dict[str, t.Any] = {
425 "only_ids": 0,
426 "all": 0,
427 }
428 if LooseVersion(self.api_version) < LooseVersion("1.25"):
429 # only use "filter" on API 1.24 and under, as it is deprecated
430 params["filter"] = name
431 else:
432 params["filters"] = convert_filters({"reference": name})
433 images = self.get_json("/images/json", params=params)
434 except Exception as exc: # pylint: disable=broad-exception-caught
435 self.fail(f"Error searching for image {name} - {exc}")
436 if tag:
437 lookup = f"{name}:{tag}"
438 lookup_digest = f"{name}@{tag}"
439 response = images
440 images = []
441 for image in response:
442 tags = image.get("RepoTags")
443 digests = image.get("RepoDigests")
444 if (tags and lookup in tags) or (digests and lookup_digest in digests):
445 images = [image]
446 break
447 return images
448
449 def find_image(self, name: str, tag: str | None) -> dict[str, t.Any] | None:
450 """
451 Lookup an image (by name and tag) and return the inspection results.
452 """
453 if not name:
454 return None
455
456 self.log(f"Find image {name}:{tag}")
457 images = self._image_lookup(name, tag)
458 if not images:
459 # In API <= 1.20 seeing 'docker.io/<name>' as the name of images pulled from docker hub
460 registry, repo_name = auth.resolve_repository_name(name)
461 if registry == "docker.io":
462 # If docker.io is explicitly there in name, the image
463 # is not found in some cases (#41509)
464 self.log(f"Check for docker.io image: {repo_name}")
465 images = self._image_lookup(repo_name, tag)
466 if not images and repo_name.startswith("library/"):
467 # Sometimes library/xxx images are not found
468 lookup = repo_name[len("library/") :]
469 self.log(f"Check for docker.io image: {lookup}")
470 images = self._image_lookup(lookup, tag)
471 if not images:
472 # Last case for some Docker versions: if docker.io was not there,
473 # it can be that the image was not found either
474 # (https://github.com/ansible/ansible/pull/15586)
475 lookup = f"{registry}/{repo_name}"
476 self.log(f"Check for docker.io image: {lookup}")
477 images = self._image_lookup(lookup, tag)
478 if not images and "/" not in repo_name:
479 # This seems to be happening with podman-docker
480 # (https://github.com/ansible-collections/community.docker/issues/291)
481 lookup = f"{registry}/library/{repo_name}"
482 self.log(f"Check for docker.io image: {lookup}")
483 images = self._image_lookup(lookup, tag)
484
485 if len(images) > 1:
486 self.fail(f"Daemon returned more than one result for {name}:{tag}")
487
488 if len(images) == 1:
489 try:
490 return self.get_json("/images/{0}/json", images[0]["Id"])
491 except NotFound:
492 self.log(f"Image {name}:{tag} not found.")
493 return None
494 except Exception as exc: # pylint: disable=broad-exception-caught
495 self.fail(f"Error inspecting image {name}:{tag} - {exc}")
496
497 self.log(f"Image {name}:{tag} not found.")
498 return None
499
500 def find_image_by_id(
501 self, image_id: str, accept_missing_image: bool = False
502 ) -> dict[str, t.Any] | None:
503 """
504 Lookup an image (by ID) and return the inspection results.
505 """
506 if not image_id:
507 return None
508
509 self.log(f"Find image {image_id} (by ID)")
510 try:
511 return self.get_json("/images/{0}/json", image_id)
512 except NotFound as exc:
513 if not accept_missing_image:
514 self.fail(f"Error inspecting image ID {image_id} - {exc}")
515 self.log(f"Image {image_id} not found.")
516 return None
517 except Exception as exc: # pylint: disable=broad-exception-caught
518 self.fail(f"Error inspecting image ID {image_id} - {exc}")
519
520 @staticmethod
521 def _compare_images(
522 img1: dict[str, t.Any] | None, img2: dict[str, t.Any] | None
523 ) -> bool:
524 if img1 is None or img2 is None:
525 return img1 == img2
526 filter_keys = {"Metadata", "Identity"}
527 # Since Docker 29.2 (?) the order of entries in Identity.Pull can change
528 # even though the image is the same. Since we're only really interested
529 # in the image's Id field, we simply skip all of Identity.
530 img1_filtered = {k: v for k, v in img1.items() if k not in filter_keys}
531 img2_filtered = {k: v for k, v in img2.items() if k not in filter_keys}
532 return img1_filtered == img2_filtered
533
534 def pull_image(
535 self, name: str, tag: str = "latest", image_platform: str | None = None
536 ) -> tuple[dict[str, t.Any] | None, bool]:
537 """
538 Pull an image
539 """
540 self.log(f"Pulling image {name}:{tag}")
541 old_image = self.find_image(name, tag)
542 try:
543 repository, image_tag = parse_repository_tag(name)
544 registry, dummy_repo_name = auth.resolve_repository_name(repository)
545 params = {
546 "tag": tag or image_tag or "latest",
547 "fromImage": repository,
548 }
549 if image_platform is not None:
550 params["platform"] = image_platform
551
552 headers = {}
553 header = auth.get_config_header(self, registry)
554 if header:
555 headers["X-Registry-Auth"] = header
556
557 response = self._post(
558 self._url("/images/create"),
559 params=params,
560 headers=headers,
561 stream=True,
562 timeout=None,
563 )
564 self._raise_for_status(response)
565 for line in self._stream_helper(response, decode=True):
566 self.log(line, pretty_print=True)
567 if line.get("error"):
568 if line.get("errorDetail"):
569 error_detail = line.get("errorDetail")
570 self.fail(
571 f"Error pulling {name} - code: {error_detail.get('code')} message: {error_detail.get('message')}"
572 )
573 else:
574 self.fail(f"Error pulling {name} - {line.get('error')}")
575 except Exception as exc: # pylint: disable=broad-exception-caught
576 self.fail(f"Error pulling image {name}:{tag} - {exc}")
577
578 new_image = self.find_image(name, tag)
579
580 return new_image, self._compare_images(old_image, new_image)
581
582
583 class AnsibleDockerClient(AnsibleDockerClientBase):
584 def __init__(
585 self,
586 argument_spec: dict[str, t.Any] | None = None,
587 supports_check_mode: bool = False,
588 mutually_exclusive: Sequence[Sequence[str]] | None = None,
589 required_together: Sequence[Sequence[str]] | None = None,
590 required_if: (
591 Sequence[
592 tuple[str, t.Any, Sequence[str]]
593 | tuple[str, t.Any, Sequence[str], bool]
594 ]
595 | None
596 ) = None,
597 required_one_of: Sequence[Sequence[str]] | None = None,
598 required_by: dict[str, Sequence[str]] | None = None,
599 min_docker_api_version: str | None = None,
600 option_minimal_versions: dict[str, t.Any] | None = None,
601 option_minimal_versions_ignore_params: Sequence[str] | None = None,
602 fail_results: dict[str, t.Any] | None = None,
603 ):
604 # Modules can put information in here which will always be returned
605 # in case client.fail() is called.
606 self.fail_results = fail_results or {}
607
608 merged_arg_spec = {}
609 merged_arg_spec.update(DOCKER_COMMON_ARGS)
610 if argument_spec:
611 merged_arg_spec.update(argument_spec)
612 self.arg_spec = merged_arg_spec
613
614 mutually_exclusive_params: list[Sequence[str]] = []
615 mutually_exclusive_params += DOCKER_MUTUALLY_EXCLUSIVE
616 if mutually_exclusive:
617 mutually_exclusive_params += mutually_exclusive
618
619 required_together_params: list[Sequence[str]] = []
620 required_together_params += DOCKER_REQUIRED_TOGETHER
621 if required_together:
622 required_together_params += required_together
623
624 self.module = AnsibleModule(
625 argument_spec=merged_arg_spec,
626 supports_check_mode=supports_check_mode,
627 mutually_exclusive=mutually_exclusive_params,
628 required_together=required_together_params,
629 required_if=required_if,
630 required_one_of=required_one_of,
631 required_by=required_by or {},
632 )
633
634 self.debug = self.module.params.get("debug")
635 self.check_mode = self.module.check_mode
636
637 super().__init__(min_docker_api_version=min_docker_api_version)
638
639 if option_minimal_versions is not None:
640 self._get_minimal_versions(
641 option_minimal_versions, option_minimal_versions_ignore_params
642 )
643
644 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
645 self.fail_results.update(kwargs)
646 self.module.fail_json(msg=msg, **sanitize_result(self.fail_results))
647
648 def deprecate(
649 self,
650 msg: str,
651 version: str | None = None,
652 date: str | None = None,
653 collection_name: str | None = None,
654 ) -> None:
655 self.module.deprecate(
656 msg, version=version, date=date, collection_name=collection_name
657 )
658
659 def _get_params(self) -> dict[str, t.Any]:
660 return self.module.params
661
662 def _get_minimal_versions(
663 self,
664 option_minimal_versions: dict[str, t.Any],
665 ignore_params: Sequence[str] | None = None,
666 ) -> None:
667 self.option_minimal_versions: dict[str, dict[str, t.Any]] = {}
668 for option in self.module.argument_spec:
669 if ignore_params is not None and option in ignore_params:
670 continue
671 self.option_minimal_versions[option] = {}
672 self.option_minimal_versions.update(option_minimal_versions)
673
674 for option, data in self.option_minimal_versions.items():
675 # Test whether option is supported, and store result
676 support_docker_api = True
677 if "docker_api_version" in data:
678 support_docker_api = self.docker_api_version >= LooseVersion(
679 data["docker_api_version"]
680 )
681 data["supported"] = support_docker_api
682 # Fail if option is not supported but used
683 if not data["supported"]:
684 # Test whether option is specified
685 if "detect_usage" in data:
686 used = data["detect_usage"](self)
687 else:
688 used = self.module.params.get(option) is not None
689 if used and "default" in self.module.argument_spec[option]:
690 used = (
691 self.module.params[option]
692 != self.module.argument_spec[option]["default"]
693 )
694 if used:
695 # If the option is used, compose error message.
696 if "usage_msg" in data:
697 usg = data["usage_msg"]
698 else:
699 usg = f"set {option} option"
700 if not support_docker_api:
701 msg = f"Docker API version is {self.docker_api_version_str}. Minimum version required is {data['docker_api_version']} to {usg}."
702 else:
703 # should not happen
704 msg = f"Cannot {usg} with your configuration."
705 self.fail(msg)
706
707 def report_warnings(
708 self, result: t.Any, warnings_key: Sequence[str] | None = None
709 ) -> None:
710 """
711 Checks result of client operation for warnings, and if present, outputs them.
712
713 warnings_key should be a list of keys used to crawl the result dictionary.
714 For example, if warnings_key == ['a', 'b'], the function will consider
715 result['a']['b'] if these keys exist. If the result is a non-empty string, it
716 will be reported as a warning. If the result is a list, every entry will be
717 reported as a warning.
718
719 In most cases (if warnings are returned at all), warnings_key should be
720 ['Warnings'] or ['Warning']. The default value (if not specified) is ['Warnings'].
721 """
722 if warnings_key is None:
723 warnings_key = ["Warnings"]
724 for key in warnings_key:
725 if not isinstance(result, Mapping):
726 return
727 result = result.get(key)
728 if isinstance(result, Sequence):
729 for warning in result:
730 self.module.warn(f"Docker warning: {warning}")
731 elif isinstance(result, str) and result:
732 self.module.warn(f"Docker warning: {result}")