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
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""Schedule registered collectors and isolate failures."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from concurrent.futures import ThreadPoolExecutor, wait
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from time import monotonic
|
|
7
|
+
|
|
8
|
+
from drift.collectors.base import (
|
|
9
|
+
COLLECTOR_IDS,
|
|
10
|
+
CollectorContext,
|
|
11
|
+
CollectorId,
|
|
12
|
+
CollectorResult,
|
|
13
|
+
CollectorSpec,
|
|
14
|
+
CollectorStatus,
|
|
15
|
+
DiagnosticCode,
|
|
16
|
+
Observation,
|
|
17
|
+
ProbeIssue,
|
|
18
|
+
ProbeResult,
|
|
19
|
+
known_absence,
|
|
20
|
+
)
|
|
21
|
+
from drift.config import ProjectConfig
|
|
22
|
+
|
|
23
|
+
_COLLECTOR_TIMEOUT = 8.0
|
|
24
|
+
_PRIMARY_PROBE: dict[CollectorId, str] = {"docker": "installed", "git": "repository"}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def collector_status(
|
|
28
|
+
collector_id: CollectorId, probes: Mapping[str, ProbeResult]
|
|
29
|
+
) -> CollectorStatus:
|
|
30
|
+
applicable = [
|
|
31
|
+
probe for probe in probes.values() if probe.status != "not_applicable"
|
|
32
|
+
]
|
|
33
|
+
gaps = [
|
|
34
|
+
probe
|
|
35
|
+
for probe in applicable
|
|
36
|
+
if isinstance(probe, ProbeIssue)
|
|
37
|
+
and not (
|
|
38
|
+
probe.status == "unavailable" and known_absence(collector_id, probe.code)
|
|
39
|
+
)
|
|
40
|
+
]
|
|
41
|
+
if gaps:
|
|
42
|
+
if len(gaps) != len(applicable):
|
|
43
|
+
return "partial"
|
|
44
|
+
if any(probe.status == "failed" for probe in gaps):
|
|
45
|
+
return "failed"
|
|
46
|
+
if any(probe.status == "unsupported" for probe in gaps):
|
|
47
|
+
return "unsupported"
|
|
48
|
+
return "unavailable"
|
|
49
|
+
|
|
50
|
+
primary = probes.get(_PRIMARY_PROBE.get(collector_id, ""))
|
|
51
|
+
if isinstance(primary, Observation) and primary.value is False:
|
|
52
|
+
return "unavailable"
|
|
53
|
+
if (
|
|
54
|
+
collector_id == "runtime"
|
|
55
|
+
and applicable
|
|
56
|
+
and all(probe.status == "unavailable" for probe in applicable)
|
|
57
|
+
):
|
|
58
|
+
return "unavailable"
|
|
59
|
+
return "ok"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _failed(collector: CollectorSpec, code: DiagnosticCode) -> CollectorResult:
|
|
63
|
+
return CollectorResult(
|
|
64
|
+
"failed", dict.fromkeys(sorted(collector.probe_ids), ProbeIssue("failed", code))
|
|
65
|
+
)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _collect(
|
|
69
|
+
collector_id: CollectorId, collector: CollectorSpec, context: CollectorContext
|
|
70
|
+
) -> CollectorResult:
|
|
71
|
+
if not context.remaining():
|
|
72
|
+
return _failed(collector, "timeout")
|
|
73
|
+
try:
|
|
74
|
+
observations = collector.collect(context)
|
|
75
|
+
if observations.keys() != set(collector.probe_ids):
|
|
76
|
+
return _failed(collector, "collector_error")
|
|
77
|
+
probes = dict(sorted(observations.items()))
|
|
78
|
+
return CollectorResult(collector_status(collector_id, probes), probes)
|
|
79
|
+
except Exception:
|
|
80
|
+
return _failed(collector, "collector_error")
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def run_collectors(
|
|
84
|
+
root: Path, config: ProjectConfig, registry: Mapping[CollectorId, CollectorSpec]
|
|
85
|
+
) -> dict[CollectorId, CollectorResult]:
|
|
86
|
+
"""Run enabled entries from a caller-supplied internal registry in stable order."""
|
|
87
|
+
registry = {key: registry[key] for key in COLLECTOR_IDS if key in registry}
|
|
88
|
+
enabled = config.collectors.model_dump()
|
|
89
|
+
active = [key for key in registry if enabled[key]]
|
|
90
|
+
results = {key: CollectorResult("disabled", {}) for key in registry}
|
|
91
|
+
if not active:
|
|
92
|
+
return results
|
|
93
|
+
|
|
94
|
+
deadline = monotonic() + _COLLECTOR_TIMEOUT
|
|
95
|
+
pool = ThreadPoolExecutor(max_workers=len(active))
|
|
96
|
+
try:
|
|
97
|
+
futures = {
|
|
98
|
+
pool.submit(
|
|
99
|
+
_collect,
|
|
100
|
+
key,
|
|
101
|
+
registry[key],
|
|
102
|
+
CollectorContext(root, config.model_copy(deep=True), deadline),
|
|
103
|
+
): key
|
|
104
|
+
for key in active
|
|
105
|
+
}
|
|
106
|
+
finished, overdue = wait(futures, timeout=max(0.0, deadline - monotonic()))
|
|
107
|
+
for future in finished:
|
|
108
|
+
results[futures[future]] = future.result()
|
|
109
|
+
for future in overdue:
|
|
110
|
+
key = futures[future]
|
|
111
|
+
results[key] = _failed(registry[key], "timeout")
|
|
112
|
+
finally:
|
|
113
|
+
pool.shutdown(wait=False, cancel_futures=True)
|
|
114
|
+
return results
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Collect active names and dotenv declarations without recording values."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
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.config import ProjectConfig
|
|
10
|
+
|
|
11
|
+
_FILE_LIMIT = 1024 * 1024
|
|
12
|
+
_ASSIGNMENT = re.compile(r"(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def probe_ids(config: ProjectConfig) -> tuple[str, ...]:
|
|
16
|
+
return ("active", *(f"file:{path}" for path in config.environment.files))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _active(context: CollectorContext) -> ProbeResult:
|
|
20
|
+
allowlist = context.config.environment.active_allowlist
|
|
21
|
+
names = set(os.environ)
|
|
22
|
+
if os.name == "nt":
|
|
23
|
+
names = {name.upper() for name in names}
|
|
24
|
+
if allowlist is not None:
|
|
25
|
+
names.intersection_update(allowlist)
|
|
26
|
+
try:
|
|
27
|
+
for name in names:
|
|
28
|
+
name.encode("utf-8")
|
|
29
|
+
except UnicodeError:
|
|
30
|
+
return ProbeIssue("failed", "invalid_input")
|
|
31
|
+
return Observation(sorted(names))
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _closing_quote(line: str, quote: str, start: int) -> int:
|
|
35
|
+
escaped = False
|
|
36
|
+
for index in range(start, len(line)):
|
|
37
|
+
character = line[index]
|
|
38
|
+
if character == quote and not escaped:
|
|
39
|
+
return index
|
|
40
|
+
escaped = quote == '"' and character == "\\" and not escaped
|
|
41
|
+
return -1
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _declarations(context: CollectorContext, stream: BinaryIO) -> ProbeResult:
|
|
45
|
+
data = bytearray()
|
|
46
|
+
while context.remaining():
|
|
47
|
+
chunk = stream.read(min(65536, _FILE_LIMIT + 1 - len(data)))
|
|
48
|
+
if not chunk:
|
|
49
|
+
break
|
|
50
|
+
data.extend(chunk)
|
|
51
|
+
if len(data) > _FILE_LIMIT:
|
|
52
|
+
return ProbeIssue("failed", "size_limit")
|
|
53
|
+
else:
|
|
54
|
+
return ProbeIssue("failed", "timeout")
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
text = data.decode("utf-8")
|
|
58
|
+
except UnicodeError:
|
|
59
|
+
return ProbeIssue("failed", "invalid_input")
|
|
60
|
+
|
|
61
|
+
names: set[str] = set()
|
|
62
|
+
quote = ""
|
|
63
|
+
for line in text.split("\n"):
|
|
64
|
+
if not context.remaining():
|
|
65
|
+
return ProbeIssue("failed", "timeout")
|
|
66
|
+
line = line.removesuffix("\r")
|
|
67
|
+
start = 0
|
|
68
|
+
if not quote:
|
|
69
|
+
line = line.lstrip(" \t")
|
|
70
|
+
if not line or line.startswith("#"):
|
|
71
|
+
continue
|
|
72
|
+
assignment = _ASSIGNMENT.match(line)
|
|
73
|
+
if not assignment:
|
|
74
|
+
return ProbeIssue("failed", "invalid_input")
|
|
75
|
+
names.add(assignment[1])
|
|
76
|
+
start = assignment.end()
|
|
77
|
+
if line[start : start + 1] not in {"'", '"'}:
|
|
78
|
+
continue
|
|
79
|
+
quote = line[start]
|
|
80
|
+
start += 1
|
|
81
|
+
end = _closing_quote(line, quote, start)
|
|
82
|
+
if end >= 0:
|
|
83
|
+
trailing = line[end + 1 :].lstrip(" \t")
|
|
84
|
+
if trailing and not trailing.startswith("#"):
|
|
85
|
+
return ProbeIssue("failed", "invalid_input")
|
|
86
|
+
quote = ""
|
|
87
|
+
if quote:
|
|
88
|
+
return ProbeIssue("failed", "invalid_input")
|
|
89
|
+
return Observation(sorted(names))
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def collect(context: CollectorContext) -> dict[str, ProbeResult]:
|
|
93
|
+
results = {"active": _active(context)}
|
|
94
|
+
for path in context.config.environment.files:
|
|
95
|
+
results[f"file:{path}"] = read_file(
|
|
96
|
+
context, path, lambda stream: _declarations(context, stream)
|
|
97
|
+
)
|
|
98
|
+
return results
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Map project file read failures to collector diagnostics."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
from typing import BinaryIO
|
|
5
|
+
|
|
6
|
+
from drift.collectors.base import CollectorContext, ProbeIssue, ProbeResult
|
|
7
|
+
from drift.exceptions import UnsafePathError
|
|
8
|
+
from drift.paths import open_project_file
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def read_file(
|
|
12
|
+
context: CollectorContext, path: str, read: Callable[[BinaryIO], ProbeResult]
|
|
13
|
+
) -> ProbeResult:
|
|
14
|
+
if not context.remaining():
|
|
15
|
+
return ProbeIssue("failed", "timeout")
|
|
16
|
+
try:
|
|
17
|
+
with open_project_file(context.root, path) as stream:
|
|
18
|
+
return read(stream)
|
|
19
|
+
except FileNotFoundError:
|
|
20
|
+
return ProbeIssue("unavailable", "not_found")
|
|
21
|
+
except PermissionError:
|
|
22
|
+
return ProbeIssue("failed", "permission_denied")
|
|
23
|
+
except UnsafePathError:
|
|
24
|
+
return ProbeIssue("failed", "unsafe_path")
|
|
25
|
+
except OSError:
|
|
26
|
+
return ProbeIssue("failed", "io_error")
|
drift/collectors/git.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""Read Git context from a standard local checkout after a safety preflight."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import stat
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from drift.collectors.base import CollectorContext, Observation, ProbeIssue, ProbeResult
|
|
9
|
+
from drift.collectors.runner import CommandOutput, run_probe
|
|
10
|
+
|
|
11
|
+
PROBE_IDS = ("repository", "branch", "commit", "worktree")
|
|
12
|
+
_UNSAFE = ProbeIssue("unsupported", "unsupported_checkout")
|
|
13
|
+
_INVALID = ProbeIssue("failed", "invalid_output")
|
|
14
|
+
_OBJECT_ID = re.compile(rb"(?:[a-f0-9]{40}|[a-f0-9]{64})")
|
|
15
|
+
_CORE_KEYS = {
|
|
16
|
+
b"core.repositoryformatversion",
|
|
17
|
+
b"core.filemode",
|
|
18
|
+
b"core.bare",
|
|
19
|
+
b"core.logallrefupdates",
|
|
20
|
+
b"core.ignorecase",
|
|
21
|
+
b"core.precomposeunicode",
|
|
22
|
+
b"core.symlinks",
|
|
23
|
+
b"core.autocrlf",
|
|
24
|
+
b"core.eol",
|
|
25
|
+
b"core.safecrlf",
|
|
26
|
+
b"core.checkstat",
|
|
27
|
+
b"core.trustctime",
|
|
28
|
+
b"core.longpaths",
|
|
29
|
+
b"extensions.objectformat",
|
|
30
|
+
b"user.name",
|
|
31
|
+
b"user.email",
|
|
32
|
+
}
|
|
33
|
+
_SECTION_KEYS = {
|
|
34
|
+
b"branch": {b"remote", b"merge", b"vscode-merge-base"},
|
|
35
|
+
b"remote": {b"url", b"fetch", b"pushurl", b"push"},
|
|
36
|
+
}
|
|
37
|
+
_EXTERNAL_METADATA = {
|
|
38
|
+
"commondir",
|
|
39
|
+
"gitdir",
|
|
40
|
+
"config.worktree",
|
|
41
|
+
"objects/info/alternates",
|
|
42
|
+
"objects/info/http-alternates",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _linked(info: os.stat_result) -> bool:
|
|
47
|
+
return stat.S_ISLNK(info.st_mode) or bool(
|
|
48
|
+
getattr(info, "st_file_attributes", 0) & stat.FILE_ATTRIBUTE_REPARSE_POINT
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _raise_walk_error(error: OSError) -> None:
|
|
53
|
+
raise error
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _preflight_metadata(metadata: Path, context: CollectorContext) -> ProbeIssue | None:
|
|
57
|
+
for expected in ("HEAD", "config", "objects"):
|
|
58
|
+
try:
|
|
59
|
+
info = (metadata / expected).lstat()
|
|
60
|
+
except FileNotFoundError:
|
|
61
|
+
return _UNSAFE
|
|
62
|
+
expected_type = stat.S_ISDIR if expected == "objects" else stat.S_ISREG
|
|
63
|
+
if _linked(info) or not expected_type(info.st_mode):
|
|
64
|
+
return _UNSAFE
|
|
65
|
+
|
|
66
|
+
for directory, subdirectories, files in os.walk(
|
|
67
|
+
metadata, followlinks=False, onerror=_raise_walk_error
|
|
68
|
+
):
|
|
69
|
+
for name in (*subdirectories, *files):
|
|
70
|
+
if not context.remaining():
|
|
71
|
+
return ProbeIssue("failed", "timeout")
|
|
72
|
+
path = Path(directory) / name
|
|
73
|
+
relative = path.relative_to(metadata).as_posix()
|
|
74
|
+
if relative in _EXTERNAL_METADATA or relative.endswith(".promisor"):
|
|
75
|
+
return _UNSAFE
|
|
76
|
+
info = path.lstat()
|
|
77
|
+
if _linked(info) or not (
|
|
78
|
+
stat.S_ISDIR(info.st_mode) or stat.S_ISREG(info.st_mode)
|
|
79
|
+
):
|
|
80
|
+
return _UNSAFE
|
|
81
|
+
return None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _allowed_key(key: bytes) -> bool:
|
|
85
|
+
if key in _CORE_KEYS:
|
|
86
|
+
return True
|
|
87
|
+
parts = key.split(b".")
|
|
88
|
+
return len(parts) >= 3 and parts[-1] in _SECTION_KEYS.get(parts[0], set())
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _preflight_config(metadata: Path, context: CollectorContext) -> ProbeIssue | None:
|
|
92
|
+
def config(*args: str) -> CommandOutput | ProbeIssue:
|
|
93
|
+
return run_probe(
|
|
94
|
+
"git",
|
|
95
|
+
(
|
|
96
|
+
"--no-pager",
|
|
97
|
+
f"--git-dir={os.devnull}",
|
|
98
|
+
"config",
|
|
99
|
+
"--file",
|
|
100
|
+
str(metadata / "config"),
|
|
101
|
+
"--no-includes",
|
|
102
|
+
*args,
|
|
103
|
+
),
|
|
104
|
+
cwd=context.root,
|
|
105
|
+
deadline=context.deadline,
|
|
106
|
+
profile="git",
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
output = config("--null", "--name-only", "--list")
|
|
110
|
+
if isinstance(output, ProbeIssue):
|
|
111
|
+
return output
|
|
112
|
+
if output.stdout and not output.stdout.endswith(b"\0"):
|
|
113
|
+
return _INVALID
|
|
114
|
+
keys = output.stdout.split(b"\0")[:-1]
|
|
115
|
+
if not all(map(_allowed_key, keys)):
|
|
116
|
+
return _UNSAFE
|
|
117
|
+
if b"core.bare" in keys:
|
|
118
|
+
bare = config("--type=bool", "--get-all", "core.bare")
|
|
119
|
+
if isinstance(bare, ProbeIssue):
|
|
120
|
+
return bare
|
|
121
|
+
values = bare.stdout.splitlines()
|
|
122
|
+
if not values or any(value != b"false" for value in values):
|
|
123
|
+
return _UNSAFE
|
|
124
|
+
return None
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _status(output: bytes) -> dict[str, ProbeResult]:
|
|
128
|
+
oid = head = b""
|
|
129
|
+
dirty = False
|
|
130
|
+
if not output.endswith(b"\0"):
|
|
131
|
+
return dict.fromkeys(PROBE_IDS[1:], _INVALID)
|
|
132
|
+
for record in output.split(b"\0")[:-1]:
|
|
133
|
+
if record.startswith(b"# branch.oid "):
|
|
134
|
+
oid = record.removeprefix(b"# branch.oid ")
|
|
135
|
+
elif record.startswith(b"# branch.head "):
|
|
136
|
+
head = record.removeprefix(b"# branch.head ")
|
|
137
|
+
elif record.startswith((b"1 ", b"u ", b"? ")):
|
|
138
|
+
dirty = True
|
|
139
|
+
elif not record.startswith(b"# "):
|
|
140
|
+
return dict.fromkeys(PROBE_IDS[1:], _INVALID)
|
|
141
|
+
|
|
142
|
+
branch: ProbeResult = _INVALID
|
|
143
|
+
if head == b"(detached)":
|
|
144
|
+
branch = ProbeIssue("not_applicable", "detached_head")
|
|
145
|
+
elif head and all(byte >= 32 and byte != 127 for byte in head):
|
|
146
|
+
try:
|
|
147
|
+
branch = Observation(head.decode("utf-8"))
|
|
148
|
+
except UnicodeError:
|
|
149
|
+
pass
|
|
150
|
+
commit: ProbeResult = _INVALID
|
|
151
|
+
if oid == b"(initial)":
|
|
152
|
+
commit = ProbeIssue("not_applicable", "unborn_head")
|
|
153
|
+
elif _OBJECT_ID.fullmatch(oid):
|
|
154
|
+
commit = Observation(oid.decode("ascii"))
|
|
155
|
+
if not oid or not head:
|
|
156
|
+
return dict.fromkeys(PROBE_IDS[1:], _INVALID)
|
|
157
|
+
return {
|
|
158
|
+
"branch": branch,
|
|
159
|
+
"commit": commit,
|
|
160
|
+
"worktree": Observation("dirty" if dirty else "clean"),
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def collect(context: CollectorContext) -> dict[str, ProbeResult]:
|
|
165
|
+
metadata = context.root / ".git"
|
|
166
|
+
try:
|
|
167
|
+
info = metadata.lstat()
|
|
168
|
+
except FileNotFoundError:
|
|
169
|
+
return {
|
|
170
|
+
"repository": Observation(False),
|
|
171
|
+
**dict.fromkeys(
|
|
172
|
+
PROBE_IDS[1:], ProbeIssue("not_applicable", "prerequisite_missing")
|
|
173
|
+
),
|
|
174
|
+
}
|
|
175
|
+
except PermissionError:
|
|
176
|
+
return dict.fromkeys(PROBE_IDS, ProbeIssue("failed", "permission_denied"))
|
|
177
|
+
except OSError:
|
|
178
|
+
return dict.fromkeys(PROBE_IDS, ProbeIssue("failed", "io_error"))
|
|
179
|
+
if _linked(info) or not stat.S_ISDIR(info.st_mode):
|
|
180
|
+
return dict.fromkeys(PROBE_IDS, _UNSAFE)
|
|
181
|
+
|
|
182
|
+
try:
|
|
183
|
+
issue = _preflight_metadata(metadata, context) or _preflight_config(
|
|
184
|
+
metadata, context
|
|
185
|
+
)
|
|
186
|
+
except PermissionError:
|
|
187
|
+
issue = ProbeIssue("failed", "permission_denied")
|
|
188
|
+
except OSError:
|
|
189
|
+
issue = ProbeIssue("failed", "io_error")
|
|
190
|
+
if issue is not None:
|
|
191
|
+
return {"repository": Observation(True), **dict.fromkeys(PROBE_IDS[1:], issue)}
|
|
192
|
+
|
|
193
|
+
output = run_probe(
|
|
194
|
+
"git",
|
|
195
|
+
(
|
|
196
|
+
"--no-pager",
|
|
197
|
+
"--no-optional-locks",
|
|
198
|
+
f"--git-dir={metadata}",
|
|
199
|
+
f"--work-tree={context.root}",
|
|
200
|
+
"-c",
|
|
201
|
+
f"core.hooksPath={os.devnull}",
|
|
202
|
+
"-c",
|
|
203
|
+
f"core.attributesFile={os.devnull}",
|
|
204
|
+
"-c",
|
|
205
|
+
f"core.excludesFile={os.devnull}",
|
|
206
|
+
"status",
|
|
207
|
+
"--porcelain=v2",
|
|
208
|
+
"--branch",
|
|
209
|
+
"-z",
|
|
210
|
+
"--untracked-files=normal",
|
|
211
|
+
"--ignore-submodules=all",
|
|
212
|
+
"--no-renames",
|
|
213
|
+
"--no-ahead-behind",
|
|
214
|
+
),
|
|
215
|
+
cwd=context.root,
|
|
216
|
+
deadline=context.deadline,
|
|
217
|
+
profile="git",
|
|
218
|
+
)
|
|
219
|
+
if isinstance(output, ProbeIssue):
|
|
220
|
+
return {"repository": Observation(True), **dict.fromkeys(PROBE_IDS[1:], output)}
|
|
221
|
+
return {"repository": Observation(True), **_status(output.stdout)}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""Build the registry of collectors supported for a project."""
|
|
2
|
+
|
|
3
|
+
from drift.collectors import dependency, docker, environment, git, runtime, system
|
|
4
|
+
from drift.collectors.base import CollectorId, CollectorSpec
|
|
5
|
+
from drift.config import ProjectConfig
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def build_registry(config: ProjectConfig) -> dict[CollectorId, CollectorSpec]:
|
|
9
|
+
return {
|
|
10
|
+
"dependency": CollectorSpec(dependency.PROBE_IDS, dependency.collect),
|
|
11
|
+
"docker": CollectorSpec(docker.PROBE_IDS, docker.collect),
|
|
12
|
+
"environment": CollectorSpec(
|
|
13
|
+
environment.probe_ids(config), environment.collect
|
|
14
|
+
),
|
|
15
|
+
"git": CollectorSpec(git.PROBE_IDS, git.collect),
|
|
16
|
+
"system": CollectorSpec(system.PROBE_IDS, system.collect),
|
|
17
|
+
"runtime": CollectorSpec(runtime.PROBE_IDS, runtime.collect),
|
|
18
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Run fixed, local probe commands with bounded output and duration."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import signal
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from collections.abc import Callable, Sequence
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
from time import monotonic, sleep
|
|
12
|
+
from typing import Literal
|
|
13
|
+
|
|
14
|
+
from drift.collectors.base import ProbeIssue
|
|
15
|
+
|
|
16
|
+
_COMMAND_TIMEOUT = 2.0
|
|
17
|
+
_OUTPUT_LIMIT = 256 * 1024
|
|
18
|
+
_POLL_INTERVAL = 0.01
|
|
19
|
+
_LAUNCHER_NAME = re.compile(r"[a-zA-Z0-9_+.\-]+")
|
|
20
|
+
_WINDOWS_WRAPPERS = (".cmd", ".bat", ".ps1")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass(frozen=True)
|
|
24
|
+
class CommandOutput:
|
|
25
|
+
"""Transient output for a collector parser. Keep it out of reports."""
|
|
26
|
+
|
|
27
|
+
stdout: bytes = field(repr=False)
|
|
28
|
+
stderr: bytes = field(repr=False)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def launcher_paths() -> list[Path]:
|
|
32
|
+
"""Return absolute entries in the invoking user's PATH."""
|
|
33
|
+
return [
|
|
34
|
+
path
|
|
35
|
+
for entry in os.environ.get("PATH", "").split(os.pathsep)
|
|
36
|
+
if (path := Path(entry)).is_absolute()
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _resolve(executable: str | Path, search: Sequence[Path]) -> Path | ProbeIssue:
|
|
41
|
+
if isinstance(executable, Path):
|
|
42
|
+
if not executable.is_absolute():
|
|
43
|
+
return ProbeIssue("failed", "invalid_input")
|
|
44
|
+
return _resolve(executable.name, (executable.parent,))
|
|
45
|
+
if executable in {".", ".."} or not _LAUNCHER_NAME.fullmatch(executable):
|
|
46
|
+
return ProbeIssue("failed", "invalid_input")
|
|
47
|
+
|
|
48
|
+
windows = os.name == "nt"
|
|
49
|
+
suffix = Path(executable).suffix.lower()
|
|
50
|
+
if windows and suffix not in {".exe", *_WINDOWS_WRAPPERS}:
|
|
51
|
+
names = tuple(
|
|
52
|
+
executable + extension for extension in (".exe", *_WINDOWS_WRAPPERS)
|
|
53
|
+
)
|
|
54
|
+
else:
|
|
55
|
+
names = (executable,)
|
|
56
|
+
|
|
57
|
+
for directory in search:
|
|
58
|
+
for name in names:
|
|
59
|
+
path = directory / name
|
|
60
|
+
if path.is_file() and os.access(path, os.X_OK):
|
|
61
|
+
if windows and path.suffix.lower() != ".exe":
|
|
62
|
+
return ProbeIssue("unsupported", "unsupported_launcher")
|
|
63
|
+
return path
|
|
64
|
+
return ProbeIssue("unavailable", "executable_missing")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _capture(
|
|
68
|
+
process: subprocess.Popen[bytes],
|
|
69
|
+
deadline: float,
|
|
70
|
+
classify_exit: Callable[[bytes], ProbeIssue] | None,
|
|
71
|
+
) -> CommandOutput | ProbeIssue:
|
|
72
|
+
assert process.stdout is not None and process.stderr is not None
|
|
73
|
+
stdout, stderr = bytearray(), bytearray()
|
|
74
|
+
streams = {process.stdout.fileno(): stdout, process.stderr.fileno(): stderr}
|
|
75
|
+
for fd in streams:
|
|
76
|
+
os.set_blocking(fd, False)
|
|
77
|
+
|
|
78
|
+
remaining = _OUTPUT_LIMIT
|
|
79
|
+
while monotonic() < deadline:
|
|
80
|
+
received = False
|
|
81
|
+
for fd, output in tuple(streams.items()):
|
|
82
|
+
try:
|
|
83
|
+
chunk = os.read(fd, min(8192, remaining + 1))
|
|
84
|
+
except BlockingIOError:
|
|
85
|
+
continue
|
|
86
|
+
if not chunk:
|
|
87
|
+
del streams[fd]
|
|
88
|
+
continue
|
|
89
|
+
if len(chunk) > remaining:
|
|
90
|
+
return ProbeIssue("failed", "output_limit")
|
|
91
|
+
output.extend(chunk)
|
|
92
|
+
remaining -= len(chunk)
|
|
93
|
+
received = True
|
|
94
|
+
|
|
95
|
+
if not streams and (returncode := process.poll()) is not None:
|
|
96
|
+
if returncode != 0:
|
|
97
|
+
if classify_exit is not None:
|
|
98
|
+
return classify_exit(bytes(stderr))
|
|
99
|
+
return ProbeIssue("failed", "command_failed")
|
|
100
|
+
return CommandOutput(bytes(stdout), bytes(stderr))
|
|
101
|
+
if not received:
|
|
102
|
+
sleep(min(_POLL_INTERVAL, max(0, deadline - monotonic())))
|
|
103
|
+
return ProbeIssue("failed", "timeout")
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _stop(process: subprocess.Popen[bytes]) -> None:
|
|
107
|
+
try:
|
|
108
|
+
if sys.platform != "win32" and os.name == "posix":
|
|
109
|
+
os.killpg(process.pid, signal.SIGKILL)
|
|
110
|
+
elif process.poll() is None:
|
|
111
|
+
process.kill()
|
|
112
|
+
except ProcessLookupError:
|
|
113
|
+
pass
|
|
114
|
+
except PermissionError:
|
|
115
|
+
# Darwin can reject the group signal after the last member exits.
|
|
116
|
+
if sys.platform != "darwin" or process.poll() is None:
|
|
117
|
+
raise
|
|
118
|
+
process.wait()
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def run_probe(
|
|
122
|
+
executable: str | Path,
|
|
123
|
+
args: Sequence[str],
|
|
124
|
+
*,
|
|
125
|
+
cwd: Path,
|
|
126
|
+
deadline: float,
|
|
127
|
+
profile: Literal["default", "go", "git"] = "default",
|
|
128
|
+
docker_config: Path | None = None,
|
|
129
|
+
classify_exit: Callable[[bytes], ProbeIssue] | None = None,
|
|
130
|
+
) -> CommandOutput | ProbeIssue:
|
|
131
|
+
"""Run a trusted tool name with arguments supplied by collector code."""
|
|
132
|
+
if not cwd.is_absolute():
|
|
133
|
+
return ProbeIssue("failed", "invalid_input")
|
|
134
|
+
deadline = min(deadline, monotonic() + _COMMAND_TIMEOUT)
|
|
135
|
+
if monotonic() >= deadline:
|
|
136
|
+
return ProbeIssue("failed", "timeout")
|
|
137
|
+
|
|
138
|
+
search = launcher_paths()
|
|
139
|
+
environment = (
|
|
140
|
+
{key: os.environ[key] for key in ("SYSTEMROOT", "WINDIR") if key in os.environ}
|
|
141
|
+
if os.name == "nt"
|
|
142
|
+
else {}
|
|
143
|
+
)
|
|
144
|
+
environment.update(PATH=os.pathsep.join(map(str, search)), LC_ALL="C", LANG="C")
|
|
145
|
+
if profile == "go":
|
|
146
|
+
environment.update(GOTOOLCHAIN="local", GOENV="off")
|
|
147
|
+
elif profile == "git":
|
|
148
|
+
environment.update(
|
|
149
|
+
GIT_CONFIG_NOSYSTEM="1",
|
|
150
|
+
GIT_CONFIG_GLOBAL=os.devnull,
|
|
151
|
+
GIT_ATTR_NOSYSTEM="1",
|
|
152
|
+
GIT_ALLOW_PROTOCOL="",
|
|
153
|
+
GIT_NO_LAZY_FETCH="1",
|
|
154
|
+
GIT_NO_REPLACE_OBJECTS="1",
|
|
155
|
+
GIT_TERMINAL_PROMPT="0",
|
|
156
|
+
GIT_OPTIONAL_LOCKS="0",
|
|
157
|
+
)
|
|
158
|
+
if docker_config is not None:
|
|
159
|
+
environment["DOCKER_CONFIG"] = str(docker_config)
|
|
160
|
+
|
|
161
|
+
try:
|
|
162
|
+
if not cwd.is_dir():
|
|
163
|
+
return ProbeIssue("failed", "invalid_input")
|
|
164
|
+
launcher = _resolve(executable, search)
|
|
165
|
+
if isinstance(launcher, ProbeIssue):
|
|
166
|
+
return launcher
|
|
167
|
+
if monotonic() >= deadline:
|
|
168
|
+
return ProbeIssue("failed", "timeout")
|
|
169
|
+
with subprocess.Popen(
|
|
170
|
+
[str(launcher), *args],
|
|
171
|
+
cwd=cwd,
|
|
172
|
+
env=environment,
|
|
173
|
+
stdin=subprocess.DEVNULL,
|
|
174
|
+
stdout=subprocess.PIPE,
|
|
175
|
+
stderr=subprocess.PIPE,
|
|
176
|
+
shell=False,
|
|
177
|
+
start_new_session=os.name == "posix",
|
|
178
|
+
) as process:
|
|
179
|
+
finished = False
|
|
180
|
+
try:
|
|
181
|
+
result = _capture(process, deadline, classify_exit)
|
|
182
|
+
finished = process.returncode is not None
|
|
183
|
+
return result
|
|
184
|
+
finally:
|
|
185
|
+
if not finished:
|
|
186
|
+
_stop(process)
|
|
187
|
+
except FileNotFoundError:
|
|
188
|
+
return ProbeIssue("unavailable", "executable_missing")
|
|
189
|
+
except PermissionError:
|
|
190
|
+
return ProbeIssue("failed", "permission_denied")
|
|
191
|
+
except OSError:
|
|
192
|
+
return ProbeIssue("failed", "io_error")
|
|
193
|
+
except ValueError:
|
|
194
|
+
return ProbeIssue("failed", "invalid_input")
|