Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_util.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 ipaddress
11 import json
12 import re
13 import typing as t
14 from datetime import timedelta
15 from urllib.parse import urlparse
16
17 from ansible.module_utils.basic import env_fallback
18 from ansible.module_utils.common.collections import is_sequence
19 from ansible.module_utils.common.text.converters import to_text
20
21 if t.TYPE_CHECKING:
22 from collections.abc import Callable
23
24 from ansible.module_utils.basic import AnsibleModule
25
26 from ._common import AnsibleDockerClientBase as CADCB
27 from ._common_api import AnsibleDockerClientBase as CAPIADCB
28 from ._common_cli import AnsibleDockerClientBase as CCLIADCB
29
30 Client = t.Union[CADCB, CAPIADCB, CCLIADCB] # noqa: UP007
31
32
33 DEFAULT_DOCKER_HOST = "unix:///var/run/docker.sock"
34 DEFAULT_TLS = False
35 DEFAULT_TLS_VERIFY = False
36 DEFAULT_TLS_HOSTNAME = "localhost" # deprecated
37 DEFAULT_TIMEOUT_SECONDS = 60
38
39 DOCKER_COMMON_ARGS = {
40 "docker_host": {
41 "type": "str",
42 "default": DEFAULT_DOCKER_HOST,
43 "fallback": (env_fallback, ["DOCKER_HOST"]),
44 "aliases": ["docker_url"],
45 },
46 "tls_hostname": {
47 "type": "str",
48 "fallback": (env_fallback, ["DOCKER_TLS_HOSTNAME"]),
49 },
50 "api_version": {
51 "type": "str",
52 "default": "auto",
53 "fallback": (env_fallback, ["DOCKER_API_VERSION"]),
54 "aliases": ["docker_api_version"],
55 },
56 "timeout": {
57 "type": "int",
58 "default": DEFAULT_TIMEOUT_SECONDS,
59 "fallback": (env_fallback, ["DOCKER_TIMEOUT"]),
60 },
61 "ca_path": {"type": "path", "aliases": ["ca_cert", "tls_ca_cert", "cacert_path"]},
62 "client_cert": {"type": "path", "aliases": ["tls_client_cert", "cert_path"]},
63 "client_key": {"type": "path", "aliases": ["tls_client_key", "key_path"]},
64 "tls": {
65 "type": "bool",
66 "default": DEFAULT_TLS,
67 "fallback": (env_fallback, ["DOCKER_TLS"]),
68 },
69 "use_ssh_client": {"type": "bool", "default": False},
70 "validate_certs": {
71 "type": "bool",
72 "default": DEFAULT_TLS_VERIFY,
73 "fallback": (env_fallback, ["DOCKER_TLS_VERIFY"]),
74 "aliases": ["tls_verify"],
75 },
76 "debug": {"type": "bool", "default": False},
77 }
78
79 DOCKER_COMMON_ARGS_VARS = {
80 option_name: f"ansible_docker_{option_name}"
81 for option_name in DOCKER_COMMON_ARGS
82 if option_name != "debug"
83 }
84
85 DOCKER_MUTUALLY_EXCLUSIVE: list[tuple[str, ...] | list[str]] = []
86
87 DOCKER_REQUIRED_TOGETHER: list[tuple[str, ...] | list[str]] = [
88 ["client_cert", "client_key"]
89 ]
90
91 DEFAULT_DOCKER_REGISTRY = "https://index.docker.io/v1/"
92 BYTE_SUFFIXES = ["B", "KB", "MB", "GB", "TB", "PB"]
93
94
95 def is_image_name_id(name: str) -> bool:
96 """Check whether the given image name is in fact an image ID (hash)."""
97 return bool(re.match("^sha256:[0-9a-fA-F]{64}$", name))
98
99
100 def is_valid_tag(tag: str, allow_empty: bool = False) -> bool:
101 """Check whether the given string is a valid docker tag name."""
102 if not tag:
103 return allow_empty
104 # See here ("Extended description") for a definition what tags can be:
105 # https://docs.docker.com/engine/reference/commandline/tag/
106 return bool(re.match("^[a-zA-Z0-9_][a-zA-Z0-9_.-]{0,127}$", tag))
107
108
109 def sanitize_result(data: t.Any) -> t.Any:
110 """Sanitize data object for return to Ansible.
111
112 When the data object contains types such as docker.types.containers.HostConfig,
113 Ansible will fail when these are returned via exit_json or fail_json.
114 HostConfig is derived from dict, but its constructor requires additional
115 arguments. This function sanitizes data structures by recursively converting
116 everything derived from dict to dict and everything derived from list (and tuple)
117 to a list.
118 """
119 if isinstance(data, dict):
120 return dict((k, sanitize_result(v)) for k, v in data.items())
121 if isinstance(data, (list, tuple)):
122 return [sanitize_result(v) for v in data]
123 return data
124
125
126 def log_debug(msg: t.Any, pretty_print: bool = False) -> None:
127 """Write a log message to docker.log.
128
129 If ``pretty_print=True``, the message will be pretty-printed as JSON.
130 """
131 with open("docker.log", "at", encoding="utf-8") as log_file:
132 if pretty_print:
133 log_file.write(
134 json.dumps(msg, sort_keys=True, indent=4, separators=(",", ": "))
135 )
136 log_file.write("\n")
137 else:
138 log_file.write(f"{msg}\n")
139
140
141 class DockerBaseClass:
142 def __init__(self) -> None:
143 self.debug = False
144
145 def log(self, msg: t.Any, pretty_print: bool = False) -> None:
146 pass
147 # if self.debug:
148 # log_debug(msg, pretty_print=pretty_print)
149
150
151 def update_tls_hostname(
152 result: dict[str, t.Any],
153 old_behavior: bool = False,
154 deprecate_function: Callable[[str], None] | None = None,
155 uses_tls: bool = True,
156 ) -> None:
157 if result["tls_hostname"] is None:
158 # get default machine name from the url
159 parsed_url = urlparse(result["docker_host"])
160 result["tls_hostname"] = parsed_url.netloc.rsplit(":", 1)[0]
161
162
163 def compare_dict_allow_more_present(av: dict, bv: dict) -> bool:
164 """
165 Compare two dictionaries for whether every entry of the first is in the second.
166 """
167 for key, value in av.items():
168 if key not in bv:
169 return False
170 if bv[key] != value:
171 return False
172 return True
173
174
175 def compare_generic(
176 a: t.Any,
177 b: t.Any,
178 method: t.Literal["ignore", "strict", "allow_more_present"],
179 datatype: t.Literal["value", "list", "set", "set(dict)", "dict"],
180 ) -> bool:
181 """
182 Compare values a and b as described by method and datatype.
183
184 Returns ``True`` if the values compare equal, and ``False`` if not.
185
186 ``a`` is usually the module's parameter, while ``b`` is a property
187 of the current object. ``a`` must not be ``None`` (except for
188 ``datatype == 'value'``).
189
190 Valid values for ``method`` are:
191 - ``ignore`` (always compare as equal);
192 - ``strict`` (only compare if really equal)
193 - ``allow_more_present`` (allow b to have elements which a does not have).
194
195 Valid values for ``datatype`` are:
196 - ``value``: for simple values (strings, numbers, ...);
197 - ``list``: for ``list``s or ``tuple``s where order matters;
198 - ``set``: for ``list``s, ``tuple``s or ``set``s where order does not
199 matter;
200 - ``set(dict)``: for ``list``s, ``tuple``s or ``sets`` where order does
201 not matter and which contain ``dict``s; ``allow_more_present`` is used
202 for the ``dict``s, and these are assumed to be dictionaries of values;
203 - ``dict``: for dictionaries of values.
204 """
205 if method == "ignore":
206 return True
207 # If a or b is None:
208 if a is None or b is None:
209 # If both are None: equality
210 if a == b:
211 return True
212 # Otherwise, not equal for values, and equal
213 # if the other is empty for set/list/dict
214 if datatype == "value":
215 return False
216 # For allow_more_present, allow a to be None
217 if method == "allow_more_present" and a is None:
218 return True
219 # Otherwise, the iterable object which is not None must have length 0
220 return len(b if a is None else a) == 0
221 # Do proper comparison (both objects not None)
222 if datatype == "value":
223 return a == b
224 if datatype == "list":
225 if method == "strict":
226 return a == b
227 i = 0
228 for v in a:
229 while i < len(b) and b[i] != v:
230 i += 1
231 if i == len(b):
232 return False
233 i += 1
234 return True
235 if datatype == "dict":
236 if method == "strict":
237 return a == b
238 return compare_dict_allow_more_present(a, b)
239 if datatype == "set":
240 set_a = set(a)
241 set_b = set(b)
242 if method == "strict":
243 return set_a == set_b
244 return set_b >= set_a
245 if datatype == "set(dict)":
246 for av in a:
247 found = False
248 for bv in b:
249 if compare_dict_allow_more_present(av, bv):
250 found = True
251 break
252 if not found:
253 return False
254 if method == "strict":
255 # If we would know that both a and b do not contain duplicates,
256 # we could simply compare len(a) to len(b) to finish this test.
257 # We can assume that b has no duplicates (as it is returned by
258 # docker), but we do not know for a.
259 for bv in b:
260 found = False
261 for av in a:
262 if compare_dict_allow_more_present(av, bv):
263 found = True
264 break
265 if not found:
266 return False
267 return True
268
269
270 class DifferenceTracker:
271 def __init__(self) -> None:
272 self._diff: list[dict[str, t.Any]] = []
273
274 def add(self, name: str, parameter: t.Any = None, active: t.Any = None) -> None:
275 self._diff.append(
276 {
277 "name": name,
278 "parameter": parameter,
279 "active": active,
280 }
281 )
282
283 def merge(self, other_tracker: DifferenceTracker) -> None:
284 self._diff.extend(other_tracker._diff)
285
286 @property
287 def empty(self) -> bool:
288 return len(self._diff) == 0
289
290 def get_before_after(self) -> tuple[dict[str, t.Any], dict[str, t.Any]]:
291 """
292 Return texts ``before`` and ``after``.
293 """
294 before = {}
295 after = {}
296 for item in self._diff:
297 before[item["name"]] = item["active"]
298 after[item["name"]] = item["parameter"]
299 return before, after
300
301 def has_difference_for(self, name: str) -> bool:
302 """
303 Returns a boolean if a difference exists for name
304 """
305 return any(diff for diff in self._diff if diff["name"] == name)
306
307 def get_legacy_docker_container_diffs(self) -> list[dict[str, t.Any]]:
308 """
309 Return differences in the docker_container legacy format.
310 """
311 result = []
312 for entry in self._diff:
313 item = {}
314 item[entry["name"]] = {
315 "parameter": entry["parameter"],
316 "container": entry["active"],
317 }
318 result.append(item)
319 return result
320
321 def get_legacy_docker_diffs(self) -> list[str]:
322 """
323 Return differences in the docker_container legacy format.
324 """
325 result = [entry["name"] for entry in self._diff]
326 return result
327
328
329 def sanitize_labels(
330 labels: dict[str, t.Any] | None,
331 labels_field: str,
332 client: Client | None = None,
333 module: AnsibleModule | None = None,
334 ) -> None:
335 def fail(msg: str) -> t.NoReturn:
336 if client is not None:
337 client.fail(msg)
338 if module is not None:
339 module.fail_json(msg=msg)
340 raise ValueError(msg)
341
342 if labels is None:
343 return
344 for k, v in list(labels.items()):
345 if not isinstance(k, str):
346 fail(f"The key {k!r} of {labels_field} is not a string!")
347 if isinstance(v, (bool, float)):
348 fail(
349 f"The value {v!r} for {k!r} of {labels_field} is not a string or something than can be safely converted to a string!"
350 )
351 labels[k] = to_text(v)
352
353
354 @t.overload
355 def clean_dict_booleans_for_docker_api(
356 data: dict[str, t.Any], *, allow_sequences: t.Literal[False] = False
357 ) -> dict[str, str]: ...
358
359
360 @t.overload
361 def clean_dict_booleans_for_docker_api(
362 data: dict[str, t.Any], *, allow_sequences: bool
363 ) -> dict[str, str | list[str]]: ...
364
365
366 def clean_dict_booleans_for_docker_api(
367 data: dict[str, t.Any] | None, *, allow_sequences: bool = False
368 ) -> dict[str, str] | dict[str, str | list[str]]:
369 """
370 Go does not like Python booleans 'True' or 'False', while Ansible is just
371 fine with them in YAML. As such, they need to be converted in cases where
372 we pass dictionaries to the Docker API (e.g. docker_network's
373 driver_options and docker_prune's filters). When `allow_sequences=True`
374 YAML sequences (lists, tuples) are converted to [str] instead of str([...])
375 which is the expected format of filters which accept lists such as labels.
376 """
377
378 def sanitize(value: t.Any) -> str:
379 if value is True:
380 return "true"
381 if value is False:
382 return "false"
383 return str(value)
384
385 result = {}
386 if data is not None:
387 for k, v in data.items():
388 result[str(k)] = (
389 [sanitize(e) for e in v]
390 if allow_sequences and is_sequence(v)
391 else sanitize(v)
392 )
393 return result
394
395
396 def convert_duration_to_nanosecond(time_str: str) -> int:
397 """
398 Return time duration in nanosecond.
399 """
400 if not isinstance(time_str, str):
401 raise ValueError(f"Missing unit in duration - {time_str}")
402
403 regex = re.compile(
404 r"^(((?P<hours>\d+)h)?"
405 r"((?P<minutes>\d+)m(?!s))?"
406 r"((?P<seconds>\d+)s)?"
407 r"((?P<milliseconds>\d+)ms)?"
408 r"((?P<microseconds>\d+)us)?)$"
409 )
410 parts = regex.match(time_str)
411
412 if not parts:
413 raise ValueError(f"Invalid time duration - {time_str}")
414
415 parts_dict = parts.groupdict()
416 time_params = {}
417 for name, value in parts_dict.items():
418 if value:
419 time_params[name] = int(value)
420
421 delta = timedelta(**time_params)
422 time_in_nanoseconds = (
423 delta.microseconds + (delta.seconds + delta.days * 24 * 3600) * 10**6
424 ) * 10**3
425
426 return time_in_nanoseconds
427
428
429 def normalize_healthcheck_test(test: t.Any) -> list[str]:
430 if isinstance(test, (tuple, list)):
431 return [str(e) for e in test]
432 return ["CMD-SHELL", str(test)]
433
434
435 def normalize_healthcheck(
436 healthcheck: dict[str, t.Any], normalize_test: bool = False
437 ) -> dict[str, t.Any]:
438 """
439 Return dictionary of healthcheck parameters.
440 """
441 result = {}
442
443 # All supported healthcheck parameters
444 options = (
445 "test",
446 "test_cli_compatible",
447 "interval",
448 "timeout",
449 "start_period",
450 "start_interval",
451 "retries",
452 )
453
454 duration_options = ("interval", "timeout", "start_period", "start_interval")
455
456 for key in options:
457 if key in healthcheck:
458 value = healthcheck[key]
459 if value is None:
460 # due to recursive argument_spec, all keys are always present
461 # (but have default value None if not specified)
462 continue
463 if key in duration_options:
464 value = convert_duration_to_nanosecond(value)
465 if not value and not (
466 healthcheck.get("test_cli_compatible") and key == "test"
467 ):
468 continue
469 if key == "retries":
470 try:
471 value = int(value)
472 except ValueError as exc:
473 raise ValueError(
474 f'Cannot parse number of retries for healthcheck. Expected an integer, got "{value}".'
475 ) from exc
476 if key == "test" and value and normalize_test:
477 value = normalize_healthcheck_test(value)
478 result[key] = value
479
480 return result
481
482
483 def parse_healthcheck(
484 healthcheck: dict[str, t.Any] | None,
485 ) -> tuple[dict[str, t.Any] | None, bool | None]:
486 """
487 Return dictionary of healthcheck parameters and boolean if
488 healthcheck defined in image was requested to be disabled.
489 """
490 if (not healthcheck) or (not healthcheck.get("test")):
491 return None, None
492
493 result = normalize_healthcheck(healthcheck, normalize_test=True)
494
495 if result["test"] == ["NONE"]:
496 # If the user explicitly disables the healthcheck, return None
497 # as the healthcheck object, and set disable_healthcheck to True
498 return None, True
499
500 return result, False
501
502
503 def omit_none_from_dict(d: dict[str, t.Any]) -> dict[str, t.Any]:
504 """
505 Return a copy of the dictionary with all keys with value None omitted.
506 """
507 return {k: v for (k, v) in d.items() if v is not None}
508
509
510 @t.overload
511 def normalize_ip_address(ip_address: str) -> str: ...
512
513
514 @t.overload
515 def normalize_ip_address(ip_address: str | None) -> str | None: ...
516
517
518 def normalize_ip_address(ip_address: str | None) -> str | None:
519 """
520 Given an IP address as a string, normalize it so that it can be
521 used to compare IP addresses as strings.
522 """
523 if ip_address is None:
524 return None
525 try:
526 return ipaddress.ip_address(ip_address).compressed
527 except ValueError:
528 # Fallback for invalid addresses: simply return the input
529 return ip_address
530
531
532 @t.overload
533 def normalize_ip_network(network: str) -> str: ...
534
535
536 @t.overload
537 def normalize_ip_network(network: str | None) -> str | None: ...
538
539
540 def normalize_ip_network(network: str | None) -> str | None:
541 """
542 Given a network in CIDR notation as a string, normalize it so that it can be
543 used to compare networks as strings.
544 """
545 if network is None:
546 return None
547 try:
548 return ipaddress.ip_network(network).compressed
549 except ValueError:
550 # Fallback for invalid networks: simply return the input
551 return network