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
stackdoctor/live.py
ADDED
|
@@ -0,0 +1,808 @@
|
|
|
1
|
+
"""Live, read-only checks of a running Compose project (`validate --live`).
|
|
2
|
+
|
|
3
|
+
Opt-in and read-only: StackDoctor lists and inspects the project's containers
|
|
4
|
+
and opens (and immediately closes) TCP connections to the ports it publishes on
|
|
5
|
+
the host. It never starts, stops, changes or executes anything in a container.
|
|
6
|
+
|
|
7
|
+
Secrets: `docker inspect` output includes the container's full environment
|
|
8
|
+
(`Config.Env`) and the output of its health checks, which can both contain
|
|
9
|
+
credentials. StackDoctor never asks for them. A Go template makes Docker
|
|
10
|
+
return only allowlisted fields (`INSPECT_TEMPLATE`), so the raw environment
|
|
11
|
+
never reaches this process. Docker's error output is redacted and truncated
|
|
12
|
+
before it is shown, like discovery's.
|
|
13
|
+
|
|
14
|
+
Bounds: every Docker command has the per-command timeout, the whole collection
|
|
15
|
+
has a total budget, and the number of host checks is capped. There are no
|
|
16
|
+
retries; a check that does not answer within its timeout is reported as such.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import socket
|
|
21
|
+
import subprocess
|
|
22
|
+
import time
|
|
23
|
+
from collections.abc import Callable, Iterable, Sequence
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from datetime import UTC, datetime
|
|
26
|
+
from pathlib import Path
|
|
27
|
+
from typing import Any, Literal
|
|
28
|
+
|
|
29
|
+
from stackdoctor.dependencies import HostReference, find_host_references
|
|
30
|
+
from stackdoctor.discovery import (
|
|
31
|
+
DEFAULT_TIMEOUT_SECONDS,
|
|
32
|
+
ComposeRunner,
|
|
33
|
+
safe_stderr,
|
|
34
|
+
subprocess_runner,
|
|
35
|
+
)
|
|
36
|
+
from stackdoctor.evidence import config_item, make_item_evidence
|
|
37
|
+
from stackdoctor.models import ComposeProject, EvidenceItem, Finding, LiveSummary, Severity
|
|
38
|
+
from stackdoctor.pglog import LOG_TAIL_LINES, parse_events
|
|
39
|
+
from stackdoctor.postgres import is_postgres
|
|
40
|
+
from stackdoctor.probes import (
|
|
41
|
+
MAX_PROBE_CONTAINERS,
|
|
42
|
+
Target,
|
|
43
|
+
can_probe,
|
|
44
|
+
dns_tcp_command,
|
|
45
|
+
parse_dns_tcp,
|
|
46
|
+
pg_isready_command,
|
|
47
|
+
pg_result,
|
|
48
|
+
probe_name,
|
|
49
|
+
run_probe,
|
|
50
|
+
)
|
|
51
|
+
from stackdoctor.rules import POSTGRES_DEFAULT_PORT
|
|
52
|
+
|
|
53
|
+
DEFAULT_BUDGET_SECONDS = 60.0
|
|
54
|
+
TCP_TIMEOUT_SECONDS = 3.0
|
|
55
|
+
PEER_WAIT_SECONDS = 1.0
|
|
56
|
+
MAX_HOST_CHECKS = 50
|
|
57
|
+
COMPOSE_PROJECT_LABEL = "com.docker.compose.project"
|
|
58
|
+
|
|
59
|
+
# Only these fields leave Docker. Network names are listed without their
|
|
60
|
+
# settings (addresses, endpoint IDs). A trailing null keeps the list valid JSON.
|
|
61
|
+
INSPECT_TEMPLATE = (
|
|
62
|
+
"{"
|
|
63
|
+
'"id":{{json .Id}},'
|
|
64
|
+
'"service":{{json (index .Config.Labels "com.docker.compose.service")}},'
|
|
65
|
+
'"oneoff":{{json (index .Config.Labels "com.docker.compose.oneoff")}},'
|
|
66
|
+
'"status":{{json .State.Status}},'
|
|
67
|
+
'"exit_code":{{.State.ExitCode}},'
|
|
68
|
+
'"oom_killed":{{.State.OOMKilled}},'
|
|
69
|
+
'"restart_count":{{.RestartCount}},'
|
|
70
|
+
'"health":{{with index .State "Health"}}{{json .Status}}{{else}}null{{end}},'
|
|
71
|
+
'"networks":[{{range $name, $_ := .NetworkSettings.Networks}}{{json $name}},{{end}}null],'
|
|
72
|
+
'"ports":{{json .NetworkSettings.Ports}}'
|
|
73
|
+
"}"
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
TcpResult = Literal["open", "closed", "refused", "timeout", "error"]
|
|
77
|
+
Connector = Callable[[str, int, float], TcpResult]
|
|
78
|
+
Clock = Callable[[], datetime]
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class LiveUnavailableError(Exception):
|
|
82
|
+
"""Live checks could not run (for example, the Docker daemon is unreachable).
|
|
83
|
+
|
|
84
|
+
The message is already redacted and safe to show.
|
|
85
|
+
"""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class Container:
|
|
90
|
+
"""The allowlisted state of one service container."""
|
|
91
|
+
|
|
92
|
+
id: str
|
|
93
|
+
service: str
|
|
94
|
+
status: str
|
|
95
|
+
exit_code: int
|
|
96
|
+
oom_killed: bool
|
|
97
|
+
restart_count: int
|
|
98
|
+
health: str | None
|
|
99
|
+
networks: tuple[str, ...]
|
|
100
|
+
published: tuple[
|
|
101
|
+
tuple[int, str, str, str], ...
|
|
102
|
+
] # (container port, protocol, host ip, host port)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class Snapshot:
|
|
107
|
+
"""Everything one live collection found, with the evidence items to cite."""
|
|
108
|
+
|
|
109
|
+
project: str
|
|
110
|
+
containers: dict[str, Container] = field(default_factory=dict)
|
|
111
|
+
items: dict[str, EvidenceItem] = field(default_factory=dict)
|
|
112
|
+
host_checks: list[tuple[str, EvidenceItem]] = field(default_factory=list) # (service, item)
|
|
113
|
+
logs: dict[str, EvidenceItem] = field(default_factory=dict) # PostgreSQL services
|
|
114
|
+
probes: list[tuple[str, EvidenceItem]] = field(default_factory=list) # (source, item)
|
|
115
|
+
pg_checks: list[tuple[str, str, EvidenceItem]] = field(default_factory=list) # (source, target)
|
|
116
|
+
probe_errors: int = 0
|
|
117
|
+
complete: bool = True
|
|
118
|
+
|
|
119
|
+
def summary(self) -> LiveSummary:
|
|
120
|
+
return LiveSummary(
|
|
121
|
+
status="checked" if self.containers else "not_running",
|
|
122
|
+
containers=len(self.containers),
|
|
123
|
+
host_checks=len(self.host_checks),
|
|
124
|
+
logs=len(self.logs),
|
|
125
|
+
probes=len(self.probes) + len(self.pg_checks),
|
|
126
|
+
probe_errors=self.probe_errors,
|
|
127
|
+
complete=self.complete,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def evidence(self) -> tuple[EvidenceItem, ...]:
|
|
131
|
+
return (
|
|
132
|
+
*self.items.values(),
|
|
133
|
+
*(item for _, item in self.host_checks),
|
|
134
|
+
*self.logs.values(),
|
|
135
|
+
*(item for _, item in self.probes),
|
|
136
|
+
*(item for _, _, item in self.pg_checks),
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def tcp_connect(host: str, port: int, timeout: float) -> TcpResult:
|
|
141
|
+
"""Connect over TCP, wait briefly for the peer, and close. Sends nothing.
|
|
142
|
+
|
|
143
|
+
Docker's port proxy accepts a host connection even when nothing listens
|
|
144
|
+
inside the container, then closes it at once. So an accepted connection
|
|
145
|
+
is followed by a short read: a peer that hangs up immediately is
|
|
146
|
+
``closed``; one that waits (most servers wait for the client) or sends a
|
|
147
|
+
greeting is ``open``.
|
|
148
|
+
|
|
149
|
+
A peer that accepts and resets at once is ``closed`` too, wherever the
|
|
150
|
+
reset surfaces. Usually ``recv`` reports it, but on Linux it can arrive
|
|
151
|
+
before ``connect`` has finished: with a timeout, CPython connects
|
|
152
|
+
without blocking and then reads the result with ``getsockopt(SO_ERROR)``,
|
|
153
|
+
which is then ECONNRESET, so `create_connection` itself raises
|
|
154
|
+
`ConnectionResetError`. (A reset in answer to the connection request is
|
|
155
|
+
ECONNREFUSED, ``refused``.)
|
|
156
|
+
"""
|
|
157
|
+
try:
|
|
158
|
+
with socket.create_connection((host, port), timeout=timeout) as connection:
|
|
159
|
+
connection.settimeout(PEER_WAIT_SECONDS)
|
|
160
|
+
try:
|
|
161
|
+
return "open" if connection.recv(1) else "closed"
|
|
162
|
+
except TimeoutError:
|
|
163
|
+
return "open"
|
|
164
|
+
except ConnectionResetError:
|
|
165
|
+
return "closed"
|
|
166
|
+
except ConnectionRefusedError:
|
|
167
|
+
return "refused"
|
|
168
|
+
except TimeoutError:
|
|
169
|
+
return "timeout"
|
|
170
|
+
except OSError:
|
|
171
|
+
return "error"
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def collect(
|
|
175
|
+
project: ComposeProject,
|
|
176
|
+
*,
|
|
177
|
+
runner: ComposeRunner = subprocess_runner,
|
|
178
|
+
connect: Connector = tcp_connect,
|
|
179
|
+
clock: Clock = lambda: datetime.now(UTC),
|
|
180
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
181
|
+
budget: float = DEFAULT_BUDGET_SECONDS,
|
|
182
|
+
probe: bool = False,
|
|
183
|
+
) -> Snapshot:
|
|
184
|
+
"""Inspect the running containers of ``project`` and check published ports.
|
|
185
|
+
|
|
186
|
+
Also reads the newest log lines of PostgreSQL containers for known errors.
|
|
187
|
+
With ``probe``, runs short-lived probe containers on the project's networks
|
|
188
|
+
(`stackdoctor.probes`). All steps share one time budget.
|
|
189
|
+
|
|
190
|
+
Raises:
|
|
191
|
+
LiveUnavailableError: if Docker cannot be reached or answers unexpectedly.
|
|
192
|
+
"""
|
|
193
|
+
deadline = time.monotonic() + budget
|
|
194
|
+
snapshot = _inspect(project, runner=runner, clock=clock, timeout=timeout)
|
|
195
|
+
if not snapshot.containers:
|
|
196
|
+
return snapshot
|
|
197
|
+
_check_host_ports(snapshot, connect=connect, clock=clock, deadline=deadline)
|
|
198
|
+
_read_postgres_logs(
|
|
199
|
+
project, snapshot, runner=runner, clock=clock, timeout=timeout, deadline=deadline
|
|
200
|
+
)
|
|
201
|
+
if probe:
|
|
202
|
+
_run_probes(project, snapshot, runner=runner, clock=clock, deadline=deadline)
|
|
203
|
+
return snapshot
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def check_docker(
|
|
207
|
+
project: ComposeProject,
|
|
208
|
+
*,
|
|
209
|
+
runner: ComposeRunner = subprocess_runner,
|
|
210
|
+
timeout: float = DEFAULT_TIMEOUT_SECONDS,
|
|
211
|
+
) -> None:
|
|
212
|
+
"""Check, read-only, that Docker answers for ``project`` (`docker ps`, `docker inspect`).
|
|
213
|
+
|
|
214
|
+
A cheap pre-flight for callers that run live checks later, such as
|
|
215
|
+
`stackdoctor diagnose --live`.
|
|
216
|
+
|
|
217
|
+
Raises:
|
|
218
|
+
LiveUnavailableError: if Docker cannot be reached or answers unexpectedly.
|
|
219
|
+
"""
|
|
220
|
+
_inspect(project, runner=runner, clock=lambda: datetime.now(UTC), timeout=timeout)
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _inspect(
|
|
224
|
+
project: ComposeProject, *, runner: ComposeRunner, clock: Clock, timeout: float
|
|
225
|
+
) -> Snapshot:
|
|
226
|
+
snapshot = Snapshot(project.name)
|
|
227
|
+
cwd = Path.cwd()
|
|
228
|
+
|
|
229
|
+
listing = _docker(
|
|
230
|
+
runner,
|
|
231
|
+
[
|
|
232
|
+
"docker",
|
|
233
|
+
"ps",
|
|
234
|
+
"--all",
|
|
235
|
+
"--no-trunc",
|
|
236
|
+
"--filter",
|
|
237
|
+
f"label={COMPOSE_PROJECT_LABEL}={project.name}",
|
|
238
|
+
"--filter",
|
|
239
|
+
"label=com.docker.compose.oneoff=False",
|
|
240
|
+
"--format",
|
|
241
|
+
"{{.ID}}",
|
|
242
|
+
],
|
|
243
|
+
cwd=cwd,
|
|
244
|
+
timeout=timeout,
|
|
245
|
+
)
|
|
246
|
+
ids = listing.split()
|
|
247
|
+
if not ids:
|
|
248
|
+
return snapshot
|
|
249
|
+
|
|
250
|
+
inspected = _docker(
|
|
251
|
+
runner, ["docker", "inspect", "--format", INSPECT_TEMPLATE, *ids], cwd=cwd, timeout=timeout
|
|
252
|
+
)
|
|
253
|
+
now = clock()
|
|
254
|
+
known = {service.name for service in project.services}
|
|
255
|
+
for line in inspected.splitlines():
|
|
256
|
+
if not line.strip():
|
|
257
|
+
continue
|
|
258
|
+
container = _parse_container(line)
|
|
259
|
+
if container.service not in known or container.service in snapshot.containers:
|
|
260
|
+
continue # not in the configuration (orphan), or a scaled replica
|
|
261
|
+
snapshot.containers[container.service] = container
|
|
262
|
+
snapshot.items[container.service] = EvidenceItem(
|
|
263
|
+
id=f"inspect:{container.service}",
|
|
264
|
+
source="container_inspect",
|
|
265
|
+
subject=container.service,
|
|
266
|
+
description=f"docker inspect {container.service} (allowlisted state fields)",
|
|
267
|
+
collected_at=now,
|
|
268
|
+
data=_container_data(container),
|
|
269
|
+
)
|
|
270
|
+
return snapshot
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _check_host_ports(
|
|
274
|
+
snapshot: Snapshot, *, connect: Connector, clock: Clock, deadline: float
|
|
275
|
+
) -> None:
|
|
276
|
+
for service, container in sorted(snapshot.containers.items()):
|
|
277
|
+
if container.status != "running":
|
|
278
|
+
continue
|
|
279
|
+
for target, protocol, host_ip, host_port in container.published:
|
|
280
|
+
if protocol != "tcp" or not host_port.isdigit():
|
|
281
|
+
continue
|
|
282
|
+
if len(snapshot.host_checks) >= MAX_HOST_CHECKS or time.monotonic() > deadline:
|
|
283
|
+
snapshot.complete = False
|
|
284
|
+
return
|
|
285
|
+
address = _reachable_address(host_ip)
|
|
286
|
+
started = time.monotonic()
|
|
287
|
+
result = connect(address, int(host_port), TCP_TIMEOUT_SECONDS)
|
|
288
|
+
elapsed_ms = round((time.monotonic() - started) * 1000)
|
|
289
|
+
snapshot.host_checks.append(
|
|
290
|
+
(
|
|
291
|
+
service,
|
|
292
|
+
EvidenceItem(
|
|
293
|
+
id=f"host:{service}:{host_port}",
|
|
294
|
+
source="host_probe",
|
|
295
|
+
subject=service,
|
|
296
|
+
description=f"TCP connect from the host to {address}:{host_port}",
|
|
297
|
+
collected_at=clock(),
|
|
298
|
+
data={
|
|
299
|
+
"address": address,
|
|
300
|
+
"port": int(host_port),
|
|
301
|
+
"container_port": target,
|
|
302
|
+
"result": result,
|
|
303
|
+
"elapsed_ms": elapsed_ms,
|
|
304
|
+
},
|
|
305
|
+
),
|
|
306
|
+
)
|
|
307
|
+
)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _read_postgres_logs(
|
|
311
|
+
project: ComposeProject,
|
|
312
|
+
snapshot: Snapshot,
|
|
313
|
+
*,
|
|
314
|
+
runner: ComposeRunner,
|
|
315
|
+
clock: Clock,
|
|
316
|
+
timeout: float,
|
|
317
|
+
deadline: float,
|
|
318
|
+
) -> None:
|
|
319
|
+
"""Count known FATAL events in the newest log lines of PostgreSQL containers."""
|
|
320
|
+
for service in project.services:
|
|
321
|
+
container = snapshot.containers.get(service.name)
|
|
322
|
+
if container is None or not is_postgres(service):
|
|
323
|
+
continue
|
|
324
|
+
if time.monotonic() > deadline:
|
|
325
|
+
snapshot.complete = False
|
|
326
|
+
return
|
|
327
|
+
args = ["docker", "logs", "--tail", str(LOG_TAIL_LINES), container.id]
|
|
328
|
+
try:
|
|
329
|
+
result = runner(args, cwd=Path.cwd(), timeout=timeout)
|
|
330
|
+
except subprocess.TimeoutExpired:
|
|
331
|
+
snapshot.complete = False
|
|
332
|
+
continue
|
|
333
|
+
if result.returncode != 0:
|
|
334
|
+
continue
|
|
335
|
+
# The server logs to stderr; the raw lines are not kept.
|
|
336
|
+
lines = (result.stdout + "\n" + result.stderr).splitlines()
|
|
337
|
+
events = parse_events(lines)
|
|
338
|
+
snapshot.logs[service.name] = EvidenceItem(
|
|
339
|
+
id=f"log:{service.name}",
|
|
340
|
+
source="container_log",
|
|
341
|
+
subject=service.name,
|
|
342
|
+
description=(
|
|
343
|
+
f"docker logs --tail {LOG_TAIL_LINES} {service.name} "
|
|
344
|
+
"(known PostgreSQL errors only; no raw lines)"
|
|
345
|
+
),
|
|
346
|
+
collected_at=clock(),
|
|
347
|
+
data={
|
|
348
|
+
"lines_read": min(len(lines), LOG_TAIL_LINES),
|
|
349
|
+
"events": [
|
|
350
|
+
{
|
|
351
|
+
"kind": event.kind,
|
|
352
|
+
"name": event.name,
|
|
353
|
+
"count": event.count,
|
|
354
|
+
"last_seen": event.last_seen,
|
|
355
|
+
}
|
|
356
|
+
for event in events
|
|
357
|
+
],
|
|
358
|
+
},
|
|
359
|
+
)
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def _run_probes(
|
|
363
|
+
project: ComposeProject,
|
|
364
|
+
snapshot: Snapshot,
|
|
365
|
+
*,
|
|
366
|
+
runner: ComposeRunner,
|
|
367
|
+
clock: Clock,
|
|
368
|
+
deadline: float,
|
|
369
|
+
) -> None:
|
|
370
|
+
"""Probe each service's references from its own networks."""
|
|
371
|
+
services = {service.name: service for service in project.services}
|
|
372
|
+
resources = {
|
|
373
|
+
network.name: network.resource_name or network.name for network in project.networks
|
|
374
|
+
}
|
|
375
|
+
by_source: dict[str, list[HostReference]] = {}
|
|
376
|
+
for ref in find_host_references(project.services):
|
|
377
|
+
if ref.category in ("service", "unknown") and can_probe(ref.host):
|
|
378
|
+
by_source.setdefault(ref.source, []).append(ref)
|
|
379
|
+
|
|
380
|
+
def budget_left() -> bool:
|
|
381
|
+
if (
|
|
382
|
+
time.monotonic() > deadline
|
|
383
|
+
or len(snapshot.probes) + len(snapshot.pg_checks) >= MAX_PROBE_CONTAINERS
|
|
384
|
+
):
|
|
385
|
+
snapshot.complete = False
|
|
386
|
+
return False
|
|
387
|
+
return True
|
|
388
|
+
|
|
389
|
+
for source, refs in sorted(by_source.items()):
|
|
390
|
+
service = services[source]
|
|
391
|
+
if service.network_mode or not service.networks:
|
|
392
|
+
continue # host/none/shared namespaces are not modeled
|
|
393
|
+
networks = [resources.get(name, name) for name in service.networks]
|
|
394
|
+
targets: list[Target] = []
|
|
395
|
+
for ref in refs:
|
|
396
|
+
# A service that is not running cannot answer; that is SD201's job.
|
|
397
|
+
if ref.category == "service" and not _running(snapshot, ref.target):
|
|
398
|
+
continue
|
|
399
|
+
target = Target(ref.host, ref.port)
|
|
400
|
+
if target not in targets:
|
|
401
|
+
targets.append(target)
|
|
402
|
+
if targets and budget_left():
|
|
403
|
+
name = probe_name()
|
|
404
|
+
outcome = run_probe(runner, dns_tcp_command(name, networks, targets), name)
|
|
405
|
+
if outcome is None or outcome[0] != 0:
|
|
406
|
+
snapshot.probe_errors += 1
|
|
407
|
+
else:
|
|
408
|
+
snapshot.probes.append(
|
|
409
|
+
(
|
|
410
|
+
source,
|
|
411
|
+
EvidenceItem(
|
|
412
|
+
id=f"probe:{source}",
|
|
413
|
+
source="network_probe",
|
|
414
|
+
subject=source,
|
|
415
|
+
description=(
|
|
416
|
+
f"DNS and TCP checks from a probe container on {source}'s "
|
|
417
|
+
f"networks ({', '.join(networks)})"
|
|
418
|
+
),
|
|
419
|
+
collected_at=clock(),
|
|
420
|
+
data=_probe_data(networks, parse_dns_tcp(outcome[1], targets)),
|
|
421
|
+
),
|
|
422
|
+
)
|
|
423
|
+
)
|
|
424
|
+
|
|
425
|
+
checked: set[tuple[str, int]] = set()
|
|
426
|
+
for ref in refs:
|
|
427
|
+
target_service = services.get(ref.target or "")
|
|
428
|
+
if target_service is None or not is_postgres(target_service):
|
|
429
|
+
continue
|
|
430
|
+
port = ref.port or POSTGRES_DEFAULT_PORT
|
|
431
|
+
if (
|
|
432
|
+
not _running(snapshot, target_service.name)
|
|
433
|
+
or (target_service.name, port) in checked
|
|
434
|
+
):
|
|
435
|
+
continue
|
|
436
|
+
checked.add((target_service.name, port))
|
|
437
|
+
if not target_service.image or not budget_left():
|
|
438
|
+
continue
|
|
439
|
+
name = probe_name()
|
|
440
|
+
command = pg_isready_command(name, networks, target_service.image, ref.host, port)
|
|
441
|
+
outcome = run_probe(runner, command, name)
|
|
442
|
+
result = "timeout" if outcome is None else pg_result(outcome[0])
|
|
443
|
+
if result == "unknown":
|
|
444
|
+
snapshot.probe_errors += 1 # Docker could not run it (for example, no image)
|
|
445
|
+
continue
|
|
446
|
+
snapshot.pg_checks.append(
|
|
447
|
+
(
|
|
448
|
+
source,
|
|
449
|
+
target_service.name,
|
|
450
|
+
EvidenceItem(
|
|
451
|
+
id=f"pg:{source}:{target_service.name}:{port}",
|
|
452
|
+
source="network_probe",
|
|
453
|
+
subject=source,
|
|
454
|
+
description=(
|
|
455
|
+
f"pg_isready -h {ref.host} -p {port} from a probe container on "
|
|
456
|
+
f"{source}'s networks (no credentials sent)"
|
|
457
|
+
),
|
|
458
|
+
collected_at=clock(),
|
|
459
|
+
data={"host": ref.host, "port": port, "result": result},
|
|
460
|
+
),
|
|
461
|
+
)
|
|
462
|
+
)
|
|
463
|
+
|
|
464
|
+
|
|
465
|
+
def _probe_data(networks: list[str], checks: list[dict[str, Any]]) -> dict[str, Any]:
|
|
466
|
+
return {"networks": networks, "checks": checks}
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
def _running(snapshot: Snapshot, service: str | None) -> bool:
|
|
470
|
+
container = snapshot.containers.get(service or "")
|
|
471
|
+
return container is not None and container.status == "running"
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
# --- Live rules --------------------------------------------------------------------
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def container_not_running(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
478
|
+
"""SD201: a service's container exited with an error, is restarting, or is dead."""
|
|
479
|
+
for service, container in sorted(snapshot.containers.items()):
|
|
480
|
+
item = snapshot.items[service]
|
|
481
|
+
if container.status == "restarting":
|
|
482
|
+
problem = f"is restarting (restarted {container.restart_count} times)"
|
|
483
|
+
elif container.status == "exited" and (container.exit_code != 0 or container.oom_killed):
|
|
484
|
+
reason = "was killed for running out of memory" if container.oom_killed else ""
|
|
485
|
+
problem = f"exited with code {container.exit_code}" + (
|
|
486
|
+
f" and {reason}" if reason else ""
|
|
487
|
+
)
|
|
488
|
+
elif container.status == "dead":
|
|
489
|
+
problem = "is dead"
|
|
490
|
+
else:
|
|
491
|
+
continue
|
|
492
|
+
yield Finding(
|
|
493
|
+
rule_id="SD201",
|
|
494
|
+
severity=Severity.ERROR,
|
|
495
|
+
title=f"{service} is not running",
|
|
496
|
+
message=f"The container of {service} {problem}.",
|
|
497
|
+
service=service,
|
|
498
|
+
hint=f"Check its logs: docker compose logs {service}",
|
|
499
|
+
evidence=(
|
|
500
|
+
make_item_evidence(item, "status"),
|
|
501
|
+
make_item_evidence(item, "exit_code"),
|
|
502
|
+
make_item_evidence(item, "restart_count"),
|
|
503
|
+
),
|
|
504
|
+
)
|
|
505
|
+
|
|
506
|
+
|
|
507
|
+
def container_unhealthy(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
508
|
+
"""SD202: a running container's health check reports unhealthy."""
|
|
509
|
+
for service, container in sorted(snapshot.containers.items()):
|
|
510
|
+
if container.status != "running" or container.health != "unhealthy":
|
|
511
|
+
continue
|
|
512
|
+
yield Finding(
|
|
513
|
+
rule_id="SD202",
|
|
514
|
+
severity=Severity.ERROR,
|
|
515
|
+
title=f"{service} is unhealthy",
|
|
516
|
+
message=f"{service} is running, but its health check reports it unhealthy.",
|
|
517
|
+
service=service,
|
|
518
|
+
hint=f"See the health check output: docker compose ps {service}, then docker inspect.",
|
|
519
|
+
evidence=(make_item_evidence(snapshot.items[service], "health"),),
|
|
520
|
+
)
|
|
521
|
+
|
|
522
|
+
|
|
523
|
+
def stale_networks(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
524
|
+
"""SD203: a running container is not on a network its configuration lists."""
|
|
525
|
+
resources = {
|
|
526
|
+
network.name: network.resource_name or network.name for network in project.networks
|
|
527
|
+
}
|
|
528
|
+
for service in project.services:
|
|
529
|
+
container = snapshot.containers.get(service.name)
|
|
530
|
+
if container is None or container.status != "running" or service.network_mode:
|
|
531
|
+
continue
|
|
532
|
+
missing = sorted(
|
|
533
|
+
name for name in service.networks if resources.get(name, name) not in container.networks
|
|
534
|
+
)
|
|
535
|
+
if not missing:
|
|
536
|
+
continue
|
|
537
|
+
yield Finding(
|
|
538
|
+
rule_id="SD203",
|
|
539
|
+
severity=Severity.ERROR,
|
|
540
|
+
title=f"{service.name} is not on {', '.join(missing)}",
|
|
541
|
+
message=(
|
|
542
|
+
f"The configuration attaches {service.name} to {', '.join(missing)}, but its "
|
|
543
|
+
"running container is not on it. The container was probably created from an "
|
|
544
|
+
"older version of the configuration, so names on that network do not resolve."
|
|
545
|
+
),
|
|
546
|
+
service=service.name,
|
|
547
|
+
hint="Recreate it: docker compose up -d " + service.name,
|
|
548
|
+
evidence=(
|
|
549
|
+
make_item_evidence(config_item(project), "services", service.name, "networks"),
|
|
550
|
+
make_item_evidence(snapshot.items[service.name], "networks"),
|
|
551
|
+
),
|
|
552
|
+
)
|
|
553
|
+
|
|
554
|
+
|
|
555
|
+
def host_port_unreachable(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
556
|
+
"""SD204: a published port does not accept connections from the host."""
|
|
557
|
+
for service, item in snapshot.host_checks:
|
|
558
|
+
if item.data["result"] == "open":
|
|
559
|
+
continue
|
|
560
|
+
address, port, result = item.data["address"], item.data["port"], item.data["result"]
|
|
561
|
+
target = item.data["container_port"]
|
|
562
|
+
if result == "closed":
|
|
563
|
+
cause = (
|
|
564
|
+
f"the connection was accepted and closed at once, which is what Docker does "
|
|
565
|
+
f"when nothing listens on port {target} inside the container"
|
|
566
|
+
)
|
|
567
|
+
else:
|
|
568
|
+
cause = f"the connection failed ({result})"
|
|
569
|
+
yield Finding(
|
|
570
|
+
rule_id="SD204",
|
|
571
|
+
severity=Severity.WARNING,
|
|
572
|
+
title=f"{address}:{port} does not answer",
|
|
573
|
+
message=(
|
|
574
|
+
f"{service} publishes container port {target} on the host as {port}, but "
|
|
575
|
+
f"{cause}. The process may listen on another port, or only on its own "
|
|
576
|
+
"localhost."
|
|
577
|
+
),
|
|
578
|
+
service=service,
|
|
579
|
+
hint=f"Check that {service} listens on 0.0.0.0:{target} inside the container.",
|
|
580
|
+
evidence=(make_item_evidence(item, "result"),),
|
|
581
|
+
)
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def name_does_not_resolve(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
585
|
+
"""SD205: a host a service connects to does not resolve on that service's networks."""
|
|
586
|
+
for source, item in snapshot.probes:
|
|
587
|
+
for index, check in enumerate(_checks(item)):
|
|
588
|
+
if check["dns"] != "fail":
|
|
589
|
+
continue
|
|
590
|
+
networks = ", ".join(str(n) for n in _list(item.data["networks"]))
|
|
591
|
+
yield Finding(
|
|
592
|
+
rule_id="SD205",
|
|
593
|
+
severity=Severity.ERROR,
|
|
594
|
+
title=f'"{check["host"]}" does not resolve for {source}',
|
|
595
|
+
message=(
|
|
596
|
+
f"A probe on {source}'s networks ({networks}) could not resolve "
|
|
597
|
+
f'"{check["host"]}", so {source} cannot reach it by that name.'
|
|
598
|
+
),
|
|
599
|
+
service=source,
|
|
600
|
+
hint="Check the name, and that both services share a network.",
|
|
601
|
+
evidence=(make_item_evidence(item, "checks", index, "dns"),),
|
|
602
|
+
)
|
|
603
|
+
|
|
604
|
+
|
|
605
|
+
def port_unreachable(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
606
|
+
"""SD206: a host resolves, but nothing accepts connections on the port used."""
|
|
607
|
+
for source, item in snapshot.probes:
|
|
608
|
+
for index, check in enumerate(_checks(item)):
|
|
609
|
+
if check["dns"] != "ok" or check["tcp"] != "fail":
|
|
610
|
+
continue
|
|
611
|
+
yield Finding(
|
|
612
|
+
rule_id="SD206",
|
|
613
|
+
severity=Severity.ERROR,
|
|
614
|
+
title=f"{check['host']}:{check['port']} refuses connections from {source}",
|
|
615
|
+
message=(
|
|
616
|
+
f"{check['host']} resolves on {source}'s networks, but a TCP connection "
|
|
617
|
+
f"to port {check['port']} failed. Nothing listens on that port, or the "
|
|
618
|
+
"service only listens on its own localhost."
|
|
619
|
+
),
|
|
620
|
+
service=source,
|
|
621
|
+
hint="Use the port the service listens on inside the container.",
|
|
622
|
+
evidence=(
|
|
623
|
+
make_item_evidence(item, "checks", index, "dns"),
|
|
624
|
+
make_item_evidence(item, "checks", index, "tcp"),
|
|
625
|
+
),
|
|
626
|
+
)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def postgres_not_accepting(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
630
|
+
"""SD207: PostgreSQL does not accept connections (pg_isready from the client's networks)."""
|
|
631
|
+
for source, target, item in snapshot.pg_checks:
|
|
632
|
+
result = item.data["result"]
|
|
633
|
+
if result == "accepting":
|
|
634
|
+
continue
|
|
635
|
+
starting = result == "rejecting"
|
|
636
|
+
yield Finding(
|
|
637
|
+
rule_id="SD207",
|
|
638
|
+
severity=Severity.WARNING if starting else Severity.ERROR,
|
|
639
|
+
title=f"{target} does not accept connections from {source}",
|
|
640
|
+
message=(
|
|
641
|
+
f"pg_isready from {source}'s networks reports {result} for "
|
|
642
|
+
f"{item.data['host']}:{item.data['port']}"
|
|
643
|
+
+ (
|
|
644
|
+
" (the server is up but refuses connections, for example while it starts)."
|
|
645
|
+
if starting
|
|
646
|
+
else "."
|
|
647
|
+
)
|
|
648
|
+
),
|
|
649
|
+
service=source,
|
|
650
|
+
hint=f"Check the logs of {target}: docker compose logs {target}",
|
|
651
|
+
evidence=(make_item_evidence(item, "result"),),
|
|
652
|
+
)
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
_LOG_RULES = {
|
|
656
|
+
"auth_failed": (
|
|
657
|
+
"SD208",
|
|
658
|
+
'password authentication failed for user "{name}"',
|
|
659
|
+
"A client's password does not match the user's. If the configured passwords "
|
|
660
|
+
"match, the data volume was probably initialized with an older POSTGRES_PASSWORD, "
|
|
661
|
+
"which only applies to an empty data directory.",
|
|
662
|
+
),
|
|
663
|
+
"database_missing": (
|
|
664
|
+
"SD209",
|
|
665
|
+
'database "{name}" does not exist',
|
|
666
|
+
"Create the database (an init script, or POSTGRES_DB on an empty data directory), "
|
|
667
|
+
"or connect to an existing one.",
|
|
668
|
+
),
|
|
669
|
+
"role_missing": (
|
|
670
|
+
"SD210",
|
|
671
|
+
'role "{name}" does not exist',
|
|
672
|
+
"Create the role, or connect as an existing user. POSTGRES_USER only applies to an "
|
|
673
|
+
"empty data directory.",
|
|
674
|
+
),
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
def postgres_log_errors(project: ComposeProject, snapshot: Snapshot) -> Iterable[Finding]:
|
|
679
|
+
"""SD208-SD210: connection errors PostgreSQL itself logged."""
|
|
680
|
+
for service, item in sorted(snapshot.logs.items()):
|
|
681
|
+
for index, event in enumerate(_dicts(item.data["events"])):
|
|
682
|
+
rule_id, text, hint = _LOG_RULES[str(event["kind"])]
|
|
683
|
+
error = text.format(name=event["name"])
|
|
684
|
+
seen = f", last at {event['last_seen']}" if event["last_seen"] else ""
|
|
685
|
+
yield Finding(
|
|
686
|
+
rule_id=rule_id,
|
|
687
|
+
severity=Severity.ERROR,
|
|
688
|
+
title=f"{service}: {error}",
|
|
689
|
+
message=(
|
|
690
|
+
f'{service} logged "FATAL: {error}" {event["count"]} time(s) in its '
|
|
691
|
+
f"newest {LOG_TAIL_LINES} log lines{seen}."
|
|
692
|
+
),
|
|
693
|
+
service=service,
|
|
694
|
+
hint=hint,
|
|
695
|
+
evidence=(
|
|
696
|
+
make_item_evidence(item, "events", index, "name"),
|
|
697
|
+
make_item_evidence(item, "events", index, "count"),
|
|
698
|
+
),
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
LIVE_RULES: tuple[Callable[[ComposeProject, Snapshot], Iterable[Finding]], ...] = (
|
|
703
|
+
container_not_running,
|
|
704
|
+
container_unhealthy,
|
|
705
|
+
stale_networks,
|
|
706
|
+
host_port_unreachable,
|
|
707
|
+
name_does_not_resolve,
|
|
708
|
+
port_unreachable,
|
|
709
|
+
postgres_not_accepting,
|
|
710
|
+
postgres_log_errors,
|
|
711
|
+
)
|
|
712
|
+
|
|
713
|
+
|
|
714
|
+
def _checks(item: EvidenceItem) -> list[dict[str, Any]]:
|
|
715
|
+
return _dicts(item.data["checks"])
|
|
716
|
+
|
|
717
|
+
|
|
718
|
+
def _dicts(value: Any) -> list[dict[str, Any]]:
|
|
719
|
+
# Evidence data is typed as JSON; the collectors above only write dicts here.
|
|
720
|
+
return [entry for entry in _list(value) if isinstance(entry, dict)]
|
|
721
|
+
|
|
722
|
+
|
|
723
|
+
def _list(value: Any) -> list[Any]:
|
|
724
|
+
return value if isinstance(value, list) else []
|
|
725
|
+
|
|
726
|
+
|
|
727
|
+
def live_findings(project: ComposeProject, snapshot: Snapshot) -> list[Finding]:
|
|
728
|
+
return [finding for rule in LIVE_RULES for finding in rule(project, snapshot)]
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
# --- Helpers -----------------------------------------------------------------------
|
|
732
|
+
|
|
733
|
+
|
|
734
|
+
def _docker(runner: ComposeRunner, args: Sequence[str], *, cwd: Path, timeout: float) -> str:
|
|
735
|
+
try:
|
|
736
|
+
result = runner(args, cwd=cwd, timeout=timeout)
|
|
737
|
+
except FileNotFoundError:
|
|
738
|
+
raise LiveUnavailableError("Docker CLI not found on PATH.") from None
|
|
739
|
+
except subprocess.TimeoutExpired:
|
|
740
|
+
raise LiveUnavailableError(
|
|
741
|
+
f"{args[0]} {args[1]} did not finish within {timeout:g} seconds."
|
|
742
|
+
) from None
|
|
743
|
+
if result.returncode != 0:
|
|
744
|
+
detail = safe_stderr(result.stderr)
|
|
745
|
+
message = f"{args[0]} {args[1]} failed with exit code {result.returncode}"
|
|
746
|
+
raise LiveUnavailableError(f"{message}: {detail}" if detail else f"{message}.")
|
|
747
|
+
return result.stdout
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _parse_container(line: str) -> Container:
|
|
751
|
+
try:
|
|
752
|
+
data: dict[str, Any] = json.loads(line)
|
|
753
|
+
ports: dict[str, list[dict[str, str]] | None] = data["ports"] or {}
|
|
754
|
+
published = tuple(
|
|
755
|
+
(
|
|
756
|
+
int(spec.partition("/")[0]),
|
|
757
|
+
spec.partition("/")[2] or "tcp",
|
|
758
|
+
binding["HostIp"],
|
|
759
|
+
binding["HostPort"],
|
|
760
|
+
)
|
|
761
|
+
for spec, bindings in sorted(ports.items())
|
|
762
|
+
for binding in bindings or ()
|
|
763
|
+
)
|
|
764
|
+
return Container(
|
|
765
|
+
id=str(data["id"]),
|
|
766
|
+
service=str(data["service"]),
|
|
767
|
+
status=str(data["status"]),
|
|
768
|
+
exit_code=int(data["exit_code"]),
|
|
769
|
+
oom_killed=bool(data["oom_killed"]),
|
|
770
|
+
restart_count=int(data["restart_count"]),
|
|
771
|
+
health=data["health"],
|
|
772
|
+
networks=tuple(sorted(name for name in data["networks"] if name)),
|
|
773
|
+
published=published,
|
|
774
|
+
)
|
|
775
|
+
except (ValueError, KeyError, TypeError, AttributeError):
|
|
776
|
+
# Never echo the line: it is Docker output about the user's containers.
|
|
777
|
+
raise LiveUnavailableError(
|
|
778
|
+
"docker inspect returned output StackDoctor cannot read."
|
|
779
|
+
) from None
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def _container_data(container: Container) -> dict[str, Any]:
|
|
783
|
+
return {
|
|
784
|
+
"status": container.status,
|
|
785
|
+
"exit_code": container.exit_code,
|
|
786
|
+
"oom_killed": container.oom_killed,
|
|
787
|
+
"restart_count": container.restart_count,
|
|
788
|
+
"health": container.health,
|
|
789
|
+
"networks": list(container.networks),
|
|
790
|
+
"published": [
|
|
791
|
+
{
|
|
792
|
+
"container_port": target,
|
|
793
|
+
"protocol": protocol,
|
|
794
|
+
"host_ip": host_ip,
|
|
795
|
+
"host_port": host_port,
|
|
796
|
+
}
|
|
797
|
+
for target, protocol, host_ip, host_port in container.published
|
|
798
|
+
],
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
|
|
802
|
+
def _reachable_address(host_ip: str) -> str:
|
|
803
|
+
# A port bound to all interfaces is reached through the loopback address.
|
|
804
|
+
if host_ip in ("", "0.0.0.0"):
|
|
805
|
+
return "127.0.0.1"
|
|
806
|
+
if host_ip == "::":
|
|
807
|
+
return "::1"
|
|
808
|
+
return host_ip
|