Debian Codegraph @

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

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
2 # Copyright (c) 2023, Léo El Amri (@lel-amri)
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 os
13 import re
14 import shutil
15 import tempfile
16 import traceback
17 import typing as t
18 from collections import namedtuple
19 from shlex import quote
20
21 from ansible.module_utils.basic import missing_required_lib
22 from ansible.module_utils.common.text.converters import to_text
23
24 from ansible_collections.community.docker.plugins.module_utils._logfmt import (
25 InvalidLogFmt as _InvalidLogFmt,
26 )
27 from ansible_collections.community.docker.plugins.module_utils._logfmt import (
28 parse_line as _parse_logfmt_line,
29 )
30 from ansible_collections.community.docker.plugins.module_utils._util import (
31 DockerBaseClass,
32 )
33 from ansible_collections.community.docker.plugins.module_utils._version import (
34 LooseVersion,
35 )
36
37 PYYAML_IMPORT_ERROR: None | str # pylint: disable=invalid-name
38 try:
39 import yaml
40
41 try:
42 # use C version if possible for speedup
43 from yaml import CSafeDumper as _SafeDumper
44 except ImportError:
45 from yaml import SafeDumper as _SafeDumper # type: ignore
46 except ImportError:
47 HAS_PYYAML = False
48 PYYAML_IMPORT_ERROR = traceback.format_exc() # pylint: disable=invalid-name
49 else:
50 HAS_PYYAML = True
51 PYYAML_IMPORT_ERROR = None # pylint: disable=invalid-name
52
53 if t.TYPE_CHECKING:
54 from collections.abc import Callable, Sequence
55
56 from ansible_collections.community.docker.plugins.module_utils._common_cli import (
57 AnsibleModuleDockerClient as _Client,
58 )
59
60
61 DOCKER_COMPOSE_FILES = (
62 "compose.yaml",
63 "compose.yml",
64 "docker-compose.yaml",
65 "docker-compose.yml",
66 )
67
68 DOCKER_STATUS_DONE = frozenset(
69 (
70 "Started",
71 "Healthy",
72 "Exited",
73 "Restarted",
74 "Running",
75 "Created",
76 "Stopped",
77 "Killed",
78 "Removed",
79 # An extra, specific to containers
80 "Recreated",
81 # Extras for pull events
82 "Pulled",
83 # Extras for built events
84 "Built",
85 )
86 )
87 DOCKER_STATUS_WORKING = frozenset(
88 (
89 "Creating",
90 "Starting",
91 "Restarting",
92 "Stopping",
93 "Killing",
94 "Removing",
95 # An extra, specific to containers
96 "Recreate",
97 # Extras for pull events
98 "Pulling",
99 # Extras for build start events
100 "Building",
101 )
102 )
103 DOCKER_STATUS_PULL = frozenset(
104 (
105 "Pulled",
106 "Pulling",
107 )
108 )
109 DOCKER_STATUS_BUILD = frozenset(
110 (
111 "Built",
112 "Building",
113 )
114 )
115 DOCKER_STATUS_ERROR = frozenset(("Error",))
116 DOCKER_STATUS_WARNING = frozenset(("Warning",))
117 DOCKER_STATUS_WAITING = frozenset(("Waiting",))
118 DOCKER_STATUS = frozenset(
119 DOCKER_STATUS_DONE
120 | DOCKER_STATUS_WORKING
121 | DOCKER_STATUS_PULL
122 | DOCKER_STATUS_ERROR
123 | DOCKER_STATUS_WAITING
124 )
125 DOCKER_STATUS_AND_WARNING = frozenset(DOCKER_STATUS | DOCKER_STATUS_WARNING)
126
127 DOCKER_PULL_PROGRESS_DONE = frozenset(
128 (
129 "Already exists",
130 "Download complete",
131 "Pull complete",
132 )
133 )
134 DOCKER_PULL_PROGRESS_WORKING_OLD = frozenset(
135 (
136 "Pulling fs layer",
137 "Waiting",
138 "Downloading",
139 "Verifying Checksum",
140 "Extracting",
141 )
142 )
143 DOCKER_PULL_PROGRESS_WORKING = frozenset(DOCKER_PULL_PROGRESS_WORKING_OLD | {"Working"})
144
145
146 class ResourceType:
147 UNKNOWN = "unknown"
148 NETWORK = "network"
149 IMAGE = "image"
150 IMAGE_LAYER = "image-layer"
151 VOLUME = "volume"
152 CONTAINER = "container"
153 SERVICE = "service"
154
155 @classmethod
156 def from_docker_compose_event(cls, resource_type: str) -> t.Any:
157 return {
158 "Network": cls.NETWORK,
159 "Image": cls.IMAGE,
160 "Volume": cls.VOLUME,
161 "Container": cls.CONTAINER,
162 "Service": cls.SERVICE,
163 }[resource_type]
164
165
166 Event = namedtuple("Event", ["resource_type", "resource_id", "status", "msg"])
167
168
169 _DRY_RUN_MARKER = "DRY-RUN MODE -"
170
171 _RE_RESOURCE_EVENT = re.compile(
172 r"^"
173 r"\s*"
174 r"(?P<resource_type>Network|Image|Volume|Container)"
175 r"\s+"
176 r"(?P<resource_id>\S+)"
177 r"\s+"
178 r"(?P<status>\S(?:|.*\S))"
179 r"\s*"
180 r"$"
181 )
182
183 _RE_PULL_EVENT = re.compile(
184 r"^"
185 r"\s*"
186 r"(?P<service>\S+)"
187 r"\s+"
188 f"(?P<status>{'|'.join(re.escape(status) for status in DOCKER_STATUS_PULL)})"
189 r"\s*"
190 r"$"
191 )
192
193 _DOCKER_PULL_PROGRESS_WD = sorted(
194 DOCKER_PULL_PROGRESS_DONE | DOCKER_PULL_PROGRESS_WORKING_OLD
195 )
196
197 _RE_PULL_PROGRESS = re.compile(
198 r"^"
199 r"\s*"
200 r"(?P<layer>\S+)"
201 r"\s+"
202 f"(?P<status>{'|'.join(re.escape(status) for status in _DOCKER_PULL_PROGRESS_WD)})"
203 r"\s*"
204 r"(?:|\s\[[^]]+\]\s+\S+\s*|\s+[0-9.kKmMgGbB]+/[0-9.kKmMgGbB]+\s*)"
205 r"$"
206 )
207
208 _RE_ERROR_EVENT = re.compile(
209 r"^"
210 r"\s*"
211 r"(?P<resource_id>\S+)"
212 r"\s+"
213 f"(?P<status>{'|'.join(re.escape(status) for status in DOCKER_STATUS_ERROR)})"
214 r"\s*"
215 r"(?P<msg>\S.*\S)?"
216 r"$"
217 )
218
219 _RE_WARNING_EVENT = re.compile(
220 r"^"
221 r"\s*"
222 r"(?P<resource_id>\S+)"
223 r"\s+"
224 f"(?P<status>{'|'.join(re.escape(status) for status in DOCKER_STATUS_WARNING)})"
225 r"\s*"
226 r"(?P<msg>\S.*\S)?"
227 r"$"
228 )
229
230 _RE_CONTINUE_EVENT = re.compile(r"^\s*(?P<resource_id>\S+)\s+-\s*(?P<msg>\S(?:|.*\S))$")
231
232 _RE_SKIPPED_EVENT = re.compile(
233 r"^"
234 r"\s*"
235 r"(?P<resource_id>\S+)"
236 r"\s+"
237 r"Skipped(?: -"
238 r"\s*"
239 r"(?P<msg>\S(?:|.*\S))|\s*)"
240 r"$"
241 )
242
243 _RE_BUILD_START_EVENT = re.compile(r"^\s*build service\s+(?P<resource_id>\S+)$")
244
245 _RE_BUILD_PROGRESS_EVENT = re.compile(r"^\s*==>\s+(?P<msg>.*)$")
246
247 # The following needs to be kept in sync with the MINIMUM_VERSION compose_v2 docs fragment
248 MINIMUM_COMPOSE_VERSION = "2.18.0"
249
250
251 def _extract_event(
252 line: str, warn_function: Callable[[str], None] | None = None
253 ) -> tuple[Event | None, bool]:
254 match = _RE_RESOURCE_EVENT.match(line)
255 if match is not None:
256 status = match.group("status")
257 msg = None
258 if status not in DOCKER_STATUS:
259 status, msg = msg, status
260 return (
261 Event(
262 ResourceType.from_docker_compose_event(match.group("resource_type")),
263 match.group("resource_id"),
264 status,
265 msg,
266 ),
267 True,
268 )
269 match = _RE_PULL_EVENT.match(line)
270 if match:
271 return (
272 Event(
273 ResourceType.SERVICE,
274 match.group("service"),
275 match.group("status"),
276 None,
277 ),
278 True,
279 )
280 match = _RE_ERROR_EVENT.match(line)
281 if match:
282 return (
283 Event(
284 ResourceType.UNKNOWN,
285 match.group("resource_id"),
286 match.group("status"),
287 match.group("msg") or None,
288 ),
289 True,
290 )
291 match = _RE_WARNING_EVENT.match(line)
292 if match:
293 if warn_function:
294 if match.group("msg"):
295 msg = f"{match.group('resource_id')}: {match.group('msg')}"
296 else:
297 msg = f"Unspecified warning for {match.group('resource_id')}"
298 warn_function(msg)
299 return None, True
300 match = _RE_PULL_PROGRESS.match(line)
301 if match:
302 return (
303 Event(
304 ResourceType.IMAGE_LAYER,
305 match.group("layer"),
306 match.group("status"),
307 None,
308 ),
309 True,
310 )
311 match = _RE_SKIPPED_EVENT.match(line)
312 if match:
313 return (
314 Event(
315 ResourceType.UNKNOWN,
316 match.group("resource_id"),
317 "Skipped",
318 match.group("msg"),
319 ),
320 True,
321 )
322 match = _RE_BUILD_START_EVENT.match(line)
323 if match:
324 return (
325 Event(
326 ResourceType.SERVICE,
327 match.group("resource_id"),
328 "Building",
329 None,
330 ),
331 True,
332 )
333 return None, False
334
335
336 def _extract_logfmt_event(
337 line: str, warn_function: Callable[[str], None] | None = None
338 ) -> tuple[Event | None, bool]:
339 try:
340 result = _parse_logfmt_line(line, logrus_mode=True)
341 except _InvalidLogFmt:
342 return None, False
343 if "time" not in result or "level" not in result or "msg" not in result:
344 return None, False
345 if result["level"] == "warning":
346 if warn_function:
347 warn_function(result["msg"])
348 return None, True
349 # TODO: no idea what to do with this
350 return None, False
351
352
353 def _warn_missing_dry_run_prefix(
354 line: str,
355 warn_missing_dry_run_prefix: bool,
356 warn_function: Callable[[str], None] | None,
357 ) -> None:
358 if warn_missing_dry_run_prefix and warn_function:
359 # This could be a bug, a change of docker compose's output format, ...
360 # Tell the user to report it to us :-)
361 warn_function(
362 f"Event line is missing dry-run mode marker: {line!r}. Please check with the latest community.docker version,"
363 " and if the problem still happens there, please report this at "
364 "https://github.com/ansible-collections/community.docker/issues/new?assignees=&labels=&projects=&template=bug_report.md"
365 )
366
367
368 def _warn_unparsable_line(
369 line: str, warn_function: Callable[[str], None] | None
370 ) -> None:
371 # This could be a bug, a change of docker compose's output format, ...
372 # Tell the user to report it to us :-)
373 if warn_function:
374 warn_function(
375 f"Cannot parse event from line: {line!r}. Please check with the latest community.docker version,"
376 " and if the problem still happens there, please report this at "
377 "https://github.com/ansible-collections/community.docker/issues/new?assignees=&labels=&projects=&template=bug_report.md"
378 )
379
380
381 def _find_last_event_for(
382 events: list[Event], resource_id: str
383 ) -> tuple[int, Event] | None:
384 for index, event in enumerate(reversed(events)):
385 if event.resource_id == resource_id:
386 return len(events) - 1 - index, event
387 return None
388
389
390 def _concat_event_msg(event: Event, append_msg: str) -> Event:
391 return Event(
392 event.resource_type,
393 event.resource_id,
394 event.status,
395 "\n".join(msg for msg in [event.msg, append_msg] if msg is not None),
396 )
397
398
399 _JSON_LEVEL_TO_STATUS_MAP = {
400 "warning": "Warning",
401 "error": "Error",
402 }
403
404
405 def parse_json_events(
406 stderr: bytes, warn_function: Callable[[str], None] | None = None
407 ) -> list[Event]:
408 events = []
409 stderr_lines = stderr.splitlines()
410 if stderr_lines and stderr_lines[-1] == b"":
411 del stderr_lines[-1]
412 for line in stderr_lines:
413 line = line.strip()
414 if not line.startswith(b"{") or not line.endswith(b"}"):
415 if line.startswith(b"Warning: "):
416 # This is a bug in Compose that will get fixed by https://github.com/docker/compose/pull/11996
417 event = Event(
418 ResourceType.UNKNOWN,
419 None,
420 "Warning",
421 to_text(line[len(b"Warning: ") :]),
422 )
423 events.append(event)
424 continue
425 if warn_function:
426 warn_function(
427 f"Cannot parse event from non-JSON line: {line!r}. Please check with the latest community.docker version,"
428 " and if the problem still happens there, please report this at "
429 "https://github.com/ansible-collections/community.docker/issues/new?assignees=&labels=&projects=&template=bug_report.md"
430 )
431 continue
432 try:
433 line_data = json.loads(line)
434 except Exception as exc: # pylint: disable=broad-exception-caught
435 if warn_function:
436 warn_function(
437 f"Cannot parse event from line: {line!r}: {exc}. Please check with the latest community.docker version,"
438 " and if the problem still happens there, please report this at "
439 "https://github.com/ansible-collections/community.docker/issues/new?assignees=&labels=&projects=&template=bug_report.md"
440 )
441 continue
442 if line_data.get("tail"):
443 resource_type = ResourceType.UNKNOWN
444 msg = line_data.get("text")
445 status = "Error"
446 if isinstance(msg, str) and msg.lower().startswith("warning:"):
447 # For some reason, Writer.TailMsgf() is always used for errors *except* in one place,
448 # where its message is prepended with 'WARNING: ' (in pkg/compose/pull.go).
449 status = "Warning"
450 msg = msg[len("warning:") :].lstrip()
451 event = Event(
452 resource_type,
453 None,
454 status,
455 msg,
456 )
457 elif line_data.get("error"):
458 resource_type = ResourceType.UNKNOWN
459 event = Event(
460 resource_type,
461 line_data.get("id"),
462 "Error",
463 line_data.get("message"),
464 )
465 else:
466 resource_type = ResourceType.UNKNOWN
467 resource_id = line_data.get("id")
468 status = line_data.get("status")
469 text = line_data.get("text")
470 if resource_id == " " and text and text.startswith("build service "):
471 # Example:
472 # {"dry-run":true,"id":" ","text":"build service app"}
473 resource_id = "S" + text[len("build s") :]
474 text = "Building"
475 if (
476 isinstance(resource_id, str)
477 and resource_id.endswith("==>")
478 and text
479 and text.startswith("==> writing image ")
480 ):
481 # Example:
482 # {"dry-run":true,"id":"==>","text":"==> writing image dryRun-7d1043473d55bfa90e8530d35801d4e381bc69f0"}
483 # {"dry-run":true,"id":"ansible-docker-test-dc713f1f-container ==>","text":"==> writing image dryRun-5d9204268db1a73d57bbd24a25afbeacebe2bc02"}
484 # (The longer form happens since Docker Compose 2.39.0)
485 continue
486 if (
487 isinstance(resource_id, str)
488 and resource_id.endswith("==> ==>")
489 and text
490 and text.startswith("naming to ")
491 ):
492 # Example:
493 # {"dry-run":true,"id":"==> ==>","text":"naming to display-app"}
494 # {"dry-run":true,"id":"ansible-docker-test-dc713f1f-container ==> ==>","text":"naming to ansible-docker-test-dc713f1f-image"}
495 # (The longer form happens since Docker Compose 2.39.0)
496 continue
497 if (
498 status in ("Working", "Done")
499 and isinstance(line_data.get("parent_id"), str)
500 and line_data["parent_id"].startswith("Image ")
501 ):
502 # Compose 5.0.0+:
503 # {"id":"63a26ae4e8a8","parent_id":"Image ghcr.io/ansible-collections/simple-1:tag","status":"Working"}
504 # {"id":"63a26ae4e8a8","parent_id":"Image ghcr.io/ansible-collections/simple-1:tag","status":"Done","percent":100}
505 resource_type = ResourceType.IMAGE_LAYER
506 resource_id = line_data["parent_id"][len("Image ") :]
507 elif isinstance(resource_id, str) and " " in resource_id:
508 resource_type_str, resource_id = resource_id.split(" ", 1)
509 try:
510 resource_type = ResourceType.from_docker_compose_event(
511 resource_type_str
512 )
513 except KeyError:
514 if warn_function:
515 warn_function(
516 f"Unknown resource type {resource_type_str!r} in line {line!r}. Please check with the latest community.docker version,"
517 " and if the problem still happens there, please report this at "
518 "https://github.com/ansible-collections/community.docker/issues/new?assignees=&labels=&projects=&template=bug_report.md"
519 )
520 resource_type = ResourceType.UNKNOWN
521 elif text in DOCKER_STATUS_PULL:
522 resource_type = ResourceType.IMAGE
523 status, text = text, status
524 elif (
525 text in DOCKER_PULL_PROGRESS_DONE
526 or line_data.get("text") in DOCKER_PULL_PROGRESS_WORKING_OLD
527 ):
528 resource_type = ResourceType.IMAGE_LAYER
529 status, text = text, status
530 elif (
531 status is None
532 and isinstance(text, str)
533 and text.startswith("Skipped - ")
534 ):
535 status, text = text.split(" - ", 1)
536 elif (
537 line_data.get("level") in _JSON_LEVEL_TO_STATUS_MAP
538 and "msg" in line_data
539 ):
540 status = _JSON_LEVEL_TO_STATUS_MAP[line_data["level"]]
541 text = line_data["msg"]
542 if (
543 status not in DOCKER_STATUS_AND_WARNING
544 and text in DOCKER_STATUS_AND_WARNING
545 ):
546 status, text = text, status
547 event = Event(
548 resource_type,
549 resource_id,
550 status,
551 text,
552 )
553
554 events.append(event)
555 return events
556
557
558 def parse_events(
559 stderr: bytes,
560 dry_run: bool = False,
561 warn_function: Callable[[str], None] | None = None,
562 nonzero_rc: bool = False,
563 ) -> list[Event]:
564 events = []
565 error_event = None
566 stderr_lines = stderr.splitlines()
567 if stderr_lines and stderr_lines[-1] == b"":
568 del stderr_lines[-1]
569 for index, line_b in enumerate(stderr_lines):
570 line = to_text(line_b.strip())
571 if not line:
572 continue
573 warn_missing_dry_run_prefix = False
574 if dry_run:
575 if line.startswith(_DRY_RUN_MARKER):
576 line = line[len(_DRY_RUN_MARKER) :].lstrip()
577 else:
578 warn_missing_dry_run_prefix = True
579 event, parsed = _extract_event(line, warn_function=warn_function)
580 if event is not None:
581 events.append(event)
582 if event.status in DOCKER_STATUS_ERROR:
583 error_event = event
584 else:
585 error_event = None
586 _warn_missing_dry_run_prefix(
587 line, warn_missing_dry_run_prefix, warn_function
588 )
589 continue
590 if parsed:
591 continue
592 match = _RE_BUILD_PROGRESS_EVENT.match(line)
593 if match:
594 # Ignore this
595 continue
596 match = _RE_CONTINUE_EVENT.match(line)
597 if match:
598 # Continuing an existing event
599 index_event = _find_last_event_for(events, match.group("resource_id"))
600 if index_event is not None:
601 index, event = index_event
602 events[index] = _concat_event_msg(event, match.group("msg"))
603 event, parsed = _extract_logfmt_event(line, warn_function=warn_function)
604 if event is not None:
605 events.append(event)
606 elif parsed:
607 continue
608 if error_event is not None:
609 # Unparsable line that apparently belongs to the previous error event
610 events[-1] = _concat_event_msg(error_event, line)
611 continue
612 if line.startswith("Error "):
613 # Error message that is independent of an error event
614 error_event = Event(
615 ResourceType.UNKNOWN,
616 "",
617 "Error",
618 line,
619 )
620 events.append(error_event)
621 continue
622 if len(stderr_lines) == 1 or (nonzero_rc and index == len(stderr_lines) - 1):
623 # **Very likely** an error message that is independent of an error event
624 error_event = Event(
625 ResourceType.UNKNOWN,
626 "",
627 "Error",
628 line,
629 )
630 events.append(error_event)
631 continue
632 _warn_missing_dry_run_prefix(line, warn_missing_dry_run_prefix, warn_function)
633 _warn_unparsable_line(line, warn_function)
634 return events
635
636
637 def has_changes(
638 events: Sequence[Event],
639 ignore_service_pull_events: bool = False,
640 ignore_build_events: bool = False,
641 ) -> bool:
642 for event in events:
643 if event.status in DOCKER_STATUS_WORKING:
644 if ignore_service_pull_events and event.status in DOCKER_STATUS_PULL:
645 continue
646 if ignore_build_events and event.status in DOCKER_STATUS_BUILD:
647 continue
648 return True
649 if (
650 event.resource_type == ResourceType.IMAGE_LAYER
651 and event.status in DOCKER_PULL_PROGRESS_WORKING
652 ):
653 return True
654 return False
655
656
657 def extract_actions(events: Sequence[Event]) -> list[dict[str, t.Any]]:
658 actions = []
659 pull_actions = set()
660 for event in events:
661 if (
662 event.resource_type == ResourceType.IMAGE_LAYER
663 and event.status in DOCKER_PULL_PROGRESS_WORKING
664 ):
665 pull_id = (event.resource_id, event.status)
666 if pull_id not in pull_actions:
667 pull_actions.add(pull_id)
668 actions.append(
669 {
670 "what": event.resource_type,
671 "id": event.resource_id,
672 "status": event.status,
673 }
674 )
675 if (
676 event.resource_type != ResourceType.IMAGE_LAYER
677 and event.status in DOCKER_STATUS_WORKING
678 ):
679 actions.append(
680 {
681 "what": event.resource_type,
682 "id": event.resource_id,
683 "status": event.status,
684 }
685 )
686 return actions
687
688
689 def emit_warnings(
690 events: Sequence[Event], warn_function: Callable[[str], None]
691 ) -> None:
692 for event in events:
693 # If a message is present, assume it is a warning
694 if (
695 event.status is None and event.msg is not None
696 ) or event.status in DOCKER_STATUS_WARNING:
697 warn_function(
698 f"Docker compose: {event.resource_type} {event.resource_id}: {event.msg}"
699 )
700
701
702 def is_failed(events: Sequence[Event], rc: int) -> bool:
703 return bool(rc)
704
705
706 def update_failed(
707 result: dict[str, t.Any],
708 events: Sequence[Event],
709 args: list[str],
710 stdout: str | bytes,
711 stderr: str | bytes,
712 rc: int,
713 cli: str,
714 ) -> bool:
715 if not rc:
716 return False
717 errors = []
718 for event in events:
719 if event.status in DOCKER_STATUS_ERROR:
720 if event.resource_id is None:
721 if event.resource_type == "unknown":
722 msg = (
723 "General error: "
724 if event.resource_type == "unknown"
725 else f"Error when processing {event.resource_type}: "
726 )
727 else:
728 msg = (
729 f"Error when processing {event.resource_type} {event.resource_id}: "
730 )
731 if event.resource_type == "unknown":
732 msg = f"Error when processing {event.resource_id}: "
733 if event.resource_id == "":
734 msg = "General error: "
735 msg += f"{event.status}" if event.msg is None else f"{event.msg}"
736 errors.append(msg)
737 if not errors:
738 errors.append(f"Return code {rc} is non-zero")
739 result["failed"] = True
740 result["msg"] = "\n".join(errors)
741 result["cmd"] = " ".join(quote(arg) for arg in [cli] + args)
742 result["stdout"] = to_text(stdout)
743 result["stderr"] = to_text(stderr)
744 result["rc"] = rc
745 return True
746
747
748 def common_compose_argspec() -> dict[str, t.Any]:
749 return {
750 "project_src": {"type": "path"},
751 "project_name": {"type": "str"},
752 "files": {"type": "list", "elements": "path"},
753 "definition": {"type": "dict"},
754 "env_files": {"type": "list", "elements": "path"},
755 "profiles": {"type": "list", "elements": "str"},
756 "check_files_existing": {"type": "bool", "default": True},
757 }
758
759
760 def common_compose_argspec_ex() -> dict[str, t.Any]:
761 return {
762 "argspec": common_compose_argspec(),
763 "mutually_exclusive": [("definition", "project_src"), ("definition", "files")],
764 "required_one_of": [
765 ("definition", "project_src"),
766 ],
767 "required_by": {
768 "definition": ("project_name",),
769 },
770 }
771
772
773 def combine_binary_output(*outputs: bytes | None) -> bytes:
774 return b"\n".join(out for out in outputs if out)
775
776
777 def combine_text_output(*outputs: str | None) -> str:
778 return "\n".join(out for out in outputs if out)
779
780
781 class BaseComposeManager(DockerBaseClass):
782 def __init__(
783 self, client: _Client, min_version: str = MINIMUM_COMPOSE_VERSION
784 ) -> None:
785 super().__init__()
786 self.client = client
787 self.check_mode = self.client.check_mode
788 self.cleanup_dirs = set()
789 parameters = self.client.module.params
790
791 if parameters["definition"] is not None and not HAS_PYYAML:
792 self.fail(missing_required_lib("PyYAML"), exception=PYYAML_IMPORT_ERROR)
793
794 self.project_name = parameters["project_name"]
795 if parameters["definition"] is not None:
796 self.project_src = tempfile.mkdtemp(prefix="ansible")
797 self.cleanup_dirs.add(self.project_src)
798 compose_file = os.path.join(self.project_src, "compose.yaml")
799 self.client.module.add_cleanup_file(compose_file)
800 try:
801 with open(compose_file, "wb") as f:
802 yaml.dump(
803 parameters["definition"],
804 f,
805 encoding="utf-8",
806 Dumper=_SafeDumper,
807 )
808 except Exception as exc: # pylint: disable=broad-exception-caught
809 self.fail(f"Error writing to {compose_file} - {exc}")
810 else:
811 self.project_src = os.path.abspath(parameters["project_src"])
812
813 self.files = parameters["files"]
814 self.env_files = parameters["env_files"]
815 self.profiles = parameters["profiles"]
816
817 compose_version = self.get_compose_version()
818 self.compose_version = LooseVersion(compose_version)
819 if self.compose_version < LooseVersion(min_version):
820 self.fail(
821 f"Docker CLI {self.client.get_cli()} has the compose plugin with version {compose_version}; need version {min_version} or later"
822 )
823
824 if not os.path.isdir(self.project_src):
825 self.fail(f'"{self.project_src}" is not a directory')
826
827 self.check_files_existing = parameters["check_files_existing"]
828 if self.files:
829 for file in self.files:
830 path = os.path.join(self.project_src, file)
831 if not os.path.exists(path):
832 self.fail(
833 f'Cannot find Compose file "{file}" relative to project directory "{self.project_src}"'
834 )
835 elif self.check_files_existing and all(
836 not os.path.exists(os.path.join(self.project_src, f))
837 for f in DOCKER_COMPOSE_FILES
838 ):
839 filenames = ", ".join(DOCKER_COMPOSE_FILES[:-1])
840 self.fail(
841 f'"{self.project_src}" does not contain {filenames}, or {DOCKER_COMPOSE_FILES[-1]}'
842 )
843
844 # Support for JSON output was added in Compose 2.29.0 (https://github.com/docker/compose/releases/tag/v2.29.0);
845 # more precisely in https://github.com/docker/compose/pull/11478
846 self.use_json_events = self.compose_version >= LooseVersion("2.29.0")
847
848 def get_compose_version(self) -> str:
849 return (
850 self.get_compose_version_from_cli() or self.get_compose_version_from_api()
851 )
852
853 def get_compose_version_from_cli(self) -> str | None:
854 rc, version_info, dummy_stderr = self.client.call_cli(
855 "compose", "version", "--format", "json"
856 )
857 if rc:
858 return None
859 try:
860 version = json.loads(version_info)["version"]
861 if version == "dev":
862 return None
863 return version.lstrip("v")
864 except Exception: # pylint: disable=broad-exception-caught
865 return None
866
867 def get_compose_version_from_api(self) -> str:
868 compose = self.client.get_client_plugin_info("compose")
869 if compose is None:
870 self.fail(
871 f"Docker CLI {self.client.get_cli()} does not have the compose plugin installed"
872 )
873 if compose["Version"] == "dev":
874 self.fail(
875 f'Docker CLI {self.client.get_cli()} has a compose plugin installed, but it reports version "dev".'
876 " Please use a version of the plugin that returns a proper version."
877 )
878 return compose["Version"].lstrip("v")
879
880 def fail(self, msg: str, **kwargs: t.Any) -> t.NoReturn:
881 self.cleanup()
882 self.client.fail(msg, **kwargs)
883
884 def get_base_args(self, plain_progress: bool = False) -> list[str]:
885 args = ["compose", "--ansi", "never"]
886 if self.use_json_events and not plain_progress:
887 args.extend(["--progress", "json"])
888 elif self.compose_version >= LooseVersion("2.19.0"):
889 # https://github.com/docker/compose/pull/10690
890 args.extend(["--progress", "plain"])
891 args.extend(["--project-directory", self.project_src])
892 if self.project_name:
893 args.extend(["--project-name", self.project_name])
894 for file in self.files or []:
895 args.extend(["--file", file])
896 for env_file in self.env_files or []:
897 args.extend(["--env-file", env_file])
898 for profile in self.profiles or []:
899 args.extend(["--profile", profile])
900 return args
901
902 def _handle_failed_cli_call(
903 self, args: list[str], rc: int, stdout: str | bytes, stderr: bytes
904 ) -> t.NoReturn:
905 events = parse_json_events(stderr, warn_function=self.client.warn)
906 result: dict[str, t.Any] = {}
907 self.update_failed(result, events, args, stdout, stderr, rc)
908 self.client.module.exit_json(**result)
909
910 def list_containers_raw(self) -> list[dict[str, t.Any]]:
911 args = self.get_base_args() + ["ps", "--format", "json", "--all"]
912 if self.compose_version >= LooseVersion("2.23.0"):
913 # https://github.com/docker/compose/pull/11038
914 args.append("--no-trunc")
915 if self.compose_version >= LooseVersion("2.21.0"):
916 # Breaking change in 2.21.0: https://github.com/docker/compose/pull/10918
917 rc, containers, stderr = self.client.call_cli_json_stream(
918 *args, cwd=self.project_src, check_rc=not self.use_json_events
919 )
920 else:
921 rc, containers, stderr = self.client.call_cli_json(
922 *args, cwd=self.project_src, check_rc=not self.use_json_events
923 )
924 if self.use_json_events and rc != 0:
925 self._handle_failed_cli_call(args, rc, json.dumps(containers), stderr)
926 return containers
927
928 def list_containers(self) -> list[dict[str, t.Any]]:
929 result = []
930 for container in self.list_containers_raw():
931 labels = {}
932 if container.get("Labels"):
933 for part in container["Labels"].split(","):
934 label_value = part.split("=", 1)
935 labels[label_value[0]] = (
936 label_value[1] if len(label_value) > 1 else ""
937 )
938 container["Labels"] = labels
939 container["Names"] = container.get("Names", container["Name"]).split(",")
940 container["Networks"] = container.get("Networks", "").split(",")
941 container["Publishers"] = container.get("Publishers") or []
942 result.append(container)
943 return result
944
945 def list_images(self) -> list[str]:
946 args = self.get_base_args() + ["images", "--format", "json"]
947 rc, images, stderr = self.client.call_cli_json(
948 *args, cwd=self.project_src, check_rc=not self.use_json_events
949 )
950 if self.use_json_events and rc != 0:
951 self._handle_failed_cli_call(args, rc, images, stderr)
952 if isinstance(images, dict):
953 # Handle breaking change in Docker Compose 2.37.0; see
954 # https://github.com/ansible-collections/community.docker/issues/1082
955 # and https://github.com/docker/compose/issues/12916 for details
956 images = list(images.values())
957 return images
958
959 def parse_events(
960 self, stderr: bytes, dry_run: bool = False, nonzero_rc: bool = False
961 ) -> list[Event]:
962 if self.use_json_events:
963 return parse_json_events(stderr, warn_function=self.client.warn)
964 return parse_events(
965 stderr,
966 dry_run=dry_run,
967 warn_function=self.client.warn,
968 nonzero_rc=nonzero_rc,
969 )
970
971 def emit_warnings(self, events: Sequence[Event]) -> None:
972 emit_warnings(events, warn_function=self.client.warn)
973
974 def update_result(
975 self,
976 result: dict[str, t.Any],
977 events: Sequence[Event],
978 stdout: str | bytes,
979 stderr: str | bytes,
980 ignore_service_pull_events: bool = False,
981 ignore_build_events: bool = False,
982 ) -> None:
983 result["changed"] = result.get("changed", False) or has_changes(
984 events,
985 ignore_service_pull_events=ignore_service_pull_events,
986 ignore_build_events=ignore_build_events,
987 )
988 result["actions"] = result.get("actions", []) + extract_actions(events)
989 result["stdout"] = combine_text_output(result.get("stdout"), to_text(stdout))
990 result["stderr"] = combine_text_output(result.get("stderr"), to_text(stderr))
991
992 def update_failed(
993 self,
994 result: dict[str, t.Any],
995 events: Sequence[Event],
996 args: list[str],
997 stdout: str | bytes,
998 stderr: bytes,
999 rc: int,
1000 ) -> bool:
1001 return update_failed(
1002 result,
1003 events,
1004 args=args,
1005 stdout=stdout,
1006 stderr=stderr,
1007 rc=rc,
1008 cli=self.client.get_cli(),
1009 )
1010
1011 def cleanup_result(self, result: dict[str, t.Any]) -> None:
1012 if not result.get("failed"):
1013 # Only return stdout and stderr if it is not empty
1014 for res in ("stdout", "stderr"):
1015 if result.get(res) == "":
1016 result.pop(res)
1017
1018 def cleanup(self) -> None:
1019 for directory in self.cleanup_dirs:
1020 try:
1021 shutil.rmtree(directory, True)
1022 except Exception: # pylint: disable=broad-exception-caught
1023 # should not happen, but simply ignore to be on the safe side
1024 pass