fw_cli.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 ast
  6. import hashlib
  7. import json
  8. import os
  9. import re
  10. import signal
  11. import shutil
  12. import subprocess
  13. import sys
  14. import tempfile
  15. import uuid
  16. import xml.etree.ElementTree as ET
  17. from pathlib import Path
  18. ROOT = Path(__file__).resolve().parents[1]
  19. sys.dont_write_bytecode=True
  20. os.environ['PYTHONDONTWRITEBYTECODE']='1'
  21. if str(ROOT) not in sys.path:
  22. sys.path.insert(0, str(ROOT))
  23. site_pkg = Path("/workspace/site-packages")
  24. if site_pkg.is_dir() and str(site_pkg) not in sys.path:
  25. sys.path.insert(0, str(site_pkg))
  26. from tools.fw_targets import list_aliases, load_registry, resolve_target as resolve_dict, target_status_line
  27. from tools.generate_target import generate_named_target
  28. from tools.target_registry import TargetError, resolve_target
  29. from tools.source_identity import source_identity
  30. def _new_run_path(name: str) -> Path:
  31. base=Path(os.environ.get('XDG_STATE_HOME') or tempfile.gettempdir())/'prod2u/fw'
  32. return base/(name+'-'+uuid.uuid4().hex[:12])
  33. def _die(message: str, code: int = 2) -> int:
  34. print(message, file=sys.stderr)
  35. return code
  36. def cmd_list(_args: argparse.Namespace) -> int:
  37. for alias in list_aliases(ROOT):
  38. print(target_status_line(alias, ROOT))
  39. return 0
  40. def _generate_one(alias: str, *, check: bool=False) -> dict:
  41. return generate_named_target(alias, check=check)
  42. def cmd_generate(args: argparse.Namespace) -> int:
  43. names=list_aliases(ROOT) if args.target=='all' else (args.target,)
  44. for name in names:
  45. print(json.dumps(_generate_one(name,check=args.check),sort_keys=True))
  46. return 0
  47. def _python() -> str:
  48. return sys.executable
  49. def cmd_build(args: argparse.Namespace) -> int:
  50. target=resolve_target(args.target)
  51. if sys.platform!='linux':return _die('Run TD builds in the authorized Linux container')
  52. _generate_one(target.alias,check=True)
  53. out=args.run_root or _new_run_path(target.project_id+'-td')
  54. print('TD run: '+str(out.resolve()),flush=True)
  55. command=[_python(),str(ROOT/'tools/run_6400_td.py'),'--profile',target.project_id,'--run-root',str(out)]
  56. if getattr(args,'host_baud',None) is not None:command.extend(['--host-baud',str(args.host_baud)])
  57. if getattr(args,'allow_dirty',False):command.append('--allow-dirty')
  58. return subprocess.call(command,cwd=ROOT)
  59. def cmd_test(args: argparse.Namespace) -> int:
  60. if sys.platform!='linux':return _die('Run current product verification in the authorized Linux container')
  61. products=tuple(resolve_target(name).project_id for name in list_aliases(ROOT)) if args.target=='all' else (resolve_target(args.target).project_id,)
  62. for product in products:_generate_one(product,check=True)
  63. out=(args.run_root or _new_run_path('current-regression')).resolve()
  64. if out==ROOT or ROOT in out.parents:return _die('--run-root must be outside the source checkout')
  65. out.mkdir(parents=True,exist_ok=False)
  66. manifest=json.loads((ROOT/'config/current-product-tests.json').read_text(encoding='utf-8'))
  67. unit_tests=list(manifest['shared_unit_tests'])
  68. for product in products:unit_tests.extend(manifest['targets'][product]['unit_tests'])
  69. unit_tests=list(dict.fromkeys(unit_tests))
  70. if not unit_tests:return _die('empty current unit test set')
  71. identity=source_identity(ROOT)
  72. receipt={'schema':'prod2u-current-regression-v1','scope':'current unit and RTL regression; not Full acceptance',
  73. 'run_id':out.name,'products':products,'source':identity,'status':'RUNNING','complete':False}
  74. receipt_path=out/'RESULT.json'
  75. receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
  76. command=[_python(),'-m','pytest','-q',*unit_tests,'--junitxml='+str(out/'python.xml'),'--basetemp='+str(out/'pytest-temp'),'-o','cache_dir='+str(out/'pytest-cache')]
  77. log_path=out/'python.log'
  78. with log_path.open('w') as log:
  79. log.write(json.dumps(command)+'\n');log.flush()
  80. process=subprocess.Popen(command,cwd=ROOT,stdout=log,stderr=subprocess.STDOUT,start_new_session=True)
  81. try:unit_code=process.wait(timeout=args.timeout)
  82. except subprocess.TimeoutExpired:os.killpg(process.pid,signal.SIGKILL);process.wait();unit_code=124
  83. unit_count=0;unit_errors=1;unit_skipped=1
  84. try:
  85. suites=list(ET.parse(out/'python.xml').getroot().iter('testsuite'))
  86. unit_count=sum(int(x.get('tests','0')) for x in suites)
  87. unit_errors=sum(int(x.get('errors','0'))+int(x.get('failures','0')) for x in suites)
  88. unit_skipped=sum(int(x.get('skipped','0')) for x in suites)
  89. except (OSError,ET.ParseError,ValueError):pass
  90. unit_pass=unit_code==0 and unit_count>0 and unit_errors==0 and unit_skipped==0
  91. 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()}
  92. print('Unit tests: '+('PASS' if unit_pass else 'FAIL')+'; '+str(log_path),flush=True)
  93. try:
  94. rtl_code=cmd_diagnose(argparse.Namespace(target='all' if len(products)>1 else products[0],run_root=out/'rtl',
  95. timeout=args.timeout,reuse_rtl=getattr(args,'reuse_rtl',None)))
  96. except (ValueError,OSError) as error:
  97. rtl_code=2;receipt['rtl_error']=str(error)
  98. rtl_receipt=out/'rtl/RESULT.json'
  99. receipt['rtl_result']=str(rtl_receipt) if rtl_receipt.is_file() else None;receipt['complete']=True
  100. receipt['status']='PASS' if unit_pass and rtl_code==0 else 'FAIL'
  101. receipt_path.write_text(json.dumps(receipt,indent=2)+'\n')
  102. print(str(receipt_path),flush=True)
  103. return 0 if receipt['status']=='PASS' else (unit_code or rtl_code or 1)
  104. def cmd_package(args: argparse.Namespace) -> int:
  105. # There is only one public package implementation/command surface.
  106. from tools.package_prod2u import main as package_main
  107. return package_main(args.package_args)
  108. def _file_hash(path):
  109. with Path(path).open('rb') as stream:return hashlib.file_digest(stream,'sha256').hexdigest()
  110. def _json_hash(value):
  111. return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
  112. def _generator_dependencies():
  113. pending=['tools/generate_target.py','tools/generate_6400_manual.py','tools/generate_mrdimm_params.py',
  114. 'tools/generate_mrdimm_adc.py','tools/target_registry.py','tools/fw_targets.py']
  115. found=set()
  116. while pending:
  117. name=pending.pop()
  118. if name in found:continue
  119. found.add(name)
  120. for node in ast.walk(ast.parse((ROOT/name).read_text(encoding='utf-8-sig'))):
  121. modules=[a.name for a in node.names] if isinstance(node,ast.Import) else (
  122. [node.module,*[node.module+'.'+a.name for a in node.names]] if isinstance(node,ast.ImportFrom) and node.module else [])
  123. for module in modules:
  124. path=module.replace('.','/')+'.py'
  125. if module.startswith('tools.') and (ROOT/path).is_file():pending.append(path)
  126. return found
  127. def rtl_plan(products,tests,tools):
  128. registry=load_registry(ROOT)
  129. inputs={};steps=[]
  130. generator_files=_generator_dependencies()
  131. for product in products:
  132. manifest_path='products/'+product+'/source-closure.json'
  133. manifest=json.loads((ROOT/manifest_path).read_text(encoding='utf-8'))
  134. sources=manifest['sources']
  135. target=next(row for row in registry['targets'].values() if row['project_id']==product)
  136. paths=set(sources)|generator_files|{manifest_path,'tools/fw_cli.py','projects/registry.json'}
  137. paths.update(p.relative_to(ROOT).as_posix() for p in (ROOT/'contracts').glob('*') if p.suffix in ('.json','.yaml'))
  138. for key in ('project_config','adc','sdc'):
  139. if target.get(key):paths.add(target[key])
  140. projects=[target['project_config']];seen_projects=set()
  141. while projects:
  142. name=projects.pop()
  143. if name in seen_projects:continue
  144. seen_projects.add(name);paths.add(name)
  145. configuration=json.loads((ROOT/name).read_text(encoding='utf-8'))
  146. if configuration.get('inherits'):projects.append(configuration['inherits'])
  147. for key in ('board_evidence','constraints','source_closure'):
  148. value=configuration.get(key)
  149. if isinstance(value,str) and (ROOT/value).is_file():paths.add(value)
  150. if product=='mrdimm-chamber':paths.add('config/pin_inventory.prod2u_door_temp_v1_2.json')
  151. paths.update('tests/sim/'+name+'.v' for name in tests[product])
  152. if product=='6400-front-rear':paths.add('src/modules/double_bank_target_store.v')
  153. pending=list(paths)
  154. while pending:
  155. name=pending.pop()
  156. if Path(name).suffix not in ('.v','.sv','.vh'):continue
  157. for include in re.findall(chr(96)+r'include\s+"([^"]+)"',(ROOT/name).read_text(encoding='utf-8')):
  158. path=include if (ROOT/include).is_file() else (Path(name).parent/include).as_posix()
  159. if path not in paths:paths.add(path);pending.append(path)
  160. inputs[product]={name:_file_hash(ROOT/name) for name in sorted(paths)}
  161. source_args=[name for name in sources if name.endswith('.v')]
  162. for top,behavior in [(manifest['top_module'],False),*((name,True) for name in tests[product])]:
  163. if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*',top):raise ValueError('invalid regression top')
  164. step_tag = f"{product}-{top}" if len(products) > 1 else top
  165. binary='{run_root}/'+step_tag+'.vvp'
  166. command=['iverilog','-g2012','-Wall','-I.','-B',tools['iverilog']['library_root'],'-s',top,'-o',binary,*source_args]
  167. if behavior:
  168. command.append('tests/sim/'+top+'.v')
  169. if top=='prod2u_6400_uart_e2e_tb':command.append('src/modules/double_bank_target_store.v')
  170. steps.append({'name':step_tag+'-compile','command':command,'marker':None,'binary':step_tag+'.vvp'})
  171. if behavior:steps.append({'name':step_tag,'command':['vvp',binary,'+ARTIFACT_DIR={run_root}'],'marker':top+' PASS','binary':None})
  172. if len({x['name'] for x in steps})!=len(steps):raise ValueError('duplicate regression output names')
  173. return {'schema':'prod2u-rtl-input-closure-v1','inputs':inputs,'tools':tools,
  174. 'test_configuration':{p:tests[p] for p in products},'steps':steps}
  175. def _render_command(step,run_root):
  176. return [arg.replace('{run_root}',str(run_root)) for arg in step['command']]
  177. def validate_rtl_cache(path,plan):
  178. path=Path(path).resolve();receipt_bytes=path.read_bytes();cached=json.loads(receipt_bytes)
  179. if cached.get('schema')!='prod2u-rtl-regression-v2' or cached.get('status')!='PASS' or cached.get('complete') is not True:
  180. raise ValueError('RTL_REUSE_REJECTED: only complete v2 PASS receipts can be reused')
  181. key=_json_hash(plan)
  182. if cached.get('cache_key')!=key or cached.get('plan')!=plan:
  183. raise ValueError('RTL_REUSE_REJECTED: input/tool/command closure differs')
  184. if not plan['steps'] or cached.get('inputs')!=plan['inputs']:
  185. raise ValueError('RTL_REUSE_REJECTED: empty or inconsistent input evidence')
  186. origin=cached.get('source',{})
  187. if any(not re.fullmatch('[0-9a-f]{40}',str(origin.get(k,''))) or origin.get(k)!=cached.get(k) for k in ('commit','tree')):
  188. raise ValueError('RTL_REUSE_REJECTED: source identity missing or inconsistent')
  189. rows=cached.get('results',[])
  190. if len(rows)!=len(plan['steps']) or cached.get('expected_check_count')!=len(rows):
  191. raise ValueError('RTL_REUSE_REJECTED: missing checks')
  192. native_root=cached.get('native_run_root')
  193. if not native_root or not Path(native_root).is_absolute():raise ValueError('RTL_REUSE_REJECTED: native command root missing')
  194. copies={}
  195. for expected,row in zip(plan['steps'],rows):
  196. command=_render_command(expected,native_root)
  197. name=expected['name']+'.log'
  198. if (row.get('name')!=expected['name'] or row.get('command')!=command or row.get('required_marker')!=expected['marker']
  199. or row.get('status')!='PASS' or row.get('exit_code')!=0 or row.get('log')!=name):
  200. raise ValueError('RTL_REUSE_REJECTED: result/command mismatch')
  201. data=(path.parent/name).read_bytes()
  202. if hashlib.sha256(data).hexdigest()!=row.get('log_sha256'):raise ValueError('RTL_REUSE_REJECTED: log hash mismatch')
  203. text=data.decode('utf-8',errors='replace')
  204. lines=text.splitlines()
  205. if not lines or json.loads(lines[0])!=command or (expected['marker'] and expected['marker'] not in text):
  206. raise ValueError('RTL_REUSE_REJECTED: native log/marker mismatch')
  207. copies[name]=data
  208. artifacts=cached.get('artifacts',{})
  209. required={step['binary'] for step in plan['steps'] if step['binary']}
  210. if not required<=set(artifacts):raise ValueError('RTL_REUSE_REJECTED: compiled binaries missing')
  211. for name,expected_hash in artifacts.items():
  212. if not re.fullmatch(r'[A-Za-z0-9_.-]+\.(vvp|hex)',name):
  213. raise ValueError('RTL_REUSE_REJECTED: invalid artifact name')
  214. data=(path.parent/name).read_bytes()
  215. if not data or hashlib.sha256(data).hexdigest()!=expected_hash:raise ValueError('RTL_REUSE_REJECTED: artifact hash mismatch')
  216. copies[name]=data
  217. return cached,copies,receipt_bytes
  218. def _rtl_tools():
  219. result={}
  220. driver=Path(shutil.which('iverilog') or '')
  221. requested=os.environ.get('PROD2U_IVERILOG_LIBDIR')
  222. candidates=[Path(requested)] if requested else [driver.parent.parent/'lib/ivl',*sorted(Path('/usr/lib').glob('*/ivl'))]
  223. library=next((p.resolve() for p in candidates if (p/'ivl').is_file() and (p/'ivlpp').is_file()),None)
  224. if library is None:raise ValueError('Icarus backend directory unavailable; set PROD2U_IVERILOG_LIBDIR')
  225. for tool in ('iverilog','vvp'):
  226. path=Path(shutil.which(tool) or '')
  227. if not path.is_file():raise ValueError('RTL tool missing: '+tool)
  228. version=subprocess.check_output([tool,*(['-B',str(library)] if tool=='iverilog' else []),'-V'],stderr=subprocess.STDOUT)
  229. result[tool]={'path':str(path.resolve()),'sha256':_file_hash(path),'version':version.decode(errors='replace').splitlines()[0],
  230. 'version_output_sha256':hashlib.sha256(version).hexdigest()}
  231. result['iverilog']['library_root']=str(library)
  232. result['iverilog']['library_files']={p.relative_to(library).as_posix():_file_hash(p) for p in sorted(library.rglob('*')) if p.is_file()}
  233. import yaml
  234. result['python']=sys.version;result['PyYAML']=yaml.__version__
  235. return result
  236. def cmd_diagnose(args: argparse.Namespace) -> int:
  237. """Bounded migrated RTL checks; explicitly not the full Quick/Full gate."""
  238. if sys.platform != "linux":
  239. return _die("Run RTL diagnostics in the authorized LAN Linux container")
  240. out = args.run_root.resolve()
  241. if out == ROOT or ROOT in out.parents:
  242. return _die("--run-root must be outside the source checkout")
  243. test_manifest_path=ROOT/'config/current-product-tests.json'
  244. test_manifest=json.loads(test_manifest_path.read_text(encoding='utf-8'))
  245. products = tuple(test_manifest.get('targets', {}).keys()) if args.target == "all" else (args.target,)
  246. if test_manifest.get('schema')!='prod2u-current-product-tests-v1':
  247. return _die('current test manifest schema mismatch')
  248. tests={name:entry['testbenches'] for name,entry in test_manifest['targets'].items()}
  249. if any(not tests[p] for p in products):
  250. return _die('empty current product test set')
  251. for product in products:_generate_one(product,check=True)
  252. plan=rtl_plan(products,tests,_rtl_tools())
  253. identity=source_identity(ROOT)
  254. reuse=getattr(args,'reuse_rtl',None)
  255. if reuse:
  256. cached,copies,receipt_bytes=validate_rtl_cache(reuse,plan)
  257. out.mkdir(parents=True,exist_ok=False)
  258. for name,data in copies.items():(out/name).write_bytes(data)
  259. receipt={**cached,'run_id':out.name,'source':identity,'commit':identity['commit'],'tree':identity['tree'],
  260. 'execution':'reused','reuse':{'receipt':str(Path(reuse).resolve()),'sha256':hashlib.sha256(receipt_bytes).hexdigest(),
  261. 'source':cached['source'],'scope':'copied verified native evidence; no RTL command rerun'}}
  262. (out/'REUSED-RECEIPT.json').write_bytes(receipt_bytes)
  263. (out/'RESULT.json').write_text(json.dumps(receipt,indent=2)+'\n',encoding='utf-8')
  264. print('RTL evidence reused after exact closure/log/artifact checks: '+str(reuse),flush=True)
  265. return 0
  266. out.mkdir(parents=True,exist_ok=False)
  267. receipt = {"schema":"prod2u-rtl-regression-v2","scope": "migration-diagnostic-only", "run_id": out.name,
  268. "hardware": "NOT_RUN", "results": [], "inputs": {}, "status": "RUNNING", "complete": False,
  269. "expected_check_count":len(plan['steps']),"plan":plan,"cache_key":_json_hash(plan),
  270. "native_run_root":str(out),"execution":"fresh"}
  271. receipt['commit']=identity['commit'];receipt['tree']=identity['tree'];receipt['source']=identity
  272. for tool in ('iverilog','vvp'):receipt[tool]=plan['tools'][tool]['version']
  273. def execute(name: str, command: list[str], marker: str | None = None,binary=None) -> bool:
  274. log_path = out / (name + ".log")
  275. with log_path.open("w", encoding="utf-8") as log:
  276. log.write(json.dumps(command) + "\n"); log.flush()
  277. process = subprocess.Popen(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
  278. try:
  279. code = process.wait(timeout=args.timeout)
  280. except subprocess.TimeoutExpired:
  281. os.killpg(process.pid, signal.SIGKILL); process.wait(); code = 124
  282. observed = log_path.read_text(errors="replace")
  283. passed = code == 0 and (marker is None or marker in observed) and (not binary or ((out/binary).is_file() and (out/binary).stat().st_size>0))
  284. receipt["results"].append({"name": name, "command": command, "exit_code": code,
  285. "status": "PASS" if passed else "FAIL", "required_marker": marker,
  286. "log": log_path.name, "log_sha256": hashlib.sha256(log_path.read_bytes()).hexdigest()})
  287. # An interrupted partial run must never look like a completed PASS.
  288. receipt["status"] = "RUNNING"
  289. (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
  290. print(f"{name}: {'PASS' if passed else 'FAIL'}", flush=True)
  291. return passed
  292. receipt['inputs']=plan['inputs']
  293. compile_pass={}
  294. for step in plan['steps']:
  295. if step['binary']:
  296. compile_pass[step['name'].removesuffix('-compile')]=execute(step['name'],_render_command(step,out),None,step['binary'])
  297. elif compile_pass.get(step['name']):
  298. execute(step['name'],_render_command(step,out),step['marker'])
  299. receipt["complete"] = True
  300. receipt["artifacts"] = {p.name: _file_hash(p) for p in out.iterdir() if p.suffix in (".hex",".vvp")}
  301. receipt["status"] = "PASS" if len(receipt["results"]) == receipt["expected_check_count"] and all(
  302. item["status"] == "PASS" for item in receipt["results"]) else "FAIL"
  303. (out / "RESULT.json").write_text(json.dumps(receipt, indent=2) + "\n")
  304. return 0 if receipt["status"] == "PASS" else 1
  305. def main(argv: list[str] | None = None) -> int:
  306. parser = argparse.ArgumentParser(prog="fw", description="Prod2U multi-target firmware entry")
  307. sub = parser.add_subparsers(dest="command", required=True)
  308. sub.add_parser("list")
  309. gen = sub.add_parser("generate")
  310. gen.add_argument("target")
  311. gen.add_argument("--check",action="store_true")
  312. tes = sub.add_parser("test")
  313. tes.add_argument("target")
  314. tes.add_argument("--run-root",type=Path)
  315. tes.add_argument("--timeout",type=int,default=180)
  316. tes.add_argument("--reuse-rtl",type=Path,help="reuse only matching complete RTL evidence; Python tests still run")
  317. diag = sub.add_parser("diagnose", help="bounded migration tests; not Full acceptance")
  318. diag.add_argument("target", choices=("all", "6400-front-rear", "mrdimm-chamber", "6400-v2"))
  319. diag.add_argument("--run-root", type=Path, required=True)
  320. diag.add_argument("--timeout", type=int, default=60)
  321. diag.add_argument("--reuse-rtl",type=Path,help="verified v2 RTL receipt; mismatches reject instead of silently rerunning")
  322. bld = sub.add_parser("build")
  323. bld.add_argument("target")
  324. bld.add_argument("--run-root",type=Path)
  325. bld.add_argument("--host-baud",type=int,choices=(921600,460800,230400,115200))
  326. bld.add_argument("--allow-dirty",action="store_true")
  327. pkg = sub.add_parser("package")
  328. pkg.add_argument("package_args",nargs=argparse.REMAINDER)
  329. args = parser.parse_args(argv)
  330. commands = {
  331. "list": cmd_list,
  332. "generate": cmd_generate,
  333. "test": cmd_test,
  334. "diagnose": cmd_diagnose,
  335. "build": cmd_build,
  336. "package": cmd_package,
  337. }
  338. try:
  339. return commands[args.command](args)
  340. except SystemExit as exc:
  341. return int(exc.code or 0)
  342. except (TargetError, ValueError, OSError) as exc:
  343. return _die(str(exc), 2)
  344. if __name__ == "__main__":
  345. load_registry(ROOT)
  346. raise SystemExit(main())