build_windows_exes_remote.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. #!/usr/bin/env python3
  2. """Build current product GUIs natively on Windows from explicit, verified TD receipts.
  3. Example:
  4. python tools/build_windows_exes_remote.py --product 6400-v2 mrdimm-chamber \
  5. --run-root 6400-v2=/data/prod2u/cpld-runs/current-6400 \
  6. --run-root mrdimm-chamber=/data/prod2u/cpld-runs/current-mrdimm \
  7. --output-dir /data/prod2u/windows-exes
  8. Every invocation keeps a new local and remote run directory. Native logs, metadata,
  9. self-test exit codes and EXE hashes are retained, including failed builds. It does
  10. not program a board or claim a hardware or visual GUI test.
  11. """
  12. from __future__ import annotations
  13. import argparse
  14. import base64
  15. from datetime import datetime, timezone
  16. import hashlib
  17. import json
  18. from pathlib import Path
  19. import re
  20. import subprocess
  21. import sys
  22. import tarfile
  23. import uuid
  24. ROOT = Path(__file__).resolve().parents[1]
  25. if str(ROOT) not in sys.path:
  26. sys.path.insert(0, str(ROOT))
  27. from tools.source_identity import source_identity
  28. PRODUCTS = {
  29. "6400-v2": {
  30. "exe_name": "Prod2U-6400-V2-GUI", "script": "tools/6400_v2_hex_gui.py",
  31. "board": "6400V2.0", "generated": "6400-v2",
  32. "assets": [("generated/6400-v2/manual-uart-contract.json", "generated/6400-v2"),
  33. ("generated/6400-v2/golden-vectors.json", "generated/6400-v2"),
  34. ("contracts/ct7428-format.json", "generated/6400-v2")],
  35. },
  36. "mrdimm-chamber": {
  37. "exe_name": "Prod2U-MRDIMM-GUI", "script": "tools/mrdimm_hex_gui.py",
  38. "board": "FCB V1.2", "generated": "mrdimm",
  39. "assets": [("generated/mrdimm/snapshot-layout.json", ".")],
  40. },
  41. }
  42. def sha256_file(path: Path) -> str:
  43. with Path(path).open("rb") as stream:
  44. return hashlib.file_digest(stream, "sha256").hexdigest()
  45. def assignments(values: list[str]) -> dict[str, Path]:
  46. result = {}
  47. for value in values:
  48. product, separator, path = value.partition("=")
  49. if not separator or product not in PRODUCTS or not path or product in result:
  50. raise ValueError("expected one PRODUCT=PATH per product: " + value)
  51. result[product] = Path(path).resolve()
  52. return result
  53. def prepare_product(product: str, receipt_path: Path, run_root: Path | None,
  54. version: str, identity: dict) -> dict:
  55. receipt_path = Path(receipt_path).resolve()
  56. receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
  57. if (receipt.get("profile") != product or receipt.get("status") != "PASS"
  58. or receipt.get("production") is not True or receipt.get("simulation_only") is not False
  59. or not receipt.get("timing_pass_25mhz")
  60. or receipt.get("warning_audit", {}).get("status") != "PASS"):
  61. raise ValueError(f"{product}: requires a passing production TD receipt with timing/warning audit")
  62. if receipt.get("release_version") not in (None, version):
  63. raise ValueError(f"{product}: TD release_version differs from VERSION")
  64. inputs = receipt.get("inputs", {})
  65. if not inputs or any(sha256_file(ROOT / name) != digest for name, digest in inputs.items()):
  66. raise ValueError(f"{product}: current source does not match TD input hashes")
  67. manifest_sha = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
  68. if receipt.get("source_manifest_sha256") != manifest_sha:
  69. raise ValueError(f"{product}: TD input manifest hash mismatch")
  70. for key in ("commit", "tree"):
  71. if not re.fullmatch(r"[0-9a-f]{40}", str(receipt.get(key, ""))):
  72. raise ValueError(f"{product}: missing TD {key}")
  73. if not receipt.get("bitstream"):
  74. raise ValueError(f"{product}: receipt has no bitstream path")
  75. bitstream = Path(receipt["bitstream"])
  76. if not bitstream.is_absolute():
  77. bitstream = (run_root or receipt_path.parent) / bitstream
  78. bitstream = bitstream.resolve()
  79. if sha256_file(bitstream) != receipt.get("bitstream_sha256"):
  80. raise ValueError(f"{product}: bitstream hash differs from TD receipt")
  81. build_parameters = receipt.get("build_parameters", {})
  82. host_baud = build_parameters.get("host_baud")
  83. if host_baud not in (921600, 460800, 230400, 115200):
  84. raise ValueError(f"{product}: TD receipt must identify the actual host_baud")
  85. cfg = PRODUCTS[product]
  86. contract_path = ROOT / "generated" / cfg["generated"] / "contract-sha256.txt"
  87. contract_sha = contract_path.read_text().strip()
  88. if not re.fullmatch(r"[0-9a-f]{64}", contract_sha):
  89. raise ValueError(f"{product}: generated contract identity is invalid")
  90. metadata = {
  91. "product": product, "profile": product, "board": cfg["board"], "release_version": version,
  92. "commit": identity["commit"], "source_tree": identity["tree"],
  93. "source_clean": identity.get("clean"), "source_kind": identity["source_kind"],
  94. "contract_sha256": contract_sha,
  95. "bitstream_sha256": receipt["bitstream_sha256"],
  96. "bitstream_source_commit": receipt["commit"], "bitstream_source_tree": receipt["tree"],
  97. "source_manifest_sha256": manifest_sha, "td_receipt_sha256": sha256_file(receipt_path),
  98. "td_run_id": receipt.get("run_id"), "host_baud": host_baud, "bmc_baud": 115200,
  99. "hardware_validation": "NOT_RUN_BY_GUI_BUILD",
  100. }
  101. return {**cfg, "metadata": metadata, "receipt_path": str(receipt_path),
  102. "bitstream": str(bitstream), "run_root": str(run_root or receipt_path.parent)}
  103. # The Windows runner uses its local interpreter and writes results even on failure.
  104. NATIVE_RUNNER = r'''
  105. import hashlib, json, os, subprocess, sys, traceback
  106. from pathlib import Path
  107. HERE = Path(__file__).resolve().parent
  108. ROOT = HERE / "src"
  109. plan = json.loads((HERE / "build-plan.json").read_text(encoding="utf-8"))
  110. summary = {"schema": "prod2u-native-windows-gui-v2", "run_id": plan["run_id"],
  111. "release_version": plan["release_version"], "source_files_sha256": plan["source_files_sha256"],
  112. "python": sys.version, "platform": sys.platform, "products": {},
  113. "visual_gui_validation": "NOT_RUN", "hardware_validation": "NOT_RUN"}
  114. (HERE / "artifacts").mkdir(exist_ok=True)
  115. for product, cfg in plan["products"].items():
  116. artifact = HERE / "artifacts" / product
  117. artifact.mkdir(exist_ok=True)
  118. result = {"status": "FAIL", "metadata": cfg["metadata"]}
  119. summary["products"][product] = result
  120. try:
  121. for source, digest in plan["source_files_sha256"].items():
  122. if hashlib.sha256((ROOT / source).read_bytes()).hexdigest() != digest:
  123. raise ValueError("transferred source hash mismatch: " + source)
  124. work = HERE / "work" / product
  125. work.mkdir(parents=True)
  126. meta_path = artifact / "gui-build-metadata.json"
  127. meta_path.write_text(json.dumps(cfg["metadata"], indent=2) + "\n", encoding="utf-8")
  128. name = cfg["exe_name"] + "-v" + plan["release_version"]
  129. version_parts = tuple(int(v) for v in plan["release_version"].split(".")) + (0,)
  130. if len(version_parts) != 4:
  131. raise ValueError("release version must be major.minor.patch")
  132. version_file = work / "version_info.txt"
  133. version_file.write_text(
  134. "VSVersionInfo(ffi=FixedFileInfo(filevers=" + repr(version_parts) +
  135. ", prodvers=" + repr(version_parts) +
  136. ", mask=0x3f, flags=0, OS=0x40004, fileType=1, subtype=0, date=(0,0)), "
  137. "kids=[StringFileInfo([StringTable('040904B0', [" +
  138. ",".join("StringStruct(" + repr(k) + "," + repr(v) + ")" for k, v in {
  139. "CompanyName": "Prod2U", "ProductName": cfg["board"],
  140. "FileDescription": cfg["board"] + " control software",
  141. "FileVersion": ".".join(map(str, version_parts)),
  142. "ProductVersion": plan["release_version"],
  143. "OriginalFilename": name + ".exe",
  144. }.items()) + "])]), VarFileInfo([VarStruct('Translation', [1033,1200])])])",
  145. encoding="utf-8")
  146. command = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", "--onefile", "--windowed",
  147. "--name", name, "--version-file", str(version_file), "--distpath", str(artifact), "--workpath", str(work / "build"),
  148. "--specpath", str(work), "--paths", str(ROOT), "--paths", str(ROOT / "tools"),
  149. "--paths", str(ROOT / "tools/_vendor"), "--hidden-import", "hth_protocol",
  150. "--hidden-import", "prod2u_status", "--hidden-import", "stream_receiver",
  151. "--hidden-import", "serial", "--hidden-import", "serial.tools.list_ports",
  152. "--add-data", str(meta_path) + ";.", "--add-data", str(ROOT / "VERSION") + ";."]
  153. for source, destination in cfg["assets"]:
  154. command += ["--add-data", str(ROOT / source) + ";" + destination]
  155. command.append(str(ROOT / cfg["script"]))
  156. # An EXE without pyserial cannot fulfil the connected GUI's purpose.
  157. with (artifact / "build.log").open("w", encoding="utf-8") as log:
  158. preflight = subprocess.run([sys.executable, "-c", "import tkinter, serial, PyInstaller"],
  159. stdout=log, stderr=subprocess.STDOUT, timeout=60)
  160. result["dependency_exit"] = preflight.returncode
  161. if preflight.returncode:
  162. raise RuntimeError("native GUI dependencies missing; see build.log")
  163. run = subprocess.run(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, timeout=1200)
  164. result["build_exit"] = run.returncode
  165. if run.returncode:
  166. raise RuntimeError("PyInstaller failed; see build.log")
  167. exe = artifact / (name + ".exe")
  168. import pefile
  169. pe = pefile.PE(str(exe))
  170. vi = pe.VS_FIXEDFILEINFO[0]
  171. actual_version = (vi.FileVersionMS >> 16, vi.FileVersionMS & 65535,
  172. vi.FileVersionLS >> 16, vi.FileVersionLS & 65535)
  173. pe.close()
  174. if actual_version != version_parts:
  175. raise ValueError("Windows FileVersion does not match release")
  176. result["windows_file_version"] = ".".join(map(str, actual_version))
  177. with (artifact / "self-test.log").open("w", encoding="utf-8") as log:
  178. test = subprocess.run([str(exe), "--self-test", "--self-test-report", str(artifact / "self-test.json")],
  179. stdout=log, stderr=subprocess.STDOUT, timeout=60)
  180. result["self_test_exit"] = test.returncode
  181. if test.returncode:
  182. raise RuntimeError("native EXE self-test failed; see self-test.log")
  183. self_test = json.loads((artifact / "self-test.json").read_text(encoding="utf-8"))
  184. if self_test.get("status") != "PASS" or self_test.get("product") != product:
  185. raise RuntimeError("native EXE self-test report missing or for wrong product")
  186. result.update(status="PASS", exe="artifacts/" + product + "/" + exe.name,
  187. size=exe.stat().st_size, sha256=hashlib.sha256(exe.read_bytes()).hexdigest(),
  188. self_test=self_test)
  189. except Exception as exc:
  190. result["error"] = str(exc)
  191. (artifact / "failure.log").write_text(traceback.format_exc(), encoding="utf-8")
  192. finally:
  193. (artifact / "RESULT.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
  194. (HERE / "BUILD-SUMMARY.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
  195. print(product + ": " + result["status"], flush=True)
  196. sys.exit(0 if all(r["status"] == "PASS" for r in summary["products"].values()) else 1)
  197. '''
  198. def powershell_command(script: str) -> str:
  199. return "powershell -NoProfile -NonInteractive -EncodedCommand " + base64.b64encode(script.encode("utf-16le")).decode()
  200. def ps_quote(text: str) -> str:
  201. return "'" + text.replace("'", "''") + "'"
  202. def prepare_product_blocked_td(product: str, blocker_path: Path, version: str, identity: dict, host_baud: int = 921600) -> dict:
  203. """Prepare native Windows GUI build when TD bitgen is honestly blocked (e.g. expired license)."""
  204. blocker_path = Path(blocker_path).resolve()
  205. blocker = json.loads(blocker_path.read_text(encoding="utf-8"))
  206. status = str(blocker.get("status", ""))
  207. if not status.startswith("BLOCKED_"):
  208. raise ValueError(f"{product}: blocker receipt status must start with BLOCKED_, got {status!r}")
  209. cfg = PRODUCTS[product]
  210. contract_path = ROOT / "generated" / cfg["generated"] / "contract-sha256.txt"
  211. contract_sha = contract_path.read_text().strip()
  212. if not re.fullmatch(r"[0-9a-f]{64}", contract_sha):
  213. raise ValueError(f"{product}: generated contract identity is invalid")
  214. metadata = {
  215. "product": product, "profile": product, "board": cfg["board"], "release_version": version,
  216. "commit": identity["commit"], "source_tree": identity["tree"],
  217. "source_clean": identity.get("clean"), "source_kind": identity["source_kind"],
  218. "contract_sha256": contract_sha,
  219. "bitstream_status": status,
  220. "bitstream_sha256": None,
  221. "td_blocker_receipt_sha256": sha256_file(blocker_path),
  222. "td_blocker_error": blocker.get("error_code"),
  223. "host_baud": int(host_baud), "bmc_baud": 115200,
  224. "hardware_validation": "NOT_RUN_BY_GUI_BUILD",
  225. }
  226. return {**cfg, "metadata": metadata, "receipt_path": str(blocker_path),
  227. "bitstream": None, "run_root": str(blocker_path.parent)}
  228. def main(argv=None) -> int:
  229. parser = argparse.ArgumentParser(description=__doc__)
  230. parser.add_argument("--product", choices=tuple(PRODUCTS), nargs="+", required=True)
  231. parser.add_argument("--td-receipt", action="append", default=[], metavar="PRODUCT=PATH")
  232. parser.add_argument("--run-root", action="append", default=[], metavar="PRODUCT=PATH")
  233. parser.add_argument("--td-blocker-receipt", type=Path, default=None,
  234. help="Explicit TD blocker receipt JSON (status BLOCKED_*) when no .bit exists")
  235. parser.add_argument("--host-baud", type=int, default=921600, choices=(921600, 460800, 230400, 115200))
  236. parser.add_argument("--output-dir", type=Path, required=True)
  237. parser.add_argument("--host", default="administrator@192.168.2.24")
  238. parser.add_argument("--windows-build-root", default="C:/Users/Administrator/prod2u-builds")
  239. parser.add_argument("--windows-python", default="python")
  240. parser.add_argument("--prepare-only", action="store_true", help="prepare sources/plan without connecting to Windows")
  241. args = parser.parse_args(argv)
  242. receipts, roots = assignments(args.td_receipt), assignments(args.run_root)
  243. version = (ROOT / "VERSION").read_text().strip()
  244. if not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?", version):
  245. raise ValueError("VERSION must contain a readable semantic version")
  246. identity = source_identity(ROOT)
  247. products = {}
  248. for product in dict.fromkeys(args.product):
  249. if args.td_blocker_receipt is not None:
  250. products[product] = prepare_product_blocked_td(product, args.td_blocker_receipt, version, identity, args.host_baud)
  251. continue
  252. receipt = receipts.get(product)
  253. if receipt is None and product in roots:
  254. receipt = roots[product] / "td-receipt.json"
  255. if receipt is None:
  256. parser.error("missing --td-receipt or --run-root for " + product)
  257. products[product] = prepare_product(product, receipt, roots.get(product), version, identity)
  258. run_id = "windows-gui-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8]
  259. local = args.output_dir.resolve() / run_id
  260. local.mkdir(parents=True, exist_ok=False)
  261. remote = args.windows_build_root.rstrip("/") + "/" + run_id
  262. files = {"VERSION", "tools/prod2u_gui.py", "tools/stream_receiver.py",
  263. "tools/_vendor/hth_protocol.py", "tools/_vendor/prod2u_status.py"}
  264. for cfg in products.values():
  265. files.add(cfg["script"])
  266. files.update(source for source, _ in cfg["assets"])
  267. plan = {"schema": "prod2u-native-windows-build-plan-v2", "run_id": run_id,
  268. "release_version": version, "windows_build_dir": remote, "products": products,
  269. "source_files_sha256": {name: sha256_file(ROOT / name) for name in sorted(files)}}
  270. (local / "build-plan.json").write_text(json.dumps(plan, indent=2) + "\n", encoding="utf-8")
  271. (local / "run_build.py").write_text(NATIVE_RUNNER, encoding="utf-8")
  272. with tarfile.open(local / "build_src.tar", "w") as archive:
  273. for name in sorted(files):
  274. archive.add(ROOT / name, arcname=name, recursive=False)
  275. if args.prepare_only:
  276. print(str(local))
  277. return 0
  278. def command(arguments, log_name, check=True):
  279. with (local / log_name).open("a", encoding="utf-8") as log:
  280. result = subprocess.run(arguments, stdout=log, stderr=subprocess.STDOUT)
  281. if check and result.returncode:
  282. raise RuntimeError(f"command failed ({result.returncode}); see {local / log_name}")
  283. return result.returncode
  284. def remote_ps(script, log_name, check=True):
  285. return command(["ssh", "-o", "ConnectTimeout=10", args.host, powershell_command(script)], log_name, check)
  286. remote_ps("$ErrorActionPreference='Stop'; $p=" + ps_quote(remote)
  287. + "; if (Test-Path $p) {throw 'run directory exists'}; New-Item -ItemType Directory -Path ($p+'/src') | Out-Null",
  288. "transfer.log")
  289. for name in ("build_src.tar", "build-plan.json", "run_build.py"):
  290. command(["scp", str(local / name), args.host + ":" + remote + "/" + name], "transfer.log")
  291. remote_ps("tar -xf " + ps_quote(remote + "/build_src.tar") + " -C " + ps_quote(remote + "/src")
  292. + "; exit $LASTEXITCODE", "transfer.log")
  293. build_exit = remote_ps("& " + ps_quote(args.windows_python) + " " + ps_quote(remote + "/run_build.py")
  294. + "; exit $LASTEXITCODE", "native-run.log", check=False)
  295. # Preserve failed native evidence too; no shared directory or previous run is deleted.
  296. remote_ps("Set-Location " + ps_quote(remote)
  297. + "; tar -cf native-results.tar artifacts BUILD-SUMMARY.json build-plan.json; exit $LASTEXITCODE",
  298. "transfer.log")
  299. command(["scp", args.host + ":" + remote + "/native-results.tar", str(local / "native-results.tar")], "transfer.log")
  300. with tarfile.open(local / "native-results.tar") as archive:
  301. archive.extractall(local, filter="data")
  302. summary = json.loads((local / "BUILD-SUMMARY.json").read_text(encoding="utf-8"))
  303. if set(summary.get("products", {})) != set(products):
  304. raise ValueError("native summary product set differs from the build plan")
  305. for product, result in summary["products"].items():
  306. if result.get("metadata") != products[product]["metadata"]:
  307. raise ValueError("native summary metadata differs from the build plan: " + product)
  308. if result.get("status") == "PASS":
  309. if sha256_file(local / result["exe"]) != result["sha256"]:
  310. raise ValueError("download hash mismatch: " + product)
  311. (local / "DOWNLOAD-VERIFICATION.json").write_text(json.dumps({
  312. "run_id": run_id, "native_build_exit": build_exit, "download_hashes": "PASS",
  313. "native_summary_sha256": sha256_file(local / "BUILD-SUMMARY.json"),
  314. "windows_build_dir": remote, "local_dir": str(local),
  315. }, indent=2) + "\n", encoding="utf-8")
  316. print(str(local / "BUILD-SUMMARY.json"))
  317. return 0 if build_exit == 0 and all(r["status"] == "PASS" for r in summary["products"].values()) else 1
  318. if __name__ == "__main__":
  319. raise SystemExit(main())