| 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-2025 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 json |
| 15 |
import os |
| 16 |
import typing as t |
| 17 |
from shutil import copyfile, rmtree |
| 18 |
|
| 19 |
from ..errors import ContextException |
| 20 |
from ..tls import TLSConfig |
| 21 |
from .config import ( |
| 22 |
get_context_host, |
| 23 |
get_meta_dir, |
| 24 |
get_meta_file, |
| 25 |
get_tls_dir, |
| 26 |
) |
| 27 |
|
| 28 |
IN_MEMORY = "IN MEMORY" |
| 29 |
|
| 30 |
|
| 31 |
class Context: |
| 32 |
"""A context.""" |
| 33 |
|
| 34 |
def __init__( |
| 35 |
self, |
| 36 |
name: str, |
| 37 |
orchestrator: str | None = None, |
| 38 |
host: str | None = None, |
| 39 |
endpoints: dict[str, dict[str, t.Any]] | None = None, |
| 40 |
skip_tls_verify: bool = False, |
| 41 |
tls: bool = False, |
| 42 |
description: str | None = None, |
| 43 |
) -> None: |
| 44 |
if not name: |
| 45 |
raise ValueError("Name not provided") |
| 46 |
self.name = name |
| 47 |
self.context_type = None |
| 48 |
self.orchestrator = orchestrator |
| 49 |
self.endpoints = {} |
| 50 |
self.tls_cfg: dict[str, TLSConfig] = {} |
| 51 |
self.meta_path = IN_MEMORY |
| 52 |
self.tls_path = IN_MEMORY |
| 53 |
self.description = description |
| 54 |
|
| 55 |
if not endpoints: |
| 56 |
# set default docker endpoint if no endpoint is set |
| 57 |
default_endpoint = ( |
| 58 |
"docker" |
| 59 |
if (not orchestrator or orchestrator == "swarm") |
| 60 |
else orchestrator |
| 61 |
) |
| 62 |
|
| 63 |
self.endpoints = { |
| 64 |
default_endpoint: { |
| 65 |
"Host": get_context_host(host, skip_tls_verify or tls), |
| 66 |
"SkipTLSVerify": skip_tls_verify, |
| 67 |
} |
| 68 |
} |
| 69 |
return |
| 70 |
|
| 71 |
# check docker endpoints |
| 72 |
for k, v in endpoints.items(): |
| 73 |
if not isinstance(v, dict): |
| 74 |
# unknown format |
| 75 |
raise ContextException( |
| 76 |
f"Unknown endpoint format for context {name}: {v}", |
| 77 |
) |
| 78 |
|
| 79 |
self.endpoints[k] = v |
| 80 |
if k != "docker": |
| 81 |
continue |
| 82 |
|
| 83 |
self.endpoints[k]["Host"] = v.get( |
| 84 |
"Host", get_context_host(host, skip_tls_verify or tls) |
| 85 |
) |
| 86 |
self.endpoints[k]["SkipTLSVerify"] = bool( |
| 87 |
v.get("SkipTLSVerify", skip_tls_verify) |
| 88 |
) |
| 89 |
|
| 90 |
def set_endpoint( |
| 91 |
self, |
| 92 |
name: str = "docker", |
| 93 |
host: str | None = None, |
| 94 |
tls_cfg: TLSConfig | None = None, |
| 95 |
skip_tls_verify: bool = False, |
| 96 |
def_namespace: str | None = None, |
| 97 |
) -> None: |
| 98 |
self.endpoints[name] = { |
| 99 |
"Host": get_context_host(host, not skip_tls_verify or tls_cfg is not None), |
| 100 |
"SkipTLSVerify": skip_tls_verify, |
| 101 |
} |
| 102 |
if def_namespace: |
| 103 |
self.endpoints[name]["DefaultNamespace"] = def_namespace |
| 104 |
|
| 105 |
if tls_cfg: |
| 106 |
self.tls_cfg[name] = tls_cfg |
| 107 |
|
| 108 |
def inspect(self) -> dict[str, t.Any]: |
| 109 |
return self() |
| 110 |
|
| 111 |
@classmethod |
| 112 |
def load_context(cls, name: str) -> t.Self | None: |
| 113 |
meta = Context._load_meta(name) |
| 114 |
if meta: |
| 115 |
instance = cls( |
| 116 |
meta["Name"], |
| 117 |
orchestrator=meta["Metadata"].get("StackOrchestrator", None), |
| 118 |
endpoints=meta.get("Endpoints", None), |
| 119 |
description=meta["Metadata"].get("Description"), |
| 120 |
) |
| 121 |
instance.context_type = meta["Metadata"].get("Type", None) |
| 122 |
instance._load_certs() |
| 123 |
instance.meta_path = get_meta_dir(name) |
| 124 |
return instance |
| 125 |
return None |
| 126 |
|
| 127 |
@classmethod |
| 128 |
def _load_meta(cls, name: str) -> dict[str, t.Any] | None: |
| 129 |
meta_file = get_meta_file(name) |
| 130 |
if not os.path.isfile(meta_file): |
| 131 |
return None |
| 132 |
|
| 133 |
metadata: dict[str, t.Any] = {} |
| 134 |
try: |
| 135 |
with open(meta_file, "rt", encoding="utf-8") as f: |
| 136 |
metadata = json.load(f) |
| 137 |
except (OSError, KeyError, ValueError) as e: |
| 138 |
# unknown format |
| 139 |
raise RuntimeError( |
| 140 |
f"Detected corrupted meta file for context {name} : {e}" |
| 141 |
) from e |
| 142 |
|
| 143 |
# for docker endpoints, set defaults for |
| 144 |
# Host and SkipTLSVerify fields |
| 145 |
for k, v in metadata["Endpoints"].items(): |
| 146 |
if k != "docker": |
| 147 |
continue |
| 148 |
metadata["Endpoints"][k]["Host"] = v.get( |
| 149 |
"Host", get_context_host(None, False) |
| 150 |
) |
| 151 |
metadata["Endpoints"][k]["SkipTLSVerify"] = bool( |
| 152 |
v.get("SkipTLSVerify", True) |
| 153 |
) |
| 154 |
|
| 155 |
return metadata |
| 156 |
|
| 157 |
def _load_certs(self) -> None: |
| 158 |
certs = {} |
| 159 |
tls_dir = get_tls_dir(self.name) |
| 160 |
for endpoint in self.endpoints: |
| 161 |
if not os.path.isdir(os.path.join(tls_dir, endpoint)): |
| 162 |
continue |
| 163 |
ca_cert = None |
| 164 |
cert = None |
| 165 |
key = None |
| 166 |
for filename in os.listdir(os.path.join(tls_dir, endpoint)): |
| 167 |
if filename.startswith("ca"): |
| 168 |
ca_cert = os.path.join(tls_dir, endpoint, filename) |
| 169 |
elif filename.startswith("cert"): |
| 170 |
cert = os.path.join(tls_dir, endpoint, filename) |
| 171 |
elif filename.startswith("key"): |
| 172 |
key = os.path.join(tls_dir, endpoint, filename) |
| 173 |
if all([cert, key]) or ca_cert: |
| 174 |
verify = None |
| 175 |
if endpoint == "docker" and not self.endpoints["docker"].get( |
| 176 |
"SkipTLSVerify", False |
| 177 |
): |
| 178 |
verify = True |
| 179 |
certs[endpoint] = TLSConfig( |
| 180 |
client_cert=(cert, key) if cert and key else None, |
| 181 |
ca_cert=ca_cert, |
| 182 |
verify=verify, |
| 183 |
) |
| 184 |
self.tls_cfg = certs |
| 185 |
self.tls_path = tls_dir |
| 186 |
|
| 187 |
def save(self) -> None: |
| 188 |
meta_dir = get_meta_dir(self.name) |
| 189 |
if not os.path.isdir(meta_dir): |
| 190 |
os.makedirs(meta_dir) |
| 191 |
with open(get_meta_file(self.name), "wt", encoding="utf-8") as f: |
| 192 |
f.write(json.dumps(self.Metadata)) |
| 193 |
|
| 194 |
tls_dir = get_tls_dir(self.name) |
| 195 |
for endpoint, tls in self.tls_cfg.items(): |
| 196 |
if not os.path.isdir(os.path.join(tls_dir, endpoint)): |
| 197 |
os.makedirs(os.path.join(tls_dir, endpoint)) |
| 198 |
|
| 199 |
ca_file = tls.ca_cert |
| 200 |
if ca_file: |
| 201 |
copyfile( |
| 202 |
ca_file, os.path.join(tls_dir, endpoint, os.path.basename(ca_file)) |
| 203 |
) |
| 204 |
|
| 205 |
if tls.cert: |
| 206 |
cert_file, key_file = tls.cert |
| 207 |
copyfile( |
| 208 |
cert_file, |
| 209 |
os.path.join(tls_dir, endpoint, os.path.basename(cert_file)), |
| 210 |
) |
| 211 |
copyfile( |
| 212 |
key_file, |
| 213 |
os.path.join(tls_dir, endpoint, os.path.basename(key_file)), |
| 214 |
) |
| 215 |
|
| 216 |
self.meta_path = get_meta_dir(self.name) |
| 217 |
self.tls_path = get_tls_dir(self.name) |
| 218 |
|
| 219 |
def remove(self) -> None: |
| 220 |
if os.path.isdir(self.meta_path): |
| 221 |
rmtree(self.meta_path) |
| 222 |
if os.path.isdir(self.tls_path): |
| 223 |
rmtree(self.tls_path) |
| 224 |
|
| 225 |
def __repr__(self) -> str: |
| 226 |
return f"<{self.__class__.__name__}: '{self.name}'>" |
| 227 |
|
| 228 |
def __str__(self) -> str: |
| 229 |
return json.dumps(self.__call__(), indent=2) |
| 230 |
|
| 231 |
def __call__(self) -> dict[str, t.Any]: |
| 232 |
result = self.Metadata |
| 233 |
result.update(self.TLSMaterial) |
| 234 |
result.update(self.Storage) |
| 235 |
return result |
| 236 |
|
| 237 |
def is_docker_host(self) -> bool: |
| 238 |
return self.context_type is None |
| 239 |
|
| 240 |
@property |
| 241 |
def Name(self) -> str: # pylint: disable=invalid-name |
| 242 |
return self.name |
| 243 |
|
| 244 |
@property |
| 245 |
def Host(self) -> str | None: # pylint: disable=invalid-name |
| 246 |
if not self.orchestrator or self.orchestrator == "swarm": |
| 247 |
endpoint = self.endpoints.get("docker", None) |
| 248 |
if endpoint: |
| 249 |
return endpoint.get("Host", None) # type: ignore |
| 250 |
return None |
| 251 |
|
| 252 |
return self.endpoints[self.orchestrator].get("Host", None) # type: ignore |
| 253 |
|
| 254 |
@property |
| 255 |
def Orchestrator(self) -> str | None: # pylint: disable=invalid-name |
| 256 |
return self.orchestrator |
| 257 |
|
| 258 |
@property |
| 259 |
def Metadata(self) -> dict[str, t.Any]: # pylint: disable=invalid-name |
| 260 |
meta: dict[str, t.Any] = {} |
| 261 |
if self.orchestrator: |
| 262 |
meta = {"StackOrchestrator": self.orchestrator} |
| 263 |
return {"Name": self.name, "Metadata": meta, "Endpoints": self.endpoints} |
| 264 |
|
| 265 |
@property |
| 266 |
def TLSConfig(self) -> TLSConfig | None: # pylint: disable=invalid-name |
| 267 |
key = self.orchestrator |
| 268 |
if not key or key == "swarm": |
| 269 |
key = "docker" |
| 270 |
if key in self.tls_cfg: |
| 271 |
return self.tls_cfg[key] |
| 272 |
return None |
| 273 |
|
| 274 |
@property |
| 275 |
def TLSMaterial(self) -> dict[str, t.Any]: # pylint: disable=invalid-name |
| 276 |
certs: dict[str, t.Any] = {} |
| 277 |
for endpoint, tls in self.tls_cfg.items(): |
| 278 |
paths = [tls.ca_cert, *tls.cert] if tls.cert else [tls.ca_cert] |
| 279 |
certs[endpoint] = [ |
| 280 |
os.path.basename(path) if path else None for path in paths |
| 281 |
] |
| 282 |
return {"TLSMaterial": certs} |
| 283 |
|
| 284 |
@property |
| 285 |
def Storage(self) -> dict[str, t.Any]: # pylint: disable=invalid-name |
| 286 |
return {"Storage": {"MetadataPath": self.meta_path, "TLSPath": self.tls_path}} |