build_amd64_release.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. #!/usr/bin/env python3
  2. """Build the self-contained hth Linux amd64 release archive."""
  3. from __future__ import annotations
  4. import argparse
  5. import gzip
  6. import hashlib
  7. import json
  8. import os
  9. import shutil
  10. import subprocess
  11. import sys
  12. import tarfile
  13. import tempfile
  14. from datetime import datetime, timezone
  15. from pathlib import Path
  16. BINARIES = ("hthd", "hthctl", "hth-capture")
  17. EXECUTABLES = {
  18. "install.sh",
  19. "uninstall.sh",
  20. "verify-install.sh",
  21. "selftest.sh",
  22. *BINARIES,
  23. }
  24. PREVIOUS_RELEASE = {
  25. "tag": "v0.1.1",
  26. "commit": "7128a205a5cf70256bf6bb3cc87068b1d03e7fd4",
  27. "service": "hthd.service",
  28. "binaries": [
  29. "/usr/local/bin/hthd",
  30. "/usr/local/bin/hthctl",
  31. "/usr/local/bin/hth-capture",
  32. ],
  33. "config": "/etc/hth/hthd.yaml",
  34. "runtime": "/run/hth",
  35. "state": "/var/lib/hth",
  36. }
  37. def sha256(path: Path) -> str:
  38. digest = hashlib.sha256()
  39. with path.open("rb") as stream:
  40. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  41. digest.update(chunk)
  42. return digest.hexdigest()
  43. def git(repo: Path, *args: str) -> str:
  44. return subprocess.check_output(
  45. ["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL
  46. ).strip()
  47. def cpld_provenance(host_root: Path) -> dict[str, object]:
  48. import_path = host_root / "generated" / "6400" / "import-source.json"
  49. imported = json.loads(import_path.read_text(encoding="utf-8"))
  50. if imported.get("schema") != "hth-cpld-contract-import-v2":
  51. raise RuntimeError("6400 CPLD import provenance must use v2 source/package binding")
  52. required = (
  53. "source_commit",
  54. "package_commit",
  55. "contract_sha256",
  56. "source_contract_file_sha256",
  57. "source_input_bundle_sha256",
  58. )
  59. missing = [name for name in required if not imported.get(name)]
  60. if missing:
  61. raise RuntimeError("6400 CPLD import provenance missing: " + ", ".join(missing))
  62. contract = host_root / "contracts" / "6400" / "host-contract.json"
  63. contract_data = json.loads(contract.read_text(encoding="utf-8"))
  64. if sha256(contract) != imported["source_contract_file_sha256"]:
  65. raise RuntimeError("HTH contract file does not match imported CPLD contract SHA-256")
  66. if contract_data.get("contract_sha256") != imported["contract_sha256"]:
  67. raise RuntimeError("HTH contract ID does not match imported CPLD contract ID")
  68. return {
  69. "functional_source_commit": imported["source_commit"],
  70. "package_commit": imported["package_commit"],
  71. "contract_id_sha256": imported["contract_sha256"],
  72. "contract_file_sha256": imported["source_contract_file_sha256"],
  73. "source_input_bundle_sha256": imported["source_input_bundle_sha256"],
  74. "td_bitstream_source_commit": imported["source_commit"],
  75. "td_bitstream_rebuilt_from_package_commit": (
  76. imported["source_commit"] == imported["package_commit"]
  77. ),
  78. "firmware_artifact_included": False,
  79. }
  80. def copy_file(source: Path, target: Path, mode: int = 0o644) -> None:
  81. if not source.is_file():
  82. raise FileNotFoundError(source)
  83. target.parent.mkdir(parents=True, exist_ok=True)
  84. if source.suffix == ".sh":
  85. # A Windows checkout may contain CRLF. Release scripts must keep a
  86. # Linux shebang and LF line endings after extraction.
  87. target.write_bytes(source.read_bytes().replace(b"\r\n", b"\n"))
  88. else:
  89. shutil.copyfile(source, target)
  90. target.chmod(mode)
  91. def build_binaries(host_root: Path, binary_dir: Path, version: str) -> None:
  92. binary_dir.mkdir(parents=True, exist_ok=True)
  93. env = os.environ.copy()
  94. env.update({"GOOS": "linux", "GOARCH": "amd64", "CGO_ENABLED": "0"})
  95. for name in BINARIES:
  96. subprocess.run(
  97. [
  98. "go",
  99. "build",
  100. "-trimpath",
  101. "-ldflags",
  102. "-s -w -X hth/internal/app.APIVersion=hth.api.v1",
  103. "-o",
  104. str(binary_dir / name),
  105. f"./cmd/{name}",
  106. ],
  107. cwd=host_root,
  108. env=env,
  109. check=True,
  110. )
  111. def build_sdk_wheel(host_root: Path, output_dir: Path) -> Path:
  112. output_dir.mkdir(parents=True, exist_ok=True)
  113. subprocess.run(
  114. [
  115. sys.executable,
  116. "-m",
  117. "build",
  118. "--wheel",
  119. "--no-isolation",
  120. "--outdir",
  121. str(output_dir),
  122. ],
  123. cwd=host_root / "sdk" / "python",
  124. check=True,
  125. )
  126. wheels = sorted(output_dir.glob("hth_sdk-*.whl"))
  127. if len(wheels) != 1:
  128. raise RuntimeError(f"expected one hth-sdk wheel, found {wheels}")
  129. return wheels[0]
  130. def write_inner_sums(stage: Path) -> None:
  131. names = sorted(
  132. path.relative_to(stage).as_posix()
  133. for path in stage.rglob("*")
  134. if path.is_file() and path.name != "SHA256SUMS"
  135. )
  136. lines = [f"{sha256(stage / name)} {name}" for name in names]
  137. # Write bytes so a Windows build host cannot turn Linux checksum records
  138. # into CRLF and make sha256sum parse the filename incorrectly.
  139. (stage / "SHA256SUMS").write_bytes(("\n".join(lines) + "\n").encode("ascii"))
  140. def add_tree(tar: tarfile.TarFile, stage: Path, top: str) -> None:
  141. for path in sorted(stage.rglob("*"), key=lambda item: item.relative_to(stage).as_posix()):
  142. rel = path.relative_to(stage).as_posix()
  143. info = tar.gettarinfo(str(path), arcname=f"{top}/{rel}")
  144. info.uid = info.gid = 0
  145. info.uname = info.gname = "root"
  146. info.mtime = 0
  147. if path.name in EXECUTABLES:
  148. info.mode = 0o755
  149. elif path.is_file():
  150. info.mode = 0o644
  151. if path.is_file():
  152. with path.open("rb") as stream:
  153. tar.addfile(info, stream)
  154. else:
  155. tar.addfile(info)
  156. def create_archive(stage: Path, archive: Path, top: str) -> None:
  157. archive.parent.mkdir(parents=True, exist_ok=True)
  158. with archive.open("wb") as raw:
  159. with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as zipped:
  160. with tarfile.open(fileobj=zipped, mode="w") as tar:
  161. add_tree(tar, stage, top)
  162. def main() -> int:
  163. parser = argparse.ArgumentParser()
  164. parser.add_argument("--version", required=True, help="Release version, for example v0.1.0")
  165. parser.add_argument("--output-dir", type=Path, required=True)
  166. parser.add_argument("--binary-dir", type=Path, help="Use prebuilt Linux amd64 binaries")
  167. parser.add_argument("--sdk-wheel", type=Path, help="Use a prebuilt hth-sdk wheel")
  168. parser.add_argument("--source-commit", help="Override commit only for detached release staging")
  169. args = parser.parse_args()
  170. host_root = Path(__file__).resolve().parents[1]
  171. version = args.version
  172. if not version.startswith("v") or any(ch.isspace() for ch in version):
  173. parser.error("--version must start with v and contain no whitespace")
  174. source_commit = args.source_commit or git(host_root, "rev-parse", "HEAD")
  175. contract = host_root / "contracts" / "6400" / "host-contract.json"
  176. profile = host_root / "profiles" / "6400-control" / "profile.json"
  177. cpld_import = host_root / "generated" / "6400" / "import-source.json"
  178. release_src = host_root / "deploy" / "amd64-release"
  179. imported_cpld = cpld_provenance(host_root)
  180. with tempfile.TemporaryDirectory(prefix="hth-amd64-release-") as temp:
  181. temp_root = Path(temp)
  182. stage = temp_root / "stage"
  183. binaries = args.binary_dir.resolve() if args.binary_dir else temp_root / "bin"
  184. sdk_wheel = (
  185. args.sdk_wheel.resolve()
  186. if args.sdk_wheel
  187. else build_sdk_wheel(host_root, temp_root / "wheel")
  188. )
  189. if args.binary_dir is None:
  190. build_binaries(host_root, binaries, version)
  191. for name in BINARIES:
  192. copy_file(binaries / name, stage / "bin" / name, 0o755)
  193. for name in ("install.sh", "uninstall.sh", "verify-install.sh", "selftest.sh"):
  194. copy_file(release_src / name, stage / name, 0o755)
  195. copy_file(release_src / "README.md", stage / "README.md")
  196. copy_file(release_src / "README.zh-CN.md", stage / "README.zh-CN.md")
  197. copy_file(profile, stage / "profiles" / "6400-control" / "profile.json")
  198. copy_file(contract, stage / "contracts" / "host-contract.json")
  199. copy_file(cpld_import, stage / "contracts" / "cpld-import-source.json")
  200. copy_file(sdk_wheel, stage / "sdk" / sdk_wheel.name)
  201. copy_file(
  202. release_src / "config" / "hthd.6400-mock.yaml",
  203. stage / "config" / "hthd.6400-mock.yaml",
  204. )
  205. copy_file(
  206. release_src / "config" / "hthd.6400-serial.yaml",
  207. stage / "config" / "hthd.6400-serial.yaml",
  208. )
  209. copy_file(host_root / "deploy" / "systemd" / "hthd.service", stage / "service" / "hthd.service")
  210. copy_file(host_root / "deploy" / "sysusers.d" / "hth.conf", stage / "service" / "hth.conf")
  211. copy_file(host_root / "deploy" / "tmpfiles" / "hth.conf", stage / "service" / "hthd-tmpfiles.conf")
  212. copy_file(
  213. host_root / "deploy" / "udev" / "99-hth-controller.rules.template",
  214. stage / "service" / "99-hth-controller.rules.template",
  215. )
  216. (stage / "PREVIOUS-RELEASE.json").write_text(
  217. json.dumps(PREVIOUS_RELEASE, indent=2, sort_keys=True) + "\n",
  218. encoding="utf-8",
  219. )
  220. metadata = {
  221. "schema": "hth-linux-amd64-release-v2",
  222. "version": version,
  223. "target": {"os": "linux", "arch": "amd64", "machine": "x86_64"},
  224. "source_commit": source_commit,
  225. "contract_sha256": sha256(contract),
  226. "production_profile_sha256": sha256(profile),
  227. "api_version": "hth.api.v1",
  228. "profile_id": "6400-control",
  229. "cpld_provenance": imported_cpld,
  230. "service_name": "hthd.service",
  231. "previous_release": PREVIOUS_RELEASE,
  232. "hardware_validation": "NOT RUN",
  233. "com_validation": "NOT RUN",
  234. "jtag_validation": "NOT RUN",
  235. "real_thermal_performance": "NOT RUN",
  236. "built_at_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
  237. "binaries": {name: sha256(stage / "bin" / name) for name in BINARIES},
  238. "python_sdk": {"wheel": sdk_wheel.name, "sha256": sha256(sdk_wheel)},
  239. }
  240. (stage / "RELEASE-METADATA.json").write_text(
  241. json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
  242. )
  243. write_inner_sums(stage)
  244. top = f"hth-linux-amd64-{version}"
  245. archive = args.output_dir.resolve() / f"{top}.tar.gz"
  246. create_archive(stage, archive, top)
  247. digest = sha256(archive)
  248. outer_sum = archive.with_suffix(archive.suffix + ".sha256")
  249. outer_sum.write_bytes(f"{digest} {archive.name}\n".encode("ascii"))
  250. print(f"archive={archive}")
  251. print(f"sha256={digest}")
  252. print(f"source_commit={source_commit}")
  253. return 0
  254. if __name__ == "__main__":
  255. raise SystemExit(main())