fw_cli.py 20 KB

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