qodalis-cli-server-plugin-docker 1.0.0b39__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2007 @@
1
+ """All the logic of the Docker plugin: hosts, the hide / protect / read-only rules, container references and the shapes
2
+ of the contract. The REST routes, the terminal commands, the exec socket and the MCP tools all call it, so the rules
3
+ hold for each of them."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ import codecs
9
+ import json
10
+ import logging
11
+ import math
12
+ import os
13
+ import re
14
+ import stat
15
+ import time
16
+ import uuid
17
+ from dataclasses import dataclass
18
+ from datetime import datetime, timezone
19
+ from typing import Any, Awaitable, Callable, Optional, Union
20
+
21
+ from . import compose as cmp
22
+ from .engine import DockerError, DockerHostConfig, EngineClient, EngineUpgrade, assert_path_name, encode_component
23
+ from .settings import DockerSettings
24
+ from qodalis_cli_server_abstractions import split_shell_words
25
+ from .shapes import (
26
+ BUILTIN_NETWORKS,
27
+ COMPOSE_CONFIG_FILES,
28
+ COMPOSE_PROJECT,
29
+ COMPOSE_WORKING_DIR,
30
+ container_name,
31
+ format_seconds,
32
+ MAX_LOG_LINE,
33
+ iso_seconds,
34
+ js_str,
35
+ map_container,
36
+ map_detail,
37
+ map_stats,
38
+ matches_pattern,
39
+ normalize_image_ref,
40
+ number_of,
41
+ parse_logs,
42
+ parse_time,
43
+ short_id,
44
+ text_of,
45
+ )
46
+
47
+ HOST_NAME_PATTERN = re.compile(r"^[a-z0-9][a-z0-9-]{0,31}$")
48
+ LOCAL_HOST = "local"
49
+ OPERATION_EVENT = "docker:operation"
50
+ DEFAULT_SHELL = ["/bin/sh", "-c", "command -v bash >/dev/null 2>&1 && exec bash || exec sh"]
51
+ MAX_OPERATIONS = 50
52
+ EXEC_OUTPUT_CAP = 1024 * 1024
53
+ COMPOSE_FILE_CAP = cmp.COMPOSE_FILE_CAP
54
+ read_compose_file = cmp.read_compose_file
55
+ COMPOSE_NOT_FOUND = "the docker compose CLI was not found on this server"
56
+ COMPOSE_NO_ROOTS = "no composeRoots are set"
57
+ COMPOSE_DOWN_SECONDS = 120
58
+ COMPOSE_CONFIG_SECONDS = 60
59
+ COMPOSE_CHECK_CACHE_SECONDS = 60
60
+ MAX_COMPOSE_PROCESSES = 5
61
+ CONTAINER_ACTIONS = ("start", "stop", "restart", "kill", "pause", "unpause")
62
+ _RESOURCE_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,254}$")
63
+
64
+ logger = logging.getLogger("qcli.plugin.docker")
65
+
66
+
67
+
68
+
69
+
70
+ @dataclass
71
+ class DockerCaller:
72
+ """Who asks: the audit log and the operations say who did it; ``signed_in`` feeds the sign-in rule."""
73
+
74
+ name: Optional[str] = None
75
+ signed_in: bool = False
76
+ #: Holds ``docker:admin``; set explicitly (a server without sign-in, ``allowUnprotected``, sets it true).
77
+ admin: bool = False
78
+
79
+
80
+ # a plain string is the name of a signed-in user
81
+ Caller = Union[DockerCaller, str, None]
82
+ UNPROTECTED_TEXT = "the Docker plugin needs a protected server (sign-in); see its allowUnprotected setting"
83
+ MAX_RUNNING_OPERATIONS = 5
84
+ MAX_STATS_IDS = 100
85
+ STATS_AT_A_TIME = 10
86
+
87
+
88
+ def as_caller(caller: Caller) -> DockerCaller:
89
+ if isinstance(caller, DockerCaller):
90
+ return caller
91
+ if isinstance(caller, str) and caller:
92
+ return DockerCaller(name=caller, signed_in=True)
93
+ return DockerCaller()
94
+
95
+ AuditFn = Callable[[dict[str, Any]], Awaitable[None]]
96
+ PublishFn = Callable[[str, dict[str, Any], str], Awaitable[None]]
97
+
98
+
99
+ def _message(err: BaseException) -> str:
100
+ if isinstance(err, DockerError):
101
+ return err.message
102
+ return str(err) or type(err).__name__
103
+
104
+
105
+ def _sorted(items: list[Any], key: Callable[[Any], str]) -> list[Any]:
106
+ return sorted(items, key=key)
107
+
108
+
109
+ read_compose_file = cmp.read_compose_file
110
+
111
+
112
+ class HostContext:
113
+ def __init__(self, name: str, client: EngineClient) -> None:
114
+ self.name = name
115
+ self.client = client
116
+
117
+
118
+ class OperationRecord:
119
+ def __init__(self, op: dict[str, Any]) -> None:
120
+ self.op = op
121
+ self.done: "asyncio.Future[None]" = asyncio.get_running_loop().create_future()
122
+ self.last_progress_event = 0.0
123
+ self.task: Optional["asyncio.Task[None]"] = None
124
+ #: ``<host>/<stack>`` of a running ``stack-up``: one per stack.
125
+ self.key: Optional[str] = None
126
+
127
+
128
+ class DockerService:
129
+ """The Docker plugin's service."""
130
+
131
+ def __init__(
132
+ self, settings: Callable[[], DockerSettings], *, audit: Optional[AuditFn] = None, publish: Optional[PublishFn] = None,
133
+ log: Optional[logging.Logger] = None, now: Optional[Callable[[], datetime]] = None,
134
+ new_id: Optional[Callable[[], str]] = None, stats_gap_seconds: Optional[float] = None,
135
+ pull_silence_seconds: Optional[float] = None, compose_timeout_seconds: Optional[float] = None,
136
+ compose_down_timeout_seconds: Optional[float] = None,
137
+ ) -> None:
138
+ self._settings = settings
139
+ self._audit = audit
140
+ self._publish = publish
141
+ self._log = log or logger
142
+ self._now = now or (lambda: datetime.now(timezone.utc))
143
+ self._new_id = new_id or (lambda: str(uuid.uuid4()))
144
+ self._stats_gap = 1.0 if stats_gap_seconds is None else stats_gap_seconds
145
+ self._pull_silence = 120.0 if pull_silence_seconds is None else pull_silence_seconds
146
+ self._clients: dict[str, tuple[Any, EngineClient]] = {}
147
+ self._operations: list[OperationRecord] = []
148
+ self._warned: set[str] = set()
149
+ self._tasks: set["asyncio.Task[Any]"] = set()
150
+ self._compose_timeout = compose_timeout_seconds
151
+ self._compose_down_timeout = compose_down_timeout_seconds
152
+ #: The compose processes that run now (killed when the service stops).
153
+ self._compose_processes: set[Any] = set()
154
+ self._compose_gate: Optional["asyncio.Semaphore"] = None
155
+ self._compose_checks: dict[str, dict[str, Any]] = {}
156
+ self._compose_checking: dict[str, "asyncio.Future[None]"] = {}
157
+ #: ``<host>/<stack>`` of the compose changes that run now (an ``up`` blocks the others on the same stack).
158
+ self._busy_stacks: set[str] = set()
159
+
160
+ # -- basics -----------------------------------------------------------------------------------------------------
161
+
162
+ @property
163
+ def clock(self) -> datetime:
164
+ """The service's clock (tests fix it)."""
165
+ return self._now()
166
+
167
+ @property
168
+ def settings(self) -> DockerSettings:
169
+ return self._settings()
170
+
171
+ @property
172
+ def read_only(self) -> bool:
173
+ return self.settings.read_only is True
174
+
175
+ def _iso(self) -> str:
176
+ return format_seconds(self._now().timestamp())
177
+
178
+ # -- hosts ------------------------------------------------------------------------------------------------------
179
+
180
+ def _warn_once(self, key: str, text: str) -> None:
181
+ if key in self._warned:
182
+ return
183
+ self._warned.add(key)
184
+ self._log.warning(text)
185
+
186
+ def host_configs(self) -> dict[str, DockerHostConfig]:
187
+ """The configured hosts by name: ``local`` (the default) first, then the valid entries of ``hosts``."""
188
+ settings = self.settings
189
+ result: dict[str, DockerHostConfig] = {}
190
+ if (settings.endpoint or "").strip():
191
+ result[LOCAL_HOST] = settings.host_config()
192
+ extra = settings.hosts if isinstance(settings.hosts, dict) else {}
193
+ for name in sorted(extra):
194
+ entry = extra[name]
195
+ if not HOST_NAME_PATTERN.match(name) or name == LOCAL_HOST:
196
+ self._warn_once(f"name:{name}", f'docker: ignoring the host "{name}": invalid or reserved name')
197
+ continue
198
+ if not isinstance(entry, dict) or not isinstance(entry.get("endpoint"), str) or not entry["endpoint"].strip():
199
+ self._warn_once(f"entry:{name}", f'docker: ignoring the host "{name}": it needs an endpoint')
200
+ continue
201
+ result[name] = DockerHostConfig(
202
+ endpoint=entry["endpoint"].strip(), tls_ca=entry.get("tlsCa") or None, tls_cert=entry.get("tlsCert") or None,
203
+ tls_key=entry.get("tlsKey") or None, tls_verify=entry.get("tlsVerify") is not False,
204
+ )
205
+ return result
206
+
207
+ def _client(self, name: str, config: DockerHostConfig) -> Optional[EngineClient]:
208
+ timeout = min(120.0, max(1.0, float(self.settings.timeout_seconds or 15)))
209
+ key = (config.key(), timeout)
210
+ cached = self._clients.get(name)
211
+ if cached and cached[0] == key:
212
+ return cached[1]
213
+ try:
214
+ client = EngineClient(name, config, timeout)
215
+ except ValueError as err:
216
+ self._warn_once(f"endpoint:{name}:{key}", f'docker: ignoring the host "{name}": {err}')
217
+ return None
218
+ self._clients[name] = (key, client)
219
+ return client
220
+
221
+ def host(self, name: Optional[str] = None) -> HostContext:
222
+ """The host called ``name`` (default ``local``); 404 when unknown."""
223
+ wanted = name.strip() if name and name.strip() else LOCAL_HOST
224
+ config = self.host_configs().get(wanted)
225
+ client = self._client(wanted, config) if config else None
226
+ if client is None:
227
+ raise DockerError(404, f"unknown Docker host: {wanted}")
228
+ return HostContext(wanted, client)
229
+
230
+ async def hosts(self) -> dict[str, Any]:
231
+ """Every host, probed with a 3 s timeout in parallel."""
232
+
233
+ async def probe(name: str, config: DockerHostConfig) -> dict[str, Any]:
234
+ client = self._client(name, config)
235
+ base: dict[str, Any] = {"name": name, "endpoint": client.display if client else "", "default": name == LOCAL_HOST}
236
+ if client is None:
237
+ return {**base, "reachable": False, "error": "invalid endpoint"}
238
+ try:
239
+ version, containers = await asyncio.gather(
240
+ client.json("GET", "/version", timeout=3),
241
+ client.json("GET", "/containers/json", query={"all": 1}, timeout=3),
242
+ )
243
+ visible = self._visible(containers or [])
244
+ return {
245
+ **base, "reachable": True, "version": text_of((version or {}).get("Version")),
246
+ "containers": len(visible), "running": len([c for c in visible if c.get("State") == "running"]),
247
+ }
248
+ except Exception as err: # noqa: BLE001 - an unreachable host is an answer
249
+ return {**base, "reachable": False, "error": _message(err)}
250
+
251
+ entries = list(self.host_configs().items())
252
+ hosts = await asyncio.gather(*(probe(name, config) for name, config in entries))
253
+ return {"hosts": list(hosts), "readOnly": self.read_only}
254
+
255
+ # -- rules ------------------------------------------------------------------------------------------------------
256
+
257
+ @staticmethod
258
+ def _matches_any(patterns: Optional[list[str]], name: str, labels: dict[str, str]) -> bool:
259
+ return any(isinstance(p, str) and matches_pattern(p, name, labels) for p in (patterns or []))
260
+
261
+ def is_hidden(self, name: str, labels: dict[str, str]) -> bool:
262
+ return self._matches_any(self.settings.hide, name, labels)
263
+
264
+ def is_protected(self, name: str, labels: dict[str, str]) -> bool:
265
+ return self._matches_any(self.settings.protect, name, labels)
266
+
267
+ def _visible(self, raw: list[dict[str, Any]]) -> list[dict[str, Any]]:
268
+ return [c for c in raw if not self.is_hidden(container_name(c), c.get("Labels") or {})]
269
+
270
+ def _map(self, raw: dict[str, Any]) -> dict[str, Any]:
271
+ return map_container(raw, self.is_protected(container_name(raw), raw.get("Labels") or {}))
272
+
273
+ def assert_caller(self, caller: Caller) -> None:
274
+ """The sign-in rule: the socket is root-equivalent, so unless ``allowUnprotected`` is on a call without a
275
+ signed-in caller (a server that is not protected) is refused: 403 with :data:`UNPROTECTED_TEXT`. Every entry
276
+ (routes, commands, the socket, MCP tools) calls it once per call."""
277
+ if self.settings.allow_unprotected is True or as_caller(caller).signed_in:
278
+ return
279
+ raise DockerError(403, UNPROTECTED_TEXT)
280
+
281
+ CROSS_SITE_TEXT = "cross-site requests are refused"
282
+
283
+ @staticmethod
284
+ def is_cross_site(origin: Optional[str], host: Optional[str]) -> bool:
285
+ """Whether an ``Origin`` header names another site than the request's own ``Host`` (host:port). An absent origin
286
+ passes; one that cannot be parsed (``null``) counts as cross-site."""
287
+ if origin is None:
288
+ return False
289
+ from urllib.parse import urlsplit
290
+
291
+ try:
292
+ netloc = urlsplit(origin).netloc
293
+ except ValueError:
294
+ return True
295
+ return not netloc or not host or netloc.lower() != host.strip().lower()
296
+
297
+ def assert_same_site(self, caller: Caller, origin: Optional[str], host: Optional[str]) -> None:
298
+ """With ``allowUnprotected``, a change by a caller without a principal that carries a foreign ``Origin`` is refused
299
+ (403 ``cross-site requests are refused``): a page of another site cannot drive the plugin."""
300
+ if not as_caller(caller).signed_in and self.settings.allow_unprotected is True and self.is_cross_site(origin, host):
301
+ raise DockerError(403, self.CROSS_SITE_TEXT)
302
+
303
+ def assert_writable(self) -> None:
304
+ """403 while read-only."""
305
+ if self.read_only:
306
+ raise DockerError(403, "the Docker plugin is read-only")
307
+
308
+ @staticmethod
309
+ def _assert_not_protected(container: dict[str, Any]) -> None:
310
+ if container["protected"]:
311
+ raise DockerError(409, f"container {container['name']} is protected")
312
+
313
+ # -- audit ------------------------------------------------------------------------------------------------------
314
+
315
+ async def _audited(
316
+ self, caller: Caller, host: str, event: str, kind: str, name: str, details: str, properties: dict[str, Any],
317
+ run: Callable[[], Awaitable[Any]], extra: Optional[Callable[[Any], dict[str, Any]]] = None,
318
+ ) -> Any:
319
+ """Runs a change and records it: the entry on success, with ``properties.error`` on failure (the error re-raised)."""
320
+
321
+ async def record(props: dict[str, Any], text: str) -> None:
322
+ if self._audit is None:
323
+ return
324
+ user = as_caller(caller).name or "anonymous"
325
+ try:
326
+ await self._audit({
327
+ "event": event, "username": user, "actor": user, "target": f"docker:{host}/{kind}/{name}",
328
+ "details": text, "properties": {"host": host, **props},
329
+ })
330
+ except Exception as err: # noqa: BLE001 - the audit log is best effort
331
+ self._log.warning("docker: audit failed: %s", _message(err))
332
+
333
+ try:
334
+ result = await run()
335
+ except asyncio.CancelledError:
336
+ raise
337
+ except Exception as err:
338
+ shown = getattr(err, "audit_message", None) or _message(err)
339
+ await record({**properties, "error": shown}, f"{details} (failed: {shown})")
340
+ raise
341
+ await record({**properties, **(extra(result) if extra else {})}, details)
342
+ return result
343
+
344
+ async def _refusing(
345
+ self, caller: Caller, host: Optional[str], event: str, kind: str, name: str, details: str, properties: dict[str, Any],
346
+ check: Callable[[], None],
347
+ ) -> None:
348
+ """Runs a rule check of a change (read-only, protected); a refusal is recorded like any failed change
349
+ (``properties.error``)."""
350
+ try:
351
+ check()
352
+ except DockerError as err:
353
+ failure = err
354
+
355
+ async def fail() -> None:
356
+ raise failure
357
+
358
+ try:
359
+ await self._audited(caller, (host or "").strip() or LOCAL_HOST, event, kind, name, details, properties, fail)
360
+ except DockerError:
361
+ pass
362
+ raise
363
+
364
+ # -- containers -------------------------------------------------------------------------------------------------
365
+
366
+ async def _all_raw_containers(self, h: HostContext, all_: bool = True, size: bool = False) -> list[dict[str, Any]]:
367
+ return (await h.client.json("GET", "/containers/json", query={"all": 1 if all_ else 0, "size": 1 if size else None})) or []
368
+
369
+ async def _raw_containers(self, h: HostContext, all_: bool = True, size: bool = False) -> list[dict[str, Any]]:
370
+ """The engine's raw container items without the hidden ones."""
371
+ return self._visible(await self._all_raw_containers(h, all_, size))
372
+
373
+ async def _hidden_ids(self, h: HostContext) -> set[str]:
374
+ """The ids of the hidden containers (their events name them in their attributes)."""
375
+ listing = await self._all_raw_containers(h)
376
+ return {str(c.get("Id")) for c in listing if self.is_hidden(container_name(c), c.get("Labels") or {})}
377
+
378
+ def _is_hidden_event(self, e: dict[str, Any], hidden: set[str]) -> bool:
379
+ """Whether an event concerns a hidden container: a container event by its name and labels, any other by
380
+ ``attributes.container``."""
381
+ if e["type"] == "container":
382
+ return self.is_hidden(e["name"], e["attributes"]) or e["id"] in hidden
383
+ container = e["attributes"].get("container")
384
+ return container is not None and container in hidden
385
+
386
+ async def list_containers(self, host_name: Optional[str] = None, *, all: Optional[bool] = None, stack: Optional[str] = None) -> dict[str, Any]: # noqa: A002
387
+ h = self.host(host_name)
388
+ containers = [self._map(c) for c in await self._raw_containers(h, all is not False)]
389
+ if stack:
390
+ containers = [c for c in containers if c["stack"] == stack]
391
+ return {"host": h.name, "containers": _sorted(containers, lambda c: c["name"])}
392
+
393
+ async def _resolve(self, h: HostContext, ref: Any) -> dict[str, Any]:
394
+ """The visible container a reference (full id, id prefix of 3+ characters, or name) names; 404 / 400."""
395
+ return self._resolve_in(await self._raw_containers(h), ref)
396
+
397
+ @staticmethod
398
+ def _resolve_in(listing: list[dict[str, Any]], ref: Any) -> dict[str, Any]:
399
+ """:meth:`_resolve` against a container list already fetched."""
400
+ wanted = str(ref if ref is not None else "").strip()
401
+ if not wanted:
402
+ raise DockerError(400, "a container is required")
403
+ exact = [c for c in listing if c.get("Id") == wanted or container_name(c) == wanted]
404
+ if len(exact) == 1:
405
+ return exact[0]
406
+ if len(exact) > 1:
407
+ raise DockerError(400, f"more than one container matches {wanted}")
408
+ if len(wanted) >= 3 and re.match(r"^[0-9a-f]+$", wanted, re.IGNORECASE):
409
+ lower = wanted.lower()
410
+ by_prefix = [c for c in listing if str(c.get("Id")).startswith(lower)]
411
+ if len(by_prefix) == 1:
412
+ return by_prefix[0]
413
+ if len(by_prefix) > 1:
414
+ raise DockerError(400, f"more than one container matches {wanted}")
415
+ raise DockerError(404, f"no such container: {wanted}")
416
+
417
+ async def get_container(self, host_name: Optional[str], ref: str) -> dict[str, Any]:
418
+ h = self.host(host_name)
419
+ raw = await self._resolve(h, ref)
420
+ inspect = await h.client.json("GET", f"/containers/{raw['Id']}/json")
421
+ return {"host": h.name, "container": map_detail(self._map(raw), inspect or {})}
422
+
423
+ @staticmethod
424
+ def _since_seconds(since: Optional[str]) -> Optional[float]:
425
+ if since is None or since == "":
426
+ return None
427
+ seconds = parse_time(since)
428
+ if seconds is None:
429
+ raise DockerError(400, "since must be an ISO 8601 time")
430
+ return seconds
431
+
432
+ async def logs(
433
+ self, host_name: Optional[str], ref: str, *, tail: Optional[int] = None, since: Optional[str] = None, timestamps: Optional[bool] = None,
434
+ ) -> dict[str, Any]:
435
+ h = self.host(host_name)
436
+ tail = 100 if tail is None else tail
437
+ if not isinstance(tail, int) or isinstance(tail, bool) or tail < 1 or tail > 2000:
438
+ raise DockerError(400, "tail must be a whole number from 1 to 2000")
439
+ since_seconds = self._since_seconds(since)
440
+ stamps = timestamps is not False
441
+ raw = await self._resolve(h, ref)
442
+ inspect = await h.client.json("GET", f"/containers/{raw['Id']}/json")
443
+ res = await h.client.request(
444
+ "GET", f"/containers/{raw['Id']}/logs",
445
+ query={"stdout": 1, "stderr": 1, "tail": tail, "since": since_seconds, "timestamps": 1 if stamps else 0}, timeout=30,
446
+ )
447
+ tty = ((inspect or {}).get("Config") or {}).get("Tty") is True
448
+ return {"host": h.name, "lines": parse_logs(res.body, tty, stamps)}
449
+
450
+ async def follow_logs(
451
+ self, host_name: Optional[str], ref: str, on_lines: Callable[[list[dict[str, Any]]], None], *,
452
+ tail: Optional[int] = None, since: Optional[str] = None, timestamps: Optional[bool] = None,
453
+ ) -> None:
454
+ """A live log stream for ``--follow``: lines as they come until the stream ends or the task is cancelled."""
455
+ h = self.host(host_name)
456
+ raw = await self._resolve(h, ref)
457
+ inspect = await h.client.json("GET", f"/containers/{raw['Id']}/json")
458
+ tty = ((inspect or {}).get("Config") or {}).get("Tty") is True
459
+ stamps = timestamps is not False
460
+ since_seconds = self._since_seconds(since)
461
+ stream = await h.client.stream(
462
+ "GET", f"/containers/{raw['Id']}/logs",
463
+ query={"stdout": 1, "stderr": 1, "follow": 1, "tail": tail if tail is not None else 100, "since": since_seconds, "timestamps": 1 if stamps else 0},
464
+ timeout=30,
465
+ )
466
+ buffer = b""
467
+ try:
468
+ async for chunk in stream:
469
+ buffer += chunk
470
+ # only whole frames (multiplexed) or whole lines (tty) are parsed; the rest waits for more
471
+ if tty:
472
+ end = buffer.rfind(b"\n") + 1
473
+ # a line that never ends is flushed at the cut length
474
+ if end == 0 and len(buffer) >= MAX_LOG_LINE:
475
+ end = len(buffer)
476
+ else:
477
+ end = 0
478
+ while end + 8 <= len(buffer) and end + 8 + int.from_bytes(buffer[end + 4:end + 8], "big") <= len(buffer):
479
+ end += 8 + int.from_bytes(buffer[end + 4:end + 8], "big")
480
+ if end > 0:
481
+ lines = parse_logs(buffer[:end], tty, stamps)
482
+ buffer = buffer[end:]
483
+ if lines:
484
+ on_lines(lines)
485
+ finally:
486
+ stream.close()
487
+
488
+ async def stats(self, host_name: Optional[str] = None, ids: Optional[list[str]] = None) -> dict[str, Any]:
489
+ if ids and len(ids) > MAX_STATS_IDS:
490
+ raise DockerError(400, f"too many ids ({MAX_STATS_IDS} at most)")
491
+ h = self.host(host_name)
492
+ # one container list for every reference; the same container named twice is sampled once
493
+ listing = await self._raw_containers(h, bool(ids))
494
+ targets = [c for c in listing if c.get("State") == "running"]
495
+ if ids:
496
+ targets = []
497
+ for ref in ids:
498
+ c = self._resolve_in(listing, ref)
499
+ if not any(t.get("Id") == c.get("Id") for t in targets):
500
+ targets.append(c)
501
+
502
+ async def sample(container_id: str) -> Any:
503
+ return await h.client.json("GET", f"/containers/{container_id}/stats", query={"stream": 0, "one-shot": 1}, timeout=30)
504
+
505
+ async def two_samples(c: dict[str, Any]) -> dict[str, Any]:
506
+ first = await sample(c["Id"])
507
+ if self._stats_gap > 0:
508
+ await asyncio.sleep(self._stats_gap)
509
+ second = await sample(c["Id"])
510
+ return map_stats(c["Id"], container_name(c), first or {}, second or {})
511
+
512
+ # at most STATS_AT_A_TIME containers are sampled at once
513
+ stats: list[dict[str, Any]] = []
514
+ for i in range(0, len(targets), STATS_AT_A_TIME):
515
+ stats.extend(await asyncio.gather(*(two_samples(c) for c in targets[i:i + STATS_AT_A_TIME])))
516
+ return {"host": h.name, "at": self._iso(), "stats": _sorted(list(stats), lambda s: s["name"])}
517
+
518
+ # -- info, disk usage, events -----------------------------------------------------------------------------------
519
+
520
+ async def info(self, host_name: Optional[str] = None) -> dict[str, Any]:
521
+ h = self.host(host_name)
522
+ info, version, listing = await asyncio.gather(
523
+ h.client.json("GET", "/info"), h.client.json("GET", "/version"), self._raw_containers(h),
524
+ )
525
+ info, version = info or {}, version or {}
526
+
527
+ def count(state: str) -> int:
528
+ return len([c for c in listing if c.get("State") == state])
529
+
530
+ return {
531
+ "host": h.name,
532
+ "version": text_of(info.get("ServerVersion") if info.get("ServerVersion") is not None else version.get("Version")),
533
+ "apiVersion": text_of(version.get("ApiVersion")),
534
+ "os": text_of(info.get("OperatingSystem")),
535
+ "kernel": text_of(info.get("KernelVersion")),
536
+ "arch": text_of(info.get("Architecture")),
537
+ "cpus": number_of(info.get("NCPU"), 0),
538
+ "memoryBytes": number_of(info.get("MemTotal"), 0),
539
+ "name": text_of(info.get("Name")),
540
+ "storageDriver": text_of(info.get("Driver")),
541
+ "rootDir": text_of(info.get("DockerRootDir")),
542
+ "containers": {
543
+ "total": len(listing),
544
+ "running": count("running"),
545
+ "paused": count("paused"),
546
+ "stopped": len([c for c in listing if c.get("State") not in ("running", "paused")]),
547
+ },
548
+ "images": number_of(info.get("Images"), 0),
549
+ }
550
+
551
+ async def df(self, host_name: Optional[str] = None) -> dict[str, Any]:
552
+ h = self.host(host_name)
553
+ df, listing = await asyncio.gather(h.client.json("GET", "/system/df"), self._raw_containers(h))
554
+ df = df or {}
555
+ visible_ids = {c.get("Id") for c in listing}
556
+
557
+ def total(items: list[Any], pick: Callable[[Any], Any]) -> float | int:
558
+ result = 0
559
+ for i in items:
560
+ result += max(0, number_of(pick(i), 0))
561
+ return result
562
+
563
+ images: list[Any] = df.get("Images") or []
564
+ containers = [c for c in (df.get("Containers") or []) if c.get("Id") in visible_ids]
565
+ volumes: list[Any] = df.get("Volumes") or []
566
+ cache: list[Any] = df.get("BuildCache") or []
567
+ return {
568
+ "host": h.name,
569
+ "images": {
570
+ "count": len(images),
571
+ "sizeBytes": total(images, lambda i: i.get("Size")),
572
+ "reclaimableBytes": total([i for i in images if number_of(i.get("Containers"), 0) == 0], lambda i: i.get("Size")),
573
+ },
574
+ "containers": {
575
+ "count": len(containers),
576
+ "sizeBytes": total(containers, lambda c: c.get("SizeRw")),
577
+ "reclaimableBytes": total([c for c in containers if c.get("State") not in ("running", "paused")], lambda c: c.get("SizeRw")),
578
+ },
579
+ "volumes": {
580
+ "count": len(volumes),
581
+ "sizeBytes": total(volumes, lambda v: (v.get("UsageData") or {}).get("Size")),
582
+ "reclaimableBytes": total(
583
+ [v for v in volumes if number_of((v.get("UsageData") or {}).get("RefCount"), 0) == 0], lambda v: (v.get("UsageData") or {}).get("Size"),
584
+ ),
585
+ },
586
+ "buildCache": {
587
+ "count": len(cache),
588
+ "sizeBytes": total(cache, lambda c: c.get("Size")),
589
+ "reclaimableBytes": total([c for c in cache if not c.get("InUse")], lambda c: c.get("Size")),
590
+ },
591
+ }
592
+
593
+ @staticmethod
594
+ def _map_event(raw: dict[str, Any]) -> dict[str, Any]:
595
+ actor = raw.get("Actor") or {}
596
+ attributes = {k: js_str(v) for k, v in (actor.get("Attributes") or {}).items()}
597
+ when = raw.get("time")
598
+ if when is None and raw.get("timeNano"):
599
+ when = raw["timeNano"] / 1e9
600
+ return {
601
+ "time": iso_seconds(when),
602
+ "type": text_of(raw.get("Type") if raw.get("Type") is not None else raw.get("type")),
603
+ "action": text_of(raw.get("Action") if raw.get("Action") is not None else raw.get("status")),
604
+ "id": text_of(actor.get("ID") if actor.get("ID") is not None else raw.get("id")),
605
+ "name": text_of(attributes.get("name")),
606
+ "attributes": attributes,
607
+ }
608
+
609
+ def _parse_events(self, text: str) -> list[dict[str, Any]]:
610
+ events = []
611
+ for line in text.split("\n"):
612
+ if not line.strip():
613
+ continue
614
+ try:
615
+ events.append(self._map_event(json.loads(line)))
616
+ except (ValueError, AttributeError):
617
+ continue # a partial line
618
+ return events
619
+
620
+ async def events(self, host_name: Optional[str] = None, *, since: Optional[int] = None, limit: Optional[int] = None) -> dict[str, Any]:
621
+ h = self.host(host_name)
622
+ since = 3600 if since is None else since
623
+ limit = 200 if limit is None else limit
624
+ if not isinstance(since, int) or since < 1 or since > 86400:
625
+ raise DockerError(400, "since must be a whole number of seconds from 1 to 86400")
626
+ if not isinstance(limit, int) or limit < 1 or limit > 1000:
627
+ raise DockerError(400, "limit must be a whole number from 1 to 1000")
628
+ now = math.floor(self._now().timestamp())
629
+ res = await h.client.request("GET", "/events", query={"since": now - since, "until": now}, timeout=30)
630
+ hidden = await self._hidden_ids(h)
631
+ kept = [e for e in self._parse_events(res.body.decode("utf-8", "replace")) if not self._is_hidden_event(e, hidden)]
632
+ # newest first; the engine's order is oldest first
633
+ return {"host": h.name, "events": list(reversed(kept))[:limit]}
634
+
635
+ async def follow_events(self, host_name: Optional[str], since: int, on_events: Callable[[list[dict[str, Any]]], None]) -> None:
636
+ """Events as they happen, for ``docker system events --follow``."""
637
+ h = self.host(host_name)
638
+ now = math.floor(self._now().timestamp())
639
+ hidden = await self._hidden_ids(h)
640
+ stream = await h.client.stream("GET", "/events", query={"since": now - since}, timeout=30)
641
+ decoder = codecs.getincrementaldecoder("utf-8")("replace")
642
+ buffer = ""
643
+ try:
644
+ async for chunk in stream:
645
+ buffer += decoder.decode(chunk)
646
+ parts = buffer.split("\n")
647
+ buffer = parts.pop()
648
+ parsed = self._parse_events("\n".join(parts))
649
+ # a hidden container created after the follow started: its id is hidden from then on (its network and
650
+ # volume events name it in their attributes)
651
+ for e in parsed:
652
+ if e.get("type") == "container" and e.get("id") and self.is_hidden(e.get("name") or "", e.get("attributes") or {}):
653
+ hidden.add(e["id"])
654
+ events = [e for e in parsed if not self._is_hidden_event(e, hidden)]
655
+ if events:
656
+ on_events(events)
657
+ finally:
658
+ stream.close()
659
+
660
+ # -- container actions ------------------------------------------------------------------------------------------
661
+
662
+ async def _refreshed(self, h: HostContext, container_id: str) -> dict[str, Any]:
663
+ listing = await h.client.json("GET", "/containers/json", query={"all": 1, "filters": json.dumps({"id": [container_id]}, separators=(",", ":"))})
664
+ raw = next((c for c in (listing or []) if c.get("Id") == container_id), None)
665
+ if raw is None:
666
+ raise DockerError(404, f"no such container: {container_id}")
667
+ return self._map(raw)
668
+
669
+ @staticmethod
670
+ async def _run_action(h: HostContext, container_id: str, action: str) -> None:
671
+ slow = action in ("stop", "restart")
672
+ await h.client.request("POST", f"/containers/{container_id}/{action}", allow_304=True, timeout=90 if slow else None)
673
+
674
+ async def container_action(self, host_name: Optional[str], ref: str, action: str, caller: Caller = None) -> dict[str, Any]:
675
+ if action not in CONTAINER_ACTIONS:
676
+ raise DockerError(400, f"unknown action: {action}")
677
+ await self._refusing(
678
+ caller, host_name, f"docker.container.{action}", "container", ref, f"{action} container {ref}", {"container": ref}, self.assert_writable,
679
+ )
680
+ h = self.host(host_name)
681
+ raw = await self._resolve(h, ref)
682
+ container = self._map(raw)
683
+ await self._refusing(
684
+ caller, h.name, f"docker.container.{action}", "container", container["name"], f"{action} container {container['name']}",
685
+ {"container": container["name"], "id": container["shortId"]}, lambda: self._assert_not_protected(container),
686
+ )
687
+ await self._audited(
688
+ caller, h.name, f"docker.container.{action}", "container", container["name"], f"{action} container {container['name']}",
689
+ {"container": container["name"], "id": container["shortId"]}, lambda: self._run_action(h, container["id"], action),
690
+ )
691
+ return {"ok": True, "container": await self._refreshed(h, container["id"])}
692
+
693
+ async def remove_container(self, host_name: Optional[str], ref: str, *, force: Optional[bool] = None, volumes: Optional[bool] = None, caller: Caller = None) -> dict[str, Any]:
694
+ await self._refusing(
695
+ caller, host_name, "docker.container.remove", "container", ref, f"remove container {ref}", {"container": ref}, self.assert_writable,
696
+ )
697
+ h = self.host(host_name)
698
+ container = self._map(await self._resolve(h, ref))
699
+ await self._refusing(
700
+ caller, h.name, "docker.container.remove", "container", container["name"], f"remove container {container['name']}",
701
+ {"container": container["name"], "id": container["shortId"]}, lambda: self._assert_not_protected(container),
702
+ )
703
+ await self._audited(
704
+ caller, h.name, "docker.container.remove", "container", container["name"], f"remove container {container['name']}",
705
+ {"container": container["name"], "id": container["shortId"], "force": force is True, "volumes": volumes is True},
706
+ lambda: h.client.request("DELETE", f"/containers/{container['id']}", query={"force": 1 if force else 0, "v": 1 if volumes else 0}),
707
+ )
708
+ return {"ok": True}
709
+
710
+ async def prune_containers(self, host_name: Optional[str] = None, caller: Caller = None) -> dict[str, Any]:
711
+ await self._refusing(
712
+ caller, host_name, "docker.containers.prune", "containers", "stopped", "prune stopped containers", {}, self.assert_writable,
713
+ )
714
+ h = self.host(host_name)
715
+ stopped = [c for c in await self._raw_containers(h, True, True) if c.get("State") in ("exited", "dead", "created") and not self._map(c)["protected"]]
716
+
717
+ async def run() -> dict[str, Any]:
718
+ removed: list[str] = []
719
+ reclaimed: float | int = 0
720
+ for c in _sorted(stopped, container_name):
721
+ try:
722
+ await h.client.request("DELETE", f"/containers/{c['Id']}", query={"force": 0, "v": 0})
723
+ removed.append(container_name(c))
724
+ reclaimed += number_of(c.get("SizeRw"), 0)
725
+ except Exception as err: # noqa: BLE001
726
+ if not isinstance(err, DockerError) or err.status != 404:
727
+ self._log.warning("docker: prune skipped %s: %s", container_name(c), _message(err))
728
+ return {"removed": removed, "reclaimedBytes": reclaimed}
729
+
730
+ return await self._audited(
731
+ caller, h.name, "docker.containers.prune", "containers", "stopped", "prune stopped containers", {}, run,
732
+ lambda r: {"removed": len(r["removed"]), "reclaimedBytes": r["reclaimedBytes"]},
733
+ )
734
+
735
+ # -- exec -------------------------------------------------------------------------------------------------------
736
+
737
+ @staticmethod
738
+ def _validate_exec(options: dict[str, Any]) -> dict[str, Any]:
739
+ command = options.get("command")
740
+ if not isinstance(command, list) or len(command) == 0 or any(not isinstance(c, str) for c in command):
741
+ raise DockerError(400, "command must be a non-empty array of strings")
742
+ if len(command) > 256 or any(len(c) > 65536 for c in command):
743
+ raise DockerError(400, "command is too long")
744
+ for key in ("user", "workdir"):
745
+ v = options.get(key)
746
+ if v is not None and (not isinstance(v, str) or len(v) > 256):
747
+ raise DockerError(400, f"{key} must be a string")
748
+ raw_timeout = options.get("timeoutSeconds")
749
+ timeout = 30 if raw_timeout is None else raw_timeout
750
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not float(timeout).is_integer() or timeout < 1 or timeout > 300:
751
+ raise DockerError(400, "timeoutSeconds must be a whole number from 1 to 300")
752
+ return {"command": command, "user": options.get("user") or None, "workdir": options.get("workdir") or None, "timeout": int(timeout)}
753
+
754
+ async def exec(self, host_name: Optional[str], ref: str, options: dict[str, Any], caller: Caller = None) -> dict[str, Any]:
755
+ """Runs a command in a container and returns its output (each stream capped at 1 MB)."""
756
+ data = self._validate_exec(options)
757
+ text = " ".join(data["command"])
758
+ brief = text[:200] + "…" if len(text) > 200 else text
759
+ await self._refusing(
760
+ caller, host_name, "docker.exec.run", "container", ref, f"run in {ref}: {brief}", {"container": ref, "command": data["command"]}, self.assert_writable,
761
+ )
762
+ h = self.host(host_name)
763
+ container = self._map(await self._resolve(h, ref))
764
+ await self._refusing(
765
+ caller, h.name, "docker.exec.run", "container", container["name"], f"run in {container['name']}: {brief}",
766
+ {"container": container["name"], "command": data["command"]}, lambda: self._assert_not_protected(container),
767
+ )
768
+ properties: dict[str, Any] = {"container": container["name"], "command": data["command"]}
769
+ if data["user"]:
770
+ properties["user"] = data["user"]
771
+ if data["workdir"]:
772
+ properties["workdir"] = data["workdir"]
773
+
774
+ async def run() -> dict[str, Any]:
775
+ body: dict[str, Any] = {"AttachStdout": True, "AttachStderr": True, "Tty": False, "Cmd": data["command"]}
776
+ if data["user"]:
777
+ body["User"] = data["user"]
778
+ if data["workdir"]:
779
+ body["WorkingDir"] = data["workdir"]
780
+ created = await h.client.json("POST", f"/containers/{container['id']}/exec", body=body)
781
+ upgrade = await h.client.upgrade(f"/exec/{created['Id']}/start", {"Detach": False, "Tty": False})
782
+ output = await self._collect_exec(upgrade, data["timeout"])
783
+ return {"exitCode": await self._exec_exit_code(h, created["Id"]), **output}
784
+
785
+ return await self._audited(
786
+ caller, h.name, "docker.exec.run", "container", container["name"],
787
+ f"run in {container['name']}: {brief}", properties, run,
788
+ lambda r: {"exitCode": r["exitCode"]},
789
+ )
790
+
791
+ @staticmethod
792
+ async def _exec_exit_code(h: HostContext, exec_id: str) -> int:
793
+ """The exit code of an exec, read once the engine says it is no longer running (polled for up to 2 s; 1 when
794
+ it never stops)."""
795
+ deadline = time.monotonic() + 2
796
+ while True:
797
+ try:
798
+ inspect = await h.client.json("GET", f"/exec/{exec_id}/json")
799
+ except Exception: # noqa: BLE001
800
+ return 1
801
+ if (inspect or {}).get("Running") is not True:
802
+ return number_of((inspect or {}).get("ExitCode"), 0)
803
+ if time.monotonic() >= deadline:
804
+ return 1
805
+ await asyncio.sleep(0.05)
806
+
807
+ @staticmethod
808
+ async def _collect_exec(upgrade: EngineUpgrade, timeout_seconds: int) -> dict[str, Any]:
809
+ chunks: dict[str, list[bytes]] = {"stdout": [], "stderr": []}
810
+ sizes = {"stdout": 0, "stderr": 0}
811
+ truncated = False
812
+ pending = b""
813
+
814
+ async def read_all() -> None:
815
+ nonlocal pending, truncated
816
+ while True:
817
+ data = await upgrade.read()
818
+ if not data:
819
+ return
820
+ pending += data
821
+ while len(pending) >= 8:
822
+ size = int.from_bytes(pending[4:8], "big")
823
+ if len(pending) < 8 + size:
824
+ break
825
+ stream = "stderr" if pending[0] == 2 else "stdout"
826
+ payload = pending[8:8 + size]
827
+ pending = pending[8 + size:]
828
+ room = EXEC_OUTPUT_CAP - sizes[stream]
829
+ if len(payload) > room:
830
+ truncated = True
831
+ if room > 0:
832
+ part = payload[:room]
833
+ chunks[stream].append(part)
834
+ sizes[stream] += len(part)
835
+
836
+ try:
837
+ await asyncio.wait_for(read_all(), timeout_seconds)
838
+ except (asyncio.TimeoutError, TimeoutError) as err:
839
+ raise DockerError(504, f"the command did not finish in {timeout_seconds} s") from err
840
+ finally:
841
+ upgrade.close()
842
+ return {
843
+ "stdout": b"".join(chunks["stdout"]).decode("utf-8", "replace"),
844
+ "stderr": b"".join(chunks["stderr"]).decode("utf-8", "replace"),
845
+ "truncated": truncated,
846
+ }
847
+
848
+ async def check_exec(self, host_name: Optional[str], ref: str, caller: Caller = None) -> dict[str, Any]:
849
+ """The rules an exec must pass (not read-only, a known host and container, not protected): the container, else the error."""
850
+ await self._refusing(
851
+ caller, host_name, "docker.exec.session", "container", ref, f"interactive session in {ref}", {"container": ref}, self.assert_writable,
852
+ )
853
+ h = self.host(host_name)
854
+ container = self._map(await self._resolve(h, ref))
855
+ await self._refusing(
856
+ caller, h.name, "docker.exec.session", "container", container["name"], f"interactive session in {container['name']}",
857
+ {"container": container["name"]}, lambda: self._assert_not_protected(container),
858
+ )
859
+ if container["state"] == "paused":
860
+ raise DockerError(409, f"container {container['name']} is paused, unpause it before exec")
861
+ if container["state"] != "running":
862
+ raise DockerError(409, f"container {container['name']} is not running")
863
+ return {"host": h.name, "container": container}
864
+
865
+ async def prepare_exec_session(
866
+ self, host_name: Optional[str], ref: str, *, command: Optional[list[str]] = None, user: Optional[str] = None, caller: Caller = None,
867
+ ) -> dict[str, Any]:
868
+ """Prepares an interactive exec session (a TTY): the rules, the container and the exec created."""
869
+ await self._refusing(
870
+ caller, host_name, "docker.exec.session", "container", ref, f"interactive session in {ref}", {"container": ref}, self.assert_writable,
871
+ )
872
+ if user is not None and len(user) > 256:
873
+ raise DockerError(400, "user must be a string")
874
+ h = self.host(host_name)
875
+ container = self._map(await self._resolve(h, ref))
876
+ await self._refusing(
877
+ caller, h.name, "docker.exec.session", "container", container["name"], f"interactive session in {container['name']}",
878
+ {"container": container["name"]}, lambda: self._assert_not_protected(container),
879
+ )
880
+ if container["state"] == "paused":
881
+ raise DockerError(409, f"container {container['name']} is paused, unpause it before exec")
882
+ if container["state"] != "running":
883
+ raise DockerError(409, f"container {container['name']} is not running")
884
+ argv = command if command else list(DEFAULT_SHELL)
885
+ body: dict[str, Any] = {
886
+ "AttachStdin": True, "AttachStdout": True, "AttachStderr": True, "Tty": True, "Cmd": argv, "Env": ["TERM=xterm-256color"],
887
+ }
888
+ if user:
889
+ body["User"] = user
890
+ created = await h.client.json("POST", f"/containers/{container['id']}/exec", body=body)
891
+ session: dict[str, Any] = {"host": h.name, "container": container, "execId": created["Id"], "command": argv}
892
+ if user:
893
+ session["user"] = user
894
+ return session
895
+
896
+ async def start_exec_session(self, prepared: dict[str, Any], *, cols: Optional[int] = None, rows: Optional[int] = None, caller: Caller = None) -> tuple[EngineUpgrade, Callable[[int, int], Awaitable[None]], Callable[[], Awaitable[int]]]:
897
+ """Starts a prepared exec and hands over the raw TTY stream (plus a ``resize`` and the ``exit_code`` reader)."""
898
+ h = self.host(prepared["host"])
899
+
900
+ async def resize(width: int, height: int) -> None:
901
+ try:
902
+ await h.client.request("POST", f"/exec/{prepared['execId']}/resize", query={"h": height, "w": width})
903
+ except Exception: # noqa: BLE001 - the exec may have ended
904
+ pass
905
+
906
+ properties: dict[str, Any] = {"container": prepared["container"]["name"], "command": prepared["command"]}
907
+ if prepared.get("user"):
908
+ properties["user"] = prepared["user"]
909
+ upgrade = await self._audited(
910
+ caller, h.name, "docker.exec.session", "container", prepared["container"]["name"],
911
+ f"interactive session in {prepared['container']['name']}: {' '.join(prepared['command'])}", properties,
912
+ lambda: h.client.upgrade(f"/exec/{prepared['execId']}/start", {"Detach": False, "Tty": True}),
913
+ )
914
+ if cols and rows:
915
+ await resize(cols, rows)
916
+ return upgrade, resize, lambda: self._exec_exit_code(h, prepared["execId"])
917
+
918
+ # -- images -----------------------------------------------------------------------------------------------------
919
+
920
+ async def images(self, host_name: Optional[str] = None) -> dict[str, Any]:
921
+ h = self.host(host_name)
922
+ raw, containers = await asyncio.gather(h.client.json("GET", "/images/json"), self._raw_containers(h))
923
+ images = []
924
+ for i in raw or []:
925
+ tags = [t for t in (i.get("RepoTags") or []) if t and t != "<none>:<none>"]
926
+ images.append({
927
+ "id": js_str(i["Id"]),
928
+ "shortId": short_id(i["Id"]),
929
+ "tags": tags,
930
+ "sizeBytes": number_of(i.get("Size"), 0),
931
+ "createdAt": iso_seconds(i.get("Created")),
932
+ "containers": len([c for c in containers if c.get("ImageID") == i["Id"]]),
933
+ "dangling": len(tags) == 0,
934
+ })
935
+ # newest first, then by id
936
+ images.sort(key=lambda i: i["id"])
937
+ images.sort(key=lambda i: i["createdAt"] or "", reverse=True)
938
+ return {"host": h.name, "images": images}
939
+
940
+ async def remove_image(self, host_name: Optional[str], image_id: str, *, force: Optional[bool] = None, caller: Caller = None) -> dict[str, Any]:
941
+ await self._refusing(
942
+ caller, host_name, "docker.image.remove", "image", image_id, f"remove image {image_id}", {"image": image_id}, self.assert_writable,
943
+ )
944
+ h = self.host(host_name)
945
+ if not image_id or not image_id.strip():
946
+ raise DockerError(400, "an image is required")
947
+ assert_path_name("image", image_id)
948
+
949
+ async def run() -> dict[str, Any]:
950
+ items = await h.client.json("DELETE", f"/images/{encode_component(image_id)}", query={"force": 1 if force else 0}) or []
951
+ return {
952
+ "ok": True,
953
+ "untagged": [js_str(i["Untagged"]) for i in items if i.get("Untagged")],
954
+ "deleted": [js_str(i["Deleted"]) for i in items if i.get("Deleted")],
955
+ }
956
+
957
+ return await self._audited(
958
+ caller, h.name, "docker.image.remove", "image", image_id, f"remove image {image_id}", {"image": image_id, "force": force is True}, run,
959
+ )
960
+
961
+ async def prune_images(self, host_name: Optional[str] = None, *, all: Optional[bool] = None, caller: Caller = None) -> dict[str, Any]: # noqa: A002
962
+ await self._refusing(
963
+ caller, host_name, "docker.images.prune", "images", "unused" if all else "dangling",
964
+ "prune every unused image" if all else "prune dangling images", {"all": all is True}, self.assert_writable,
965
+ )
966
+ h = self.host(host_name)
967
+
968
+ async def run() -> dict[str, Any]:
969
+ res = await h.client.json(
970
+ "POST", "/images/prune", query={"filters": json.dumps({"dangling": ["false" if all else "true"]}, separators=(",", ":"))}, timeout=120,
971
+ ) or {}
972
+ removed = [js_str(i.get("Untagged") if i.get("Untagged") is not None else i.get("Deleted")) for i in res.get("ImagesDeleted") or []]
973
+ return {"removed": removed, "reclaimedBytes": number_of(res.get("SpaceReclaimed"), 0)}
974
+
975
+ return await self._audited(
976
+ caller, h.name, "docker.images.prune", "images", "unused" if all else "dangling",
977
+ "prune every unused image" if all else "prune dangling images", {"all": all is True}, run,
978
+ lambda r: {"removed": len(r["removed"]), "reclaimedBytes": r["reclaimedBytes"]},
979
+ )
980
+
981
+ # -- operations (pulls) -----------------------------------------------------------------------------------------
982
+
983
+ def is_admin(self, caller: Caller) -> bool:
984
+ """Whether a caller sees the log of a compose operation: it holds ``docker:admin``, or it has no principal and the
985
+ server allows unprotected callers (``allowUnprotected``)."""
986
+ c = as_caller(caller)
987
+ if c.admin is True:
988
+ return True
989
+ return not c.signed_in and self.settings.allow_unprotected is True
990
+
991
+ @staticmethod
992
+ def public_operation(op: dict[str, Any], admin: bool = False) -> dict[str, Any]:
993
+ """A copy of the operation; for a caller without ``docker:admin`` a ``stack-up`` has no log and no message."""
994
+ copy = dict(op)
995
+ if op.get("kind") == "stack-up" and not admin:
996
+ copy["log"] = []
997
+ copy.pop("message", None)
998
+ return copy
999
+
1000
+ def operation_for_readers(self, op: dict[str, Any]) -> dict[str, Any]:
1001
+ """The operation as callers without ``docker:admin`` may see it (the event personalizer of the plugin uses it)."""
1002
+ return self.public_operation(op, False)
1003
+
1004
+ def operations(self, caller: Caller = None) -> dict[str, Any]:
1005
+ """Every running operation and the newest finished ones, 50 in all, newest first."""
1006
+ admin = self.is_admin(caller)
1007
+ running = len([r for r in self._operations if r.op["state"] == "running"])
1008
+ budget = max(0, MAX_OPERATIONS - running)
1009
+ shown: list[OperationRecord] = []
1010
+ for r in reversed(self._operations):
1011
+ if r.op["state"] == "running":
1012
+ shown.append(r)
1013
+ elif budget > 0:
1014
+ shown.append(r)
1015
+ budget -= 1
1016
+ return {"operations": [self.public_operation(r.op, admin) for r in shown]}
1017
+
1018
+ def operation(self, op_id: str, caller: Caller = None) -> dict[str, Any]:
1019
+ admin = self.is_admin(caller)
1020
+ record = next((r for r in self._operations if r.op["id"] == op_id), None)
1021
+ if record is None:
1022
+ raise DockerError(404, f"no such operation: {op_id}")
1023
+ return {"operation": self.public_operation(record.op, admin)}
1024
+
1025
+ async def wait_operation(self, op_id: str) -> dict[str, Any]:
1026
+ """Resolves when the operation ended (done or failed)."""
1027
+ record = next((r for r in self._operations if r.op["id"] == op_id), None)
1028
+ if record is None:
1029
+ raise DockerError(404, f"no such operation: {op_id}")
1030
+ await asyncio.shield(record.done)
1031
+ return dict(record.op)
1032
+
1033
+ def _spawn(self, coro: Awaitable[Any]) -> "asyncio.Task[Any]":
1034
+ task = asyncio.ensure_future(coro)
1035
+ self._tasks.add(task)
1036
+ task.add_done_callback(self._tasks.discard)
1037
+ return task
1038
+
1039
+ async def _start_operation(
1040
+ self, kind: str, title: str, host: str, caller: Caller, run: Callable[[Callable[[dict[str, Any]], None]], Awaitable[Optional[str]]],
1041
+ key: Optional[str] = None,
1042
+ ) -> dict[str, Any]:
1043
+ if len([r for r in self._operations if r.op["state"] == "running"]) >= MAX_RUNNING_OPERATIONS:
1044
+ raise DockerError(409, f"too many operations are running ({MAX_RUNNING_OPERATIONS} at most)")
1045
+ op: dict[str, Any] = {
1046
+ "id": self._new_id(), "kind": kind, "title": title, "state": "running", "startedAt": self._iso(), "progress": None, "log": [],
1047
+ }
1048
+ if as_caller(caller).name:
1049
+ op["user"] = as_caller(caller).name
1050
+ op["host"] = host
1051
+ record = OperationRecord(op)
1052
+ record.key = key
1053
+
1054
+ async def publish() -> None:
1055
+ try:
1056
+ if self._publish is not None:
1057
+ # once, to docker:read; the plugin's personalizer reduces a stack-up for sockets without docker:admin
1058
+ await self._publish(OPERATION_EVENT, dict(op), "docker:read")
1059
+ except Exception: # noqa: BLE001 - an event nobody gets is not an error
1060
+ pass
1061
+
1062
+ def emit(force: bool) -> None:
1063
+ now = time.monotonic()
1064
+ if not force and now - record.last_progress_event < 1.0:
1065
+ return
1066
+ record.last_progress_event = now
1067
+ self._spawn(publish())
1068
+
1069
+ def update(patch: dict[str, Any]) -> None:
1070
+ op.update(patch)
1071
+ emit(False)
1072
+
1073
+ self._operations.append(record)
1074
+ if len(self._operations) > MAX_OPERATIONS * 2:
1075
+ # only finished operations go: a running one still counts towards the cap of 5
1076
+ for old in [r for r in self._operations if r.op["state"] != "running"]:
1077
+ if len(self._operations) <= MAX_OPERATIONS:
1078
+ break
1079
+ self._operations.remove(old)
1080
+ emit(True)
1081
+
1082
+ async def work() -> None:
1083
+ try:
1084
+ final = await run(update)
1085
+ op["state"] = "done"
1086
+ op["finishedAt"] = self._iso()
1087
+ if final:
1088
+ op["message"] = final
1089
+ except asyncio.CancelledError:
1090
+ op["state"] = "failed"
1091
+ op["finishedAt"] = self._iso()
1092
+ op["error"] = "cancelled"
1093
+ emit(True)
1094
+ record.done.set_result(None)
1095
+ raise
1096
+ except Exception as err: # noqa: BLE001 - the operation failed, with the error
1097
+ op["state"] = "failed"
1098
+ op["finishedAt"] = self._iso()
1099
+ op["error"] = _message(err)
1100
+ emit(True)
1101
+ if not record.done.done():
1102
+ record.done.set_result(None)
1103
+
1104
+ record.task = self._spawn(work())
1105
+ # the work runs up to its first wait, as the operation's first answer shows it (a JS promise body runs at once)
1106
+ await asyncio.sleep(0)
1107
+ return dict(op)
1108
+
1109
+ async def _pull_into(self, h: HostContext, image: str, update: Callable[[dict[str, Any]], None]) -> Optional[str]:
1110
+ """Pulls one image (progress as bytes of the layers) and returns the last status line."""
1111
+ ref = normalize_image_ref(image)
1112
+ name, tag = ref["name"], ref["tag"]
1113
+ query = {"fromImage": f"{name}{tag}"} if tag.startswith("@") else {"fromImage": name, "tag": tag}
1114
+ stream = await h.client.stream("POST", "/images/create", query=query, timeout=60)
1115
+ layers: dict[str, tuple[float, float]] = {}
1116
+ state: dict[str, Optional[str]] = {"last": None, "error": None}
1117
+
1118
+ def line(text: str) -> None:
1119
+ if not text.strip():
1120
+ return
1121
+ try:
1122
+ item = json.loads(text)
1123
+ except ValueError:
1124
+ return
1125
+ if not isinstance(item, dict):
1126
+ return
1127
+ if item.get("error"):
1128
+ state["error"] = js_str(item["error"])
1129
+ if item.get("status"):
1130
+ state["last"] = js_str(item["status"])
1131
+ detail = item.get("progressDetail")
1132
+ if item.get("id") and isinstance(detail, dict) and number_of(detail.get("total"), 0) > 0:
1133
+ layers[js_str(item["id"])] = (number_of(detail.get("current"), 0), number_of(detail["total"]))
1134
+ if layers:
1135
+ current = total = 0
1136
+ for c, t in layers.values():
1137
+ current += min(c, t)
1138
+ total += t
1139
+ patch: dict[str, Any] = {"progress": {"current": current, "total": total}}
1140
+ if state["last"]:
1141
+ patch["message"] = state["last"]
1142
+ update(patch)
1143
+ elif state["last"]:
1144
+ update({"message": state["last"]})
1145
+
1146
+ decoder = codecs.getincrementaldecoder("utf-8")("replace")
1147
+ buffer = ""
1148
+ iterator = stream.__aiter__()
1149
+ try:
1150
+ while True:
1151
+ # An engine that goes silent fails the pull
1152
+ try:
1153
+ chunk = await asyncio.wait_for(iterator.__anext__(), self._pull_silence)
1154
+ except StopAsyncIteration:
1155
+ break
1156
+ except (asyncio.TimeoutError, TimeoutError) as err:
1157
+ raise RuntimeError(f"the engine sent nothing for {round(self._pull_silence)} s") from err
1158
+ buffer += decoder.decode(chunk)
1159
+ parts = buffer.split("\n")
1160
+ buffer = parts.pop()
1161
+ for part in parts:
1162
+ line(part)
1163
+ # A connection that closes without the end of the stream ends without a result
1164
+ if stream.incomplete:
1165
+ raise RuntimeError("the engine closed the connection before the pull ended")
1166
+ line(buffer)
1167
+ finally:
1168
+ stream.close()
1169
+ if state["error"]:
1170
+ raise RuntimeError(state["error"])
1171
+ return state["last"]
1172
+
1173
+ async def pull(self, host_name: Optional[str], image: Any, caller: Caller = None) -> dict[str, Any]:
1174
+ """Starts a pull in the background (202 with the operation)."""
1175
+ if not isinstance(image, str) or not image.strip() or len(image) > 512 or re.search(r"\s", image.strip()):
1176
+ raise DockerError(400, "image must be an image name, for example nginx:1.27")
1177
+ ref = normalize_image_ref(image)["ref"]
1178
+ await self._refusing(caller, host_name, "docker.image.pull", "image", ref, f"pull image {ref}", {"image": ref}, self.assert_writable)
1179
+ h = self.host(host_name)
1180
+
1181
+ def run(update: Callable[[dict[str, Any]], None]) -> Awaitable[Optional[str]]:
1182
+ return self._audited(
1183
+ caller, h.name, "docker.image.pull", "image", ref, f"pull image {ref}", {"image": ref}, lambda: self._pull_into(h, ref, update),
1184
+ )
1185
+
1186
+ return await self._start_operation("pull", f"Pull {ref}", h.name, caller, run)
1187
+
1188
+ # -- stacks -----------------------------------------------------------------------------------------------------
1189
+
1190
+ def _compose_roots(self, h: Optional[HostContext] = None) -> list[str]:
1191
+ """The absolute ``composeRoots``; with a host only when it is one of ``composeHosts`` (the roots belong to those
1192
+ hosts: for any other no root file is used and no ``down`` stack is listed)."""
1193
+ if h is not None:
1194
+ hosts = self.settings.compose_hosts if isinstance(self.settings.compose_hosts, list) else [LOCAL_HOST]
1195
+ if h.name not in hosts:
1196
+ return []
1197
+ roots = self.settings.compose_roots
1198
+ return [r.strip() for r in roots if isinstance(r, str) and r.strip() and os.path.isabs(r.strip())] if isinstance(roots, list) else []
1199
+
1200
+ def _compose_file_of(self, h: HostContext, name: str, config_files: list[str]) -> Optional[str]:
1201
+ """The compose file of a stack: the first of the stack's ``config_files`` label (only on a unix socket host, and it
1202
+ must pass the checks of the roots) and ``<root>/<name>/compose.yaml|compose.yml|docker-compose.yml|docker-compose.yaml``."""
1203
+ roots = self._compose_roots(h)
1204
+ if not roots:
1205
+ return None
1206
+ label = config_files[0] if config_files else None
1207
+ if label and h.client.is_unix_socket and cmp.check_compose_file(label, roots):
1208
+ return label
1209
+ return cmp.find_root_compose_file(name, roots)
1210
+
1211
+ @staticmethod
1212
+ def _label_files(containers: list[dict[str, Any]]) -> list[str]:
1213
+ first = next((c for c in containers if c["labels"].get(COMPOSE_CONFIG_FILES)), None)
1214
+ return [x.strip() for x in ((first["labels"][COMPOSE_CONFIG_FILES] if first else "") or "").split(",") if x.strip()]
1215
+
1216
+ @staticmethod
1217
+ def _stack_of(name: str, containers: list[dict[str, Any]], compose_file: Optional[str] = None) -> dict[str, Any]:
1218
+ running = len([c for c in containers if c["state"] == "running"])
1219
+ first = next((c for c in containers if c["labels"].get(COMPOSE_WORKING_DIR) or c["labels"].get(COMPOSE_CONFIG_FILES)), None)
1220
+ files = (first["labels"].get(COMPOSE_CONFIG_FILES) if first else None) or ""
1221
+ return {
1222
+ "name": name,
1223
+ "state": "stopped" if running == 0 else ("running" if running == len(containers) else "partial"),
1224
+ "containers": len(containers),
1225
+ "running": running,
1226
+ "services": sorted({c["service"] for c in containers if c["service"]}),
1227
+ "workingDir": (first["labels"].get(COMPOSE_WORKING_DIR) if first else None) or "",
1228
+ "configFiles": [s.strip() for s in files.split(",") if s.strip()],
1229
+ "composeFile": compose_file,
1230
+ }
1231
+
1232
+ @staticmethod
1233
+ def _down_stack(name: str, file: str) -> dict[str, Any]:
1234
+ return {"name": name, "state": "down", "containers": 0, "running": 0, "services": [], "workingDir": os.path.dirname(file), "configFiles": [file], "composeFile": file}
1235
+
1236
+ async def _hidden_projects(self, h: HostContext) -> set[str]:
1237
+ """The compose projects all of whose containers are hidden (they do not exist for the caller, folder or not)."""
1238
+ projects: dict[str, bool] = {}
1239
+ for c in await self._all_raw_containers(h):
1240
+ project = (c.get("Labels") or {}).get(COMPOSE_PROJECT)
1241
+ if project:
1242
+ projects[project] = projects.get(project, True) and self.is_hidden(container_name(c), c.get("Labels") or {})
1243
+ return {p for p, all_hidden in projects.items() if all_hidden}
1244
+
1245
+ async def stacks(self, host_name: Optional[str] = None) -> dict[str, Any]:
1246
+ h = self.host(host_name)
1247
+ everything = await self._all_raw_containers(h)
1248
+ containers = [self._map(c) for c in self._visible(everything)]
1249
+ groups: dict[str, list[dict[str, Any]]] = {}
1250
+ for c in containers:
1251
+ if c["stack"]:
1252
+ groups.setdefault(c["stack"], []).append(c)
1253
+ stacks = [self._stack_of(name, items, self._compose_file_of(h, name, self._label_files(items))) for name, items in groups.items()]
1254
+ # a folder of a root with a compose file is a stack even without containers (unless all its containers are hidden)
1255
+ hidden = {
1256
+ (c.get("Labels") or {}).get(COMPOSE_PROJECT) for c in everything
1257
+ if (c.get("Labels") or {}).get(COMPOSE_PROJECT) and self.is_hidden(container_name(c), c.get("Labels") or {})
1258
+ } - set(groups)
1259
+ for name, file in cmp.discover_compose_stacks(self._compose_roots(h)):
1260
+ if name not in groups and name not in hidden:
1261
+ stacks.append(self._down_stack(name, file))
1262
+ return {"host": h.name, "stacks": _sorted(stacks, lambda s: s["name"])}
1263
+
1264
+ async def _stack_containers(self, h: HostContext, name: str) -> list[dict[str, Any]]:
1265
+ containers = [c for c in (self._map(r) for r in await self._raw_containers(h)) if c["stack"] == name]
1266
+ if not containers:
1267
+ raise DockerError(404, f"no such stack: {name}")
1268
+ return _sorted(containers, lambda c: c["name"])
1269
+
1270
+ async def stack(self, host_name: Optional[str], name: str) -> dict[str, Any]:
1271
+ h = self.host(host_name)
1272
+ containers = _sorted([c for c in (self._map(r) for r in await self._raw_containers(h)) if c["stack"] == name], lambda c: c["name"])
1273
+ roots = self._compose_roots(h)
1274
+ if containers:
1275
+ stack = self._stack_of(name, containers, self._compose_file_of(h, name, self._label_files(containers)))
1276
+ else:
1277
+ file = cmp.find_root_compose_file(name, roots)
1278
+ if not file or name in await self._hidden_projects(h):
1279
+ raise DockerError(404, f"no such stack: {name}")
1280
+ stack = self._down_stack(name, file)
1281
+ content = cmp.read_compose_file(stack["composeFile"], roots) if stack["composeFile"] else None
1282
+ compose_file = {"path": stack["composeFile"], "content": content} if stack["composeFile"] and content is not None else None
1283
+ return {"host": h.name, "stack": stack, "containers": containers, "composeFile": compose_file}
1284
+
1285
+ # -- compose (the docker compose CLI of the server's machine) ---------------------------------------------------
1286
+
1287
+ def _compose_words(self) -> list[str]:
1288
+ words = split_shell_words((self.settings.compose_command or "").strip() or "docker compose")
1289
+ return words or ["docker", "compose"]
1290
+
1291
+ def _compose_env(self) -> dict[str, str]:
1292
+ return cmp.compose_environment(self.settings.compose_env if isinstance(self.settings.compose_env, list) else [])
1293
+
1294
+ def _gate(self) -> "asyncio.Semaphore":
1295
+ if self._compose_gate is None:
1296
+ self._compose_gate = asyncio.Semaphore(MAX_COMPOSE_PROCESSES)
1297
+ return self._compose_gate
1298
+
1299
+ async def _run_compose(self, argv: list[str], cwd: str, env: dict[str, str], timeout: float, on_lines: Optional[Callable[[list[str]], None]] = None, gated: bool = True) -> cmp.ComposeRunResult:
1300
+ """Runs the CLI (at most 5 compose processes at once besides the operations: more wait)."""
1301
+ if not gated:
1302
+ return await cmp.run_compose(argv, cwd, env, timeout, on_lines, self._compose_processes)
1303
+ async with self._gate():
1304
+ return await cmp.run_compose(argv, cwd, env, timeout, on_lines, self._compose_processes)
1305
+
1306
+ @staticmethod
1307
+ def _scrub(h: HostContext, text: str) -> str:
1308
+ """Compose text shown or logged never names the host's TLS files (the docker CLI can print them)."""
1309
+ c = h.client.connection
1310
+ for key in ("tlsCa", "tlsCert", "tlsKey"):
1311
+ if c.get(key):
1312
+ text = text.replace(c[key], "<tls file>")
1313
+ return text
1314
+
1315
+ def _assert_compose_host(self, name: str) -> None:
1316
+ """409 for a host compose may not change (``composeHosts``, default only ``local``)."""
1317
+ hosts = self.settings.compose_hosts if isinstance(self.settings.compose_hosts, list) else [LOCAL_HOST]
1318
+ if name not in hosts:
1319
+ raise DockerError(409, f"compose is not enabled for host {name}")
1320
+
1321
+ async def compose(self, host_name: Optional[str] = None) -> dict[str, Any]:
1322
+ """Whether the compose CLI answers (``version --short``, 5 s, cached for 60 s, one check at a time) and the roots it
1323
+ works under."""
1324
+ roots = self._compose_roots()
1325
+ if not roots:
1326
+ return {"available": False, "roots": roots, "error": COMPOSE_NO_ROOTS}
1327
+ h = self.host(host_name)
1328
+ hosts = self.settings.compose_hosts if isinstance(self.settings.compose_hosts, list) else [LOCAL_HOST]
1329
+ if h.name not in hosts:
1330
+ return {"available": False, "roots": roots, "error": f"compose is not enabled for host {h.name}"}
1331
+ key = json.dumps([self._compose_words(), h.name])
1332
+ cached = self._compose_checks.get(key)
1333
+ if cached is None or time.monotonic() - cached["at"] > COMPOSE_CHECK_CACHE_SECONDS:
1334
+ pending = self._compose_checking.get(key)
1335
+ if pending is None:
1336
+ async def check() -> None:
1337
+ try:
1338
+ argv, env = self._compose_invocation(h, ["version", "--short"])
1339
+ res = await self._run_compose(argv, os.getcwd(), env, 5)
1340
+ entry: dict[str, Any] = {"at": time.monotonic()}
1341
+ if res.spawn_error is not None or res.timed_out or res.exit_code != 0:
1342
+ entry["error"] = COMPOSE_NOT_FOUND if res.spawn_error is not None or res.timed_out else (self._scrub(h, res.lines[-1]) if res.lines else COMPOSE_NOT_FOUND)
1343
+ else:
1344
+ entry["version"] = res.lines[-1] if res.lines else ""
1345
+ self._compose_checks[key] = entry
1346
+ finally:
1347
+ self._compose_checking.pop(key, None)
1348
+
1349
+ pending = asyncio.ensure_future(check())
1350
+ self._compose_checking[key] = pending
1351
+ await asyncio.shield(pending)
1352
+ entry = self._compose_checks[key]
1353
+ if entry.get("error"):
1354
+ return {"available": False, "roots": roots, "error": entry["error"]}
1355
+ return {"available": True, "version": entry.get("version", ""), "roots": roots}
1356
+
1357
+ async def _assert_compose(self, host_name: Optional[str]) -> None:
1358
+ info = await self.compose(host_name)
1359
+ if not info["available"]:
1360
+ raise DockerError(409, info.get("error") or COMPOSE_NOT_FOUND)
1361
+
1362
+ def _compose_invocation(self, h: HostContext, args: list[str]) -> tuple[list[str], dict[str, str]]:
1363
+ """The CLI's words and the host's connection as docker's global flags (always, the default socket included, so the
1364
+ server's own docker context or ``DOCKER_HOST`` can never pick another engine), in a minimal environment."""
1365
+ words = self._compose_words()
1366
+ c = h.client.connection
1367
+ env = self._compose_env()
1368
+ if cmp.is_legacy_compose(words):
1369
+ # docker-compose has no global connection flags: DOCKER_HOST cannot carry separate TLS files
1370
+ if c["tls"]:
1371
+ raise DockerError(400, 'compose on a TLS host needs "docker compose"')
1372
+ env["DOCKER_HOST"] = c["tcp"] if c["tcp"] else f"unix://{c['unixPath']}"
1373
+ return [*words, *args], env
1374
+ flags = ["--host", c["tcp"] if c["tcp"] else f"unix://{c['unixPath']}"]
1375
+ if c["tls"]:
1376
+ flags.append("--tlsverify" if c["tlsVerify"] else "--tls")
1377
+ if c["tlsCa"]:
1378
+ flags += ["--tlscacert", c["tlsCa"]]
1379
+ if c["tlsCert"]:
1380
+ flags += ["--tlscert", c["tlsCert"]]
1381
+ if c["tlsKey"]:
1382
+ flags += ["--tlskey", c["tlsKey"]]
1383
+ # the global flags come right after the program (``docker --host x compose ...``)
1384
+ return [words[0], *flags, *words[1:], *args], env
1385
+
1386
+ @staticmethod
1387
+ def _assert_stack_name(name: Any) -> None:
1388
+ if not isinstance(name, str) or not cmp.STACK_NAME.match(name):
1389
+ raise DockerError(400, "invalid stack name")
1390
+
1391
+ async def _stack_containers_unfiltered(self, h: HostContext, name: str) -> list[dict[str, Any]]:
1392
+ """The containers of a stack as the engine lists them, hidden ones included (they decide what may be changed)."""
1393
+ return [c for c in await self._all_raw_containers(h) if (c.get("Labels") or {}).get(COMPOSE_PROJECT) == name]
1394
+
1395
+ def _assert_stack_changeable(self, name: str, raw: list[dict[str, Any]]) -> None:
1396
+ """409 when a container of the stack is protected or hidden: compose would change it."""
1397
+ protected = next((m for m in (self._map(c) for c in raw) if m["protected"]), None)
1398
+ if protected:
1399
+ raise DockerError(409, f"container {protected['name']} is protected")
1400
+ if any(self.is_hidden(container_name(c), c.get("Labels") or {}) for c in raw):
1401
+ raise DockerError(409, f"stack {name} has containers this plugin may not change")
1402
+
1403
+ def _reserve(self, host_name: Optional[str], name: str) -> str:
1404
+ """Reserves ``<host>/<stack>`` for one change (up, down, write, delete) with no wait between the check and the
1405
+ reservation: a second change meanwhile is 409. The caller releases it (``_busy_stacks.discard``)."""
1406
+ key = f"{(host_name or '').strip() or LOCAL_HOST}/{name}"
1407
+ if key in self._busy_stacks:
1408
+ raise DockerError(409, f"stack {name} is already being updated")
1409
+ self._busy_stacks.add(key)
1410
+ return key
1411
+
1412
+ @staticmethod
1413
+ def _seconds(value: float) -> str:
1414
+ return str(int(value)) if float(value).is_integer() else str(value)
1415
+
1416
+ async def up_stack(self, host_name: Optional[str], name: str, body: Optional[dict[str, Any]] = None, caller: Caller = None) -> dict[str, Any]:
1417
+ """Runs compose ``up`` of a stack in the background (kind ``stack-up``); 202 with the operation. The stack stays
1418
+ reserved until the operation ends."""
1419
+ key = self._reserve(host_name, name) if isinstance(name, str) else ""
1420
+ try:
1421
+ return await self._up_stack(host_name, name, body, caller, key)
1422
+ except BaseException:
1423
+ self._busy_stacks.discard(key)
1424
+ raise
1425
+
1426
+ async def _up_stack(self, host_name: Optional[str], name: str, body: Optional[dict[str, Any]], caller: Caller, key: str) -> dict[str, Any]:
1427
+ """Runs compose ``up`` of a stack in the background (kind ``stack-up``); 202 with the operation."""
1428
+ body = body or {}
1429
+ event = "docker.stack.up"
1430
+ await self._refusing(caller, host_name, event, "stack", name, f"deploy stack {name}", {"stack": name}, self.assert_writable)
1431
+ self._assert_stack_name(name)
1432
+ if body.get("pull") is not None and not isinstance(body.get("pull"), bool):
1433
+ raise DockerError(400, "pull must be true or false")
1434
+ if body.get("file") is not None and not isinstance(body.get("file"), str):
1435
+ raise DockerError(400, "file must be a path")
1436
+ h = self.host(host_name)
1437
+ self._assert_compose_host(h.name)
1438
+ await self._assert_compose(h.name)
1439
+ self._compose_invocation(h, []) # a host the CLI cannot reach (docker-compose on a TLS host) is 400 before anything runs
1440
+ raw = await self._stack_containers_unfiltered(h, name)
1441
+ await self._refusing(caller, h.name, event, "stack", name, f"deploy stack {name}", {"stack": name}, lambda: self._assert_stack_changeable(name, raw))
1442
+ mapped = [self._map(c) for c in raw if not self.is_hidden(container_name(c), c.get("Labels") or {})]
1443
+ file = self._compose_file_of(h, name, self._label_files(mapped))
1444
+ if not file and body.get("file") is not None:
1445
+ # ``file`` is only for a stack that has no file by the rule, and it must pass the same checks
1446
+ if not cmp.check_compose_file(body["file"], self._compose_roots(h)):
1447
+ raise DockerError(400, "file must be a compose file under composeRoots")
1448
+ file = body["file"]
1449
+ if not file:
1450
+ raise DockerError(400, f"stack {name} has no compose file under composeRoots")
1451
+ real = cmp.check_compose_file(file, self._compose_roots(h))
1452
+ if real is None:
1453
+ raise DockerError(400, f"stack {name} has no compose file under composeRoots")
1454
+ limit = self._compose_timeout if self._compose_timeout is not None else float(min(3600, max(10, float(self.settings.compose_timeout_seconds or 900))))
1455
+ pull = body.get("pull") is True
1456
+ argv, env = self._compose_invocation(h, [f"--project-name={name}", f"--file={real}", "up", "-d", "--remove-orphans", *(["--pull", "always"] if pull else [])])
1457
+
1458
+ def run(update: Callable[[dict[str, Any]], None]) -> Awaitable[Optional[str]]:
1459
+ async def go() -> Optional[str]:
1460
+ def on_lines(lines: list[str]) -> None:
1461
+ shown = [self._scrub(h, x) for x in lines]
1462
+ update({"log": shown, **({"message": shown[-1]} if shown else {})})
1463
+
1464
+ res = await self._run_compose(argv, os.path.dirname(real), env, limit, on_lines, gated=False)
1465
+ shown = [self._scrub(h, x) for x in res.lines]
1466
+ update({"log": shown})
1467
+ self._compose_outcome(res, f"compose did not finish in {self._seconds(limit)} s")
1468
+ return shown[-1] if shown else None
1469
+
1470
+ async def released() -> Optional[str]:
1471
+ try:
1472
+ return await self._audited(caller, h.name, event, "stack", name, f"deploy stack {name}", {"stack": name, "file": file, "pull": pull}, go)
1473
+ finally:
1474
+ self._busy_stacks.discard(key)
1475
+
1476
+ return released()
1477
+
1478
+ return await self._start_operation("stack-up", f"Deploy stack {name}", h.name, caller, run, key)
1479
+
1480
+ @staticmethod
1481
+ def _compose_outcome(res: cmp.ComposeRunResult, timeout_text: str) -> None:
1482
+ """Raises when a compose run failed: not started, over its time, or an exit code other than 0 (compose's own text is
1483
+ never part of the error: it can quote values)."""
1484
+ if res.spawn_error is not None:
1485
+ raise RuntimeError(COMPOSE_NOT_FOUND)
1486
+ if res.timed_out:
1487
+ raise RuntimeError(timeout_text)
1488
+ if res.exit_code != 0:
1489
+ raise RuntimeError(f"compose exited with code {res.exit_code}")
1490
+
1491
+ async def write_stack_compose(self, host_name: Optional[str], name: str, body: Optional[dict[str, Any]] = None, caller: Caller = None) -> dict[str, Any]:
1492
+ key = self._reserve(host_name, name)
1493
+ try:
1494
+ return await self._write_stack_compose(host_name, name, body, caller)
1495
+ finally:
1496
+ self._busy_stacks.discard(key)
1497
+
1498
+ async def _write_stack_compose(self, host_name: Optional[str], name: str, body: Optional[dict[str, Any]], caller: Caller) -> dict[str, Any]:
1499
+ """Writes the compose file of a stack (the existing one, or ``<first usable root>/<name>/compose.yaml``) after
1500
+ ``config --quiet`` accepted it."""
1501
+ event = "docker.stack.compose.write"
1502
+ details = f"write the compose file of stack {name}"
1503
+ await self._refusing(caller, host_name, event, "stack", name, details, {"stack": name}, self.assert_writable)
1504
+ self._assert_stack_name(name)
1505
+ content = (body or {}).get("content")
1506
+ if not isinstance(content, str) or not content.strip():
1507
+ raise DockerError(400, "content must be the compose file as text")
1508
+ if len(content.encode("utf-8")) > COMPOSE_FILE_CAP:
1509
+ raise DockerError(400, "the compose file is too large (256 KB at most)")
1510
+ h = self.host(host_name)
1511
+ self._assert_compose_host(h.name)
1512
+ await self._assert_compose(h.name)
1513
+ roots = self._compose_roots(h)
1514
+ visible = [c for c in (self._map(r) for r in await self._raw_containers(h)) if c["stack"] == name]
1515
+ existing = self._compose_file_of(h, name, self._label_files(visible))
1516
+ # a new stack goes under the first root that exists
1517
+ root = None if existing else next((r for r in roots if os.path.isdir(r)), None)
1518
+ if not existing and root is None:
1519
+ raise DockerError(409, COMPOSE_NO_ROOTS)
1520
+ target = existing if existing else os.path.join(root, name, "compose.yaml") # type: ignore[arg-type]
1521
+ folder = os.path.dirname(target)
1522
+
1523
+ async def write() -> None:
1524
+ created = False
1525
+ temp: Optional[str] = None
1526
+ try:
1527
+ if not existing:
1528
+ try:
1529
+ os.mkdir(folder)
1530
+ created = True
1531
+ except FileExistsError:
1532
+ pass
1533
+ except OSError as err:
1534
+ raise DockerError(500, f"cannot create the folder of stack {name}") from err
1535
+ # the folder and the target are never links, and the folder's real path is under a root
1536
+ if not cmp.is_plain_folder_under_root(folder, roots):
1537
+ raise DockerError(400, "the folder of the compose file is not a plain folder under composeRoots")
1538
+ mode = 0o644
1539
+ try:
1540
+ st = os.lstat(target)
1541
+ if stat.S_ISLNK(st.st_mode):
1542
+ raise DockerError(400, "the compose file is a symbolic link")
1543
+ mode = stat.S_IMODE(st.st_mode) # a replaced file keeps its permissions
1544
+ except FileNotFoundError:
1545
+ pass
1546
+ # the CLI is given the real path of the folder it works in
1547
+ real_folder = os.path.realpath(folder)
1548
+ temp = os.path.join(real_folder, f".qcli-{name}-{re.sub('[^a-z0-9]', '', self._new_id(), flags=re.IGNORECASE)[:12]}.yaml")
1549
+ fd = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), mode)
1550
+ try:
1551
+ os.write(fd, content.encode("utf-8"))
1552
+ os.fchmod(fd, mode)
1553
+ finally:
1554
+ os.close(fd)
1555
+ argv, env = self._compose_invocation(h, [f"--project-name={name}", f"--file={temp}", "config", "--quiet"])
1556
+ res = await self._run_compose(argv, real_folder, env, COMPOSE_CONFIG_SECONDS)
1557
+ if res.spawn_error is not None:
1558
+ raise DockerError(409, COMPOSE_NOT_FOUND)
1559
+ if res.timed_out:
1560
+ raise DockerError(504, f"compose config did not finish in {COMPOSE_CONFIG_SECONDS} s")
1561
+ if res.exit_code != 0:
1562
+ # the caller sees compose's message; the audit log only the exit code (the message can quote values)
1563
+ shown_text = self._scrub(h, res.text.strip())
1564
+ for x in {temp, os.path.join(folder, os.path.basename(temp)), os.path.join(real_folder, os.path.basename(temp))}:
1565
+ shown_text = shown_text.replace(x, "compose.yaml")
1566
+ err = DockerError(400, (shown_text or f"compose exited with code {res.exit_code}")[:2000])
1567
+ err.audit_message = f"compose exited with code {res.exit_code}" # type: ignore[attr-defined]
1568
+ raise err
1569
+ os.replace(temp, os.path.join(real_folder, os.path.basename(target)))
1570
+ temp = None
1571
+ except BaseException:
1572
+ if temp:
1573
+ try:
1574
+ os.unlink(temp)
1575
+ except OSError:
1576
+ pass
1577
+ # a folder this call made goes again when anything after it failed
1578
+ if created:
1579
+ try:
1580
+ os.rmdir(folder)
1581
+ except OSError:
1582
+ pass
1583
+ raise
1584
+
1585
+ await self._audited(caller, h.name, event, "stack", name, details, {"stack": name, "file": target}, write)
1586
+ result = await self.stack(host_name, name)
1587
+ return {"stack": result["stack"], "composeFile": result["composeFile"] or {"path": target, "content": content}}
1588
+
1589
+ async def delete_stack_compose(self, host_name: Optional[str], name: str, caller: Caller = None) -> dict[str, Any]:
1590
+ key = self._reserve(host_name, name)
1591
+ try:
1592
+ return await self._delete_stack_compose(host_name, name, caller)
1593
+ finally:
1594
+ self._busy_stacks.discard(key)
1595
+
1596
+ async def _delete_stack_compose(self, host_name: Optional[str], name: str, caller: Caller) -> dict[str, Any]:
1597
+ """Removes the compose file (not the folder) of a stack that has no containers."""
1598
+ event = "docker.stack.compose.remove"
1599
+ details = f"remove the compose file of stack {name}"
1600
+ await self._refusing(caller, host_name, event, "stack", name, details, {"stack": name}, self.assert_writable)
1601
+ self._assert_stack_name(name)
1602
+ h = self.host(host_name)
1603
+ self._assert_compose_host(h.name)
1604
+ await self._assert_compose(h.name)
1605
+ if await self._stack_containers_unfiltered(h, name):
1606
+ raise DockerError(409, f"stack {name} still has containers")
1607
+ file = cmp.find_root_compose_file(name, self._compose_roots(h))
1608
+ if not file:
1609
+ raise DockerError(404, f"stack {name} has no compose file under composeRoots")
1610
+
1611
+ async def remove() -> None:
1612
+ os.unlink(file)
1613
+
1614
+ await self._audited(caller, h.name, event, "stack", name, details, {"stack": name, "file": file}, remove)
1615
+ return {"ok": True}
1616
+
1617
+ async def _compose_down(self, h: HostContext, name: str, file: str, volumes: bool, caller: Caller) -> dict[str, Any]:
1618
+ key = self._reserve(h.name, name)
1619
+ try:
1620
+ return await self._compose_down_locked(h, name, file, volumes, caller)
1621
+ finally:
1622
+ self._busy_stacks.discard(key)
1623
+
1624
+ async def _compose_down_locked(self, h: HostContext, name: str, file: str, volumes: bool, caller: Caller) -> dict[str, Any]:
1625
+ """``compose down`` of a stack with a file; the answer lists what the engine no longer has (containers and networks of the project, before and after)."""
1626
+ event = "docker.stack.down"
1627
+ self._assert_stack_name(name)
1628
+ self._assert_compose_host(h.name)
1629
+ await self._assert_compose(h.name)
1630
+ raw = await self._stack_containers_unfiltered(h, name)
1631
+ await self._refusing(caller, h.name, event, "stack", name, f"take down stack {name}", {"stack": name}, lambda: self._assert_stack_changeable(name, raw))
1632
+ real = cmp.check_compose_file(file, self._compose_roots(h))
1633
+ if real is None:
1634
+ raise DockerError(400, f"stack {name} has no compose file under composeRoots")
1635
+ argv, env = self._compose_invocation(h, [f"--project-name={name}", f"--file={real}", "down", *(["--volumes"] if volumes else [])])
1636
+
1637
+ async def lists() -> dict[str, list[str]]:
1638
+ networks = await h.client.json("GET", "/networks", query={"filters": json.dumps({"label": [f"{COMPOSE_PROJECT}={name}"]}, separators=(",", ":"))}) or []
1639
+ return {
1640
+ "containers": [container_name(c) for c in await self._stack_containers_unfiltered(h, name)],
1641
+ "networks": [js_str(n.get("Name")) for n in networks if js_str(n.get("Name")) not in BUILTIN_NETWORKS],
1642
+ }
1643
+
1644
+ async def run() -> dict[str, Any]:
1645
+ before = await lists()
1646
+ limit = self._compose_down_timeout if self._compose_down_timeout is not None else COMPOSE_DOWN_SECONDS
1647
+ res = await self._run_compose(argv, os.path.dirname(real), env, limit)
1648
+ if res.spawn_error is not None:
1649
+ raise DockerError(409, COMPOSE_NOT_FOUND)
1650
+ if res.timed_out:
1651
+ raise DockerError(504, f"compose down did not finish in {self._seconds(limit)} s")
1652
+ after = await lists()
1653
+ errors = [] if res.exit_code == 0 else [f"compose exited with code {res.exit_code}"]
1654
+ return {
1655
+ "ok": len(errors) == 0,
1656
+ "removedContainers": sorted(c for c in before["containers"] if c not in after["containers"]),
1657
+ "removedNetworks": sorted(n for n in before["networks"] if n not in after["networks"]),
1658
+ "errors": errors,
1659
+ }
1660
+
1661
+ return await self._audited(
1662
+ caller, h.name, event, "stack", name, f"take down stack {name}", {"stack": name, "containers": len(raw), "compose": True, "volumes": volumes}, run,
1663
+ lambda r: {"removedContainers": len(r["removedContainers"]), "removedNetworks": len(r["removedNetworks"]), "errors": len(r["errors"])},
1664
+ )
1665
+
1666
+ def dispose(self) -> None:
1667
+ """Kills the compose processes that run now (the server stops)."""
1668
+ for proc in list(self._compose_processes):
1669
+ cmp._kill_group(proc)
1670
+ self._compose_processes.clear()
1671
+
1672
+ async def stack_action(self, host_name: Optional[str], name: str, action: str, caller: Caller = None) -> dict[str, Any]:
1673
+ await self._refusing(
1674
+ caller, host_name, f"docker.stack.{action}", "stack", name, f"{action} stack {name}", {"stack": name}, self.assert_writable,
1675
+ )
1676
+ h = self.host(host_name)
1677
+ containers = await self._stack_containers(h, name)
1678
+
1679
+ async def one(c: dict[str, Any]) -> dict[str, Any]:
1680
+ if c["protected"]:
1681
+ return {"container": c["name"], "ok": False, "error": f"container {c['name']} is protected"}
1682
+ try:
1683
+ await self._run_action(h, c["id"], action)
1684
+ return {"container": c["name"], "ok": True}
1685
+ except Exception as err: # noqa: BLE001 - reported for this container
1686
+ return {"container": c["name"], "ok": False, "error": _message(err)}
1687
+
1688
+ async def run() -> dict[str, Any]:
1689
+ results = await asyncio.gather(*(one(c) for c in containers))
1690
+ return {"ok": all(r["ok"] for r in results), "results": list(results)}
1691
+
1692
+ return await self._audited(
1693
+ caller, h.name, f"docker.stack.{action}", "stack", name, f"{action} stack {name}", {"stack": name, "containers": len(containers)}, run,
1694
+ lambda r: {"failed": len([x for x in r["results"] if not x["ok"]])},
1695
+ )
1696
+
1697
+ async def stack_pull(self, host_name: Optional[str], name: str, caller: Caller = None) -> dict[str, Any]:
1698
+ await self._refusing(
1699
+ caller, host_name, "docker.stack.pull", "stack", name, f"pull the images of stack {name}", {"stack": name}, self.assert_writable,
1700
+ )
1701
+ h = self.host(host_name)
1702
+ containers = await self._stack_containers(h, name)
1703
+ images = sorted({c["image"] for c in containers if c["image"] and not re.match(r"^(sha256:)?[0-9a-f]{12,64}$", c["image"])})
1704
+
1705
+ def run(update: Callable[[dict[str, Any]], None]) -> Awaitable[Optional[str]]:
1706
+ async def pull_all() -> str:
1707
+ update({"progress": {"current": 0, "total": len(images)}})
1708
+ for i, image in enumerate(images):
1709
+ update({"message": f"pulling {image} ({i + 1}/{len(images)})"})
1710
+ await self._pull_into(h, image, lambda _patch: None)
1711
+ update({"progress": {"current": i + 1, "total": len(images)}})
1712
+ return f"pulled {len(images)} image(s)" if images else "no image to pull"
1713
+
1714
+ return self._audited(
1715
+ caller, h.name, "docker.stack.pull", "stack", name, f"pull the images of stack {name}", {"stack": name, "images": images}, pull_all,
1716
+ )
1717
+
1718
+ return await self._start_operation("stack-pull", f"Pull stack {name}", h.name, caller, run)
1719
+
1720
+ async def stack_down(self, host_name: Optional[str], name: str, caller: Caller = None, volumes: Any = None) -> dict[str, Any]:
1721
+ await self._refusing(
1722
+ caller, host_name, "docker.stack.down", "stack", name, f"take down stack {name}", {"stack": name}, self.assert_writable,
1723
+ )
1724
+ if volumes is not None and not isinstance(volumes, bool):
1725
+ raise DockerError(400, "volumes must be true or false")
1726
+ h = self.host(host_name)
1727
+ # a stack with a compose file goes down through the compose CLI (and ``volumes`` removes its volumes)
1728
+ if self._compose_roots(h):
1729
+ visible = [c for c in (self._map(r) for r in await self._raw_containers(h)) if c["stack"] == name]
1730
+ file = self._compose_file_of(h, name, self._label_files(visible))
1731
+ if file:
1732
+ return await self._compose_down(h, name, file, volumes is True, caller)
1733
+ if volumes is True:
1734
+ raise DockerError(400, "volumes needs a compose file")
1735
+ containers = await self._stack_containers(h, name)
1736
+ blocked = next((c for c in containers if c["protected"]), None)
1737
+
1738
+ def check_protected() -> None:
1739
+ if blocked:
1740
+ raise DockerError(409, f"container {blocked['name']} is protected")
1741
+
1742
+ await self._refusing(caller, h.name, "docker.stack.down", "stack", name, f"take down stack {name}", {"stack": name}, check_protected)
1743
+ # Hidden containers are not removed and cannot be told about: with some, the stack's networks stay too
1744
+ has_hidden = any(
1745
+ (c.get("Labels") or {}).get(COMPOSE_PROJECT) == name and self.is_hidden(container_name(c), c.get("Labels") or {})
1746
+ for c in await self._all_raw_containers(h)
1747
+ )
1748
+
1749
+ async def run() -> dict[str, Any]:
1750
+ removed_containers: list[str] = []
1751
+ removed_networks: list[str] = []
1752
+ errors: list[str] = []
1753
+ for c in containers:
1754
+ try:
1755
+ if c["state"] in ("running", "paused", "restarting"):
1756
+ if c["state"] == "paused":
1757
+ await self._run_action(h, c["id"], "unpause")
1758
+ await self._run_action(h, c["id"], "stop")
1759
+ await h.client.request("DELETE", f"/containers/{c['id']}", query={"force": 0, "v": 0})
1760
+ removed_containers.append(c["name"])
1761
+ except Exception as err: # noqa: BLE001
1762
+ errors.append(f"container {c['name']}: {_message(err)}")
1763
+ networks = [] if has_hidden else (await h.client.json(
1764
+ "GET", "/networks", query={"filters": json.dumps({"label": [f"{COMPOSE_PROJECT}={name}"]}, separators=(",", ":"))},
1765
+ ) or [])
1766
+ for n in _sorted([x for x in networks if x.get("Name") not in BUILTIN_NETWORKS], lambda x: js_str(x.get("Name"))):
1767
+ try:
1768
+ await h.client.request("DELETE", f"/networks/{n['Id']}")
1769
+ removed_networks.append(js_str(n["Name"]))
1770
+ except Exception as err: # noqa: BLE001
1771
+ errors.append(f"network {n.get('Name')}: {_message(err)}")
1772
+ return {"ok": len(errors) == 0, "removedContainers": removed_containers, "removedNetworks": removed_networks, "errors": errors}
1773
+
1774
+ return await self._audited(
1775
+ caller, h.name, "docker.stack.down", "stack", name, f"take down stack {name}", {"stack": name, "containers": len(containers)}, run,
1776
+ lambda r: {"removedContainers": len(r["removedContainers"]), "removedNetworks": len(r["removedNetworks"]), "errors": len(r["errors"])},
1777
+ )
1778
+
1779
+ # -- volumes ----------------------------------------------------------------------------------------------------
1780
+
1781
+ @staticmethod
1782
+ def _map_volume(raw: dict[str, Any], in_use: set[str]) -> dict[str, Any]:
1783
+ source = raw.get("Labels") or {}
1784
+ labels = {k: js_str(source[k]) for k in sorted(source)}
1785
+ return {
1786
+ "name": js_str(raw["Name"]),
1787
+ "driver": text_of(raw.get("Driver")),
1788
+ "mountpoint": text_of(raw.get("Mountpoint")),
1789
+ "createdAt": iso_seconds(raw.get("CreatedAt")),
1790
+ "labels": labels,
1791
+ "stack": labels.get(COMPOSE_PROJECT),
1792
+ "inUse": js_str(raw["Name"]) in in_use,
1793
+ }
1794
+
1795
+ @staticmethod
1796
+ async def _volumes_in_use(h: HostContext) -> set[str]:
1797
+ """Volumes used by any container, hidden ones included (so a volume of a hidden container never looks unused)."""
1798
+ everything = await h.client.json("GET", "/containers/json", query={"all": 1}) or []
1799
+ used: set[str] = set()
1800
+ for c in everything:
1801
+ for m in c.get("Mounts") or []:
1802
+ if m.get("Type") == "volume" and m.get("Name"):
1803
+ used.add(js_str(m["Name"]))
1804
+ return used
1805
+
1806
+ async def volumes(self, host_name: Optional[str] = None) -> dict[str, Any]:
1807
+ h = self.host(host_name)
1808
+ res, used = await asyncio.gather(h.client.json("GET", "/volumes"), self._volumes_in_use(h))
1809
+ volumes = [self._map_volume(v, used) for v in (res or {}).get("Volumes") or []]
1810
+ return {"host": h.name, "volumes": _sorted(volumes, lambda v: v["name"])}
1811
+
1812
+ async def volume(self, host_name: Optional[str], name: str) -> dict[str, Any]:
1813
+ h = self.host(host_name)
1814
+ assert_path_name("volume", name)
1815
+ raw, used = await asyncio.gather(h.client.json("GET", f"/volumes/{encode_component(name)}"), self._volumes_in_use(h))
1816
+ return {"host": h.name, "volume": self._map_volume(raw, used)}
1817
+
1818
+ async def create_volume(self, host_name: Optional[str], body: dict[str, Any], caller: Caller = None) -> dict[str, Any]:
1819
+ name = body.get("name") if isinstance(body, dict) else None
1820
+ if not isinstance(name, str) or not _RESOURCE_NAME.match(name):
1821
+ raise DockerError(400, "name must start with a letter or digit and contain only letters, digits, _ . -")
1822
+ driver = body.get("driver")
1823
+ if driver is not None and (not isinstance(driver, str) or not driver.strip() or len(driver) > 64):
1824
+ raise DockerError(400, "driver must be a driver name")
1825
+ labels = None
1826
+ if body.get("labels") is not None:
1827
+ raw_labels = body["labels"]
1828
+ if not isinstance(raw_labels, dict) or any(not isinstance(v, str) for v in raw_labels.values()):
1829
+ raise DockerError(400, "labels must be an object of strings")
1830
+ labels = raw_labels
1831
+ await self._refusing(
1832
+ caller, host_name, "docker.volume.create", "volume", name, f"create volume {name}", {"volume": name}, self.assert_writable,
1833
+ )
1834
+ h = self.host(host_name)
1835
+ request_body: dict[str, Any] = {"Name": name}
1836
+ if driver:
1837
+ request_body["Driver"] = driver
1838
+ if labels:
1839
+ request_body["Labels"] = labels
1840
+ properties: dict[str, Any] = {"volume": name}
1841
+ if driver:
1842
+ properties["driver"] = driver
1843
+ raw = await self._audited(
1844
+ caller, h.name, "docker.volume.create", "volume", name, f"create volume {name}", properties,
1845
+ lambda: h.client.json("POST", "/volumes/create", body=request_body),
1846
+ )
1847
+ return {"volume": self._map_volume(raw, set())}
1848
+
1849
+ async def remove_volume(self, host_name: Optional[str], name: str, *, force: Optional[bool] = None, caller: Caller = None) -> dict[str, Any]:
1850
+ await self._refusing(
1851
+ caller, host_name, "docker.volume.remove", "volume", name, f"remove volume {name}", {"volume": name}, self.assert_writable,
1852
+ )
1853
+ h = self.host(host_name)
1854
+ assert_path_name("volume", name)
1855
+ await self._audited(
1856
+ caller, h.name, "docker.volume.remove", "volume", name, f"remove volume {name}", {"volume": name, "force": force is True},
1857
+ lambda: h.client.request("DELETE", f"/volumes/{encode_component(name)}", query={"force": 1 if force else 0}),
1858
+ )
1859
+ return {"ok": True}
1860
+
1861
+ async def prune_volumes(self, host_name: Optional[str] = None, caller: Caller = None) -> dict[str, Any]:
1862
+ await self._refusing(
1863
+ caller, host_name, "docker.volumes.prune", "volumes", "unused", "prune unused volumes", {}, self.assert_writable,
1864
+ )
1865
+ h = self.host(host_name)
1866
+
1867
+ async def run() -> dict[str, Any]:
1868
+ try:
1869
+ res = await h.client.json("POST", "/volumes/prune", query={"filters": json.dumps({"all": ["true"]}, separators=(",", ":"))}, timeout=120)
1870
+ except DockerError as err:
1871
+ # engines before API 1.42 do not know the `all` filter (they prune every unused volume anyway)
1872
+ if err.status != 400:
1873
+ raise
1874
+ res = await h.client.json("POST", "/volumes/prune", timeout=120)
1875
+ res = res or {}
1876
+ return {"removed": [js_str(v) for v in res.get("VolumesDeleted") or []], "reclaimedBytes": number_of(res.get("SpaceReclaimed"), 0)}
1877
+
1878
+ return await self._audited(
1879
+ caller, h.name, "docker.volumes.prune", "volumes", "unused", "prune unused volumes", {}, run,
1880
+ lambda r: {"removed": len(r["removed"]), "reclaimedBytes": r["reclaimedBytes"]},
1881
+ )
1882
+
1883
+ # -- networks ---------------------------------------------------------------------------------------------------
1884
+
1885
+ @staticmethod
1886
+ def _map_network(raw: dict[str, Any], containers: list[dict[str, Any]]) -> dict[str, Any]:
1887
+ labels = raw.get("Labels") or {}
1888
+ count = len([
1889
+ c for c in containers
1890
+ if any(n.get("NetworkID") == raw.get("Id") for n in ((c.get("NetworkSettings") or {}).get("Networks") or {}).values())
1891
+ ])
1892
+ return {
1893
+ "id": js_str(raw["Id"]),
1894
+ "shortId": js_str(raw["Id"])[:12],
1895
+ "name": js_str(raw["Name"]),
1896
+ "driver": text_of(raw.get("Driver")),
1897
+ "scope": text_of(raw.get("Scope")),
1898
+ "internal": raw.get("Internal") is True,
1899
+ "createdAt": iso_seconds(raw.get("Created")),
1900
+ "subnets": [s for s in (text_of(c.get("Subnet")) for c in (raw.get("IPAM") or {}).get("Config") or []) if s],
1901
+ "containers": count,
1902
+ "stack": labels.get(COMPOSE_PROJECT),
1903
+ "builtin": js_str(raw["Name"]) in BUILTIN_NETWORKS,
1904
+ }
1905
+
1906
+ async def networks(self, host_name: Optional[str] = None) -> dict[str, Any]:
1907
+ h = self.host(host_name)
1908
+ raw, containers = await asyncio.gather(h.client.json("GET", "/networks"), self._raw_containers(h))
1909
+ networks = [self._map_network(n, containers) for n in raw or []]
1910
+ return {"host": h.name, "networks": _sorted(networks, lambda n: n["name"])}
1911
+
1912
+ async def network(self, host_name: Optional[str], network_id: str) -> dict[str, Any]:
1913
+ h = self.host(host_name)
1914
+ assert_path_name("network", network_id)
1915
+ raw, containers = await asyncio.gather(h.client.json("GET", f"/networks/{encode_component(network_id)}"), self._raw_containers(h))
1916
+ by_id = {c["Id"]: c for c in containers}
1917
+ attached = [
1918
+ {"id": cid, "name": text_of(c.get("Name") if c.get("Name") is not None else container_name(by_id[cid])), "ip": re.sub(r"/\d+$", "", text_of(c.get("IPv4Address")))}
1919
+ for cid, c in (raw.get("Containers") or {}).items() if cid in by_id
1920
+ ]
1921
+ return {"host": h.name, "network": self._map_network(raw, containers), "containers": _sorted(attached, lambda c: c["name"])}
1922
+
1923
+ async def create_network(self, host_name: Optional[str], body: dict[str, Any], caller: Caller = None) -> dict[str, Any]:
1924
+ name = body.get("name") if isinstance(body, dict) else None
1925
+ if not isinstance(name, str) or not _RESOURCE_NAME.match(name):
1926
+ raise DockerError(400, "name must start with a letter or digit and contain only letters, digits, _ . -")
1927
+ driver = body.get("driver")
1928
+ if driver is not None and (not isinstance(driver, str) or not driver.strip() or len(driver) > 64):
1929
+ raise DockerError(400, "driver must be a driver name")
1930
+ internal = body.get("internal")
1931
+ if internal is not None and not isinstance(internal, bool):
1932
+ raise DockerError(400, "internal must be true or false")
1933
+ subnet = body.get("subnet")
1934
+ if subnet is not None and (not isinstance(subnet, str) or not re.match(r"^[0-9a-fA-F:.]+/\d{1,3}$", subnet)):
1935
+ raise DockerError(400, "subnet must be a CIDR, for example 10.20.0.0/24")
1936
+ await self._refusing(
1937
+ caller, host_name, "docker.network.create", "network", name, f"create network {name}", {"network": name}, self.assert_writable,
1938
+ )
1939
+ h = self.host(host_name)
1940
+ request_body: dict[str, Any] = {"Name": name, "Driver": driver if driver is not None else "bridge", "Internal": internal is True}
1941
+ if subnet:
1942
+ request_body["IPAM"] = {"Config": [{"Subnet": subnet}]}
1943
+ properties: dict[str, Any] = {"network": name, "driver": driver if driver is not None else "bridge", "internal": internal is True}
1944
+ if subnet:
1945
+ properties["subnet"] = subnet
1946
+ created = await self._audited(
1947
+ caller, h.name, "docker.network.create", "network", name, f"create network {name}", properties,
1948
+ lambda: h.client.json("POST", "/networks/create", body=request_body),
1949
+ )
1950
+ return {"network": (await self.network(h.name, created["Id"]))["network"]}
1951
+
1952
+ async def remove_network(self, host_name: Optional[str], network_id: str, caller: Caller = None) -> dict[str, Any]:
1953
+ await self._refusing(
1954
+ caller, host_name, "docker.network.remove", "network", network_id, f"remove network {network_id}", {"network": network_id}, self.assert_writable,
1955
+ )
1956
+ h = self.host(host_name)
1957
+ assert_path_name("network", network_id)
1958
+ raw = await h.client.json("GET", f"/networks/{encode_component(network_id)}")
1959
+ name = js_str(raw["Name"])
1960
+ if name in BUILTIN_NETWORKS:
1961
+ raise DockerError(409, f"{name} is a built-in network")
1962
+ await self._audited(
1963
+ caller, h.name, "docker.network.remove", "network", name, f"remove network {name}", {"network": name},
1964
+ lambda: h.client.request("DELETE", f"/networks/{raw['Id']}"),
1965
+ )
1966
+ return {"ok": True}
1967
+
1968
+ async def prune_networks(self, host_name: Optional[str] = None, caller: Caller = None) -> dict[str, Any]:
1969
+ await self._refusing(
1970
+ caller, host_name, "docker.networks.prune", "networks", "unused", "prune unused networks", {}, self.assert_writable,
1971
+ )
1972
+ h = self.host(host_name)
1973
+
1974
+ async def run() -> dict[str, Any]:
1975
+ # Not the engine's prune: it would remove the networks of hidden and protected containers too
1976
+ networks, containers = await asyncio.gather(h.client.json("GET", "/networks"), self._all_raw_containers(h))
1977
+ in_use: set[str] = set()
1978
+ kept: set[str] = set()
1979
+ for c in containers:
1980
+ nets = (c.get("NetworkSettings") or {}).get("Networks") or {}
1981
+ names = list(nets.keys())
1982
+ mode = (c.get("HostConfig") or {}).get("NetworkMode")
1983
+ if mode:
1984
+ names.append(js_str(mode))
1985
+ ids = [js_str((n or {}).get("NetworkID") or "") for n in nets.values()]
1986
+ labels = c.get("Labels") or {}
1987
+ guarded = self.is_hidden(container_name(c), labels) or self.is_protected(container_name(c), labels)
1988
+ for k in names + ids:
1989
+ if guarded:
1990
+ kept.add(k)
1991
+ if c.get("State") in ("running", "paused", "restarting"):
1992
+ in_use.add(k)
1993
+ removed: list[str] = []
1994
+ for n in _sorted([x for x in (networks or []) if js_str(x.get("Name")) not in BUILTIN_NETWORKS], lambda x: js_str(x.get("Name"))):
1995
+ if any(k in in_use or k in kept for k in (js_str(n.get("Name")), js_str(n.get("Id")))):
1996
+ continue
1997
+ try:
1998
+ await h.client.request("DELETE", f"/networks/{n['Id']}")
1999
+ removed.append(js_str(n["Name"]))
2000
+ except Exception as err: # noqa: BLE001
2001
+ if not isinstance(err, DockerError) or err.status != 404:
2002
+ self._log.warning("docker: prune skipped network %s: %s", n.get("Name"), _message(err))
2003
+ return {"removed": removed}
2004
+
2005
+ return await self._audited(
2006
+ caller, h.name, "docker.networks.prune", "networks", "unused", "prune unused networks", {}, run, lambda r: {"removed": len(r["removed"])},
2007
+ )