#!/usr/bin/env python3 """Linux-first toolchain doctor: probe only, never installs. Detects td2026 via PATH (wrapper typically at /usr/local/bin/td2026). Prefers OSS CAD at $XDG_CACHE_HOME/prod2u/oss-cad-suite/latest/bin when present. Never hard-codes Windows paths or td603. """ from __future__ import annotations import argparse import hashlib import json import os import shutil import subprocess import sys from datetime import datetime, timezone from pathlib import Path from typing import Any ROOT = Path(__file__).resolve().parents[1] if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) def _cache_root() -> Path: override = os.environ.get("PRODU2_TOOLCHAIN_BASE", "").strip() if override: return Path(override) persistent = Path("/data/prod2u") if persistent.is_dir() or os.access("/data", os.W_OK): return persistent return Path(os.environ.get("XDG_CACHE_HOME", str(Path.home() / ".cache"))) / "prod2u" def _oss_cad_bin() -> Path: override = os.environ.get("OSS_CAD_SUITE_ROOT") if override: return Path(override) / "bin" return _cache_root() / "oss-cad-suite" / "latest" / "bin" def _prefer_oss_cad_on_path() -> None: """Prepend OSS CAD bin when present so shutil.which prefers it.""" oss_bin = _oss_cad_bin() if not oss_bin.is_dir(): return current = os.environ.get("PATH", "") prefix = str(oss_bin) parts = current.split(os.pathsep) if current else [] if prefix not in parts: os.environ["PATH"] = prefix + (os.pathsep + current if current else "") def _sha256_file(path: Path) -> str | None: if not path.is_file(): return None digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def _run(cmd: list[str], *, timeout: float = 20.0, env: dict[str, str] | None = None) -> dict[str, Any]: clean_env = os.environ.copy() # TD libraries must not pollute doctor/smoke commands. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"): clean_env.pop(key, None) if env: clean_env.update(env) try: completed = subprocess.run( cmd, capture_output=True, text=True, timeout=timeout, check=False, env=clean_env, ) return { "command": cmd, "exit_code": completed.returncode, "stdout": (completed.stdout or "")[:2000], "stderr": (completed.stderr or "")[:2000], } except FileNotFoundError as exc: return {"command": cmd, "exit_code": 127, "error": str(exc)} except subprocess.TimeoutExpired: return {"command": cmd, "exit_code": 124, "error": "timeout"} def _which(name: str) -> Path | None: found = shutil.which(name) return Path(found).resolve() if found else None def probe_binary(name: str, version_args: list[str] | None = None) -> dict[str, Any]: path = _which(name) result: dict[str, Any] = { "name": name, "resolved_path": str(path) if path else None, "present": path is not None, "sha256": _sha256_file(path) if path else None, } if path and version_args is not None: result["version_probe"] = _run([str(path), *version_args]) return result def probe_oss_cad() -> dict[str, Any]: oss_bin = _oss_cad_bin() root = oss_bin.parent markers = ["yosys", "sby", "verilator"] present_tools = { name: (oss_bin / name).is_file() for name in markers } return { "name": "oss_cad_suite", "root": str(root), "bin": str(oss_bin), "present": oss_bin.is_dir(), "tools": present_tools, "preferred_on_path": oss_bin.is_dir(), } def probe_td2026() -> dict[str, Any]: # PATH only — typically /usr/local/bin/td2026. Never td603 / Windows paths. path = _which("td2026") home = Path(os.environ.get("ANLOGIC_TD_HOME", "/data/anlogic/TD_Release_2026.1_SP2_NL")) license_path = home / "license" / "Anlogic.lic" result: dict[str, Any] = { "name": "td2026", "resolved_path": str(path) if path else None, "present": path is not None, "wrapper_sha256": _sha256_file(path) if path else None, "install_root": str(home) if home.is_dir() else None, "bw_root": "/data/anlogic/BW_Release_2026.1_SP2" if Path("/data/anlogic/BW_Release_2026.1_SP2").is_dir() else None, "license_present": license_path.is_file(), "license_readable": os.access(license_path, os.R_OK) if license_path.is_file() else False, } if path: # Run version probe with TD libraries only for this subprocess. td_env = { "LD_LIBRARY_PATH": f"{home}/lib:{home}/lib/Qt/lib", "QT_PLUGIN_PATH": f"{home}/lib/Qt/plugins", "ANLOGIC_TD_HOME": str(home), } result["version_probe"] = _run([str(path), "-version"], env=td_env) return result def probe_python_venv(venv: Path) -> dict[str, Any]: python = venv / "bin" / "python" result: dict[str, Any] = { "name": "verify_venv", "path": str(venv), "present": python.is_file(), "python": str(python) if python.is_file() else None, } if python.is_file(): result["imports"] = _run( [str(python), "-c", "import pytest,jsonschema,psutil; print('ok')"] ) return result def probe_host_resources() -> dict[str, Any]: # Shared with the verification / packager matrix scheduler. from tools.resource_scheduler import host_resources return host_resources() def build_report() -> dict[str, Any]: _prefer_oss_cad_on_path() # Sanitize PATH for probes: keep system + OSS CAD, drop accidental TD lib pollution. for key in ("LD_LIBRARY_PATH", "LD_PRELOAD", "QT_PLUGIN_PATH"): os.environ.pop(key, None) venv = Path( os.environ.get( "PRODU2_VERIFY_VENV", str(_cache_root() / "venvs" / "verify"), ) ) tools = [ probe_binary("python3", ["--version"]), probe_binary("git", ["--version"]), probe_binary("iverilog", ["-V"]), probe_binary("vvp", ["-V"]), probe_binary("verilator", ["--version"]), probe_binary("yosys", ["-V"]), probe_binary("sby", ["--version"]), probe_binary("unzip", ["-v"]), probe_binary("zstd", ["--version"]), probe_binary("jq", ["--version"]), probe_oss_cad(), probe_td2026(), probe_python_venv(venv), ] missing = [item["name"] for item in tools if not item.get("present")] # Core acceptance: python3 + iverilog + td2026. OSS CAD / venv may be degraded. core_missing = [n for n in ("python3", "iverilog", "td2026") if n in missing] return { "schema": "prod2u-toolchain-doctor-v1", "generated_at_utc": datetime.now(timezone.utc).isoformat(), "repository_root": str(ROOT), "platform": { "python": sys.version, "executable": sys.executable, }, "host_resources": probe_host_resources(), "path_policy": { "base": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "oss_cad_preferred": str(_oss_cad_bin()), "ld_library_path_cleared": True, "td_command": "td2026", }, "tools": tools, "missing": missing, "status": "pass" if not core_missing else "degraded", } def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--json-out", type=Path, default=None) args = parser.parse_args() report = build_report() text = json.dumps(report, indent=2) + "\n" if args.json_out: args.json_out.parent.mkdir(parents=True, exist_ok=True) args.json_out.write_text(text, encoding="utf-8") print(text) return 0 if report["status"] in {"pass", "degraded"} else 1 if __name__ == "__main__": raise SystemExit(main())