build_amd64_release.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 tarfile
  12. import tempfile
  13. from datetime import datetime, timezone
  14. from pathlib import Path
  15. BINARIES = ("hthd", "hthctl", "hth-capture")
  16. EXECUTABLES = {"install.sh", "uninstall.sh", "selftest.sh", *BINARIES}
  17. def sha256(path: Path) -> str:
  18. digest = hashlib.sha256()
  19. with path.open("rb") as stream:
  20. for chunk in iter(lambda: stream.read(1024 * 1024), b""):
  21. digest.update(chunk)
  22. return digest.hexdigest()
  23. def git(repo: Path, *args: str) -> str:
  24. return subprocess.check_output(
  25. ["git", *args], cwd=repo, text=True, stderr=subprocess.DEVNULL
  26. ).strip()
  27. def copy_file(source: Path, target: Path, mode: int = 0o644) -> None:
  28. if not source.is_file():
  29. raise FileNotFoundError(source)
  30. target.parent.mkdir(parents=True, exist_ok=True)
  31. if source.suffix == ".sh":
  32. # A Windows checkout may contain CRLF. Release scripts must keep a
  33. # Linux shebang and LF line endings after extraction.
  34. target.write_bytes(source.read_bytes().replace(b"\r\n", b"\n"))
  35. else:
  36. shutil.copyfile(source, target)
  37. target.chmod(mode)
  38. def build_binaries(host_root: Path, binary_dir: Path, version: str) -> None:
  39. binary_dir.mkdir(parents=True, exist_ok=True)
  40. env = os.environ.copy()
  41. env.update({"GOOS": "linux", "GOARCH": "amd64", "CGO_ENABLED": "0"})
  42. for name in BINARIES:
  43. subprocess.run(
  44. [
  45. "go",
  46. "build",
  47. "-trimpath",
  48. "-ldflags",
  49. "-s -w -X hth/internal/app.APIVersion=hth.api.v1",
  50. "-o",
  51. str(binary_dir / name),
  52. f"./cmd/{name}",
  53. ],
  54. cwd=host_root,
  55. env=env,
  56. check=True,
  57. )
  58. def write_inner_sums(stage: Path) -> None:
  59. names = sorted(
  60. path.relative_to(stage).as_posix()
  61. for path in stage.rglob("*")
  62. if path.is_file() and path.name != "SHA256SUMS"
  63. )
  64. lines = [f"{sha256(stage / name)} {name}" for name in names]
  65. # Write bytes so a Windows build host cannot turn Linux checksum records
  66. # into CRLF and make sha256sum parse the filename incorrectly.
  67. (stage / "SHA256SUMS").write_bytes(("\n".join(lines) + "\n").encode("ascii"))
  68. def add_tree(tar: tarfile.TarFile, stage: Path, top: str) -> None:
  69. for path in sorted(stage.rglob("*"), key=lambda item: item.relative_to(stage).as_posix()):
  70. rel = path.relative_to(stage).as_posix()
  71. info = tar.gettarinfo(str(path), arcname=f"{top}/{rel}")
  72. info.uid = info.gid = 0
  73. info.uname = info.gname = "root"
  74. info.mtime = 0
  75. if path.name in EXECUTABLES:
  76. info.mode = 0o755
  77. elif path.is_file():
  78. info.mode = 0o644
  79. if path.is_file():
  80. with path.open("rb") as stream:
  81. tar.addfile(info, stream)
  82. else:
  83. tar.addfile(info)
  84. def create_archive(stage: Path, archive: Path, top: str) -> None:
  85. archive.parent.mkdir(parents=True, exist_ok=True)
  86. with archive.open("wb") as raw:
  87. with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as zipped:
  88. with tarfile.open(fileobj=zipped, mode="w") as tar:
  89. add_tree(tar, stage, top)
  90. def main() -> int:
  91. parser = argparse.ArgumentParser()
  92. parser.add_argument("--version", required=True, help="Release version, for example v0.1.0")
  93. parser.add_argument("--output-dir", type=Path, required=True)
  94. parser.add_argument("--binary-dir", type=Path, help="Use prebuilt Linux amd64 binaries")
  95. parser.add_argument("--source-commit", help="Override commit only for detached release staging")
  96. args = parser.parse_args()
  97. host_root = Path(__file__).resolve().parents[1]
  98. repo_root = host_root.parent
  99. version = args.version
  100. if not version.startswith("v") or any(ch.isspace() for ch in version):
  101. parser.error("--version must start with v and contain no whitespace")
  102. source_commit = args.source_commit or git(repo_root, "rev-parse", "HEAD")
  103. project = repo_root / "projects" / "prod2u-door-temp" / "project.json"
  104. profile = host_root / "profiles" / "prod2u-door-temp" / "profile.json"
  105. release_src = host_root / "deploy" / "amd64-release"
  106. with tempfile.TemporaryDirectory(prefix="hth-amd64-release-") as temp:
  107. temp_root = Path(temp)
  108. stage = temp_root / "stage"
  109. binaries = args.binary_dir.resolve() if args.binary_dir else temp_root / "bin"
  110. if args.binary_dir is None:
  111. build_binaries(host_root, binaries, version)
  112. for name in BINARIES:
  113. copy_file(binaries / name, stage / "bin" / name, 0o755)
  114. for name in ("install.sh", "uninstall.sh", "selftest.sh"):
  115. copy_file(release_src / name, stage / name, 0o755)
  116. copy_file(release_src / "README.md", stage / "README.md")
  117. copy_file(release_src / "README.zh-CN.md", stage / "README.zh-CN.md")
  118. copy_file(profile, stage / "profile.json")
  119. copy_file(release_src / "config" / "hthd.mock.yaml", stage / "config" / "hthd.mock.yaml")
  120. copy_file(release_src / "config" / "hthd.serial.yaml", stage / "config" / "hthd.serial.yaml")
  121. copy_file(host_root / "deploy" / "systemd" / "hthd.service", stage / "service" / "hthd.service")
  122. copy_file(host_root / "deploy" / "sysusers.d" / "hth.conf", stage / "service" / "hth.conf")
  123. copy_file(host_root / "deploy" / "tmpfiles" / "hth.conf", stage / "service" / "hthd-tmpfiles.conf")
  124. copy_file(
  125. host_root / "deploy" / "udev" / "99-hth-controller.rules.template",
  126. stage / "service" / "99-hth-controller.rules.template",
  127. )
  128. metadata = {
  129. "schema": "hth-linux-amd64-release-v1",
  130. "version": version,
  131. "target": {"os": "linux", "arch": "amd64", "machine": "x86_64"},
  132. "source_commit": source_commit,
  133. "project_sha256": sha256(project),
  134. "profile_sha256": sha256(profile),
  135. "api_version": "hth.api.v1",
  136. "profile_id": "prod2u-normal-multiproject-115200-v1",
  137. "hardware_validation": "not_run",
  138. "built_at_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
  139. "binaries": {name: sha256(stage / "bin" / name) for name in BINARIES},
  140. }
  141. (stage / "RELEASE-METADATA.json").write_text(
  142. json.dumps(metadata, indent=2, sort_keys=True) + "\n", encoding="utf-8"
  143. )
  144. write_inner_sums(stage)
  145. top = f"hth-linux-amd64-{version}"
  146. archive = args.output_dir.resolve() / f"{top}.tar.gz"
  147. create_archive(stage, archive, top)
  148. digest = sha256(archive)
  149. outer_sum = archive.with_suffix(archive.suffix + ".sha256")
  150. outer_sum.write_bytes(f"{digest} {archive.name}\n".encode("ascii"))
  151. print(f"archive={archive}")
  152. print(f"sha256={digest}")
  153. print(f"source_commit={source_commit}")
  154. return 0
  155. if __name__ == "__main__":
  156. raise SystemExit(main())