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.
- qodalis_cli_docker/__init__.py +44 -0
- qodalis_cli_docker/builder.py +196 -0
- qodalis_cli_docker/commands.py +1434 -0
- qodalis_cli_docker/compose.py +319 -0
- qodalis_cli_docker/console/extension.css +32 -0
- qodalis_cli_docker/console/extension.js +89 -0
- qodalis_cli_docker/console_page.py +28 -0
- qodalis_cli_docker/controller.py +309 -0
- qodalis_cli_docker/engine.py +482 -0
- qodalis_cli_docker/exec_socket.py +246 -0
- qodalis_cli_docker/mcp_tools.py +149 -0
- qodalis_cli_docker/plugin.py +36 -0
- qodalis_cli_docker/service.py +2007 -0
- qodalis_cli_docker/settings.py +172 -0
- qodalis_cli_docker/shapes.py +317 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/METADATA +300 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/RECORD +20 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/WHEEL +4 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/entry_points.txt +2 -0
- qodalis_cli_server_plugin_docker-1.0.0b39.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"""The settings of the plugin (config provider ``docker``, section ``settings``), read on every call."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from typing import Any, Callable, Optional
|
|
7
|
+
|
|
8
|
+
from qodalis_cli_server_abstractions.config import CliConfigSettingDefinition, CliConfigValidation
|
|
9
|
+
|
|
10
|
+
from .engine import DockerHostConfig
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def docker_settings() -> list[CliConfigSettingDefinition]:
|
|
14
|
+
"""The settings of the contract (code options of the same keys are their defaults)."""
|
|
15
|
+
return [
|
|
16
|
+
CliConfigSettingDefinition(
|
|
17
|
+
key="endpoint", label="Endpoint", type="string", required=True,
|
|
18
|
+
description="The default host: unix:///var/run/docker.sock, tcp://host:2375, tcp://host:2376 (TLS) or "
|
|
19
|
+
"https://host:2376. The socket is root-equivalent, so there is no default.",
|
|
20
|
+
validation=CliConfigValidation(max=500),
|
|
21
|
+
),
|
|
22
|
+
CliConfigSettingDefinition(key="tlsCa", label="TLS CA file", description="Path of the PEM file of the CA of the default host",
|
|
23
|
+
type="string", validation=CliConfigValidation(max=500)),
|
|
24
|
+
CliConfigSettingDefinition(key="tlsCert", label="TLS certificate file", description="Path of the PEM client certificate of the default host",
|
|
25
|
+
type="string", validation=CliConfigValidation(max=500)),
|
|
26
|
+
CliConfigSettingDefinition(key="tlsKey", label="TLS key file", description="Path of the PEM client key of the default host",
|
|
27
|
+
type="string", validation=CliConfigValidation(max=500)),
|
|
28
|
+
CliConfigSettingDefinition(key="tlsVerify", label="Verify the certificate", description="Verify the certificate of the engine",
|
|
29
|
+
type="boolean", default=True),
|
|
30
|
+
CliConfigSettingDefinition(
|
|
31
|
+
key="hosts", label="More hosts", type="json", default={},
|
|
32
|
+
description='Other hosts as JSON: { "<name>": { "endpoint": "...", "tlsCa": "...", "tlsCert": "...", "tlsKey": "...", '
|
|
33
|
+
'"tlsVerify": true } }; names are a-z, 0-9 and -, up to 32 characters, and local is the default host',
|
|
34
|
+
),
|
|
35
|
+
CliConfigSettingDefinition(key="readOnly", label="Read only", description="Refuse every change (actions, pulls, exec, removals)",
|
|
36
|
+
type="boolean", default=False),
|
|
37
|
+
CliConfigSettingDefinition(
|
|
38
|
+
key="hide", label="Hidden containers", type="string[]", default=[],
|
|
39
|
+
description="Containers nobody sees: names with * wildcards (postgres*) or label:<key>[=<value>]",
|
|
40
|
+
),
|
|
41
|
+
CliConfigSettingDefinition(
|
|
42
|
+
key="protect", label="Protected containers", type="string[]", default=[],
|
|
43
|
+
description="Containers that can be read but not changed: names with * wildcards or label:<key>[=<value>]",
|
|
44
|
+
),
|
|
45
|
+
CliConfigSettingDefinition(
|
|
46
|
+
key="composeRoots", label="Compose folders", type="string[]", default=[],
|
|
47
|
+
description="Folders whose compose files may be shown on a stack (absolute paths); empty: no compose file is ever read",
|
|
48
|
+
),
|
|
49
|
+
CliConfigSettingDefinition(
|
|
50
|
+
key="allowUnprotected", label="Allow unprotected callers", type="boolean", default=False,
|
|
51
|
+
description="Serve callers that are not signed in (a server without the users plugin). The Docker socket is "
|
|
52
|
+
"root-equivalent: leave it off unless the server is not reachable by anyone else",
|
|
53
|
+
),
|
|
54
|
+
CliConfigSettingDefinition(
|
|
55
|
+
key="composeCommand", label="Compose command", type="string", default="docker compose", validation=CliConfigValidation(max=500),
|
|
56
|
+
description="The compose CLI, words split like a shell line and run without a shell: docker compose (default) or "
|
|
57
|
+
"docker-compose. It must be installed on the machine the server runs on",
|
|
58
|
+
),
|
|
59
|
+
CliConfigSettingDefinition(
|
|
60
|
+
key="composeHosts", label="Compose hosts", type="string[]", default=["local"],
|
|
61
|
+
description="The hosts compose may change (default: local only). Compose reads env_file, build contexts, file secrets and includes from "
|
|
62
|
+
"the server's disk and sends them to the engine, so other hosts are off unless listed",
|
|
63
|
+
),
|
|
64
|
+
CliConfigSettingDefinition(
|
|
65
|
+
key="composeEnv", label="Compose environment", type="string[]", default=[],
|
|
66
|
+
description="Names of the server's environment variables the compose CLI may see (for ${VAR} in compose files); "
|
|
67
|
+
"nothing else of the server's environment is passed, and names starting with DOCKER_ or COMPOSE_ are ignored",
|
|
68
|
+
),
|
|
69
|
+
CliConfigSettingDefinition(
|
|
70
|
+
key="composeTimeoutSeconds", label="Compose time limit (seconds)", type="number", default=900,
|
|
71
|
+
description="Time limit of one compose up (down has 120 s)", validation=CliConfigValidation(min=10, max=3600),
|
|
72
|
+
),
|
|
73
|
+
CliConfigSettingDefinition(
|
|
74
|
+
key="timeoutSeconds", label="Timeout (seconds)", type="number", default=15,
|
|
75
|
+
description="Timeout of one Engine API call (not of streams, pulls or exec)",
|
|
76
|
+
validation=CliConfigValidation(min=1, max=120),
|
|
77
|
+
),
|
|
78
|
+
]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class DockerSettings:
|
|
82
|
+
"""The settings of the plugin, read on every call (tests change the attributes of one)."""
|
|
83
|
+
|
|
84
|
+
def __init__(
|
|
85
|
+
self, endpoint: str = "", tls_ca: Optional[str] = None, tls_cert: Optional[str] = None, tls_key: Optional[str] = None,
|
|
86
|
+
tls_verify: bool = True, hosts: Optional[dict[str, Any]] = None, read_only: bool = False,
|
|
87
|
+
hide: Optional[list[str]] = None, protect: Optional[list[str]] = None, timeout_seconds: float = 15,
|
|
88
|
+
compose_roots: Optional[list[str]] = None, allow_unprotected: bool = False, compose_command: str = "docker compose",
|
|
89
|
+
compose_timeout_seconds: float = 900, compose_hosts: Optional[list[str]] = None, compose_env: Optional[list[str]] = None,
|
|
90
|
+
) -> None:
|
|
91
|
+
self.endpoint = endpoint
|
|
92
|
+
self.tls_ca = tls_ca
|
|
93
|
+
self.tls_cert = tls_cert
|
|
94
|
+
self.tls_key = tls_key
|
|
95
|
+
self.tls_verify = tls_verify
|
|
96
|
+
#: ``{ "<name>": { "endpoint": ..., "tlsCa": ..., "tlsCert": ..., "tlsKey": ..., "tlsVerify": ... } }``.
|
|
97
|
+
self.hosts: dict[str, Any] = hosts if hosts is not None else {}
|
|
98
|
+
self.read_only = read_only
|
|
99
|
+
self.hide: list[str] = hide if hide is not None else []
|
|
100
|
+
self.protect: list[str] = protect if protect is not None else []
|
|
101
|
+
self.timeout_seconds = timeout_seconds
|
|
102
|
+
#: Folders whose compose files may be shown (empty: no compose file is ever read).
|
|
103
|
+
self.compose_roots: list[str] = compose_roots if compose_roots is not None else []
|
|
104
|
+
#: Serve callers that are not signed in.
|
|
105
|
+
self.allow_unprotected = allow_unprotected
|
|
106
|
+
#: The compose CLI (words split like a shell line, run without a shell).
|
|
107
|
+
self.compose_command = compose_command
|
|
108
|
+
#: Time limit of one ``up`` in seconds (10-3600).
|
|
109
|
+
self.compose_timeout_seconds = compose_timeout_seconds
|
|
110
|
+
#: The hosts compose may change.
|
|
111
|
+
self.compose_hosts: list[str] = compose_hosts if compose_hosts is not None else ["local"]
|
|
112
|
+
#: Names of the server's environment variables the compose CLI may see.
|
|
113
|
+
self.compose_env: list[str] = compose_env if compose_env is not None else []
|
|
114
|
+
|
|
115
|
+
def __repr__(self) -> str: # never shows key paths
|
|
116
|
+
return f"DockerSettings(endpoint={self.endpoint!r}, read_only={self.read_only!r})"
|
|
117
|
+
|
|
118
|
+
def host_config(self) -> DockerHostConfig:
|
|
119
|
+
return DockerHostConfig(
|
|
120
|
+
endpoint=self.endpoint.strip(), tls_ca=self.tls_ca or None, tls_cert=self.tls_cert or None,
|
|
121
|
+
tls_key=self.tls_key or None, tls_verify=self.tls_verify is not False,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _text(value: Any) -> str:
|
|
126
|
+
return value.strip() if isinstance(value, str) else ""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _list(value: Any) -> list[str]:
|
|
130
|
+
return [s for s in (str(v).strip() for v in value) if s] if isinstance(value, (list, tuple)) else []
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def read_docker_settings(value: Callable[[str], Any]) -> DockerSettings:
|
|
134
|
+
"""The plugin's settings from a provider's ``value("settings", key)``, read on every call."""
|
|
135
|
+
hosts = value("hosts")
|
|
136
|
+
parsed: Any = hosts
|
|
137
|
+
if isinstance(hosts, str):
|
|
138
|
+
try:
|
|
139
|
+
parsed = json.loads(hosts)
|
|
140
|
+
except ValueError:
|
|
141
|
+
parsed = {}
|
|
142
|
+
try:
|
|
143
|
+
timeout = float(value("timeoutSeconds"))
|
|
144
|
+
except (TypeError, ValueError):
|
|
145
|
+
timeout = 15.0
|
|
146
|
+
if timeout != timeout or timeout < 1:
|
|
147
|
+
timeout = 15.0
|
|
148
|
+
timeout = min(120.0, timeout)
|
|
149
|
+
try:
|
|
150
|
+
compose_timeout = float(value("composeTimeoutSeconds"))
|
|
151
|
+
except (TypeError, ValueError):
|
|
152
|
+
compose_timeout = 900.0
|
|
153
|
+
compose_timeout = min(3600.0, compose_timeout) if compose_timeout == compose_timeout and compose_timeout >= 10 else 900.0
|
|
154
|
+
raw_hosts = value("composeHosts")
|
|
155
|
+
return DockerSettings(
|
|
156
|
+
endpoint=_text(value("endpoint")),
|
|
157
|
+
tls_ca=_text(value("tlsCa")) or None,
|
|
158
|
+
tls_cert=_text(value("tlsCert")) or None,
|
|
159
|
+
tls_key=_text(value("tlsKey")) or None,
|
|
160
|
+
tls_verify=value("tlsVerify") is not False,
|
|
161
|
+
hosts=parsed if isinstance(parsed, dict) else {},
|
|
162
|
+
read_only=value("readOnly") is True,
|
|
163
|
+
hide=_list(value("hide")),
|
|
164
|
+
protect=_list(value("protect")),
|
|
165
|
+
compose_roots=_list(value("composeRoots")),
|
|
166
|
+
allow_unprotected=value("allowUnprotected") is True,
|
|
167
|
+
compose_command=_text(value("composeCommand")) or "docker compose",
|
|
168
|
+
compose_timeout_seconds=int(compose_timeout) if compose_timeout.is_integer() else compose_timeout,
|
|
169
|
+
compose_hosts=_list(raw_hosts) if raw_hosts is not None else ["local"],
|
|
170
|
+
compose_env=_list(value("composeEnv")),
|
|
171
|
+
timeout_seconds=int(timeout) if timeout.is_integer() else timeout,
|
|
172
|
+
)
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
"""The shapes the Docker plugin answers with (section 4 of the contract) and the mapping from the Engine API's JSON.
|
|
2
|
+
|
|
3
|
+
The answers are plain dicts whose keys come in the order of the contract (the transcripts compare bytes)."""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from datetime import datetime, timedelta, timezone
|
|
10
|
+
from typing import Any, Optional
|
|
11
|
+
|
|
12
|
+
MASK = "••••••"
|
|
13
|
+
_SECRET_NAME = re.compile(r"password|passwd|secret|token|key|credential|auth", re.IGNORECASE)
|
|
14
|
+
COMPOSE_PROJECT = "com.docker.compose.project"
|
|
15
|
+
COMPOSE_SERVICE = "com.docker.compose.service"
|
|
16
|
+
COMPOSE_CONFIG_FILES = "com.docker.compose.project.config_files"
|
|
17
|
+
COMPOSE_WORKING_DIR = "com.docker.compose.project.working_dir"
|
|
18
|
+
BUILTIN_NETWORKS = frozenset({"bridge", "host", "none"})
|
|
19
|
+
|
|
20
|
+
_RFC3339 = re.compile(
|
|
21
|
+
r"^(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d+))?)?\s*(Z|[+-]\d{2}:?\d{2})?)?$",
|
|
22
|
+
re.IGNORECASE,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def js_str(value: Any) -> str:
|
|
27
|
+
"""``String(value)`` of the engine's JSON values (``undefined``/``null`` are not passed here)."""
|
|
28
|
+
if isinstance(value, bool):
|
|
29
|
+
return "true" if value else "false"
|
|
30
|
+
if isinstance(value, float) and value.is_integer():
|
|
31
|
+
return str(int(value))
|
|
32
|
+
return str(value)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def text_of(value: Any, default: str = "") -> str:
|
|
36
|
+
"""``String(value ?? default)``."""
|
|
37
|
+
return default if value is None else js_str(value)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def number_of(value: Any, default: float | int = 0) -> float | int:
|
|
41
|
+
"""``Number(value ?? default)`` for JSON numbers (and numeric text); NaN becomes ``default``."""
|
|
42
|
+
if value is None:
|
|
43
|
+
return default
|
|
44
|
+
try:
|
|
45
|
+
n = float(value)
|
|
46
|
+
except (TypeError, ValueError):
|
|
47
|
+
return default
|
|
48
|
+
if n != n:
|
|
49
|
+
return default
|
|
50
|
+
return int(n) if n.is_integer() else n
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def parse_time(text: str) -> Optional[float]:
|
|
54
|
+
"""Epoch seconds of an ISO 8601 / RFC 3339 text (a date alone is midnight UTC, no offset is UTC), else ``None``."""
|
|
55
|
+
m = _RFC3339.match(text.strip())
|
|
56
|
+
if not m:
|
|
57
|
+
return None
|
|
58
|
+
year, month, day, hour, minute, second, fraction, zone = m.groups()
|
|
59
|
+
try:
|
|
60
|
+
base = datetime(int(year), int(month), int(day), int(hour or 0), int(minute or 0), int(second or 0), tzinfo=timezone.utc)
|
|
61
|
+
except ValueError:
|
|
62
|
+
return None
|
|
63
|
+
seconds = base.timestamp() + (float(f"0.{fraction}") if fraction else 0.0)
|
|
64
|
+
if zone and zone.upper() != "Z":
|
|
65
|
+
sign = 1 if zone[0] == "+" else -1
|
|
66
|
+
digits = zone[1:].replace(":", "")
|
|
67
|
+
seconds -= sign * (int(digits[:2]) * 3600 + int(digits[2:]) * 60)
|
|
68
|
+
return seconds
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def format_seconds(value: float) -> str:
|
|
72
|
+
"""The time as ISO 8601 UTC in whole seconds (``2026-12-04T10:15:00Z``)."""
|
|
73
|
+
moment = datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=math.floor(value))
|
|
74
|
+
return moment.strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def iso_seconds(value: Any) -> Optional[str]:
|
|
78
|
+
"""ISO 8601 UTC in whole seconds from the engine's unix seconds or RFC 3339 text; ``None`` for its zero time."""
|
|
79
|
+
if value is None or value == "":
|
|
80
|
+
return None
|
|
81
|
+
if isinstance(value, str) and value.startswith("0001-01-01"):
|
|
82
|
+
return None
|
|
83
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
84
|
+
seconds: Optional[float] = float(value)
|
|
85
|
+
else:
|
|
86
|
+
seconds = parse_time(str(value))
|
|
87
|
+
if seconds is None or seconds <= 0:
|
|
88
|
+
return None
|
|
89
|
+
return format_seconds(seconds)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def short_id(value: Any) -> str:
|
|
93
|
+
return re.sub(r"^sha256:", "", text_of(value))[:12]
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def mask_env(entry: str) -> str:
|
|
97
|
+
"""``NAME=value`` with the value masked when the name looks secret."""
|
|
98
|
+
index = entry.find("=")
|
|
99
|
+
if index < 0:
|
|
100
|
+
return f"{entry}={MASK}" if _SECRET_NAME.search(entry) else entry
|
|
101
|
+
name = entry[:index]
|
|
102
|
+
return f"{name}={MASK}" if _SECRET_NAME.search(name) else entry
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def matches_pattern(pattern: str, name: str, labels: dict[str, str]) -> bool:
|
|
106
|
+
"""A pattern of ``hide`` / ``protect``: a name with ``*`` wildcards, or ``label:<key>[=<value>]``."""
|
|
107
|
+
if pattern.startswith("label:"):
|
|
108
|
+
spec = pattern[len("label:"):]
|
|
109
|
+
eq = spec.find("=")
|
|
110
|
+
key = spec if eq < 0 else spec[:eq]
|
|
111
|
+
if not key or key not in labels:
|
|
112
|
+
return False
|
|
113
|
+
return eq < 0 or labels[key] == spec[eq + 1:]
|
|
114
|
+
if not pattern:
|
|
115
|
+
return False
|
|
116
|
+
regex = "^" + ".*".join(re.escape(part) for part in pattern.split("*")) + "$"
|
|
117
|
+
return re.match(regex, name, re.DOTALL) is not None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def container_name(raw: Any) -> str:
|
|
121
|
+
"""The container's name: among ``Names`` the entry with a single ``/`` (legacy links add aliases such as ``/other/alias``)."""
|
|
122
|
+
names = [js_str(n) for n in raw.get("Names")] if isinstance(raw, dict) and isinstance(raw.get("Names"), list) else []
|
|
123
|
+
own = next((n for n in names if re.match(r"^/[^/]+\Z", n)), None)
|
|
124
|
+
if own is None:
|
|
125
|
+
own = names[0] if names else (raw.get("Name") if isinstance(raw, dict) else None)
|
|
126
|
+
return re.sub(r"^/", "", text_of(own))
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _health_of(status: str) -> Optional[str]:
|
|
130
|
+
m = re.search(r"\((healthy|unhealthy|health: starting)\)", status)
|
|
131
|
+
if not m:
|
|
132
|
+
return None
|
|
133
|
+
return "starting" if m.group(1) == "health: starting" else m.group(1)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _labels_of(raw: Any) -> dict[str, str]:
|
|
137
|
+
labels = (raw or {}).get("Labels") or {}
|
|
138
|
+
return {k: js_str(labels[k]) for k in sorted(labels)}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def map_container(raw: dict[str, Any], is_protected: bool) -> dict[str, Any]:
|
|
142
|
+
"""An item of ``GET /containers/json``."""
|
|
143
|
+
labels = _labels_of(raw)
|
|
144
|
+
status = text_of(raw.get("Status"))
|
|
145
|
+
ports: list[dict[str, Any]] = []
|
|
146
|
+
for p in raw.get("Ports") or []:
|
|
147
|
+
port: dict[str, Any] = {}
|
|
148
|
+
if p.get("IP"):
|
|
149
|
+
port["ip"] = js_str(p["IP"])
|
|
150
|
+
port["private"] = number_of(p.get("PrivatePort"), 0)
|
|
151
|
+
if p.get("PublicPort"):
|
|
152
|
+
port["public"] = number_of(p["PublicPort"], 0)
|
|
153
|
+
port["type"] = text_of(p.get("Type"), "tcp")
|
|
154
|
+
ports.append(port)
|
|
155
|
+
return {
|
|
156
|
+
"id": js_str(raw["Id"]),
|
|
157
|
+
"shortId": js_str(raw["Id"])[:12],
|
|
158
|
+
"name": container_name(raw),
|
|
159
|
+
"image": text_of(raw.get("Image")),
|
|
160
|
+
"imageId": text_of(raw.get("ImageID")),
|
|
161
|
+
"state": text_of(raw.get("State")),
|
|
162
|
+
"status": status,
|
|
163
|
+
"health": _health_of(status),
|
|
164
|
+
"createdAt": iso_seconds(raw.get("Created")),
|
|
165
|
+
"ports": ports,
|
|
166
|
+
"stack": labels.get(COMPOSE_PROJECT),
|
|
167
|
+
"service": labels.get(COMPOSE_SERVICE),
|
|
168
|
+
"labels": labels,
|
|
169
|
+
"protected": is_protected,
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def map_detail(base: dict[str, Any], raw: dict[str, Any]) -> dict[str, Any]:
|
|
174
|
+
"""The container plus the extra fields of ``GET /containers/{id}/json``."""
|
|
175
|
+
state = raw.get("State") or {}
|
|
176
|
+
policy = (raw.get("HostConfig") or {}).get("RestartPolicy") or {}
|
|
177
|
+
policy_name = text_of(policy.get("Name") or "no")
|
|
178
|
+
retries = number_of(policy.get("MaximumRetryCount"), 0)
|
|
179
|
+
networks = (raw.get("NetworkSettings") or {}).get("Networks") or {}
|
|
180
|
+
command = [raw.get("Path"), *(raw.get("Args") or [])]
|
|
181
|
+
return {
|
|
182
|
+
**base,
|
|
183
|
+
"command": [js_str(x) for x in command if x is not None],
|
|
184
|
+
"env": [mask_env(e) for e in ((raw.get("Config") or {}).get("Env") or [])],
|
|
185
|
+
"mounts": [
|
|
186
|
+
{
|
|
187
|
+
"type": text_of(m.get("Type")),
|
|
188
|
+
"source": text_of(m["Name"] if m.get("Type") == "volume" and m.get("Name") else m.get("Source")),
|
|
189
|
+
"destination": text_of(m.get("Destination")),
|
|
190
|
+
"rw": m.get("RW") is not False,
|
|
191
|
+
}
|
|
192
|
+
for m in raw.get("Mounts") or []
|
|
193
|
+
],
|
|
194
|
+
"networks": [
|
|
195
|
+
{
|
|
196
|
+
"name": name,
|
|
197
|
+
"ip": text_of(n.get("IPAddress")),
|
|
198
|
+
"gateway": text_of(n.get("Gateway")),
|
|
199
|
+
"mac": text_of(n.get("MacAddress")),
|
|
200
|
+
}
|
|
201
|
+
for name, n in sorted(networks.items(), key=lambda kv: kv[0])
|
|
202
|
+
],
|
|
203
|
+
"restartPolicy": f"{policy_name}:{js_str(retries)}" if retries > 0 else policy_name,
|
|
204
|
+
"startedAt": iso_seconds(state.get("StartedAt")),
|
|
205
|
+
"finishedAt": iso_seconds(state.get("FinishedAt")),
|
|
206
|
+
"exitCode": number_of(state.get("ExitCode"), 0),
|
|
207
|
+
"restartCount": number_of(raw.get("RestartCount"), 0),
|
|
208
|
+
"platform": text_of(raw.get("Platform")),
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
#: A log line longer than this is cut and ends with ``…``.
|
|
213
|
+
MAX_LOG_LINE = 16 * 1024
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _cut(text: str) -> str:
|
|
217
|
+
return f"{text[:MAX_LOG_LINE]}…" if len(text) > MAX_LOG_LINE else text
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _log_line(stream: str, line: str, timestamps: bool) -> dict[str, Any]:
|
|
221
|
+
if timestamps:
|
|
222
|
+
space = line.find(" ")
|
|
223
|
+
if space > 0 and re.match(r"^\d{4}-\d{2}-\d{2}T", line):
|
|
224
|
+
return {"stream": stream, "time": line[:space], "text": _cut(line[space + 1:])}
|
|
225
|
+
return {"stream": stream, "text": _cut(line)}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _text_of_bytes(data: bytes) -> str:
|
|
229
|
+
return data.decode("utf-8", "replace")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def parse_logs(body: bytes, tty: bool, timestamps: bool) -> list[dict[str, Any]]:
|
|
233
|
+
"""Splits a multiplexed stdout/stderr stream (or a TTY's raw one) into log lines."""
|
|
234
|
+
lines: list[dict[str, Any]] = []
|
|
235
|
+
pending = {"stdout": "", "stderr": ""}
|
|
236
|
+
|
|
237
|
+
def push(stream: str, text: str) -> None:
|
|
238
|
+
parts = (pending[stream] + text).split("\n")
|
|
239
|
+
pending[stream] = parts.pop()
|
|
240
|
+
for part in parts:
|
|
241
|
+
lines.append(_log_line(stream, part[:-1] if part.endswith("\r") else part, timestamps))
|
|
242
|
+
|
|
243
|
+
if tty:
|
|
244
|
+
push("stdout", _text_of_bytes(body))
|
|
245
|
+
else:
|
|
246
|
+
offset = 0
|
|
247
|
+
while offset + 8 <= len(body):
|
|
248
|
+
kind = body[offset]
|
|
249
|
+
size = int.from_bytes(body[offset + 4:offset + 8], "big")
|
|
250
|
+
push("stderr" if kind == 2 else "stdout", _text_of_bytes(body[offset + 8:offset + 8 + size]))
|
|
251
|
+
offset += 8 + size
|
|
252
|
+
for stream in ("stdout", "stderr"):
|
|
253
|
+
if pending[stream]:
|
|
254
|
+
lines.append(_log_line(stream, pending[stream], timestamps))
|
|
255
|
+
return lines
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def round2(value: float) -> float | int:
|
|
259
|
+
"""``Math.round(n * 100) / 100`` (halves up), as a whole number when it is one."""
|
|
260
|
+
result = math.floor(value * 100 + 0.5) / 100
|
|
261
|
+
return int(result) if result.is_integer() else result
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def map_stats(container_id: str, name: str, first: dict[str, Any], second: dict[str, Any]) -> dict[str, Any]:
|
|
265
|
+
"""Stats from two engine samples (``stream=false``): CPU over the gap between them, memory without the page cache."""
|
|
266
|
+
cpu2, cpu1 = second.get("cpu_stats") or {}, first.get("cpu_stats") or {}
|
|
267
|
+
cpu_delta = number_of((cpu2.get("cpu_usage") or {}).get("total_usage")) - number_of((cpu1.get("cpu_usage") or {}).get("total_usage"))
|
|
268
|
+
sys_delta = number_of(cpu2.get("system_cpu_usage")) - number_of(cpu1.get("system_cpu_usage"))
|
|
269
|
+
percpu = (cpu2.get("cpu_usage") or {}).get("percpu_usage")
|
|
270
|
+
cpus = number_of(cpu2.get("online_cpus") if cpu2.get("online_cpus") is not None else (len(percpu) if isinstance(percpu, list) else None), 1) or 1
|
|
271
|
+
cpu_percent = round2((cpu_delta / sys_delta) * cpus * 100) if cpu_delta > 0 and sys_delta > 0 else 0
|
|
272
|
+
mem = second.get("memory_stats") or {}
|
|
273
|
+
mem_stats = mem.get("stats") or {}
|
|
274
|
+
cache_value = mem_stats.get("inactive_file")
|
|
275
|
+
if cache_value is None:
|
|
276
|
+
cache_value = mem_stats.get("total_inactive_file")
|
|
277
|
+
if cache_value is None:
|
|
278
|
+
cache_value = mem_stats.get("cache")
|
|
279
|
+
memory_bytes = max(0, number_of(mem.get("usage")) - number_of(cache_value))
|
|
280
|
+
memory_limit = number_of(mem.get("limit"))
|
|
281
|
+
net_rx = net_tx = 0
|
|
282
|
+
for n in (second.get("networks") or {}).values():
|
|
283
|
+
net_rx += number_of(n.get("rx_bytes"))
|
|
284
|
+
net_tx += number_of(n.get("tx_bytes"))
|
|
285
|
+
block_read = block_write = 0
|
|
286
|
+
for e in (second.get("blkio_stats") or {}).get("io_service_bytes_recursive") or []:
|
|
287
|
+
op = text_of(e.get("op")).lower()
|
|
288
|
+
if op == "read":
|
|
289
|
+
block_read += number_of(e.get("value"))
|
|
290
|
+
elif op == "write":
|
|
291
|
+
block_write += number_of(e.get("value"))
|
|
292
|
+
return {
|
|
293
|
+
"id": container_id,
|
|
294
|
+
"name": name,
|
|
295
|
+
"cpuPercent": cpu_percent,
|
|
296
|
+
"memoryBytes": memory_bytes,
|
|
297
|
+
"memoryLimitBytes": memory_limit,
|
|
298
|
+
"memoryPercent": round2((memory_bytes / memory_limit) * 100) if memory_limit > 0 else 0,
|
|
299
|
+
"netRxBytes": net_rx,
|
|
300
|
+
"netTxBytes": net_tx,
|
|
301
|
+
"blockReadBytes": block_read,
|
|
302
|
+
"blockWriteBytes": block_write,
|
|
303
|
+
"pids": number_of((second.get("pids_stats") or {}).get("current")),
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def normalize_image_ref(image: str) -> dict[str, str]:
|
|
308
|
+
"""``nginx`` -> ``nginx:latest``; a registry port or a digest is not a tag."""
|
|
309
|
+
value = image.strip()
|
|
310
|
+
at = value.find("@")
|
|
311
|
+
if at > 0:
|
|
312
|
+
return {"name": value[:at], "tag": value[at:], "ref": value}
|
|
313
|
+
slash = value.rfind("/")
|
|
314
|
+
colon = value.rfind(":")
|
|
315
|
+
if colon > slash:
|
|
316
|
+
return {"name": value[:colon], "tag": value[colon + 1:], "ref": value}
|
|
317
|
+
return {"name": value, "tag": "latest", "ref": f"{value}:latest"}
|