| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345 |
- #!/usr/bin/env python3
- """Build current product GUIs natively on Windows from explicit, verified TD receipts.
- Example:
- python tools/build_windows_exes_remote.py --product 6400-v2 mrdimm-chamber \
- --run-root 6400-v2=/data/prod2u/cpld-runs/current-6400 \
- --run-root mrdimm-chamber=/data/prod2u/cpld-runs/current-mrdimm \
- --output-dir /data/prod2u/windows-exes
- Every invocation keeps a new local and remote run directory. Native logs, metadata,
- self-test exit codes and EXE hashes are retained, including failed builds. It does
- not program a board or claim a hardware or visual GUI test.
- """
- from __future__ import annotations
- import argparse
- import base64
- from datetime import datetime, timezone
- import hashlib
- import json
- from pathlib import Path
- import re
- import subprocess
- import sys
- import tarfile
- import uuid
- ROOT = Path(__file__).resolve().parents[1]
- if str(ROOT) not in sys.path:
- sys.path.insert(0, str(ROOT))
- from tools.source_identity import source_identity
- PRODUCTS = {
- "6400-v2": {
- "exe_name": "Prod2U-6400-V2-GUI", "script": "tools/6400_v2_hex_gui.py",
- "board": "6400V2.0", "generated": "6400-v2",
- "assets": [("generated/6400-v2/manual-uart-contract.json", "generated/6400-v2"),
- ("generated/6400-v2/golden-vectors.json", "generated/6400-v2"),
- ("contracts/ct7428-format.json", "generated/6400-v2")],
- },
- "mrdimm-chamber": {
- "exe_name": "Prod2U-MRDIMM-GUI", "script": "tools/mrdimm_hex_gui.py",
- "board": "FCB V1.2", "generated": "mrdimm",
- "assets": [("generated/mrdimm/snapshot-layout.json", ".")],
- },
- }
- def sha256_file(path: Path) -> str:
- with Path(path).open("rb") as stream:
- return hashlib.file_digest(stream, "sha256").hexdigest()
- def assignments(values: list[str]) -> dict[str, Path]:
- result = {}
- for value in values:
- product, separator, path = value.partition("=")
- if not separator or product not in PRODUCTS or not path or product in result:
- raise ValueError("expected one PRODUCT=PATH per product: " + value)
- result[product] = Path(path).resolve()
- return result
- def prepare_product(product: str, receipt_path: Path, run_root: Path | None,
- version: str, identity: dict) -> dict:
- receipt_path = Path(receipt_path).resolve()
- receipt = json.loads(receipt_path.read_text(encoding="utf-8"))
- if (receipt.get("profile") != product or receipt.get("status") != "PASS"
- or receipt.get("production") is not True or receipt.get("simulation_only") is not False
- or not receipt.get("timing_pass_25mhz")
- or receipt.get("warning_audit", {}).get("status") != "PASS"):
- raise ValueError(f"{product}: requires a passing production TD receipt with timing/warning audit")
- if receipt.get("release_version") not in (None, version):
- raise ValueError(f"{product}: TD release_version differs from VERSION")
- inputs = receipt.get("inputs", {})
- if not inputs or any(sha256_file(ROOT / name) != digest for name, digest in inputs.items()):
- raise ValueError(f"{product}: current source does not match TD input hashes")
- manifest_sha = hashlib.sha256(json.dumps(inputs, sort_keys=True, separators=(",", ":")).encode()).hexdigest()
- if receipt.get("source_manifest_sha256") != manifest_sha:
- raise ValueError(f"{product}: TD input manifest hash mismatch")
- for key in ("commit", "tree"):
- if not re.fullmatch(r"[0-9a-f]{40}", str(receipt.get(key, ""))):
- raise ValueError(f"{product}: missing TD {key}")
- if not receipt.get("bitstream"):
- raise ValueError(f"{product}: receipt has no bitstream path")
- bitstream = Path(receipt["bitstream"])
- if not bitstream.is_absolute():
- bitstream = (run_root or receipt_path.parent) / bitstream
- bitstream = bitstream.resolve()
- if sha256_file(bitstream) != receipt.get("bitstream_sha256"):
- raise ValueError(f"{product}: bitstream hash differs from TD receipt")
- build_parameters = receipt.get("build_parameters", {})
- host_baud = build_parameters.get("host_baud")
- if host_baud not in (921600, 460800, 230400, 115200):
- raise ValueError(f"{product}: TD receipt must identify the actual host_baud")
- cfg = PRODUCTS[product]
- contract_path = ROOT / "generated" / cfg["generated"] / "contract-sha256.txt"
- contract_sha = contract_path.read_text().strip()
- if not re.fullmatch(r"[0-9a-f]{64}", contract_sha):
- raise ValueError(f"{product}: generated contract identity is invalid")
- metadata = {
- "product": product, "profile": product, "board": cfg["board"], "release_version": version,
- "commit": identity["commit"], "source_tree": identity["tree"],
- "source_clean": identity.get("clean"), "source_kind": identity["source_kind"],
- "contract_sha256": contract_sha,
- "bitstream_sha256": receipt["bitstream_sha256"],
- "bitstream_source_commit": receipt["commit"], "bitstream_source_tree": receipt["tree"],
- "source_manifest_sha256": manifest_sha, "td_receipt_sha256": sha256_file(receipt_path),
- "td_run_id": receipt.get("run_id"), "host_baud": host_baud, "bmc_baud": 115200,
- "hardware_validation": "NOT_RUN_BY_GUI_BUILD",
- }
- return {**cfg, "metadata": metadata, "receipt_path": str(receipt_path),
- "bitstream": str(bitstream), "run_root": str(run_root or receipt_path.parent)}
- # The Windows runner uses its local interpreter and writes results even on failure.
- NATIVE_RUNNER = r'''
- import hashlib, json, os, subprocess, sys, traceback
- from pathlib import Path
- HERE = Path(__file__).resolve().parent
- ROOT = HERE / "src"
- plan = json.loads((HERE / "build-plan.json").read_text(encoding="utf-8"))
- summary = {"schema": "prod2u-native-windows-gui-v2", "run_id": plan["run_id"],
- "release_version": plan["release_version"], "source_files_sha256": plan["source_files_sha256"],
- "python": sys.version, "platform": sys.platform, "products": {},
- "visual_gui_validation": "NOT_RUN", "hardware_validation": "NOT_RUN"}
- (HERE / "artifacts").mkdir(exist_ok=True)
- for product, cfg in plan["products"].items():
- artifact = HERE / "artifacts" / product
- artifact.mkdir(exist_ok=True)
- result = {"status": "FAIL", "metadata": cfg["metadata"]}
- summary["products"][product] = result
- try:
- for source, digest in plan["source_files_sha256"].items():
- if hashlib.sha256((ROOT / source).read_bytes()).hexdigest() != digest:
- raise ValueError("transferred source hash mismatch: " + source)
- work = HERE / "work" / product
- work.mkdir(parents=True)
- meta_path = artifact / "gui-build-metadata.json"
- meta_path.write_text(json.dumps(cfg["metadata"], indent=2) + "\n", encoding="utf-8")
- name = cfg["exe_name"] + "-v" + plan["release_version"]
- version_parts = tuple(int(v) for v in plan["release_version"].split(".")) + (0,)
- if len(version_parts) != 4:
- raise ValueError("release version must be major.minor.patch")
- version_file = work / "version_info.txt"
- version_file.write_text(
- "VSVersionInfo(ffi=FixedFileInfo(filevers=" + repr(version_parts) +
- ", prodvers=" + repr(version_parts) +
- ", mask=0x3f, flags=0, OS=0x40004, fileType=1, subtype=0, date=(0,0)), "
- "kids=[StringFileInfo([StringTable('040904B0', [" +
- ",".join("StringStruct(" + repr(k) + "," + repr(v) + ")" for k, v in {
- "CompanyName": "Prod2U", "ProductName": cfg["board"],
- "FileDescription": cfg["board"] + " control software",
- "FileVersion": ".".join(map(str, version_parts)),
- "ProductVersion": plan["release_version"],
- "OriginalFilename": name + ".exe",
- }.items()) + "])]), VarFileInfo([VarStruct('Translation', [1033,1200])])])",
- encoding="utf-8")
- command = [sys.executable, "-m", "PyInstaller", "--noconfirm", "--clean", "--onefile", "--windowed",
- "--name", name, "--version-file", str(version_file), "--distpath", str(artifact), "--workpath", str(work / "build"),
- "--specpath", str(work), "--paths", str(ROOT), "--paths", str(ROOT / "tools"),
- "--paths", str(ROOT / "tools/_vendor"), "--hidden-import", "hth_protocol",
- "--hidden-import", "prod2u_status", "--hidden-import", "stream_receiver",
- "--hidden-import", "serial", "--hidden-import", "serial.tools.list_ports",
- "--add-data", str(meta_path) + ";.", "--add-data", str(ROOT / "VERSION") + ";."]
- for source, destination in cfg["assets"]:
- command += ["--add-data", str(ROOT / source) + ";" + destination]
- command.append(str(ROOT / cfg["script"]))
- # An EXE without pyserial cannot fulfil the connected GUI's purpose.
- with (artifact / "build.log").open("w", encoding="utf-8") as log:
- preflight = subprocess.run([sys.executable, "-c", "import tkinter, serial, PyInstaller"],
- stdout=log, stderr=subprocess.STDOUT, timeout=60)
- result["dependency_exit"] = preflight.returncode
- if preflight.returncode:
- raise RuntimeError("native GUI dependencies missing; see build.log")
- run = subprocess.run(command, cwd=ROOT, stdout=log, stderr=subprocess.STDOUT, timeout=1200)
- result["build_exit"] = run.returncode
- if run.returncode:
- raise RuntimeError("PyInstaller failed; see build.log")
- exe = artifact / (name + ".exe")
- import pefile
- pe = pefile.PE(str(exe))
- vi = pe.VS_FIXEDFILEINFO[0]
- actual_version = (vi.FileVersionMS >> 16, vi.FileVersionMS & 65535,
- vi.FileVersionLS >> 16, vi.FileVersionLS & 65535)
- pe.close()
- if actual_version != version_parts:
- raise ValueError("Windows FileVersion does not match release")
- result["windows_file_version"] = ".".join(map(str, actual_version))
- with (artifact / "self-test.log").open("w", encoding="utf-8") as log:
- test = subprocess.run([str(exe), "--self-test", "--self-test-report", str(artifact / "self-test.json")],
- stdout=log, stderr=subprocess.STDOUT, timeout=60)
- result["self_test_exit"] = test.returncode
- if test.returncode:
- raise RuntimeError("native EXE self-test failed; see self-test.log")
- self_test = json.loads((artifact / "self-test.json").read_text(encoding="utf-8"))
- if self_test.get("status") != "PASS" or self_test.get("product") != product:
- raise RuntimeError("native EXE self-test report missing or for wrong product")
- result.update(status="PASS", exe="artifacts/" + product + "/" + exe.name,
- size=exe.stat().st_size, sha256=hashlib.sha256(exe.read_bytes()).hexdigest(),
- self_test=self_test)
- except Exception as exc:
- result["error"] = str(exc)
- (artifact / "failure.log").write_text(traceback.format_exc(), encoding="utf-8")
- finally:
- (artifact / "RESULT.json").write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8")
- (HERE / "BUILD-SUMMARY.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
- print(product + ": " + result["status"], flush=True)
- sys.exit(0 if all(r["status"] == "PASS" for r in summary["products"].values()) else 1)
- '''
- def powershell_command(script: str) -> str:
- return "powershell -NoProfile -NonInteractive -EncodedCommand " + base64.b64encode(script.encode("utf-16le")).decode()
- def ps_quote(text: str) -> str:
- return "'" + text.replace("'", "''") + "'"
- def prepare_product_blocked_td(product: str, blocker_path: Path, version: str, identity: dict, host_baud: int = 921600) -> dict:
- """Prepare native Windows GUI build when TD bitgen is honestly blocked (e.g. expired license)."""
- blocker_path = Path(blocker_path).resolve()
- blocker = json.loads(blocker_path.read_text(encoding="utf-8"))
- status = str(blocker.get("status", ""))
- if not status.startswith("BLOCKED_"):
- raise ValueError(f"{product}: blocker receipt status must start with BLOCKED_, got {status!r}")
- cfg = PRODUCTS[product]
- contract_path = ROOT / "generated" / cfg["generated"] / "contract-sha256.txt"
- contract_sha = contract_path.read_text().strip()
- if not re.fullmatch(r"[0-9a-f]{64}", contract_sha):
- raise ValueError(f"{product}: generated contract identity is invalid")
- metadata = {
- "product": product, "profile": product, "board": cfg["board"], "release_version": version,
- "commit": identity["commit"], "source_tree": identity["tree"],
- "source_clean": identity.get("clean"), "source_kind": identity["source_kind"],
- "contract_sha256": contract_sha,
- "bitstream_status": status,
- "bitstream_sha256": None,
- "td_blocker_receipt_sha256": sha256_file(blocker_path),
- "td_blocker_error": blocker.get("error_code"),
- "host_baud": int(host_baud), "bmc_baud": 115200,
- "hardware_validation": "NOT_RUN_BY_GUI_BUILD",
- }
- return {**cfg, "metadata": metadata, "receipt_path": str(blocker_path),
- "bitstream": None, "run_root": str(blocker_path.parent)}
- def main(argv=None) -> int:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--product", choices=tuple(PRODUCTS), nargs="+", required=True)
- parser.add_argument("--td-receipt", action="append", default=[], metavar="PRODUCT=PATH")
- parser.add_argument("--run-root", action="append", default=[], metavar="PRODUCT=PATH")
- parser.add_argument("--td-blocker-receipt", type=Path, default=None,
- help="Explicit TD blocker receipt JSON (status BLOCKED_*) when no .bit exists")
- parser.add_argument("--host-baud", type=int, default=921600, choices=(921600, 460800, 230400, 115200))
- parser.add_argument("--output-dir", type=Path, required=True)
- parser.add_argument("--host", default="administrator@192.168.2.24")
- parser.add_argument("--windows-build-root", default="C:/Users/Administrator/prod2u-builds")
- parser.add_argument("--windows-python", default="python")
- parser.add_argument("--prepare-only", action="store_true", help="prepare sources/plan without connecting to Windows")
- args = parser.parse_args(argv)
- receipts, roots = assignments(args.td_receipt), assignments(args.run_root)
- version = (ROOT / "VERSION").read_text().strip()
- if not re.fullmatch(r"\d+\.\d+\.\d+(?:[-+][A-Za-z0-9.-]+)?", version):
- raise ValueError("VERSION must contain a readable semantic version")
- identity = source_identity(ROOT)
- products = {}
- for product in dict.fromkeys(args.product):
- if args.td_blocker_receipt is not None:
- products[product] = prepare_product_blocked_td(product, args.td_blocker_receipt, version, identity, args.host_baud)
- continue
- receipt = receipts.get(product)
- if receipt is None and product in roots:
- receipt = roots[product] / "td-receipt.json"
- if receipt is None:
- parser.error("missing --td-receipt or --run-root for " + product)
- products[product] = prepare_product(product, receipt, roots.get(product), version, identity)
- run_id = "windows-gui-" + datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-" + uuid.uuid4().hex[:8]
- local = args.output_dir.resolve() / run_id
- local.mkdir(parents=True, exist_ok=False)
- remote = args.windows_build_root.rstrip("/") + "/" + run_id
- files = {"VERSION", "tools/prod2u_gui.py", "tools/stream_receiver.py",
- "tools/_vendor/hth_protocol.py", "tools/_vendor/prod2u_status.py"}
- for cfg in products.values():
- files.add(cfg["script"])
- files.update(source for source, _ in cfg["assets"])
- plan = {"schema": "prod2u-native-windows-build-plan-v2", "run_id": run_id,
- "release_version": version, "windows_build_dir": remote, "products": products,
- "source_files_sha256": {name: sha256_file(ROOT / name) for name in sorted(files)}}
- (local / "build-plan.json").write_text(json.dumps(plan, indent=2) + "\n", encoding="utf-8")
- (local / "run_build.py").write_text(NATIVE_RUNNER, encoding="utf-8")
- with tarfile.open(local / "build_src.tar", "w") as archive:
- for name in sorted(files):
- archive.add(ROOT / name, arcname=name, recursive=False)
- if args.prepare_only:
- print(str(local))
- return 0
- def command(arguments, log_name, check=True):
- with (local / log_name).open("a", encoding="utf-8") as log:
- result = subprocess.run(arguments, stdout=log, stderr=subprocess.STDOUT)
- if check and result.returncode:
- raise RuntimeError(f"command failed ({result.returncode}); see {local / log_name}")
- return result.returncode
- def remote_ps(script, log_name, check=True):
- return command(["ssh", "-o", "ConnectTimeout=10", args.host, powershell_command(script)], log_name, check)
- remote_ps("$ErrorActionPreference='Stop'; $p=" + ps_quote(remote)
- + "; if (Test-Path $p) {throw 'run directory exists'}; New-Item -ItemType Directory -Path ($p+'/src') | Out-Null",
- "transfer.log")
- for name in ("build_src.tar", "build-plan.json", "run_build.py"):
- command(["scp", str(local / name), args.host + ":" + remote + "/" + name], "transfer.log")
- remote_ps("tar -xf " + ps_quote(remote + "/build_src.tar") + " -C " + ps_quote(remote + "/src")
- + "; exit $LASTEXITCODE", "transfer.log")
- build_exit = remote_ps("& " + ps_quote(args.windows_python) + " " + ps_quote(remote + "/run_build.py")
- + "; exit $LASTEXITCODE", "native-run.log", check=False)
- # Preserve failed native evidence too; no shared directory or previous run is deleted.
- remote_ps("Set-Location " + ps_quote(remote)
- + "; tar -cf native-results.tar artifacts BUILD-SUMMARY.json build-plan.json; exit $LASTEXITCODE",
- "transfer.log")
- command(["scp", args.host + ":" + remote + "/native-results.tar", str(local / "native-results.tar")], "transfer.log")
- with tarfile.open(local / "native-results.tar") as archive:
- archive.extractall(local, filter="data")
- summary = json.loads((local / "BUILD-SUMMARY.json").read_text(encoding="utf-8"))
- if set(summary.get("products", {})) != set(products):
- raise ValueError("native summary product set differs from the build plan")
- for product, result in summary["products"].items():
- if result.get("metadata") != products[product]["metadata"]:
- raise ValueError("native summary metadata differs from the build plan: " + product)
- if result.get("status") == "PASS":
- if sha256_file(local / result["exe"]) != result["sha256"]:
- raise ValueError("download hash mismatch: " + product)
- (local / "DOWNLOAD-VERIFICATION.json").write_text(json.dumps({
- "run_id": run_id, "native_build_exit": build_exit, "download_hashes": "PASS",
- "native_summary_sha256": sha256_file(local / "BUILD-SUMMARY.json"),
- "windows_build_dir": remote, "local_dir": str(local),
- }, indent=2) + "\n", encoding="utf-8")
- print(str(local / "BUILD-SUMMARY.json"))
- return 0 if build_exit == 0 and all(r["status"] == "PASS" for r in summary["products"].values()) else 1
- if __name__ == "__main__":
- raise SystemExit(main())
|