Browse Source

feat(host): add self-contained amd64 release bundle

root 3 tháng trước cách đây
mục cha
commit
d39954e4c2

+ 4 - 0
README.zh-CN.md

@@ -71,6 +71,10 @@ bash host/tools/run_host_verify.sh full
 
 ## 快速开始(Mock,不碰硬件)
 
+面向 Debian/Ubuntu 类 x86_64 主机的一键发布包说明见
+[`docs/amd64-release.zh-CN.md`](docs/amd64-release.zh-CN.md)。发布包自带静态
+二进制;默认安装 Mock,真实串口必须显式启用。
+
 ```bash
 # 守护进程(Go 侧;后端 mock,不打开串口)
 hthd --backend=mock --config host/deploy/examples/hthd.mock.yaml

+ 54 - 0
deploy/amd64-release/README.md

@@ -0,0 +1,54 @@
+# hth Linux amd64 release
+
+This package targets Debian/Ubuntu-like x86_64 Linux hosts running systemd.
+It contains prebuilt static `hthd`, `hthctl`, and `hth-capture` binaries, the
+Prod2U profile, and service configuration. Go, Python, and protobuf tools are
+not required on the target host.
+
+## Install
+
+```bash
+tar -xzf hth-linux-amd64-vX.Y.Z.tar.gz
+cd hth-linux-amd64-vX.Y.Z
+./selftest.sh
+sudo ./install.sh --backend mock
+```
+
+The default backend is `mock`. For a real controller, configure a stable udev
+symlink first and then install explicitly:
+
+```bash
+sudo ./install.sh --backend serial --serial-path /dev/hth/controller0
+```
+
+The installer refuses to overwrite an existing `/etc/hth/hthd.yaml` unless
+`--force` is supplied. Use `--no-start` to install without starting systemd.
+The serial backend requires the device path to exist and has explicit safety
+targets; it never silently falls back to mock.
+
+## Verify and operate
+
+```bash
+sudo hthd --check-config --config /etc/hth/hthd.yaml
+hthctl devices
+hthctl capabilities
+hthctl snapshot
+sudo systemctl status hthd
+```
+
+The service owns the only serial port. Clients use the Unix sockets under
+`/run/hth`; do not pass `/dev/ttyUSB*` into model containers.
+
+## Uninstall
+
+```bash
+sudo ./uninstall.sh
+sudo ./uninstall.sh --purge   # also remove /etc/hth, /var/lib/hth, /run/hth
+```
+
+Normal uninstall preserves configuration and captured data. Only `--purge`
+removes them.
+
+This package does not validate physical motors, limit switches, temperature
+mapping, or FPGA wiring. Hardware validation remains a separate authorized
+step and is not implied by the mock self-test.

+ 34 - 0
deploy/amd64-release/config/hthd.mock.yaml

@@ -0,0 +1,34 @@
+api_version: hth.api.v1
+device_id: prod2u-0
+display_name: Prod2U mock
+backend: mock
+profile: /etc/hth/profiles/prod2u-door-temp/profile.json
+runtime_root: /run/hth
+sockets:
+  observe: /run/hth/observe/observe.sock
+  control: /run/hth/control/control.sock
+  observe_perm: "0660"
+  control_perm: "0660"
+  observe_group: hth-observe
+  control_group: hth-control
+poll:
+  temperature_ms: 200
+  motor_status_ms: 100
+watchdog:
+  heartbeat_period_ms: 5000
+lease:
+  min_ttl_ms: 1000
+  max_ttl_ms: 30000
+safety:
+  fan: 10
+  ptc: 0
+  door_close_percent: 0
+ring_buffer_size: 1024
+subscriber_buffer_size: 8
+command_cache_size: 256
+grpc:
+  reflection: false
+mock:
+  seed: 1
+  startup_complete: true
+  first_order_thermal: true

+ 32 - 0
deploy/amd64-release/config/hthd.serial.yaml

@@ -0,0 +1,32 @@
+api_version: hth.api.v1
+device_id: prod2u-0
+display_name: Prod2U serial
+backend: serial
+profile: /etc/hth/profiles/prod2u-door-temp/profile.json
+serial:
+  path: @SERIAL_PATH@
+runtime_root: /run/hth
+sockets:
+  observe: /run/hth/observe/observe.sock
+  control: /run/hth/control/control.sock
+  observe_perm: "0660"
+  control_perm: "0660"
+  observe_group: hth-observe
+  control_group: hth-control
+poll:
+  temperature_ms: 5000
+  motor_status_ms: 100
+watchdog:
+  heartbeat_period_ms: 5000
+lease:
+  min_ttl_ms: 1000
+  max_ttl_ms: 30000
+safety:
+  fan: 10
+  ptc: 0
+  door_close_percent: 0
+ring_buffer_size: 1024
+subscriber_buffer_size: 8
+command_cache_size: 256
+grpc:
+  reflection: false

+ 108 - 0
deploy/amd64-release/install.sh

@@ -0,0 +1,108 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+PREFIX="${HTH_PREFIX:-/usr/local}"
+ETCDIR="${HTH_ETC_DIR:-/etc/hth}"
+UNITDIR="${HTH_UNIT_DIR:-/etc/systemd/system}"
+LIBDIR="${HTH_LIB_DIR:-/usr/lib}"
+BACKEND="mock"
+SERIAL_PATH="/dev/hth/controller0"
+NO_START=0
+FORCE=0
+
+usage() {
+  cat >&2 <<'EOF'
+Usage: sudo ./install.sh [--backend mock|serial] [--serial-path PATH]
+                         [--no-start] [--force]
+
+The default backend is mock. Use --backend serial explicitly for a real
+controller. The serial path must exist when installing the serial backend.
+EOF
+}
+
+while [[ $# -gt 0 ]]; do
+  case "$1" in
+    --backend) BACKEND="${2:-}"; shift 2 ;;
+    --serial-path) SERIAL_PATH="${2:-}"; shift 2 ;;
+    --no-start) NO_START=1; shift ;;
+    --force) FORCE=1; shift ;;
+    -h|--help) usage; exit 0 ;;
+    *) echo "install: unknown argument: $1" >&2; usage; exit 2 ;;
+  esac
+done
+
+if [[ "$(uname -m)" != "x86_64" ]]; then
+  echo "install: this release targets x86_64 Linux (found $(uname -m))" >&2
+  exit 2
+fi
+if [[ "$(id -u)" -ne 0 ]]; then
+  echo "install: run as root, for example: sudo ./install.sh --backend mock" >&2
+  exit 2
+fi
+case "$BACKEND" in
+  mock|serial) ;;
+  *) echo "install: --backend must be mock or serial" >&2; exit 2 ;;
+esac
+if [[ "$BACKEND" == serial && ! -e "$SERIAL_PATH" ]]; then
+  echo "install: serial device does not exist: $SERIAL_PATH" >&2
+  exit 2
+fi
+for required in "$ROOT/bin/hthd" "$ROOT/bin/hthctl" "$ROOT/bin/hth-capture" \
+                "$ROOT/profile.json" "$ROOT/config/hthd.mock.yaml" \
+                "$ROOT/config/hthd.serial.yaml" "$ROOT/service/hthd.service" \
+                "$ROOT/service/hth.conf" "$ROOT/service/hthd-tmpfiles.conf"; do
+  [[ -f "$required" ]] || { echo "install: package is incomplete: $required" >&2; exit 1; }
+done
+if [[ -f "$ROOT/SHA256SUMS" ]]; then
+  (cd "$ROOT" && sha256sum -c SHA256SUMS >/dev/null)
+fi
+
+if [[ -e "$ETCDIR/hthd.yaml" && "$FORCE" -ne 1 ]]; then
+  echo "install: refusing to overwrite $ETCDIR/hthd.yaml; use --force after reviewing it" >&2
+  exit 3
+fi
+for command_name in systemctl systemd-sysusers systemd-tmpfiles; do
+  if ! command -v "$command_name" >/dev/null 2>&1; then
+    echo "install: required systemd command is missing: $command_name" >&2
+    exit 1
+  fi
+done
+
+install -d -m 0755 "$PREFIX/bin"
+install -d -m 0755 "$UNITDIR" "$LIBDIR/sysusers.d" "$LIBDIR/tmpfiles.d"
+install -m 0755 "$ROOT/bin/hthd" "$PREFIX/bin/hthd"
+install -m 0755 "$ROOT/bin/hthctl" "$PREFIX/bin/hthctl"
+install -m 0755 "$ROOT/bin/hth-capture" "$PREFIX/bin/hth-capture"
+install -d -m 0750 "$ETCDIR/profiles/prod2u-door-temp"
+install -m 0644 "$ROOT/profile.json" "$ETCDIR/profiles/prod2u-door-temp/profile.json"
+install -m 0644 "$ROOT/service/hthd.service" "$UNITDIR/hthd.service"
+install -m 0644 "$ROOT/service/hth.conf" "$LIBDIR/sysusers.d/hth.conf"
+install -m 0644 "$ROOT/service/hthd-tmpfiles.conf" "$LIBDIR/tmpfiles.d/hth.conf"
+install -d -m 0750 "$ETCDIR"
+
+TEMPLATE="$ROOT/config/hthd.${BACKEND}.yaml"
+TMP_CONFIG="$(mktemp)"
+trap 'rm -f "$TMP_CONFIG"' EXIT
+if [[ "$BACKEND" == serial ]]; then
+  sed "s|@SERIAL_PATH@|${SERIAL_PATH//|/\\|}|g" "$TEMPLATE" > "$TMP_CONFIG"
+else
+  cp "$TEMPLATE" "$TMP_CONFIG"
+fi
+sed -i "s|/etc/hth/profiles/prod2u-door-temp/profile.json|$ETCDIR/profiles/prod2u-door-temp/profile.json|g" "$TMP_CONFIG"
+install -m 0640 "$TMP_CONFIG" "$ETCDIR/hthd.yaml"
+
+systemd-sysusers "$LIBDIR/sysusers.d/hth.conf"
+systemd-tmpfiles --create "$LIBDIR/tmpfiles.d/hth.conf"
+chown root:hth "$ETCDIR" "$ETCDIR/hthd.yaml" "$ETCDIR/profiles" "$ETCDIR/profiles/prod2u-door-temp" 2>/dev/null || true
+chmod 0750 "$ETCDIR" "$ETCDIR/profiles" "$ETCDIR/profiles/prod2u-door-temp"
+chmod 0640 "$ETCDIR/hthd.yaml" "$ETCDIR/profiles/prod2u-door-temp/profile.json"
+
+"$PREFIX/bin/hthd" --check-config --config "$ETCDIR/hthd.yaml"
+systemctl daemon-reload
+if [[ "$NO_START" -eq 0 ]]; then
+  systemctl enable --now hthd.service
+  systemctl --no-pager --full status hthd.service | sed -n '1,12p'
+fi
+echo "hth amd64 release installed: backend=$BACKEND config=$ETCDIR/hthd.yaml"
+echo "uninstall: sudo $ROOT/uninstall.sh   (add --purge to remove config and data)"

+ 28 - 0
deploy/amd64-release/selftest.sh

@@ -0,0 +1,28 @@
+#!/usr/bin/env bash
+set -euo pipefail
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+for name in hthd hthctl hth-capture; do
+  [[ -x "$ROOT/bin/$name" ]] || { echo "selftest: missing executable $name" >&2; exit 1; }
+done
+TMP="$(mktemp -d -t hth-amd64-selftest.XXXXXX)"
+cleanup() { if [[ -n "${PID:-}" ]]; then kill "$PID" 2>/dev/null || true; wait "$PID" 2>/dev/null || true; fi; rm -rf "$TMP"; }
+trap cleanup EXIT
+mkdir -p "$TMP/runtime"
+sed -e "s|/etc/hth/profiles/prod2u-door-temp/profile.json|$ROOT/profile.json|g" \
+    -e "s|/run/hth|$TMP/runtime|g" \
+    -e 's/observe_group: hth-observe/observe_group: ""/' \
+    -e 's/control_group: hth-control/control_group: ""/' \
+    "$ROOT/config/hthd.mock.yaml" > "$TMP/hthd.yaml"
+"$ROOT/bin/hthd" --check-config --config "$TMP/hthd.yaml"
+"$ROOT/bin/hthd" --config "$TMP/hthd.yaml" >"$TMP/hthd.stdout" 2>"$TMP/hthd.stderr" &
+PID=$!
+for _ in $(seq 1 50); do
+  [[ -S "$TMP/runtime/observe/observe.sock" && -S "$TMP/runtime/control/control.sock" ]] && break
+  sleep 0.1
+done
+[[ -S "$TMP/runtime/observe/observe.sock" && -S "$TMP/runtime/control/control.sock" ]] || {
+  cat "$TMP/hthd.stderr" >&2
+  exit 1
+}
+"$ROOT/bin/hthctl" --observe-sock "$TMP/runtime/observe/observe.sock" devices >/dev/null
+echo "HTH_AMD64_SELFTEST_PASS"

+ 30 - 0
deploy/amd64-release/uninstall.sh

@@ -0,0 +1,30 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+PREFIX="${HTH_PREFIX:-/usr/local}"
+ETCDIR="${HTH_ETC_DIR:-/etc/hth}"
+UNITDIR="${HTH_UNIT_DIR:-/etc/systemd/system}"
+LIBDIR="${HTH_LIB_DIR:-/usr/lib}"
+PURGE=0
+if [[ "${1:-}" == --purge ]]; then PURGE=1; fi
+if [[ "${1:-}" != "" && "${1:-}" != --purge ]]; then
+  echo "Usage: sudo ./uninstall.sh [--purge]" >&2
+  exit 2
+fi
+if [[ "$(id -u)" -ne 0 ]]; then
+  echo "uninstall: run as root" >&2
+  exit 2
+fi
+
+if command -v systemctl >/dev/null 2>&1; then
+  systemctl disable --now hthd.service 2>/dev/null || true
+fi
+rm -f "$PREFIX/bin/hthd" "$PREFIX/bin/hthctl" "$PREFIX/bin/hth-capture"
+rm -f "$UNITDIR/hthd.service" "$LIBDIR/sysusers.d/hth.conf" "$LIBDIR/tmpfiles.d/hth.conf"
+if command -v systemctl >/dev/null 2>&1; then
+  systemctl daemon-reload 2>/dev/null || true
+fi
+if [[ "$PURGE" -eq 1 ]]; then
+  rm -rf "$ETCDIR" /var/lib/hth /run/hth
+fi
+echo "hth amd64 release uninstalled (purge=$PURGE; config/data preserved unless purge=1)"

+ 44 - 0
docs/amd64-release.zh-CN.md

@@ -0,0 +1,44 @@
+# Linux amd64 一键部署包
+
+发布资产 `hth-linux-amd64-vX.Y.Z.tar.gz` 面向 Debian/Ubuntu 类、`x86_64`
+且使用 systemd 的 Linux 主机。包内已经包含静态编译的 `hthd`、`hthctl`、
+`hth-capture`,目标机不需要 Go、Python 或 protobuf 工具。
+
+## 安装
+
+```bash
+tar -xzf hth-linux-amd64-vX.Y.Z.tar.gz
+cd hth-linux-amd64-vX.Y.Z
+./selftest.sh
+sudo ./install.sh --backend mock
+```
+
+默认安装 `mock` backend,不会打开串口。现场设备必须显式选择 serial,并
+使用稳定的 udev 名称:
+
+```bash
+sudo ./install.sh --backend serial --serial-path /dev/hth/controller0
+```
+
+安装器会校验包内 `SHA256SUMS`、检查目标架构、生成 hth 用户/组和 systemd
+运行目录、执行 `hthd --check-config`,然后启动服务。已有
+`/etc/hth/hthd.yaml` 时默认拒绝覆盖,确认迁移后才使用 `--force`。
+
+## 验证与卸载
+
+```bash
+hthctl devices
+hthctl capabilities
+hthctl snapshot
+sudo systemctl status hthd
+sudo ./uninstall.sh
+sudo ./uninstall.sh --purge
+```
+
+普通卸载保留 `/etc/hth` 配置和采集数据;只有 `--purge` 会删除这些内容。
+
+模型或数据容器只挂载 `/run/hth/observe/observe.sock`;控制容器另挂
+`control.sock`,不应获得 `/dev/ttyUSB*` 或 `/dev/ttyACM*`。
+
+这个包的自检只覆盖软件、配置、Mock 和 UDS。真实 FPGA、温度传感器、
+电机、限位和板级连线验证仍需独立授权,当前硬件证据为 `NOT RUN`。

+ 174 - 0
tools/build_amd64_release.py

@@ -0,0 +1,174 @@
+#!/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 tarfile
+import tempfile
+from datetime import datetime, timezone
+from pathlib import Path
+
+BINARIES = ("hthd", "hthctl", "hth-capture")
+EXECUTABLES = {"install.sh", "uninstall.sh", "selftest.sh", *BINARIES}
+
+
+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 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)
+    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 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]
+    (stage / "SHA256SUMS").write_text("\n".join(lines) + "\n", encoding="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("--source-commit", help="Override commit only for detached release staging")
+    args = parser.parse_args()
+
+    host_root = Path(__file__).resolve().parents[1]
+    repo_root = host_root.parent
+    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(repo_root, "rev-parse", "HEAD")
+    project = repo_root / "projects" / "prod2u-door-temp" / "project.json"
+    profile = host_root / "profiles" / "prod2u-door-temp" / "profile.json"
+    release_src = host_root / "deploy" / "amd64-release"
+
+    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"
+        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", "selftest.sh"):
+            copy_file(release_src / name, stage / name, 0o755)
+        copy_file(release_src / "README.md", stage / "README.md")
+        copy_file(profile, stage / "profile.json")
+        copy_file(release_src / "config" / "hthd.mock.yaml", stage / "config" / "hthd.mock.yaml")
+        copy_file(release_src / "config" / "hthd.serial.yaml", stage / "config" / "hthd.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",
+        )
+
+        metadata = {
+            "schema": "hth-linux-amd64-release-v1",
+            "version": version,
+            "target": {"os": "linux", "arch": "amd64", "machine": "x86_64"},
+            "source_commit": source_commit,
+            "project_sha256": sha256(project),
+            "profile_sha256": sha256(profile),
+            "api_version": "hth.api.v1",
+            "profile_id": "prod2u-normal-multiproject-115200-v1",
+            "hardware_validation": "not_run",
+            "built_at_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat(),
+            "binaries": {name: sha256(stage / "bin" / name) for name in BINARIES},
+        }
+        (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_text(f"{digest}  {archive.name}\n", encoding="ascii")
+        print(f"archive={archive}")
+        print(f"sha256={digest}")
+        print(f"source_commit={source_commit}")
+    return 0
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())