Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_module_container/docker_api.py

raw
1 # Copyright (c) 2022 Felix Fontein <[email protected]>
2 # Copyright 2016 Red Hat | Ansible
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 json
12 import traceback
13 import typing as t
14
15 from ansible.module_utils.common.text.converters import to_text
16 from ansible.module_utils.common.text.formatters import human_to_bytes
17
18 from ansible_collections.community.docker.plugins.module_utils._api.errors import (
19 APIError,
20 DockerException,
21 NotFound,
22 )
23 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
24 convert_port_bindings,
25 normalize_links,
26 )
27 from ansible_collections.community.docker.plugins.module_utils._common_api import (
28 AnsibleDockerClient,
29 RequestException,
30 )
31 from ansible_collections.community.docker.plugins.module_utils._module_container.base import (
32 _DEFAULT_IP_REPLACEMENT_STRING,
33 OPTION_AUTO_REMOVE,
34 OPTION_BLKIO_WEIGHT,
35 OPTION_CAP_DROP,
36 OPTION_CAPABILITIES,
37 OPTION_CGROUP_NS_MODE,
38 OPTION_CGROUP_PARENT,
39 OPTION_COMMAND,
40 OPTION_CPU_PERIOD,
41 OPTION_CPU_QUOTA,
42 OPTION_CPU_SHARES,
43 OPTION_CPUS,
44 OPTION_CPUSET_CPUS,
45 OPTION_CPUSET_MEMS,
46 OPTION_DETACH_INTERACTIVE,
47 OPTION_DEVICE_CGROUP_RULES,
48 OPTION_DEVICE_READ_BPS,
49 OPTION_DEVICE_READ_IOPS,
50 OPTION_DEVICE_REQUESTS,
51 OPTION_DEVICE_WRITE_BPS,
52 OPTION_DEVICE_WRITE_IOPS,
53 OPTION_DEVICES,
54 OPTION_DNS_OPTS,
55 OPTION_DNS_SEARCH_DOMAINS,
56 OPTION_DNS_SERVERS,
57 OPTION_DOMAINNAME,
58 OPTION_ENTRYPOINT,
59 OPTION_ENVIRONMENT,
60 OPTION_ETC_HOSTS,
61 OPTION_GROUPS,
62 OPTION_HEALTHCHECK,
63 OPTION_HOSTNAME,
64 OPTION_IMAGE,
65 OPTION_INIT,
66 OPTION_IPC_MODE,
67 OPTION_KERNEL_MEMORY,
68 OPTION_LABELS,
69 OPTION_LINKS,
70 OPTION_LOG_DRIVER_OPTIONS,
71 OPTION_MAC_ADDRESS,
72 OPTION_MEMORY,
73 OPTION_MEMORY_RESERVATION,
74 OPTION_MEMORY_SWAP,
75 OPTION_MEMORY_SWAPPINESS,
76 OPTION_MOUNTS_VOLUMES,
77 OPTION_NETWORK,
78 OPTION_OOM_KILLER,
79 OPTION_OOM_SCORE_ADJ,
80 OPTION_PID_MODE,
81 OPTION_PIDS_LIMIT,
82 OPTION_PLATFORM,
83 OPTION_PORTS,
84 OPTION_PRIVILEGED,
85 OPTION_READ_ONLY,
86 OPTION_RESTART_POLICY,
87 OPTION_RUNTIME,
88 OPTION_SECURITY_OPTS,
89 OPTION_SHM_SIZE,
90 OPTION_STOP_SIGNAL,
91 OPTION_STOP_TIMEOUT,
92 OPTION_STORAGE_OPTS,
93 OPTION_SYSCTLS,
94 OPTION_TMPFS,
95 OPTION_TTY,
96 OPTION_ULIMITS,
97 OPTION_USER,
98 OPTION_USERNS_MODE,
99 OPTION_UTS,
100 OPTION_VOLUME_DRIVER,
101 OPTION_VOLUMES_FROM,
102 OPTION_WORKING_DIR,
103 OPTIONS,
104 Engine,
105 EngineDriver,
106 _is_volume_permissions,
107 )
108 from ansible_collections.community.docker.plugins.module_utils._platform import (
109 compose_platform_string,
110 normalize_platform_string,
111 )
112 from ansible_collections.community.docker.plugins.module_utils._util import (
113 normalize_healthcheck_test,
114 omit_none_from_dict,
115 )
116 from ansible_collections.community.docker.plugins.module_utils._version import (
117 LooseVersion,
118 )
119
120 if t.TYPE_CHECKING:
121 from collections.abc import Callable, Sequence
122
123 from ansible.module_utils.basic import AnsibleModule
124
125 from .base import Option, OptionGroup
126
127 Sentry = object
128
129
130 _SENTRY: Sentry = object()
131
132
133 class DockerAPIEngineDriver(EngineDriver[AnsibleDockerClient]):
134 name = "docker_api"
135
136 def setup(
137 self,
138 argument_spec: dict[str, t.Any],
139 mutually_exclusive: Sequence[Sequence[str]] | None = None,
140 required_together: Sequence[Sequence[str]] | None = None,
141 required_one_of: Sequence[Sequence[str]] | None = None,
142 required_if: (
143 Sequence[
144 tuple[str, t.Any, Sequence[str]]
145 | tuple[str, t.Any, Sequence[str], bool]
146 ]
147 | None
148 ) = None,
149 required_by: dict[str, Sequence[str]] | None = None,
150 ) -> tuple[AnsibleModule, list[OptionGroup], AnsibleDockerClient]:
151 argument_spec = dict(argument_spec or {})
152 mutually_exclusive = list(mutually_exclusive or [])
153 required_together = list(required_together or [])
154 required_one_of = list(required_one_of or [])
155 required_if = list(required_if or [])
156 required_by = dict(required_by or {})
157
158 active_options = []
159 option_minimal_versions = {}
160 for options in OPTIONS:
161 if not options.supports_engine(self.name):
162 continue
163
164 mutually_exclusive.extend(options.ansible_mutually_exclusive)
165 required_together.extend(options.ansible_required_together)
166 required_one_of.extend(options.ansible_required_one_of)
167 required_if.extend(options.ansible_required_if)
168 required_by.update(options.ansible_required_by)
169 argument_spec.update(options.argument_spec)
170
171 engine = options.get_engine(self.name)
172 if engine.min_api_version is not None:
173 for option in options.options:
174 if not option.not_an_ansible_option:
175 option_minimal_versions[option.name] = {
176 "docker_api_version": engine.min_api_version
177 }
178 if engine.extra_option_minimal_versions:
179 option_minimal_versions.update(engine.extra_option_minimal_versions)
180
181 active_options.append(options)
182
183 client = AnsibleDockerClient(
184 argument_spec=argument_spec,
185 mutually_exclusive=mutually_exclusive,
186 required_together=required_together,
187 required_one_of=required_one_of,
188 required_if=required_if,
189 required_by=required_by,
190 option_minimal_versions=option_minimal_versions,
191 supports_check_mode=True,
192 )
193
194 return client.module, active_options, client
195
196 def get_host_info(self, client: AnsibleDockerClient) -> dict[str, t.Any]:
197 return client.info()
198
199 def get_api_version(self, client: AnsibleDockerClient) -> LooseVersion:
200 return client.docker_api_version
201
202 def get_container_id(self, container: dict[str, t.Any]) -> str:
203 return container["Id"]
204
205 def get_image_from_container(self, container: dict[str, t.Any]) -> str:
206 return container["Image"]
207
208 def get_image_name_from_container(self, container: dict[str, t.Any]) -> str | None:
209 return container["Config"].get("Image")
210
211 def is_container_removing(self, container: dict[str, t.Any]) -> bool:
212 if container.get("State"):
213 return container["State"].get("Status") == "removing"
214 return False
215
216 def is_container_running(self, container: dict[str, t.Any]) -> bool:
217 return bool(
218 container.get("State")
219 and container["State"].get("Running")
220 and not container["State"].get("Ghost", False)
221 )
222
223 def is_container_paused(self, container: dict[str, t.Any]) -> bool:
224 if container.get("State"):
225 return container["State"].get("Paused", False)
226 return False
227
228 def inspect_container_by_name(
229 self, client: AnsibleDockerClient, container_name: str
230 ) -> dict[str, t.Any] | None:
231 return client.get_container(container_name)
232
233 def inspect_container_by_id(
234 self, client: AnsibleDockerClient, container_id: str
235 ) -> dict[str, t.Any] | None:
236 return client.get_container_by_id(container_id)
237
238 def inspect_image_by_id(
239 self, client: AnsibleDockerClient, image_id: str
240 ) -> dict[str, t.Any] | None:
241 return client.find_image_by_id(image_id, accept_missing_image=True)
242
243 def inspect_image_by_name(
244 self, client: AnsibleDockerClient, repository: str, tag: str
245 ) -> dict[str, t.Any] | None:
246 return client.find_image(repository, tag)
247
248 def pull_image(
249 self,
250 client: AnsibleDockerClient,
251 repository: str,
252 tag: str,
253 image_platform: str | None = None,
254 ) -> tuple[dict[str, t.Any] | None, bool]:
255 return client.pull_image(repository, tag, image_platform=image_platform)
256
257 def pause_container(self, client: AnsibleDockerClient, container_id: str) -> None:
258 client.post_call("/containers/{0}/pause", container_id)
259
260 def unpause_container(self, client: AnsibleDockerClient, container_id: str) -> None:
261 client.post_call("/containers/{0}/unpause", container_id)
262
263 def disconnect_container_from_network(
264 self, client: AnsibleDockerClient, container_id: str, network_id: str
265 ) -> None:
266 client.post_json(
267 "/networks/{0}/disconnect", network_id, data={"Container": container_id}
268 )
269
270 def _create_endpoint_config(self, parameters: dict[str, t.Any]) -> dict[str, t.Any]:
271 parameters = parameters.copy()
272 params = {}
273 for para, dest_para in {
274 "ipv4_address": "IPv4Address",
275 "ipv6_address": "IPv6Address",
276 "links": "Links",
277 "aliases": "Aliases",
278 "mac_address": "MacAddress",
279 "driver_opts": "DriverOpts",
280 }.items():
281 value = parameters.pop(para, None)
282 if value:
283 if para == "links":
284 value = normalize_links(value)
285 elif para == "driver_opts":
286 # Ensure driver_opts values are strings
287 for key, val in value.items():
288 if not isinstance(val, str):
289 raise ValueError(
290 f"driver_opts values must be strings, got {type(val).__name__} for key '{key}'"
291 )
292 params[dest_para] = value
293 for para, dest_para in {
294 "gw_priority": "GwPriority",
295 }.items():
296 value = parameters.pop(para, None)
297 if value is not None:
298 params[dest_para] = value
299 if parameters:
300 ups = ", ".join([f'"{p}"' for p in sorted(parameters)])
301 raise ValueError(
302 f"Unknown parameter(s) for connect_container_to_network for Docker API driver: {ups}"
303 )
304 ipam_config = {}
305 for param in ("IPv4Address", "IPv6Address"):
306 if param in params:
307 ipam_config[param] = params.pop(param)
308 if ipam_config:
309 params["IPAMConfig"] = ipam_config
310 return params
311
312 def connect_container_to_network(
313 self,
314 client: AnsibleDockerClient,
315 container_id: str,
316 network_id: str,
317 parameters: dict[str, t.Any] | None = None,
318 ) -> None:
319 parameters = (parameters or {}).copy()
320 params = self._create_endpoint_config(parameters or {})
321 data = {
322 "Container": container_id,
323 "EndpointConfig": params,
324 }
325 client.post_json("/networks/{0}/connect", network_id, data=data)
326
327 def create_container_supports_more_than_one_network(
328 self, client: AnsibleDockerClient
329 ) -> bool:
330 return client.docker_api_version >= LooseVersion("1.44")
331
332 def create_container(
333 self,
334 client: AnsibleDockerClient,
335 container_name: str,
336 create_parameters: dict[str, t.Any],
337 networks: dict[str, dict[str, t.Any]] | None = None,
338 ) -> str:
339 params = {"name": container_name}
340 if "platform" in create_parameters:
341 params["platform"] = create_parameters.pop("platform")
342 if networks is not None:
343 create_parameters = create_parameters.copy()
344 create_parameters["NetworkingConfig"] = {
345 "EndpointsConfig": dict(
346 (network, self._create_endpoint_config(network_params))
347 for network, network_params in networks.items()
348 )
349 }
350 new_container = client.post_json_to_json(
351 "/containers/create", data=create_parameters, params=params
352 )
353 client.report_warnings(new_container)
354 return new_container["Id"]
355
356 def start_container(self, client: AnsibleDockerClient, container_id: str) -> None:
357 client.post_json("/containers/{0}/start", container_id)
358
359 def wait_for_container(
360 self,
361 client: AnsibleDockerClient,
362 container_id: str,
363 timeout: int | float | None = None,
364 ) -> int | None:
365 return client.post_json_to_json(
366 "/containers/{0}/wait", container_id, timeout=timeout
367 )["StatusCode"]
368
369 def get_container_output(
370 self, client: AnsibleDockerClient, container_id: str
371 ) -> tuple[bytes, t.Literal[True]] | tuple[str, t.Literal[False]]:
372 config = client.get_json("/containers/{0}/json", container_id)
373 logging_driver = config["HostConfig"]["LogConfig"]["Type"]
374 if logging_driver in ("json-file", "journald", "local"):
375 params = {
376 "stderr": 1,
377 "stdout": 1,
378 "timestamps": 0,
379 "follow": 0,
380 "tail": "all",
381 }
382 res = client._get(
383 client._url("/containers/{0}/logs", container_id), params=params
384 )
385 output = client._get_result_tty(False, res, config["Config"]["Tty"])
386 return output, True
387 return f"Result logged using `{logging_driver}` driver", False
388
389 def update_container(
390 self,
391 client: AnsibleDockerClient,
392 container_id: str,
393 update_parameters: dict[str, t.Any],
394 ) -> None:
395 result = client.post_json_to_json(
396 "/containers/{0}/update", container_id, data=update_parameters
397 )
398 client.report_warnings(result)
399
400 def restart_container(
401 self,
402 client: AnsibleDockerClient,
403 container_id: str,
404 timeout: int | float | None = None,
405 ) -> None:
406 client_timeout: int | float | None = client.timeout
407 if client_timeout is not None:
408 client_timeout += timeout or 10
409 client.post_call(
410 "/containers/{0}/restart",
411 container_id,
412 params={"t": timeout},
413 timeout=client_timeout,
414 )
415
416 def kill_container(
417 self,
418 client: AnsibleDockerClient,
419 container_id: str,
420 kill_signal: str | None = None,
421 ) -> None:
422 params = {}
423 if kill_signal is not None:
424 params["signal"] = kill_signal
425 client.post_call("/containers/{0}/kill", container_id, params=params)
426
427 def stop_container(
428 self,
429 client: AnsibleDockerClient,
430 container_id: str,
431 timeout: int | float | None = None,
432 ) -> None:
433 if timeout:
434 params = {"t": timeout}
435 else:
436 params = {}
437 timeout = 10
438 client_timeout = client.timeout
439 if client_timeout is not None:
440 client_timeout += timeout
441 count = 0
442 while True:
443 try:
444 client.post_call(
445 "/containers/{0}/stop",
446 container_id,
447 params=params,
448 timeout=client_timeout,
449 )
450 except APIError as exc:
451 if (
452 "Unpause the container before stopping or killing"
453 in exc.explanation
454 ):
455 # New docker daemon versions do not allow containers to be removed
456 # if they are paused. Make sure we do not end up in an infinite loop.
457 if count == 3:
458 raise RuntimeError(
459 f"{exc} [tried to unpause three times]"
460 ) from exc
461 count += 1
462 # Unpause
463 try:
464 self.unpause_container(client, container_id)
465 except Exception as exc2:
466 raise RuntimeError(f"{exc2} [while unpausing]") from exc2
467 # Now try again
468 continue
469 raise
470 # We only loop when explicitly requested by 'continue'
471 break
472
473 def remove_container(
474 self,
475 client: AnsibleDockerClient,
476 container_id: str,
477 remove_volumes: bool = False,
478 link: bool = False,
479 force: bool = False,
480 ) -> None:
481 params = {"v": remove_volumes, "link": link, "force": force}
482 count = 0
483 while True:
484 try:
485 client.delete_call("/containers/{0}", container_id, params=params)
486 except NotFound:
487 pass
488 except APIError as exc:
489 if (
490 "Unpause the container before stopping or killing"
491 in exc.explanation
492 ):
493 # New docker daemon versions do not allow containers to be removed
494 # if they are paused. Make sure we do not end up in an infinite loop.
495 if count == 3:
496 raise RuntimeError(
497 f"{exc} [tried to unpause three times]"
498 ) from exc
499 count += 1
500 # Unpause
501 try:
502 self.unpause_container(client, container_id)
503 except Exception as exc2:
504 raise RuntimeError(f"{exc2} [while unpausing]") from exc2
505 # Now try again
506 continue
507 if (
508 "removal of container " in exc.explanation
509 and " is already in progress" in exc.explanation
510 ):
511 pass
512 else:
513 raise
514 # We only loop when explicitly requested by 'continue'
515 break
516
517 def run(self, runner: Callable[[], None], client: AnsibleDockerClient) -> None:
518 try:
519 runner()
520 except DockerException as e:
521 client.fail(
522 f"An unexpected Docker error occurred: {e}",
523 exception=traceback.format_exc(),
524 )
525 except RequestException as e:
526 client.fail(
527 f"An unexpected requests error occurred when trying to talk to the Docker daemon: {e}",
528 exception=traceback.format_exc(),
529 )
530
531
532 class DockerAPIEngine(Engine[AnsibleDockerClient]):
533 def get_value(
534 self,
535 module: AnsibleModule,
536 container: dict[str, t.Any],
537 api_version: LooseVersion,
538 options: list[Option],
539 image: dict[str, t.Any] | None,
540 host_info: dict[str, t.Any] | None,
541 ) -> dict[str, t.Any]:
542 return self._get_value(
543 module, container, api_version, options, image, host_info
544 )
545
546 def compare_value(
547 self, option: Option, param_value: t.Any, container_value: t.Any
548 ) -> bool:
549 if self._compare_value is not None:
550 return self._compare_value(option, param_value, container_value)
551 return super().compare_value(option, param_value, container_value)
552
553 def set_value(
554 self,
555 module: AnsibleModule,
556 data: dict[str, t.Any],
557 api_version: LooseVersion,
558 options: list[Option],
559 values: dict[str, t.Any],
560 ) -> None:
561 if self._set_value is not None:
562 self._set_value(module, data, api_version, options, values)
563
564 def get_expected_values(
565 self,
566 module: AnsibleModule,
567 client: AnsibleDockerClient,
568 api_version: LooseVersion,
569 options: list[Option],
570 image: dict[str, t.Any] | None,
571 values: dict[str, t.Any],
572 host_info: dict[str, t.Any] | None,
573 ) -> dict[str, t.Any]:
574 if self._get_expected_values is None:
575 return values
576 return self._get_expected_values(
577 module, client, api_version, options, image, values, host_info
578 )
579
580 def ignore_mismatching_result(
581 self,
582 module: AnsibleModule,
583 client: AnsibleDockerClient,
584 api_version: LooseVersion,
585 option: Option,
586 image: dict[str, t.Any] | None,
587 container_value: t.Any,
588 expected_value: t.Any,
589 host_info: dict[str, t.Any] | None,
590 ) -> bool:
591 if self._ignore_mismatching_result is None:
592 return False
593 return self._ignore_mismatching_result(
594 module,
595 client,
596 api_version,
597 option,
598 image,
599 container_value,
600 expected_value,
601 host_info,
602 )
603
604 def preprocess_value(
605 self,
606 module: AnsibleModule,
607 client: AnsibleDockerClient,
608 api_version: LooseVersion,
609 options: list[Option],
610 values: dict[str, t.Any],
611 ) -> dict[str, t.Any]:
612 if self._preprocess_value is None:
613 return values
614 return self._preprocess_value(module, client, api_version, options, values)
615
616 def update_value(
617 self,
618 module: AnsibleModule,
619 data: dict[str, t.Any],
620 api_version: LooseVersion,
621 options: list[Option],
622 values: dict[str, t.Any],
623 ) -> None:
624 if self._update_value is not None:
625 self._update_value(module, data, api_version, options, values)
626
627 def can_set_value(self, api_version: LooseVersion) -> bool:
628 if self._can_set_value is None:
629 return self._set_value is not None
630 return self._can_set_value(api_version)
631
632 def can_update_value(self, api_version: LooseVersion) -> bool:
633 if self._can_update_value is None:
634 return self._update_value is not None
635 return self._can_update_value(api_version)
636
637 def needs_container_image(self, values: dict[str, t.Any]) -> bool:
638 if self._needs_container_image is None:
639 return False
640 return self._needs_container_image(values)
641
642 def needs_host_info(self, values: dict[str, t.Any]) -> bool:
643 if self._needs_host_info is None:
644 return False
645 return self._needs_host_info(values)
646
647 def __init__(
648 self,
649 get_value: Callable[
650 [
651 AnsibleModule,
652 dict[str, t.Any],
653 LooseVersion,
654 list[Option],
655 dict[str, t.Any] | None,
656 dict[str, t.Any] | None,
657 ],
658 dict[str, t.Any],
659 ],
660 preprocess_value: (
661 Callable[
662 [
663 AnsibleModule,
664 AnsibleDockerClient,
665 LooseVersion,
666 list[Option],
667 dict[str, t.Any],
668 ],
669 dict[str, t.Any],
670 ]
671 | None
672 ) = None,
673 get_expected_values: (
674 Callable[
675 [
676 AnsibleModule,
677 AnsibleDockerClient,
678 LooseVersion,
679 list[Option],
680 dict[str, t.Any] | None,
681 dict[str, t.Any],
682 dict[str, t.Any] | None,
683 ],
684 dict[str, t.Any],
685 ]
686 | None
687 ) = None,
688 ignore_mismatching_result: (
689 Callable[
690 [
691 AnsibleModule,
692 AnsibleDockerClient,
693 LooseVersion,
694 Option,
695 dict[str, t.Any] | None,
696 t.Any,
697 t.Any,
698 dict[str, t.Any] | None,
699 ],
700 bool,
701 ]
702 | None
703 ) = None,
704 set_value: (
705 Callable[
706 [
707 AnsibleModule,
708 dict[str, t.Any],
709 LooseVersion,
710 list[Option],
711 dict[str, t.Any],
712 ],
713 None,
714 ]
715 | None
716 ) = None,
717 update_value: (
718 Callable[
719 [
720 AnsibleModule,
721 dict[str, t.Any],
722 LooseVersion,
723 list[Option],
724 dict[str, t.Any],
725 ],
726 None,
727 ]
728 | None
729 ) = None,
730 can_set_value: Callable[[LooseVersion], bool] | None = None,
731 can_update_value: Callable[[LooseVersion], bool] | None = None,
732 min_api_version: str | None = None,
733 compare_value: Callable[[Option, t.Any, t.Any], bool] | None = None,
734 needs_container_image: Callable[[dict[str, t.Any]], bool] | None = None,
735 needs_host_info: Callable[[dict[str, t.Any]], bool] | None = None,
736 extra_option_minimal_versions: dict[str, dict[str, t.Any]] | None = None,
737 ):
738 self.min_api_version = min_api_version
739 self.min_api_version_obj = (
740 None if min_api_version is None else LooseVersion(min_api_version)
741 )
742 self.extra_option_minimal_versions = extra_option_minimal_versions
743 self._get_value = get_value
744 self._compare_value = compare_value
745 self._set_value = set_value
746 self._get_expected_values = get_expected_values
747 self._ignore_mismatching_result = ignore_mismatching_result
748 self._preprocess_value = preprocess_value
749 self._update_value = update_value
750 self._can_set_value = can_set_value
751 self._can_update_value = can_update_value
752 self._needs_container_image = needs_container_image
753 self._needs_host_info = needs_host_info
754
755 @classmethod
756 def config_value(
757 cls,
758 config_name: str,
759 postprocess_for_get: (
760 Callable[[AnsibleModule, LooseVersion, t.Any, Sentry], t.Any | Sentry]
761 | None
762 ) = None,
763 preprocess_for_set: (
764 Callable[[AnsibleModule, LooseVersion, t.Any], t.Any] | None
765 ) = None,
766 get_expected_value: (
767 Callable[
768 [
769 AnsibleModule,
770 AnsibleDockerClient,
771 LooseVersion,
772 dict[str, t.Any] | None,
773 t.Any,
774 Sentry,
775 ],
776 t.Any | Sentry,
777 ]
778 | None
779 ) = None,
780 ignore_mismatching_result: (
781 Callable[
782 [
783 AnsibleModule,
784 AnsibleDockerClient,
785 LooseVersion,
786 Option,
787 dict[str, t.Any] | None,
788 t.Any,
789 t.Any,
790 dict[str, t.Any] | None,
791 ],
792 bool,
793 ]
794 | None
795 ) = None,
796 min_api_version: str | None = None,
797 preprocess_value: (
798 Callable[[AnsibleModule, AnsibleDockerClient, LooseVersion, t.Any], t.Any]
799 | None
800 ) = None,
801 update_parameter: str | None = None,
802 extra_option_minimal_versions: dict[str, dict[str, t.Any]] | None = None,
803 ) -> DockerAPIEngine:
804 def preprocess_value_(
805 module: AnsibleModule,
806 client: AnsibleDockerClient,
807 api_version: LooseVersion,
808 options: list[Option],
809 values: dict[str, t.Any],
810 ) -> dict[str, t.Any]:
811 if len(options) != 1:
812 raise AssertionError(
813 "config_value can only be used for a single option"
814 )
815 if preprocess_value is not None and options[0].name in values:
816 value = preprocess_value(
817 module, client, api_version, values[options[0].name]
818 )
819 if value is None:
820 del values[options[0].name]
821 else:
822 values[options[0].name] = value
823 return values
824
825 def get_value(
826 module: AnsibleModule,
827 container: dict[str, t.Any],
828 api_version: LooseVersion,
829 options: list[Option],
830 image: dict[str, t.Any] | None,
831 host_info: dict[str, t.Any] | None,
832 ) -> dict[str, t.Any]:
833 if len(options) != 1:
834 raise AssertionError(
835 "config_value can only be used for a single option"
836 )
837 value = container["Config"].get(config_name, _SENTRY)
838 if postprocess_for_get:
839 value = postprocess_for_get(module, api_version, value, _SENTRY)
840 if value is _SENTRY:
841 return {}
842 return {options[0].name: value}
843
844 get_expected_values_: (
845 Callable[
846 [
847 AnsibleModule,
848 AnsibleDockerClient,
849 LooseVersion,
850 list[Option],
851 dict[str, t.Any] | None,
852 dict[str, t.Any],
853 dict[str, t.Any] | None,
854 ],
855 dict[str, t.Any],
856 ]
857 | None
858 ) = None
859 if get_expected_value:
860
861 def get_expected_values_( # noqa: F811
862 module: AnsibleModule,
863 client: AnsibleDockerClient,
864 api_version: LooseVersion,
865 options: list[Option],
866 image: dict[str, t.Any] | None,
867 values: dict[str, t.Any],
868 host_info: dict[str, t.Any] | None,
869 ) -> dict[str, t.Any]:
870 if len(options) != 1:
871 raise AssertionError(
872 "host_config_value can only be used for a single option"
873 )
874 value = values.get(options[0].name, _SENTRY)
875 value = get_expected_value(
876 module, client, api_version, image, value, _SENTRY
877 )
878 if value is _SENTRY:
879 return values
880 return {options[0].name: value}
881
882 def set_value(
883 module: AnsibleModule,
884 data: dict[str, t.Any],
885 api_version: LooseVersion,
886 options: list[Option],
887 values: dict[str, t.Any],
888 ) -> None:
889 if len(options) != 1:
890 raise AssertionError(
891 "config_value can only be used for a single option"
892 )
893 if options[0].name not in values:
894 return
895 value = values[options[0].name]
896 if preprocess_for_set:
897 value = preprocess_for_set(module, api_version, value)
898 data[config_name] = value
899
900 update_value: (
901 Callable[
902 [
903 AnsibleModule,
904 dict[str, t.Any],
905 LooseVersion,
906 list[Option],
907 dict[str, t.Any],
908 ],
909 None,
910 ]
911 | None
912 ) = None
913 if update_parameter:
914
915 def update_value( # noqa: F811
916 module: AnsibleModule,
917 data: dict[str, t.Any],
918 api_version: LooseVersion,
919 options: list[Option],
920 values: dict[str, t.Any],
921 ) -> None:
922 if len(options) != 1:
923 raise AssertionError(
924 "update_parameter can only be used for a single option"
925 )
926 if options[0].name not in values:
927 return
928 value = values[options[0].name]
929 if preprocess_for_set:
930 value = preprocess_for_set(module, api_version, value)
931 data[update_parameter] = value
932
933 return cls(
934 get_value=get_value,
935 preprocess_value=preprocess_value_,
936 get_expected_values=get_expected_values_,
937 ignore_mismatching_result=ignore_mismatching_result,
938 set_value=set_value,
939 min_api_version=min_api_version,
940 update_value=update_value,
941 extra_option_minimal_versions=extra_option_minimal_versions,
942 )
943
944 @classmethod
945 def host_config_value(
946 cls,
947 host_config_name: str,
948 postprocess_for_get: (
949 Callable[[AnsibleModule, LooseVersion, t.Any, Sentry], t.Any | Sentry]
950 | None
951 ) = None,
952 preprocess_for_set: (
953 Callable[[AnsibleModule, LooseVersion, t.Any], t.Any] | None
954 ) = None,
955 get_expected_value: (
956 Callable[
957 [
958 AnsibleModule,
959 AnsibleDockerClient,
960 LooseVersion,
961 dict[str, t.Any] | None,
962 t.Any,
963 Sentry,
964 ],
965 t.Any | Sentry,
966 ]
967 | None
968 ) = None,
969 ignore_mismatching_result: (
970 Callable[
971 [
972 AnsibleModule,
973 AnsibleDockerClient,
974 LooseVersion,
975 Option,
976 dict[str, t.Any] | None,
977 t.Any,
978 t.Any,
979 dict[str, t.Any] | None,
980 ],
981 bool,
982 ]
983 | None
984 ) = None,
985 min_api_version: str | None = None,
986 preprocess_value: (
987 Callable[[AnsibleModule, AnsibleDockerClient, LooseVersion, t.Any], t.Any]
988 | None
989 ) = None,
990 update_parameter: str | None = None,
991 extra_option_minimal_versions: dict[str, dict[str, t.Any]] | None = None,
992 ) -> DockerAPIEngine:
993 def preprocess_value_(
994 module: AnsibleModule,
995 client: AnsibleDockerClient,
996 api_version: LooseVersion,
997 options: list[Option],
998 values: dict[str, t.Any],
999 ) -> dict[str, t.Any]:
1000 if len(options) != 1:
1001 raise AssertionError(
1002 "host_config_value can only be used for a single option"
1003 )
1004 if preprocess_value is not None and options[0].name in values:
1005 value = preprocess_value(
1006 module, client, api_version, values[options[0].name]
1007 )
1008 if value is None:
1009 del values[options[0].name]
1010 else:
1011 values[options[0].name] = value
1012 return values
1013
1014 def get_value(
1015 module: AnsibleModule,
1016 container: dict[str, t.Any],
1017 api_version: LooseVersion,
1018 options: list[Option],
1019 image: dict[str, t.Any] | None,
1020 host_info: dict[str, t.Any] | None,
1021 ) -> dict[str, t.Any]:
1022 if len(options) != 1:
1023 raise AssertionError(
1024 "host_config_value can only be used for a single option"
1025 )
1026 value = container["HostConfig"].get(host_config_name, _SENTRY)
1027 if postprocess_for_get:
1028 value = postprocess_for_get(module, api_version, value, _SENTRY)
1029 if value is _SENTRY:
1030 return {}
1031 return {options[0].name: value}
1032
1033 get_expected_values_: (
1034 Callable[
1035 [
1036 AnsibleModule,
1037 AnsibleDockerClient,
1038 LooseVersion,
1039 list[Option],
1040 dict[str, t.Any] | None,
1041 dict[str, t.Any],
1042 dict[str, t.Any] | None,
1043 ],
1044 dict[str, t.Any],
1045 ]
1046 | None
1047 ) = None
1048 if get_expected_value:
1049
1050 def get_expected_values_( # noqa: F811
1051 module: AnsibleModule,
1052 client: AnsibleDockerClient,
1053 api_version: LooseVersion,
1054 options: list[Option],
1055 image: dict[str, t.Any] | None,
1056 values: dict[str, t.Any],
1057 host_info: dict[str, t.Any] | None,
1058 ) -> dict[str, t.Any]:
1059 if len(options) != 1:
1060 raise AssertionError(
1061 "host_config_value can only be used for a single option"
1062 )
1063 value = values.get(options[0].name, _SENTRY)
1064 value = get_expected_value(
1065 module, client, api_version, image, value, _SENTRY
1066 )
1067 if value is _SENTRY:
1068 return values
1069 return {options[0].name: value}
1070
1071 def set_value(
1072 module: AnsibleModule,
1073 data: dict[str, t.Any],
1074 api_version: LooseVersion,
1075 options: list[Option],
1076 values: dict[str, t.Any],
1077 ) -> None:
1078 if len(options) != 1:
1079 raise AssertionError(
1080 "host_config_value can only be used for a single option"
1081 )
1082 if options[0].name not in values:
1083 return
1084 if "HostConfig" not in data:
1085 data["HostConfig"] = {}
1086 value = values[options[0].name]
1087 if preprocess_for_set:
1088 value = preprocess_for_set(module, api_version, value)
1089 data["HostConfig"][host_config_name] = value
1090
1091 update_value: (
1092 Callable[
1093 [
1094 AnsibleModule,
1095 dict[str, t.Any],
1096 LooseVersion,
1097 list[Option],
1098 dict[str, t.Any],
1099 ],
1100 None,
1101 ]
1102 | None
1103 ) = None
1104 if update_parameter:
1105
1106 def update_value( # noqa: F811
1107 module: AnsibleModule,
1108 data: dict[str, t.Any],
1109 api_version: LooseVersion,
1110 options: list[Option],
1111 values: dict[str, t.Any],
1112 ) -> None:
1113 if len(options) != 1:
1114 raise AssertionError(
1115 "update_parameter can only be used for a single option"
1116 )
1117 if options[0].name not in values:
1118 return
1119 value = values[options[0].name]
1120 if preprocess_for_set:
1121 value = preprocess_for_set(module, api_version, value)
1122 data[update_parameter] = value
1123
1124 return cls(
1125 get_value=get_value,
1126 preprocess_value=preprocess_value_,
1127 get_expected_values=get_expected_values_,
1128 ignore_mismatching_result=ignore_mismatching_result,
1129 set_value=set_value,
1130 min_api_version=min_api_version,
1131 update_value=update_value,
1132 extra_option_minimal_versions=extra_option_minimal_versions,
1133 )
1134
1135
1136 def _normalize_port(port: str) -> str:
1137 if "/" not in port:
1138 return port + "/tcp"
1139 return port
1140
1141
1142 def _get_default_host_ip(module: AnsibleModule, client: AnsibleDockerClient) -> str:
1143 if module.params["default_host_ip"] is not None:
1144 return module.params["default_host_ip"]
1145 ip = "0.0.0.0"
1146 for network_data in module.params["networks"] or []:
1147 if network_data.get("name"):
1148 network = client.get_network(network_data["name"])
1149 if network is None:
1150 client.fail(
1151 f"Cannot inspect the network '{network_data['name']}' to determine the default IP",
1152 )
1153 if network.get("Driver") == "bridge" and network.get("Options", {}).get(
1154 "com.docker.network.bridge.host_binding_ipv4"
1155 ):
1156 ip = network["Options"]["com.docker.network.bridge.host_binding_ipv4"]
1157 break
1158 return ip
1159
1160
1161 def _get_value_detach_interactive(
1162 module: AnsibleModule,
1163 container: dict[str, t.Any],
1164 api_version: LooseVersion,
1165 options: list[Option],
1166 image: dict[str, t.Any] | None,
1167 host_info: dict[str, t.Any] | None,
1168 ) -> dict[str, t.Any]:
1169 attach_stdin = container["Config"].get("OpenStdin")
1170 attach_stderr = container["Config"].get("AttachStderr")
1171 attach_stdout = container["Config"].get("AttachStdout")
1172 return {
1173 "interactive": bool(attach_stdin),
1174 "detach": not (attach_stderr and attach_stdout),
1175 }
1176
1177
1178 def _set_value_detach_interactive(
1179 module: AnsibleModule,
1180 data: dict[str, t.Any],
1181 api_version: LooseVersion,
1182 options: list[Option],
1183 values: dict[str, t.Any],
1184 ) -> None:
1185 interactive = values.get("interactive")
1186 detach = values.get("detach")
1187
1188 data["AttachStdout"] = False
1189 data["AttachStderr"] = False
1190 data["AttachStdin"] = False
1191 data["StdinOnce"] = False
1192 data["OpenStdin"] = interactive
1193 if not detach:
1194 data["AttachStdout"] = True
1195 data["AttachStderr"] = True
1196 if interactive:
1197 data["AttachStdin"] = True
1198 data["StdinOnce"] = True
1199
1200
1201 def _get_expected_env_value(
1202 module: AnsibleModule,
1203 client: AnsibleDockerClient,
1204 api_version: LooseVersion,
1205 image: dict[str, t.Any] | None,
1206 value: t.Any,
1207 sentry: Sentry,
1208 ) -> t.Any | Sentry:
1209 expected_env = {}
1210 if image and image["Config"].get("Env"):
1211 for env_var in image["Config"]["Env"]:
1212 parts = env_var.split("=", 1)
1213 expected_env[parts[0]] = parts[1]
1214 if value and value is not sentry:
1215 for env_var in value:
1216 parts = env_var.split("=", 1)
1217 expected_env[parts[0]] = parts[1]
1218 param_env = []
1219 for key, env_value in expected_env.items():
1220 param_env.append(f"{key}={env_value}")
1221 return param_env
1222
1223
1224 def _preprocess_cpus(
1225 module: AnsibleModule,
1226 client: AnsibleDockerClient,
1227 api_version: LooseVersion,
1228 value: t.Any,
1229 ) -> t.Any:
1230 if value is not None:
1231 value = int(round(value * 1e9))
1232 return value
1233
1234
1235 def _preprocess_devices(
1236 module: AnsibleModule,
1237 client: AnsibleDockerClient,
1238 api_version: LooseVersion,
1239 value: t.Any,
1240 ) -> t.Any:
1241 if not value:
1242 return value
1243 expected_devices = []
1244 for device in value:
1245 parts = device.split(":")
1246 if len(parts) == 1:
1247 expected_devices.append(
1248 {
1249 "CgroupPermissions": "rwm",
1250 "PathInContainer": parts[0],
1251 "PathOnHost": parts[0],
1252 }
1253 )
1254 elif len(parts) == 2:
1255 parts = device.split(":")
1256 expected_devices.append(
1257 {
1258 "CgroupPermissions": "rwm",
1259 "PathInContainer": parts[1],
1260 "PathOnHost": parts[0],
1261 }
1262 )
1263 else:
1264 expected_devices.append(
1265 {
1266 "CgroupPermissions": parts[2],
1267 "PathInContainer": parts[1],
1268 "PathOnHost": parts[0],
1269 }
1270 )
1271 return expected_devices
1272
1273
1274 def _preprocess_rate_bps(
1275 module: AnsibleModule,
1276 client: AnsibleDockerClient,
1277 api_version: LooseVersion,
1278 value: t.Any,
1279 ) -> t.Any:
1280 if not value:
1281 return value
1282 devices = []
1283 for device in value:
1284 devices.append(
1285 {
1286 "Path": device["path"],
1287 "Rate": human_to_bytes(device["rate"]),
1288 }
1289 )
1290 return devices
1291
1292
1293 def _preprocess_rate_iops(
1294 module: AnsibleModule,
1295 client: AnsibleDockerClient,
1296 api_version: LooseVersion,
1297 value: t.Any,
1298 ) -> t.Any:
1299 if not value:
1300 return value
1301 devices = []
1302 for device in value:
1303 devices.append(
1304 {
1305 "Path": device["path"],
1306 "Rate": device["rate"],
1307 }
1308 )
1309 return devices
1310
1311
1312 def _preprocess_device_requests(
1313 module: AnsibleModule,
1314 client: AnsibleDockerClient,
1315 api_version: LooseVersion,
1316 value: t.Any,
1317 ) -> t.Any:
1318 if not value:
1319 return value
1320 device_requests = []
1321 for dr in value:
1322 device_requests.append(
1323 {
1324 "Driver": dr["driver"],
1325 "Count": dr["count"],
1326 "DeviceIDs": dr["device_ids"],
1327 "Capabilities": dr["capabilities"],
1328 "Options": dr["options"],
1329 }
1330 )
1331 return device_requests
1332
1333
1334 def _preprocess_etc_hosts(
1335 module: AnsibleModule,
1336 client: AnsibleDockerClient,
1337 api_version: LooseVersion,
1338 value: t.Any,
1339 ) -> t.Any:
1340 if value is None:
1341 return value
1342 results = []
1343 for key, val in value.items():
1344 results.append(f"{key}:{val}")
1345 return results
1346
1347
1348 def _preprocess_healthcheck(
1349 module: AnsibleModule,
1350 client: AnsibleDockerClient,
1351 api_version: LooseVersion,
1352 value: t.Any,
1353 ) -> t.Any:
1354 if value is None:
1355 return value
1356 if not value or not (
1357 value.get("test")
1358 or (value.get("test_cli_compatible") and value.get("test") is None)
1359 ):
1360 value = {"test": ["NONE"]}
1361 elif "test" in value:
1362 value["test"] = normalize_healthcheck_test(value["test"])
1363 return omit_none_from_dict(
1364 {
1365 "Test": value.get("test"),
1366 "Interval": value.get("interval"),
1367 "Timeout": value.get("timeout"),
1368 "StartPeriod": value.get("start_period"),
1369 "StartInterval": value.get("start_interval"),
1370 "Retries": value.get("retries"),
1371 }
1372 )
1373
1374
1375 def _postprocess_healthcheck_get_value(
1376 module: AnsibleModule, api_version: LooseVersion, value: t.Any, sentry: Sentry
1377 ) -> t.Any | Sentry:
1378 if value is None or value is sentry or value.get("Test") == ["NONE"]:
1379 return {"Test": ["NONE"]}
1380 return value
1381
1382
1383 def _preprocess_convert_to_bytes(
1384 module: AnsibleModule,
1385 values: dict[str, t.Any],
1386 name: str,
1387 unlimited_value: int | None = None,
1388 ) -> dict[str, t.Any]:
1389 if name not in values:
1390 return values
1391 try:
1392 value = values[name]
1393 if unlimited_value is not None and value in ("unlimited", str(unlimited_value)):
1394 value = unlimited_value
1395 else:
1396 value = human_to_bytes(value)
1397 values[name] = value
1398 return values
1399 except ValueError as exc:
1400 module.fail_json(msg=f"Failed to convert {name} to bytes: {exc}")
1401
1402
1403 def _get_image_labels(image: dict[str, t.Any] | None) -> dict[str, str]:
1404 if not image:
1405 return {}
1406
1407 # Cannot use get('Labels', {}) because 'Labels' may be present and be None
1408 return image["Config"].get("Labels") or {}
1409
1410
1411 def _get_expected_labels_value(
1412 module: AnsibleModule,
1413 client: AnsibleDockerClient,
1414 api_version: LooseVersion,
1415 image: dict[str, t.Any] | None,
1416 value: dict[str, t.Any],
1417 sentry: Sentry,
1418 ) -> dict[str, t.Any] | Sentry:
1419 if value is sentry:
1420 return sentry
1421 expected_labels = {}
1422 if module.params["image_label_mismatch"] == "ignore":
1423 expected_labels.update(dict(_get_image_labels(image)))
1424 expected_labels.update(value)
1425 return expected_labels
1426
1427
1428 def _preprocess_links(
1429 module: AnsibleModule,
1430 client: AnsibleDockerClient,
1431 api_version: LooseVersion,
1432 value: t.Any,
1433 ) -> t.Any:
1434 if value is None:
1435 return None
1436
1437 result = []
1438 for link in value:
1439 parsed_link = link.split(":", 1)
1440 if len(parsed_link) == 2:
1441 link, alias = parsed_link
1442 else:
1443 link, alias = parsed_link[0], parsed_link[0]
1444 result.append(f"/{link}:/{module.params['name']}/{alias}")
1445
1446 return result
1447
1448
1449 def _ignore_mismatching_label_result(
1450 module: AnsibleModule,
1451 client: AnsibleDockerClient,
1452 api_version: LooseVersion,
1453 option: Option,
1454 image: dict[str, t.Any] | None,
1455 container_value: t.Any,
1456 expected_value: t.Any,
1457 host_info: dict[str, t.Any] | None,
1458 ) -> bool:
1459 if (
1460 option.comparison == "strict"
1461 and module.params["image_label_mismatch"] == "fail"
1462 ):
1463 # If there are labels from the base image that should be removed and
1464 # base_image_mismatch is fail we want raise an error.
1465 image_labels = _get_image_labels(image)
1466 would_remove_labels = []
1467 labels_param = module.params["labels"] or {}
1468 for label in image_labels:
1469 if label not in labels_param:
1470 # Format label for error message
1471 would_remove_labels.append(f'"{label}"')
1472 if would_remove_labels:
1473 labels = ", ".join(would_remove_labels)
1474 msg = (
1475 "Some labels should be removed but are present in the base image. You can set image_label_mismatch to 'ignore' to ignore"
1476 f" this error. Labels: {labels}"
1477 )
1478 client.fail(msg)
1479 return False
1480
1481
1482 def _needs_host_info_network(values: dict[str, t.Any]) -> bool:
1483 return values.get("network_mode") == "default"
1484
1485
1486 def _ignore_mismatching_network_result(
1487 module: AnsibleModule,
1488 client: AnsibleDockerClient,
1489 api_version: LooseVersion,
1490 option: Option,
1491 image: dict[str, t.Any] | None,
1492 container_value: t.Any,
1493 expected_value: t.Any,
1494 host_info: dict[str, t.Any] | None,
1495 ) -> bool:
1496 # 'networks' is handled out-of-band
1497 if option.name == "networks":
1498 return True
1499 # The 'default' network_mode value is translated by the Docker daemon to 'bridge' on Linux and 'nat' on Windows.
1500 # This happens since Docker 26.1.0 due to https://github.com/moby/moby/pull/47431; before, 'default' was returned.
1501 if option.name == "network_mode" and expected_value == "default":
1502 os_type = host_info.get("OSType") if host_info else None
1503 if (container_value, os_type) in (("bridge", "linux"), ("nat", "windows")):
1504 return True
1505 return False
1506
1507
1508 def _preprocess_network_values(
1509 module: AnsibleModule,
1510 client: AnsibleDockerClient,
1511 api_version: LooseVersion,
1512 options: list[Option],
1513 values: dict[str, t.Any],
1514 ) -> dict[str, t.Any]:
1515 if "networks" in values:
1516 for network in values["networks"]:
1517 network["id"] = _get_network_id(module, client, network["name"])
1518 if not network["id"]:
1519 client.fail(
1520 f"Parameter error: network named {network['name']} could not be found. Does it exist?"
1521 )
1522
1523 if "network_mode" in values:
1524 values["network_mode"] = _preprocess_container_names(
1525 module, client, api_version, values["network_mode"]
1526 )
1527
1528 return values
1529
1530
1531 def _get_network_id(
1532 module: AnsibleModule, client: AnsibleDockerClient, network_name: str
1533 ) -> str | None:
1534 try:
1535 params = {"filters": json.dumps({"name": [network_name]})}
1536 for network in client.get_json("/networks", params=params):
1537 if network["Name"] == network_name:
1538 return network["Id"]
1539 return None
1540 except Exception as exc: # pylint: disable=broad-exception-caught
1541 client.fail(f"Error getting network id for {network_name} - {exc}")
1542
1543
1544 def _get_values_network(
1545 module: AnsibleModule,
1546 container: dict[str, t.Any],
1547 api_version: LooseVersion,
1548 options: list[Option],
1549 image: dict[str, t.Any] | None,
1550 host_info: dict[str, t.Any] | None,
1551 ) -> dict[str, t.Any]:
1552 value = container["HostConfig"].get("NetworkMode", _SENTRY)
1553 if value is _SENTRY:
1554 return {}
1555 return {"network_mode": value}
1556
1557
1558 def _set_values_network(
1559 module: AnsibleModule,
1560 data: dict[str, t.Any],
1561 api_version: LooseVersion,
1562 options: list[Option],
1563 values: dict[str, t.Any],
1564 ) -> None:
1565 if "network_mode" not in values:
1566 return
1567 if "HostConfig" not in data:
1568 data["HostConfig"] = {}
1569 value = values["network_mode"]
1570 data["HostConfig"]["NetworkMode"] = value
1571
1572
1573 def _get_values_mounts(
1574 module: AnsibleModule,
1575 container: dict[str, t.Any],
1576 api_version: LooseVersion,
1577 options: list[Option],
1578 image: dict[str, t.Any] | None,
1579 host_info: dict[str, t.Any] | None,
1580 ) -> dict[str, t.Any]:
1581 volumes = container["Config"].get("Volumes")
1582 binds = container["HostConfig"].get("Binds")
1583 # According to https://github.com/moby/moby/, support for HostConfig.Mounts
1584 # has been included at least since v17.03.0-ce, which has API version 1.26.
1585 # The previous tag, v1.9.1, has API version 1.21 and does not have
1586 # HostConfig.Mounts. I have no idea what about API 1.25...
1587 mounts = container["HostConfig"].get("Mounts")
1588 if mounts is not None:
1589 mounts_list = []
1590 empty_dict: dict[str, t.Any] = {}
1591 for mount in mounts:
1592 mounts_list.append(
1593 {
1594 "type": mount.get("Type"),
1595 "source": mount.get("Source"),
1596 "target": mount.get("Target"),
1597 "read_only": mount.get(
1598 "ReadOnly", False
1599 ), # golang's omitempty for bool returns None for False
1600 "consistency": mount.get("Consistency"),
1601 "propagation": mount.get("BindOptions", empty_dict).get(
1602 "Propagation"
1603 ),
1604 "no_copy": mount.get("VolumeOptions", empty_dict).get(
1605 "NoCopy", False
1606 ),
1607 "labels": mount.get("VolumeOptions", empty_dict).get(
1608 "Labels", empty_dict
1609 ),
1610 "volume_driver": mount.get("VolumeOptions", empty_dict)
1611 .get("DriverConfig", empty_dict)
1612 .get("Name"),
1613 "volume_options": mount.get("VolumeOptions", empty_dict)
1614 .get("DriverConfig", empty_dict)
1615 .get("Options", empty_dict),
1616 "tmpfs_size": mount.get("TmpfsOptions", empty_dict).get(
1617 "SizeBytes"
1618 ),
1619 "tmpfs_mode": mount.get("TmpfsOptions", empty_dict).get("Mode"),
1620 "non_recursive": mount.get("BindOptions", empty_dict).get(
1621 "NonRecursive"
1622 ),
1623 "create_mountpoint": mount.get("BindOptions", empty_dict).get(
1624 "CreateMountpoint"
1625 ),
1626 "read_only_non_recursive": mount.get("BindOptions", empty_dict).get(
1627 "ReadOnlyNonRecursive"
1628 ),
1629 "read_only_force_recursive": mount.get(
1630 "BindOptions", empty_dict
1631 ).get("ReadOnlyForceRecursive"),
1632 "subpath": mount.get("VolumeOptions", empty_dict).get("Subpath")
1633 or mount.get("ImageOptions", empty_dict).get("Subpath"),
1634 "tmpfs_options": mount.get("TmpfsOptions", empty_dict).get(
1635 "Options"
1636 ),
1637 }
1638 )
1639 mounts = mounts_list
1640 result = {}
1641 if volumes is not None:
1642 result["volumes"] = volumes
1643 if binds is not None:
1644 result["volume_binds"] = binds
1645 if mounts is not None:
1646 result["mounts"] = mounts
1647 return result
1648
1649
1650 def _get_bind_from_dict(volume_dict: dict[str, t.Any] | None) -> list[str]:
1651 results = []
1652 if volume_dict:
1653 for host_path, config in volume_dict.items():
1654 if isinstance(config, dict) and config.get("bind"):
1655 container_path = config.get("bind")
1656 mode = config.get("mode", "rw")
1657 results.append(f"{host_path}:{container_path}:{mode}")
1658 return results
1659
1660
1661 def _get_image_binds(volumes: dict[str, t.Any] | list[dict[str, t.Any]]) -> list[str]:
1662 """
1663 Convert array of binds to array of strings with format host_path:container_path:mode
1664
1665 :param volumes: array of bind dicts
1666 :return: array of strings
1667 """
1668 results = []
1669 if isinstance(volumes, dict):
1670 results += _get_bind_from_dict(volumes)
1671 elif isinstance(volumes, list):
1672 for vol in volumes:
1673 results += _get_bind_from_dict(vol)
1674 return results
1675
1676
1677 def _get_expected_values_mounts(
1678 module: AnsibleModule,
1679 client: AnsibleDockerClient,
1680 api_version: LooseVersion,
1681 options: list[Option],
1682 image: dict[str, t.Any] | None,
1683 values: dict[str, t.Any],
1684 host_info: dict[str, t.Any] | None,
1685 ) -> dict[str, t.Any]:
1686 expected_values = {}
1687
1688 # binds
1689 if "mounts" in values:
1690 expected_values["mounts"] = values["mounts"]
1691
1692 # volumes
1693 expected_vols = {}
1694 if image and image["Config"].get("Volumes"):
1695 expected_vols.update(image["Config"].get("Volumes"))
1696 if "volumes" in values:
1697 for vol in values["volumes"]:
1698 # We only expect anonymous volumes to show up in the list
1699 if ":" in vol:
1700 parts = vol.split(":")
1701 if len(parts) == 3:
1702 continue
1703 if len(parts) == 2 and not _is_volume_permissions(parts[1]):
1704 continue
1705 expected_vols[vol] = {}
1706 if expected_vols:
1707 expected_values["volumes"] = expected_vols
1708
1709 # binds
1710 image_vols = []
1711 if image:
1712 image_vols = _get_image_binds(image["Config"].get("Volumes"))
1713 param_vols = []
1714 if "volume_binds" in values:
1715 param_vols = values["volume_binds"]
1716 expected_values["volume_binds"] = list(set(image_vols + param_vols))
1717
1718 return expected_values
1719
1720
1721 def _set_values_mounts(
1722 module: AnsibleModule,
1723 data: dict[str, t.Any],
1724 api_version: LooseVersion,
1725 options: list[Option],
1726 values: dict[str, t.Any],
1727 ) -> None:
1728 if "mounts" in values:
1729 if "HostConfig" not in data:
1730 data["HostConfig"] = {}
1731 mounts: list[dict[str, t.Any]] = []
1732 for mount in values["mounts"]:
1733 mount_type = mount.get("type")
1734 mount_res = {
1735 "Target": mount.get("target"),
1736 "Source": mount.get("source"),
1737 "Type": mount_type,
1738 "ReadOnly": mount.get("read_only"),
1739 }
1740 if "consistency" in mount:
1741 mount_res["Consistency"] = mount["consistency"]
1742 if mount_type == "bind":
1743 bind_opts: dict[str, t.Any] = {}
1744 if "propagation" in mount:
1745 bind_opts["Propagation"] = mount["propagation"]
1746 if "non_recursive" in mount:
1747 bind_opts["NonRecursive"] = mount["non_recursive"]
1748 if "create_mountpoint" in mount:
1749 bind_opts["CreateMountpoint"] = mount["create_mountpoint"]
1750 if "read_only_non_recursive" in mount:
1751 bind_opts["ReadOnlyNonRecursive"] = mount["read_only_non_recursive"]
1752 if "read_only_force_recursive" in mount:
1753 bind_opts["ReadOnlyForceRecursive"] = mount[
1754 "read_only_force_recursive"
1755 ]
1756 if bind_opts:
1757 mount_res["BindOptions"] = bind_opts
1758 if mount_type == "volume":
1759 volume_opts: dict[str, t.Any] = {}
1760 if mount.get("no_copy"):
1761 volume_opts["NoCopy"] = True
1762 if mount.get("labels"):
1763 volume_opts["Labels"] = mount.get("labels")
1764 if mount.get("volume_driver"):
1765 driver_config: dict[str, t.Any] = {
1766 "Name": mount.get("volume_driver"),
1767 }
1768 if mount.get("volume_options"):
1769 driver_config["Options"] = mount.get("volume_options")
1770 volume_opts["DriverConfig"] = driver_config
1771 if "subpath" in mount:
1772 volume_opts["Subpath"] = mount["subpath"]
1773 if volume_opts:
1774 mount_res["VolumeOptions"] = volume_opts
1775 if mount_type == "tmpfs":
1776 tmpfs_opts: dict[str, t.Any] = {}
1777 if mount.get("tmpfs_mode"):
1778 tmpfs_opts["Mode"] = mount.get("tmpfs_mode")
1779 if mount.get("tmpfs_size"):
1780 tmpfs_opts["SizeBytes"] = mount.get("tmpfs_size")
1781 if "tmpfs_options" in mount:
1782 tmpfs_opts["Options"] = mount["tmpfs_options"]
1783 if tmpfs_opts:
1784 mount_res["TmpfsOptions"] = tmpfs_opts
1785 if mount_type == "image":
1786 image_opts: dict[str, t.Any] = {}
1787 if "subpath" in mount:
1788 image_opts["Subpath"] = mount["subpath"]
1789 if image_opts:
1790 mount_res["ImageOptions"] = image_opts
1791 mounts.append(mount_res)
1792 data["HostConfig"]["Mounts"] = mounts
1793 if "volumes" in values:
1794 volumes: dict[str, t.Any] = {}
1795 for volume in values["volumes"]:
1796 # Only pass anonymous volumes to create container
1797 if ":" in volume:
1798 parts = volume.split(":")
1799 if len(parts) == 3:
1800 continue
1801 if len(parts) == 2 and not _is_volume_permissions(parts[1]):
1802 continue
1803 volumes[volume] = {}
1804 data["Volumes"] = volumes
1805 if "volume_binds" in values:
1806 if "HostConfig" not in data:
1807 data["HostConfig"] = {}
1808 data["HostConfig"]["Binds"] = values["volume_binds"]
1809
1810
1811 def _get_values_log(
1812 module: AnsibleModule,
1813 container: dict[str, t.Any],
1814 api_version: LooseVersion,
1815 options: list[Option],
1816 image: dict[str, t.Any] | None,
1817 host_info: dict[str, t.Any] | None,
1818 ) -> dict[str, t.Any]:
1819 log_config = container["HostConfig"].get("LogConfig") or {}
1820 return {
1821 "log_driver": log_config.get("Type"),
1822 "log_options": log_config.get("Config"),
1823 }
1824
1825
1826 def _set_values_log(
1827 module: AnsibleModule,
1828 data: dict[str, t.Any],
1829 api_version: LooseVersion,
1830 options: list[Option],
1831 values: dict[str, t.Any],
1832 ) -> None:
1833 if "log_driver" not in values:
1834 return
1835 log_config = {
1836 "Type": values["log_driver"],
1837 "Config": values.get("log_options") or {},
1838 }
1839 if "HostConfig" not in data:
1840 data["HostConfig"] = {}
1841 data["HostConfig"]["LogConfig"] = log_config
1842
1843
1844 def _get_values_platform(
1845 module: AnsibleModule,
1846 container: dict[str, t.Any],
1847 api_version: LooseVersion,
1848 options: list[Option],
1849 image: dict[str, t.Any] | None,
1850 host_info: dict[str, t.Any] | None,
1851 ) -> dict[str, t.Any]:
1852 if image and (image.get("Os") or image.get("Architecture") or image.get("Variant")):
1853 return {
1854 "platform": compose_platform_string(
1855 os=image.get("Os"),
1856 arch=image.get("Architecture"),
1857 variant=image.get("Variant"),
1858 daemon_os=host_info.get("OSType") if host_info else None,
1859 daemon_arch=host_info.get("Architecture") if host_info else None,
1860 )
1861 }
1862 return {
1863 "platform": container.get("Platform"),
1864 }
1865
1866
1867 def _get_expected_values_platform(
1868 module: AnsibleModule,
1869 client: AnsibleDockerClient,
1870 api_version: LooseVersion,
1871 options: list[Option],
1872 image: dict[str, t.Any] | None,
1873 values: dict[str, t.Any],
1874 host_info: dict[str, t.Any] | None,
1875 ) -> dict[str, t.Any]:
1876 expected_values = {}
1877 if "platform" in values:
1878 try:
1879 expected_values["platform"] = normalize_platform_string(
1880 values["platform"],
1881 daemon_os=host_info.get("OSType") if host_info else None,
1882 daemon_arch=host_info.get("Architecture") if host_info else None,
1883 )
1884 except ValueError as exc:
1885 module.fail_json(msg=f"Error while parsing platform parameer: {exc}")
1886 return expected_values
1887
1888
1889 def _set_values_platform(
1890 module: AnsibleModule,
1891 data: dict[str, t.Any],
1892 api_version: LooseVersion,
1893 options: list[Option],
1894 values: dict[str, t.Any],
1895 ) -> None:
1896 if "platform" in values:
1897 data["platform"] = values["platform"]
1898
1899
1900 def _needs_container_image_platform(values: dict[str, t.Any]) -> bool:
1901 return "platform" in values
1902
1903
1904 def _needs_host_info_platform(values: dict[str, t.Any]) -> bool:
1905 return "platform" in values
1906
1907
1908 def _get_values_restart(
1909 module: AnsibleModule,
1910 container: dict[str, t.Any],
1911 api_version: LooseVersion,
1912 options: list[Option],
1913 image: dict[str, t.Any] | None,
1914 host_info: dict[str, t.Any] | None,
1915 ) -> dict[str, t.Any]:
1916 restart_policy = container["HostConfig"].get("RestartPolicy") or {}
1917 return {
1918 "restart_policy": restart_policy.get("Name"),
1919 "restart_retries": restart_policy.get("MaximumRetryCount"),
1920 }
1921
1922
1923 def _set_values_restart(
1924 module: AnsibleModule,
1925 data: dict[str, t.Any],
1926 api_version: LooseVersion,
1927 options: list[Option],
1928 values: dict[str, t.Any],
1929 ) -> None:
1930 if "restart_policy" not in values:
1931 return
1932 restart_policy = {
1933 "Name": values["restart_policy"],
1934 "MaximumRetryCount": values.get("restart_retries"),
1935 }
1936 if "HostConfig" not in data:
1937 data["HostConfig"] = {}
1938 data["HostConfig"]["RestartPolicy"] = restart_policy
1939
1940
1941 def _update_value_restart(
1942 module: AnsibleModule,
1943 data: dict[str, t.Any],
1944 api_version: LooseVersion,
1945 options: list[Option],
1946 values: dict[str, t.Any],
1947 ) -> None:
1948 if "restart_policy" not in values:
1949 return
1950 data["RestartPolicy"] = {
1951 "Name": values["restart_policy"],
1952 "MaximumRetryCount": values.get("restart_retries"),
1953 }
1954
1955
1956 def _get_values_ports(
1957 module: AnsibleModule,
1958 container: dict[str, t.Any],
1959 api_version: LooseVersion,
1960 options: list[Option],
1961 image: dict[str, t.Any] | None,
1962 host_info: dict[str, t.Any] | None,
1963 ) -> dict[str, t.Any]:
1964 host_config = container["HostConfig"]
1965 config = container["Config"]
1966
1967 # "ExposedPorts": null returns None type & causes AttributeError - PR #5517
1968 expected_exposed: list[str] = []
1969 if config.get("ExposedPorts") is not None:
1970 for port_and_protocol in config.get("ExposedPorts", {}):
1971 port, protocol = _normalize_port(port_and_protocol).rsplit("/")
1972 try:
1973 start, end = port.split("-", 1)
1974 start_port = int(start)
1975 end_port = int(end)
1976 for port_no in range(start_port, end_port + 1):
1977 expected_exposed.append(f"{port_no}/{protocol}")
1978 continue
1979 except ValueError:
1980 # Either it is not a range, or a broken one - in both cases, simply add the original form
1981 expected_exposed.append(f"{port}/{protocol}")
1982
1983 return {
1984 "published_ports": host_config.get("PortBindings"),
1985 "exposed_ports": expected_exposed,
1986 "publish_all_ports": host_config.get("PublishAllPorts"),
1987 }
1988
1989
1990 def _get_expected_values_ports(
1991 module: AnsibleModule,
1992 client: AnsibleDockerClient,
1993 api_version: LooseVersion,
1994 options: list[Option],
1995 image: dict[str, t.Any] | None,
1996 values: dict[str, t.Any],
1997 host_info: dict[str, t.Any] | None,
1998 ) -> dict[str, t.Any]:
1999 expected_values: dict[str, t.Any] = {}
2000
2001 if "published_ports" in values:
2002 expected_bound_ports = {}
2003 for container_port, config in values["published_ports"].items():
2004 if isinstance(container_port, int):
2005 container_port = f"{container_port}/tcp"
2006 if len(config) == 1:
2007 if isinstance(config[0], int):
2008 expected_bound_ports[container_port] = [
2009 {"HostIp": "0.0.0.0", "HostPort": config[0]}
2010 ]
2011 else:
2012 expected_bound_ports[container_port] = [
2013 {"HostIp": config[0], "HostPort": ""}
2014 ]
2015 elif isinstance(config[0], tuple):
2016 expected_bound_ports[container_port] = []
2017 for host_ip, host_port in config:
2018 expected_bound_ports[container_port].append(
2019 {
2020 "HostIp": host_ip,
2021 "HostPort": to_text(
2022 host_port, errors="surrogate_or_strict"
2023 ),
2024 }
2025 )
2026 else:
2027 expected_bound_ports[container_port] = [
2028 {
2029 "HostIp": config[0],
2030 "HostPort": to_text(config[1], errors="surrogate_or_strict"),
2031 }
2032 ]
2033 expected_values["published_ports"] = expected_bound_ports
2034
2035 image_ports: set[str] = set()
2036 if image:
2037 image_exposed_ports = image["Config"].get("ExposedPorts") or {}
2038 image_ports = {_normalize_port(p) for p in image_exposed_ports}
2039 param_ports: set[str] = set()
2040 if "ports" in values:
2041 param_ports = {f"{p[0]}/{p[1]}" for p in values["ports"]}
2042 result = sorted(image_ports | param_ports)
2043 expected_values["exposed_ports"] = result
2044
2045 if "publish_all_ports" in values:
2046 expected_values["publish_all_ports"] = values["publish_all_ports"]
2047
2048 return expected_values
2049
2050
2051 def _set_values_ports(
2052 module: AnsibleModule,
2053 data: dict[str, t.Any],
2054 api_version: LooseVersion,
2055 options: list[Option],
2056 values: dict[str, t.Any],
2057 ) -> None:
2058 if "ports" in values:
2059 exposed_ports: dict[str, dict[str, t.Any]] = {}
2060 for port_definition in values["ports"]:
2061 port = port_definition
2062 proto = "tcp"
2063 if isinstance(port_definition, tuple):
2064 if len(port_definition) == 2:
2065 proto = port_definition[1]
2066 port = port_definition[0]
2067 exposed_ports[f"{port}/{proto}"] = {}
2068 data["ExposedPorts"] = exposed_ports
2069 if "published_ports" in values:
2070 if "HostConfig" not in data:
2071 data["HostConfig"] = {}
2072 data["HostConfig"]["PortBindings"] = convert_port_bindings(
2073 values["published_ports"]
2074 )
2075 if "publish_all_ports" in values and values["publish_all_ports"]:
2076 if "HostConfig" not in data:
2077 data["HostConfig"] = {}
2078 data["HostConfig"]["PublishAllPorts"] = values["publish_all_ports"]
2079
2080
2081 def _preprocess_value_ports(
2082 module: AnsibleModule,
2083 client: AnsibleDockerClient,
2084 api_version: LooseVersion,
2085 options: list[Option],
2086 values: dict[str, t.Any],
2087 ) -> dict[str, t.Any]:
2088 if "published_ports" not in values:
2089 return values
2090 found = False
2091 for port_specs in values["published_ports"].values():
2092 if not isinstance(port_specs, list):
2093 port_specs = [port_specs]
2094 for port_spec in port_specs:
2095 if port_spec[0] == _DEFAULT_IP_REPLACEMENT_STRING:
2096 found = True
2097 break
2098 if not found:
2099 return values
2100 default_ip = _get_default_host_ip(module, client)
2101 for port, port_specs in values["published_ports"].items():
2102 if isinstance(port_specs, list):
2103 for index, port_spec in enumerate(port_specs):
2104 if port_spec[0] == _DEFAULT_IP_REPLACEMENT_STRING:
2105 port_specs[index] = tuple([default_ip] + list(port_spec[1:]))
2106 else:
2107 if port_specs[0] == _DEFAULT_IP_REPLACEMENT_STRING:
2108 values["published_ports"][port] = tuple(
2109 [default_ip] + list(port_specs[1:])
2110 )
2111 return values
2112
2113
2114 def _preprocess_container_names(
2115 module: AnsibleModule,
2116 client: AnsibleDockerClient,
2117 api_version: LooseVersion,
2118 value: t.Any,
2119 ) -> t.Any:
2120 if value is None or not value.startswith("container:"):
2121 return value
2122 container_name = value[len("container:") :]
2123 # Try to inspect container to see whether this is an ID or a
2124 # name (and in the latter case, retrieve its ID)
2125 container = client.get_container(container_name)
2126 if container is None:
2127 # If we cannot find the container, issue a warning and continue with
2128 # what the user specified.
2129 module.warn(f'Cannot find a container with name or ID "{container_name}"')
2130 return value
2131 return f"container:{container['Id']}"
2132
2133
2134 def _get_value_command(
2135 module: AnsibleModule,
2136 container: dict[str, t.Any],
2137 api_version: LooseVersion,
2138 options: list[Option],
2139 image: dict[str, t.Any] | None,
2140 host_info: dict[str, t.Any] | None,
2141 ) -> dict[str, t.Any]:
2142 value = container["Config"].get("Cmd", _SENTRY)
2143 if value is _SENTRY:
2144 return {}
2145 return {"command": value}
2146
2147
2148 def _set_value_command(
2149 module: AnsibleModule,
2150 data: dict[str, t.Any],
2151 api_version: LooseVersion,
2152 options: list[Option],
2153 values: dict[str, t.Any],
2154 ) -> None:
2155 if "command" not in values:
2156 return
2157 value = values["command"]
2158 data["Cmd"] = value
2159
2160
2161 def _get_expected_values_command(
2162 module: AnsibleModule,
2163 client: AnsibleDockerClient,
2164 api_version: LooseVersion,
2165 options: list[Option],
2166 image: dict[str, t.Any] | None,
2167 values: dict[str, t.Any],
2168 host_info: dict[str, t.Any] | None,
2169 ) -> dict[str, t.Any]:
2170 expected_values = {}
2171 if "command" in values:
2172 command = values["command"]
2173 if command == [] and image and image["Config"].get("Cmd"):
2174 command = image["Config"].get("Cmd")
2175 expected_values["command"] = command
2176 return expected_values
2177
2178
2179 def _needs_container_image_command(values: dict[str, t.Any]) -> bool:
2180 return values.get("command") == []
2181
2182
2183 OPTION_AUTO_REMOVE.add_engine(
2184 "docker_api", DockerAPIEngine.host_config_value("AutoRemove")
2185 )
2186
2187 OPTION_BLKIO_WEIGHT.add_engine(
2188 "docker_api",
2189 DockerAPIEngine.host_config_value("BlkioWeight", update_parameter="BlkioWeight"),
2190 )
2191
2192 OPTION_CAPABILITIES.add_engine(
2193 "docker_api", DockerAPIEngine.host_config_value("CapAdd")
2194 )
2195
2196 OPTION_CAP_DROP.add_engine("docker_api", DockerAPIEngine.host_config_value("CapDrop"))
2197
2198 OPTION_CGROUP_NS_MODE.add_engine(
2199 "docker_api",
2200 DockerAPIEngine.host_config_value("CgroupnsMode", min_api_version="1.41"),
2201 )
2202
2203 OPTION_CGROUP_PARENT.add_engine(
2204 "docker_api", DockerAPIEngine.host_config_value("CgroupParent")
2205 )
2206
2207 OPTION_COMMAND.add_engine(
2208 "docker_api",
2209 DockerAPIEngine(
2210 get_value=_get_value_command,
2211 set_value=_set_value_command,
2212 get_expected_values=_get_expected_values_command,
2213 needs_container_image=_needs_container_image_command,
2214 ),
2215 )
2216
2217 OPTION_CPU_PERIOD.add_engine(
2218 "docker_api",
2219 DockerAPIEngine.host_config_value("CpuPeriod", update_parameter="CpuPeriod"),
2220 )
2221
2222 OPTION_CPU_QUOTA.add_engine(
2223 "docker_api",
2224 DockerAPIEngine.host_config_value("CpuQuota", update_parameter="CpuQuota"),
2225 )
2226
2227 OPTION_CPUSET_CPUS.add_engine(
2228 "docker_api",
2229 DockerAPIEngine.host_config_value("CpusetCpus", update_parameter="CpusetCpus"),
2230 )
2231
2232 OPTION_CPUSET_MEMS.add_engine(
2233 "docker_api",
2234 DockerAPIEngine.host_config_value("CpusetMems", update_parameter="CpusetMems"),
2235 )
2236
2237 OPTION_CPU_SHARES.add_engine(
2238 "docker_api",
2239 DockerAPIEngine.host_config_value("CpuShares", update_parameter="CpuShares"),
2240 )
2241
2242 OPTION_ENTRYPOINT.add_engine("docker_api", DockerAPIEngine.config_value("Entrypoint"))
2243
2244 OPTION_CPUS.add_engine(
2245 "docker_api",
2246 DockerAPIEngine.host_config_value("NanoCpus", preprocess_value=_preprocess_cpus),
2247 )
2248
2249 OPTION_DETACH_INTERACTIVE.add_engine(
2250 "docker_api",
2251 DockerAPIEngine(
2252 get_value=_get_value_detach_interactive, set_value=_set_value_detach_interactive
2253 ),
2254 )
2255
2256 OPTION_DEVICES.add_engine(
2257 "docker_api",
2258 DockerAPIEngine.host_config_value("Devices", preprocess_value=_preprocess_devices),
2259 )
2260
2261 OPTION_DEVICE_READ_BPS.add_engine(
2262 "docker_api",
2263 DockerAPIEngine.host_config_value(
2264 "BlkioDeviceReadBps", preprocess_value=_preprocess_rate_bps
2265 ),
2266 )
2267
2268 OPTION_DEVICE_WRITE_BPS.add_engine(
2269 "docker_api",
2270 DockerAPIEngine.host_config_value(
2271 "BlkioDeviceWriteBps", preprocess_value=_preprocess_rate_bps
2272 ),
2273 )
2274
2275 OPTION_DEVICE_READ_IOPS.add_engine(
2276 "docker_api",
2277 DockerAPIEngine.host_config_value(
2278 "BlkioDeviceReadIOps", preprocess_value=_preprocess_rate_iops
2279 ),
2280 )
2281
2282 OPTION_DEVICE_WRITE_IOPS.add_engine(
2283 "docker_api",
2284 DockerAPIEngine.host_config_value(
2285 "BlkioDeviceWriteIOps", preprocess_value=_preprocess_rate_iops
2286 ),
2287 )
2288
2289 OPTION_DEVICE_REQUESTS.add_engine(
2290 "docker_api",
2291 DockerAPIEngine.host_config_value(
2292 "DeviceRequests",
2293 min_api_version="1.40",
2294 preprocess_value=_preprocess_device_requests,
2295 ),
2296 )
2297
2298 OPTION_DEVICE_CGROUP_RULES.add_engine(
2299 "docker_api",
2300 DockerAPIEngine.host_config_value("DeviceCgroupRules", min_api_version="1.28"),
2301 )
2302
2303 OPTION_DNS_SERVERS.add_engine("docker_api", DockerAPIEngine.host_config_value("Dns"))
2304
2305 OPTION_DNS_OPTS.add_engine(
2306 "docker_api", DockerAPIEngine.host_config_value("DnsOptions")
2307 )
2308
2309 OPTION_DNS_SEARCH_DOMAINS.add_engine(
2310 "docker_api", DockerAPIEngine.host_config_value("DnsSearch")
2311 )
2312
2313 OPTION_DOMAINNAME.add_engine("docker_api", DockerAPIEngine.config_value("Domainname"))
2314
2315 OPTION_ENVIRONMENT.add_engine(
2316 "docker_api",
2317 DockerAPIEngine.config_value("Env", get_expected_value=_get_expected_env_value),
2318 )
2319
2320 OPTION_ETC_HOSTS.add_engine(
2321 "docker_api",
2322 DockerAPIEngine.host_config_value(
2323 "ExtraHosts", preprocess_value=_preprocess_etc_hosts
2324 ),
2325 )
2326
2327 OPTION_GROUPS.add_engine("docker_api", DockerAPIEngine.host_config_value("GroupAdd"))
2328
2329 OPTION_HEALTHCHECK.add_engine(
2330 "docker_api",
2331 DockerAPIEngine.config_value(
2332 "Healthcheck",
2333 preprocess_value=_preprocess_healthcheck,
2334 postprocess_for_get=_postprocess_healthcheck_get_value,
2335 extra_option_minimal_versions={
2336 "healthcheck.start_interval": {
2337 "docker_api_version": "1.44",
2338 "detect_usage": lambda c: c.module.params["healthcheck"]
2339 and c.module.params["healthcheck"]["start_interval"] is not None,
2340 },
2341 },
2342 ),
2343 )
2344
2345 OPTION_HOSTNAME.add_engine("docker_api", DockerAPIEngine.config_value("Hostname"))
2346
2347 OPTION_IMAGE.add_engine(
2348 "docker_api",
2349 DockerAPIEngine.config_value(
2350 "Image",
2351 ignore_mismatching_result=lambda module, client, api_version, option, image, container_value, expected_value, host_info: True,
2352 ),
2353 )
2354
2355 OPTION_INIT.add_engine("docker_api", DockerAPIEngine.host_config_value("Init"))
2356
2357 OPTION_IPC_MODE.add_engine(
2358 "docker_api",
2359 DockerAPIEngine.host_config_value(
2360 "IpcMode", preprocess_value=_preprocess_container_names
2361 ),
2362 )
2363
2364 OPTION_KERNEL_MEMORY.add_engine(
2365 "docker_api",
2366 DockerAPIEngine.host_config_value("KernelMemory", update_parameter="KernelMemory"),
2367 )
2368
2369 OPTION_LABELS.add_engine(
2370 "docker_api",
2371 DockerAPIEngine.config_value(
2372 "Labels",
2373 get_expected_value=_get_expected_labels_value,
2374 ignore_mismatching_result=_ignore_mismatching_label_result,
2375 ),
2376 )
2377
2378 OPTION_LINKS.add_engine(
2379 "docker_api",
2380 DockerAPIEngine.host_config_value("Links", preprocess_value=_preprocess_links),
2381 )
2382
2383 OPTION_LOG_DRIVER_OPTIONS.add_engine(
2384 "docker_api",
2385 DockerAPIEngine(
2386 get_value=_get_values_log,
2387 set_value=_set_values_log,
2388 ),
2389 )
2390
2391 OPTION_MAC_ADDRESS.add_engine("docker_api", DockerAPIEngine.config_value("MacAddress"))
2392
2393 OPTION_MEMORY.add_engine(
2394 "docker_api", DockerAPIEngine.host_config_value("Memory", update_parameter="Memory")
2395 )
2396
2397 OPTION_MEMORY_RESERVATION.add_engine(
2398 "docker_api",
2399 DockerAPIEngine.host_config_value(
2400 "MemoryReservation", update_parameter="MemoryReservation"
2401 ),
2402 )
2403
2404 OPTION_MEMORY_SWAP.add_engine(
2405 "docker_api",
2406 DockerAPIEngine.host_config_value("MemorySwap", update_parameter="MemorySwap"),
2407 )
2408
2409 OPTION_MEMORY_SWAPPINESS.add_engine(
2410 "docker_api", DockerAPIEngine.host_config_value("MemorySwappiness")
2411 )
2412
2413 OPTION_STOP_TIMEOUT.add_engine(
2414 "docker_api", DockerAPIEngine.config_value("StopTimeout")
2415 )
2416
2417 OPTION_NETWORK.add_engine(
2418 "docker_api",
2419 DockerAPIEngine(
2420 preprocess_value=_preprocess_network_values,
2421 get_value=_get_values_network,
2422 set_value=_set_values_network,
2423 ignore_mismatching_result=_ignore_mismatching_network_result,
2424 needs_host_info=_needs_host_info_network,
2425 extra_option_minimal_versions={
2426 "networks.mac_address": {
2427 "docker_api_version": "1.44",
2428 "detect_usage": lambda c: any(
2429 net_info.get("mac_address") is not None
2430 for net_info in (c.module.params["networks"] or [])
2431 ),
2432 },
2433 "networks.driver_opts": {
2434 "docker_api_version": "1.32",
2435 "detect_usage": lambda c: any(
2436 net_info.get("driver_opts") is not None
2437 for net_info in (c.module.params["networks"] or [])
2438 ),
2439 },
2440 "networks.gw_priority": {
2441 "docker_api_version": "1.48",
2442 "detect_usage": lambda c: any(
2443 net_info.get("gw_priority") is not None
2444 for net_info in (c.module.params["networks"] or [])
2445 ),
2446 },
2447 },
2448 ),
2449 )
2450
2451 OPTION_OOM_KILLER.add_engine(
2452 "docker_api", DockerAPIEngine.host_config_value("OomKillDisable")
2453 )
2454
2455 OPTION_OOM_SCORE_ADJ.add_engine(
2456 "docker_api", DockerAPIEngine.host_config_value("OomScoreAdj")
2457 )
2458
2459 OPTION_PID_MODE.add_engine(
2460 "docker_api",
2461 DockerAPIEngine.host_config_value(
2462 "PidMode", preprocess_value=_preprocess_container_names
2463 ),
2464 )
2465
2466 OPTION_PIDS_LIMIT.add_engine(
2467 "docker_api", DockerAPIEngine.host_config_value("PidsLimit")
2468 )
2469
2470 OPTION_PLATFORM.add_engine(
2471 "docker_api",
2472 DockerAPIEngine(
2473 get_value=_get_values_platform,
2474 set_value=_set_values_platform,
2475 get_expected_values=_get_expected_values_platform,
2476 needs_container_image=_needs_container_image_platform,
2477 needs_host_info=_needs_host_info_platform,
2478 min_api_version="1.41",
2479 ),
2480 )
2481
2482 OPTION_PRIVILEGED.add_engine(
2483 "docker_api", DockerAPIEngine.host_config_value("Privileged")
2484 )
2485
2486 OPTION_READ_ONLY.add_engine(
2487 "docker_api", DockerAPIEngine.host_config_value("ReadonlyRootfs")
2488 )
2489
2490 OPTION_RESTART_POLICY.add_engine(
2491 "docker_api",
2492 DockerAPIEngine(
2493 get_value=_get_values_restart,
2494 set_value=_set_values_restart,
2495 update_value=_update_value_restart,
2496 ),
2497 )
2498
2499 OPTION_RUNTIME.add_engine("docker_api", DockerAPIEngine.host_config_value("Runtime"))
2500
2501 OPTION_SECURITY_OPTS.add_engine(
2502 "docker_api", DockerAPIEngine.host_config_value("SecurityOpt")
2503 )
2504
2505 OPTION_SHM_SIZE.add_engine("docker_api", DockerAPIEngine.host_config_value("ShmSize"))
2506
2507 OPTION_STOP_SIGNAL.add_engine("docker_api", DockerAPIEngine.config_value("StopSignal"))
2508
2509 OPTION_STORAGE_OPTS.add_engine(
2510 "docker_api", DockerAPIEngine.host_config_value("StorageOpt")
2511 )
2512
2513 OPTION_SYSCTLS.add_engine("docker_api", DockerAPIEngine.host_config_value("Sysctls"))
2514
2515 OPTION_TMPFS.add_engine("docker_api", DockerAPIEngine.host_config_value("Tmpfs"))
2516
2517 OPTION_TTY.add_engine("docker_api", DockerAPIEngine.config_value("Tty"))
2518
2519 OPTION_ULIMITS.add_engine("docker_api", DockerAPIEngine.host_config_value("Ulimits"))
2520
2521 OPTION_USER.add_engine("docker_api", DockerAPIEngine.config_value("User"))
2522
2523 OPTION_USERNS_MODE.add_engine(
2524 "docker_api", DockerAPIEngine.host_config_value("UsernsMode")
2525 )
2526
2527 OPTION_UTS.add_engine("docker_api", DockerAPIEngine.host_config_value("UTSMode"))
2528
2529 OPTION_VOLUME_DRIVER.add_engine(
2530 "docker_api", DockerAPIEngine.host_config_value("VolumeDriver")
2531 )
2532
2533 OPTION_VOLUMES_FROM.add_engine(
2534 "docker_api", DockerAPIEngine.host_config_value("VolumesFrom")
2535 )
2536
2537 OPTION_WORKING_DIR.add_engine("docker_api", DockerAPIEngine.config_value("WorkingDir"))
2538
2539 OPTION_MOUNTS_VOLUMES.add_engine(
2540 "docker_api",
2541 DockerAPIEngine(
2542 get_value=_get_values_mounts,
2543 get_expected_values=_get_expected_values_mounts,
2544 set_value=_set_values_mounts,
2545 extra_option_minimal_versions={
2546 "mounts.non_recursive": {
2547 "docker_api_version": "1.40",
2548 "detect_usage": lambda c: any(
2549 mount.get("non_recursive") is not None
2550 for mount in (c.module.params["mounts"] or [])
2551 ),
2552 },
2553 "mounts.create_mountpoint": {
2554 "docker_api_version": "1.42",
2555 "detect_usage": lambda c: any(
2556 mount.get("create_mountpoint") is not None
2557 for mount in (c.module.params["mounts"] or [])
2558 ),
2559 },
2560 "mounts.type=cluster": {
2561 "docker_api_version": "1.42",
2562 "detect_usage": lambda c: any(
2563 mount.get("type") == "cluster"
2564 for mount in (c.module.params["mounts"] or [])
2565 ),
2566 },
2567 "mounts.read_only_non_recursive": {
2568 "docker_api_version": "1.44",
2569 "detect_usage": lambda c: any(
2570 mount.get("read_only_non_recursive") is not None
2571 for mount in (c.module.params["mounts"] or [])
2572 ),
2573 },
2574 "mounts.read_only_force_recursive": {
2575 "docker_api_version": "1.44",
2576 "detect_usage": lambda c: any(
2577 mount.get("read_only_force_recursive") is not None
2578 for mount in (c.module.params["mounts"] or [])
2579 ),
2580 },
2581 "mounts.subpath": {
2582 "docker_api_version": "1.45",
2583 "detect_usage": lambda c: any(
2584 mount.get("subpath") is not None
2585 for mount in (c.module.params["mounts"] or [])
2586 ),
2587 },
2588 "mounts.tmpfs_options": {
2589 "docker_api_version": "1.46",
2590 "detect_usage": lambda c: any(
2591 mount.get("tmpfs_options") is not None
2592 for mount in (c.module.params["mounts"] or [])
2593 ),
2594 },
2595 "mounts.type=image": {
2596 "docker_api_version": "1.47",
2597 "detect_usage": lambda c: any(
2598 mount.get("type") == "image"
2599 for mount in (c.module.params["mounts"] or [])
2600 ),
2601 },
2602 },
2603 ),
2604 )
2605
2606 OPTION_PORTS.add_engine(
2607 "docker_api",
2608 DockerAPIEngine(
2609 get_value=_get_values_ports,
2610 get_expected_values=_get_expected_values_ports,
2611 set_value=_set_values_ports,
2612 preprocess_value=_preprocess_value_ports,
2613 ),
2614 )