| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285 |
- #!/usr/bin/env python3
- """Build the self-contained hth Linux amd64 release archive."""
- from __future__ import annotations
- import argparse
- import gzip
- import hashlib
- import json
- import os
- import shutil
- import subprocess
- import sys
- import tarfile
- import tempfile
- from datetime import datetime, timezone
- from pathlib import Path
- BINARIES = ("hthd", "hthctl", "hth-capture")
- EXECUTABLES = {
- "install.sh",
- "uninstall.sh",
- "verify-install.sh",
- "selftest.sh",
- *BINARIES,
- }
- PREVIOUS_RELEASE = {
- "tag": "v0.1.1",
- "commit": "7128a205a5cf70256bf6bb3cc87068b1d03e7fd4",
- "service": "hthd.service",
- "binaries": [
- "/usr/local/bin/hthd",
- "/usr/local/bin/hthctl",
- "/usr/local/bin/hth-capture",
- ],
- "config": "/etc/hth/hthd.yaml",
- "runtime": "/run/hth",
- "state": "/var/lib/hth",
- }
- def sha256(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as stream:
- for chunk in iter(lambda: stream.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def git(repo: Path, *args: str) -> str:
- return subprocess.check_output(
- ["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL
- ).strip()
- def cpld_provenance(host_root: Path) -> dict[str, object]:
- import_path = host_root / "generated" / "6400" / "import-source.json"
- imported = json.loads(import_path.read_text(encoding="utf-8"))
- if imported.get("schema") != "hth-cpld-contract-import-v2":
- raise RuntimeError("6400 CPLD import provenance must use v2 source/package binding")
- required = (
- "source_commit",
- "package_commit",
- "contract_sha256",
- "source_contract_file_sha256",
- "source_input_bundle_sha256",
- )
- missing = [name for name in required if not imported.get(name)]
- if missing:
- raise RuntimeError("6400 CPLD import provenance missing: " + ", ".join(missing))
- contract = host_root / "contracts" / "6400" / "host-contract.json"
- contract_data = json.loads(contract.read_text(encoding="utf-8"))
- if sha256(contract) != imported["source_contract_file_sha256"]:
- raise RuntimeError("HTH contract file does not match imported CPLD contract SHA-256")
- if contract_data.get("contract_sha256") != imported["contract_sha256"]:
- raise RuntimeError("HTH contract ID does not match imported CPLD contract ID")
- return {
- "functional_source_commit": imported["source_commit"],
- "package_commit": imported["package_commit"],
- "contract_id_sha256": imported["contract_sha256"],
- "contract_file_sha256": imported["source_contract_file_sha256"],
- "source_input_bundle_sha256": imported["source_input_bundle_sha256"],
- "td_bitstream_source_commit": imported["source_commit"],
- "td_bitstream_rebuilt_from_package_commit": (
- imported["source_commit"] == imported["package_commit"]
- ),
- "firmware_artifact_included": False,
- }
- def copy_file(source: Path, target: Path, mode: int = 0o644) -> None:
- if not source.is_file():
- raise FileNotFoundError(source)
- target.parent.mkdir(parents=True, exist_ok=True)
- if source.suffix == ".sh":
- # A Windows checkout may contain CRLF. Release scripts must keep a
- # Linux shebang and LF line endings after extraction.
- target.write_bytes(source.read_bytes().replace(b"\r\n", b"\n"))
- else:
- shutil.copyfile(source, target)
- target.chmod(mode)
- def build_binaries(host_root: Path, binary_dir: Path, version: str) -> None:
- binary_dir.mkdir(parents=True, exist_ok=True)
- env = os.environ.copy()
- env.update({"GOOS": "linux", "GOARCH": "amd64", "CGO_ENABLED": "0"})
- for name in BINARIES:
- subprocess.run(
- [
- "go",
- "build",
- "-trimpath",
- "-ldflags",
- "-s -w -X hth/internal/app.APIVersion=hth.api.v1",
- "-o",
- str(binary_dir / name),
- f"./cmd/{name}",
- ],
- cwd=host_root,
- env=env,
- check=True,
- )
- def build_sdk_wheel(host_root: Path, output_dir: Path) -> Path:
- output_dir.mkdir(parents=True, exist_ok=True)
- subprocess.run(
- [
- sys.executable,
- "-m",
- "build",
- "--wheel",
- "--no-isolation",
- "--outdir",
- str(output_dir),
- ],
- cwd=host_root / "sdk" / "python",
- check=True,
- )
- wheels = sorted(output_dir.glob("hth_sdk-*.whl"))
- if len(wheels) != 1:
- raise RuntimeError(f"expected one hth-sdk wheel, found {wheels}")
- return wheels[0]
- def write_inner_sums(stage: Path) -> None:
- names = sorted(
- path.relative_to(stage).as_posix()
- for path in stage.rglob("*")
- if path.is_file() and path.name != "SHA256SUMS"
- )
- lines = [f"{sha256(stage / name)} {name}" for name in names]
- # Write bytes so a Windows build host cannot turn Linux checksum records
- # into CRLF and make sha256sum parse the filename incorrectly.
- (stage / "SHA256SUMS").write_bytes(("\n".join(lines) + "\n").encode("ascii"))
- def add_tree(tar: tarfile.TarFile, stage: Path, top: str) -> None:
- for path in sorted(stage.rglob("*"), key=lambda item: item.relative_to(stage).as_posix()):
- rel = path.relative_to(stage).as_posix()
- info = tar.gettarinfo(str(path), arcname=f"{top}/{rel}")
- info.uid = info.gid = 0
- info.uname = info.gname = "root"
- info.mtime = 0
- if path.name in EXECUTABLES:
- info.mode = 0o755
- elif path.is_file():
- info.mode = 0o644
- if path.is_file():
- with path.open("rb") as stream:
- tar.addfile(info, stream)
- else:
- tar.addfile(info)
- def create_archive(stage: Path, archive: Path, top: str) -> None:
- archive.parent.mkdir(parents=True, exist_ok=True)
- with archive.open("wb") as raw:
- with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as zipped:
- with tarfile.open(fileobj=zipped, mode="w") as tar:
- add_tree(tar, stage, top)
- def main() -> int:
- parser = argparse.ArgumentParser()
- parser.add_argument("--version", required=True, help="Release version, for example v0.1.0")
- parser.add_argument("--output-dir", type=Path, required=True)
- parser.add_argument("--binary-dir", type=Path, help="Use prebuilt Linux amd64 binaries")
- parser.add_argument("--sdk-wheel", type=Path, help="Use a prebuilt hth-sdk wheel")
- parser.add_argument("--source-commit", help="Override commit only for detached release staging")
- args = parser.parse_args()
- host_root = Path(__file__).resolve().parents[1]
- version = args.version
- if not version.startswith("v") or any(ch.isspace() for ch in version):
- parser.error("--version must start with v and contain no whitespace")
- source_commit = args.source_commit or git(host_root, "rev-parse", "HEAD")
- contract = host_root / "contracts" / "6400" / "host-contract.json"
- profile = host_root / "profiles" / "6400-control" / "profile.json"
- cpld_import = host_root / "generated" / "6400" / "import-source.json"
- release_src = host_root / "deploy" / "amd64-release"
- imported_cpld = cpld_provenance(host_root)
- with tempfile.TemporaryDirectory(prefix="hth-amd64-release-") as temp:
- temp_root = Path(temp)
- stage = temp_root / "stage"
- binaries = args.binary_dir.resolve() if args.binary_dir else temp_root / "bin"
- sdk_wheel = (
- args.sdk_wheel.resolve()
- if args.sdk_wheel
- else build_sdk_wheel(host_root, temp_root / "wheel")
- )
- if args.binary_dir is None:
- build_binaries(host_root, binaries, version)
- for name in BINARIES:
- copy_file(binaries / name, stage / "bin" / name, 0o755)
- for name in ("install.sh", "uninstall.sh", "verify-install.sh", "selftest.sh"):
- copy_file(release_src / name, stage / name, 0o755)
- copy_file(release_src / "README.md", stage / "README.md")
- copy_file(release_src / "README.zh-CN.md", stage / "README.zh-CN.md")
- copy_file(profile, stage / "profiles" / "6400-control" / "profile.json")
- copy_file(contract, stage / "contracts" / "host-contract.json")
- copy_file(cpld_import, stage / "contracts" / "cpld-import-source.json")
- copy_file(sdk_wheel, stage / "sdk" / sdk_wheel.name)
- copy_file(
- release_src / "config" / "hthd.6400-mock.yaml",
- stage / "config" / "hthd.6400-mock.yaml",
- )
- copy_file(
- release_src / "config" / "hthd.6400-serial.yaml",
- stage / "config" / "hthd.6400-serial.yaml",
- )
- copy_file(host_root / "deploy" / "systemd" / "hthd.service", stage / "service" / "hthd.service")
- copy_file(host_root / "deploy" / "sysusers.d" / "hth.conf", stage / "service" / "hth.conf")
- copy_file(host_root / "deploy" / "tmpfiles" / "hth.conf", stage / "service" / "hthd-tmpfiles.conf")
- copy_file(
- host_root / "deploy" / "udev" / "99-hth-controller.rules.template",
- stage / "service" / "99-hth-controller.rules.template",
- )
- (stage / "PREVIOUS-RELEASE.json").write_text(
- json.dumps(PREVIOUS_RELEASE, indent=2, sort_keys=True) + "\n",
- encoding="utf-8",
- )
- metadata = {
- "schema": "hth-linux-amd64-release-v2",
- "version": version,
- "target": {"os": "linux", "arch": "amd64", "machine": "x86_64"},
- "source_commit": source_commit,
- "contract_sha256": sha256(contract),
- "production_profile_sha256": sha256(profile),
- "api_version": "hth.api.v1",
- "profile_id": "6400-control",
- "cpld_provenance": imported_cpld,
- "service_name": "hthd.service",
- "previous_release": PREVIOUS_RELEASE,
- "hardware_validation": "NOT RUN",
- "com_validation": "NOT RUN",
- "jtag_validation": "NOT RUN",
- "real_thermal_performance": "NOT RUN",
- "built_at_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
- "binaries": {name: sha256(stage / "bin" / name) for name in BINARIES},
- "python_sdk": {"wheel": sdk_wheel.name, "sha256": sha256(sdk_wheel)},
- }
- (stage / "RELEASE-METADATA.json").write_text(
- json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
- )
- write_inner_sums(stage)
- top = f"hth-linux-amd64-{version}"
- archive = args.output_dir.resolve() / f"{top}.tar.gz"
- create_archive(stage, archive, top)
- digest = sha256(archive)
- outer_sum = archive.with_suffix(archive.suffix + ".sha256")
- outer_sum.write_bytes(f"{digest} {archive.name}\n".encode("ascii"))
- print(f"archive={archive}")
- print(f"sha256={digest}")
- print(f"source_commit={source_commit}")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|