| 1 |
# Copyright (c) 2019 Piotr Wojciechowski (@wojciechowskipiotr) <[email protected]> |
| 2 |
# Copyright (c) Thierry Bouvet (@tbouvet) |
| 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 typing as t |
| 13 |
from time import sleep |
| 14 |
|
| 15 |
try: |
| 16 |
from docker.errors import APIError, NotFound |
| 17 |
except ImportError: |
| 18 |
# missing Docker SDK for Python handled in ansible.module_utils.docker.common |
| 19 |
pass |
| 20 |
|
| 21 |
from ansible_collections.community.docker.plugins.module_utils._common import ( |
| 22 |
AnsibleDockerClient, |
| 23 |
) |
| 24 |
from ansible_collections.community.docker.plugins.module_utils._version import ( |
| 25 |
LooseVersion, |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
class AnsibleDockerSwarmClient(AnsibleDockerClient): |
| 30 |
def get_swarm_node_id(self) -> str | None: |
| 31 |
""" |
| 32 |
Get the 'NodeID' of the Swarm node or 'None' if host is not in Swarm. It returns the NodeID |
| 33 |
of Docker host the module is executed on |
| 34 |
:return: |
| 35 |
NodeID of host or 'None' if not part of Swarm |
| 36 |
""" |
| 37 |
|
| 38 |
try: |
| 39 |
info = self.info() |
| 40 |
except APIError as exc: |
| 41 |
self.fail(f"Failed to get node information for {exc}") |
| 42 |
|
| 43 |
if info: |
| 44 |
json_str = json.dumps(info, ensure_ascii=False) |
| 45 |
swarm_info = json.loads(json_str) |
| 46 |
if swarm_info["Swarm"]["NodeID"]: |
| 47 |
return swarm_info["Swarm"]["NodeID"] |
| 48 |
return None |
| 49 |
|
| 50 |
def check_if_swarm_node(self, node_id: str | None = None) -> bool | None: |
| 51 |
""" |
| 52 |
Checking if host is part of Docker Swarm. If 'node_id' is not provided it reads the Docker host |
| 53 |
system information looking if specific key in output exists. If 'node_id' is provided then it tries to |
| 54 |
read node information assuming it is run on Swarm manager. The get_node_inspect() method handles exception if |
| 55 |
it is not executed on Swarm manager |
| 56 |
|
| 57 |
:param node_id: Node identifier |
| 58 |
:return: |
| 59 |
bool: True if node is part of Swarm, False otherwise |
| 60 |
""" |
| 61 |
|
| 62 |
if node_id is None: |
| 63 |
try: |
| 64 |
info = self.info() |
| 65 |
except APIError: |
| 66 |
self.fail("Failed to get host information.") |
| 67 |
|
| 68 |
if info: |
| 69 |
json_str = json.dumps(info, ensure_ascii=False) |
| 70 |
swarm_info = json.loads(json_str) |
| 71 |
if swarm_info["Swarm"]["NodeID"]: |
| 72 |
return True |
| 73 |
return swarm_info["Swarm"]["LocalNodeState"] in ( |
| 74 |
"active", |
| 75 |
"pending", |
| 76 |
"locked", |
| 77 |
) |
| 78 |
return False |
| 79 |
try: |
| 80 |
node_info = self.get_node_inspect(node_id=node_id) |
| 81 |
except APIError: |
| 82 |
return None |
| 83 |
|
| 84 |
return node_info["ID"] is not None |
| 85 |
|
| 86 |
def check_if_swarm_manager(self) -> bool: |
| 87 |
""" |
| 88 |
Checks if node role is set as Manager in Swarm. The node is the docker host on which module action |
| 89 |
is performed. The inspect_swarm() will fail if node is not a manager |
| 90 |
|
| 91 |
:return: True if node is Swarm Manager, False otherwise |
| 92 |
""" |
| 93 |
|
| 94 |
try: |
| 95 |
self.inspect_swarm() |
| 96 |
return True |
| 97 |
except APIError: |
| 98 |
return False |
| 99 |
|
| 100 |
def fail_task_if_not_swarm_manager(self) -> None: |
| 101 |
""" |
| 102 |
If host is not a swarm manager then Ansible task on this host should end with 'failed' state |
| 103 |
""" |
| 104 |
if not self.check_if_swarm_manager(): |
| 105 |
self.fail( |
| 106 |
"Error running docker swarm module: must run on swarm manager node" |
| 107 |
) |
| 108 |
|
| 109 |
def check_if_swarm_worker(self) -> bool: |
| 110 |
""" |
| 111 |
Checks if node role is set as Worker in Swarm. The node is the docker host on which module action |
| 112 |
is performed. Will fail if run on host that is not part of Swarm via check_if_swarm_node() |
| 113 |
|
| 114 |
:return: True if node is Swarm Worker, False otherwise |
| 115 |
""" |
| 116 |
|
| 117 |
return bool(self.check_if_swarm_node() and not self.check_if_swarm_manager()) |
| 118 |
|
| 119 |
def check_if_swarm_node_is_down( |
| 120 |
self, node_id: str | None = None, repeat_check: int = 1 |
| 121 |
) -> bool: |
| 122 |
""" |
| 123 |
Checks if node status on Swarm manager is 'down'. If node_id is provided it query manager about |
| 124 |
node specified in parameter, otherwise it query manager itself. If run on Swarm Worker node or |
| 125 |
host that is not part of Swarm it will fail the playbook |
| 126 |
|
| 127 |
:param repeat_check: number of check attempts with 5 seconds delay between them, by default check only once |
| 128 |
:param node_id: node ID or name, if None then method will try to get node_id of host module run on |
| 129 |
:return: |
| 130 |
True if node is part of swarm but its state is down, False otherwise |
| 131 |
""" |
| 132 |
|
| 133 |
repeat_check = max(1, repeat_check) |
| 134 |
|
| 135 |
if node_id is None: |
| 136 |
node_id = self.get_swarm_node_id() |
| 137 |
|
| 138 |
for retry in range(0, repeat_check): |
| 139 |
if retry > 0: |
| 140 |
sleep(5) |
| 141 |
node_info = self.get_node_inspect(node_id=node_id) |
| 142 |
if node_info["Status"]["State"] == "down": |
| 143 |
return True |
| 144 |
return False |
| 145 |
|
| 146 |
@t.overload |
| 147 |
def get_node_inspect( |
| 148 |
self, node_id: str | None = None, skip_missing: t.Literal[False] = False |
| 149 |
) -> dict[str, t.Any]: ... |
| 150 |
|
| 151 |
@t.overload |
| 152 |
def get_node_inspect( |
| 153 |
self, node_id: str | None = None, skip_missing: bool = False |
| 154 |
) -> dict[str, t.Any] | None: ... |
| 155 |
|
| 156 |
def get_node_inspect( |
| 157 |
self, node_id: str | None = None, skip_missing: bool = False |
| 158 |
) -> dict[str, t.Any] | None: |
| 159 |
""" |
| 160 |
Returns Swarm node info as in 'docker node inspect' command about single node |
| 161 |
|
| 162 |
:param skip_missing: if True then function will return None instead of failing the task |
| 163 |
:param node_id: node ID or name, if None then method will try to get node_id of host module run on |
| 164 |
:return: |
| 165 |
Single node information structure |
| 166 |
""" |
| 167 |
|
| 168 |
if node_id is None: |
| 169 |
node_id = self.get_swarm_node_id() |
| 170 |
|
| 171 |
if node_id is None: |
| 172 |
self.fail("Failed to get node information.") |
| 173 |
|
| 174 |
try: |
| 175 |
node_info = self.inspect_node(node_id=node_id) |
| 176 |
except APIError as exc: |
| 177 |
if exc.status_code == 503: |
| 178 |
self.fail( |
| 179 |
"Cannot inspect node: To inspect node execute module on Swarm Manager" |
| 180 |
) |
| 181 |
if exc.status_code == 404 and skip_missing: |
| 182 |
return None |
| 183 |
self.fail(f"Error while reading from Swarm manager: {exc}") |
| 184 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 185 |
self.fail(f"Error inspecting swarm node: {exc}") |
| 186 |
|
| 187 |
json_str = json.dumps(node_info, ensure_ascii=False) |
| 188 |
node_info = json.loads(json_str) |
| 189 |
|
| 190 |
if "ManagerStatus" in node_info and node_info["ManagerStatus"].get("Leader"): |
| 191 |
# This is workaround of bug in Docker when in some cases the Leader IP is 0.0.0.0 |
| 192 |
# Check moby/moby#35437 for details |
| 193 |
count_colons = node_info["ManagerStatus"]["Addr"].count(":") |
| 194 |
if count_colons == 1: |
| 195 |
swarm_leader_ip = ( |
| 196 |
node_info["ManagerStatus"]["Addr"].split(":", 1)[0] |
| 197 |
or node_info["Status"]["Addr"] |
| 198 |
) |
| 199 |
else: |
| 200 |
swarm_leader_ip = node_info["Status"]["Addr"] |
| 201 |
node_info["Status"]["Addr"] = swarm_leader_ip |
| 202 |
return node_info |
| 203 |
|
| 204 |
def get_all_nodes_inspect(self) -> list[dict[str, t.Any]]: |
| 205 |
""" |
| 206 |
Returns Swarm node info as in 'docker node inspect' command about all registered nodes |
| 207 |
|
| 208 |
:return: |
| 209 |
Structure with information about all nodes |
| 210 |
""" |
| 211 |
try: |
| 212 |
node_info = self.nodes() |
| 213 |
except APIError as exc: |
| 214 |
if exc.status_code == 503: |
| 215 |
self.fail( |
| 216 |
"Cannot inspect node: To inspect node execute module on Swarm Manager" |
| 217 |
) |
| 218 |
self.fail(f"Error while reading from Swarm manager: {exc}") |
| 219 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 220 |
self.fail(f"Error inspecting swarm node: {exc}") |
| 221 |
|
| 222 |
json_str = json.dumps(node_info, ensure_ascii=False) |
| 223 |
node_info = json.loads(json_str) |
| 224 |
return node_info |
| 225 |
|
| 226 |
@t.overload |
| 227 |
def get_all_nodes_list(self, output: t.Literal["short"] = "short") -> list[str]: ... |
| 228 |
|
| 229 |
@t.overload |
| 230 |
def get_all_nodes_list( |
| 231 |
self, output: t.Literal["long"] |
| 232 |
) -> list[dict[str, t.Any]]: ... |
| 233 |
|
| 234 |
def get_all_nodes_list( |
| 235 |
self, output: t.Literal["short", "long"] = "short" |
| 236 |
) -> list[str] | list[dict[str, t.Any]]: |
| 237 |
""" |
| 238 |
Returns list of nodes registered in Swarm |
| 239 |
|
| 240 |
:param output: Defines format of returned data |
| 241 |
:return: |
| 242 |
If 'output' is 'short' then return data is list of nodes hostnames registered in Swarm, |
| 243 |
if 'output' is 'long' then returns data is list of dict containing the attributes as in |
| 244 |
output of command 'docker node ls' |
| 245 |
""" |
| 246 |
nodes_inspect = self.get_all_nodes_inspect() |
| 247 |
|
| 248 |
if output == "short": |
| 249 |
nodes_list = [] |
| 250 |
for node in nodes_inspect: |
| 251 |
nodes_list.append(node["Description"]["Hostname"]) |
| 252 |
return nodes_list |
| 253 |
if output == "long": |
| 254 |
nodes_info_list = [] |
| 255 |
for node in nodes_inspect: |
| 256 |
node_property: dict[str, t.Any] = {} |
| 257 |
|
| 258 |
node_property["ID"] = node["ID"] |
| 259 |
node_property["Hostname"] = node["Description"]["Hostname"] |
| 260 |
node_property["Status"] = node["Status"]["State"] |
| 261 |
node_property["Availability"] = node["Spec"]["Availability"] |
| 262 |
if "ManagerStatus" in node: |
| 263 |
if node["ManagerStatus"]["Leader"] is True: |
| 264 |
node_property["Leader"] = True |
| 265 |
node_property["ManagerStatus"] = node["ManagerStatus"][ |
| 266 |
"Reachability" |
| 267 |
] |
| 268 |
node_property["EngineVersion"] = node["Description"]["Engine"][ |
| 269 |
"EngineVersion" |
| 270 |
] |
| 271 |
|
| 272 |
nodes_info_list.append(node_property) |
| 273 |
return nodes_info_list |
| 274 |
|
| 275 |
def get_node_name_by_id(self, nodeid: str) -> str: |
| 276 |
return self.get_node_inspect(nodeid)["Description"]["Hostname"] |
| 277 |
|
| 278 |
def get_unlock_key(self) -> dict[str, t.Any] | None: |
| 279 |
if self.docker_py_version < LooseVersion("2.7.0"): |
| 280 |
return None |
| 281 |
return super().get_unlock_key() |
| 282 |
|
| 283 |
def get_service_inspect( |
| 284 |
self, service_id: str, skip_missing: bool = False |
| 285 |
) -> dict[str, t.Any] | None: |
| 286 |
""" |
| 287 |
Returns Swarm service info as in 'docker service inspect' command about single service |
| 288 |
|
| 289 |
:param service_id: service ID or name |
| 290 |
:param skip_missing: if True then function will return None instead of failing the task |
| 291 |
:return: |
| 292 |
Single service information structure |
| 293 |
""" |
| 294 |
try: |
| 295 |
service_info = self.inspect_service(service_id) |
| 296 |
except NotFound as exc: |
| 297 |
if skip_missing is False: |
| 298 |
self.fail(f"Error while reading from Swarm manager: {exc}") |
| 299 |
else: |
| 300 |
return None |
| 301 |
except APIError as exc: |
| 302 |
if exc.status_code == 503: |
| 303 |
self.fail( |
| 304 |
"Cannot inspect service: To inspect service execute module on Swarm Manager" |
| 305 |
) |
| 306 |
self.fail(f"Error inspecting swarm service: {exc}") |
| 307 |
except Exception as exc: # pylint: disable=broad-exception-caught |
| 308 |
self.fail(f"Error inspecting swarm service: {exc}") |
| 309 |
|
| 310 |
json_str = json.dumps(service_info, ensure_ascii=False) |
| 311 |
service_info = json.loads(json_str) |
| 312 |
return service_info |