fw_cli.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. #!/usr/bin/env python3
  2. """Minimal multi-target firmware entry. Users remember: target + action."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import os
  8. import re
  9. import signal
  10. import subprocess
  11. import sys
  12. import tempfile
  13. import uuid
  14. import xml.etree.ElementTree as ET
  15. from pathlib import Path
  16. ROOT = Path(__file__).resolve().parents[1]
  17. if str(ROOT) not in sys.path:
  18. sys.path.insert(0, str(ROOT))
  19. from tools.fw_targets import list_aliases, load_registry, resolve_target as resolve_dict, target_status_line
  20. from tools.generate_target import generate_named_target
  21. from tools.target_registry import TargetError, resolve_target
  22. from tools.source_identity import source_identity
  23. def _new_run_path(name: str) -> Path:
  24. base=Path(os.environ.get('XDG_STATE_HOME') or tempfile.gettempdir())/'prod2u/fw'
  25. return base/(name+'-'+uuid.uuid4().hex[:12])
  26. def _die(message: str, code: int = 2) -> int:
  27. print(message, file=sys.stderr)
  28. return code
  29. def cmd_list(_args: argparse.Namespace) -> int:
  30. for alias in list_aliases(ROOT):
  31. print(target_status_line(alias, ROOT))
  32. return 0
  33. def _generate_one(alias: str, *, check: bool=False) -> dict:
  34. return generate_named_target(alias, check=check)
  35. def cmd_generate(args: argparse.Namespace) -> int:
  36. names=list_aliases(ROOT) if args.target=='all' else (args.target,)
  37. for name in names:
  38. print(json.dumps(_generate_one(name,check=args.check),sort_keys=True))
  39. return 0
  40. def _python() -> str:
  41. return sys.executable
  42. def cmd_build(args: argparse.Namespace) -> int:
  43. target=resolve_target(args.target)
  44. if sys.platform!='linux':return _die('Run TD builds in the authorized Linux container')
  45. _generate_one(target.alias,check=True)
  46. out=args.run_root or _new_run_path(target.project_id+'-td')
  47. print('TD run: '+str(out.resolve()),flush=True)
  48. return subprocess.call([_python(),str(ROOT/'tools/run_6400_td.py'),'--profile',target.project_id,'--run-root',str(out)],cwd=ROOT)
  49. def cmd_test(args: argparse.Namespace) -> int:
  50. if sys.platform!='linux':return _die('Run current product verification in the authorized Linux container')
  51. products=tuple(resolve_target(name).project_id for name in list_aliases(ROOT)) if args.target=='all' else (resolve_target(args.target).project_id,)
  52. for product in products:_generate_one(product,check=True)
  53. out=(args.run_root or _new_run_path('current-regression')).resolve()
  54. if out==ROOT or ROOT in out.parents:return _die('--run-root must be outside the source checkout')
  55. out.mkdir(parents=True,exist_ok=False)
  56. manifest=json.loads((ROOT/'config/current-product-tests.json').read_text(encoding='utf-8'))
  57. unit_tests=list(manifest['shared_unit_tests'])
  58. for product in products:unit_tests.extend(manifest['targets'][product]['unit_tests'])
  59. unit_tests=list(dict.fromkeys(unit_tests))
  60. if not unit_tests:return _die('empty current unit test set')
  61. identity=source_identity(ROOT)
  62. receipt={'schema':'prod2u-current-regression-v1','scope':'current unit and RTL regression; not Full acceptance',
  63. 'run_id':out.name,'products':products,'source':identity,'status':'RUNNING','complete':False}
  64. receipt_path=out/'RESULT.json'
  65. receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
  66. command=[_python(),'-m','pytest','-q',*unit_tests,'--junitxml='+str(out/'python.xml'),'--basetemp='+str(out/'pytest-temp')]
  67. log_path=out/'python.log'
  68. with log_path.open('w') as log:
  69. log.write(json.dumps(command)+'\n');log.flush()
  70. process=subprocess.Popen(command,cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
  71. try:unit_code=process.wait(timeout=args.timeout)
  72. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();unit_code=124
  73. unit_count=0;unit_errors=1;unit_skipped=1
  74. try:
  75. suites=list(ET.parse(out/'python.xml').getroot().iter('testsuite'))
  76. unit_count=sum(int(x.get('tests','0')) for x in suites)
  77. unit_errors=sum(int(x.get('errors','0'))+int(x.get('failures','0')) for x in suites)
  78. unit_skipped=sum(int(x.get('skipped','0')) for x in suites)
  79. except (OSError,ET.ParseError,ValueError):pass
  80. unit_pass=unit_code==0 and unit_count>0 and unit_errors==0 and unit_skipped==0
  81. receipt['unit']={'command':command,'exit_code':unit_code,'tests':unit_count,'skipped':unit_skipped,'status':'PASS' if unit_pass else 'FAIL','log':str(log_path),'log_sha256':hashlib.sha256(log_path.read_bytes()).hexdigest()}
  82. print('Unit tests: '+('PASS' if unit_pass else 'FAIL')+'; '+str(log_path),flush=True)
  83. rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)==2 else products[0],run_root=out/'rtl',timeout=args.timeout))
  84. receipt['rtl_result']=str(out/'rtl/RESULT.json');receipt['complete']=True
  85. receipt['status']='PASS' if unit_pass and rtl_code==0 else 'FAIL'
  86. receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
  87. print(str(receipt_path),flush=True)
  88. return 0 if receipt['status']=='PASS' else (unit_code or rtl_code or 1)
  89. def cmd_package(args: argparse.Namespace) -> int:
  90. # There is only one public package implementation/command surface.
  91. from tools.package_prod2u import main as package_main
  92. return package_main(args.package_args)
  93. def cmd_diagnose(args: argparse.Namespace) -> int:
  94. """Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
  95. if sys.platform != "linux":
  96. return _die("Run RTL diagnostics in the authorized LAN Linux container")
  97. out = args.run_root.resolve()
  98. if out == ROOT or ROOT in out.parents:
  99. return _die("--run-root must be outside the source checkout")
  100. out.mkdir(parents=True, exist_ok=False)
  101. products = ("6400-front-rear", "mrdimm-chamber") if args.target == "all" else (args.target,)
  102. test_manifest_path=ROOT/'config/current-product-tests.json'
  103. test_manifest=json.loads(test_manifest_path.read_text(encoding='utf-8'))
  104. if test_manifest.get('schema')!='prod2u-current-product-tests-v1':
  105. return _die('current test manifest schema mismatch')
  106. tests={name:entry['testbenches'] for name,entry in test_manifest['targets'].items()}
  107. if any(not tests[p] for p in products):
  108. return _die('empty current product test set')
  109. receipt = {"scope": "migration-diagnostic-only", "run_id": out.name,
  110. "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
  111. "expected_check_count": sum(1 + 2 * len(tests[p]) for p in products)}
  112. identity=source_identity(ROOT)
  113. receipt['commit']=identity['commit'];receipt['tree']=identity['tree'];receipt['source']=identity
  114. for tool, flag in (("iverilog", "-V"), ("vvp", "-V")):
  115. receipt[tool] = subprocess.check_output([tool, flag], stderr=subprocess.STDOUT, text=True).splitlines()[0]
  116. def execute(name: str, command: list[str], marker: str | None = None) -> bool:
  117. log_path = out / (name + ".log")
  118. with log_path.open("w", encoding="utf-8") as log:
  119. log.write(json.dumps(command) + "\n"); log.flush()
  120. process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
  121. try:
  122. code = process.wait(timeout=args.timeout)
  123. except subprocess.TimeoutExpired:
  124. os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
  125. observed = log_path.read_text(errors="replace")
  126. passed = code == 0 and (marker is None or marker in observed)
  127. receipt["results"].append({"name": name, "command": command, "exit_code": code,
  128. "status": "PASS" if passed else "FAIL", "required_marker": marker,
  129. "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
  130. # An interrupted partial run must never look like a completed PASS.
  131. receipt["status"] = "RUNNING"
  132. (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
  133. print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
  134. return passed
  135. for product in products:
  136. manifest_path = ROOT / "products" / product / "source-closure.json"
  137. manifest = json.loads(manifest_path.read_text())
  138. sources = manifest["sources"]
  139. benches = tests[product]
  140. contract_paths = ["contracts/6400-manual.yaml"] if product == "6400-front-rear" else ["contracts/mrdimm-wire.yaml", "projects/mrdimm-chamber/project.json"]
  141. input_paths = set(sources + contract_paths + [f"tests/sim/{test}.v" for test in benches])
  142. input_paths.add(manifest_path.relative_to(ROOT).as_posix())
  143. # Include transitive generated headers imported by the mailbox.
  144. input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "generated").rglob("*.vh"))
  145. input_paths.add("tools/fw_cli.py")
  146. input_paths.add("config/current-product-tests.json")
  147. input_paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT / "tests/sim").glob("*.vh"))
  148. if product == "6400-front-rear":
  149. input_paths.add("src/modules/double_bank_target_store.v")
  150. receipt["inputs"][product] = {p: hashlib.sha256((ROOT / p).read_bytes()).hexdigest() for p in sorted(input_paths)}
  151. source_args = [p for p in sources if p.endswith(".v")]
  152. for top, behavior in [(manifest["top_module"], False), *((test, True) for test in benches)]:
  153. binary = out / (top + ".vvp")
  154. argv = ["iverilog", "-g2012", "-Wall", "-I.", "-s", top, "-o", str(binary), *source_args]
  155. if behavior:
  156. argv.append(f"tests/sim/{top}.v")
  157. if top == "prod2u_6400_uart_e2e_tb":
  158. argv.append("src/modules/double_bank_target_store.v")
  159. if execute(top + "-compile", argv) and behavior:
  160. execute(top, ["vvp", str(binary), "+ARTIFACT_DIR=" + str(out)], top + " PASS")
  161. receipt["complete"] = True
  162. receipt["artifacts"] = {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in out.glob("*.hex")}
  163. receipt["status"] = "PASS" if len(receipt["results"]) == receipt["expected_check_count"] and all(
  164. item["status"] == "PASS" for item in receipt["results"]) else "FAIL"
  165. (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
  166. return 0 if receipt["status"] == "PASS" else 1
  167. def main(argv: list[str] | None = None) -> int:
  168. parser = argparse.ArgumentParser(prog="fw", description="Prod2U multi-target firmware entry")
  169. sub = parser.add_subparsers(dest="command", required=True)
  170. sub.add_parser("list")
  171. gen = sub.add_parser("generate")
  172. gen.add_argument("target")
  173. gen.add_argument("--check",action="store_true")
  174. tes = sub.add_parser("test")
  175. tes.add_argument("target")
  176. tes.add_argument("--run-root",type=Path)
  177. tes.add_argument("--timeout",type=int,default=180)
  178. diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
  179. diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber"))
  180. diag.add_argument("--run-root", type=Path, required=True)
  181. diag.add_argument("--timeout", type=int, default=60)
  182. bld = sub.add_parser("build")
  183. bld.add_argument("target")
  184. bld.add_argument("--run-root",type=Path)
  185. pkg = sub.add_parser("package")
  186. pkg.add_argument("package_args",nargs=argparse.REMAINDER)
  187. args = parser.parse_args(argv)
  188. commands = {
  189. "list": cmd_list,
  190. "generate": cmd_generate,
  191. "test": cmd_test,
  192. "diagnose": cmd_diagnose,
  193. "build": cmd_build,
  194. "package": cmd_package,
  195. }
  196. try:
  197. return commands[args.command](args)
  198. except SystemExit as exc:
  199. return int(exc.code or 0)
  200. except (TargetError, ValueError, OSError) as exc:
  201. return _die(str(exc), 2)
  202. if __name__ == "__main__":
  203. load_registry(ROOT)
  204. raise SystemExit(main())