Repository navigation
Expand file tree
/
Copy pathfrost.py
More file actions
executable file
·1344 lines (1214 loc) · 45.2 KB
/
Copy pathfrost.py
File metadata and controls
executable file
·1344 lines (1214 loc) · 45.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Copyright 2026 Two Sigma Open Source, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Run FROST's reproducible development workflows in the pinned Docker image.
The container runs as the invoking user's UID and GID, so files it creates in
the bind-mounted checkout stay writable by native tools such as Vivado. A
host-owned cache directory, mounted at the container's ``~/.cache``, keeps
pre-commit hook environments and npm downloads across container runs.
"""
import argparse
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import sys
import time
from collections import Counter
from collections.abc import Callable, Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path
DEFAULT_IMAGE = "frost"
FAST_TEST_MARKERS = "not cocotb and not synthesis and not formal and not slow"
IMAGE_INPUT_FILES = ("Dockerfile", "docker_entrypoint.py")
DOCTOR_TIMEOUT_SECONDS = 30
IMAGE_REFERENCE_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._/:@+-]*$")
APP_NAME_PATTERN = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
FORWARDED_ENV_PREFIXES = ("COCOTB_", "FROST_")
FORWARDED_ENV_NAMES = {
"DDR_MODEL_BYTES",
"DDR_MODEL_LATENCY",
"ENABLE_CACHED_TIER",
"FPGA_CPU_CLK_FREQ",
"HTTP_PROXY",
"HTTPS_PROXY",
"MEMORY_LINK_STAGES",
"MISALIGNED_HW",
"NO_PROXY",
"NUMBER_OF_CPU_CORES",
"PYTEST_ADDOPTS",
"SIM_FAST_MAINT",
"SIM_MEM_SIZE_BYTES",
"WAVES",
"http_proxy",
"https_proxy",
"no_proxy",
}
COCOTB_COMMAND = (
"bash",
"-c",
'cd tests && make clean && exec ./test_run_cocotb.py "$@"',
"frost-cocotb",
)
PYTEST_COMMAND = (
"bash",
"-c",
'cd tests && make clean && exec pytest test_run_cocotb.py "$@"',
"frost-pytest",
)
CHECK_STEPS = (
("Lint", ("pre-commit", "run", "--all-files")),
(
"Fast Python Tests",
("pytest", "tests", "-m", FAST_TEST_MARKERS, "-v"),
),
)
TOOL_VERSION_ARGUMENTS = {
"verilator": "VERILATOR_VERSION",
"yosys": "YOSYS_VERSION",
"sby": "SBY_VERSION",
"z3": "Z3_VERSION",
"boolector": "BOOLECTOR_VERSION",
"riscv_gcc": "BOOTLIN_RISCV64_MUSL_VERSION",
"riscv_gdb": "BOOTLIN_RISCV64_MUSL_VERSION",
"clang": "LLVM_VERSION",
"clang_tidy": "LLVM_VERSION",
"clang_format": "LLVM_VERSION",
"python": "PYTHON_VERSION",
"gcc": "GCC_VERSION",
"cmake": "CMAKE_VERSION",
"meson": "MESON_VERSION",
"ninja": "NINJA_VERSION",
"qemu": "QEMU_VERSION",
"node": "NODE_VERSION",
"npm": "NPM_VERSION",
"pip": "PIP_VERSION",
"setuptools": "SETUPTOOLS_VERSION",
"wheel": "WHEEL_VERSION",
"openocd": "OPENOCD_VERSION",
"verible": "VERIBLE_VERSION",
"cocotb": "COCOTB_VERSION",
"pytest": "PYTEST_VERSION",
"pytest_cov": "PYTEST_COV_VERSION",
"pre_commit": "PRE_COMMIT_VERSION",
"click": "CLICK_VERSION",
}
PACKAGE_VERSION_TOOLS = {
"cocotb",
"pytest",
"pytest_cov",
"pre_commit",
"click",
"setuptools",
"wheel",
}
IMAGE_PROBE_SCRIPT = r"""
import hashlib
import importlib.metadata
import json
import os
import platform
import stat
import subprocess
def command_output(command):
try:
result = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
timeout=10,
)
except (OSError, subprocess.TimeoutExpired) as error:
return {"error": str(error)}
output = (result.stdout or result.stderr).strip()
if result.returncode != 0:
return {"error": output or f"exit {result.returncode}"}
return {"version": output}
def install_path(command):
# Verify that the program runs as well as identifying its Bootlin archive.
# GDB's banner contains its own version, not the toolchain release.
import shutil
resolved = shutil.which(command)
if not resolved:
return {"error": f"{command} not found"}
report = command_output([command, "--version"])
if "error" in report:
return report
return {"version": os.path.realpath(resolved) + "\n" + report["version"]}
tools = {
"verilator": command_output(["verilator", "--version"]),
"yosys": command_output(["yosys", "-V"]),
"sby": command_output(["sby", "--version"]),
"z3": command_output(["z3", "--version"]),
"boolector": command_output(["boolector", "--version"]),
"riscv_gcc": install_path("riscv64-linux-gcc"),
"riscv_gdb": install_path("riscv64-linux-gdb"),
"clang": command_output(["clang", "--version"]),
"clang_tidy": command_output(["clang-tidy", "--version"]),
"clang_format": command_output(["clang-format", "--version"]),
"python": {"version": platform.python_version()},
"gcc": command_output(["gcc", "-dumpfullversion"]),
"cmake": command_output(["cmake", "--version"]),
"meson": command_output(["meson", "--version"]),
"ninja": command_output(["ninja", "--version"]),
"qemu": command_output(["qemu-system-riscv64", "--version"]),
"node": command_output(["node", "--version"]),
"npm": command_output(["npm", "--version"]),
"pip": command_output(["python3", "-m", "pip", "--version"]),
"openocd": command_output(["openocd", "--version"]),
"verible": command_output(["verible-verilog-lint", "--version"]),
}
try:
import cocotb
except (ImportError, OSError) as error:
tools["cocotb"] = {"error": str(error)}
else:
tools["cocotb"] = {"version": cocotb.__version__}
for key, distribution in {
"pytest": "pytest",
"pytest_cov": "pytest-cov",
"pre_commit": "pre-commit",
"click": "click",
"setuptools": "setuptools",
"wheel": "wheel",
}.items():
try:
tools[key] = {"version": importlib.metadata.version(distribution)}
except importlib.metadata.PackageNotFoundError as error:
tools[key] = {"error": str(error)}
fingerprints = {}
for filename in ("Dockerfile", "docker_entrypoint.py"):
path = os.path.join("/usr/local/share/frost-image-inputs", filename)
try:
with open(path, "rb") as source:
fingerprints[filename] = hashlib.sha256(source.read()).hexdigest()
except OSError:
fingerprints[filename] = None
entrypoint = "/usr/local/bin/docker_entrypoint.py"
try:
entrypoint_mode = stat.S_IMODE(os.stat(entrypoint).st_mode)
except OSError:
entrypoint_mode = None
print(json.dumps({
"architecture": platform.machine(),
"python": platform.python_version(),
"tools": tools,
"fingerprints": fingerprints,
"entrypoint_mode": entrypoint_mode,
}))
"""
@dataclass(frozen=True)
class CommandOutcome:
"""Captured result from a diagnostic host command."""
returncode: int
stdout: str = ""
stderr: str = ""
@dataclass(frozen=True)
class Diagnostic:
"""One user-facing doctor result."""
status: str
name: str
detail: str
@dataclass(frozen=True)
class CheckStepResult:
"""Status and elapsed time of one ``check`` job."""
name: str
status: str
duration: float
returncode: int | None
@dataclass(frozen=True)
class OwnershipScan:
"""Bounded report of root-owned paths outside excluded trees."""
count: int
samples: tuple[str, ...]
errors: tuple[str, ...]
def _positive_int(raw: str) -> int:
"""Parse a strictly positive integer argument."""
try:
value = int(raw, 10)
except ValueError as error:
raise argparse.ArgumentTypeError(f"invalid integer value: {raw!r}") from error
if value < 1:
raise argparse.ArgumentTypeError("value must be >= 1")
return value
def _non_negative_int(raw: str) -> int:
"""Parse a non-negative integer argument."""
try:
value = int(raw, 10)
except ValueError as error:
raise argparse.ArgumentTypeError(f"invalid integer value: {raw!r}") from error
if value < 0:
raise argparse.ArgumentTypeError("value must be >= 0")
return value
def _app_name(raw: str) -> str:
"""Validate an application directory or registry name."""
if not APP_NAME_PATTERN.fullmatch(raw):
raise argparse.ArgumentTypeError(f"invalid application name: {raw!r}")
return raw
def _native_argument_parser(*, exit_on_error: bool = True) -> argparse.ArgumentParser:
"""Create the parser for the native Verilator runner workflow."""
parser = argparse.ArgumentParser(
prog=f"{Path(sys.argv[0]).name} native",
description="Build and run an application on the native C++ Verilator model.",
exit_on_error=exit_on_error,
)
parser.add_argument(
"app",
type=_app_name,
help="application name under sw/apps (for example hello_world or coremark)",
)
parser.add_argument(
"--mem-config",
choices=("bram", "ddr"),
default="bram",
help="memory tier: bram (default) or ddr",
)
parser.add_argument(
"--threads",
type=_positive_int,
default=1,
help="Verilator simulation thread count (default: %(default)s)",
)
parser.add_argument(
"--max-cycles",
type=_non_negative_int,
default=None,
help="optional cycle limit (0 disables the limit)",
)
return parser
def workflow_command(workflow: str, arguments: Sequence[str]) -> list[str]:
"""Return the in-container command for a named workflow."""
args = list(arguments)
if workflow == "cocotb":
return [*COCOTB_COMMAND, *args]
if workflow == "native":
try:
parsed = _native_argument_parser(exit_on_error=False).parse_args(args)
except (argparse.ArgumentError, SystemExit) as error:
raise ValueError(f"invalid native workflow arguments: {error}") from error
command = [
"make",
"-C",
"hw/sim/native",
"run",
f"APP={parsed.app}",
f"MEM_CONFIG={parsed.mem_config}",
f"THREADS={parsed.threads}",
]
if parsed.max_cycles is not None:
command.append(f"MAX_CYCLES={parsed.max_cycles}")
return command
if workflow == "pytest":
return [*PYTEST_COMMAND, *args]
if workflow == "formal":
return ["python3", "tests/test_run_formal.py", *args]
if workflow == "synthesis":
return ["python3", "tests/test_run_yosys.py", *args]
if workflow == "lint":
return ["pre-commit", "run", *(args or ["--all-files"])]
if workflow == "shell":
return ["bash", *args]
if workflow == "run":
if not args:
raise ValueError("the run workflow requires a command")
return args
raise ValueError(f"unknown workflow: {workflow}")
def forwarded_environment_names(environment: Mapping[str, str]) -> list[str]:
"""Return the allowlisted development-variable names to inherit in the container."""
return sorted(
name
for name in environment
if name in FORWARDED_ENV_NAMES
or any(name.startswith(prefix) for prefix in FORWARDED_ENV_PREFIXES)
)
def validate_image_reference(image: str) -> None:
"""Reject values that Docker could mistake for host-side options."""
if not IMAGE_REFERENCE_PATTERN.fullmatch(image):
raise ValueError(f"invalid Docker image reference: {image!r}")
def default_cache_directory(environment: Mapping[str, str]) -> Path:
"""Return the private, host-owned cache used by container workflows."""
if xdg_cache_home := environment.get("XDG_CACHE_HOME"):
cache_root = Path(xdg_cache_home).expanduser()
else:
home = environment.get("HOME")
cache_root = (Path(home).expanduser() if home else Path.home()) / ".cache"
return (cache_root / "frost" / "container").absolute()
def prepare_cache_directory(cache_directory: Path, uid: int) -> None:
"""Create or validate the private cache before mounting it into Docker."""
try:
metadata = cache_directory.lstat()
except FileNotFoundError:
cache_directory.mkdir(mode=0o700, parents=True, exist_ok=True)
metadata = cache_directory.lstat()
if stat.S_ISLNK(metadata.st_mode):
raise OSError("path is a symbolic link")
if not stat.S_ISDIR(metadata.st_mode):
raise OSError("path is not a directory")
if metadata.st_uid != uid:
raise OSError(f"owned by UID {metadata.st_uid}, expected UID {uid}")
mode = stat.S_IMODE(metadata.st_mode)
if mode != 0o700:
cache_directory.chmod(0o700)
def _normalize_returncode(returncode: int) -> int:
"""Translate a subprocess signal result to the conventional shell status."""
return 128 - returncode if returncode < 0 else returncode
def run_streaming_command(command: Sequence[str]) -> int:
"""Run a command with live output and return a shell-compatible status."""
try:
result = subprocess.run(command, check=False)
except FileNotFoundError:
print("Error: Docker is not installed or is not on PATH", file=sys.stderr)
return 127
except KeyboardInterrupt:
return 130
return _normalize_returncode(result.returncode)
def run_captured_command(
command: Sequence[str], *, timeout: int = DOCTOR_TIMEOUT_SECONDS
) -> CommandOutcome:
"""Run a bounded diagnostic command without streaming its output."""
try:
result = subprocess.run(
command,
check=False,
capture_output=True,
text=True,
timeout=timeout,
)
except FileNotFoundError as error:
return CommandOutcome(127, stderr=str(error))
except subprocess.TimeoutExpired:
# Killing the docker client leaves its container running: remove it.
if list(command[:2]) == ["docker", "run"] and "--name" in command:
name_index = command.index("--name") + 1
if name_index < len(command):
try:
subprocess.run(
["docker", "rm", "--force", command[name_index]],
check=False,
capture_output=True,
timeout=5,
)
except (OSError, subprocess.TimeoutExpired):
pass
return CommandOutcome(124, stderr=f"timed out after {timeout}s")
except OSError as error:
return CommandOutcome(1, stderr=str(error))
return CommandOutcome(
_normalize_returncode(result.returncode),
result.stdout.strip(),
result.stderr.strip(),
)
def build_docker_command(
container_command: Sequence[str],
*,
repository_root: Path,
image: str,
uid: int,
gid: int,
environment: Mapping[str, str],
cache_directory: Path | None = None,
interactive: bool = False,
environment_overrides: Mapping[str, str] | None = None,
suppressed_environment_names: frozenset[str] = frozenset(),
) -> list[str]:
"""Build the host-side Docker invocation for a workflow command."""
validate_image_reference(image)
overrides = environment_overrides or {}
# With a cache mount, Docker creates HOME as its root-owned parent, so npm's
# default ~/.npm would be unwritable to the invoking UID.
npm_cache = (
f"/tmp/frost-home-{uid}/.cache/npm"
if cache_directory is not None
else f"/tmp/frost-npm-{uid}"
)
command = [
"docker",
"run",
"--rm",
"--init",
"--pull=never",
"--user",
f"{uid}:{gid}",
"--env",
f"HOME=/tmp/frost-home-{uid}",
"--env",
f"npm_config_cache={npm_cache}",
]
for name in forwarded_environment_names(environment):
if name in suppressed_environment_names or name in overrides:
continue
command.extend(("--env", name))
for name, value in sorted(overrides.items()):
command.extend(("--env", f"{name}={value}"))
if cache_directory is not None:
command.extend(
(
"--volume",
f"{cache_directory}:/tmp/frost-home-{uid}/.cache",
)
)
if interactive:
command.append("--interactive")
if sys.stdout.isatty():
command.append("--tty")
command.extend(
(
"--volume",
f"{repository_root}:/workspace",
"--workdir",
"/workspace",
image,
*container_command,
)
)
return command
def build_image_probe_command(image: str, uid: int, gid: int) -> list[str]:
"""Build a sandboxed, checkout-free command that inventories an image."""
validate_image_reference(image)
return [
"docker",
"run",
"--rm",
"--pull=never",
"--name",
f"frost-doctor-{uid}-{os.getpid()}",
"--network",
"none",
"--read-only",
"--cap-drop",
"ALL",
"--security-opt",
"no-new-privileges",
"--pids-limit",
"128",
"--cpus",
"1",
"--memory",
"512m",
"--user",
f"{uid}:{gid}",
"--env",
f"HOME=/tmp/frost-doctor-{uid}",
"--entrypoint",
"python3",
image,
"-c",
IMAGE_PROBE_SCRIPT,
]
def dockerfile_version_pins(dockerfile: Path) -> dict[str, str]:
"""Read version-valued build arguments from the repository Dockerfile."""
pattern = re.compile(r"^ARG\s+([A-Z0-9_]+_VERSION)=([^\s#]+)")
pins: dict[str, str] = {}
for line in dockerfile.read_text(encoding="utf-8").splitlines():
if match := pattern.match(line):
pins[match.group(1)] = match.group(2)
return pins
def sha256_file(path: Path) -> str:
"""Return a stable digest for one image build input."""
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def image_fingerprint_problems(
repository_root: Path, probe: Mapping[str, object]
) -> list[str]:
"""Return build inputs missing from or stale in the inspected image."""
fingerprints = probe.get("fingerprints")
if not isinstance(fingerprints, Mapping):
return ["image did not report embedded build-input fingerprints"]
problems: list[str] = []
for filename in IMAGE_INPUT_FILES:
actual = fingerprints.get(filename)
if not isinstance(actual, str):
problems.append(f"image does not embed {filename}")
continue
expected = sha256_file(repository_root / filename)
if actual != expected:
problems.append(f"embedded {filename} differs from the checkout")
return problems
def tool_version_problems(
probe: Mapping[str, object], pins: Mapping[str, str]
) -> list[str]:
"""Return missing tools and versions that disagree with Dockerfile pins."""
tools = probe.get("tools")
if not isinstance(tools, Mapping):
return ["image did not report its tool versions"]
problems: list[str] = []
for tool, argument in TOOL_VERSION_ARGUMENTS.items():
configured = pins.get(argument)
if configured is None:
problems.append(f"Dockerfile is missing {argument}")
continue
report = tools.get(tool)
if not isinstance(report, Mapping):
problems.append(f"{tool} was not reported")
continue
if error := report.get("error"):
problems.append(f"{tool} is unavailable ({error})")
continue
version = report.get("version")
if tool == "ninja" and isinstance(version, str):
# The PyPI wheel carries Kitware's GNU make jobserver patch. Its
# CLI includes that build suffix after the pinned release version.
version = re.sub(r"\.git\.kitware\.jobserver(?:-pipe)?-\d+$", "", version)
expected = configured
if tool in PACKAGE_VERSION_TOOLS:
matches = version == expected
else:
matches = (
isinstance(version, str)
and re.search(rf"(?<![0-9.]){re.escape(expected)}(?![0-9.])", version)
is not None
)
if not matches:
problems.append(
f"{tool} expected {expected}, got {version or 'no version'}"
)
return problems
def image_runtime_problems(probe: Mapping[str, object]) -> list[str]:
"""Return incompatibilities that prevent supported non-root workflows."""
problems: list[str] = []
architecture = probe.get("architecture")
if architecture not in {"x86_64", "amd64"}:
problems.append(
f"unsupported image architecture {architecture!r}; expected x86_64"
)
python_version = probe.get("python")
if not isinstance(python_version, str) or not python_version.startswith("3.14."):
problems.append(f"expected Python 3.14, got {python_version or 'no version'}")
entrypoint_mode = probe.get("entrypoint_mode")
if entrypoint_mode != 0o755:
rendered_mode = (
oct(entrypoint_mode) if isinstance(entrypoint_mode, int) else "missing"
)
problems.append(f"entrypoint mode is {rendered_mode}, expected 0o755")
return problems
def _concise_command_error(outcome: CommandOutcome) -> str:
"""Choose one bounded, useful line from a failed diagnostic command."""
output = outcome.stderr or outcome.stdout or f"exit {outcome.returncode}"
lines = [line.strip() for line in output.splitlines() if line.strip()]
return (lines[-1] if lines else f"exit {outcome.returncode}")[:300]
def submodule_diagnostic(
repository_root: Path,
command_runner: Callable[[Sequence[str]], CommandOutcome],
) -> Diagnostic:
"""Inspect recursive submodule state without initializing anything."""
if not (repository_root / ".gitmodules").exists():
return Diagnostic("PASS", "Submodules", "repository has no submodules")
outcome = command_runner(
["git", "-C", str(repository_root), "submodule", "status", "--recursive"]
)
if outcome.returncode != 0:
return Diagnostic(
"FAIL",
"Submodules",
f"could not inspect status: {_concise_command_error(outcome)}",
)
states: dict[str, list[str]] = {"-": [], "+": [], "U": []}
for line in outcome.stdout.splitlines():
if not line or line[0] not in states:
continue
fields = line[1:].strip().split()
path = fields[1] if len(fields) > 1 else line[1:].strip()
states[line[0]].append(path)
if states["-"] or states["U"]:
details: list[str] = []
if states["-"]:
details.append("uninitialized: " + ", ".join(states["-"][:5]))
if states["U"]:
details.append("conflicted: " + ", ".join(states["U"][:5]))
return Diagnostic("FAIL", "Submodules", "; ".join(details))
if states["+"]:
return Diagnostic(
"WARN",
"Submodules",
"checked out at a different commit: " + ", ".join(states["+"][:5]),
)
count = len([line for line in outcome.stdout.splitlines() if line.strip()])
return Diagnostic(
"PASS", "Submodules", f"{count} recursive entries are initialized"
)
def scan_root_owned_paths(
repository_root: Path, uid: int, *, sample_limit: int = 8
) -> OwnershipScan:
"""Find topmost root-owned paths while pruning Git metadata and ``hw``."""
if uid == 0:
return OwnershipScan(0, (), ())
count = 0
samples: list[str] = []
errors: list[str] = []
def record_walk_error(error: OSError) -> None:
location = Path(error.filename) if error.filename else repository_root
try:
rendered = location.relative_to(repository_root).as_posix()
except ValueError:
rendered = str(location)
if len(errors) < sample_limit:
errors.append(f"{rendered}: {error.strerror or error}")
for current, directories, filenames in os.walk(
repository_root,
topdown=True,
onerror=record_walk_error,
followlinks=False,
):
current_path = Path(current)
if current_path == repository_root:
directories[:] = [
name for name in directories if name not in {".git", "hw"}
]
for name in list(directories):
path = current_path / name
try:
metadata = path.lstat()
except OSError as error:
if len(errors) < sample_limit:
errors.append(f"{path.relative_to(repository_root)}: {error}")
directories.remove(name)
continue
if metadata.st_uid == 0:
count += 1
if len(samples) < sample_limit:
samples.append(path.relative_to(repository_root).as_posix())
directories.remove(name)
for name in filenames:
path = current_path / name
try:
metadata = path.lstat()
except OSError as error:
if len(errors) < sample_limit:
errors.append(f"{path.relative_to(repository_root)}: {error}")
continue
if metadata.st_uid == 0:
count += 1
if len(samples) < sample_limit:
samples.append(path.relative_to(repository_root).as_posix())
return OwnershipScan(count, tuple(samples), tuple(errors))
def ownership_diagnostics(repository_root: Path, uid: int) -> list[Diagnostic]:
"""Describe root-owned checkout artifacts without changing ownership."""
if uid == 0:
return [
Diagnostic(
"SKIP",
"Repository ownership",
"running as root cannot diagnose UID 0 artifacts",
)
]
scan = scan_root_owned_paths(repository_root, uid)
diagnostics: list[Diagnostic] = []
if scan.count:
detail = f"{scan.count} root-owned path(s): " + ", ".join(scan.samples)
if scan.count > len(scan.samples):
detail += f" (and {scan.count - len(scan.samples)} more)"
diagnostics.append(Diagnostic("FAIL", "Repository ownership", detail))
else:
diagnostics.append(
Diagnostic(
"PASS",
"Repository ownership",
"no root-owned paths found outside .git/ and hw/",
)
)
if scan.errors:
diagnostics.append(
Diagnostic(
"WARN",
"Ownership scan",
"could not inspect: " + "; ".join(scan.errors),
)
)
return diagnostics
def cache_diagnostics(cache_directory: Path, uid: int) -> list[Diagnostic]:
"""Inspect the executable tooling cache without creating or repairing it."""
try:
metadata = cache_directory.lstat()
except FileNotFoundError:
ancestor = cache_directory.parent
while not ancestor.exists() and ancestor.parent != ancestor:
ancestor = ancestor.parent
if not ancestor.is_dir() or not os.access(ancestor, os.W_OK | os.X_OK):
return [
Diagnostic(
"FAIL",
"Container cache",
f"nearest existing parent {ancestor} is not a writable directory",
)
]
return [
Diagnostic(
"PASS",
"Container cache",
f"{cache_directory} will be created on first use",
)
]
except OSError as error:
return [Diagnostic("FAIL", "Container cache", str(error))]
if stat.S_ISLNK(metadata.st_mode):
return [Diagnostic("FAIL", "Container cache", "cache path is a symbolic link")]
if not stat.S_ISDIR(metadata.st_mode):
return [Diagnostic("FAIL", "Container cache", "cache path is not a directory")]
if metadata.st_uid != uid:
return [
Diagnostic(
"FAIL",
"Container cache",
f"owned by UID {metadata.st_uid}, expected UID {uid}",
)
]
mode = stat.S_IMODE(metadata.st_mode)
if mode & 0o700 != 0o700:
return [
Diagnostic(
"FAIL",
"Container cache",
f"owner permissions {oct(mode)} must include rwx",
)
]
foreign_count = 0
foreign_samples: list[str] = []
walk_errors: list[str] = []
def record_walk_error(error: OSError) -> None:
location = error.filename or str(cache_directory)
if len(walk_errors) < 5:
walk_errors.append(f"{location}: {error.strerror or error}")
for current, directories, filenames in os.walk(
cache_directory, topdown=True, onerror=record_walk_error, followlinks=False
):
for name in [*directories, *filenames]:
path = Path(current) / name
try:
entry = path.lstat()
except OSError as error:
if len(walk_errors) < 5:
walk_errors.append(f"{path}: {error}")
continue
if entry.st_uid != uid:
foreign_count += 1
if len(foreign_samples) < 5:
foreign_samples.append(path.relative_to(cache_directory).as_posix())
if foreign_count:
return [
Diagnostic(
"FAIL",
"Container cache",
f"{foreign_count} foreign-owned entries: " + ", ".join(foreign_samples),
)
]
if walk_errors:
return [
Diagnostic(
"FAIL",
"Container cache",
"could not inspect cache entries: " + "; ".join(walk_errors),
)
]
if mode & 0o077:
return [
Diagnostic(
"WARN",
"Container cache",
f"permissions {oct(mode)} are broader than the recommended 0o700",
)
]
return [
Diagnostic(
"PASS", "Container cache", f"{cache_directory} is private and writable"
)
]
def _print_doctor_results(diagnostics: Sequence[Diagnostic]) -> int:
"""Print ordered diagnostics and return the aggregate doctor status."""
for diagnostic in diagnostics:
print(f"[{diagnostic.status}] {diagnostic.name}: {diagnostic.detail}")
counts = Counter(diagnostic.status for diagnostic in diagnostics)
print(
"Doctor: "
f"{counts['PASS']} passed, {counts['WARN']} warnings, "
f"{counts['FAIL']} failed, {counts['SKIP']} skipped"
)
return 1 if counts["FAIL"] else 0
def run_doctor(
*,
repository_root: Path,
image: str,
uid: int,
gid: int,
environment: Mapping[str, str],
command_runner: Callable[[Sequence[str]], CommandOutcome] = run_captured_command,
docker_finder: Callable[[str], str | None] = shutil.which,
) -> int:
"""Run read-only host and image health diagnostics."""
diagnostics: list[Diagnostic] = []
docker_ready = False
daemon_ready = False
image_ready = False
docker_path = docker_finder("docker")
if docker_path is None:
diagnostics.append(
Diagnostic(
"FAIL", "Docker CLI", "Docker is not installed or is not on PATH"
)
)
else:
outcome = command_runner(["docker", "--version"])
if outcome.returncode == 0:
docker_ready = True
diagnostics.append(
Diagnostic("PASS", "Docker CLI", outcome.stdout or docker_path)
)
else:
diagnostics.append(
Diagnostic("FAIL", "Docker CLI", _concise_command_error(outcome))
)
if docker_ready:
outcome = command_runner(["docker", "info", "--format", "{{.ServerVersion}}"])
if outcome.returncode == 0:
daemon_ready = True
diagnostics.append(
Diagnostic("PASS", "Docker daemon", f"server {outcome.stdout}")
)
else:
diagnostics.append(
Diagnostic("FAIL", "Docker daemon", _concise_command_error(outcome))
)
else:
diagnostics.append(
Diagnostic("SKIP", "Docker daemon", "Docker CLI is unavailable")
)
if daemon_ready:
outcome = command_runner(
["docker", "image", "inspect", image, "--format", "{{.Id}}"]
)