stackdoctor-cli 1.0.1__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.
- stackdoctor/__init__.py +15 -0
- stackdoctor/__main__.py +6 -0
- stackdoctor/agent/__init__.py +5 -0
- stackdoctor/agent/compaction.py +66 -0
- stackdoctor/agent/diagnosis.py +398 -0
- stackdoctor/agent/loop.py +801 -0
- stackdoctor/agent/prompts.py +85 -0
- stackdoctor/agent/providers/__init__.py +295 -0
- stackdoctor/agent/providers/base.py +210 -0
- stackdoctor/agent/providers/claude.py +285 -0
- stackdoctor/agent/providers/gemini.py +312 -0
- stackdoctor/agent/providers/openai_compat.py +537 -0
- stackdoctor/agent/providers/prices.py +90 -0
- stackdoctor/benchmark/__init__.py +11 -0
- stackdoctor/benchmark/__main__.py +198 -0
- stackdoctor/benchmark/holmes.py +386 -0
- stackdoctor/benchmark/report.py +362 -0
- stackdoctor/benchmark/runner.py +710 -0
- stackdoctor/benchmark/scenarios.py +153 -0
- stackdoctor/benchmark/scoring.py +184 -0
- stackdoctor/cli.py +882 -0
- stackdoctor/dependencies.py +221 -0
- stackdoctor/discovery.py +361 -0
- stackdoctor/evidence.py +134 -0
- stackdoctor/github.py +168 -0
- stackdoctor/live.py +808 -0
- stackdoctor/mcp_server.py +233 -0
- stackdoctor/models.py +275 -0
- stackdoctor/pglog.py +55 -0
- stackdoctor/postgres.py +294 -0
- stackdoctor/probes.py +172 -0
- stackdoctor/py.typed +0 -0
- stackdoctor/redaction.py +215 -0
- stackdoctor/rules.py +303 -0
- stackdoctor/validation.py +61 -0
- stackdoctor_cli-1.0.1.dist-info/METADATA +177 -0
- stackdoctor_cli-1.0.1.dist-info/RECORD +40 -0
- stackdoctor_cli-1.0.1.dist-info/WHEEL +4 -0
- stackdoctor_cli-1.0.1.dist-info/entry_points.txt +3 -0
- stackdoctor_cli-1.0.1.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Dependency mapping for discovered Compose projects.
|
|
2
|
+
|
|
3
|
+
Declared dependencies come from Compose relationships (`depends_on`, `links`,
|
|
4
|
+
`network_mode: service:<name>`). Inferred dependencies come from environment
|
|
5
|
+
variables that name another service: connection URLs anywhere in a value, and
|
|
6
|
+
`*_HOST` / `*_ADDR` variables (with an optional matching `*_PORT`).
|
|
7
|
+
|
|
8
|
+
Everything here works on the already-redacted model. Redaction keeps URL hosts
|
|
9
|
+
and ports, so most references survive; a value that was fully redacted (for
|
|
10
|
+
example under a `*_DSN` key) is simply not analyzed.
|
|
11
|
+
|
|
12
|
+
`find_host_references` is also the input for the validation rules: it reports
|
|
13
|
+
every host a service refers to, including hosts that match no service.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import ipaddress
|
|
17
|
+
import re
|
|
18
|
+
from collections.abc import Iterable, Mapping, Sequence
|
|
19
|
+
from dataclasses import dataclass
|
|
20
|
+
from typing import Literal
|
|
21
|
+
|
|
22
|
+
from stackdoctor.models import Dependency, Service
|
|
23
|
+
from stackdoctor.redaction import REDACTED
|
|
24
|
+
|
|
25
|
+
HostCategory = Literal["service", "loopback", "ip", "external", "unknown"]
|
|
26
|
+
|
|
27
|
+
# scheme://[userinfo@]host[:port]. Hosts are parsed by hand because
|
|
28
|
+
# urllib.parse treats "[REDACTED]" in the userinfo as a malformed IPv6 address.
|
|
29
|
+
_URL = re.compile(
|
|
30
|
+
r"""(?P<scheme>\b[A-Za-z][A-Za-z0-9+.\-]*)://
|
|
31
|
+
(?:[^/\s?#]*@)?
|
|
32
|
+
(?P<host>\[[0-9A-Fa-f:.]+\]|[^:/\s?#@\[\],;]+)
|
|
33
|
+
(?::(?P<port>\d{1,5}))?""",
|
|
34
|
+
re.VERBOSE,
|
|
35
|
+
)
|
|
36
|
+
# A bare "host" or "host:port" value.
|
|
37
|
+
_HOST_PORT = re.compile(r"(?P<host>\[[0-9A-Fa-f:.]+\]|[A-Za-z0-9_.\-]+)(?::(?P<port>\d{1,5}))?")
|
|
38
|
+
# Keys whose value is a host or host:port. A bare `HOST`, and keys that name a
|
|
39
|
+
# bind or listen address, describe where a server listens, not what it calls.
|
|
40
|
+
_HOST_KEY = re.compile(r"^(?P<prefix>.+)_(?:HOST|ADDR|ADDRESS)$")
|
|
41
|
+
_BIND_WORDS = ("BIND", "LISTEN")
|
|
42
|
+
# Variables known to hold the server's own listen URLs, not targets it calls.
|
|
43
|
+
_LISTEN_URL_VARIABLES = frozenset(
|
|
44
|
+
{"ASPNETCORE_URLS", "ASPNETCORE_HTTP_URLS", "ASPNETCORE_HTTPS_URLS"}
|
|
45
|
+
)
|
|
46
|
+
# What a host must look like to be a DNS name. Wildcard listen hosts such as
|
|
47
|
+
# `+` and `*` (http://+:8000 in ASP.NET) are not names of anything.
|
|
48
|
+
_DNS_NAME = re.compile(r"^[a-z0-9_](?:[a-z0-9_.\-]*[a-z0-9_])?$")
|
|
49
|
+
_LOOPBACK_NAMES = frozenset({"localhost", "localhost.localdomain", "ip6-localhost"})
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class HostReference:
|
|
54
|
+
"""A host named in one environment variable of one service."""
|
|
55
|
+
|
|
56
|
+
source: str
|
|
57
|
+
variable: str
|
|
58
|
+
host: str
|
|
59
|
+
port: int | None
|
|
60
|
+
scheme: str | None
|
|
61
|
+
category: HostCategory
|
|
62
|
+
target: str | None = None # the matching service, when category == "service"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def find_host_references(services: Sequence[Service]) -> tuple[HostReference, ...]:
|
|
66
|
+
"""Return every host referenced from the services' environment variables."""
|
|
67
|
+
global_names = _service_names(services)
|
|
68
|
+
references: list[HostReference] = []
|
|
69
|
+
for service in services:
|
|
70
|
+
names = {**global_names, **_link_names(service)}
|
|
71
|
+
for variable, value in sorted(service.environment.items()):
|
|
72
|
+
if not value or value == REDACTED:
|
|
73
|
+
continue
|
|
74
|
+
for host, port, scheme in _hosts_in(variable, value, service.environment):
|
|
75
|
+
category, target = _classify(host, names)
|
|
76
|
+
references.append(
|
|
77
|
+
HostReference(service.name, variable, host, port, scheme, category, target)
|
|
78
|
+
)
|
|
79
|
+
return tuple(references)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def map_dependencies(services: Sequence[Service]) -> tuple[Dependency, ...]:
|
|
83
|
+
"""Build the declared and inferred dependencies between services."""
|
|
84
|
+
known = {service.name for service in services}
|
|
85
|
+
found: set[Dependency] = set()
|
|
86
|
+
for service in services:
|
|
87
|
+
for dependency in service.depends_on:
|
|
88
|
+
found.add(
|
|
89
|
+
Dependency(
|
|
90
|
+
source=service.name,
|
|
91
|
+
target=dependency.service,
|
|
92
|
+
kind="declared",
|
|
93
|
+
via="depends_on",
|
|
94
|
+
condition=dependency.condition,
|
|
95
|
+
)
|
|
96
|
+
)
|
|
97
|
+
for link in service.links:
|
|
98
|
+
target = link.partition(":")[0]
|
|
99
|
+
if target in known:
|
|
100
|
+
found.add(
|
|
101
|
+
Dependency(source=service.name, target=target, kind="declared", via="links")
|
|
102
|
+
)
|
|
103
|
+
shared = _network_mode_service(service)
|
|
104
|
+
if shared in known:
|
|
105
|
+
found.add(
|
|
106
|
+
Dependency(source=service.name, target=shared, kind="declared", via="network_mode")
|
|
107
|
+
)
|
|
108
|
+
for reference in find_host_references(services):
|
|
109
|
+
if reference.target is not None and reference.target != reference.source:
|
|
110
|
+
found.add(
|
|
111
|
+
Dependency(
|
|
112
|
+
source=reference.source,
|
|
113
|
+
target=reference.target,
|
|
114
|
+
kind="inferred",
|
|
115
|
+
via="environment",
|
|
116
|
+
variable=reference.variable,
|
|
117
|
+
scheme=reference.scheme,
|
|
118
|
+
port=reference.port,
|
|
119
|
+
)
|
|
120
|
+
)
|
|
121
|
+
return tuple(
|
|
122
|
+
sorted(
|
|
123
|
+
found, key=lambda d: (d.source, d.target, d.kind, d.via, d.variable or "", d.port or 0)
|
|
124
|
+
)
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _network_mode_service(service: Service) -> str | None:
|
|
129
|
+
mode = service.network_mode or ""
|
|
130
|
+
return mode.removeprefix("service:") if mode.startswith("service:") else None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _service_names(services: Sequence[Service]) -> dict[str, str]:
|
|
134
|
+
"""Map every DNS name a service answers to (lowercased) to the service."""
|
|
135
|
+
names: dict[str, str] = {}
|
|
136
|
+
for service in services:
|
|
137
|
+
candidates = [service.name, service.container_name or ""]
|
|
138
|
+
for aliases in service.network_aliases.values():
|
|
139
|
+
candidates.extend(aliases)
|
|
140
|
+
for candidate in candidates:
|
|
141
|
+
if candidate:
|
|
142
|
+
names.setdefault(candidate.lower(), service.name)
|
|
143
|
+
return names
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _link_names(service: Service) -> dict[str, str]:
|
|
147
|
+
names: dict[str, str] = {}
|
|
148
|
+
for link in service.links:
|
|
149
|
+
target, _, alias = link.partition(":")
|
|
150
|
+
names[(alias or target).lower()] = target
|
|
151
|
+
return names
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _hosts_in(
|
|
155
|
+
variable: str, value: str, environment: Mapping[str, str | None]
|
|
156
|
+
) -> Iterable[tuple[str, int | None, str | None]]:
|
|
157
|
+
"""Yield (host, port, scheme) for each host named in one variable.
|
|
158
|
+
|
|
159
|
+
Variables that configure where the service itself listens (bind/listen
|
|
160
|
+
variables, `ASPNETCORE_URLS`) are skipped, and so are hosts that cannot be
|
|
161
|
+
DNS names or IP addresses, such as the wildcard `+`.
|
|
162
|
+
"""
|
|
163
|
+
upper = variable.upper()
|
|
164
|
+
if upper in _LISTEN_URL_VARIABLES or any(word in upper for word in _BIND_WORDS):
|
|
165
|
+
return
|
|
166
|
+
urls = list(_URL.finditer(value))
|
|
167
|
+
for match in urls:
|
|
168
|
+
host = _clean_host(match["host"])
|
|
169
|
+
if _is_host(host):
|
|
170
|
+
yield host, _port(match["port"]), match["scheme"].lower()
|
|
171
|
+
if urls:
|
|
172
|
+
return
|
|
173
|
+
key = _HOST_KEY.match(upper)
|
|
174
|
+
if key is None:
|
|
175
|
+
return
|
|
176
|
+
bare = _HOST_PORT.fullmatch(value.strip())
|
|
177
|
+
if bare is None:
|
|
178
|
+
return
|
|
179
|
+
port = _port(bare["port"])
|
|
180
|
+
if port is None:
|
|
181
|
+
# The matching port variable, in whatever case the host variable used.
|
|
182
|
+
port_key = f"{key['prefix']}_PORT"
|
|
183
|
+
port = next(
|
|
184
|
+
(_port(v) for k, v in environment.items() if k.upper() == port_key),
|
|
185
|
+
None,
|
|
186
|
+
)
|
|
187
|
+
yield _clean_host(bare["host"]), port, None
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _is_host(host: str) -> bool:
|
|
191
|
+
if _DNS_NAME.match(host):
|
|
192
|
+
return True
|
|
193
|
+
try:
|
|
194
|
+
ipaddress.ip_address(host)
|
|
195
|
+
except ValueError:
|
|
196
|
+
return False
|
|
197
|
+
return True
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _clean_host(host: str) -> str:
|
|
201
|
+
return host.strip("[]").lower()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _port(text: str | None) -> int | None:
|
|
205
|
+
if text is None or not text.strip().isdigit():
|
|
206
|
+
return None
|
|
207
|
+
number = int(text)
|
|
208
|
+
return number if 0 < number < 65536 else None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def _classify(host: str, names: Mapping[str, str]) -> tuple[HostCategory, str | None]:
|
|
212
|
+
if host in names:
|
|
213
|
+
return "service", names[host]
|
|
214
|
+
if host in _LOOPBACK_NAMES:
|
|
215
|
+
return "loopback", None
|
|
216
|
+
try:
|
|
217
|
+
address = ipaddress.ip_address(host)
|
|
218
|
+
except ValueError:
|
|
219
|
+
return ("external" if "." in host else "unknown"), None
|
|
220
|
+
# Wildcard addresses such as 0.0.0.0 are not loopback; they land in "ip".
|
|
221
|
+
return ("loopback" if address.is_loopback else "ip"), None
|
stackdoctor/discovery.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
"""Discover Docker Compose projects with `docker compose config --format json`.
|
|
2
|
+
|
|
3
|
+
Compose itself resolves file merging, profiles, interpolation and the short and
|
|
4
|
+
long syntax forms; StackDoctor only reads its normalized output. The command is
|
|
5
|
+
read-only and does not need a running Docker daemon.
|
|
6
|
+
|
|
7
|
+
Secrets: the resolved output can contain real credentials, so
|
|
8
|
+
|
|
9
|
+
- results are built only from allowlisted fields into the redacting models in
|
|
10
|
+
`stackdoctor.models`;
|
|
11
|
+
- error messages never include stdout (only its size), and stderr is redacted
|
|
12
|
+
and truncated before it is put into a message;
|
|
13
|
+
- original exceptions are dropped (`raise ... from None`) because some of them,
|
|
14
|
+
such as `json.JSONDecodeError`, `subprocess.TimeoutExpired` and Pydantic's
|
|
15
|
+
`ValidationError`, carry the raw output.
|
|
16
|
+
|
|
17
|
+
Known limit: stderr redaction uses key patterns, URL credentials and the values
|
|
18
|
+
of sensitive-named variables in the current environment. A secret that exists
|
|
19
|
+
only in a `.env` file, under a key that does not look sensitive, cannot be
|
|
20
|
+
recognized if Compose echoes it. Compose errors normally name variables rather
|
|
21
|
+
than print their values.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
import json
|
|
25
|
+
import subprocess
|
|
26
|
+
from collections.abc import Iterator, Mapping, Sequence
|
|
27
|
+
from contextlib import contextmanager
|
|
28
|
+
from dataclasses import dataclass
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Any, Protocol
|
|
31
|
+
|
|
32
|
+
from pydantic import ValidationError
|
|
33
|
+
|
|
34
|
+
from stackdoctor.dependencies import map_dependencies
|
|
35
|
+
from stackdoctor.models import (
|
|
36
|
+
ComposeProject,
|
|
37
|
+
Healthcheck,
|
|
38
|
+
Network,
|
|
39
|
+
PortMapping,
|
|
40
|
+
Service,
|
|
41
|
+
ServiceDependency,
|
|
42
|
+
)
|
|
43
|
+
from stackdoctor.redaction import (
|
|
44
|
+
is_sensitive_key,
|
|
45
|
+
redact_text,
|
|
46
|
+
sensitive_environment_values,
|
|
47
|
+
url_passwords,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
DEFAULT_TIMEOUT_SECONDS = 30.0
|
|
51
|
+
MAX_STDERR_CHARS = 2000
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class DiscoveryError(Exception):
|
|
55
|
+
"""Discovery failed. The message is already redacted and safe to show."""
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class DockerNotFoundError(DiscoveryError):
|
|
59
|
+
"""The `docker` executable is not on PATH."""
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
class ComposeTimeoutError(DiscoveryError):
|
|
63
|
+
"""`docker compose config` did not finish in time."""
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
class ComposeConfigError(DiscoveryError):
|
|
67
|
+
"""`docker compose config` exited with an error (for example an invalid file)."""
|
|
68
|
+
|
|
69
|
+
def __init__(self, message: str, returncode: int) -> None:
|
|
70
|
+
super().__init__(message)
|
|
71
|
+
self.returncode = returncode
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
class ComposeOutputError(DiscoveryError):
|
|
75
|
+
"""Compose produced output StackDoctor cannot interpret."""
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@dataclass(frozen=True)
|
|
79
|
+
class RunResult:
|
|
80
|
+
returncode: int
|
|
81
|
+
stdout: str
|
|
82
|
+
stderr: str
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class ComposeRunner(Protocol):
|
|
86
|
+
"""Runs a command. Swappable so tests do not need Docker."""
|
|
87
|
+
|
|
88
|
+
def __call__(self, args: Sequence[str], *, cwd: Path, timeout: float) -> RunResult: ...
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def subprocess_runner(args: Sequence[str], *, cwd: Path, timeout: float) -> RunResult:
|
|
92
|
+
"""Run a command without a shell and capture its output as text."""
|
|
93
|
+
completed = subprocess.run(
|
|
94
|
+
list(args),
|
|
95
|
+
cwd=cwd,
|
|
96
|
+
capture_output=True,
|
|
97
|
+
encoding="utf-8",
|
|
98
|
+
errors="replace",
|
|
99
|
+
timeout=timeout,
|
|
100
|
+
check=False,
|
|
101
|
+
)
|
|
102
|
+
return RunResult(completed.returncode, completed.stdout, completed.stderr)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def discover(
|
|
106
|
+
project_dir: Path | str = ".",
|
|
107
|
+
compose_files: Sequence[Path | str] = (),
|
|
108
|
+
*,
|
|
109
|
+
runner: ComposeRunner = subprocess_runner,
|
|
110
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
111
|
+
) -> ComposeProject:
|
|
112
|
+
"""Discover the Compose project in ``project_dir`` and return a redacted model.
|
|
113
|
+
|
|
114
|
+
``compose_files`` are passed to Compose as ``-f`` options; when empty,
|
|
115
|
+
Compose applies its own default file lookup.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
DiscoveryError: or one of its subclasses, with a redacted message.
|
|
119
|
+
"""
|
|
120
|
+
directory = Path(project_dir)
|
|
121
|
+
if not directory.is_dir():
|
|
122
|
+
raise DiscoveryError(f"Project directory not found: {directory}")
|
|
123
|
+
|
|
124
|
+
args = ["docker", "compose"]
|
|
125
|
+
for compose_file in compose_files:
|
|
126
|
+
args += ["-f", str(compose_file)]
|
|
127
|
+
args += ["config", "--format", "json"]
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
result = runner(args, cwd=directory, timeout=timeout)
|
|
131
|
+
except FileNotFoundError:
|
|
132
|
+
raise DockerNotFoundError(
|
|
133
|
+
"Docker CLI not found on PATH. Install Docker with the Compose plugin."
|
|
134
|
+
) from None
|
|
135
|
+
except subprocess.TimeoutExpired:
|
|
136
|
+
raise ComposeTimeoutError(
|
|
137
|
+
f"docker compose config did not finish within {timeout:g} seconds."
|
|
138
|
+
) from None
|
|
139
|
+
|
|
140
|
+
if result.returncode != 0:
|
|
141
|
+
raise ComposeConfigError(_config_error_message(result), result.returncode)
|
|
142
|
+
|
|
143
|
+
try:
|
|
144
|
+
data = json.loads(result.stdout)
|
|
145
|
+
except json.JSONDecodeError:
|
|
146
|
+
size = len(result.stdout.encode("utf-8"))
|
|
147
|
+
raise ComposeOutputError(f"Compose returned invalid JSON ({size} bytes).") from None
|
|
148
|
+
|
|
149
|
+
return parse_compose_config(data)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def parse_compose_config(data: object) -> ComposeProject:
|
|
153
|
+
"""Build a redacted `ComposeProject` from parsed `docker compose config` JSON."""
|
|
154
|
+
root = _mapping(data, "the top level")
|
|
155
|
+
services = _mapping(root.get("services"), "services")
|
|
156
|
+
networks = _mapping(root.get("networks"), "networks", allow_missing=True)
|
|
157
|
+
|
|
158
|
+
specs = {name: _mapping(spec, f"services.{name}") for name, spec in sorted(services.items())}
|
|
159
|
+
labels = _secret_labels(specs)
|
|
160
|
+
service_models = tuple(_parse_service(name, spec, labels[name]) for name, spec in specs.items())
|
|
161
|
+
network_models = tuple(
|
|
162
|
+
_parse_network(name, _mapping(spec, where, allow_missing=True), where)
|
|
163
|
+
for name, spec in sorted(networks.items())
|
|
164
|
+
for where in [f"networks.{name}"]
|
|
165
|
+
)
|
|
166
|
+
with _validating("the top level"):
|
|
167
|
+
return ComposeProject(
|
|
168
|
+
name=_required(root, "name", "the top level"),
|
|
169
|
+
services=service_models,
|
|
170
|
+
networks=network_models,
|
|
171
|
+
dependencies=map_dependencies(service_models),
|
|
172
|
+
)
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _secret_labels(specs: Mapping[str, Mapping[str, Any]]) -> dict[str, dict[str, str]]:
|
|
176
|
+
"""Label secret values so rules can compare them without seeing them.
|
|
177
|
+
|
|
178
|
+
This is the only place that compares raw secrets, and it runs before the
|
|
179
|
+
models redact them. A variable gets a label when its value is a secret: the
|
|
180
|
+
password in a connection URL, or the whole value of a sensitive key (except
|
|
181
|
+
`*_FILE` variables, which hold a path). Equal secrets anywhere in the
|
|
182
|
+
project get the same label. Empty values get none, so a missing label on a
|
|
183
|
+
sensitive variable means it is empty.
|
|
184
|
+
"""
|
|
185
|
+
labels: dict[str, dict[str, str]] = {name: {} for name in specs}
|
|
186
|
+
assigned: dict[str, str] = {}
|
|
187
|
+
for name, spec in specs.items():
|
|
188
|
+
environment = spec.get("environment")
|
|
189
|
+
if not isinstance(environment, dict):
|
|
190
|
+
continue # reported by _parse_service
|
|
191
|
+
for variable, value in sorted(environment.items()):
|
|
192
|
+
if not isinstance(value, str) or not value:
|
|
193
|
+
continue
|
|
194
|
+
passwords = url_passwords(value)
|
|
195
|
+
if passwords:
|
|
196
|
+
secret = passwords[0]
|
|
197
|
+
elif is_sensitive_key(variable) and not variable.upper().endswith("_FILE"):
|
|
198
|
+
secret = value
|
|
199
|
+
else:
|
|
200
|
+
continue
|
|
201
|
+
labels[name][variable] = assigned.setdefault(secret, f"secret-{len(assigned) + 1}")
|
|
202
|
+
return labels
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _parse_service(name: str, spec: Mapping[str, Any], secret_labels: dict[str, str]) -> Service:
|
|
206
|
+
where = f"services.{name}"
|
|
207
|
+
ports = _sequence(spec.get("ports"), f"{where}.ports")
|
|
208
|
+
depends_on = _mapping(spec.get("depends_on"), f"{where}.depends_on", allow_missing=True)
|
|
209
|
+
networks = _mapping(spec.get("networks"), f"{where}.networks", allow_missing=True)
|
|
210
|
+
environment = _mapping(spec.get("environment"), f"{where}.environment", allow_missing=True)
|
|
211
|
+
healthcheck = _mapping(spec.get("healthcheck"), f"{where}.healthcheck", allow_missing=True)
|
|
212
|
+
expose = _sequence(spec.get("expose"), f"{where}.expose")
|
|
213
|
+
links = _sequence(spec.get("links"), f"{where}.links")
|
|
214
|
+
network_aliases = {
|
|
215
|
+
network: tuple(
|
|
216
|
+
_sequence(
|
|
217
|
+
_mapping(options, f"{where}.networks.{network}", allow_missing=True).get("aliases"),
|
|
218
|
+
f"{where}.networks.{network}.aliases",
|
|
219
|
+
)
|
|
220
|
+
)
|
|
221
|
+
for network, options in sorted(networks.items())
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
port_models = tuple(
|
|
225
|
+
_parse_port(_mapping(port, port_where), port_where)
|
|
226
|
+
for index, port in enumerate(ports)
|
|
227
|
+
for port_where in [f"{where}.ports[{index}]"]
|
|
228
|
+
)
|
|
229
|
+
dependency_models = tuple(
|
|
230
|
+
_parse_dependency(
|
|
231
|
+
dependency,
|
|
232
|
+
_mapping(dependency_spec, dependency_where, allow_missing=True),
|
|
233
|
+
dependency_where,
|
|
234
|
+
)
|
|
235
|
+
for dependency, dependency_spec in sorted(depends_on.items())
|
|
236
|
+
for dependency_where in [f"{where}.depends_on.{dependency}"]
|
|
237
|
+
)
|
|
238
|
+
healthcheck_model = _parse_healthcheck(healthcheck, f"{where}.healthcheck")
|
|
239
|
+
|
|
240
|
+
with _validating(where):
|
|
241
|
+
return Service(
|
|
242
|
+
name=name,
|
|
243
|
+
image=spec.get("image"),
|
|
244
|
+
has_build=spec.get("build") is not None,
|
|
245
|
+
ports=port_models,
|
|
246
|
+
networks=tuple(sorted(networks)),
|
|
247
|
+
depends_on=dependency_models,
|
|
248
|
+
environment=dict(environment),
|
|
249
|
+
restart=spec.get("restart"),
|
|
250
|
+
healthcheck=healthcheck_model,
|
|
251
|
+
expose=tuple(str(port) for port in expose),
|
|
252
|
+
network_aliases={net: aliases for net, aliases in network_aliases.items() if aliases},
|
|
253
|
+
container_name=spec.get("container_name"),
|
|
254
|
+
network_mode=spec.get("network_mode"),
|
|
255
|
+
links=tuple(links),
|
|
256
|
+
secret_labels=secret_labels,
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _parse_port(spec: Mapping[str, Any], where: str) -> PortMapping:
|
|
261
|
+
published = spec.get("published")
|
|
262
|
+
with _validating(where):
|
|
263
|
+
return PortMapping(
|
|
264
|
+
target=_required(spec, "target", where),
|
|
265
|
+
published=None if published is None else str(published),
|
|
266
|
+
protocol=spec.get("protocol") or "tcp",
|
|
267
|
+
host_ip=spec.get("host_ip"),
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _parse_dependency(service: str, spec: Mapping[str, Any], where: str) -> ServiceDependency:
|
|
272
|
+
with _validating(where):
|
|
273
|
+
return ServiceDependency(
|
|
274
|
+
service=service,
|
|
275
|
+
condition=spec.get("condition") or "service_started",
|
|
276
|
+
required=spec.get("required", True),
|
|
277
|
+
)
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _parse_healthcheck(spec: Mapping[str, Any], where: str) -> Healthcheck | None:
|
|
281
|
+
# Only timing is kept; the test command is never read (it can carry
|
|
282
|
+
# inline secrets). A disabled healthcheck counts as no healthcheck.
|
|
283
|
+
if not spec or spec.get("disable") or spec.get("test") == ["NONE"]:
|
|
284
|
+
return None
|
|
285
|
+
with _validating(where):
|
|
286
|
+
return Healthcheck(
|
|
287
|
+
interval=spec.get("interval"),
|
|
288
|
+
timeout=spec.get("timeout"),
|
|
289
|
+
retries=spec.get("retries"),
|
|
290
|
+
)
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _parse_network(name: str, spec: Mapping[str, Any], where: str) -> Network:
|
|
294
|
+
with _validating(where):
|
|
295
|
+
return Network(
|
|
296
|
+
name=name,
|
|
297
|
+
driver=spec.get("driver"),
|
|
298
|
+
external=bool(spec.get("external", False)),
|
|
299
|
+
resource_name=spec.get("name"),
|
|
300
|
+
)
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
@contextmanager
|
|
304
|
+
def _validating(where: str) -> Iterator[None]:
|
|
305
|
+
"""Turn a Pydantic `ValidationError` into a safe `ComposeOutputError`."""
|
|
306
|
+
try:
|
|
307
|
+
yield
|
|
308
|
+
except ValidationError as error:
|
|
309
|
+
raise ComposeOutputError(_describe_validation_error(error, where)) from None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def _mapping(value: object, where: str, *, allow_missing: bool = False) -> dict[str, Any]:
|
|
313
|
+
if value is None and allow_missing:
|
|
314
|
+
return {}
|
|
315
|
+
if not isinstance(value, dict):
|
|
316
|
+
raise ComposeOutputError(f"Compose output has an unexpected shape at {where}.")
|
|
317
|
+
return value
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _required(spec: Mapping[str, Any], key: str, where: str) -> Any:
|
|
321
|
+
# Returns Any on purpose: the model then validates the value's type.
|
|
322
|
+
if spec.get(key) is None:
|
|
323
|
+
raise ComposeOutputError(f"Compose output is missing '{key}' at {where}.")
|
|
324
|
+
return spec[key]
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def _sequence(value: object, where: str) -> list[Any]:
|
|
328
|
+
if value is None:
|
|
329
|
+
return []
|
|
330
|
+
if not isinstance(value, list):
|
|
331
|
+
raise ComposeOutputError(f"Compose output has an unexpected shape at {where}.")
|
|
332
|
+
return value
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def _describe_validation_error(error: ValidationError, where: str) -> str:
|
|
336
|
+
# Pydantic's own message includes the offending input values, which can be
|
|
337
|
+
# secrets. Report only field locations and error types.
|
|
338
|
+
problems = [
|
|
339
|
+
f"{'.'.join(str(part) for part in detail['loc'])} ({detail['type']})"
|
|
340
|
+
for detail in error.errors(include_input=False, include_url=False)
|
|
341
|
+
]
|
|
342
|
+
shown = "; ".join(problems[:3])
|
|
343
|
+
more = f" and {len(problems) - 3} more" if len(problems) > 3 else ""
|
|
344
|
+
return f"Compose output has unexpected values at {where}: {shown}{more}."
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def safe_stderr(stderr: str) -> str:
|
|
348
|
+
"""Redact, then truncate, a command's error output so it is safe to show."""
|
|
349
|
+
known_secrets = sensitive_environment_values()
|
|
350
|
+
# Redact first, then truncate, so a cut can never leave part of a secret
|
|
351
|
+
# that the redaction patterns would no longer recognize.
|
|
352
|
+
text = redact_text(stderr.strip(), known_values=known_secrets)
|
|
353
|
+
if len(text) > MAX_STDERR_CHARS:
|
|
354
|
+
text = text[:MAX_STDERR_CHARS] + " [truncated]"
|
|
355
|
+
return text
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _config_error_message(result: RunResult) -> str:
|
|
359
|
+
stderr = safe_stderr(result.stderr)
|
|
360
|
+
message = f"docker compose config failed with exit code {result.returncode}"
|
|
361
|
+
return f"{message}: {stderr}" if stderr else f"{message}."
|