doctor_linux.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. #!/usr/bin/env python3
  2. """Linux-first toolchain doctor: probe only, never installs."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import shutil
  9. import subprocess
  10. import sys
  11. from datetime import datetime, timezone
  12. from pathlib import Path
  13. from typing import Any
  14. ROOT = Path(__file__).resolve().parents[1]
  15. def _sha256_file(path: Path) -> str | None:
  16. if not path.is_file():
  17. return None
  18. digest = hashlib.sha256()
  19. with path.open("rb") as handle:
  20. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  21. digest.update(chunk)
  22. return digest.hexdigest()
  23. def _run(cmd: list[str], *, timeout: float = 20.0, env: dict[str, str] | None = None) -> dict[str, Any]:
  24. clean_env = os.environ.copy()
  25. # TD libraries must not pollute doctor/smoke commands.
  26. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  27. clean_env.pop(key, None)
  28. if env:
  29. clean_env.update(env)
  30. try:
  31. completed = subprocess.run(
  32. cmd,
  33. capture_output=True,
  34. text=True,
  35. timeout=timeout,
  36. check=False,
  37. env=clean_env,
  38. )
  39. return {
  40. "command": cmd,
  41. "exit_code": completed.returncode,
  42. "stdout": (completed.stdout or "")[:2000],
  43. "stderr": (completed.stderr or "")[:2000],
  44. }
  45. except FileNotFoundError as exc:
  46. return {"command": cmd, "exit_code": 127, "error": str(exc)}
  47. except subprocess.TimeoutExpired:
  48. return {"command": cmd, "exit_code": 124, "error": "timeout"}
  49. def _which(name: str) -> Path | None:
  50. found = shutil.which(name)
  51. return Path(found).resolve() if found else None
  52. def probe_binary(name: str, version_args: list[str] | None = None) -> dict[str, Any]:
  53. path = _which(name)
  54. result: dict[str, Any] = {
  55. "name": name,
  56. "resolved_path": str(path) if path else None,
  57. "present": path is not None,
  58. "sha256": _sha256_file(path) if path else None,
  59. }
  60. if path and version_args is not None:
  61. result["version_probe"] = _run([str(path), *version_args])
  62. return result
  63. def probe_td2026() -> dict[str, Any]:
  64. path = _which("td2026")
  65. home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL"))
  66. license_path = home / "license" / "Anlogic.lic"
  67. result: dict[str, Any] = {
  68. "name": "td2026",
  69. "resolved_path": str(path) if path else None,
  70. "present": path is not None,
  71. "wrapper_sha256": _sha256_file(path) if path else None,
  72. "install_root": str(home) if home.is_dir() else None,
  73. "bw_root": "/data/anlogic/BW_Release_2026.1_SP2"
  74. if Path("/data/anlogic/BW_Release_2026.1_SP2").is_dir()
  75. else None,
  76. "license_present": license_path.is_file(),
  77. "license_readable": os.access(license_path, os.R_OK) if license_path.is_file() else False,
  78. }
  79. if path:
  80. # Run version probe with TD libraries only for this subprocess.
  81. td_env = {
  82. "LD_LIBRARY_PATH": f"{home}/lib:{home}/lib/Qt/lib",
  83. "QT_PLUGIN_PATH": f"{home}/lib/Qt/plugins",
  84. "ANLOGIC_TD_HOME": str(home),
  85. }
  86. result["version_probe"] = _run([str(path), "-version"], env=td_env)
  87. return result
  88. def probe_python_venv(venv: Path) -> dict[str, Any]:
  89. python = venv / "bin" / "python"
  90. result = {
  91. "name": "verify_venv",
  92. "path": str(venv),
  93. "present": python.is_file(),
  94. "python": str(python) if python.is_file() else None,
  95. }
  96. if python.is_file():
  97. result["imports"] = _run(
  98. [str(python), "-c", "import pytest,jsonschema,psutil; print('ok')"]
  99. )
  100. return result
  101. def build_report() -> dict[str, Any]:
  102. venv = Path(os.environ.get("PRODU2_VERIFY_VENV", str(Path.home() / ".cache/prod2u/venvs/verify")))
  103. tools = [
  104. probe_binary("python3", ["--version"]),
  105. probe_binary("git", ["--version"]),
  106. probe_binary("iverilog", ["-V"]),
  107. probe_binary("vvp", ["-V"]),
  108. probe_binary("verilator", ["--version"]),
  109. probe_binary("yosys", ["-V"]),
  110. probe_binary("sby", ["--version"]),
  111. probe_binary("unzip", ["-v"]),
  112. probe_binary("zstd", ["--version"]),
  113. probe_binary("jq", ["--version"]),
  114. probe_td2026(),
  115. probe_python_venv(venv),
  116. ]
  117. missing = [item["name"] for item in tools if not item.get("present")]
  118. return {
  119. "schema": "prod2u-toolchain-doctor-v1",
  120. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  121. "repository_root": str(ROOT),
  122. "platform": {
  123. "python": sys.version,
  124. "executable": sys.executable,
  125. },
  126. "tools": tools,
  127. "missing": missing,
  128. "status": "pass" if "td2026" not in missing and "python3" not in missing and "iverilog" not in missing else "degraded",
  129. }
  130. def main() -> int:
  131. parser = argparse.ArgumentParser(description=__doc__)
  132. parser.add_argument("--json-out", type=Path, default=None)
  133. args = parser.parse_args()
  134. report = build_report()
  135. text = json.dumps(report, indent=2) + "\n"
  136. if args.json_out:
  137. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  138. args.json_out.write_text(text, encoding="utf-8")
  139. print(text)
  140. return 0 if report["status"] in {"pass", "degraded"} else 1
  141. if __name__ == "__main__":
  142. raise SystemExit(main())