Debian Codegraph @

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

raw
1 # Copyright 2016 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 abc
11 import os
12 import platform
13 import re
14 import sys
15 import traceback
16 import typing as t
17 from collections.abc import Mapping, Sequence
18
19 from ansible.module_utils.basic import AnsibleModule, missing_required_lib
20 from ansible.module_utils.parsing.convert_bool import BOOLEANS_FALSE, BOOLEANS_TRUE
21
22 from ansible_collections.community.docker.plugins.module_utils._util import (
23 DEFAULT_DOCKER_HOST,
24 DEFAULT_TIMEOUT_SECONDS,
25 DEFAULT_TLS,
26 DEFAULT_TLS_VERIFY,
27 DOCKER_COMMON_ARGS,
28 DOCKER_MUTUALLY_EXCLUSIVE,
29 DOCKER_REQUIRED_TOGETHER,
30 sanitize_result,
31 update_tls_hostname,
32 )
33 from ansible_collections.community.docker.plugins.module_utils._version import (
34 LooseVersion,
35 )
36
37 HAS_DOCKER_PY_2 = False # pylint: disable=invalid-name
38 HAS_DOCKER_PY_3 = False # pylint: disable=invalid-name
39 HAS_DOCKER_ERROR: None | str # pylint: disable=invalid-name
40 HAS_DOCKER_TRACEBACK: None | str # pylint: disable=invalid-name
41 docker_version: str | None # pylint: disable=invalid-name
42
43 try:
44 from docker import __version__ as docker_version
45 from docker.errors import APIError, TLSParameterError
46 from docker.tls import TLSConfig
47
48 if LooseVersion(docker_version) >= LooseVersion("3.0.0"):
49 HAS_DOCKER_PY_3 = True # pylint: disable=invalid-name
50 from docker import APIClient as Client
51 elif LooseVersion(docker_version) >= LooseVersion("2.0.0"):
52 HAS_DOCKER_PY_2 = True # pylint: disable=invalid-name
53 from docker import APIClient as Client
54 else:
55 from docker import Client # type: ignore
56
57 except ImportError as exc:
58 HAS_DOCKER_ERROR = str(exc) # pylint: disable=invalid-name
59 HAS_DOCKER_TRACEBACK = traceback.format_exc() # pylint: disable=invalid-name
60 HAS_DOCKER_PY = False # pylint: disable=invalid-name
61 docker_version = None # pylint: disable=invalid-name
62 else:
63 HAS_DOCKER_PY = True # pylint: disable=invalid-name
64 HAS_DOCKER_ERROR = None # pylint: disable=invalid-name
65 HAS_DOCKER_TRACEBACK = None # pylint: disable=invalid-name
66
67
68 try:
69 from requests.exceptions import ( # noqa: F401, pylint: disable=unused-import
70 RequestException,
71 )
72 except ImportError:
73 # Either Docker SDK for Python is no longer using requests, or Docker SDK for Python is not around either,
74 # or Docker SDK for Python's dependency requests is missing. In any case, define an exception
75 # class RequestException so that our code does not break.
76 class RequestException(Exception): # type: ignore
77 pass
78
79
80 if t.TYPE_CHECKING:
81 from collections.abc import Callable
82
83
84 MIN_DOCKER_VERSION = "2.0.0"
85
86
87 if not HAS_DOCKER_PY:
88 # No Docker SDK for Python. Create a place holder client to allow
89 # instantiation of AnsibleModule and proper error handing
90 class Client: # type: ignore # noqa: F811, pylint: disable=function-redefined
91 def __init__(self, **kwargs: t.Any) -> None:
92 pass
93
94 class APIError(Exception): # type: ignore # noqa: F811, pylint: disable=function-redefined
95 pass
96
97 class NotFound(Exception): # type: ignore # noqa: F811, pylint: disable=function-redefined
98 pass
99
100
101 def _get_tls_config(
102 fail_function: Callable[[str], t.NoReturn], **kwargs: t.Any
103 ) -> TLSConfig:
104 if "assert_hostname" in kwargs and LooseVersion(docker_version) >= LooseVersion(
105 "7.0.0b1"
106 ):
107 assert_hostname = kwargs.pop("assert_hostname")
108 if assert_hostname is not None:
109 fail_function(
110 "tls_hostname is not compatible with Docker SDK for Python 7.0.0+. You are using"
111 f" Docker SDK for Python {docker_version}. The tls_hostname option (value: {assert_hostname})"
112 " has either been set directly or with the environment variable DOCKER_TLS_HOSTNAME."
113 " Make sure it is not set, or switch to an older version of Docker SDK for Python."
114 )
115 # Filter out all None parameters
116 kwargs = dict((k, v) for k, v in kwargs.items() if v is not None)
117 try:
118 return TLSConfig(**kwargs)
119 except TLSParameterError as exc:
120 fail_function(f"TLS config error: {exc}")
121
122
123 def is_using_tls(auth_data: dict[str, t.Any]) -> bool:
124 return auth_data["tls_verify"] or auth_data["tls"]
125
126
127 def get_connect_params(
128 auth_data: dict[str, t.Any], fail_function: Callable[[str], t.NoReturn]
129 ) -> dict[str, t.Any]:
130 if is_using_tls(auth_data):
131 auth_data["docker_host"] = auth_data["docker_host"].replace(
132 "tcp://", "https://"
133 )
134
135 result = {
136 "base_url": auth_data["docker_host"],
137 "version": auth_data["api_version"],
138 "timeout": auth_data["timeout"],
139 }
140
141 if auth_data["tls_verify"]:
142 # TLS with verification
143 tls_config: dict[str, t.Any] = {
144 "verify": True,
145 }
146 if auth_data["tls_hostname"] is not None:
147 tls_config["assert_hostname"] = auth_data["tls_hostname"]
148 if auth_data["cert_path"] and auth_data["key_path"]:
149 tls_config["client_cert"] = (auth_data["cert_path"], auth_data["key_path"])
150 if auth_data["cacert_path"]:
151 tls_config["ca_cert"] = auth_data["cacert_path"]
152 result["tls"] = _get_tls_config(fail_function=fail_function, **tls_config)
153 elif auth_data["tls"]:
154 # TLS without verification
155 tls_config = {
156 "verify": False,
157 }
158 if auth_data["cert_path"] and auth_data["key_path"]:
159 tls_config["client_cert"] = (auth_data["cert_path"], auth_data["key_path"])
160 result["tls"] = _get_tls_config(fail_function=fail_function, **tls_config)
161
162 if auth_data.get("use_ssh_client"):
163 if LooseVersion(docker_version) < LooseVersion("4.4.0"):
164 fail_function(
165 "use_ssh_client=True requires Docker SDK for Python 4.4.0 or newer"
166 )
167 result["use_ssh_client"] = True
168
169 # No TLS
170 return result
171
172
173 DOCKERPYUPGRADE_SWITCH_TO_DOCKER = (
174 "Try `pip uninstall docker-py` followed by `pip install docker`."
175 )
176 DOCKERPYUPGRADE_UPGRADE_DOCKER = "Use `pip install --upgrade docker` to upgrade."
177
178
179 class AnsibleDockerClientBase(Client):
180 def __init__(
181 self,
182 min_docker_version: str | None = None,
183 min_docker_api_version: str | None = None,
184 ) -> None:
185 if min_docker_version is None:
186 min_docker_version = MIN_DOCKER_VERSION
187
188 self.docker_py_version = LooseVersion(docker_version)
189
190 if not HAS_DOCKER_PY:
191 msg = missing_required_lib("Docker SDK for Python: docker>=5.0.0")
192 msg = f"{msg}, for example via `pip install docker`. The error was: {HAS_DOCKER_ERROR}"
193 self.fail(msg, exception=HAS_DOCKER_TRACEBACK)
194
195 if self.docker_py_version < LooseVersion(min_docker_version):
196 msg = (
197 f"Error: Docker SDK for Python version is {docker_version} ({platform.node()}'s Python {sys.executable})."
198 f" Minimum version required is {min_docker_version}."
199 )
200 if docker_version < LooseVersion("2.0"):
201 msg += DOCKERPYUPGRADE_SWITCH_TO_DOCKER
202 else:
203 msg += DOCKERPYUPGRADE_UPGRADE_DOCKER
204 self.fail(msg)
205
206 self._connect_params = get_connect_params(
207 self.auth_params, fail_function=self.fail
208 )
209
210 try:
211 super().__init__(**self._connect_params)
212 self.docker_api_version_str = self.api_version
213 except APIError as exc:
214 self.fail(f"Docker API error: {exc}")
215 except Exception as exc: # pylint: disable=broad-exception-caught
216 self.fail(f"Error connecting: {exc}")
217
218 self.docker_api_version = LooseVersion(self.docker_api_version_str)
219 min_docker_api_version = min_docker_api_version or "1.25"
220 if self.docker_api_version < LooseVersion(min_docker_api_version):
221 self.fail(
222 f"Docker API version is {self.docker_api_version_str}. Minimum version required is {min_docker_api_version}."
223 )
224
225 def log(self, msg: t.Any, pretty_print: bool = False) -> None:
226 pass
227 # if self.debug:
228 # from .util import log_debug
229 # log_debug(msg, pretty_print=pretty_print)
230
231 @abc.abstractmethod
232 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
233 pass
234
235 @abc.abstractmethod
236 def deprecate(
237 self,
238 msg: str,
239 version: str | None = None,
240 date: str | None = None,
241 collection_name: str | None = None,
242 ) -> None:
243 pass
244
245 @staticmethod
246 def _get_value(
247 param_name: str,
248 param_value: t.Any,
249 env_variable: str | None,
250 default_value: t.Any | None,
251 value_type: t.Literal["str", "bool", "int"] = "str",
252 ) -> t.Any:
253 if param_value is not None:
254 # take module parameter value
255 if value_type == "bool":
256 if param_value in BOOLEANS_TRUE:
257 return True
258 if param_value in BOOLEANS_FALSE:
259 return False
260 return bool(param_value)
261 if value_type == "int":
262 return int(param_value)
263 return param_value
264
265 if env_variable is not None:
266 env_value = os.environ.get(env_variable)
267 if env_value is not None:
268 # take the env variable value
269 if param_name == "cert_path":
270 return os.path.join(env_value, "cert.pem")
271 if param_name == "cacert_path":
272 return os.path.join(env_value, "ca.pem")
273 if param_name == "key_path":
274 return os.path.join(env_value, "key.pem")
275 if value_type == "bool":
276 if env_value in BOOLEANS_TRUE:
277 return True
278 if env_value in BOOLEANS_FALSE:
279 return False
280 return bool(env_value)
281 if value_type == "int":
282 return int(env_value)
283 return env_value
284
285 # take the default
286 return default_value
287
288 @abc.abstractmethod
289 def _get_params(self) -> dict[str, t.Any]:
290 pass
291
292 @property
293 def auth_params(self) -> dict[str, t.Any]:
294 # Get authentication credentials.
295 # Precedence: module parameters-> environment variables-> defaults.
296
297 self.log("Getting credentials")
298
299 client_params = self._get_params()
300
301 params = {}
302 for key in DOCKER_COMMON_ARGS:
303 params[key] = client_params.get(key)
304
305 result = {
306 "docker_host": self._get_value(
307 "docker_host",
308 params["docker_host"],
309 "DOCKER_HOST",
310 DEFAULT_DOCKER_HOST,
311 value_type="str",
312 ),
313 "tls_hostname": self._get_value(
314 "tls_hostname",
315 params["tls_hostname"],
316 "DOCKER_TLS_HOSTNAME",
317 None,
318 value_type="str",
319 ),
320 "api_version": self._get_value(
321 "api_version",
322 params["api_version"],
323 "DOCKER_API_VERSION",
324 "auto",
325 value_type="str",
326 ),
327 "cacert_path": self._get_value(
328 "cacert_path",
329 params["ca_path"],
330 "DOCKER_CERT_PATH",
331 None,
332 value_type="str",
333 ),
334 "cert_path": self._get_value(
335 "cert_path",
336 params["client_cert"],
337 "DOCKER_CERT_PATH",
338 None,
339 value_type="str",
340 ),
341 "key_path": self._get_value(
342 "key_path",
343 params["client_key"],
344 "DOCKER_CERT_PATH",
345 None,
346 value_type="str",
347 ),
348 "tls": self._get_value(
349 "tls", params["tls"], "DOCKER_TLS", DEFAULT_TLS, value_type="bool"
350 ),
351 "tls_verify": self._get_value(
352 "validate_certs",
353 params["validate_certs"],
354 "DOCKER_TLS_VERIFY",
355 DEFAULT_TLS_VERIFY,
356 value_type="bool",
357 ),
358 "timeout": self._get_value(
359 "timeout",
360 params["timeout"],
361 "DOCKER_TIMEOUT",
362 DEFAULT_TIMEOUT_SECONDS,
363 value_type="int",
364 ),
365 "use_ssh_client": self._get_value(
366 "use_ssh_client",
367 params["use_ssh_client"],
368 None,
369 False,
370 value_type="bool",
371 ),
372 }
373
374 if LooseVersion(docker_version) < LooseVersion("7.0.0b1"):
375 update_tls_hostname(result)
376
377 return result
378
379 def _handle_ssl_error(self, error: Exception) -> t.NoReturn:
380 match = re.match(r"hostname.*doesn\'t match (\'.*\')", str(error))
381 if match:
382 hostname = self.auth_params["tls_hostname"]
383 self.fail(
384 f"You asked for verification that Docker daemons certificate's hostname matches {hostname}. "
385 f"The actual certificate's hostname is {match.group(1)}. Most likely you need to set DOCKER_TLS_HOSTNAME "
386 f"or pass `tls_hostname` with a value of {match.group(1)}. You may also use TLS without verification by "
387 "setting the `tls` parameter to true."
388 )
389 self.fail(f"SSL Exception: {error}")
390
391
392 class AnsibleDockerClient(AnsibleDockerClientBase):
393 def __init__(
394 self,
395 argument_spec: dict[str, t.Any] | None = None,
396 supports_check_mode: bool = False,
397 mutually_exclusive: Sequence[Sequence[str]] | None = None,
398 required_together: Sequence[Sequence[str]] | None = None,
399 required_if: (
400 Sequence[
401 tuple[str, t.Any, Sequence[str]]
402 | tuple[str, t.Any, Sequence[str], bool]
403 ]
404 | None
405 ) = None,
406 required_one_of: Sequence[Sequence[str]] | None = None,
407 required_by: dict[str, Sequence[str]] | None = None,
408 min_docker_version: str | None = None,
409 min_docker_api_version: str | None = None,
410 option_minimal_versions: dict[str, t.Any] | None = None,
411 option_minimal_versions_ignore_params: Sequence[str] | None = None,
412 fail_results: dict[str, t.Any] | None = None,
413 ):
414 # Modules can put information in here which will always be returned
415 # in case client.fail() is called.
416 self.fail_results = fail_results or {}
417
418 merged_arg_spec = {}
419 merged_arg_spec.update(DOCKER_COMMON_ARGS)
420 if argument_spec:
421 merged_arg_spec.update(argument_spec)
422 self.arg_spec = merged_arg_spec
423
424 mutually_exclusive_params: list[Sequence[str]] = []
425 mutually_exclusive_params += DOCKER_MUTUALLY_EXCLUSIVE
426 if mutually_exclusive:
427 mutually_exclusive_params += mutually_exclusive
428
429 required_together_params: list[Sequence[str]] = []
430 required_together_params += DOCKER_REQUIRED_TOGETHER
431 if required_together:
432 required_together_params += required_together
433
434 self.module = AnsibleModule(
435 argument_spec=merged_arg_spec,
436 supports_check_mode=supports_check_mode,
437 mutually_exclusive=mutually_exclusive_params,
438 required_together=required_together_params,
439 required_if=required_if,
440 required_one_of=required_one_of,
441 required_by=required_by or {},
442 )
443
444 self.debug = self.module.params.get("debug")
445 self.check_mode = self.module.check_mode
446
447 super().__init__(
448 min_docker_version=min_docker_version,
449 min_docker_api_version=min_docker_api_version,
450 )
451
452 if option_minimal_versions is not None:
453 self._get_minimal_versions(
454 option_minimal_versions, option_minimal_versions_ignore_params
455 )
456
457 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
458 self.fail_results.update(kwargs)
459 self.module.fail_json(msg=msg, **sanitize_result(self.fail_results))
460
461 def deprecate(
462 self,
463 msg: str,
464 version: str | None = None,
465 date: str | None = None,
466 collection_name: str | None = None,
467 ) -> None:
468 self.module.deprecate(
469 msg, version=version, date=date, collection_name=collection_name
470 )
471
472 def _get_params(self) -> dict[str, t.Any]:
473 return self.module.params
474
475 def _get_minimal_versions(
476 self,
477 option_minimal_versions: dict[str, t.Any],
478 ignore_params: Sequence[str] | None = None,
479 ) -> None:
480 self.option_minimal_versions: dict[str, dict[str, t.Any]] = {}
481 for option in self.module.argument_spec:
482 if ignore_params is not None and option in ignore_params:
483 continue
484 self.option_minimal_versions[option] = {}
485 self.option_minimal_versions.update(option_minimal_versions)
486
487 for option, data in self.option_minimal_versions.items():
488 # Test whether option is supported, and store result
489 support_docker_py = True
490 support_docker_api = True
491 if "docker_py_version" in data:
492 support_docker_py = self.docker_py_version >= LooseVersion(
493 data["docker_py_version"]
494 )
495 if "docker_api_version" in data:
496 support_docker_api = self.docker_api_version >= LooseVersion(
497 data["docker_api_version"]
498 )
499 data["supported"] = support_docker_py and support_docker_api
500 # Fail if option is not supported but used
501 if not data["supported"]:
502 # Test whether option is specified
503 if "detect_usage" in data:
504 used = data["detect_usage"](self)
505 else:
506 used = self.module.params.get(option) is not None
507 if used and "default" in self.module.argument_spec[option]:
508 used = (
509 self.module.params[option]
510 != self.module.argument_spec[option]["default"]
511 )
512 if used:
513 # If the option is used, compose error message.
514 if "usage_msg" in data:
515 usg = data["usage_msg"]
516 else:
517 usg = f"set {option} option"
518 if not support_docker_api:
519 msg = f"Docker API version is {self.docker_api_version_str}. Minimum version required is {data['docker_api_version']} to {usg}."
520 elif not support_docker_py:
521 msg = (
522 f"Docker SDK for Python version is {docker_version} ({platform.node()}'s Python {sys.executable})."
523 f" Minimum version required is {data['docker_py_version']} to {usg}. {DOCKERPYUPGRADE_UPGRADE_DOCKER}"
524 )
525 else:
526 # should not happen
527 msg = f"Cannot {usg} with your configuration."
528 self.fail(msg)
529
530 def report_warnings(
531 self, result: t.Any, warnings_key: Sequence[str] | None = None
532 ) -> None:
533 """
534 Checks result of client operation for warnings, and if present, outputs them.
535
536 warnings_key should be a list of keys used to crawl the result dictionary.
537 For example, if warnings_key == ['a', 'b'], the function will consider
538 result['a']['b'] if these keys exist. If the result is a non-empty string, it
539 will be reported as a warning. If the result is a list, every entry will be
540 reported as a warning.
541
542 In most cases (if warnings are returned at all), warnings_key should be
543 ['Warnings'] or ['Warning']. The default value (if not specified) is ['Warnings'].
544 """
545 if warnings_key is None:
546 warnings_key = ["Warnings"]
547 for key in warnings_key:
548 if not isinstance(result, Mapping):
549 return
550 result = result.get(key)
551 if isinstance(result, Sequence):
552 for warning in result:
553 self.module.warn(f"Docker warning: {warning}")
554 elif isinstance(result, str) and result:
555 self.module.warn(f"Docker warning: {result}")