doctor_linux.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #!/usr/bin/env python3
  2. """Linux-first toolchain doctor: probe only, never installs.
  3. Detects td2026 via PATH (wrapper typically at /usr/local/bin/td2026).
  4. Prefers OSS CAD at $XDG_CACHE_HOME/prod2u/oss-cad-suite/latest/bin when present.
  5. Never hard-codes Windows paths or td603.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. import hashlib
  10. import json
  11. import os
  12. import shutil
  13. import subprocess
  14. import sys
  15. from datetime import datetime, timezone
  16. from pathlib import Path
  17. from typing import Any
  18. ROOT = Path(__file__).resolve().parents[1]
  19. def _cache_root() -> Path:
  20. return Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "prod2u"
  21. def _oss_cad_bin() -> Path:
  22. override = os.environ.get("OSS_CAD_SUITE_ROOT")
  23. if override:
  24. return Path(override) / "bin"
  25. return _cache_root() / "oss-cad-suite" / "latest" / "bin"
  26. def _prefer_oss_cad_on_path() -> None:
  27. """Prepend OSS CAD bin when present so shutil.which prefers it."""
  28. oss_bin = _oss_cad_bin()
  29. if not oss_bin.is_dir():
  30. return
  31. current = os.environ.get("PATH", "")
  32. prefix = str(oss_bin)
  33. parts = current.split(os.pathsep) if current else []
  34. if prefix not in parts:
  35. os.environ["PATH"] = prefix + (os.pathsep + current if current else "")
  36. def _sha256_file(path: Path) -> str | None:
  37. if not path.is_file():
  38. return None
  39. digest = hashlib.sha256()
  40. with path.open("rb") as handle:
  41. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  42. digest.update(chunk)
  43. return digest.hexdigest()
  44. def _run(cmd: list[str], *, timeout: float = 20.0, env: dict[str, str] | None = None) -> dict[str, Any]:
  45. clean_env = os.environ.copy()
  46. # TD libraries must not pollute doctor/smoke commands.
  47. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  48. clean_env.pop(key, None)
  49. if env:
  50. clean_env.update(env)
  51. try:
  52. completed = subprocess.run(
  53. cmd,
  54. capture_output=True,
  55. text=True,
  56. timeout=timeout,
  57. check=False,
  58. env=clean_env,
  59. )
  60. return {
  61. "command": cmd,
  62. "exit_code": completed.returncode,
  63. "stdout": (completed.stdout or "")[:2000],
  64. "stderr": (completed.stderr or "")[:2000],
  65. }
  66. except FileNotFoundError as exc:
  67. return {"command": cmd, "exit_code": 127, "error": str(exc)}
  68. except subprocess.TimeoutExpired:
  69. return {"command": cmd, "exit_code": 124, "error": "timeout"}
  70. def _which(name: str) -> Path | None:
  71. found = shutil.which(name)
  72. return Path(found).resolve() if found else None
  73. def probe_binary(name: str, version_args: list[str] | None = None) -> dict[str, Any]:
  74. path = _which(name)
  75. result: dict[str, Any] = {
  76. "name": name,
  77. "resolved_path": str(path) if path else None,
  78. "present": path is not None,
  79. "sha256": _sha256_file(path) if path else None,
  80. }
  81. if path and version_args is not None:
  82. result["version_probe"] = _run([str(path), *version_args])
  83. return result
  84. def probe_oss_cad() -> dict[str, Any]:
  85. oss_bin = _oss_cad_bin()
  86. root = oss_bin.parent
  87. markers = ["yosys", "sby", "verilator"]
  88. present_tools = {
  89. name: (oss_bin / name).is_file() for name in markers
  90. }
  91. return {
  92. "name": "oss_cad_suite",
  93. "root": str(root),
  94. "bin": str(oss_bin),
  95. "present": oss_bin.is_dir(),
  96. "tools": present_tools,
  97. "preferred_on_path": oss_bin.is_dir(),
  98. }
  99. def probe_td2026() -> dict[str, Any]:
  100. # PATH only — typically /usr/local/bin/td2026. Never td603 / Windows paths.
  101. path = _which("td2026")
  102. home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL"))
  103. license_path = home / "license" / "Anlogic.lic"
  104. result: dict[str, Any] = {
  105. "name": "td2026",
  106. "resolved_path": str(path) if path else None,
  107. "present": path is not None,
  108. "wrapper_sha256": _sha256_file(path) if path else None,
  109. "install_root": str(home) if home.is_dir() else None,
  110. "bw_root": "/data/anlogic/BW_Release_2026.1_SP2"
  111. if Path("/data/anlogic/BW_Release_2026.1_SP2").is_dir()
  112. else None,
  113. "license_present": license_path.is_file(),
  114. "license_readable": os.access(license_path, os.R_OK) if license_path.is_file() else False,
  115. }
  116. if path:
  117. # Run version probe with TD libraries only for this subprocess.
  118. td_env = {
  119. "LD_LIBRARY_PATH": f"{home}/lib:{home}/lib/Qt/lib",
  120. "QT_PLUGIN_PATH": f"{home}/lib/Qt/plugins",
  121. "ANLOGIC_TD_HOME": str(home),
  122. }
  123. result["version_probe"] = _run([str(path), "-version"], env=td_env)
  124. return result
  125. def probe_python_venv(venv: Path) -> dict[str, Any]:
  126. python = venv / "bin" / "python"
  127. result: dict[str, Any] = {
  128. "name": "verify_venv",
  129. "path": str(venv),
  130. "present": python.is_file(),
  131. "python": str(python) if python.is_file() else None,
  132. }
  133. if python.is_file():
  134. result["imports"] = _run(
  135. [str(python), "-c", "import pytest,jsonschema,psutil; print('ok')"]
  136. )
  137. return result
  138. def probe_host_resources() -> dict[str, Any]:
  139. nproc = os.cpu_count() or 1
  140. mem_available_kb: int | None = None
  141. try:
  142. with open("/proc/meminfo", encoding="utf-8") as handle:
  143. for line in handle:
  144. if line.startswith("MemAvailable:"):
  145. mem_available_kb = int(line.split()[1])
  146. break
  147. except OSError:
  148. mem_available_kb = None
  149. disk_free_bytes: int | None = None
  150. try:
  151. disk_free_bytes = shutil.disk_usage("/").free
  152. except OSError:
  153. disk_free_bytes = None
  154. return {
  155. "nproc": nproc,
  156. "mem_available_kb": mem_available_kb,
  157. "mem_available_gib": round(mem_available_kb / (1024 * 1024), 2) if mem_available_kb else None,
  158. "disk_free_bytes": disk_free_bytes,
  159. "disk_free_gib": round(disk_free_bytes / (1024**3), 2) if disk_free_bytes else None,
  160. }
  161. def build_report() -> dict[str, Any]:
  162. _prefer_oss_cad_on_path()
  163. # Sanitize PATH for probes: keep system + OSS CAD, drop accidental TD lib pollution.
  164. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"):
  165. os.environ.pop(key, None)
  166. venv = Path(
  167. os.environ.get(
  168. "PRODU2_VERIFY_VENV",
  169. str(_cache_root() / "venvs" / "verify"),
  170. )
  171. )
  172. tools = [
  173. probe_binary("python3", ["--version"]),
  174. probe_binary("git", ["--version"]),
  175. probe_binary("iverilog", ["-V"]),
  176. probe_binary("vvp", ["-V"]),
  177. probe_binary("verilator", ["--version"]),
  178. probe_binary("yosys", ["-V"]),
  179. probe_binary("sby", ["--version"]),
  180. probe_binary("unzip", ["-v"]),
  181. probe_binary("zstd", ["--version"]),
  182. probe_binary("jq", ["--version"]),
  183. probe_oss_cad(),
  184. probe_td2026(),
  185. probe_python_venv(venv),
  186. ]
  187. missing = [item["name"] for item in tools if not item.get("present")]
  188. # Core acceptance: python3 + iverilog + td2026. OSS CAD / venv may be degraded.
  189. core_missing = [n for n in ("python3", "iverilog", "td2026") if n in missing]
  190. return {
  191. "schema": "prod2u-toolchain-doctor-v1",
  192. "generated_at_utc": datetime.now(timezone.utc).isoformat(),
  193. "repository_root": str(ROOT),
  194. "platform": {
  195. "python": sys.version,
  196. "executable": sys.executable,
  197. },
  198. "host_resources": probe_host_resources(),
  199. "path_policy": {
  200. "base": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
  201. "oss_cad_preferred": str(_oss_cad_bin()),
  202. "ld_library_path_cleared": True,
  203. "td_command": "td2026",
  204. },
  205. "tools": tools,
  206. "missing": missing,
  207. "status": "pass" if not core_missing else "degraded",
  208. }
  209. def main() -> int:
  210. parser = argparse.ArgumentParser(description=__doc__)
  211. parser.add_argument("--json-out", type=Path, default=None)
  212. args = parser.parse_args()
  213. report = build_report()
  214. text = json.dumps(report, indent=2) + "\n"
  215. if args.json_out:
  216. args.json_out.parent.mkdir(parents=True, exist_ok=True)
  217. args.json_out.write_text(text, encoding="utf-8")
  218. print(text)
  219. return 0 if report["status"] in {"pass", "degraded"} else 1
  220. if __name__ == "__main__":
  221. raise SystemExit(main())