drift-dev-env 0.1.0__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.
- drift/__init__.py +1 -0
- drift/baseline.py +48 -0
- drift/cli.py +210 -0
- drift/collectors/__init__.py +1 -0
- drift/collectors/base.py +100 -0
- drift/collectors/dependency.py +67 -0
- drift/collectors/docker.py +254 -0
- drift/collectors/engine.py +114 -0
- drift/collectors/environment.py +98 -0
- drift/collectors/file_probe.py +26 -0
- drift/collectors/git.py +221 -0
- drift/collectors/registry.py +18 -0
- drift/collectors/runner.py +194 -0
- drift/collectors/runtime.py +85 -0
- drift/collectors/system.py +20 -0
- drift/comparison.py +207 -0
- drift/config.py +118 -0
- drift/exceptions.py +65 -0
- drift/live_comparison.py +68 -0
- drift/models.py +231 -0
- drift/output.py +54 -0
- drift/paths.py +143 -0
- drift/project.py +72 -0
- drift/snapshots.py +109 -0
- drift/storage.py +283 -0
- drift_dev_env-0.1.0.dist-info/METADATA +76 -0
- drift_dev_env-0.1.0.dist-info/RECORD +30 -0
- drift_dev_env-0.1.0.dist-info/WHEEL +4 -0
- drift_dev_env-0.1.0.dist-info/entry_points.txt +2 -0
- drift_dev_env-0.1.0.dist-info/licenses/LICENSE +202 -0
drift/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Drift tracks changes in local development environments."""
|
drift/baseline.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""Manage the project-local baseline pointer."""
|
|
2
|
+
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
from drift.exceptions import (
|
|
6
|
+
BaselineMissingError,
|
|
7
|
+
DriftError,
|
|
8
|
+
InvalidBaselineError,
|
|
9
|
+
StorageError,
|
|
10
|
+
)
|
|
11
|
+
from drift.models import Metadata, Snapshot
|
|
12
|
+
from drift.storage import (
|
|
13
|
+
publish_metadata,
|
|
14
|
+
read_metadata,
|
|
15
|
+
read_snapshot,
|
|
16
|
+
resolve_snapshot,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def baseline_metadata(root: Path) -> Metadata:
|
|
21
|
+
try:
|
|
22
|
+
return read_metadata(root)
|
|
23
|
+
except FileNotFoundError:
|
|
24
|
+
raise StorageError(
|
|
25
|
+
"Drift metadata is missing. Recover it or run drift init."
|
|
26
|
+
) from None
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def set_baseline(root: Path, reference: str) -> str:
|
|
30
|
+
snapshot = resolve_snapshot(root, reference)
|
|
31
|
+
metadata = baseline_metadata(root)
|
|
32
|
+
if metadata.baseline_id != snapshot.id:
|
|
33
|
+
publish_metadata(
|
|
34
|
+
root, Metadata(schema_version=1, baseline_id=snapshot.id), replace=True
|
|
35
|
+
)
|
|
36
|
+
return snapshot.id
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def baseline_snapshot(root: Path) -> Snapshot:
|
|
40
|
+
baseline_id = baseline_metadata(root).baseline_id
|
|
41
|
+
if baseline_id is None:
|
|
42
|
+
raise BaselineMissingError("Set a baseline with drift baseline set SNAPSHOT.")
|
|
43
|
+
try:
|
|
44
|
+
return read_snapshot(root, baseline_id)
|
|
45
|
+
except DriftError:
|
|
46
|
+
raise InvalidBaselineError(
|
|
47
|
+
"The baseline snapshot is missing or unreadable. Select a valid snapshot with drift baseline set."
|
|
48
|
+
) from None
|
drift/cli.py
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
"""Drift's command-line entry point."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from importlib.metadata import version
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Annotated, cast
|
|
7
|
+
|
|
8
|
+
import typer
|
|
9
|
+
|
|
10
|
+
from drift.baseline import baseline_snapshot, set_baseline
|
|
11
|
+
from drift.live_comparison import compare_live
|
|
12
|
+
from drift.models import Snapshot, is_snapshot_reference, valid_message
|
|
13
|
+
from drift.output import Report, emit, literal
|
|
14
|
+
from drift.project import initialize, initialized_project
|
|
15
|
+
from drift.snapshots import capture_snapshot, latest_snapshot, list_history, summary
|
|
16
|
+
from drift.storage import resolve_snapshot
|
|
17
|
+
|
|
18
|
+
app = typer.Typer(name="drift", add_completion=False, rich_markup_mode=None)
|
|
19
|
+
baseline = typer.Typer(name="baseline", add_completion=False, rich_markup_mode=None)
|
|
20
|
+
app.add_typer(baseline)
|
|
21
|
+
JsonOption = Annotated[bool, typer.Option("--json", help="Emit machine-readable JSON.")]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@app.callback(invoke_without_command=True)
|
|
25
|
+
def _root(
|
|
26
|
+
ctx: typer.Context,
|
|
27
|
+
project: Annotated[
|
|
28
|
+
Path | None, typer.Option("--project", help="Select the project directory.")
|
|
29
|
+
] = None,
|
|
30
|
+
show_version: Annotated[
|
|
31
|
+
bool, typer.Option("--version", help="Show the Drift version and exit.")
|
|
32
|
+
] = False,
|
|
33
|
+
) -> None:
|
|
34
|
+
"""Track changes in your development environment."""
|
|
35
|
+
if show_version:
|
|
36
|
+
typer.echo(f"drift {version('drift-dev-env')}")
|
|
37
|
+
raise typer.Exit()
|
|
38
|
+
|
|
39
|
+
ctx.obj = project
|
|
40
|
+
if ctx.invoked_subcommand is None:
|
|
41
|
+
typer.echo(ctx.get_help())
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@app.command()
|
|
45
|
+
def init(ctx: typer.Context, as_json: JsonOption = False) -> None:
|
|
46
|
+
"""Initialize Drift in this project."""
|
|
47
|
+
|
|
48
|
+
def run() -> Report:
|
|
49
|
+
created = initialize(cast(Path | None, ctx.obj))
|
|
50
|
+
return Report(
|
|
51
|
+
{"created": created},
|
|
52
|
+
"Initialized Drift project state."
|
|
53
|
+
if created
|
|
54
|
+
else "Drift project state is already initialized.",
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
emit("init", as_json, run)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.command()
|
|
61
|
+
def snapshot(
|
|
62
|
+
ctx: typer.Context,
|
|
63
|
+
message: Annotated[
|
|
64
|
+
str | None, typer.Option("--message", "-m", help="Label this snapshot.")
|
|
65
|
+
] = None,
|
|
66
|
+
as_json: JsonOption = False,
|
|
67
|
+
) -> None:
|
|
68
|
+
"""Capture the current environment."""
|
|
69
|
+
if message is not None and not valid_message(message):
|
|
70
|
+
raise typer.BadParameter(
|
|
71
|
+
"Use 1–256 characters without control characters.", param_hint="--message"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
def run() -> Report:
|
|
75
|
+
root, config = initialized_project(cast(Path | None, ctx.obj))
|
|
76
|
+
saved = capture_snapshot(root, config, message)
|
|
77
|
+
note = f" · {literal(saved.message)}" if saved.message is not None else ""
|
|
78
|
+
statuses = ", ".join(
|
|
79
|
+
f"{name} {result.status}" for name, result in saved.collectors.items()
|
|
80
|
+
)
|
|
81
|
+
return Report(
|
|
82
|
+
{"snapshot": summary(saved)},
|
|
83
|
+
f"Saved snapshot {saved.id} · {saved.created_at}{note}\n{statuses}",
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
emit("snapshot", as_json, run)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _validate_reference(reference: str) -> None:
|
|
90
|
+
if not is_snapshot_reference(reference):
|
|
91
|
+
raise typer.BadParameter(
|
|
92
|
+
"Use a canonical snapshot ID or a lowercase hex prefix of at least six characters.",
|
|
93
|
+
param_hint="SNAPSHOT",
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _snapshot_line(record: Snapshot) -> str:
|
|
98
|
+
note = f" · {literal(record.message)}" if record.message is not None else ""
|
|
99
|
+
return f"{record.id} · {record.created_at}{note}"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@app.command()
|
|
103
|
+
def history(ctx: typer.Context, as_json: JsonOption = False) -> None:
|
|
104
|
+
"""List saved snapshots from oldest to newest."""
|
|
105
|
+
|
|
106
|
+
def run() -> Report:
|
|
107
|
+
root, _ = initialized_project(cast(Path | None, ctx.obj))
|
|
108
|
+
entries = list_history(root)
|
|
109
|
+
lines = [_snapshot_line(record) for record in entries.snapshots]
|
|
110
|
+
lines.extend(
|
|
111
|
+
f"Damaged snapshot {item['id']} ({item['code']})"
|
|
112
|
+
for item in entries.damaged
|
|
113
|
+
)
|
|
114
|
+
return Report(
|
|
115
|
+
{
|
|
116
|
+
"snapshots": [summary(record) for record in entries.snapshots],
|
|
117
|
+
"damaged": entries.damaged,
|
|
118
|
+
},
|
|
119
|
+
"\n".join(lines) or "No snapshots yet.",
|
|
120
|
+
4 if entries.damaged else 0,
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
emit("history", as_json, run)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
@app.command()
|
|
127
|
+
def show(ctx: typer.Context, snapshot: str, as_json: JsonOption = False) -> None:
|
|
128
|
+
"""Show a snapshot and its collector observations."""
|
|
129
|
+
_validate_reference(snapshot)
|
|
130
|
+
|
|
131
|
+
def run() -> Report:
|
|
132
|
+
root, _ = initialized_project(cast(Path | None, ctx.obj))
|
|
133
|
+
record = resolve_snapshot(root, snapshot)
|
|
134
|
+
lines = [
|
|
135
|
+
f"Snapshot {_snapshot_line(record)}",
|
|
136
|
+
f"Schema version {record.schema_version}",
|
|
137
|
+
]
|
|
138
|
+
lines.extend(
|
|
139
|
+
f"Scope {name} = {json.dumps(value)}"
|
|
140
|
+
for name, value in record.scope.model_dump().items()
|
|
141
|
+
)
|
|
142
|
+
for collector, result in record.collectors.items():
|
|
143
|
+
lines.append(f"{collector} ({result.status})")
|
|
144
|
+
for probe, observation in result.probes.items():
|
|
145
|
+
detail = observation.model_dump()
|
|
146
|
+
status = detail.pop("status")
|
|
147
|
+
description = (
|
|
148
|
+
json.dumps(detail["value"]) if "value" in detail else detail["code"]
|
|
149
|
+
)
|
|
150
|
+
lines.append(f" {literal(probe)} ({status}) {description}")
|
|
151
|
+
return Report({"snapshot": record.model_dump()}, "\n".join(lines))
|
|
152
|
+
|
|
153
|
+
emit("show", as_json, run)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@app.command()
|
|
157
|
+
def diff(
|
|
158
|
+
ctx: typer.Context,
|
|
159
|
+
snapshot: Annotated[
|
|
160
|
+
str | None, typer.Argument(help="Snapshot ID or unique prefix.")
|
|
161
|
+
] = None,
|
|
162
|
+
as_json: JsonOption = False,
|
|
163
|
+
) -> None:
|
|
164
|
+
"""Compare the live environment with a saved snapshot."""
|
|
165
|
+
if snapshot is not None:
|
|
166
|
+
_validate_reference(snapshot)
|
|
167
|
+
|
|
168
|
+
def run() -> Report:
|
|
169
|
+
root, config = initialized_project(cast(Path | None, ctx.obj))
|
|
170
|
+
reference = (
|
|
171
|
+
latest_snapshot(root)
|
|
172
|
+
if snapshot is None
|
|
173
|
+
else resolve_snapshot(root, snapshot)
|
|
174
|
+
)
|
|
175
|
+
return compare_live(root, config, reference)
|
|
176
|
+
|
|
177
|
+
emit("diff", as_json, run)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
@baseline.callback(invoke_without_command=True)
|
|
181
|
+
def _baseline(ctx: typer.Context) -> None:
|
|
182
|
+
"""Manage the known-working baseline."""
|
|
183
|
+
if ctx.invoked_subcommand is None:
|
|
184
|
+
typer.echo(ctx.get_help())
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
@baseline.command("set")
|
|
188
|
+
def baseline_set(
|
|
189
|
+
ctx: typer.Context, snapshot: str, as_json: JsonOption = False
|
|
190
|
+
) -> None:
|
|
191
|
+
"""Make a saved snapshot the baseline."""
|
|
192
|
+
_validate_reference(snapshot)
|
|
193
|
+
|
|
194
|
+
def run() -> Report:
|
|
195
|
+
root, _ = initialized_project(cast(Path | None, ctx.obj))
|
|
196
|
+
snapshot_id = set_baseline(root, snapshot)
|
|
197
|
+
return Report({"baseline_id": snapshot_id}, f"Baseline set to {snapshot_id}")
|
|
198
|
+
|
|
199
|
+
emit("baseline set", as_json, run)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
@app.command()
|
|
203
|
+
def verify(ctx: typer.Context, as_json: JsonOption = False) -> None:
|
|
204
|
+
"""Verify the live environment against the known-working baseline."""
|
|
205
|
+
|
|
206
|
+
def run() -> Report:
|
|
207
|
+
root, config = initialized_project(cast(Path | None, ctx.obj))
|
|
208
|
+
return compare_live(root, config, baseline_snapshot(root))
|
|
209
|
+
|
|
210
|
+
emit("verify", as_json, run)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Internal collector infrastructure."""
|
drift/collectors/base.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Typed observations shared by collectors and the scheduler."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable, Mapping
|
|
4
|
+
from dataclasses import dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from time import monotonic
|
|
7
|
+
from typing import Literal
|
|
8
|
+
|
|
9
|
+
from drift.config import ProjectConfig
|
|
10
|
+
|
|
11
|
+
type CollectorId = Literal[
|
|
12
|
+
"dependency", "docker", "environment", "git", "runtime", "system"
|
|
13
|
+
]
|
|
14
|
+
type CollectorStatus = Literal[
|
|
15
|
+
"ok", "partial", "unavailable", "unsupported", "failed", "disabled"
|
|
16
|
+
]
|
|
17
|
+
type ProbeValue = bool | str | list[str] | dict[str, dict[str, int]]
|
|
18
|
+
type DiagnosticCode = Literal[
|
|
19
|
+
"executable_missing",
|
|
20
|
+
"not_found",
|
|
21
|
+
"permission_denied",
|
|
22
|
+
"timeout",
|
|
23
|
+
"output_limit",
|
|
24
|
+
"size_limit",
|
|
25
|
+
"unsafe_path",
|
|
26
|
+
"unsupported_platform",
|
|
27
|
+
"unsupported_launcher",
|
|
28
|
+
"unsupported_checkout",
|
|
29
|
+
"invalid_output",
|
|
30
|
+
"invalid_input",
|
|
31
|
+
"io_error",
|
|
32
|
+
"command_failed",
|
|
33
|
+
"collector_error",
|
|
34
|
+
"input_changed",
|
|
35
|
+
"daemon_unreachable",
|
|
36
|
+
"prerequisite_missing",
|
|
37
|
+
"not_configured",
|
|
38
|
+
"detached_head",
|
|
39
|
+
"unborn_head",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
COLLECTOR_IDS: tuple[CollectorId, ...] = (
|
|
43
|
+
"dependency",
|
|
44
|
+
"docker",
|
|
45
|
+
"environment",
|
|
46
|
+
"git",
|
|
47
|
+
"runtime",
|
|
48
|
+
"system",
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass(frozen=True)
|
|
53
|
+
class Observation:
|
|
54
|
+
value: ProbeValue
|
|
55
|
+
status: Literal["ok"] = field(default="ok", init=False)
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@dataclass(frozen=True)
|
|
59
|
+
class ProbeIssue:
|
|
60
|
+
status: Literal["unavailable", "unsupported", "failed", "not_applicable"]
|
|
61
|
+
code: DiagnosticCode
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
type ProbeResult = Observation | ProbeIssue
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def known_absence(collector: CollectorId, code: DiagnosticCode) -> bool:
|
|
68
|
+
return (collector, code) in {
|
|
69
|
+
("runtime", "executable_missing"),
|
|
70
|
+
("dependency", "not_found"),
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class CollectorResult:
|
|
76
|
+
status: CollectorStatus
|
|
77
|
+
probes: dict[str, ProbeResult]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass(frozen=True)
|
|
81
|
+
class CollectorContext:
|
|
82
|
+
root: Path
|
|
83
|
+
config: ProjectConfig
|
|
84
|
+
deadline: float
|
|
85
|
+
|
|
86
|
+
def remaining(self) -> float:
|
|
87
|
+
"""Return the time available for additional work."""
|
|
88
|
+
return max(0.0, self.deadline - monotonic())
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class CollectorSpec:
|
|
93
|
+
probe_ids: tuple[str, ...]
|
|
94
|
+
collect: Callable[[CollectorContext], Mapping[str, ProbeResult]]
|
|
95
|
+
|
|
96
|
+
def __post_init__(self) -> None:
|
|
97
|
+
if not self.probe_ids or len(set(self.probe_ids)) != len(self.probe_ids):
|
|
98
|
+
raise ValueError(
|
|
99
|
+
"A collector must declare a nonempty set of unique probe IDs."
|
|
100
|
+
)
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Hash the supported root-level dependency files."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import os
|
|
5
|
+
from typing import BinaryIO
|
|
6
|
+
|
|
7
|
+
from drift.collectors.base import CollectorContext, Observation, ProbeIssue, ProbeResult
|
|
8
|
+
from drift.collectors.file_probe import read_file
|
|
9
|
+
from drift.paths import open_project_file
|
|
10
|
+
|
|
11
|
+
_FILES = (
|
|
12
|
+
"pyproject.toml",
|
|
13
|
+
"uv.lock",
|
|
14
|
+
"requirements.txt",
|
|
15
|
+
"package.json",
|
|
16
|
+
"package-lock.json",
|
|
17
|
+
"pnpm-lock.yaml",
|
|
18
|
+
"yarn.lock",
|
|
19
|
+
"composer.json",
|
|
20
|
+
"composer.lock",
|
|
21
|
+
"go.mod",
|
|
22
|
+
"go.sum",
|
|
23
|
+
)
|
|
24
|
+
PROBE_IDS = tuple(f"manifest:{path}" for path in _FILES)
|
|
25
|
+
_FILE_LIMIT = 64 * 1024 * 1024
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _signature(stream: BinaryIO) -> tuple[int, int, int, int, int]:
|
|
29
|
+
info = os.fstat(stream.fileno())
|
|
30
|
+
return info.st_dev, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _checksum(context: CollectorContext, path: str, stream: BinaryIO) -> ProbeResult:
|
|
34
|
+
before = _signature(stream)
|
|
35
|
+
if before[2] > _FILE_LIMIT:
|
|
36
|
+
return ProbeIssue("failed", "size_limit")
|
|
37
|
+
hashed = 0
|
|
38
|
+
digest = hashlib.sha256()
|
|
39
|
+
while context.remaining():
|
|
40
|
+
chunk = stream.read(min(65536, _FILE_LIMIT + 1 - hashed))
|
|
41
|
+
if not chunk:
|
|
42
|
+
break
|
|
43
|
+
hashed += len(chunk)
|
|
44
|
+
if hashed > _FILE_LIMIT:
|
|
45
|
+
return ProbeIssue("failed", "size_limit")
|
|
46
|
+
digest.update(chunk)
|
|
47
|
+
else:
|
|
48
|
+
return ProbeIssue("failed", "timeout")
|
|
49
|
+
|
|
50
|
+
if before != _signature(stream) or hashed != before[2]:
|
|
51
|
+
return ProbeIssue("failed", "input_changed")
|
|
52
|
+
try:
|
|
53
|
+
with open_project_file(context.root, path) as current:
|
|
54
|
+
if before != _signature(current):
|
|
55
|
+
return ProbeIssue("failed", "input_changed")
|
|
56
|
+
except FileNotFoundError:
|
|
57
|
+
return ProbeIssue("failed", "input_changed")
|
|
58
|
+
return Observation(digest.hexdigest())
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def collect(context: CollectorContext) -> dict[str, ProbeResult]:
|
|
62
|
+
results: dict[str, ProbeResult] = {}
|
|
63
|
+
for path in _FILES:
|
|
64
|
+
results[f"manifest:{path}"] = read_file(
|
|
65
|
+
context, path, lambda stream: _checksum(context, path, stream)
|
|
66
|
+
)
|
|
67
|
+
return results
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
"""Collect Docker versions and project services through local endpoints only."""
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import re
|
|
5
|
+
import socket
|
|
6
|
+
import sys
|
|
7
|
+
from collections.abc import Callable
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from uuid import uuid4
|
|
10
|
+
|
|
11
|
+
from drift.collectors.base import CollectorContext, Observation, ProbeIssue, ProbeResult
|
|
12
|
+
from drift.collectors.runner import CommandOutput, run_probe
|
|
13
|
+
|
|
14
|
+
PROBE_IDS = (
|
|
15
|
+
"installed",
|
|
16
|
+
"client_version",
|
|
17
|
+
"compose_installed",
|
|
18
|
+
"compose_version",
|
|
19
|
+
"daemon_reachable",
|
|
20
|
+
"services",
|
|
21
|
+
)
|
|
22
|
+
_NOT_INSTALLED = ProbeIssue("not_applicable", "prerequisite_missing")
|
|
23
|
+
_MISSING_EXECUTABLE = ProbeIssue("unavailable", "executable_missing")
|
|
24
|
+
_OFFLINE = ProbeIssue("unavailable", "daemon_unreachable")
|
|
25
|
+
_COMMAND_FAILED = ProbeIssue("failed", "command_failed")
|
|
26
|
+
_INVALID_OUTPUT = ProbeIssue("failed", "invalid_output")
|
|
27
|
+
_SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*")
|
|
28
|
+
_VERSION = rb"v?([0-9]+(?:\.[0-9]+)+(?:[-+][a-zA-Z0-9.+-]+)?)"
|
|
29
|
+
_CLIENT_VERSION = re.compile(
|
|
30
|
+
rb"Docker version " + _VERSION + rb"(?:, build [a-zA-Z0-9._-]+)?"
|
|
31
|
+
)
|
|
32
|
+
_SHORT_VERSION = re.compile(_VERSION)
|
|
33
|
+
_COMPOSE_VERSION = re.compile(rb"(?:Docker Compose version )?" + _VERSION)
|
|
34
|
+
_STATES = {"created", "running", "paused", "restarting", "removing", "exited", "dead"}
|
|
35
|
+
_FORMAT = '{{json (.Label "com.docker.compose.service")}}\t{{json .State}}'
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _version(
|
|
39
|
+
output: CommandOutput | ProbeIssue, pattern: re.Pattern[bytes]
|
|
40
|
+
) -> ProbeResult:
|
|
41
|
+
if isinstance(output, ProbeIssue):
|
|
42
|
+
return output
|
|
43
|
+
match = pattern.fullmatch(output.stdout.strip())
|
|
44
|
+
return Observation(match[1].decode("ascii")) if match else _INVALID_OUTPUT
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _compose_exit(stderr: bytes) -> ProbeIssue:
|
|
48
|
+
missing = (
|
|
49
|
+
b"docker: unknown command: docker compose",
|
|
50
|
+
b"docker: 'compose' is not a docker command.",
|
|
51
|
+
)
|
|
52
|
+
return (
|
|
53
|
+
_MISSING_EXECUTABLE if stderr.strip().startswith(missing) else _COMMAND_FAILED
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _daemon_exit(stderr: bytes) -> ProbeIssue:
|
|
58
|
+
lines = stderr.lower().splitlines()
|
|
59
|
+
for line in lines:
|
|
60
|
+
if b"dial unix " in line:
|
|
61
|
+
if (
|
|
62
|
+
b"connect: no such file or directory" in line
|
|
63
|
+
or b"connect: connection refused" in line
|
|
64
|
+
):
|
|
65
|
+
return _OFFLINE
|
|
66
|
+
if b"connect: permission denied" in line:
|
|
67
|
+
return ProbeIssue("failed", "permission_denied")
|
|
68
|
+
if b"/pipe/docker_engine" not in line:
|
|
69
|
+
continue
|
|
70
|
+
if (
|
|
71
|
+
b"the system cannot find the file specified" in line
|
|
72
|
+
or b"connection refused" in line
|
|
73
|
+
):
|
|
74
|
+
return _OFFLINE
|
|
75
|
+
if b"access is denied" in line:
|
|
76
|
+
return ProbeIssue("failed", "permission_denied")
|
|
77
|
+
return _COMMAND_FAILED
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _endpoint() -> str | ProbeIssue:
|
|
81
|
+
if sys.platform == "win32":
|
|
82
|
+
return "npipe:////./pipe/docker_engine"
|
|
83
|
+
if sys.platform == "darwin":
|
|
84
|
+
desktop = Path.home() / ".docker/run/docker.sock"
|
|
85
|
+
if desktop.exists():
|
|
86
|
+
return f"unix://{desktop}"
|
|
87
|
+
if sys.platform.startswith("linux") or sys.platform == "darwin":
|
|
88
|
+
return "unix:///var/run/docker.sock"
|
|
89
|
+
return ProbeIssue("unsupported", "unsupported_platform")
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _socket_issue(host: str, context: CollectorContext) -> ProbeIssue | None:
|
|
93
|
+
if not host.startswith("unix://"):
|
|
94
|
+
return None
|
|
95
|
+
remaining = context.remaining()
|
|
96
|
+
if not remaining:
|
|
97
|
+
return ProbeIssue("failed", "timeout")
|
|
98
|
+
family: int | None = getattr(socket, "AF_UNIX", None)
|
|
99
|
+
if family is None:
|
|
100
|
+
return ProbeIssue("unsupported", "unsupported_platform")
|
|
101
|
+
try:
|
|
102
|
+
with socket.socket(family) as client:
|
|
103
|
+
client.settimeout(min(2, remaining))
|
|
104
|
+
client.connect(host.removeprefix("unix://"))
|
|
105
|
+
except (FileNotFoundError, ConnectionRefusedError):
|
|
106
|
+
return _OFFLINE
|
|
107
|
+
except PermissionError:
|
|
108
|
+
return ProbeIssue("failed", "permission_denied")
|
|
109
|
+
except TimeoutError:
|
|
110
|
+
return ProbeIssue("failed", "timeout")
|
|
111
|
+
except OSError:
|
|
112
|
+
return ProbeIssue("failed", "io_error")
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _services(output: CommandOutput | ProbeIssue) -> ProbeResult:
|
|
117
|
+
if isinstance(output, ProbeIssue):
|
|
118
|
+
return output
|
|
119
|
+
counts: dict[str, dict[str, int]] = {}
|
|
120
|
+
try:
|
|
121
|
+
for row in output.stdout.splitlines():
|
|
122
|
+
raw_service, raw_state = row.split(b"\t")
|
|
123
|
+
service, state = json.loads(raw_service), json.loads(raw_state)
|
|
124
|
+
if not isinstance(service, str) or not _SERVICE.fullmatch(service):
|
|
125
|
+
return _INVALID_OUTPUT
|
|
126
|
+
if not isinstance(state, str) or state not in _STATES:
|
|
127
|
+
return _INVALID_OUTPUT
|
|
128
|
+
states = counts.setdefault(service, {})
|
|
129
|
+
states[state] = states.get(state, 0) + 1
|
|
130
|
+
except (ValueError, RecursionError):
|
|
131
|
+
return _INVALID_OUTPUT
|
|
132
|
+
return Observation(
|
|
133
|
+
{name: dict(sorted(counts[name].items())) for name in sorted(counts)}
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _user_compose(
|
|
138
|
+
context: CollectorContext, isolated: Path
|
|
139
|
+
) -> CommandOutput | ProbeIssue:
|
|
140
|
+
name = "docker-compose.exe" if sys.platform == "win32" else "docker-compose"
|
|
141
|
+
try:
|
|
142
|
+
plugin = (Path.home() / ".docker/cli-plugins" / name).resolve(strict=True)
|
|
143
|
+
if plugin.is_relative_to(context.root.resolve()) or not plugin.is_file():
|
|
144
|
+
return ProbeIssue("unsupported", "unsupported_launcher")
|
|
145
|
+
except FileNotFoundError:
|
|
146
|
+
return _MISSING_EXECUTABLE
|
|
147
|
+
except (OSError, RuntimeError):
|
|
148
|
+
return ProbeIssue("failed", "io_error")
|
|
149
|
+
return run_probe(
|
|
150
|
+
plugin,
|
|
151
|
+
("version", "--short"),
|
|
152
|
+
cwd=context.root,
|
|
153
|
+
deadline=context.deadline,
|
|
154
|
+
docker_config=isolated,
|
|
155
|
+
)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def collect(context: CollectorContext) -> dict[str, ProbeResult]:
|
|
159
|
+
isolated = context.root / f".drift-docker-{uuid4().hex}"
|
|
160
|
+
try:
|
|
161
|
+
isolated.lstat()
|
|
162
|
+
except FileNotFoundError:
|
|
163
|
+
pass
|
|
164
|
+
except OSError:
|
|
165
|
+
return dict.fromkeys(PROBE_IDS, ProbeIssue("failed", "io_error"))
|
|
166
|
+
else:
|
|
167
|
+
return dict.fromkeys(PROBE_IDS, ProbeIssue("failed", "unsafe_path"))
|
|
168
|
+
|
|
169
|
+
def docker(
|
|
170
|
+
*args: str, classify: Callable[[bytes], ProbeIssue] | None = None
|
|
171
|
+
) -> CommandOutput | ProbeIssue:
|
|
172
|
+
return run_probe(
|
|
173
|
+
"docker",
|
|
174
|
+
("--config", str(isolated), *args),
|
|
175
|
+
cwd=context.root,
|
|
176
|
+
deadline=context.deadline,
|
|
177
|
+
docker_config=isolated,
|
|
178
|
+
classify_exit=classify,
|
|
179
|
+
)
|
|
180
|
+
|
|
181
|
+
project = context.config.docker.compose_project
|
|
182
|
+
results: dict[str, ProbeResult] = {
|
|
183
|
+
"services": ProbeIssue("not_applicable", "not_configured")
|
|
184
|
+
if project is None
|
|
185
|
+
else _NOT_INSTALLED
|
|
186
|
+
}
|
|
187
|
+
client = docker("--version")
|
|
188
|
+
if isinstance(client, ProbeIssue) and client != _COMMAND_FAILED:
|
|
189
|
+
results.update(dict.fromkeys(PROBE_IDS[:-1], client))
|
|
190
|
+
if client == _MISSING_EXECUTABLE:
|
|
191
|
+
results.update(dict.fromkeys(PROBE_IDS[:-1], _NOT_INSTALLED))
|
|
192
|
+
results["installed"] = Observation(False)
|
|
193
|
+
if project is not None:
|
|
194
|
+
results["services"] = results["daemon_reachable"]
|
|
195
|
+
return results
|
|
196
|
+
results["installed"] = Observation(True)
|
|
197
|
+
results["client_version"] = _version(client, _CLIENT_VERSION)
|
|
198
|
+
|
|
199
|
+
compose = docker("compose", "version", classify=_compose_exit)
|
|
200
|
+
if compose == _MISSING_EXECUTABLE:
|
|
201
|
+
compose = _user_compose(context, isolated)
|
|
202
|
+
if isinstance(compose, ProbeIssue):
|
|
203
|
+
results["compose_installed"] = (
|
|
204
|
+
Observation(False) if compose == _MISSING_EXECUTABLE else compose
|
|
205
|
+
)
|
|
206
|
+
results["compose_version"] = (
|
|
207
|
+
_NOT_INSTALLED if compose == _MISSING_EXECUTABLE else compose
|
|
208
|
+
)
|
|
209
|
+
else:
|
|
210
|
+
results["compose_installed"] = Observation(True)
|
|
211
|
+
results["compose_version"] = _version(compose, _COMPOSE_VERSION)
|
|
212
|
+
|
|
213
|
+
host = _endpoint()
|
|
214
|
+
if isinstance(host, ProbeIssue):
|
|
215
|
+
issue: ProbeIssue | None = host
|
|
216
|
+
else:
|
|
217
|
+
issue = _socket_issue(host, context)
|
|
218
|
+
if issue is None:
|
|
219
|
+
version = _version(
|
|
220
|
+
docker(
|
|
221
|
+
"--host",
|
|
222
|
+
host,
|
|
223
|
+
"version",
|
|
224
|
+
"--format",
|
|
225
|
+
"{{.Server.Version}}",
|
|
226
|
+
classify=_daemon_exit,
|
|
227
|
+
),
|
|
228
|
+
_SHORT_VERSION,
|
|
229
|
+
)
|
|
230
|
+
if isinstance(version, ProbeIssue):
|
|
231
|
+
issue = version
|
|
232
|
+
if issue is not None:
|
|
233
|
+
results["daemon_reachable"] = Observation(False) if issue == _OFFLINE else issue
|
|
234
|
+
if project is not None:
|
|
235
|
+
results["services"] = issue
|
|
236
|
+
return results
|
|
237
|
+
|
|
238
|
+
assert isinstance(host, str)
|
|
239
|
+
results["daemon_reachable"] = Observation(True)
|
|
240
|
+
if project is not None:
|
|
241
|
+
results["services"] = _services(
|
|
242
|
+
docker(
|
|
243
|
+
"--host",
|
|
244
|
+
host,
|
|
245
|
+
"container",
|
|
246
|
+
"ls",
|
|
247
|
+
"--all",
|
|
248
|
+
"--filter",
|
|
249
|
+
f"label=com.docker.compose.project={project}",
|
|
250
|
+
"--format",
|
|
251
|
+
_FORMAT,
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
return results
|