Debian Codegraph @

ansible_collections/community/docker/plugins/modules/docker_swarm_info.py

raw
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2019 Piotr Wojciechowski <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: docker_swarm_info
11
12 short_description: Retrieves facts about Docker Swarm cluster
13
14 description:
15 - Retrieves facts about a Docker Swarm.
16 - Returns lists of swarm objects names for the services - nodes, services, tasks.
17 - The output differs depending on API version available on docker host.
18 - Must be run on Swarm Manager node; otherwise module fails with error message. It does return boolean flags in on both
19 error and success which indicate whether the docker daemon can be communicated with, whether it is in Swarm mode, and
20 whether it is a Swarm Manager node.
21 author:
22 - Piotr Wojciechowski (@WojciechowskiPiotr)
23
24 extends_documentation_fragment:
25 - community.docker._docker
26 - community.docker._docker.docker_py_2_documentation
27 - community.docker._attributes
28 - community.docker._attributes.actiongroup_docker
29 - community.docker._attributes.info_module
30 - community.docker._attributes.idempotent_not_modify_state
31
32 options:
33 nodes:
34 description:
35 - Whether to list swarm nodes.
36 type: bool
37 default: false
38 nodes_filters:
39 description:
40 - A dictionary of filter values used for selecting nodes to list.
41 - 'For example, C(name: mynode).'
42 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/node_ls/#filtering) for more information
43 on possible filters.
44 type: dict
45 services:
46 description:
47 - Whether to list swarm services.
48 type: bool
49 default: false
50 services_filters:
51 description:
52 - A dictionary of filter values used for selecting services to list.
53 - 'For example, C(name: myservice).'
54 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/service_ls/#filtering) for more
55 information on possible filters.
56 type: dict
57 tasks:
58 description:
59 - Whether to list containers.
60 type: bool
61 default: false
62 tasks_filters:
63 description:
64 - A dictionary of filter values used for selecting tasks to list.
65 - 'For example, C(node: mynode-1).'
66 - See L(the docker documentation,https://docs.docker.com/engine/reference/commandline/service_ps/#filtering) for more
67 information on possible filters.
68 type: dict
69 unlock_key:
70 description:
71 - Whether to retrieve the swarm unlock key.
72 type: bool
73 default: false
74 verbose_output:
75 description:
76 - When set to V(true) and O(nodes), O(services), or O(tasks) is set to V(true), then the module output will contain
77 verbose information about objects matching the full output of API method.
78 - For details see the documentation of your version of Docker API at U(https://docs.docker.com/engine/api/).
79 - The verbose output in this module contains only subset of information returned by this info module for each type of
80 the objects.
81 type: bool
82 default: false
83
84 requirements:
85 - "L(Docker SDK for Python,https://docker-py.readthedocs.io/en/stable/) >= 2.0.0"
86 - "Docker API >= 1.25"
87 """
88
89 EXAMPLES = r"""
90 ---
91 - name: Get info on Docker Swarm
92 community.docker.docker_swarm_info:
93 ignore_errors: true
94 register: result
95
96 - name: Inform about basic flags
97 ansible.builtin.debug:
98 msg: |
99 Was able to talk to docker daemon: {{ result.can_talk_to_docker }}
100 Docker in Swarm mode: {{ result.docker_swarm_active }}
101 This is a Manager node: {{ result.docker_swarm_manager }}
102
103 - name: Get info on Docker Swarm and list of registered nodes
104 community.docker.docker_swarm_info:
105 nodes: true
106 register: result
107
108 - name: Get info on Docker Swarm and extended list of registered nodes
109 community.docker.docker_swarm_info:
110 nodes: true
111 verbose_output: true
112 register: result
113
114 - name: Get info on Docker Swarm and filtered list of registered nodes
115 community.docker.docker_swarm_info:
116 nodes: true
117 nodes_filters:
118 name: mynode
119 register: result
120
121 - name: Show swarm facts
122 ansible.builtin.debug:
123 var: result.swarm_facts
124
125 - name: Get the swarm unlock key
126 community.docker.docker_swarm_info:
127 unlock_key: true
128 register: result
129
130 - name: Print swarm unlock key
131 ansible.builtin.debug:
132 var: result.swarm_unlock_key
133 """
134
135 RETURN = r"""
136 can_talk_to_docker:
137 description:
138 - Will be V(true) if the module can talk to the docker daemon.
139 returned: both on success and on error
140 type: bool
141 docker_swarm_active:
142 description:
143 - Will be V(true) if the module can talk to the docker daemon, and the docker daemon is in Swarm mode.
144 returned: both on success and on error
145 type: bool
146 docker_swarm_manager:
147 description:
148 - Will be V(true) if the module can talk to the docker daemon, the docker daemon is in Swarm mode, and the current node
149 is a manager node.
150 - Only if this one is V(true), the module will not fail.
151 returned: both on success and on error
152 type: bool
153 swarm_facts:
154 description:
155 - Facts representing the basic state of the docker Swarm cluster.
156 - Contains tokens to connect to the Swarm.
157 returned: always
158 type: dict
159 swarm_unlock_key:
160 description:
161 - Contains the key needed to unlock the swarm.
162 returned: When O(unlock_key=true).
163 type: str
164 nodes:
165 description:
166 - List of dict objects containing the basic information about each volume. Keys matches the C(docker node ls) output unless
167 O(verbose_output=true). See description for O(verbose_output).
168 returned: When O(nodes=true)
169 type: list
170 elements: dict
171 services:
172 description:
173 - List of dict objects containing the basic information about each volume. Keys matches the C(docker service ls) output
174 unless O(verbose_output=true). See description for O(verbose_output).
175 returned: When O(services=true)
176 type: list
177 elements: dict
178 tasks:
179 description:
180 - List of dict objects containing the basic information about each volume. Keys matches the C(docker service ps) output
181 unless O(verbose_output=true). See description for O(verbose_output).
182 returned: When O(tasks=true)
183 type: list
184 elements: dict
185 """
186
187 import traceback
188 import typing as t
189
190 try:
191 from docker.errors import APIError, DockerException
192 except ImportError:
193 # missing Docker SDK for Python handled in ansible.module_utils.docker_common
194 pass
195
196 from ansible_collections.community.docker.plugins.module_utils._common import (
197 RequestException,
198 )
199 from ansible_collections.community.docker.plugins.module_utils._swarm import (
200 AnsibleDockerSwarmClient,
201 )
202 from ansible_collections.community.docker.plugins.module_utils._util import (
203 DockerBaseClass,
204 clean_dict_booleans_for_docker_api,
205 )
206
207
208 class DockerSwarmManager(DockerBaseClass):
209 def __init__(
210 self, client: AnsibleDockerSwarmClient, results: dict[str, t.Any]
211 ) -> None:
212 super().__init__()
213
214 self.client = client
215 self.results = results
216 self.verbose_output = self.client.module.params["verbose_output"]
217
218 listed_objects: list[t.Literal["nodes", "tasks", "services"]] = [
219 "tasks",
220 "services",
221 "nodes",
222 ]
223
224 self.client.fail_task_if_not_swarm_manager()
225
226 self.results["swarm_facts"] = self.get_docker_swarm_facts()
227
228 for docker_object in listed_objects:
229 if self.client.module.params[docker_object]:
230 returned_name = docker_object
231 filter_name = docker_object + "_filters"
232 filters = clean_dict_booleans_for_docker_api(
233 client.module.params.get(filter_name)
234 )
235 self.results[returned_name] = self.get_docker_items_list(
236 docker_object, filters
237 )
238 if self.client.module.params["unlock_key"]:
239 self.results["swarm_unlock_key"] = self.get_docker_swarm_unlock_key()
240
241 def get_docker_swarm_facts(self) -> dict[str, t.Any]:
242 try:
243 return self.client.inspect_swarm()
244 except APIError as exc:
245 self.client.fail(f"Error inspecting docker swarm: {exc}")
246
247 def get_docker_items_list(
248 self,
249 docker_object: t.Literal["nodes", "tasks", "services"],
250 filters: dict[str, str],
251 ) -> list[dict[str, t.Any]]:
252 items_list: list[dict[str, t.Any]] = []
253
254 try:
255 if docker_object == "nodes":
256 items = self.client.nodes(filters=filters)
257 elif docker_object == "tasks":
258 items = self.client.tasks(filters=filters)
259 elif docker_object == "services":
260 items = self.client.services(filters=filters)
261 else:
262 raise ValueError(f"Invalid docker_object {docker_object}")
263 except APIError as exc:
264 self.client.fail(
265 f"Error inspecting docker swarm for object '{docker_object}': {exc}"
266 )
267
268 if self.verbose_output:
269 return items
270
271 for item in items:
272 item_record = {}
273
274 if docker_object == "nodes":
275 item_record = self.get_essential_facts_nodes(item)
276 elif docker_object == "tasks":
277 item_record = self.get_essential_facts_tasks(item)
278 elif docker_object == "services":
279 item_record = self.get_essential_facts_services(item)
280 if item_record.get("Mode") == "Global":
281 item_record["Replicas"] = len(items)
282 items_list.append(item_record)
283
284 return items_list
285
286 @staticmethod
287 def get_essential_facts_nodes(item: dict[str, t.Any]) -> dict[str, t.Any]:
288 object_essentials = {}
289
290 object_essentials["ID"] = item.get("ID")
291 object_essentials["Hostname"] = item["Description"]["Hostname"]
292 object_essentials["Status"] = item["Status"]["State"]
293 object_essentials["Availability"] = item["Spec"]["Availability"]
294 if "ManagerStatus" in item:
295 object_essentials["ManagerStatus"] = item["ManagerStatus"]["Reachability"]
296 if (
297 "Leader" in item["ManagerStatus"]
298 and item["ManagerStatus"]["Leader"] is True
299 ):
300 object_essentials["ManagerStatus"] = "Leader"
301 else:
302 object_essentials["ManagerStatus"] = None
303 object_essentials["EngineVersion"] = item["Description"]["Engine"][
304 "EngineVersion"
305 ]
306
307 return object_essentials
308
309 def get_essential_facts_tasks(self, item: dict[str, t.Any]) -> dict[str, t.Any]:
310 object_essentials = {}
311
312 object_essentials["ID"] = item["ID"]
313 # Returning container ID to not trigger another connection to host
314 # Container ID is sufficient to get extended info in other tasks
315 object_essentials["ContainerID"] = item["Status"]["ContainerStatus"][
316 "ContainerID"
317 ]
318 object_essentials["Image"] = item["Spec"]["ContainerSpec"]["Image"]
319 object_essentials["Node"] = self.client.get_node_name_by_id(item["NodeID"])
320 object_essentials["DesiredState"] = item["DesiredState"]
321 object_essentials["CurrentState"] = item["Status"]["State"]
322 if "Err" in item["Status"]:
323 object_essentials["Error"] = item["Status"]["Err"]
324 else:
325 object_essentials["Error"] = None
326
327 return object_essentials
328
329 @staticmethod
330 def get_essential_facts_services(item: dict[str, t.Any]) -> dict[str, t.Any]:
331 object_essentials = {}
332
333 object_essentials["ID"] = item["ID"]
334 object_essentials["Name"] = item["Spec"]["Name"]
335 if "Replicated" in item["Spec"]["Mode"]:
336 object_essentials["Mode"] = "Replicated"
337 object_essentials["Replicas"] = item["Spec"]["Mode"]["Replicated"][
338 "Replicas"
339 ]
340 elif "Global" in item["Spec"]["Mode"]:
341 object_essentials["Mode"] = "Global"
342 # Number of replicas have to be updated in calling method or may be left as None
343 object_essentials["Replicas"] = None
344 object_essentials["Image"] = item["Spec"]["TaskTemplate"]["ContainerSpec"][
345 "Image"
346 ]
347 if item["Spec"].get("EndpointSpec") and "Ports" in item["Spec"]["EndpointSpec"]:
348 object_essentials["Ports"] = item["Spec"]["EndpointSpec"]["Ports"]
349 else:
350 object_essentials["Ports"] = []
351
352 return object_essentials
353
354 def get_docker_swarm_unlock_key(self) -> str | None:
355 unlock_key = self.client.get_unlock_key() or {}
356 return unlock_key.get("UnlockKey") or None
357
358
359 def main() -> None:
360 argument_spec = {
361 "nodes": {"type": "bool", "default": False},
362 "nodes_filters": {"type": "dict"},
363 "tasks": {"type": "bool", "default": False},
364 "tasks_filters": {"type": "dict"},
365 "services": {"type": "bool", "default": False},
366 "services_filters": {"type": "dict"},
367 "unlock_key": {"type": "bool", "default": False},
368 "verbose_output": {"type": "bool", "default": False},
369 }
370 option_minimal_versions = {
371 "unlock_key": {"docker_py_version": "2.7.0"},
372 }
373
374 client = AnsibleDockerSwarmClient(
375 argument_spec=argument_spec,
376 supports_check_mode=True,
377 min_docker_version="2.0.0",
378 option_minimal_versions=option_minimal_versions,
379 fail_results={
380 "can_talk_to_docker": False,
381 "docker_swarm_active": False,
382 "docker_swarm_manager": False,
383 },
384 )
385 client.fail_results["can_talk_to_docker"] = True
386 client.fail_results["docker_swarm_active"] = client.check_if_swarm_node()
387 client.fail_results["docker_swarm_manager"] = client.check_if_swarm_manager()
388
389 try:
390 results = {
391 "changed": False,
392 }
393
394 DockerSwarmManager(client, results)
395 results.update(client.fail_results)
396 client.module.exit_json(**results)
397 except DockerException as e:
398 client.fail(
399 f"An unexpected Docker error occurred: {e}",
400 exception=traceback.format_exc(),
401 )
402 except RequestException as e:
403 client.fail(
404 f"An unexpected requests error occurred when Docker SDK for Python tried to talk to the docker daemon: {e}",
405 exception=traceback.format_exc(),
406 )
407
408
409 if __name__ == "__main__":
410 main()