| 1 |
# This code is part of the Ansible collection community.docker, but is an independent component. |
| 2 |
# This particular file, and this file only, is based on the Docker SDK for Python (https://github.com/docker/docker-py/) |
| 3 |
# |
| 4 |
# Copyright (c) 2016-2022 Docker, Inc. |
| 5 |
# |
| 6 |
# It is licensed under the Apache 2.0 license (see LICENSES/Apache-2.0.txt in this collection) |
| 7 |
# SPDX-License-Identifier: Apache-2.0 |
| 8 |
|
| 9 |
# Note that this module util is **PRIVATE** to the collection. It can have breaking changes at any time. |
| 10 |
# Do not use this from other collections or standalone plugins/modules! |
| 11 |
|
| 12 |
from __future__ import annotations |
| 13 |
|
| 14 |
import base64 |
| 15 |
import collections |
| 16 |
import json |
| 17 |
import os |
| 18 |
import os.path |
| 19 |
import shlex |
| 20 |
import string |
| 21 |
import typing as t |
| 22 |
from urllib.parse import urlparse, urlunparse |
| 23 |
|
| 24 |
from ansible_collections.community.docker.plugins.module_utils._version import ( |
| 25 |
StrictVersion, |
| 26 |
) |
| 27 |
|
| 28 |
from .. import errors |
| 29 |
from ..constants import ( |
| 30 |
BYTE_UNITS, |
| 31 |
DEFAULT_HTTP_HOST, |
| 32 |
DEFAULT_NPIPE, |
| 33 |
DEFAULT_UNIX_SOCKET, |
| 34 |
) |
| 35 |
from ..tls import TLSConfig |
| 36 |
|
| 37 |
if t.TYPE_CHECKING: |
| 38 |
from collections.abc import Mapping, Sequence |
| 39 |
|
| 40 |
|
| 41 |
URLComponents = collections.namedtuple( |
| 42 |
"URLComponents", |
| 43 |
"scheme netloc url params query fragment", |
| 44 |
) |
| 45 |
|
| 46 |
|
| 47 |
def decode_json_header(header: str | bytes) -> dict[str, t.Any]: |
| 48 |
data = base64.b64decode(header).decode("utf-8") |
| 49 |
return json.loads(data) |
| 50 |
|
| 51 |
|
| 52 |
def compare_version(v1: str, v2: str) -> t.Literal[-1, 0, 1]: |
| 53 |
"""Compare docker versions |
| 54 |
|
| 55 |
>>> v1 = '1.9' |
| 56 |
>>> v2 = '1.10' |
| 57 |
>>> compare_version(v1, v2) |
| 58 |
1 |
| 59 |
>>> compare_version(v2, v1) |
| 60 |
-1 |
| 61 |
>>> compare_version(v2, v2) |
| 62 |
0 |
| 63 |
""" |
| 64 |
s1 = StrictVersion(v1) |
| 65 |
s2 = StrictVersion(v2) |
| 66 |
if s1 == s2: |
| 67 |
return 0 |
| 68 |
if s1 > s2: |
| 69 |
return -1 |
| 70 |
return 1 |
| 71 |
|
| 72 |
|
| 73 |
def version_lt(v1: str, v2: str) -> bool: |
| 74 |
return compare_version(v1, v2) > 0 |
| 75 |
|
| 76 |
|
| 77 |
def version_gte(v1: str, v2: str) -> bool: |
| 78 |
return not version_lt(v1, v2) |
| 79 |
|
| 80 |
|
| 81 |
def _convert_port_binding( |
| 82 |
binding: ( |
| 83 |
tuple[str, str | int | None] |
| 84 |
| tuple[str | int | None] |
| 85 |
| dict[str, str] |
| 86 |
| str |
| 87 |
| int |
| 88 |
), |
| 89 |
) -> dict[str, str]: |
| 90 |
result = {"HostIp": "", "HostPort": ""} |
| 91 |
host_port: str | int | None = "" |
| 92 |
if isinstance(binding, tuple): |
| 93 |
if len(binding) == 2: |
| 94 |
host_port = binding[1] # type: ignore |
| 95 |
result["HostIp"] = binding[0] |
| 96 |
elif isinstance(binding[0], str): |
| 97 |
result["HostIp"] = binding[0] |
| 98 |
else: |
| 99 |
host_port = binding[0] |
| 100 |
elif isinstance(binding, dict): |
| 101 |
if "HostPort" in binding: |
| 102 |
host_port = binding["HostPort"] |
| 103 |
if "HostIp" in binding: |
| 104 |
result["HostIp"] = binding["HostIp"] |
| 105 |
else: |
| 106 |
raise ValueError(binding) |
| 107 |
else: |
| 108 |
host_port = binding |
| 109 |
|
| 110 |
result["HostPort"] = str(host_port) if host_port is not None else "" |
| 111 |
return result |
| 112 |
|
| 113 |
|
| 114 |
def convert_port_bindings( |
| 115 |
port_bindings: dict[ |
| 116 |
str | int, |
| 117 |
tuple[str, str | int | None] |
| 118 |
| tuple[str | int | None] |
| 119 |
| dict[str, str] |
| 120 |
| str |
| 121 |
| int |
| 122 |
| list[ |
| 123 |
tuple[str, str | int | None] |
| 124 |
| tuple[str | int | None] |
| 125 |
| dict[str, str] |
| 126 |
| str |
| 127 |
| int |
| 128 |
], |
| 129 |
], |
| 130 |
) -> dict[str, list[dict[str, str]]]: |
| 131 |
result = {} |
| 132 |
for k, v in port_bindings.items(): |
| 133 |
key = str(k) |
| 134 |
if "/" not in key: |
| 135 |
key += "/tcp" |
| 136 |
if isinstance(v, list): |
| 137 |
result[key] = [_convert_port_binding(binding) for binding in v] |
| 138 |
else: |
| 139 |
result[key] = [_convert_port_binding(v)] |
| 140 |
return result |
| 141 |
|
| 142 |
|
| 143 |
def convert_volume_binds( |
| 144 |
binds: ( |
| 145 |
list[str] |
| 146 |
| Mapping[ |
| 147 |
str | bytes, dict[str, str | bytes] | dict[str, str] | bytes | str | int |
| 148 |
] |
| 149 |
), |
| 150 |
) -> list[str]: |
| 151 |
if isinstance(binds, list): |
| 152 |
return binds # type: ignore |
| 153 |
|
| 154 |
result = [] |
| 155 |
for k, v in binds.items(): |
| 156 |
if isinstance(k, bytes): |
| 157 |
k = k.decode("utf-8") |
| 158 |
|
| 159 |
if isinstance(v, dict): |
| 160 |
if "ro" in v and "mode" in v: |
| 161 |
raise ValueError(f'Binding cannot contain both "ro" and "mode": {v!r}') |
| 162 |
|
| 163 |
bind = v["bind"] |
| 164 |
if isinstance(bind, bytes): |
| 165 |
bind = bind.decode("utf-8") |
| 166 |
|
| 167 |
if "ro" in v: |
| 168 |
mode = "ro" if v["ro"] else "rw" |
| 169 |
elif "mode" in v: |
| 170 |
mode = v["mode"] # type: ignore # TODO |
| 171 |
else: |
| 172 |
mode = "rw" |
| 173 |
|
| 174 |
# NOTE: this is only relevant for Linux hosts |
| 175 |
# (does not apply in Docker Desktop) |
| 176 |
propagation_modes = [ |
| 177 |
"rshared", |
| 178 |
"shared", |
| 179 |
"rslave", |
| 180 |
"slave", |
| 181 |
"rprivate", |
| 182 |
"private", |
| 183 |
] |
| 184 |
if "propagation" in v and v["propagation"] in propagation_modes: |
| 185 |
if mode: |
| 186 |
mode = ",".join([mode, v["propagation"]]) # type: ignore # TODO |
| 187 |
else: |
| 188 |
mode = v["propagation"] # type: ignore # TODO |
| 189 |
|
| 190 |
result.append(f"{k}:{bind}:{mode}") |
| 191 |
else: |
| 192 |
if isinstance(v, bytes): |
| 193 |
v = v.decode("utf-8") |
| 194 |
result.append(f"{k}:{v}:rw") |
| 195 |
return result |
| 196 |
|
| 197 |
|
| 198 |
def convert_tmpfs_mounts(tmpfs: dict[str, str] | list[str]) -> dict[str, str]: |
| 199 |
if isinstance(tmpfs, dict): |
| 200 |
return tmpfs |
| 201 |
|
| 202 |
if not isinstance(tmpfs, list): |
| 203 |
raise ValueError( |
| 204 |
f"Expected tmpfs value to be either a list or a dict, found: {type(tmpfs).__name__}" |
| 205 |
) |
| 206 |
|
| 207 |
result = {} |
| 208 |
for mount in tmpfs: |
| 209 |
if isinstance(mount, str): |
| 210 |
if ":" in mount: |
| 211 |
name, options = mount.split(":", 1) |
| 212 |
else: |
| 213 |
name = mount |
| 214 |
options = "" |
| 215 |
|
| 216 |
else: |
| 217 |
raise ValueError( |
| 218 |
f"Expected item in tmpfs list to be a string, found: {type(mount).__name__}" |
| 219 |
) |
| 220 |
|
| 221 |
result[name] = options |
| 222 |
return result |
| 223 |
|
| 224 |
|
| 225 |
def convert_service_networks( |
| 226 |
networks: list[str | dict[str, str]], |
| 227 |
) -> list[dict[str, str]]: |
| 228 |
if not networks: |
| 229 |
return networks # type: ignore |
| 230 |
if not isinstance(networks, list): |
| 231 |
raise TypeError("networks parameter must be a list.") |
| 232 |
|
| 233 |
result = [] |
| 234 |
for n in networks: |
| 235 |
if isinstance(n, str): |
| 236 |
n = {"Target": n} |
| 237 |
result.append(n) |
| 238 |
return result |
| 239 |
|
| 240 |
|
| 241 |
def parse_repository_tag(repo_name: str) -> tuple[str, str | None]: |
| 242 |
parts = repo_name.rsplit("@", 1) |
| 243 |
if len(parts) == 2: |
| 244 |
return tuple(parts) # type: ignore |
| 245 |
parts = repo_name.rsplit(":", 1) |
| 246 |
if len(parts) == 2 and "/" not in parts[1]: |
| 247 |
return tuple(parts) # type: ignore |
| 248 |
return repo_name, None |
| 249 |
|
| 250 |
|
| 251 |
def parse_host(addr: str | None, is_win32: bool = False, tls: bool = False) -> str: |
| 252 |
# Sensible defaults |
| 253 |
if not addr and is_win32: |
| 254 |
return DEFAULT_NPIPE |
| 255 |
if not addr or addr.strip() == "unix://": |
| 256 |
return DEFAULT_UNIX_SOCKET |
| 257 |
|
| 258 |
addr = addr.strip() |
| 259 |
|
| 260 |
parsed_url = urlparse(addr) |
| 261 |
proto = parsed_url.scheme |
| 262 |
if not proto or any(x not in string.ascii_letters + "+" for x in proto): |
| 263 |
# https://bugs.python.org/issue754016 |
| 264 |
parsed_url = urlparse("//" + addr, "tcp") |
| 265 |
proto = "tcp" |
| 266 |
|
| 267 |
if proto == "fd": |
| 268 |
raise errors.DockerException("fd protocol is not implemented") |
| 269 |
|
| 270 |
# These protos are valid aliases for our library but not for the |
| 271 |
# official spec |
| 272 |
if proto in ("http", "https"): |
| 273 |
tls = proto == "https" |
| 274 |
proto = "tcp" |
| 275 |
elif proto == "http+unix": |
| 276 |
proto = "unix" |
| 277 |
|
| 278 |
if proto not in ("tcp", "unix", "npipe", "ssh"): |
| 279 |
raise errors.DockerException(f"Invalid bind address protocol: {addr}") |
| 280 |
|
| 281 |
if proto == "tcp" and not parsed_url.netloc: |
| 282 |
# "tcp://" is exceptionally disallowed by convention; |
| 283 |
# omitting a hostname for other protocols is fine |
| 284 |
raise errors.DockerException(f"Invalid bind address format: {addr}") |
| 285 |
|
| 286 |
if any( |
| 287 |
[parsed_url.params, parsed_url.query, parsed_url.fragment, parsed_url.password] |
| 288 |
): |
| 289 |
raise errors.DockerException(f"Invalid bind address format: {addr}") |
| 290 |
|
| 291 |
if parsed_url.path and proto == "ssh": |
| 292 |
raise errors.DockerException( |
| 293 |
f"Invalid bind address format: no path allowed for this protocol: {addr}" |
| 294 |
) |
| 295 |
path = parsed_url.path |
| 296 |
if proto == "unix" and parsed_url.hostname is not None: |
| 297 |
# For legacy reasons, we consider unix://path |
| 298 |
# to be valid and equivalent to unix:///path |
| 299 |
path = f"{parsed_url.hostname}/{path}" |
| 300 |
|
| 301 |
netloc = parsed_url.netloc |
| 302 |
if proto in ("tcp", "ssh"): |
| 303 |
port = parsed_url.port or 0 |
| 304 |
if port <= 0: |
| 305 |
port = 22 if proto == "ssh" else (2375 if tls else 2376) |
| 306 |
netloc = f"{parsed_url.netloc}:{port}" |
| 307 |
|
| 308 |
if not parsed_url.hostname: |
| 309 |
netloc = f"{DEFAULT_HTTP_HOST}:{port}" |
| 310 |
|
| 311 |
# Rewrite schemes to fit library internals (requests adapters) |
| 312 |
if proto == "tcp": |
| 313 |
proto = f"http{'s' if tls else ''}" |
| 314 |
elif proto == "unix": |
| 315 |
proto = "http+unix" |
| 316 |
|
| 317 |
if proto in ("http+unix", "npipe"): |
| 318 |
return f"{proto}://{path}".rstrip("/") |
| 319 |
return urlunparse( |
| 320 |
URLComponents( |
| 321 |
scheme=proto, |
| 322 |
netloc=netloc, |
| 323 |
url=path, |
| 324 |
params="", |
| 325 |
query="", |
| 326 |
fragment="", |
| 327 |
) |
| 328 |
).rstrip("/") |
| 329 |
|
| 330 |
|
| 331 |
def parse_devices(devices: Sequence[dict[str, str] | str]) -> list[dict[str, str]]: |
| 332 |
device_list = [] |
| 333 |
for device in devices: |
| 334 |
if isinstance(device, dict): |
| 335 |
device_list.append(device) |
| 336 |
continue |
| 337 |
if not isinstance(device, str): |
| 338 |
raise errors.DockerException(f"Invalid device type {type(device)}") |
| 339 |
device_mapping = device.split(":") |
| 340 |
if device_mapping: |
| 341 |
path_on_host = device_mapping[0] |
| 342 |
if len(device_mapping) > 1: |
| 343 |
path_in_container = device_mapping[1] |
| 344 |
else: |
| 345 |
path_in_container = path_on_host |
| 346 |
if len(device_mapping) > 2: |
| 347 |
permissions = device_mapping[2] |
| 348 |
else: |
| 349 |
permissions = "rwm" |
| 350 |
device_list.append( |
| 351 |
{ |
| 352 |
"PathOnHost": path_on_host, |
| 353 |
"PathInContainer": path_in_container, |
| 354 |
"CgroupPermissions": permissions, |
| 355 |
} |
| 356 |
) |
| 357 |
return device_list |
| 358 |
|
| 359 |
|
| 360 |
def kwargs_from_env( |
| 361 |
assert_hostname: bool | None = None, |
| 362 |
environment: Mapping[str, str] | None = None, |
| 363 |
) -> dict[str, t.Any]: |
| 364 |
if not environment: |
| 365 |
environment = os.environ |
| 366 |
host = environment.get("DOCKER_HOST") |
| 367 |
|
| 368 |
# empty string for cert path is the same as unset. |
| 369 |
cert_path = environment.get("DOCKER_CERT_PATH") or None |
| 370 |
|
| 371 |
# empty string for tls verify counts as "false". |
| 372 |
# Any value or 'unset' counts as true. |
| 373 |
tls_verify_str = environment.get("DOCKER_TLS_VERIFY") |
| 374 |
if tls_verify_str == "": |
| 375 |
tls_verify = False |
| 376 |
else: |
| 377 |
tls_verify = tls_verify_str is not None |
| 378 |
enable_tls = cert_path or tls_verify |
| 379 |
|
| 380 |
params: dict[str, t.Any] = {} |
| 381 |
|
| 382 |
if host: |
| 383 |
params["base_url"] = host |
| 384 |
|
| 385 |
if not enable_tls: |
| 386 |
return params |
| 387 |
|
| 388 |
if not cert_path: |
| 389 |
cert_path = os.path.join(os.path.expanduser("~"), ".docker") |
| 390 |
|
| 391 |
if not tls_verify and assert_hostname is None: |
| 392 |
# assert_hostname is a subset of TLS verification, |
| 393 |
# so if it is not set already then set it to false. |
| 394 |
assert_hostname = False |
| 395 |
|
| 396 |
params["tls"] = TLSConfig( |
| 397 |
client_cert=( |
| 398 |
os.path.join(cert_path, "cert.pem"), |
| 399 |
os.path.join(cert_path, "key.pem"), |
| 400 |
), |
| 401 |
ca_cert=os.path.join(cert_path, "ca.pem"), |
| 402 |
verify=tls_verify, |
| 403 |
assert_hostname=assert_hostname, |
| 404 |
) |
| 405 |
|
| 406 |
return params |
| 407 |
|
| 408 |
|
| 409 |
def convert_filters( |
| 410 |
filters: Mapping[str, bool | str | int | list[int] | list[str] | list[str | int]], |
| 411 |
) -> str: |
| 412 |
result = {} |
| 413 |
for k, v in filters.items(): |
| 414 |
if isinstance(v, bool): |
| 415 |
v = "true" if v else "false" |
| 416 |
if not isinstance(v, list): |
| 417 |
v = [ |
| 418 |
v, |
| 419 |
] |
| 420 |
result[k] = [str(item) if not isinstance(item, str) else item for item in v] |
| 421 |
return json.dumps(result) |
| 422 |
|
| 423 |
|
| 424 |
def parse_bytes(s: int | float | str) -> int | float: |
| 425 |
if isinstance(s, (int, float)): |
| 426 |
return s |
| 427 |
if len(s) == 0: |
| 428 |
return 0 |
| 429 |
|
| 430 |
if s[-2:-1].isalpha() and s[-1].isalpha() and (s[-1] == "b" or s[-1] == "B"): |
| 431 |
s = s[:-1] |
| 432 |
units = BYTE_UNITS |
| 433 |
suffix = s[-1].lower() |
| 434 |
|
| 435 |
# Check if the variable is a string representation of an int |
| 436 |
# without a units part. Assuming that the units are bytes. |
| 437 |
if suffix.isdigit(): |
| 438 |
digits_part = s |
| 439 |
suffix = "b" |
| 440 |
else: |
| 441 |
digits_part = s[:-1] |
| 442 |
|
| 443 |
if suffix in units or suffix.isdigit(): |
| 444 |
try: |
| 445 |
digits = float(digits_part) |
| 446 |
except ValueError as exc: |
| 447 |
raise errors.DockerException( |
| 448 |
f"Failed converting the string value for memory ({digits_part}) to an integer." |
| 449 |
) from exc |
| 450 |
|
| 451 |
# Reconvert to long for the final result |
| 452 |
s = int(digits * units[suffix]) |
| 453 |
else: |
| 454 |
raise errors.DockerException( |
| 455 |
f"The specified value for memory ({s}) should specify the units. The postfix should be one of the `b` `k` `m` `g` characters" |
| 456 |
) |
| 457 |
|
| 458 |
return s |
| 459 |
|
| 460 |
|
| 461 |
def normalize_links(links: dict[str, str] | Sequence[tuple[str, str]]) -> list[str]: |
| 462 |
if isinstance(links, dict): |
| 463 |
sorted_links = sorted(links.items()) |
| 464 |
else: |
| 465 |
sorted_links = sorted(links) |
| 466 |
|
| 467 |
return [f"{k}:{v}" if v else k for k, v in sorted_links] |
| 468 |
|
| 469 |
|
| 470 |
def parse_env_file(env_file: str | os.PathLike) -> dict[str, str]: |
| 471 |
""" |
| 472 |
Reads a line-separated environment file. |
| 473 |
The format of each line should be "key=value". |
| 474 |
""" |
| 475 |
environment = {} |
| 476 |
|
| 477 |
with open(env_file, "rt", encoding="utf-8") as f: |
| 478 |
for line in f: |
| 479 |
if line[0] == "#": |
| 480 |
continue |
| 481 |
|
| 482 |
line = line.strip() |
| 483 |
if not line: |
| 484 |
continue |
| 485 |
|
| 486 |
parse_line = line.split("=", 1) |
| 487 |
if len(parse_line) == 2: |
| 488 |
k, v = parse_line |
| 489 |
environment[k] = v |
| 490 |
else: |
| 491 |
raise errors.DockerException( |
| 492 |
f"Invalid line in environment file {env_file}:\n{line}" |
| 493 |
) |
| 494 |
|
| 495 |
return environment |
| 496 |
|
| 497 |
|
| 498 |
def split_command(command: str) -> list[str]: |
| 499 |
return shlex.split(command) |
| 500 |
|
| 501 |
|
| 502 |
def format_environment(environment: Mapping[str, str | bytes | None]) -> list[str]: |
| 503 |
def format_env(key: str, value: str | bytes | None) -> str: |
| 504 |
if value is None: |
| 505 |
return key |
| 506 |
if isinstance(value, bytes): |
| 507 |
value = value.decode("utf-8") |
| 508 |
|
| 509 |
return f"{key}={value}" |
| 510 |
|
| 511 |
return [format_env(*var) for var in environment.items()] |
| 512 |
|
| 513 |
|
| 514 |
def format_extra_hosts(extra_hosts: Mapping[str, str], task: bool = False) -> list[str]: |
| 515 |
# Use format dictated by Swarm API if container is part of a task |
| 516 |
if task: |
| 517 |
return [f"{v} {k}" for k, v in sorted(extra_hosts.items())] |
| 518 |
|
| 519 |
return [f"{k}:{v}" for k, v in sorted(extra_hosts.items())] |