Debian Codegraph @

ansible_collections/community/docker/plugins/module_utils/_module_container/module.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 re
12 import typing as t
13 from time import sleep
14
15 from ansible.module_utils.common.text.converters import to_text
16
17 from ansible_collections.community.docker.plugins.module_utils._api.utils.utils import (
18 parse_repository_tag,
19 )
20 from ansible_collections.community.docker.plugins.module_utils._module_container.base import (
21 Client,
22 )
23 from ansible_collections.community.docker.plugins.module_utils._util import (
24 DifferenceTracker,
25 DockerBaseClass,
26 compare_generic,
27 is_image_name_id,
28 normalize_ip_address,
29 sanitize_result,
30 )
31
32 if t.TYPE_CHECKING:
33 from collections.abc import Sequence
34
35 from ansible.module_utils.basic import AnsibleModule
36
37 from .base import Engine, EngineDriver, Option, OptionGroup
38
39
40 class Container(DockerBaseClass):
41 def __init__(
42 self, container: dict[str, t.Any] | None, engine_driver: EngineDriver
43 ) -> None:
44 super().__init__()
45 self.raw = container
46 self.id: str | None = None
47 self.image: str | None = None
48 self.image_name: str | None = None
49 self.container = container
50 self.engine_driver = engine_driver
51 if container:
52 self.id = engine_driver.get_container_id(container)
53 self.image = engine_driver.get_image_from_container(container)
54 self.image_name = engine_driver.get_image_name_from_container(container)
55 self.log(self.container, pretty_print=True)
56
57 @property
58 def exists(self) -> bool:
59 return bool(self.container)
60
61 @property
62 def removing(self) -> bool:
63 return (
64 self.engine_driver.is_container_removing(self.container)
65 if self.container
66 else False
67 )
68
69 @property
70 def running(self) -> bool:
71 return (
72 self.engine_driver.is_container_running(self.container)
73 if self.container
74 else False
75 )
76
77 @property
78 def paused(self) -> bool:
79 return (
80 self.engine_driver.is_container_paused(self.container)
81 if self.container
82 else False
83 )
84
85
86 class ContainerManager(DockerBaseClass, t.Generic[Client]):
87 def __init__(
88 self,
89 module: AnsibleModule,
90 engine_driver: EngineDriver,
91 client: Client,
92 active_options: list[OptionGroup],
93 ) -> None:
94 super().__init__()
95 self.module = module
96 self.engine_driver = engine_driver
97 self.client = client
98 self.options = active_options
99 self.all_options = self._collect_all_options(active_options)
100 self.check_mode = self.module.check_mode
101 self.param_cleanup: bool = self.module.params["cleanup"]
102 self.param_container_default_behavior: t.Literal[
103 "compatibility", "no_defaults"
104 ] = self.module.params["container_default_behavior"]
105 self.param_default_host_ip: str | None = self.module.params["default_host_ip"]
106 self.param_debug: bool = self.module.params["debug"]
107 self.param_force_kill: bool = self.module.params["force_kill"]
108 self.param_image: str | None = self.module.params["image"]
109 self.param_image_comparison: t.Literal["desired-image", "current-image"] = (
110 self.module.params["image_comparison"]
111 )
112 self.param_image_label_mismatch: t.Literal["ignore", "fail"] = (
113 self.module.params["image_label_mismatch"]
114 )
115 self.param_image_name_mismatch: t.Literal["ignore", "recreate"] = (
116 self.module.params["image_name_mismatch"]
117 )
118 self.param_keep_volumes: bool = self.module.params["keep_volumes"]
119 self.param_kill_signal: str | None = self.module.params["kill_signal"]
120 self.param_name: str = self.module.params["name"]
121 self.param_networks_cli_compatible: bool = self.module.params[
122 "networks_cli_compatible"
123 ]
124 self.param_output_logs: bool = self.module.params["output_logs"]
125 self.param_paused: bool | None = self.module.params["paused"]
126 param_pull: t.Literal["never", "missing", "always", True, False] = (
127 self.module.params["pull"]
128 )
129 if param_pull is True:
130 param_pull = "always"
131 if param_pull is False:
132 param_pull = "missing"
133 self.param_pull: t.Literal["never", "missing", "always"] = param_pull
134 self.param_pull_check_mode_behavior: t.Literal[
135 "image_not_present", "always"
136 ] = self.module.params["pull_check_mode_behavior"]
137 self.param_recreate: bool = self.module.params["recreate"]
138 self.param_removal_wait_timeout: int | float | None = self.module.params[
139 "removal_wait_timeout"
140 ]
141 self.param_healthy_wait_timeout: int | float | None = self.module.params[
142 "healthy_wait_timeout"
143 ]
144 if (
145 self.param_healthy_wait_timeout is not None
146 and self.param_healthy_wait_timeout <= 0
147 ):
148 self.param_healthy_wait_timeout = None
149 self.param_restart: bool = self.module.params["restart"]
150 self.param_state: t.Literal[
151 "absent", "present", "healthy", "started", "stopped"
152 ] = self.module.params["state"]
153 self._parse_comparisons()
154 self._update_params()
155 self.results = {"changed": False, "actions": []}
156 self.diff: dict[str, t.Any] = {}
157 self.diff_tracker = DifferenceTracker()
158 self.facts: dict[str, t.Any] | None = {}
159 if self.param_default_host_ip:
160 valid_ip = False
161 if re.match(
162 r"^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$", self.param_default_host_ip
163 ):
164 valid_ip = True
165 if re.match(r"^\[[0-9a-fA-F:]+\]$", self.param_default_host_ip):
166 valid_ip = True
167 if re.match(r"^[0-9a-fA-F:]+$", self.param_default_host_ip):
168 self.param_default_host_ip = f"[{self.param_default_host_ip}]"
169 valid_ip = True
170 if not valid_ip:
171 self.fail(
172 "The value of default_host_ip must be an empty string, an IPv4 address, "
173 f'or an IPv6 address. Got "{self.param_default_host_ip}" instead.'
174 )
175 self.parameters: list[tuple[OptionGroup, dict[str, t.Any]]] | None = None
176
177 def _add_action(self, action: dict[str, t.Any]) -> None:
178 actions: list[dict[str, t.Any]] = self.results["actions"] # type: ignore
179 actions.append(action)
180
181 def _collect_all_options(
182 self, active_options: list[OptionGroup]
183 ) -> dict[str, Option]:
184 all_options = {}
185 for options in active_options:
186 for option in options.options:
187 all_options[option.name] = option
188 return all_options
189
190 def _collect_all_module_params(self) -> set[str]:
191 all_module_options = set()
192 for option, data in self.module.argument_spec.items():
193 all_module_options.add(option)
194 if "aliases" in data:
195 for alias in data["aliases"]:
196 all_module_options.add(alias)
197 return all_module_options
198
199 def _parse_comparisons(self) -> None:
200 # Keep track of all module params and all option aliases
201 all_module_options = self._collect_all_module_params()
202 comp_aliases = {}
203 for option_name, option in self.all_options.items():
204 if option.not_an_ansible_option:
205 continue
206 comp_aliases[option_name] = option_name
207 for alias in option.ansible_aliases:
208 comp_aliases[alias] = option_name
209 # Process comparisons specified by user
210 comparisons: dict[str, t.Any] | None = self.module.params.get("comparisons")
211 if comparisons:
212 # If '*' appears in comparisons, process it first
213 if "*" in comparisons:
214 value = comparisons["*"]
215 if value not in ("strict", "ignore"):
216 self.fail(
217 "The wildcard can only be used with comparison modes 'strict' and 'ignore'!"
218 )
219 for option in self.all_options.values():
220 # `networks` is special: only update if
221 # some value is actually specified
222 if (
223 option.name == "networks"
224 and self.module.params["networks"] is None
225 ):
226 continue
227 option.comparison = value
228 # Now process all other comparisons.
229 comp_aliases_used: dict[str, str] = {}
230 for key, value in comparisons.items():
231 if key == "*":
232 continue
233 # Find main key
234 key_main = comp_aliases.get(key)
235 if key_main is None:
236 if key_main in all_module_options:
237 self.fail(
238 f"The module option '{key}' cannot be specified in the comparisons dict, "
239 "since it does not correspond to container's state!"
240 )
241 if (
242 key not in self.all_options
243 or self.all_options[key].not_an_ansible_option
244 ):
245 self.fail(f"Unknown module option '{key}' in comparisons dict!")
246 key_main = key
247 if key_main in comp_aliases_used:
248 self.fail(
249 f"Both '{key}' and '{comp_aliases_used[key_main]}' (aliases of {key_main}) are specified in comparisons dict!"
250 )
251 comp_aliases_used[key_main] = key
252 # Check value and update accordingly
253 if value in ("strict", "ignore"):
254 self.all_options[key_main].comparison = value
255 elif value == "allow_more_present":
256 if self.all_options[key_main].comparison_type == "value":
257 self.fail(
258 f"Option '{key}' is a value and not a set/list/dict, so its comparison cannot be {value}"
259 )
260 self.all_options[key_main].comparison = value
261 else:
262 self.fail(f"Unknown comparison mode '{value}'!")
263 # Copy values
264 for option in self.all_options.values():
265 if option.copy_comparison_from is not None:
266 option.comparison = self.all_options[
267 option.copy_comparison_from
268 ].comparison
269
270 def _update_params(self) -> None:
271 if (
272 self.param_networks_cli_compatible is True
273 and self.module.params["networks"]
274 and self.module.params["network_mode"] is None
275 ):
276 # Same behavior as Docker CLI: if networks are specified, use the name of the first network as the value for network_mode
277 # (assuming no explicit value is specified for network_mode)
278 self.module.params["network_mode"] = self.module.params["networks"][0][
279 "name"
280 ]
281 if self.param_container_default_behavior == "compatibility":
282 old_default_values = {
283 "auto_remove": False,
284 "detach": True,
285 "init": False,
286 "interactive": False,
287 "memory": "0",
288 "paused": False,
289 "privileged": False,
290 "read_only": False,
291 "tty": False,
292 }
293 for param, value in old_default_values.items():
294 if self.module.params[param] is None:
295 self.module.params[param] = value
296
297 def fail(self, *args: str, **kwargs: t.Any) -> t.NoReturn:
298 # mypy doesn't know that Client has fail() method
299 raise self.client.fail(*args, **kwargs) # type: ignore
300
301 def run(self) -> None:
302 if self.param_state in ("stopped", "started", "present", "healthy"):
303 # mypy doesn't get that self.param_state has only one of the above values
304 self.present(self.param_state) # type: ignore
305 elif self.param_state == "absent":
306 self.absent()
307
308 if not self.check_mode and not self.param_debug:
309 self.results.pop("actions")
310
311 if self.module._diff or self.param_debug:
312 self.diff["before"], self.diff["after"] = (
313 self.diff_tracker.get_before_after()
314 )
315 self.results["diff"] = self.diff
316
317 if self.facts:
318 self.results["container"] = self.facts
319
320 def wait_for_state(
321 self,
322 container_id: str,
323 *,
324 complete_states: Sequence[str | None] | None = None,
325 wait_states: Sequence[str | None] | None = None,
326 accept_removal: bool = False,
327 max_wait: int | float | None = None,
328 health_state: bool = False,
329 ) -> dict[str, t.Any] | None:
330 delay = 1.0
331 total_wait = 0.0
332 while True:
333 # Inspect container
334 result = self.engine_driver.inspect_container_by_id(
335 self.client, container_id
336 )
337 if result is None:
338 if accept_removal:
339 return result
340 msg = f'Encontered vanished container while waiting for container "{container_id}"'
341 self.fail(msg)
342 # Check container state
343 state_info = result.get("State") or {}
344 if health_state:
345 state_info = state_info.get("Health") or {}
346 state = state_info.get("Status")
347 if complete_states is not None and state in complete_states:
348 return result
349 if wait_states is not None and state not in wait_states:
350 msg = f'Encontered unexpected state "{state}" while waiting for container "{container_id}"'
351 self.fail(msg, container=result)
352 # Wait
353 if max_wait is not None:
354 if total_wait > max_wait or delay < 1e-4:
355 msg = f'Timeout of {max_wait} seconds exceeded while waiting for container "{container_id}"'
356 self.fail(msg, container=result)
357 if total_wait + delay > max_wait:
358 delay = max_wait - total_wait
359 sleep(delay)
360 total_wait += delay
361 # Exponential backoff, but never wait longer than 10 seconds
362 # (1.1**24 < 10, 1.1**25 > 10, so it will take 25 iterations
363 # until the maximal 10 seconds delay is reached. By then, the
364 # code will have slept for ~1.5 minutes.)
365 delay = min(delay * 1.1, 10)
366
367 def _collect_params(
368 self, active_options: list[OptionGroup]
369 ) -> list[tuple[OptionGroup, dict[str, t.Any]]]:
370 parameters = []
371 for options in active_options:
372 values = {}
373 engine = options.get_engine(self.engine_driver.name)
374 for option in options.all_options:
375 if (
376 not option.not_an_ansible_option
377 and self.module.params[option.name] is not None
378 ):
379 values[option.name] = self.module.params[option.name]
380 values = options.preprocess(self.module, values)
381 engine.preprocess_value(
382 self.module,
383 self.client,
384 self.engine_driver.get_api_version(self.client),
385 options.options,
386 values,
387 )
388 parameters.append((options, values))
389 return parameters
390
391 def _needs_container_image(self) -> bool:
392 assert self.parameters is not None
393 for options, values in self.parameters:
394 engine = options.get_engine(self.engine_driver.name)
395 if engine.needs_container_image(values):
396 return True
397 return False
398
399 def _needs_host_info(self) -> bool:
400 assert self.parameters is not None
401 for options, values in self.parameters:
402 engine = options.get_engine(self.engine_driver.name)
403 if engine.needs_host_info(values):
404 return True
405 return False
406
407 def present(
408 self, state: t.Literal["stopped", "started", "present", "healthy"]
409 ) -> None:
410 self.parameters = self._collect_params(self.options)
411 container = self._get_container(self.param_name)
412 was_running = container.running
413 was_paused = container.paused
414 container_created = False
415
416 # If the image parameter was passed then we need to deal with the image
417 # version comparison. Otherwise we handle this depending on whether
418 # the container already runs or not; in the former case, in case the
419 # container needs to be restarted, we use the existing container's
420 # image ID.
421 image, container_image, comparison_image = self._get_image(
422 container, needs_container_image=self._needs_container_image()
423 )
424 self.log(image, pretty_print=True)
425 host_info = (
426 self.engine_driver.get_host_info(self.client)
427 if self._needs_host_info()
428 else None
429 )
430 if not container.exists or container.removing:
431 # New container
432 if container.removing:
433 self.log("Found container in removal phase")
434 else:
435 self.log("No container found")
436 if not self.param_image:
437 self.fail("Cannot create container when image is not specified!")
438 self.diff_tracker.add("exists", parameter=True, active=False)
439 if container.removing and not self.check_mode:
440 # Wait for container to be removed before trying to create it
441 assert container.id is not None
442 self.wait_for_state(
443 container.id,
444 wait_states=["removing"],
445 accept_removal=True,
446 max_wait=self.param_removal_wait_timeout,
447 )
448 new_container = self.container_create(self.param_image)
449 if new_container:
450 container = new_container
451 container_created = True
452 else:
453 # Existing container
454 assert container.id is not None
455 different, differences = self.has_different_configuration(
456 container, container_image, comparison_image, host_info
457 )
458 image_different = False
459 if self.all_options["image"].comparison == "strict":
460 image_different = self._image_is_different(image, container)
461 if (
462 self.param_image_name_mismatch == "recreate"
463 and self.param_image is not None
464 and self.param_image != container.image_name
465 ):
466 different = True
467 self.diff_tracker.add(
468 "image_name",
469 parameter=self.param_image,
470 active=container.image_name,
471 )
472 if image_different or different or self.param_recreate:
473 self.diff_tracker.merge(differences)
474 self.diff["differences"] = (
475 differences.get_legacy_docker_container_diffs()
476 )
477 if image_different:
478 self.diff["image_different"] = True
479 self.log("differences")
480 self.log(
481 differences.get_legacy_docker_container_diffs(), pretty_print=True
482 )
483 image_to_use = self.param_image
484 if not image_to_use and container and container.image:
485 image_to_use = container.image
486 if not image_to_use:
487 self.fail(
488 "Cannot recreate container when image is not specified or cannot be extracted from current container!"
489 )
490 if container.running:
491 self.container_stop(container.id)
492 self.container_remove(container.id)
493 if not self.check_mode:
494 self.wait_for_state(
495 container.id,
496 wait_states=["removing"],
497 accept_removal=True,
498 max_wait=self.param_removal_wait_timeout,
499 )
500 new_container = self.container_create(image_to_use)
501 if new_container:
502 container = new_container
503 container_created = True
504 comparison_image = image
505
506 if container and container.exists:
507 container = self.update_limits(
508 container, container_image, comparison_image, host_info
509 )
510 container = self.update_networks(container, container_created)
511
512 if state in ("started", "healthy") and not container.running:
513 self.diff_tracker.add("running", parameter=True, active=was_running)
514 assert container.id is not None
515 container = self.container_start(container.id)
516 elif state in ("started", "healthy") and self.param_restart:
517 self.diff_tracker.add("running", parameter=True, active=was_running)
518 self.diff_tracker.add("restarted", parameter=True, active=False)
519 assert container.id is not None
520 container = self.container_restart(container.id)
521 elif state == "stopped" and container.running:
522 self.diff_tracker.add("running", parameter=False, active=was_running)
523 assert container.id is not None
524 self.container_stop(container.id)
525 container = self._get_container(container.id)
526
527 if (
528 state in ("started", "healthy")
529 and self.param_paused is not None
530 and container.paused != self.param_paused
531 ):
532 self.diff_tracker.add(
533 "paused", parameter=self.param_paused, active=was_paused
534 )
535 if not self.check_mode:
536 assert container.id is not None
537 try:
538 if self.param_paused:
539 self.engine_driver.pause_container(
540 self.client, container.id
541 )
542 else:
543 self.engine_driver.unpause_container(
544 self.client, container.id
545 )
546 except Exception as exc: # pylint: disable=broad-exception-caught
547 self.fail(
548 f"Error {'pausing' if self.param_paused else 'unpausing'} container {container.id}: {exc}"
549 )
550 container = self._get_container(container.id)
551 self.results["changed"] = True
552 self._add_action({"set_paused": self.param_paused})
553
554 self.facts = container.raw
555
556 if state == "healthy" and not self.check_mode:
557 # `None` means that no health check enabled; simply treat this as 'healthy'
558 assert container.id is not None
559 inspect_result = self.wait_for_state(
560 container.id,
561 wait_states=["starting", "unhealthy"],
562 complete_states=["healthy", None],
563 max_wait=self.param_healthy_wait_timeout,
564 health_state=True,
565 )
566 if inspect_result:
567 # Return the latest inspection results retrieved
568 self.facts = inspect_result
569
570 def absent(self) -> None:
571 container = self._get_container(self.param_name)
572 if container.exists:
573 assert container.id is not None
574 if container.running:
575 self.diff_tracker.add("running", parameter=False, active=True)
576 self.container_stop(container.id)
577 self.diff_tracker.add("exists", parameter=False, active=True)
578 self.container_remove(container.id)
579
580 def _output_logs(self, msg: str | bytes) -> None:
581 self.module.log(msg=msg)
582
583 def _get_container(self, container: str) -> Container:
584 """
585 Expects container ID or Name. Returns a container object
586 """
587 container_data = self.engine_driver.inspect_container_by_name(
588 self.client, container
589 )
590 return Container(container_data, self.engine_driver)
591
592 def _get_container_image(
593 self, container: Container, fallback: dict[str, t.Any] | None = None
594 ) -> dict[str, t.Any] | None:
595 if not container.exists or container.removing:
596 return fallback
597 image = container.image
598 assert image is not None
599 if is_image_name_id(image):
600 image_data = self.engine_driver.inspect_image_by_id(self.client, image)
601 else:
602 repository, tag = parse_repository_tag(image)
603 if not tag:
604 tag = "latest"
605 image_data = self.engine_driver.inspect_image_by_name(
606 self.client, repository, tag
607 )
608 return image_data or fallback
609
610 def _get_image(
611 self, container: Container, needs_container_image: bool = False
612 ) -> tuple[
613 dict[str, t.Any] | None, dict[str, t.Any] | None, dict[str, t.Any] | None
614 ]:
615 image_parameter = self.param_image
616 get_container_image = needs_container_image or not image_parameter
617 container_image = (
618 self._get_container_image(container) if get_container_image else None
619 )
620 if container_image:
621 self.log("current image")
622 self.log(container_image, pretty_print=True)
623 if not image_parameter:
624 self.log("No image specified")
625 return None, container_image, container_image
626 if is_image_name_id(image_parameter):
627 image = self.engine_driver.inspect_image_by_id(self.client, image_parameter)
628 if image is None:
629 self.fail(f"Cannot find image with ID {image_parameter}")
630 else:
631 repository, tag = parse_repository_tag(image_parameter)
632 if not tag:
633 tag = "latest"
634 image = self.engine_driver.inspect_image_by_name(
635 self.client, repository, tag
636 )
637 if not image and self.param_pull == "never":
638 self.fail(
639 f"Cannot find image with name {repository}:{tag}, and pull=never"
640 )
641 if not image or self.param_pull == "always":
642 if not self.check_mode:
643 self.log("Pull the image.")
644 image, already_to_latest = self.engine_driver.pull_image(
645 self.client,
646 repository,
647 tag,
648 image_platform=self.module.params["platform"],
649 )
650 if already_to_latest:
651 self.results["changed"] = False
652 self._add_action(
653 {"pulled_image": f"{repository}:{tag}", "changed": False}
654 )
655 else:
656 self.results["changed"] = True
657 self._add_action(
658 {"pulled_image": f"{repository}:{tag}", "changed": True}
659 )
660 elif not image or self.param_pull_check_mode_behavior == "always":
661 # If the image is not there, or pull_check_mode_behavior == 'always', claim we'll
662 # pull. (Implicitly: if the image is there, claim it already was latest unless
663 # pull_check_mode_behavior == 'always'.)
664 self.results["changed"] = True
665 action: dict[str, t.Any] = {"pulled_image": f"{repository}:{tag}"}
666 if not image:
667 action["changed"] = True
668 self._add_action(action)
669
670 self.log("image")
671 self.log(image, pretty_print=True)
672
673 comparison_image = image
674 if self.param_image_comparison == "current-image":
675 if not get_container_image:
676 container_image = self._get_container_image(container)
677 comparison_image = container_image
678
679 return image, container_image, comparison_image
680
681 def _image_is_different(
682 self, image: dict[str, t.Any] | None, container: Container
683 ) -> bool:
684 if (
685 image
686 and image.get("Id")
687 and container
688 and container.image
689 and image.get("Id") != container.image
690 ):
691 self.diff_tracker.add(
692 "image", parameter=image.get("Id"), active=container.image
693 )
694 return True
695 return False
696
697 def _compose_create_parameters(self, image: str) -> dict[str, t.Any]:
698 params: dict[str, t.Any] = {}
699 assert self.parameters is not None
700 for options, values in self.parameters:
701 engine = options.get_engine(self.engine_driver.name)
702 if engine.can_set_value(self.engine_driver.get_api_version(self.client)):
703 engine.set_value(
704 self.module,
705 params,
706 self.engine_driver.get_api_version(self.client),
707 options.options,
708 values,
709 )
710 params["Image"] = image
711 return params
712
713 def _record_differences(
714 self,
715 differences: DifferenceTracker,
716 options: OptionGroup,
717 param_values: dict[str, t.Any],
718 engine: Engine,
719 container: Container,
720 container_image: dict[str, t.Any] | None,
721 image: dict[str, t.Any] | None,
722 host_info: dict[str, t.Any] | None,
723 ) -> None:
724 assert container.raw is not None
725 container_values = engine.get_value(
726 self.module,
727 container.raw,
728 self.engine_driver.get_api_version(self.client),
729 options.options,
730 container_image,
731 host_info,
732 )
733 expected_values = engine.get_expected_values(
734 self.module,
735 self.client,
736 self.engine_driver.get_api_version(self.client),
737 options.options,
738 image,
739 param_values.copy(),
740 host_info,
741 )
742 for option in options.options:
743 if option.name in expected_values:
744 param_value = expected_values[option.name]
745 container_value = container_values.get(option.name)
746 match = engine.compare_value(option, param_value, container_value)
747
748 if not match:
749 # No match.
750 if engine.ignore_mismatching_result(
751 self.module,
752 self.client,
753 self.engine_driver.get_api_version(self.client),
754 option,
755 image,
756 container_value,
757 param_value,
758 host_info,
759 ):
760 # Ignore the result
761 continue
762
763 # Record the differences
764 p = param_value
765 c = container_value
766 if option.comparison_type == "set":
767 # Since the order does not matter, sort so that the diff output is better.
768 if p is not None:
769 p = sorted(p)
770 if c is not None:
771 c = sorted(c)
772 elif option.comparison_type == "set(dict)":
773 # Since the order does not matter, sort so that the diff output is better.
774 if option.name == "expected_mounts":
775 # For selected values, use one entry as key
776 def sort_key_fn(x: dict[str, t.Any]) -> t.Any:
777 return x["target"]
778
779 else:
780 # We sort the list of dictionaries by using the sorted items of a dict as its key.
781 def sort_key_fn(x: dict[str, t.Any]) -> t.Any:
782 return sorted(
783 (a, to_text(b, errors="surrogate_or_strict"))
784 for a, b in x.items()
785 )
786
787 if p is not None:
788 p = sorted(p, key=sort_key_fn)
789 if c is not None:
790 c = sorted(c, key=sort_key_fn)
791 differences.add(option.name, parameter=p, active=c)
792
793 def has_different_configuration(
794 self,
795 container: Container,
796 container_image: dict[str, t.Any] | None,
797 image: dict[str, t.Any] | None,
798 host_info: dict[str, t.Any] | None,
799 ) -> tuple[bool, DifferenceTracker]:
800 differences = DifferenceTracker()
801 update_differences = DifferenceTracker()
802 assert self.parameters is not None
803 for options, param_values in self.parameters:
804 engine = options.get_engine(self.engine_driver.name)
805 if engine.can_update_value(self.engine_driver.get_api_version(self.client)):
806 self._record_differences(
807 update_differences,
808 options,
809 param_values,
810 engine,
811 container,
812 container_image,
813 image,
814 host_info,
815 )
816 else:
817 self._record_differences(
818 differences,
819 options,
820 param_values,
821 engine,
822 container,
823 container_image,
824 image,
825 host_info,
826 )
827 has_differences = not differences.empty
828 # Only consider differences of properties that can be updated when there are also other differences
829 if has_differences:
830 differences.merge(update_differences)
831 return has_differences, differences
832
833 def has_different_resource_limits(
834 self,
835 container: Container,
836 container_image: dict[str, t.Any] | None,
837 image: dict[str, t.Any] | None,
838 host_info: dict[str, t.Any] | None,
839 ) -> tuple[bool, DifferenceTracker]:
840 differences = DifferenceTracker()
841 assert self.parameters is not None
842 for options, param_values in self.parameters:
843 engine = options.get_engine(self.engine_driver.name)
844 if not engine.can_update_value(
845 self.engine_driver.get_api_version(self.client)
846 ):
847 continue
848 self._record_differences(
849 differences,
850 options,
851 param_values,
852 engine,
853 container,
854 container_image,
855 image,
856 host_info,
857 )
858 has_differences = not differences.empty
859 return has_differences, differences
860
861 def _compose_update_parameters(self) -> dict[str, t.Any]:
862 result: dict[str, t.Any] = {}
863 assert self.parameters is not None
864 for options, values in self.parameters:
865 engine = options.get_engine(self.engine_driver.name)
866 if not engine.can_update_value(
867 self.engine_driver.get_api_version(self.client)
868 ):
869 continue
870 engine.update_value(
871 self.module,
872 result,
873 self.engine_driver.get_api_version(self.client),
874 options.options,
875 values,
876 )
877 return result
878
879 def update_limits(
880 self,
881 container: Container,
882 container_image: dict[str, t.Any] | None,
883 image: dict[str, t.Any] | None,
884 host_info: dict[str, t.Any] | None,
885 ) -> Container:
886 limits_differ, different_limits = self.has_different_resource_limits(
887 container, container_image, image, host_info
888 )
889 if limits_differ:
890 self.log("limit differences:")
891 self.log(
892 different_limits.get_legacy_docker_container_diffs(), pretty_print=True
893 )
894 self.diff_tracker.merge(different_limits)
895 if limits_differ and not self.check_mode:
896 assert container.id is not None
897 self.container_update(container.id, self._compose_update_parameters())
898 return self._get_container(container.id)
899 return container
900
901 def has_network_differences(
902 self, container: Container
903 ) -> tuple[bool, list[dict[str, t.Any]]]:
904 """
905 Check if the container is connected to requested networks with expected options: links, aliases, ipv4, ipv6
906 """
907 different = False
908 differences: list[dict[str, t.Any]] = []
909
910 if not self.module.params["networks"]:
911 return different, differences
912
913 assert container.container is not None
914 if not container.container.get("NetworkSettings"):
915 self.fail(
916 "has_missing_networks: Error parsing container properties. NetworkSettings missing."
917 )
918
919 connected_networks = container.container["NetworkSettings"]["Networks"]
920 for network in self.module.params["networks"]:
921 network_info = connected_networks.get(network["name"])
922 if network_info is None:
923 different = True
924 differences.append({"parameter": network, "container": None})
925 else:
926 diff = False
927 network_info_ipam = network_info.get("IPAMConfig") or {}
928 if network.get("ipv4_address") and normalize_ip_address(
929 network["ipv4_address"]
930 ) != normalize_ip_address(network_info_ipam.get("IPv4Address")):
931 diff = True
932 if network.get("ipv6_address") and normalize_ip_address(
933 network["ipv6_address"]
934 ) != normalize_ip_address(network_info_ipam.get("IPv6Address")):
935 diff = True
936 if network.get("aliases") and not compare_generic(
937 network["aliases"],
938 network_info.get("Aliases"),
939 "allow_more_present",
940 "set",
941 ):
942 diff = True
943 if network.get("links"):
944 expected_links = []
945 for link, alias in network["links"]:
946 expected_links.append(f"{link}:{alias}")
947 if not compare_generic(
948 expected_links,
949 network_info.get("Links"),
950 "allow_more_present",
951 "set",
952 ):
953 diff = True
954 if network.get("mac_address") and network[
955 "mac_address"
956 ] != network_info.get("MacAddress"):
957 diff = True
958 if diff:
959 different = True
960 differences.append(
961 {
962 "parameter": network,
963 "container": {
964 "name": network["name"],
965 "ipv4_address": network_info_ipam.get("IPv4Address"),
966 "ipv6_address": network_info_ipam.get("IPv6Address"),
967 "aliases": network_info.get("Aliases"),
968 "links": network_info.get("Links"),
969 "mac_address": network_info.get("MacAddress"),
970 },
971 }
972 )
973 return different, differences
974
975 def has_extra_networks(
976 self, container: Container
977 ) -> tuple[bool, list[dict[str, t.Any]]]:
978 """
979 Check if the container is connected to non-requested networks
980 """
981 extra_networks: list[dict[str, t.Any]] = []
982 extra = False
983
984 assert container.container is not None
985 if not container.container.get("NetworkSettings"):
986 self.fail(
987 "has_extra_networks: Error parsing container properties. NetworkSettings missing."
988 )
989
990 connected_networks = container.container["NetworkSettings"].get("Networks")
991 if connected_networks:
992 for network, network_config in connected_networks.items():
993 keep = False
994 if self.module.params["networks"]:
995 for expected_network in self.module.params["networks"]:
996 if expected_network["name"] == network:
997 keep = True
998 if not keep:
999 extra = True
1000 extra_networks.append(
1001 {"name": network, "id": network_config["NetworkID"]}
1002 )
1003 return extra, extra_networks
1004
1005 def update_networks(
1006 self, container: Container, container_created: bool
1007 ) -> Container:
1008 updated_container = container
1009 if self.all_options["networks"].comparison != "ignore" or container_created:
1010 has_network_differences, network_differences = self.has_network_differences(
1011 container
1012 )
1013 if has_network_differences:
1014 if self.diff.get("differences"):
1015 self.diff["differences"].append(
1016 {"network_differences": network_differences}
1017 )
1018 else:
1019 self.diff["differences"] = [
1020 {"network_differences": network_differences}
1021 ]
1022 for netdiff in network_differences:
1023 self.diff_tracker.add(
1024 f"network.{netdiff['parameter']['name']}",
1025 parameter=netdiff["parameter"],
1026 active=netdiff["container"],
1027 )
1028 self.results["changed"] = True
1029 updated_container = self._add_networks(container, network_differences)
1030
1031 purge_networks = (
1032 self.all_options["networks"].comparison == "strict"
1033 and self.module.params["networks"] is not None
1034 )
1035 if purge_networks:
1036 has_extra_networks, extra_networks = self.has_extra_networks(container)
1037 if has_extra_networks:
1038 if self.diff.get("differences"):
1039 self.diff["differences"].append({"purge_networks": extra_networks})
1040 else:
1041 self.diff["differences"] = [{"purge_networks": extra_networks}]
1042 for extra_network in extra_networks:
1043 self.diff_tracker.add(
1044 f"network.{extra_network['name']}", active=extra_network
1045 )
1046 self.results["changed"] = True
1047 updated_container = self._purge_networks(container, extra_networks)
1048 return updated_container
1049
1050 def _add_networks(
1051 self, container: Container, differences: list[dict[str, t.Any]]
1052 ) -> Container:
1053 assert container.id is not None
1054 for diff in differences:
1055 # remove the container from the network, if connected
1056 if diff.get("container"):
1057 self._add_action({"removed_from_network": diff["parameter"]["name"]})
1058 if not self.check_mode:
1059 try:
1060 self.engine_driver.disconnect_container_from_network(
1061 self.client, container.id, diff["parameter"]["id"]
1062 )
1063 except Exception as exc: # pylint: disable=broad-exception-caught
1064 self.fail(
1065 f"Error disconnecting container from network {diff['parameter']['name']} - {exc}"
1066 )
1067 # connect to the network
1068 self._add_action(
1069 {
1070 "added_to_network": diff["parameter"]["name"],
1071 "network_parameters": diff["parameter"],
1072 }
1073 )
1074 if not self.check_mode:
1075 params = {
1076 key: value
1077 for key, value in diff["parameter"].items()
1078 if key not in ("id", "name")
1079 }
1080 try:
1081 self.log(
1082 f"Connecting container to network {diff['parameter']['id']}"
1083 )
1084 self.log(params, pretty_print=True)
1085 self.engine_driver.connect_container_to_network(
1086 self.client, container.id, diff["parameter"]["id"], params
1087 )
1088 except Exception as exc: # pylint: disable=broad-exception-caught
1089 self.fail(
1090 f"Error connecting container to network {diff['parameter']['name']} - {exc}"
1091 )
1092 return self._get_container(container.id)
1093
1094 def _purge_networks(
1095 self, container: Container, networks: list[dict[str, t.Any]]
1096 ) -> Container:
1097 assert container.id is not None
1098 for network in networks:
1099 self._add_action({"removed_from_network": network["name"]})
1100 if not self.check_mode:
1101 try:
1102 self.engine_driver.disconnect_container_from_network(
1103 self.client, container.id, network["name"]
1104 )
1105 except Exception as exc: # pylint: disable=broad-exception-caught
1106 self.fail(
1107 f"Error disconnecting container from network {network['name']} - {exc}"
1108 )
1109 return self._get_container(container.id)
1110
1111 def container_create(self, image: str) -> Container | None:
1112 create_parameters = self._compose_create_parameters(image)
1113 self.log("create container")
1114 self.log(f"image: {image} parameters:")
1115 self.log(create_parameters, pretty_print=True)
1116 networks = {}
1117 if self.param_networks_cli_compatible and self.module.params["networks"]:
1118 network_list = self.module.params["networks"]
1119 if not self.engine_driver.create_container_supports_more_than_one_network(
1120 self.client
1121 ):
1122 network_list = network_list[:1]
1123 for network in network_list:
1124 networks[network["name"]] = {
1125 key: value
1126 for key, value in network.items()
1127 if key not in ("name", "id")
1128 }
1129 self._add_action(
1130 {
1131 "created": "Created container",
1132 "create_parameters": create_parameters,
1133 "networks": networks,
1134 }
1135 )
1136 self.results["changed"] = True
1137 if not self.check_mode:
1138 try:
1139 container_id = self.engine_driver.create_container(
1140 self.client, self.param_name, create_parameters, networks=networks
1141 )
1142 except Exception as exc: # pylint: disable=broad-exception-caught
1143 self.fail(f"Error creating container: {exc}")
1144 return self._get_container(container_id)
1145 return None
1146
1147 def container_start(self, container_id: str) -> Container:
1148 self.log(f"start container {container_id}")
1149 self._add_action({"started": container_id})
1150 self.results["changed"] = True
1151 if not self.check_mode:
1152 try:
1153 self.engine_driver.start_container(self.client, container_id)
1154 except Exception as exc: # pylint: disable=broad-exception-caught
1155 self.fail(f"Error starting container {container_id}: {exc}")
1156
1157 if self.module.params["detach"] is False:
1158 status = self.engine_driver.wait_for_container(
1159 self.client, container_id
1160 )
1161 # mypy doesn't know that Client has fail_results property
1162 self.client.fail_results["status"] = status # type: ignore
1163 self.results["status"] = status
1164
1165 output: str | bytes
1166 if self.module.params["auto_remove"]:
1167 output = "Cannot retrieve result as auto_remove is enabled"
1168 if self.param_output_logs:
1169 self.module.warn(
1170 "Cannot output_logs if auto_remove is enabled!"
1171 )
1172 else:
1173 output, real_output = self.engine_driver.get_container_output(
1174 self.client, container_id
1175 )
1176 if real_output and self.param_output_logs:
1177 self._output_logs(msg=output)
1178
1179 if self.param_cleanup:
1180 self.container_remove(container_id, force=True)
1181 insp = self._get_container(container_id)
1182 if insp.raw:
1183 insp.raw["Output"] = output
1184 else:
1185 insp.raw = {"Output": output}
1186 if status != 0:
1187 # Set `failed` to True and return output as msg
1188 self.results["failed"] = True
1189 self.results["msg"] = output
1190 return insp
1191 return self._get_container(container_id)
1192
1193 def container_remove(
1194 self, container_id: str, link: bool = False, force: bool = False
1195 ) -> None:
1196 volume_state = not self.param_keep_volumes
1197 self.log(
1198 f"remove container container:{container_id} v:{volume_state} link:{link} force{force}"
1199 )
1200 self._add_action(
1201 {
1202 "removed": container_id,
1203 "volume_state": volume_state,
1204 "link": link,
1205 "force": force,
1206 }
1207 )
1208 self.results["changed"] = True
1209 if not self.check_mode:
1210 try:
1211 self.engine_driver.remove_container(
1212 self.client,
1213 container_id,
1214 remove_volumes=volume_state,
1215 link=link,
1216 force=force,
1217 )
1218 except Exception as exc: # pylint: disable=broad-exception-caught
1219 self.fail(f"Error removing container {container_id}: {exc}")
1220
1221 def container_update(
1222 self, container_id: str, update_parameters: dict[str, t.Any]
1223 ) -> Container:
1224 if update_parameters:
1225 self.log(f"update container {container_id}")
1226 self.log(update_parameters, pretty_print=True)
1227 self._add_action(
1228 {"updated": container_id, "update_parameters": update_parameters}
1229 )
1230 self.results["changed"] = True
1231 if not self.check_mode:
1232 try:
1233 self.engine_driver.update_container(
1234 self.client, container_id, update_parameters
1235 )
1236 except Exception as exc: # pylint: disable=broad-exception-caught
1237 self.fail(f"Error updating container {container_id}: {exc}")
1238 return self._get_container(container_id)
1239
1240 def container_kill(self, container_id: str) -> None:
1241 self._add_action({"killed": container_id, "signal": self.param_kill_signal})
1242 self.results["changed"] = True
1243 if not self.check_mode:
1244 try:
1245 self.engine_driver.kill_container(
1246 self.client, container_id, kill_signal=self.param_kill_signal
1247 )
1248 except Exception as exc: # pylint: disable=broad-exception-caught
1249 self.fail(f"Error killing container {container_id}: {exc}")
1250
1251 def container_restart(self, container_id: str) -> Container:
1252 self._add_action(
1253 {"restarted": container_id, "timeout": self.module.params["stop_timeout"]}
1254 )
1255 self.results["changed"] = True
1256 if not self.check_mode:
1257 try:
1258 self.engine_driver.restart_container(
1259 self.client, container_id, self.module.params["stop_timeout"] or 10
1260 )
1261 except Exception as exc: # pylint: disable=broad-exception-caught
1262 self.fail(f"Error restarting container {container_id}: {exc}")
1263 return self._get_container(container_id)
1264
1265 def container_stop(self, container_id: str) -> None:
1266 if self.param_force_kill:
1267 self.container_kill(container_id)
1268 return
1269 self._add_action(
1270 {"stopped": container_id, "timeout": self.module.params["stop_timeout"]}
1271 )
1272 self.results["changed"] = True
1273 if not self.check_mode:
1274 try:
1275 self.engine_driver.stop_container(
1276 self.client, container_id, self.module.params["stop_timeout"]
1277 )
1278 except Exception as exc: # pylint: disable=broad-exception-caught
1279 self.fail(f"Error stopping container {container_id}: {exc}")
1280
1281
1282 def run_module(engine_driver: EngineDriver) -> None:
1283 module, active_options, client = engine_driver.setup(
1284 argument_spec={
1285 "cleanup": {"type": "bool", "default": False},
1286 "comparisons": {"type": "dict"},
1287 "container_default_behavior": {
1288 "type": "str",
1289 "default": "no_defaults",
1290 "choices": ["compatibility", "no_defaults"],
1291 },
1292 "command_handling": {
1293 "type": "str",
1294 "choices": ["compatibility", "correct"],
1295 "default": "correct",
1296 },
1297 "default_host_ip": {"type": "str"},
1298 "force_kill": {"type": "bool", "default": False, "aliases": ["forcekill"]},
1299 "image": {"type": "str"},
1300 "image_comparison": {
1301 "type": "str",
1302 "choices": ["desired-image", "current-image"],
1303 "default": "desired-image",
1304 },
1305 "image_label_mismatch": {
1306 "type": "str",
1307 "choices": ["ignore", "fail"],
1308 "default": "ignore",
1309 },
1310 "image_name_mismatch": {
1311 "type": "str",
1312 "choices": ["ignore", "recreate"],
1313 "default": "recreate",
1314 },
1315 "keep_volumes": {"type": "bool", "default": True},
1316 "kill_signal": {"type": "str"},
1317 "name": {"type": "str", "required": True},
1318 "networks_cli_compatible": {"type": "bool", "default": True},
1319 "output_logs": {"type": "bool", "default": False},
1320 "paused": {"type": "bool"},
1321 "pull": {
1322 "type": "raw",
1323 "choices": ["never", "missing", "always", True, False],
1324 "default": "missing",
1325 },
1326 "pull_check_mode_behavior": {
1327 "type": "str",
1328 "choices": ["image_not_present", "always"],
1329 "default": "image_not_present",
1330 },
1331 "recreate": {"type": "bool", "default": False},
1332 "removal_wait_timeout": {"type": "float"},
1333 "restart": {"type": "bool", "default": False},
1334 "state": {
1335 "type": "str",
1336 "default": "started",
1337 "choices": ["absent", "present", "healthy", "started", "stopped"],
1338 },
1339 "healthy_wait_timeout": {"type": "float", "default": 300},
1340 },
1341 required_if=[
1342 ("state", "present", ["image"]),
1343 ],
1344 )
1345
1346 def execute() -> t.NoReturn:
1347 cm = ContainerManager(module, engine_driver, client, active_options)
1348 cm.run()
1349 module.exit_json(**sanitize_result(cm.results))
1350
1351 engine_driver.run(execute, client)