2536 lines
121 KiB
Bash
2536 lines
121 KiB
Bash
#!/bin/sh
|
|
# gpuk — installer + control CLI for the GPU Kitchen host daemon (gpu-kitchen-worker).
|
|
#
|
|
# Since C1 a compute node runs NO backend. The single privileged host component is
|
|
# the Rust `gpu-kitchen-worker` daemon (workerd), running as root DIRECTLY on the
|
|
# host (not in a container). It owns NVML clock/power locks, whitelisted host
|
|
# browsing, the model-cache staging pipeline, the signed `gpu-kitchen-bench`
|
|
# runner, and — on a controller node — the app container's lifecycle (create,
|
|
# health-gate, roll back, pull+recreate to update) via its manifest. There is no
|
|
# separate host daemon and no unix control socket: workerd is driven over the
|
|
# wss+mTLS channel by the controller, and locally by this CLI.
|
|
#
|
|
# Two roles:
|
|
# worker a headless compute node. Installs the binary + systemd unit + a
|
|
# manifest (cacheDisks) with NO app container, NO
|
|
# Postgres, NO docker app image. It ENROLLS over mTLS with a
|
|
# enrollment token, or waits for LAN discovery admission, then runs.
|
|
# controller the full app + UI. Installs the binary + systemd unit + an
|
|
# app-container manifest (image, ports, env, secretsRef) that workerd
|
|
# applies (`gpu-kitchen-worker apply`, then cmd:host_apply in steady
|
|
# state).
|
|
#
|
|
# Install (root):
|
|
# # controller:
|
|
# curl -fsSL https://repo.byterain.io/gpukitchen/channel/raw/branch/main/gpuk \
|
|
# | sudo sh -s -- install --mode controller \
|
|
# --image repo.byterain.io/gpukitchen/gpukitchen-controller:vX.Y.Z
|
|
# # worker (enroll against a controller with a single-use token from its UI):
|
|
# sudo ./deployments/install/gpuk install --mode worker \
|
|
# --controller wss://controller.lan:8443 --enroll-token - \
|
|
# --cache-dir /mnt/models --binary apps/worker/target/release/gpu-kitchen-worker
|
|
#
|
|
# Control:
|
|
# gpuk status | apply | update | enroll | logs | manifest | uninstall
|
|
#
|
|
set -eu
|
|
|
|
# ── Paths ────────────────────────────────────────────────────────────────────
|
|
# Overridable, so the daemon can be driven against a prefix a normal user owns —
|
|
# the only way any of this is testable without handing a test suite root on the
|
|
# host. Unset (the real install) they are exactly the systemd defaults workerd uses
|
|
# (apps/worker/src/module.rs, apps/worker/src/identity.rs).
|
|
BIN_DEST="${GPUK_BIN_DEST:-/usr/local/bin/gpu-kitchen-worker}"
|
|
# This CLI, installed next to the daemon by `gpuk install`: it carries the
|
|
# release key pinned at install time, and install.sh hands a plain re-run to its
|
|
# `update` (INS-03, OPS-20).
|
|
CLI_DEST="${GPUK_CLI_DEST:-$(dirname "$BIN_DEST")/gpuk}"
|
|
ETC_DIR="${GPUK_ETC_DIR:-/etc/gpu-kitchen}"
|
|
MANIFEST="$ETC_DIR/manifest.json"
|
|
IDENTITY_DIR="${GPUK_IDENTITY_DIR:-$ETC_DIR/identity}"
|
|
MACHINE_ID_FILE="${GPUK_MACHINE_ID_FILE:-$ETC_DIR/machine-id}"
|
|
WORKER_ENV="$ETC_DIR/worker.env"
|
|
SERVICE_NAME="gpu-kitchen-worker"
|
|
UNIT_DEST="${GPUK_UNIT_DEST:-/etc/systemd/system/$SERVICE_NAME.service}"
|
|
RETIRE_SERVICE="$SERVICE_NAME-retirement"
|
|
RETIRE_UNIT="$(dirname "$UNIT_DEST")/$RETIRE_SERVICE.service"
|
|
RETIRE_TIMER="$(dirname "$UNIT_DEST")/$RETIRE_SERVICE.timer"
|
|
RETIRE_PENDING="$ETC_DIR/beta-retirement-pending"
|
|
RETIRE_STATE="$ETC_DIR/beta-retirement-state"
|
|
# Outside ETC_DIR: purge must not replace the inode used to serialize lifecycle commands.
|
|
LIFECYCLE_LOCK="$ETC_DIR.lifecycle.lock"
|
|
|
|
# Where to download the binary from when no --binary is given.
|
|
GPUK_RELEASE_BASE="${GPUK_RELEASE_BASE:-}"
|
|
|
|
die() { echo "gpuk: $*" >&2; exit 1; }
|
|
|
|
# Root, or able to do the job anyway. Fail with a clear message BEFORE touching
|
|
# /etc, /usr/local/bin or systemd. Against a user-owned prefix it simply works.
|
|
need_root() {
|
|
[ "$(id -u)" -eq 0 ] && return 0
|
|
[ -w "$ETC_DIR" ] && return 0
|
|
die "this command must run as root (use sudo)"
|
|
}
|
|
|
|
# Keep cleanup and installation mutually exclusive. An update can restart systemd
|
|
# while holding this lock, so ExecStopPost cleanup must never wait for it.
|
|
# FD 9 survives the verified CLI self-reexec. Reuse only that exact lock inode.
|
|
lifecycle_lock() { # optional: nonblocking
|
|
command -v flock >/dev/null 2>&1 || die "flock is required to manage this installation"
|
|
if [ "$(readlink /proc/$$/fd/9 2>/dev/null || true)" != "$LIFECYCLE_LOCK" ]; then
|
|
[ ! -L "$LIFECYCLE_LOCK" ] || die "refusing a symlink for the installation lock"
|
|
exec 9>>"$LIFECYCLE_LOCK"
|
|
chmod 0600 "$LIFECYCLE_LOCK"
|
|
fi
|
|
if [ "${1:-}" = "nonblocking" ]; then
|
|
flock -n 9 || return 1
|
|
else
|
|
flock -x 9 || die "cannot lock this installation"
|
|
fi
|
|
trap 'rm -f "$BIN_DEST.new" "$BIN_DEST.new.minisig" "$CLI_DEST.new"; [ -z "$CHANNEL_DOC" ] || rm -f "$CHANNEL_DOC"' EXIT
|
|
}
|
|
|
|
# Only run this on the verified download (or an explicitly supplied local build),
|
|
# before replacing files or changing the manifest. A rejected candidate is removed.
|
|
check_candidate_release() { # binary, optional temporary file to remove
|
|
_release_status=0
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$1" check-release || _release_status=$?
|
|
if [ "$_release_status" -eq 0 ]; then
|
|
_candidate_expiry=$("$1" --beta-expiry) || _release_status=1
|
|
case "$_candidate_expiry" in
|
|
0) ;; # Normal and development releases have no calendar gate.
|
|
"$((0xce8c74e7 ^ 0xa5c39e17))")
|
|
# Independent installer checkpoint: compare a UTC calendar value, not
|
|
# the worker's epoch representation. The source constants stay encoded.
|
|
_release_now=$(date -u +%Y%m%d%H%M%S) || _release_status=1
|
|
case "$_release_now" in
|
|
''|*[!0-9]*) _release_status=1 ;;
|
|
*)
|
|
if [ "${#_release_now}" -ne 14 ]; then
|
|
_release_status=1
|
|
elif [ "$_release_status" -eq 0 ] && [ "$_release_now" -ge "$((7843927165021 + 12426192064979))" ]; then
|
|
# A local clock contradicting authenticated release time blocks
|
|
# installation, but is never proof that permits deletion.
|
|
_release_status=79
|
|
fi
|
|
;;
|
|
esac
|
|
;;
|
|
*) _release_status=1 ;;
|
|
esac
|
|
fi
|
|
if [ "$_release_status" -ne 0 ]; then
|
|
[ -z "${2:-}" ] || rm -f "$2" "$2.minisig"
|
|
if [ "$_release_status" -eq 78 ]; then
|
|
echo "gpuk: this beta has expired. Install the current release." >&2
|
|
exit 78
|
|
fi
|
|
if [ "$_release_status" -eq 79 ]; then
|
|
echo "gpuk: release time could not be confirmed. Try again when online." >&2
|
|
exit 79
|
|
fi
|
|
die "the release check failed; nothing has been installed"
|
|
fi
|
|
}
|
|
|
|
# ── JSON helpers (controlled inputs: paths + identifiers) ──────────────────────
|
|
json_str() { printf '%s' "$1" | sed 's/\\/\\\\/g; s/"/\\"/g'; }
|
|
|
|
# The host's IANA time zone (PLN-51): the planning's weekly template is written in the
|
|
# controller's time, and a container left in UTC would shift it silently. Empty when
|
|
# the host does not say; the controller then reports UTC and shows it.
|
|
host_timezone() {
|
|
_tz=""
|
|
if command -v timedatectl >/dev/null 2>&1; then
|
|
_tz=$(timedatectl show -p Timezone --value 2>/dev/null || true)
|
|
fi
|
|
if [ -z "$_tz" ] && [ -L /etc/localtime ]; then
|
|
_tz=$(readlink /etc/localtime | sed -n 's#.*/zoneinfo/##p')
|
|
fi
|
|
if [ -z "$_tz" ] && [ -r /etc/timezone ]; then
|
|
_tz=$(head -n 1 /etc/timezone)
|
|
fi
|
|
case "$_tz" in
|
|
*[!A-Za-z0-9_+/-]*) _tz="" ;;
|
|
esac
|
|
printf '%s' "$_tz"
|
|
}
|
|
|
|
json_array() { # args → ["a","b",...]
|
|
_out=""
|
|
for _p in "$@"; do
|
|
_e=$(json_str "$_p")
|
|
if [ -z "$_out" ]; then _out="\"$_e\""; else _out="$_out,\"$_e\""; fi
|
|
done
|
|
printf '[%s]' "$_out"
|
|
}
|
|
|
|
# ── install ────────────────────────────────────────────────────────────────────
|
|
arch_asset() {
|
|
case "$(uname -m)" in
|
|
x86_64|amd64) echo "gpu-kitchen-worker-x86_64" ;;
|
|
aarch64|arm64) echo "gpu-kitchen-worker-aarch64" ;;
|
|
*) die "unsupported architecture: $(uname -m)" ;;
|
|
esac
|
|
}
|
|
|
|
# [INS-19] A (re)install has just replaced the binary under a daemon that may be
|
|
# running: `systemctl enable --now` is a no-op on an active unit and would leave the
|
|
# OLD process in memory, speaking the old protocol to the new controller. Enable, then
|
|
# restart — which also starts a daemon that was not running.
|
|
start_daemon() {
|
|
systemctl enable "$SERVICE_NAME"
|
|
systemctl restart "$SERVICE_NAME"
|
|
}
|
|
|
|
install_binary() { # [local-path]
|
|
if [ -n "${1:-}" ]; then
|
|
[ -f "$1" ] || die "binary not found: $1"
|
|
install -m 0755 "$1" "$BIN_DEST.new"
|
|
check_candidate_release "$BIN_DEST.new" "$BIN_DEST.new"
|
|
mv "$BIN_DEST.new" "$BIN_DEST"
|
|
echo "==> installed $BIN_DEST from $1"
|
|
elif [ -n "$GPUK_RELEASE_BASE" ]; then
|
|
command -v curl >/dev/null || die "curl is required to download the binary"
|
|
# [OPS-20] A mirror changes WHERE the daemon comes from, never WHICH build: the
|
|
# signed channel names it, exactly as for `gpuk update`, and an older one is refused.
|
|
channel_fetch || die "cannot read the signed release channel at $CHANNEL_URL"
|
|
_build=$(channel_worker_build) || exit 1
|
|
refuse_daemon_downgrade "$_build"
|
|
fetch_signed_daemon "$GPUK_RELEASE_BASE/$(arch_asset)" "$_build"
|
|
chmod 0755 "$BIN_DEST.new"
|
|
check_candidate_release "$BIN_DEST.new" "$BIN_DEST.new"
|
|
mv "$BIN_DEST.new" "$BIN_DEST"
|
|
elif [ -x "$BIN_DEST" ]; then
|
|
check_candidate_release "$BIN_DEST"
|
|
echo "==> reusing existing $BIN_DEST"
|
|
else
|
|
die "no binary: pass --binary <path> or set GPUK_RELEASE_BASE=<url base>"
|
|
fi
|
|
}
|
|
|
|
# Leave this very gpuk on the host, next to the daemon: `gpuk status`, `gpuk
|
|
# update` and install.sh's plain re-run all use it. It is the copy that carries
|
|
# the release key this install pinned (substituted at publish time), so later
|
|
# updates are verified against the key the first install trusted.
|
|
install_cli() {
|
|
# Already this copy (gpuk re-run from its installed path, or identical bytes).
|
|
if [ -e "$CLI_DEST" ] && cmp -s "$0" "$CLI_DEST"; then return 0; fi
|
|
install -m 0755 "$0" "$CLI_DEST.new" && mv "$CLI_DEST.new" "$CLI_DEST" \
|
|
|| die "cannot install the gpuk CLI at $CLI_DEST"
|
|
echo "==> installed $CLI_DEST"
|
|
}
|
|
|
|
gen_secret() { head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '='; }
|
|
|
|
# BEGIN GENERATED INTERNET REACHABILITY — tools/gen-install-reachability.mjs from deployments/install/reachability.sh.in and packages/contracts/data/public-address-ranges.json; DO NOT EDIT
|
|
# Whether the Internet reaches this machine, one finding per line:
|
|
# public <ipv4> <interface> a public IPv4 on an interface (the controller listens there)
|
|
# ipv6 <ipv6> <interface> a global IPv6: reported only, nothing listens on IPv6
|
|
# cloud <ipv4> a public IPv4 the cloud metadata service maps 1:1 to it
|
|
# unknown no `ip` nor `hostname -I` to read the addresses
|
|
# The ranges come from packages/contracts/data/public-address-ranges.json, the controller's
|
|
# own definition too. GPUK_CLOUD_METADATA_URL is a test seam.
|
|
reach_classify() { # stdin: "<interface> <family> <address>[/prefix]" lines
|
|
awk '
|
|
function v4int(a, o, n, i, x) {
|
|
n = split(a, o, ".")
|
|
if (n != 4) return -1
|
|
x = 0
|
|
for (i = 1; i <= 4; i++) {
|
|
if (o[i] !~ /^[0-9]+$/ || o[i] + 0 > 255) return -1
|
|
x = x * 256 + o[i]
|
|
}
|
|
return x
|
|
}
|
|
function hexval(h, i, c, x) {
|
|
x = 0
|
|
for (i = 1; i <= length(h); i++) {
|
|
c = index("0123456789abcdef", substr(h, i, 1))
|
|
if (c == 0) return -1
|
|
x = x * 16 + c - 1
|
|
}
|
|
return x
|
|
}
|
|
function v6head32(a, h, n, h1, h2) {
|
|
n = split(tolower(a), h, ":")
|
|
if (n < 3 || h[1] == "" || length(h[1]) > 4 || length(h[2]) > 4) return -1
|
|
h1 = hexval(h[1])
|
|
h2 = (h[2] == "") ? 0 : hexval(h[2])
|
|
if (h1 < 0 || h2 < 0) return -1
|
|
return h1 * 65536 + h2
|
|
}
|
|
function v4public(a, x) {
|
|
x = v4int(a)
|
|
if (x < 0) return 0
|
|
if (x >= 0 && x <= 16777215) return 0 # 0.0.0.0/8 this network
|
|
if (x >= 167772160 && x <= 184549375) return 0 # 10.0.0.0/8 private
|
|
if (x >= 1681915904 && x <= 1686110207) return 0 # 100.64.0.0/10 CGNAT
|
|
if (x >= 2130706432 && x <= 2147483647) return 0 # 127.0.0.0/8 loopback
|
|
if (x >= 2851995648 && x <= 2852061183) return 0 # 169.254.0.0/16 link local
|
|
if (x >= 2886729728 && x <= 2887778303) return 0 # 172.16.0.0/12 private
|
|
if (x >= 3221225472 && x <= 3221225727) return 0 # 192.0.0.0/24 IETF protocol assignments
|
|
if (x >= 3221225984 && x <= 3221226239) return 0 # 192.0.2.0/24 documentation
|
|
if (x >= 3232235520 && x <= 3232301055) return 0 # 192.168.0.0/16 private
|
|
if (x >= 3323068416 && x <= 3323199487) return 0 # 198.18.0.0/15 benchmarking
|
|
if (x >= 3325256704 && x <= 3325256959) return 0 # 198.51.100.0/24 documentation
|
|
if (x >= 3405803776 && x <= 3405804031) return 0 # 203.0.113.0/24 documentation
|
|
if (x >= 3758096384 && x <= 4294967295) return 0 # 224.0.0.0/3 multicast and reserved
|
|
return 1
|
|
}
|
|
function v6global(a, x) {
|
|
x = v6head32(a)
|
|
if (x < 0) return 0
|
|
if (x < 536870912 || x > 1073741823) return 0 # outside 2000::/3
|
|
if (x >= 536939960 && x <= 536939960) return 0 # 2001:db8::/32 documentation
|
|
return 1
|
|
}
|
|
{
|
|
addr = $3; sub(/\/.*/, "", addr)
|
|
if ($2 == "inet" && v4public(addr)) print "public", addr, $1
|
|
else if ($2 == "inet6" && v6global(addr)) print "ipv6", addr, $1
|
|
else if ($2 == "cloud" && v4public(addr)) print "cloud", addr
|
|
}'
|
|
}
|
|
|
|
reach_cloud_ipv4() { # a public IPv4 from AWS, Google Cloud or Azure metadata, or nothing
|
|
command -v curl >/dev/null 2>&1 || return 0
|
|
_md="${GPUK_CLOUD_METADATA_URL:-http://169.254.169.254}"
|
|
curl -s -o /dev/null --connect-timeout 1 -m 1 "$_md/" 2>/dev/null || return 0
|
|
_tok=$(curl -sf --connect-timeout 1 -m 1 -X PUT \
|
|
-H 'X-aws-ec2-metadata-token-ttl-seconds: 60' "$_md/latest/api/token" 2>/dev/null) || _tok=""
|
|
if [ -n "$_tok" ]; then
|
|
_ip=$(curl -sf -m 1 -H "X-aws-ec2-metadata-token: $_tok" \
|
|
"$_md/latest/meta-data/public-ipv4" 2>/dev/null) || _ip=""
|
|
else
|
|
_ip=$(curl -sf -m 1 "$_md/latest/meta-data/public-ipv4" 2>/dev/null) || _ip=""
|
|
fi
|
|
[ -n "$_ip" ] || _ip=$(curl -sf -m 1 -H 'Metadata-Flavor: Google' \
|
|
"$_md/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip" 2>/dev/null) || _ip=""
|
|
[ -n "$_ip" ] || _ip=$(curl -sf -m 1 -H 'Metadata: true' \
|
|
"$_md/metadata/instance/network/interface/0/ipv4/ipAddress/0/publicIpAddress?api-version=2021-02-01&format=text" 2>/dev/null) || _ip=""
|
|
case "$_ip" in
|
|
*[!0-9.]*|"") return 0 ;;
|
|
esac
|
|
printf '%s\n' "$_ip"
|
|
}
|
|
|
|
reach_findings() {
|
|
if command -v ip >/dev/null 2>&1; then
|
|
ip -o addr show 2>/dev/null | awk '{ print $2, $3, $4 }' | reach_classify
|
|
elif _reach_h=$(hostname -I 2>/dev/null); then
|
|
for _a in $_reach_h; do
|
|
case "$_a" in *:*) echo "- inet6 $_a" ;; *) echo "- inet $_a" ;; esac
|
|
done | reach_classify
|
|
else
|
|
echo "unknown"
|
|
fi
|
|
_cloud=$(reach_cloud_ipv4)
|
|
[ -z "$_cloud" ] || echo "- cloud $_cloud" | reach_classify
|
|
}
|
|
|
|
# Why the Home lab profile is refused (INS-89), or nothing. $1 = reach_findings output.
|
|
homelab_refusal_reason() {
|
|
_why=$(printf '%s\n' "$1" | awk '
|
|
$1 == "public" { print "This machine is reachable from the Internet: it has the public address " $2 " on " $3 "."; exit }
|
|
$1 == "cloud" { print "This machine is reachable from the Internet: its cloud provider gives it the public address " $2 "."; exit }
|
|
$1 == "unknown" { print "GPU Kitchen cannot read the addresses of this machine (no ip or hostname command), so it cannot tell whether the Internet reaches it."; exit }')
|
|
[ -n "$_why" ] || return 0
|
|
echo "$_why The Home lab profile lets anyone who reaches it in without signing in, so it is not allowed here. Use --profile small-team (control from this machine only), --profile managed-network (sign-in required) or --profile public (sign-in, behind a TLS reverse proxy)."
|
|
}
|
|
|
|
# The first public IPv4 of this machine, for the controller ([INS-93]); nothing when none.
|
|
# $1 = reach_findings output.
|
|
public_ipv4_of() {
|
|
printf '%s\n' "$1" | awk '$1 == "public" || $1 == "cloud" { print $2; exit }'
|
|
}
|
|
|
|
# A global IPv6 address of this machine (INS-92): reported, never refused. $1 = findings.
|
|
global_ipv6_note() {
|
|
_v6=$(printf '%s\n' "$1" | awk '$1 == "ipv6" { print $2 " on " $3; exit }')
|
|
[ -z "$_v6" ] || echo "This machine has the global IPv6 address $_v6. GPU Kitchen listens on IPv4 only, so the Internet does not reach it there."
|
|
}
|
|
# END GENERATED INTERNET REACHABILITY
|
|
|
|
# [INS-87] The Docker bridge gateway: the host address apps on this machine reach as
|
|
# host.docker.internal, and the one the proxy binds under `public`. GPUK_DOCKER_GATEWAY
|
|
# overrides; then the daemon's own host-gateway-ip (INS-95: host.docker.internal
|
|
# resolves there, whatever the bridge); then the default bridge's gateway; Docker's
|
|
# default bridge address is the last fallback, named in a warning.
|
|
docker_bridge_gateway() {
|
|
_gw="${GPUK_DOCKER_GATEWAY:-}"
|
|
[ -n "$_gw" ] || _gw=$(sed -n 's/.*"host-gateway-ips\{0,1\}"[[:space:]]*:[[:space:]]*\[\{0,1\}[[:space:]]*"\([0-9.]*\)".*/\1/p' \
|
|
"${GPUK_DOCKER_DAEMON_JSON:-/etc/docker/daemon.json}" 2>/dev/null | head -1)
|
|
[ -n "$_gw" ] || _gw=$(docker network inspect bridge -f '{{range .IPAM.Config}}{{.Gateway}}{{end}}' 2>/dev/null || true)
|
|
case "$_gw" in
|
|
*[!0-9.]* | "") echo "==> warning: the Docker bridge address could not be read; using 172.17.0.1 (set GPUK_DOCKER_GATEWAY to change it)" >&2; _gw="172.17.0.1" ;;
|
|
esac
|
|
printf '%s' "$_gw"
|
|
}
|
|
|
|
# [INS-84] True when Docker relays every published connection through docker-proxy,
|
|
# which then hides the client behind the bridge gateway: rootless Docker, or a
|
|
# daemon running with iptables off (daemon.json or the dockerd command line).
|
|
docker_relays_every_client() {
|
|
command -v docker >/dev/null 2>&1 || return 1
|
|
case "$(docker info --format '{{json .SecurityOptions}}' 2>/dev/null)" in
|
|
*rootless*) return 0 ;;
|
|
esac
|
|
grep -Eq '"iptables"[[:space:]]*:[[:space:]]*false' "${GPUK_DOCKER_DAEMON_JSON:-/etc/docker/daemon.json}" 2>/dev/null \
|
|
&& return 0
|
|
for _dpid in $(pidof dockerd 2>/dev/null); do
|
|
case " $(tr '\0' ' ' < "/proc/$_dpid/cmdline" 2>/dev/null) " in
|
|
*" --iptables=false "* | *" --iptables false "*) return 0 ;;
|
|
esac
|
|
done
|
|
return 1
|
|
}
|
|
|
|
# The host ports a leftover app container is reached on ("ui mtls inference"),
|
|
# read off the container itself with the precedence the controller applies
|
|
# (core/published-ports.ts): host networking moves the listeners (GPUK_PORT,
|
|
# GPUK_MTLS_PORT, GPUK_LISTEN_ADDR); anything else keeps the image's fixed
|
|
# listeners and publishes them (GPUK_PUBLIC_*, then the port bindings). Empty
|
|
# when there is no such container or no docker.
|
|
leftover_container_ports() { # $1 = container name
|
|
command -v docker >/dev/null 2>&1 || return 0
|
|
# Same format string as install.sh's container_facts — one reading, two scripts.
|
|
_f=$(docker inspect -f '{{.State.Status}}|{{.HostConfig.NetworkMode}}|{{range $p, $b := .HostConfig.PortBindings}}{{range $b}}{{$p}}={{.HostPort}} {{end}}{{end}}{{"\n"}}{{range .Config.Env}}{{.}}{{"\n"}}{{end}}' "$1" 2>/dev/null) \
|
|
|| return 0
|
|
[ -n "$_f" ] || return 0
|
|
_head=$(printf '%s\n' "$_f" | head -1)
|
|
_r=${_head#*|}; _net=${_r%%|*}; _bind=${_r#*|}
|
|
_env() { printf '%s\n' "$_f" | sed -n "s/^$1=//p" | head -1; }
|
|
_pub() { printf '%s\n' "$_bind" | tr ' ' '\n' | sed -n "s/^$1\/tcp=//p" | head -1; }
|
|
if [ "$_net" = "host" ]; then
|
|
_ui=$(_env GPUK_PORT); _mtls=$(_env GPUK_MTLS_PORT)
|
|
_inf=$(_env GPUK_PROXY_PUBLIC_PORT)
|
|
[ -n "$_inf" ] || { _la=$(_env GPUK_LISTEN_ADDR); _inf=${_la##*:}; }
|
|
else
|
|
_ui=$(_env GPUK_PUBLIC_PORT); [ -n "$_ui" ] || _ui=$(_pub 8080)
|
|
_mtls=$(_env GPUK_PUBLIC_MTLS_PORT); [ -n "$_mtls" ] || _mtls=$(_pub 8443)
|
|
_inf=$(_env GPUK_PROXY_PUBLIC_PORT); [ -n "$_inf" ] || _inf=$(_pub 8200)
|
|
fi
|
|
printf '%s %s %s' "${_ui:-8080}" "${_mtls:-8443}" "${_inf:-8200}"
|
|
}
|
|
|
|
# Who holds a port: "process", "process in container NAME", or "". The process's
|
|
# cgroup names its container (host networking); a bridged publication is found
|
|
# as the container's port mapping in `docker ps` (the host-side holder is
|
|
# docker-proxy, which says nothing by itself). Same reading as install.sh.
|
|
port_owner() { # $1 = ss|netstat, $2 = port
|
|
_proc=""; _pid=""
|
|
case "$1" in
|
|
ss)
|
|
_line=$(ss -ltnpH "sport = :$2" 2>/dev/null | head -1)
|
|
_proc=$(printf '%s' "$_line" | sed -n 's/.*users:((\"\([^"]*\)\".*/\1/p')
|
|
_pid=$(printf '%s' "$_line" | sed -n 's/.*pid=\([0-9]*\).*/\1/p')
|
|
;;
|
|
netstat)
|
|
_field=$(netstat -ltnp 2>/dev/null \
|
|
| awk -v p="$2" '{n=split($4,a,":"); if (a[n]==p) {print $NF; exit}}')
|
|
case "$_field" in
|
|
*/*) _pid=${_field%%/*}; _proc=${_field#*/} ;;
|
|
*) _proc="$_field" ;;
|
|
esac
|
|
;;
|
|
esac
|
|
case "$_pid" in *[!0-9]*|"") _pid="" ;; esac
|
|
_ctr=""
|
|
if command -v docker >/dev/null 2>&1; then
|
|
if [ -n "$_pid" ] && [ -r "/proc/$_pid/cgroup" ]; then
|
|
_cid=$(sed -n 's#.*docker[-/]\([0-9a-f]\{64\}\).*#\1#p' "/proc/$_pid/cgroup" 2>/dev/null | head -1)
|
|
[ -z "$_cid" ] || _ctr=$(docker inspect -f '{{.Name}}' "$_cid" 2>/dev/null | sed 's|^/||')
|
|
fi
|
|
[ -n "$_ctr" ] || _ctr=$(docker ps --format '{{.Names}} {{.Ports}}' 2>/dev/null \
|
|
| awk -v p=":$2->" 'index($0, p) { print $1; exit }')
|
|
fi
|
|
if [ -n "$_ctr" ]; then
|
|
printf '%s' "${_proc:-a process} in container $_ctr"
|
|
else
|
|
printf '%s' "$_proc"
|
|
fi
|
|
}
|
|
|
|
# This host's LAN IPv4 — what a browser, a worker or a container on the docker
|
|
# bridge dials to reach the machine. The route to a public address names the
|
|
# source the default route uses (never a docker or libvirt bridge); failing that,
|
|
# the first global address on a physical-looking interface; failing that, the
|
|
# resolver's word. Empty when nothing answers — the caller says so. Same
|
|
# derivation as dev.sh best_host_lan_ipv4 and install.sh's banner.
|
|
host_lan_ipv4() {
|
|
_ip=$(ip route get 1.1.1.1 2>/dev/null | sed -n 's/.* src \([0-9.]*\).*/\1/p' | head -1)
|
|
if [ -z "$_ip" ]; then
|
|
_ip=$(ip -o -4 addr show scope global 2>/dev/null \
|
|
| awk '$2 !~ /^(virbr|docker|br-|veth|mpqemubr|tun|tap|vnet)/ {sub(/\/.*/, "", $4); print $4; exit}')
|
|
fi
|
|
[ -n "$_ip" ] || _ip=$(hostname -I 2>/dev/null | awk '{print $1}')
|
|
printf '%s' "$_ip"
|
|
}
|
|
|
|
seed_secrets() { # DATA_ROOT
|
|
_sd="$1/secrets"
|
|
mkdir -p "$_sd"; chmod 0700 "$_sd"
|
|
[ -f "$_sd/encryption_key" ] || { umask 077; gen_secret > "$_sd/encryption_key"; }
|
|
[ -f "$_sd/node_id" ] || { umask 077; (cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen) > "$_sd/node_id"; }
|
|
# No nominal first-run password is generated. An operator may pre-provision
|
|
# this documented break-glass file; only then is it injected into the app.
|
|
[ ! -f "$_sd/bootstrap_admin_password" ] || chmod 0600 "$_sd/bootstrap_admin_password"
|
|
}
|
|
|
|
prepare_claim_key() {
|
|
# The file is the operator's recoverable proof of machine possession. Create
|
|
# it once, preserve it across reinstalls, and let the backend unlink it after
|
|
# the atomic first-account claim. A missing file beside an existing manifest
|
|
# therefore means "consumed", never "rotate the credential". homelab and small-team
|
|
# have no claim window at all (PRF-12, SEC-53): no code is made for them.
|
|
case "$PROFILE" in homelab|small-team) return 0 ;; esac
|
|
if [ -f "$CLAIM_KEY_FILE" ]; then
|
|
chmod 0600 "$CLAIM_KEY_FILE"
|
|
elif [ ! -f "$MANIFEST" ]; then
|
|
umask 077
|
|
gen_secret > "$CLAIM_KEY_FILE"
|
|
chmod 0600 "$CLAIM_KEY_FILE"
|
|
fi
|
|
}
|
|
|
|
# Write the systemd unit generated from the worker's canonical template. The
|
|
# generator injects the Rust lock-contention exit code here too, so the binary
|
|
# and systemd restart policy cannot silently drift apart.
|
|
write_unit() {
|
|
# Normal releases retain their short stop grace. Only a stamped beta needs
|
|
# enough time for its bounded retirement cleanup after the daemon exits.
|
|
_stop_timeout=15
|
|
_restart_delay=2
|
|
if [ "$("$BIN_DEST" --beta-expiry 2>/dev/null || true)" = "$((0xce8c74e7 ^ 0xa5c39e17))" ]; then
|
|
_stop_timeout=180
|
|
_restart_delay=60
|
|
fi
|
|
# BEGIN GENERATED WORKER SYSTEMD UNIT
|
|
cat > "$UNIT_DEST" <<UNIT
|
|
[Unit]
|
|
Description=GPU Kitchen worker daemon (gpu-kitchen-worker)
|
|
Documentation=https://repo.byterain.io/Sebastien/GPU-Manager
|
|
After=network-online.target docker.service
|
|
Wants=network-online.target docker.service
|
|
|
|
[Service]
|
|
Type=simple
|
|
# The worker runs as root on the host (NVML, docker.sock, mounts) — NOT in a
|
|
# container. Identity (keypair/cert/CA) lives under $IDENTITY_DIR; enroll once
|
|
# before starting this unit. Optional overrides live in $WORKER_ENV.
|
|
EnvironmentFile=-$WORKER_ENV
|
|
Environment=GPUK_MANIFEST_PATH=$MANIFEST
|
|
ExecStart=$BIN_DEST
|
|
# The binary validates its own beta stamp and authenticated pending state.
|
|
ExecStopPost=$BIN_DEST retire-beta
|
|
# WRK-173: the old MainPID transfers supervision to the verified replacement
|
|
# before it exits. Notifications remain local to this service cgroup.
|
|
NotifyAccess=all
|
|
# Transient operation state only. The node lock has its own stable inode under
|
|
# /run/lock, outside this systemd-managed directory.
|
|
RuntimeDirectory=gpu-kitchen
|
|
RuntimeDirectoryMode=0750
|
|
Restart=always
|
|
RestartSec=$_restart_delay
|
|
# Lock contention is an operator error, not a crash: do not retry forever while
|
|
# another directly installed worker owns the WRK-167 host lock.
|
|
RestartPreventExitStatus=75 78
|
|
User=root
|
|
# Fail-closed renewal: on a refused cert renewal the daemon exits and systemd
|
|
# restarts it into an enroll-required state.
|
|
KillSignal=SIGTERM
|
|
# WRK-273: a stop asks the worker alone; a driver change it carries (apt, dpkg,
|
|
# DKMS) ends first, the worker asking systemd for more time while it waits.
|
|
KillMode=mixed
|
|
TimeoutStopSec=$_stop_timeout
|
|
|
|
[Install]
|
|
WantedBy=multi-user.target
|
|
UNIT
|
|
# END GENERATED WORKER SYSTEMD UNIT
|
|
write_retirement_units
|
|
}
|
|
|
|
write_retirement_units() {
|
|
for _retry_file in "$RETIRE_UNIT" "$RETIRE_TIMER"; do
|
|
[ ! -L "$_retry_file" ] || die "refusing a symlink for the retirement service"
|
|
[ ! -e "$_retry_file" ] || { [ -f "$_retry_file" ] && [ "$(stat -c %u "$_retry_file")" = "$(id -u)" ]; } \
|
|
|| die "the retirement service is not owned by this installation"
|
|
done
|
|
if [ "$_stop_timeout" -eq 180 ]; then
|
|
# BEGIN GENERATED RETIREMENT SYSTEMD UNITS
|
|
cat > "$RETIRE_UNIT" <<UNIT
|
|
[Unit]
|
|
Description=Finish GPU Kitchen beta retirement
|
|
After=network-online.target docker.service
|
|
Wants=network-online.target docker.service
|
|
|
|
[Service]
|
|
Type=oneshot
|
|
EnvironmentFile=-$WORKER_ENV
|
|
Environment=GPUK_MANIFEST_PATH=$MANIFEST
|
|
ExecStart=$BIN_DEST retire-beta
|
|
TimeoutStartSec=180
|
|
User=root
|
|
UNIT
|
|
cat > "$RETIRE_TIMER" <<UNIT
|
|
[Unit]
|
|
Description=Retry unfinished GPU Kitchen beta retirement
|
|
|
|
[Timer]
|
|
OnBootSec=60
|
|
OnUnitInactiveSec=300
|
|
Unit=gpu-kitchen-worker-retirement.service
|
|
|
|
[Install]
|
|
WantedBy=timers.target
|
|
UNIT
|
|
# END GENERATED RETIREMENT SYSTEMD UNITS
|
|
chmod 0644 "$RETIRE_UNIT" "$RETIRE_TIMER"
|
|
systemctl daemon-reload
|
|
systemctl enable --now "$RETIRE_SERVICE.timer"
|
|
else
|
|
if [ -e "$RETIRE_UNIT" ] || [ -e "$RETIRE_TIMER" ]; then
|
|
systemctl disable --now "$RETIRE_SERVICE.timer" \
|
|
|| die "cannot disable the previous beta retirement timer"
|
|
rm -f "$RETIRE_UNIT" "$RETIRE_TIMER"
|
|
fi
|
|
rm -f "$RETIRE_PENDING" "$RETIRE_STATE"
|
|
fi
|
|
}
|
|
|
|
# TLS reverse-proxy example, FILLED with the operator's domain (INS-47) — written
|
|
# under `--domain <d>`, whatever the profile. Kept aligned with
|
|
# deployments/controller/Caddyfile.example (the dev/CI compose variant); this copy
|
|
# targets the all-in-one image, where nginx on the UI port is the single front
|
|
# door (INS-09) so one upstream carries pages, /api and the /ws upgrade alike.
|
|
# We write a file and NOTHING more: no package install, no service start, no
|
|
# other program's config read or touched — putting the proxy in service stays an
|
|
# operator act (OPS-13), and its presence stays unverifiable (OPS-67).
|
|
write_caddyfile() {
|
|
mkdir -p "$DATA_ROOT/caddy"
|
|
# [INS-87] Under `public` the proxy binds the Docker bridge gateway, never a public
|
|
# interface: this front is the only way in from outside, at https://$DOMAIN/v1.
|
|
PROXY_UPSTREAM="localhost:$INFERENCE_PORT"
|
|
SITE_BODY=" reverse_proxy localhost:$HTTP_PORT"
|
|
if [ "$PROFILE" = "public" ]; then
|
|
PROXY_UPSTREAM="$PROXY_GATEWAY:$INFERENCE_PORT"
|
|
SITE_BODY=" # OpenAI-compatible inference (gpuk-proxy): https://$DOMAIN/v1
|
|
handle /v1/* {
|
|
reverse_proxy $PROXY_UPSTREAM
|
|
}
|
|
handle {
|
|
reverse_proxy localhost:$HTTP_PORT
|
|
}"
|
|
fi
|
|
cat > "$DATA_ROOT/caddy/Caddyfile" <<CADDY
|
|
# TLS in front of GPU Kitchen — generated by the installer for --domain $DOMAIN
|
|
# (specs/plateforme/installation/preflight-et-image.md INS-47). Caddy provisions and renews the
|
|
# certificate itself once DNS for $DOMAIN points at this machine.
|
|
#
|
|
# sudo cp $DATA_ROOT/caddy/Caddyfile /etc/caddy/Caddyfile
|
|
# sudo systemctl reload caddy
|
|
#
|
|
# The app already knows $DOMAIN as one of its names (GPUK_ALLOWED_HOSTS) and reads
|
|
# the real client address from this proxy's X-Forwarded-For (GPUK_TRUST_PROXY) —
|
|
# without it every visitor would share Caddy's address, and one login throttle.
|
|
# Under --profile public it also runs with GPUK_HSTS=true and
|
|
# GPUK_SESSION_COOKIE_SECURE=true. What does NOT go through this proxy:
|
|
# - the worker mTLS channel (:$MTLS_PORT): workers pin the controller CA and must
|
|
# reach it DIRECTLY — terminating it here would break the pin.
|
|
# - worker<->worker data transfers (:8300): LAN-only by contract (OPS-68).
|
|
|
|
$DOMAIN {
|
|
encode zstd gzip
|
|
$SITE_BODY
|
|
}
|
|
|
|
# OpenAI-compatible inference endpoint (gpuk-proxy) on a name of its own — uncomment
|
|
# when inference clients live beyond the trusted LAN; TLS keeps their API keys off
|
|
# the wire. The proxy already reads this front's X-Forwarded-For (GPUK_TRUST_PROXY in
|
|
# the manifest's proxy block), so key source bindings and usage see the real client.
|
|
#
|
|
# inference.$DOMAIN {
|
|
# encode zstd gzip
|
|
# reverse_proxy $PROXY_UPSTREAM
|
|
# }
|
|
CADDY
|
|
chmod 0644 "$DATA_ROOT/caddy/Caddyfile"
|
|
echo "==> wrote $DATA_ROOT/caddy/Caddyfile (filled TLS reverse-proxy example for $DOMAIN)"
|
|
}
|
|
|
|
# Pre-existing model caches (B81): a server that installs GPU Kitchen usually already
|
|
# holds tens or hundreds of GB of weights. We print a hint and nothing more — cache
|
|
# questions belong to the first-run wizard (INS-48, REG-41), never to the CLI; no
|
|
# config of any other program is read or touched, and referencing a cache stays an
|
|
# explicit choice made in the UI.
|
|
hint_existing_caches() {
|
|
hec_chosen=$(readlink -f "$1" 2>/dev/null || echo "$1")
|
|
hec_found=""
|
|
for hec_dir in /root/.cache/huggingface /home/*/.cache/huggingface "${HF_HOME:-}"; do
|
|
[ -n "$hec_dir" ] || continue
|
|
[ -d "$hec_dir/hub" ] || continue
|
|
hec_real=$(readlink -f "$hec_dir" 2>/dev/null || echo "$hec_dir")
|
|
[ "$hec_real" != "$hec_chosen" ] || continue
|
|
# Hub layout only (models--*) — matches what the scan can actually reference.
|
|
ls -d "$hec_dir"/hub/models--* >/dev/null 2>&1 || continue
|
|
hec_found="$hec_found $hec_real"
|
|
done
|
|
[ -n "$hec_found" ] || return 0
|
|
echo
|
|
for hec_dir in $hec_found; do
|
|
echo "==> existing model cache found at $hec_dir"
|
|
done
|
|
echo " GPU Kitchen will offer to reuse those models at first launch, and any"
|
|
echo " time from Nodes & GPU -> Storage. A reused cache is referenced in"
|
|
echo " place. Nothing is moved or deleted."
|
|
}
|
|
|
|
cmd_install() {
|
|
IMAGE=""; MODE="worker"; CLUSTER="default"; DATA_ROOT="/var/lib/gpu-kitchen"
|
|
# bridge, not host (INS-49): on the host network every listener the image opens
|
|
# is a host-wide claim, and a box that already runs something on 3000 or 8000
|
|
# killed Nitro. Bridged, only the three published ports touch the host; what
|
|
# that costs — the host daemon must be told its LAN address and the engines'
|
|
# docker network — is written to worker.env below. `--network host` remains.
|
|
CACHE_DIR=""; NETWORK="bridge"; CONTROLLER_URL=""; BIN_SRC=""; HEALTH_PORT="8001"
|
|
# 1337, not 8080: kept in lockstep with install.sh's default (INS-01). The
|
|
# worker channel and the inference endpoint move the same way (INS-46).
|
|
ENROLL_TOKEN=""; HTTP_PORT="1337"; MTLS_PORT="8443"; INFERENCE_PORT="8200"
|
|
# Worker data plane (OPS-68): the daemon reads GPUK_DATA_PORT,
|
|
# GPUK_MODEL_TRANSFER_PORT and GPUK_HANDOVER_DATA_PORT from worker.env and
|
|
# announces the first two to the controller, so moving them here is complete.
|
|
DATA_PORT="8300"; TRANSFER_PORT="8301"; HANDOVER_PORT="8302"
|
|
PROFILE=""; DOMAIN=""; NO_DOMAIN=0; DRY_RUN=0; RESET_MANIFEST=0
|
|
while [ $# -gt 0 ]; do
|
|
case "$1" in
|
|
--image) IMAGE="$2"; shift 2 ;;
|
|
--reset-manifest) RESET_MANIFEST=1; shift ;;
|
|
--mode) MODE="$2"; shift 2 ;;
|
|
--cluster) CLUSTER="$2"; shift 2 ;;
|
|
--profile) PROFILE="$2"; shift 2 ;;
|
|
--domain) DOMAIN="$2"; shift 2 ;;
|
|
--no-domain) NO_DOMAIN=1; shift ;;
|
|
--data-root) DATA_ROOT="$2"; shift 2 ;;
|
|
--cache-dir) CACHE_DIR="$2"; shift 2 ;;
|
|
--network) NETWORK="$2"; shift 2 ;;
|
|
--controller) CONTROLLER_URL="$2"; shift 2 ;;
|
|
# `--token` is an ENROLLMENT token (single-use or shared), NOT a bearer:
|
|
# the worker↔controller channel is cert-only since D11. `--token` is kept as
|
|
# a spelling of `--enroll-token`.
|
|
--enroll-token|--token) ENROLL_TOKEN="$2"; shift 2 ;;
|
|
--health-port) HEALTH_PORT="$2"; shift 2 ;;
|
|
--http-port) HTTP_PORT="$2"; shift 2 ;;
|
|
--mtls-port) MTLS_PORT="$2"; shift 2 ;;
|
|
--inference-port) INFERENCE_PORT="$2"; shift 2 ;;
|
|
--data-port) DATA_PORT="$2"; shift 2 ;;
|
|
--transfer-port) TRANSFER_PORT="$2"; shift 2 ;;
|
|
--handover-port) HANDOVER_PORT="$2"; shift 2 ;;
|
|
--binary) BIN_SRC="$2"; shift 2 ;;
|
|
--dry-run) DRY_RUN=1; shift ;;
|
|
*) die "unknown install option: $1" ;;
|
|
esac
|
|
done
|
|
|
|
# Roles, as the backend names them (multi-server/config.ts): "controller" (full
|
|
# app + UI, accepts workers) and "worker" (headless compute node). Historical
|
|
# spellings still work.
|
|
case "$MODE" in
|
|
controller|server|standalone|manager) MODE="controller" ;;
|
|
worker|agent) MODE="worker" ;;
|
|
*) die "--mode must be controller or worker (got '$MODE')" ;;
|
|
esac
|
|
|
|
if [ "$MODE" = "worker" ] && [ -n "$PROFILE" ]; then
|
|
die "--profile applies only to --mode controller; workers do not have an installation profile"
|
|
fi
|
|
if [ "$ENROLL_TOKEN" = "-" ]; then ENROLL_TOKEN=$(enroll_token_from_tty) || exit 1; fi
|
|
|
|
for _pv in "$HTTP_PORT" "$MTLS_PORT" "$INFERENCE_PORT" "$HEALTH_PORT" \
|
|
"$DATA_PORT" "$TRANSFER_PORT" "$HANDOVER_PORT"; do
|
|
case "$_pv" in
|
|
''|*[!0-9]*) die "not a port number: '$_pv'" ;;
|
|
esac
|
|
[ "$_pv" -ge 1 ] && [ "$_pv" -le 65535 ] || die "port out of range: $_pv"
|
|
done
|
|
if [ "$HTTP_PORT" = "$MTLS_PORT" ] || [ "$HTTP_PORT" = "$INFERENCE_PORT" ] || [ "$MTLS_PORT" = "$INFERENCE_PORT" ]; then
|
|
die "--http-port, --mtls-port and --inference-port must differ (got $HTTP_PORT, $MTLS_PORT, $INFERENCE_PORT)"
|
|
fi
|
|
# The worker's four listeners (health + data plane) must differ too; the
|
|
# handover port is the data port's temporary twin (WRK-173), never the same.
|
|
_seen=""
|
|
for _pv in "$HEALTH_PORT" "$DATA_PORT" "$TRANSFER_PORT" "$HANDOVER_PORT"; do
|
|
case " $_seen " in
|
|
*" $_pv "*) die "--health-port, --data-port, --transfer-port and --handover-port must differ (got $HEALTH_PORT, $DATA_PORT, $TRANSFER_PORT, $HANDOVER_PORT)" ;;
|
|
esac
|
|
_seen="$_seen $_pv"
|
|
done
|
|
case "$PROFILE" in
|
|
""|homelab|small-team|managed-network|public) ;;
|
|
*) die "--profile must be homelab, small-team, managed-network or public (got '$PROFILE')" ;;
|
|
esac
|
|
|
|
# [INS-88] The domain is a setting of the install, kept in the manifest (GPUK_DOMAIN):
|
|
# a re-run without --domain keeps it, --no-domain drops it, and everything derived
|
|
# from it (allowed host, trusted proxy, public inference URL) is rendered again.
|
|
[ "$NO_DOMAIN" -eq 0 ] || [ -z "$DOMAIN" ] || die "--domain and --no-domain cannot be combined"
|
|
if [ -z "$DOMAIN" ] && [ "$NO_DOMAIN" -eq 0 ] && [ "$RESET_MANIFEST" -eq 0 ] && [ -f "$MANIFEST" ]; then
|
|
DOMAIN=$(manifest_env_value GPUK_DOMAIN)
|
|
fi
|
|
if [ -n "$DOMAIN" ]; then
|
|
case "$DOMAIN" in
|
|
*[!A-Za-z0-9.-]*) die "--domain must be a bare domain name (got '$DOMAIN')" ;;
|
|
esac
|
|
fi
|
|
|
|
if [ "$MODE" = "controller" ]; then
|
|
if [ -z "$IMAGE" ] && [ "$DRY_RUN" -eq 1 ]; then
|
|
IMAGE="example.invalid/gpukitchen-controller:v0.0.0-dry-run"
|
|
fi
|
|
[ -n "$IMAGE" ] || die "--image registry/gpukitchen-controller:<tag> is required for a controller"
|
|
case "$IMAGE" in
|
|
*@sha256:*) ;;
|
|
*:latest) die "refusing floating image tag '$IMAGE' — use an explicit release tag or digest" ;;
|
|
*)
|
|
_image_tag="${IMAGE##*:}"
|
|
case "$_image_tag" in
|
|
"$IMAGE"|*/*) die "controller image must carry an explicit tag or sha256 digest (got '$IMAGE')" ;;
|
|
esac
|
|
;;
|
|
esac
|
|
fi
|
|
[ -n "$CACHE_DIR" ] || CACHE_DIR="$DATA_ROOT/hf"
|
|
|
|
CACHE_JSON="[{\"hostPath\":\"$(json_str "$CACHE_DIR")\",\"shared\":false}]"
|
|
SELF_ENROLL_FILE="$DATA_ROOT/self-enroll-token"
|
|
BOOTSTRAP_PASSWORD_FILE="$DATA_ROOT/secrets/bootstrap_admin_password"
|
|
CLAIM_KEY_FILE="$DATA_ROOT/secrets/claim_key"
|
|
CLAIM_KEY_AVAILABLE=0
|
|
|
|
# ── Docker's port proxy (INS-84) ─────────────────────────────────────────────
|
|
# A bridged controller trusts the bridge gateway as "this machine": with Docker's
|
|
# NAT rules, only a connection opened on the host itself arrives through it. When
|
|
# Docker relays EVERY published connection through its userland proxy (rootless,
|
|
# or iptables turned off), every visitor arrives as the gateway, and the local
|
|
# posture would let the Internet in. Refused, naming the way out — a dry run too.
|
|
if [ "$MODE" = "controller" ] && [ "$NETWORK" != "host" ] && docker_relays_every_client; then
|
|
die "Docker on this host relays every published connection through its port proxy (rootless Docker, or \"iptables\": false), so GPU Kitchen cannot tell a visitor from this machine. Re-run with --network host."
|
|
fi
|
|
|
|
# ── Internet reachability (INS-89, INS-93) ───────────────────────────────────
|
|
# Home lab lets in, without signing in, whoever reaches the control port. On a
|
|
# machine the Internet reaches, that is everyone: refused, a dry run too. Whatever
|
|
# the profile, the public address is handed to the controller, which refuses a
|
|
# later switch to Home lab in Settings on the same ground.
|
|
HOST_PUBLIC_IPV4=""
|
|
if [ "$MODE" = "controller" ]; then
|
|
_reach=$(reach_findings)
|
|
HOST_PUBLIC_IPV4=$(public_ipv4_of "$_reach")
|
|
if [ "$PROFILE" = "homelab" ]; then
|
|
_refusal=$(homelab_refusal_reason "$_reach")
|
|
[ -z "$_refusal" ] || die "$_refusal"
|
|
_note=$(global_ipv6_note "$_reach")
|
|
[ -z "$_note" ] || echo "==> note: $_note"
|
|
fi
|
|
fi
|
|
|
|
PROXY_GATEWAY=""
|
|
if [ "$MODE" = "controller" ] && [ "$PROFILE" = "public" ]; then
|
|
PROXY_GATEWAY=$(docker_bridge_gateway)
|
|
fi
|
|
|
|
if [ "$DRY_RUN" -eq 1 ]; then
|
|
case "$MODE:$PROFILE" in
|
|
controller:homelab|controller:small-team) ;;
|
|
controller:*) CLAIM_KEY_AVAILABLE=1 ;;
|
|
esac
|
|
echo "==> dry run: no file, service or container was changed"
|
|
[ ! -f "$MANIFEST" ] \
|
|
|| echo "==> dry run: $MANIFEST exists — this render would be MERGED into it, controller-owned settings kept"
|
|
if [ "$MODE" = "worker" ]; then render_worker_manifest; else render_controller_manifest; fi
|
|
[ -z "$DOMAIN" ] || echo "==> dry run: would write $DATA_ROOT/caddy/Caddyfile for $DOMAIN"
|
|
return 0
|
|
fi
|
|
|
|
# ── Port conflicts (INS-46) — the mutator's own guard ────────────────────────
|
|
# install.sh's preflight already checks these, and on a terminal it offers an
|
|
# alternative port. gpuk is the actual mutator and contributors call it
|
|
# DIRECTLY, so it re-checks and refuses, non-interactively, naming the flag
|
|
# that moves the port. Same helpers as install.sh (both scripts ship standalone
|
|
# from the channel). A listener owned by an existing install is not a conflict:
|
|
# a manifest on disk means the re-run is the update path, and every checked
|
|
# port is then our own; without a manifest, a leftover app container still
|
|
# holds OUR ports — apply() renames and stops it before the new one starts.
|
|
if [ ! -f "$MANIFEST" ]; then
|
|
_port_tool="${GPUK_PORT_CHECK_TOOL:-}"
|
|
case "$_port_tool" in
|
|
""|ss|netstat) ;;
|
|
*) die "GPUK_PORT_CHECK_TOOL must be ss or netstat (got '$_port_tool')" ;;
|
|
esac
|
|
if [ -z "$_port_tool" ]; then
|
|
if command -v ss >/dev/null 2>&1; then _port_tool="ss"
|
|
elif command -v netstat >/dev/null 2>&1; then _port_tool="netstat"; fi
|
|
fi
|
|
_ours=""
|
|
if [ "$MODE" = "controller" ]; then
|
|
_ours=$(leftover_container_ports gpu-kitchen)
|
|
[ -z "$_ours" ] || echo "==> existing app container gpu-kitchen found (ports $_ours): the install replaces it"
|
|
fi
|
|
if [ -z "$_port_tool" ]; then
|
|
echo "==> warning: cannot check for port conflicts (no ss or netstat)"
|
|
else
|
|
if [ "$MODE" = "controller" ]; then
|
|
set -- "$HTTP_PORT:UI:--http-port" \
|
|
"$MTLS_PORT:worker channel:--mtls-port" \
|
|
"$INFERENCE_PORT:inference endpoint:--inference-port"
|
|
else
|
|
# Worker data-plane ports (OPS-68) plus the local health listener.
|
|
set -- "$HEALTH_PORT:worker health:--health-port" \
|
|
"$DATA_PORT:worker data plane:--data-port" \
|
|
"$TRANSFER_PORT:model transfers:--transfer-port" \
|
|
"$HANDOVER_PORT:handover data plane:--handover-port"
|
|
fi
|
|
for _spec in "$@"; do
|
|
_p=${_spec%%:*}; _rest=${_spec#*:}; _label=${_rest%%:*}; _flag=${_rest#*:}
|
|
case " $_ours " in *" $_p "*) continue ;; esac
|
|
_busy=1
|
|
case "$_port_tool" in
|
|
ss) [ -n "$(ss -ltnH "sport = :$_p" 2>/dev/null)" ] || _busy=0 ;;
|
|
netstat)
|
|
netstat -ltn 2>/dev/null \
|
|
| awk -v p="$_p" '{n=split($4,a,":"); if (a[n]==p) found=1} END{exit found?0:1}' \
|
|
|| _busy=0
|
|
;;
|
|
esac
|
|
[ "$_busy" -eq 0 ] && continue
|
|
_owner=$(port_owner "$_port_tool" "$_p")
|
|
_hint="Free it first, then run the install again."
|
|
[ -z "$_flag" ] || _hint="Pass $_flag <p> to choose another port, or free it first."
|
|
die "port $_p ($_label) is already in use by ${_owner:-an unknown process}. $_hint"
|
|
done
|
|
fi
|
|
fi
|
|
|
|
need_root
|
|
lifecycle_lock
|
|
install_binary "$BIN_SRC"
|
|
install_cli
|
|
|
|
mkdir -p "$ETC_DIR" "$DATA_ROOT" "$CACHE_DIR"
|
|
seed_secrets "$DATA_ROOT"
|
|
if [ "$MODE" = "controller" ]; then
|
|
prepare_claim_key
|
|
[ ! -s "$CLAIM_KEY_FILE" ] || CLAIM_KEY_AVAILABLE=1
|
|
fi
|
|
|
|
umask 077
|
|
if [ "$MODE" = "worker" ]; then
|
|
write_worker_manifest
|
|
# Optional env overrides for the daemon (cluster grouping, display name, an
|
|
# explicit controller URL). The enrolled identity carries the controller URL
|
|
# + CA too — this is belt-and-braces / pre-enroll discovery grouping.
|
|
{
|
|
echo "GPUK_CLUSTER=$CLUSTER"
|
|
echo "GPUK_WORKER_HEALTH_PORT=$HEALTH_PORT"
|
|
echo "GPUK_DATA_PORT=$DATA_PORT"
|
|
echo "GPUK_MODEL_TRANSFER_PORT=$TRANSFER_PORT"
|
|
echo "GPUK_HANDOVER_DATA_PORT=$HANDOVER_PORT"
|
|
echo "GPUK_MACHINE_ID_FILE=$MACHINE_ID_FILE"
|
|
echo "NODE_DISPLAY_NAME=$(hostname)"
|
|
[ -n "$CONTROLLER_URL" ] && echo "GPUK_CONTROLLER_URLS=$CONTROLLER_URL"
|
|
} > "$WORKER_ENV"
|
|
chmod 0600 "$WORKER_ENV"
|
|
echo "==> wrote $MANIFEST (worker: no app container)"
|
|
else
|
|
write_controller_manifest
|
|
# The host daemon and app container share DATA_ROOT. Only controller-mode
|
|
# workerd gets this private bootstrap channel; remote workers stay tokenless.
|
|
#
|
|
# A bridged app container (INS-49) needs two more lines, read by the daemon
|
|
# from its OWN env — the daemon runs on the host, not in the container:
|
|
# - GPUK_DATA_HOST: the daemon dials the published mTLS port through docker
|
|
# NAT, so the controller sees it arrive from the bridge gateway (172.17.0.1)
|
|
# and would persist THAT as the node's address (WRK-93). The LAN address is
|
|
# what peers, the proxy and the UI must dial instead.
|
|
# - BACKEND_DOCKER_NETWORK: the engines the daemon launches join the app
|
|
# container's docker network, so the backend and gpuk-proxy reach them by
|
|
# container IP (apps/worker/src/modules/docker.rs, staging/engine.rs).
|
|
# Exactly what dev.sh hands the dev worker; host networking needs neither.
|
|
_data_host=""
|
|
if [ "$NETWORK" != "host" ]; then
|
|
_data_host="${GPUK_DATA_HOST:-$(host_lan_ipv4)}"
|
|
[ -n "$_data_host" ] || echo "==> warning: this host's LAN IPv4 could not be determined (no ip, no hostname -I)." \
|
|
"Set GPUK_DATA_HOST=<lan ip> in $WORKER_ENV, or the controller will address its own worker through the docker bridge."
|
|
fi
|
|
{
|
|
echo "GPUK_CLUSTER=$CLUSTER"
|
|
echo "GPUK_WORKER_HEALTH_PORT=$HEALTH_PORT"
|
|
echo "GPUK_MACHINE_ID_FILE=$MACHINE_ID_FILE"
|
|
echo "GPUK_CONTROLLER_URLS=wss://127.0.0.1:$MTLS_PORT"
|
|
echo "GPUK_SELF_ENROLL_FILE=$SELF_ENROLL_FILE"
|
|
echo "NODE_DISPLAY_NAME=$(hostname)"
|
|
if [ "$NETWORK" != "host" ]; then
|
|
[ -z "$_data_host" ] || echo "GPUK_DATA_HOST=$_data_host"
|
|
echo "BACKEND_DOCKER_NETWORK=$NETWORK"
|
|
fi
|
|
} > "$WORKER_ENV"
|
|
chmod 0600 "$WORKER_ENV"
|
|
echo "==> wrote $MANIFEST (controller: app container $IMAGE, network $NETWORK)"
|
|
fi
|
|
chmod 0600 "$MANIFEST"
|
|
[ -z "$DOMAIN" ] || write_caddyfile
|
|
|
|
write_unit
|
|
systemctl daemon-reload
|
|
echo "==> wrote $UNIT_DEST"
|
|
|
|
# ── Worker: token enrollment before start, or unattended LAN discovery ──
|
|
if [ "$MODE" = "worker" ]; then
|
|
if [ -n "$ENROLL_TOKEN" ]; then
|
|
[ -n "$CONTROLLER_URL" ] || die "--controller wss://<controller>:<port> is required to enroll"
|
|
echo "==> enrolling against $CONTROLLER_URL ..."
|
|
enroll_worker "$CONTROLLER_URL" "$ENROLL_TOKEN" \
|
|
|| die "enrollment failed (bad/expired token, or controller unreachable)"
|
|
else
|
|
if [ -n "$CONTROLLER_URL" ]; then
|
|
echo "==> no token given: the daemon will request admission from $CONTROLLER_URL and wait"
|
|
echo " for automatic admission or administrator approval."
|
|
else
|
|
echo "==> no token or controller given: the daemon will discover its cluster on the LAN and wait"
|
|
echo " for automatic admission or administrator approval."
|
|
fi
|
|
fi
|
|
start_daemon
|
|
echo "==> $SERVICE_NAME enabled and started"
|
|
echo
|
|
rm -f "$ETC_DIR/beta-retired"
|
|
echo "Done. The worker daemon is running${ENROLL_TOKEN:+ and enrolled}."
|
|
echo " Status : gpuk status Logs: gpuk logs"
|
|
hint_existing_caches "$CACHE_DIR"
|
|
return 0
|
|
fi
|
|
|
|
# ── Controller: start the daemon, then bring up the app container ──
|
|
start_daemon
|
|
echo "==> $SERVICE_NAME enabled and started"
|
|
# The pull is the long part of a first install (a multi-GB image) and workerd
|
|
# runs docker with its output captured, so pulling from inside `apply` is
|
|
# minutes of silence that read as a hang. Pull here, on the terminal, where
|
|
# docker's own per-layer progress is what the operator sees; `apply` then finds
|
|
# the image present and skips its pull (INS-03).
|
|
# Feedback only, never the verdict: `apply` pulls again whatever happened here
|
|
# and reports the cause itself (the CI shell gate installs a stub daemon against
|
|
# an image that does not exist anywhere — the daemon's pull is the one that counts).
|
|
if ! docker image inspect "$IMAGE" >/dev/null 2>&1; then
|
|
echo "==> pulling $IMAGE (docker shows the progress per layer) ..."
|
|
docker pull "$IMAGE" \
|
|
|| echo "==> the pull did not complete here; the daemon retries it during apply and reports the cause if it fails again"
|
|
fi
|
|
echo "==> applying manifest — starting the app container and waiting for its health check (up to 60s) ..."
|
|
# No unix socket any more: workerd reconciles the app container in-process from
|
|
# the on-disk manifest (there is no backend to relay through on the very first
|
|
# boot). Steady-state updates go through the daemon over WS.
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" apply \
|
|
|| die "the app container did not come up — the [worker] lines above say why (a [controller] FATAL line names the component and the fix). Full container logs: gpuk logs"
|
|
echo
|
|
rm -f "$ETC_DIR/beta-retired"
|
|
echo "Done. The worker daemon is running and the app container is up."
|
|
echo " Status : gpuk status App logs: gpuk logs Daemon: journalctl -u $SERVICE_NAME"
|
|
hint_existing_caches "$CACHE_DIR"
|
|
}
|
|
|
|
# Worker manifest: cacheDisks and an EMPTY image so
|
|
# has_app_container() is false (apps/worker/src/modules/manifest.rs). No ports, no env,
|
|
# no secretsRef — a worker runs no app container.
|
|
render_worker_manifest() {
|
|
cat <<JSON
|
|
{
|
|
"schemaVersion": 2,
|
|
"image": "",
|
|
"mode": "worker",
|
|
"cluster": "$(json_str "$CLUSTER")",
|
|
"gpus": "all",
|
|
"dataRoot": "$(json_str "$DATA_ROOT")",
|
|
"cacheDisks": $CACHE_JSON
|
|
}
|
|
JSON
|
|
}
|
|
|
|
# Every env key gpuk may ever write into a manifest — conditional ones included.
|
|
# On a re-run the merge sets each of them to the fresh value or DELETES it when the
|
|
# fresh render no longer carries it (a profile change drops GPUK_HSTS); any other
|
|
# key was pushed by the controller and is kept. Keep this list in step with
|
|
# render_controller_manifest.
|
|
INSTALL_ENV_KEYS="NODE_ENV,TZ,GPUK_CLUSTER,GPUK_SELF_ENROLL_FILE,NODE_DISPLAY_NAME,HF_HOME,GPUK_DATA_ROOT,GPUK_INSTALL_PROFILE,GPUK_HSTS,GPUK_SESSION_COOKIE_SECURE,GPUK_BOOTSTRAP_MUST_CHANGE,BACKEND_DOCKER_NETWORK,GPUK_PORT,GPUK_PUBLIC_PORT,GPUK_MTLS_PORT,GPUK_PUBLIC_MTLS_PORT,GPUK_PROXY_PUBLIC_PORT,GPUK_UI_BIND,GPUK_PROXY_PUBLIC_URL,GPUK_DOMAIN,GPUK_ALLOWED_HOSTS,GPUK_TRUST_PROXY,GPUK_TRUSTED_PROXY_CIDRS,GPUK_ACCEPT_SOURCE_CIDRS,GPUK_HOST_PUBLIC_IPV4"
|
|
|
|
# Write the manifest — or, when one exists, MERGE into it (INS-03). Re-running the
|
|
# installer is the update path, and the manifest is not ours alone: since the first
|
|
# install the controller has patched it (extra cache disks, shared origin, eviction,
|
|
# LED binary, ports moved from Settings -> Network…). Rewriting it from flags would
|
|
# silently undo all of that, so the fresh render goes through the daemon's own
|
|
# `install-manifest`, which only replaces what the installer owns (image, mode,
|
|
# cluster, network, data root, ports, secret references, the primary cache disk,
|
|
# the env keys above) and keeps the rest. The first write is the render as-is.
|
|
write_manifest() { # $1 = render function
|
|
if [ -f "$MANIFEST" ] && [ "$RESET_MANIFEST" -eq 1 ]; then
|
|
# The operator's explicit regeneration (WRK-191): the daemon archives the
|
|
# existing document — readable or not — writes the render as-is and NAMES what
|
|
# the archive carried that the render does not. The flags install.sh inherited
|
|
# from the old file (ports, profile, data root) are already in the render.
|
|
"$1" > "$MANIFEST.new"
|
|
chmod 0600 "$MANIFEST.new"
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" install-manifest \
|
|
--from "$MANIFEST.new" --reset >/dev/null \
|
|
|| { rm -f "$MANIFEST.new"; die "could not reset $MANIFEST — the [worker] line above names the cause"; }
|
|
rm -f "$MANIFEST.new"
|
|
echo "==> $MANIFEST rebuilt from this install's settings (--reset-manifest); the previous file is archived beside it"
|
|
elif [ -f "$MANIFEST" ]; then
|
|
"$1" > "$MANIFEST.new"
|
|
chmod 0600 "$MANIFEST.new"
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" install-manifest \
|
|
--from "$MANIFEST.new" --own-env "$INSTALL_ENV_KEYS" >/dev/null \
|
|
|| {
|
|
rm -f "$MANIFEST.new"
|
|
die "could not merge the new settings into $MANIFEST — the [worker] line above names the cause.
|
|
A manifest written by an older release can carry a field this release removed. Re-run the same
|
|
command with --reset-manifest: the file is archived beside itself as manifest.json.before-reset.<time>,
|
|
rebuilt from this install's settings, and every setting the archive carried that the rebuild does
|
|
not (extra cache disks, LED binary, eviction…) is listed so you can set it again from the UI."
|
|
}
|
|
rm -f "$MANIFEST.new"
|
|
echo "==> merged into the existing $MANIFEST (controller-owned settings kept)"
|
|
else
|
|
"$1" > "$MANIFEST"
|
|
fi
|
|
}
|
|
|
|
write_worker_manifest() { write_manifest render_worker_manifest; }
|
|
|
|
# Controller manifest: the declarative app-container description workerd applies.
|
|
render_controller_manifest() {
|
|
# NOTE there is deliberately no PORT here: PORT is the backend's own port, a
|
|
# loopback-only 8000 behind nginx in the all-in-one image. What the outside world
|
|
# dials is GPUK_PUBLIC_PORT (the published host port), which falls back to nginx's
|
|
# own GPUK_PORT when nothing republishes it.
|
|
EXTRA_ENV=""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_DATA_ROOT\":\"$(json_str "$DATA_ROOT")\""
|
|
HOST_TZ=$(host_timezone)
|
|
[ -z "$HOST_TZ" ] || EXTRA_ENV="$EXTRA_ENV,\"TZ\":\"$(json_str "$HOST_TZ")\""
|
|
[ -z "$PROFILE" ] || EXTRA_ENV="$EXTRA_ENV,\"GPUK_INSTALL_PROFILE\":\"$(json_str "$PROFILE")\""
|
|
[ -z "${HOST_PUBLIC_IPV4:-}" ] \
|
|
|| EXTRA_ENV="$EXTRA_ENV,\"GPUK_HOST_PUBLIC_IPV4\":\"$(json_str "$HOST_PUBLIC_IPV4")\""
|
|
if [ "$PROFILE" = "public" ]; then
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_HSTS\":\"true\""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_SESSION_COOKIE_SECURE\":\"true\""
|
|
fi
|
|
# SEC-16: the DNS-rebinding Host guard stays on during the anonymous first run even
|
|
# under `enforced`, so the operator's own name must be a known host of the install
|
|
# before the wizard can load through it — whatever the profile. SEC-15: that name
|
|
# is served through a reverse proxy, whose X-Forwarded-For carries the real client.
|
|
# [INS-85] [PRX-97] The same front serves inference.$DOMAIN: the proxy container must read
|
|
# its X-Forwarded-For too (loopback is its only trusted hop), or every client is
|
|
# 127.0.0.1 to source bindings, IP affinity and usage.
|
|
# [INS-87] Under `public` the proxy binds the Docker bridge gateway only, and the TLS
|
|
# front dials it there: that gateway is then the proxy's trusted hop, and the address
|
|
# tools are given is https://$DOMAIN/v1.
|
|
PROXY_ENV_JSON=""
|
|
PROXY_ADDR_JSON=""
|
|
if [ "$PROFILE" = "public" ]; then
|
|
PROXY_ADDR_JSON=",
|
|
\"listenAddress\": \"$(json_str "$PROXY_GATEWAY")\""
|
|
fi
|
|
# [PRX-133] Under `public` the proxy also keeps only connections from this machine and
|
|
# its Docker bridges: a neighbour routing to the bridge address is closed at accept.
|
|
PROXY_ENV=""
|
|
[ "$PROFILE" != "public" ] || PROXY_ENV="\"GPUK_ACCEPT_SOURCE_CIDRS\": \"127.0.0.0/8,bridges\""
|
|
if [ -n "$DOMAIN" ]; then
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_DOMAIN\":\"$(json_str "$DOMAIN")\""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_ALLOWED_HOSTS\":\"$(json_str "$DOMAIN")\""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_TRUST_PROXY\":\"true\""
|
|
PROXY_ENV="${PROXY_ENV:+$PROXY_ENV, }\"GPUK_TRUST_PROXY\": \"true\""
|
|
if [ "$PROFILE" = "public" ]; then
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_PROXY_PUBLIC_URL\":\"https://$(json_str "$DOMAIN")/v1\""
|
|
PROXY_ENV="$PROXY_ENV, \"GPUK_TRUSTED_PROXY_CIDRS\": \"$(json_str "$PROXY_GATEWAY")/32\""
|
|
fi
|
|
fi
|
|
[ -z "$PROXY_ENV" ] || PROXY_ENV_JSON=",
|
|
\"env\": { $PROXY_ENV }"
|
|
BOOTSTRAP_SECRET_JSON=""
|
|
if [ -s "$BOOTSTRAP_PASSWORD_FILE" ]; then
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_BOOTSTRAP_MUST_CHANGE\":\"1\""
|
|
BOOTSTRAP_SECRET_JSON=",\"GPUK_BOOTSTRAP_ADMIN_PASSWORD\":\"$(json_str "$BOOTSTRAP_PASSWORD_FILE")\""
|
|
fi
|
|
CLAIM_SECRET_JSON=""
|
|
if [ "$CLAIM_KEY_AVAILABLE" -eq 1 ]; then
|
|
CLAIM_SECRET_JSON=",\"GPUK_CLAIM_KEY\":\"$(json_str "$CLAIM_KEY_FILE")\""
|
|
fi
|
|
[ "$NETWORK" = "host" ] || EXTRA_ENV="$EXTRA_ENV,\"BACKEND_DOCKER_NETWORK\":\"$(json_str "$NETWORK")\""
|
|
|
|
# Published != bound (INS-43). On a bridged network the container keeps the image's
|
|
# FIXED listeners — nginx 8080, worker mTLS 8443 — and the port flags only move the
|
|
# HOST side of the publication; Settings -> Network moves it later by patching this
|
|
# same manifest, so the container port must never become a variable. With host
|
|
# networking nothing is published and the listeners themselves take the ports
|
|
# (core/published-ports.ts reads this back with the same rules).
|
|
# The inference port is neither: gpuk-proxy runs in its OWN container on the host
|
|
# network in both modes (PRX-84) and binds it itself — proxy.listenPort, which the
|
|
# daemon turns into the proxy's GPUK_LISTEN_ADDR. GPUK_PROXY_PUBLIC_PORT is what the
|
|
# backend shows (core/cluster-settings.ts proxyPublicPort).
|
|
# [INS-83] Under `public` the plain-HTTP UI port answers on this machine's loopback
|
|
# only: the TLS front on the host is the one way in, so a password never crosses
|
|
# the Internet in clear by http://<public-ip>:<port>. The mTLS port stays on every
|
|
# interface — workers pin the controller CA and must reach it directly.
|
|
PORTS_JSON="{}"
|
|
LOOPBACK_JSON=""
|
|
if [ "$NETWORK" = "host" ]; then
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_PORT\":\"$(json_str "$HTTP_PORT")\""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_MTLS_PORT\":\"$(json_str "$MTLS_PORT")\""
|
|
[ "$PROFILE" != "public" ] || EXTRA_ENV="$EXTRA_ENV,\"GPUK_UI_BIND\":\"127.0.0.1\""
|
|
else
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_PORT\":\"8080\""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_PUBLIC_PORT\":\"$(json_str "$HTTP_PORT")\""
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_PUBLIC_MTLS_PORT\":\"$(json_str "$MTLS_PORT")\""
|
|
PORTS_JSON="{\"8080\":$HTTP_PORT,\"8443\":$MTLS_PORT}"
|
|
[ "$PROFILE" != "public" ] || LOOPBACK_JSON="
|
|
\"loopbackPorts\": [\"8080\"],"
|
|
fi
|
|
EXTRA_ENV="$EXTRA_ENV,\"GPUK_PROXY_PUBLIC_PORT\":\"$(json_str "$INFERENCE_PORT")\""
|
|
|
|
cat <<JSON
|
|
{
|
|
"schemaVersion": 2,
|
|
"image": "$(json_str "$IMAGE")",
|
|
"containerName": "gpu-kitchen",
|
|
"mode": "controller",
|
|
"cluster": "$(json_str "$CLUSTER")",
|
|
"networkMode": "$(json_str "$NETWORK")",
|
|
"gpus": "all",
|
|
"restartPolicy": "unless-stopped",
|
|
"dataRoot": "$(json_str "$DATA_ROOT")",
|
|
"cacheDisks": $CACHE_JSON,
|
|
"ports": $PORTS_JSON,$LOOPBACK_JSON
|
|
"env": {
|
|
"NODE_ENV": "production",
|
|
"GPUK_CLUSTER": "$(json_str "$CLUSTER")",
|
|
"GPUK_SELF_ENROLL_FILE": "$(json_str "$SELF_ENROLL_FILE")",
|
|
"NODE_DISPLAY_NAME": "$(json_str "$(hostname)")",
|
|
"HF_HOME": "$(json_str "$CACHE_DIR")"$EXTRA_ENV
|
|
},
|
|
"secretsRef": {
|
|
"ENCRYPTION_KEY": "$(json_str "$DATA_ROOT/secrets/encryption_key")",
|
|
"NODE_ID": "$(json_str "$DATA_ROOT/secrets/node_id")"$BOOTSTRAP_SECRET_JSON$CLAIM_SECRET_JSON
|
|
},
|
|
"proxy": {
|
|
"containerName": "gpu-kitchen-proxy",
|
|
"listenPort": $INFERENCE_PORT$PROXY_ADDR_JSON$PROXY_ENV_JSON
|
|
}
|
|
}
|
|
JSON
|
|
}
|
|
|
|
write_controller_manifest() { write_manifest render_controller_manifest; }
|
|
|
|
# ── control subcommands ────────────────────────────────────────────────────────
|
|
container_name() {
|
|
sed -n 's/.*"containerName"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -1
|
|
}
|
|
|
|
# The proxy's own container (PRX-84): the second containerName of the manifest —
|
|
# the app container's comes first, the proxy section closes the document.
|
|
proxy_container_name() {
|
|
_pcn=$(sed -n 's/.*"containerName"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | sed -n 2p)
|
|
printf '%s' "${_pcn:-gpu-kitchen-proxy}"
|
|
}
|
|
|
|
manifest_env_value() { # $1 = key of a string field of the manifest
|
|
sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$MANIFEST" 2>/dev/null | head -1
|
|
}
|
|
|
|
manifest_data_root() {
|
|
sed -n 's/.*"dataRoot"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -1
|
|
}
|
|
|
|
manifest_image() {
|
|
sed -n 's/.*"image"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$MANIFEST" 2>/dev/null | head -1
|
|
}
|
|
|
|
manifest_env() { # $1 = env key of the app container
|
|
sed -n "s/.*\"$1\"[[:space:]]*:[[:space:]]*\"\([^\"]*\)\".*/\1/p" "$MANIFEST" 2>/dev/null | head -1
|
|
}
|
|
|
|
# [SEC-72] The one-time setup link, rebuilt from the key file the controller unlinks once
|
|
# the first account exists. Empty when the key is gone (consumed) or was never made
|
|
# (homelab, small-team, worker). The UI port is the published one when the app is bridged.
|
|
setup_url() {
|
|
_kf="$(manifest_data_root)/secrets/claim_key"
|
|
[ -s "$_kf" ] || return 0
|
|
_up=$(manifest_env GPUK_PUBLIC_PORT); [ -n "$_up" ] || _up=$(manifest_env GPUK_PORT)
|
|
_host=$(hostname -f 2>/dev/null || hostname 2>/dev/null || echo localhost)
|
|
printf 'http://%s:%s/start?key=%s' "$_host" "${_up:-8080}" "$(cat "$_kf")"
|
|
}
|
|
|
|
health_port() {
|
|
sed -n 's/.*GPUK_WORKER_HEALTH_PORT=\([0-9]*\).*/\1/p' "$WORKER_ENV" 2>/dev/null | head -1
|
|
}
|
|
|
|
# Split an image reference into repository and tag.
|
|
#
|
|
# `${img%%:*}` cuts at the FIRST colon and is WRONG:
|
|
# `registry.internal:5000/gpuk/controller:v1.2.3` would yield repo
|
|
# `registry.internal`. The colon in a registry's host:port is not a tag separator.
|
|
# Rule: it is a tag only if the last colon comes after the last slash.
|
|
# (Same logic as apps/controller/api/src/core/release-channel.ts — see its unit tests.)
|
|
image_repo() {
|
|
# A digest suffix (…@sha256:…) never carries the repo; drop it, then apply
|
|
# the tag logic — `repo:tag@sha256:…` and `repo@sha256:…` both reduce right.
|
|
set -- "${1%@*}"
|
|
_t="${1##*:}"
|
|
case "$_t" in
|
|
"$1") printf '%s' "$1" ;; # no colon at all → untagged
|
|
*/*) printf '%s' "$1" ;; # the last colon is inside a path → host:port, untagged
|
|
*) printf '%s' "${1%:*}" ;;
|
|
esac
|
|
}
|
|
|
|
image_tag() {
|
|
# `repo:tag@sha256:…` keeps the human-readable tag next to the content pin —
|
|
# docker resolves by digest and ignores the tag. Strip the digest, then parse.
|
|
set -- "${1%@*}"
|
|
_t="${1##*:}"
|
|
case "$_t" in
|
|
"$1") return ;;
|
|
*/*) return ;;
|
|
*) printf '%s' "$_t" ;;
|
|
esac
|
|
}
|
|
|
|
# The release channel: one flat JSON document served next to the installer. The
|
|
# UI's update check reads the same one (apps/controller/api/src/core/release-channel.ts) — one
|
|
# source of truth. Interim default: the public Gitea channel repo — flips to
|
|
# https://gpu.kitchen/latest.json once the hub exists (specs/developpement/ci-cd/README.md).
|
|
CHANNEL_URL="${GPUK_CHANNEL_URL:-https://repo.byterain.io/gpukitchen/channel/raw/branch/main/latest.json}"
|
|
|
|
# The release public key pinned in THIS copy of gpuk (OPS-20). The channel copy
|
|
# gets the real key substituted at publish time; the operator override
|
|
# (GPUK_UPDATE_PUBKEY) covers a self-hosted channel with its own keypair. The
|
|
# first install fetched gpuk itself over HTTPS from the channel — that moment is
|
|
# trust-on-first-use, like a worker's enrolment token pin; every later `update`
|
|
# is verified against the key pinned HERE, so whoever controls latest.json can
|
|
# no longer pick what an existing install runs.
|
|
CHANNEL_PUBKEY="${GPUK_UPDATE_PUBKEY:-RWQ7BKXJqGX2jdKXu1GxeSPVAN3JDRTefpImM/mFRjtFwq4E7mhnQtA7}"
|
|
|
|
# The pinned key and the minisign CLI every verification needs (channel
|
|
# document, downloaded daemon binary); fail-closed.
|
|
require_release_key() {
|
|
case "$CHANNEL_PUBKEY" in
|
|
# The unstamped placeholder, matched by its prefix only: the release stamps
|
|
# the key by substituting the whole placeholder wherever it appears, and a
|
|
# guard spelling it in full would become one refusing the very key it pinned.
|
|
""|__GPUK_UPDATE_*)
|
|
die "this gpuk carries no pinned release public key — set GPUK_UPDATE_PUBKEY (the minisign public-key line), or GPUK_CHANNEL_INSECURE=1 to skip verification" ;;
|
|
esac
|
|
ensure_minisign 0
|
|
}
|
|
|
|
# The minisign CLI is what verifies the release; a host without it gets it from
|
|
# its own package manager — detected, non-interactive, quiet — before anything
|
|
# else changes. No known manager, or an install that fails: stop, naming the
|
|
# manual command. GPUK_MINISIGN names another verifier binary (test seam).
|
|
MINISIGN="${GPUK_MINISIGN:-minisign}"
|
|
minisign_manual_command() {
|
|
if command -v apt-get >/dev/null 2>&1; then echo "apt-get install minisign"
|
|
elif command -v dnf >/dev/null 2>&1; then echo "dnf install minisign (EPEL on RHEL)"
|
|
elif command -v yum >/dev/null 2>&1; then echo "yum install minisign (EPEL)"
|
|
elif command -v zypper >/dev/null 2>&1; then echo "zypper install minisign"
|
|
elif command -v apk >/dev/null 2>&1; then echo "apk add minisign"
|
|
elif command -v pacman >/dev/null 2>&1; then echo "pacman -S minisign"
|
|
else echo "install minisign from https://jedisct1.github.io/minisign/"
|
|
fi
|
|
}
|
|
ensure_minisign() { # $1 = 1 when nothing may be installed (dry run)
|
|
command -v "$MINISIGN" >/dev/null 2>&1 && return 0
|
|
[ "${1:-0}" -eq 0 ] \
|
|
|| die "minisign is required to verify the release and a dry run installs nothing: $(minisign_manual_command), or set GPUK_CHANNEL_INSECURE=1"
|
|
_mlog=$(mktemp)
|
|
for _pm in apt-get dnf yum zypper apk pacman; do
|
|
command -v "$_pm" >/dev/null 2>&1 || continue
|
|
echo "==> minisign is missing — installing it with $_pm"
|
|
case "$_pm" in
|
|
apt-get) { DEBIAN_FRONTEND=noninteractive apt-get update -qq \
|
|
&& DEBIAN_FRONTEND=noninteractive apt-get install -y -qq minisign; } ;;
|
|
dnf) dnf install -y -q minisign ;;
|
|
yum) yum install -y -q minisign ;;
|
|
zypper) zypper --non-interactive --quiet install minisign ;;
|
|
apk) apk add --quiet minisign ;;
|
|
pacman) pacman -S --noconfirm --needed --quiet minisign ;;
|
|
esac >"$_mlog" 2>&1 || true
|
|
if command -v "$MINISIGN" >/dev/null 2>&1; then rm -f "$_mlog"; return 0; fi
|
|
done
|
|
tail -5 "$_mlog" >&2 2>/dev/null || true
|
|
rm -f "$_mlog"
|
|
die "minisign is required to verify the release and could not be installed automatically. Nothing was changed: run '$(minisign_manual_command)' as root, then re-run — or set GPUK_CHANNEL_INSECURE=1"
|
|
}
|
|
|
|
# Fetch latest.json AND its minisign signature, verify, and leave the verified
|
|
# document at $CHANNEL_DOC. Fail-closed: no signature, bad signature, no
|
|
# minisign CLI or no pinned key are all fatal — GPUK_CHANNEL_INSECURE=1 is the
|
|
# explicit, logged opt-out (a private mirror that does not sign).
|
|
CHANNEL_DOC=""
|
|
CHANNEL_MAX_TIME=20
|
|
channel_fetch() {
|
|
command -v curl >/dev/null 2>&1 || return 1
|
|
CHANNEL_DOC=$(mktemp) || return 1
|
|
curl -fsSL --max-time "$CHANNEL_MAX_TIME" "$CHANNEL_URL" -o "$CHANNEL_DOC" 2>/dev/null || return 1
|
|
if [ "${GPUK_CHANNEL_INSECURE:-}" = "1" ]; then
|
|
echo "WARNING: GPUK_CHANNEL_INSECURE=1 — release channel signature NOT verified" >&2
|
|
return 0
|
|
fi
|
|
require_release_key
|
|
_sig=$(mktemp)
|
|
if ! curl -fsSL --max-time "$CHANNEL_MAX_TIME" "${CHANNEL_URL}.minisig" -o "$_sig" 2>/dev/null; then
|
|
rm -f "$_sig"
|
|
die "no signature at ${CHANNEL_URL}.minisig — refusing an unsigned channel document (OPS-20)"
|
|
fi
|
|
if ! "$MINISIGN" -Vq -m "$CHANNEL_DOC" -x "$_sig" -P "$CHANNEL_PUBKEY" >/dev/null 2>&1; then
|
|
rm -f "$_sig"
|
|
die "latest.json signature verification FAILED — refusing the channel document (OPS-20)"
|
|
fi
|
|
rm -f "$_sig"
|
|
}
|
|
|
|
channel_field() {
|
|
sed -n 's/.*"'"$2"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" | head -1
|
|
}
|
|
|
|
channel_version() {
|
|
channel_fetch || return 1
|
|
channel_field "$CHANNEL_DOC" version
|
|
}
|
|
|
|
# [OPS-10] [OPS-102] After a cold stop: start the daemon, then bring the app container back by
|
|
# applying the manifest, as `gpuk apply` does. Starting the daemon alone does not: it does not
|
|
# re-create the app container, and Docker never restarts a container that was stopped by hand
|
|
# (unless-stopped) — a real installation stayed down after `gpuk backup`.
|
|
restart_controller() {
|
|
systemctl start "$SERVICE_NAME" || return 1
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" apply >/dev/null
|
|
}
|
|
|
|
# ── backup ─────────────────────────────────────────────────────────────────────
|
|
# OPS-10: the embedded Postgres is only backed up COLD — hot-copying pgdata with
|
|
# a file tool is forbidden (torn pages). Order matters: stop the DAEMON first
|
|
# (its reconciler would immediately restart a stopped app container), then the
|
|
# container, snapshot, then restart_controller brings both back.
|
|
# An install on an external DATABASE_URL is refused here: gpuk only owns the
|
|
# embedded pgdata — back the real database up with pg_dump/backup-compose.sh.
|
|
# The finished directory still has to be copied to encrypted off-host storage,
|
|
# next to the recovery set (OPS-04/OPS-05: ENCRYPTION_KEY above all).
|
|
# [OPS-10] The database must be at rest: only a container Docker CONFIRMS stopped, or
|
|
# confirms absent, lets a copy or a second server open pgdata. A Docker that cannot say
|
|
# (daemon down, timeout) is a refusal, never "absent".
|
|
stop_app_container() {
|
|
docker stop "$1" >/dev/null 2>&1 || true
|
|
if ! _state=$(docker inspect -f '{{.State.Status}}' "$1" 2>&1); then
|
|
case "$_state" in
|
|
*"No such object"*|*"No such container"*) return 0 ;;
|
|
esac
|
|
die "cannot read the state of $1 — refusing $2"
|
|
fi
|
|
case "$_state" in
|
|
exited|created|dead) ;;
|
|
*) die "container $1 is $_state — refusing $2" ;;
|
|
esac
|
|
}
|
|
|
|
cmd_backup() {
|
|
need_root
|
|
lifecycle_lock
|
|
# [OPS-90] --offsite: once published, the archive goes off this host through the command
|
|
# named in $ETC_DIR/offsite.env (offsite-restic.sh, which reads its settings there too).
|
|
_offsite=0
|
|
_out=""
|
|
for _a in "$@"; do
|
|
case "$_a" in
|
|
--offsite) _offsite=1 ;;
|
|
-*) die "unknown backup option: $_a" ;;
|
|
*) _out="$_a" ;;
|
|
esac
|
|
done
|
|
_offsite_env="$ETC_DIR/offsite.env"
|
|
_offsite_cmd=""
|
|
if [ "$_offsite" -eq 1 ]; then
|
|
[ -f "$_offsite_env" ] || die "--offsite needs $_offsite_env (GPUK_BACKUP_OFFSITE_CMD and the GPUK_OFFSITE_* settings)"
|
|
_offsite_cmd=$(sed -n "s/^GPUK_BACKUP_OFFSITE_CMD=//p" "$_offsite_env" | tail -n 1 | tr -d "'")
|
|
[ -x "$_offsite_cmd" ] || die "GPUK_BACKUP_OFFSITE_CMD in $_offsite_env is not an executable: '$_offsite_cmd'"
|
|
fi
|
|
_img=$(manifest_image)
|
|
[ -n "$_img" ] || die "this is a worker node — no controller data to back up here"
|
|
if grep -q '"DATABASE_URL"' "$MANIFEST" 2>/dev/null; then
|
|
die "this install uses an external DATABASE_URL — back THAT database up (pg_dump); gpuk backup only snapshots the embedded pgdata"
|
|
fi
|
|
_root=$(manifest_data_root)
|
|
[ -n "$_root" ] || die "no dataRoot in $MANIFEST"
|
|
[ -d "$_root/pgdata" ] || die "no embedded pgdata under $_root — nothing to snapshot"
|
|
command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required"
|
|
|
|
_out="${_out:-$_root/backups/$(date -u +%Y%m%dT%H%M%SZ)}"
|
|
# A dangling link is something too: never write through a path someone else prepared.
|
|
if [ -e "$_out" ] || [ -L "$_out" ]; then die "refusing to overwrite existing $_out"; fi
|
|
mkdir -p "$(dirname "$_out")"
|
|
_tmp="$_out.partial"
|
|
# [OPS-109] Private BEFORE the first byte: a local user who opens the archive while it is
|
|
# written keeps reading it after a later chmod. The restart gets the caller's umask back.
|
|
_umask=$(umask)
|
|
umask 077
|
|
# rm removes a planted link itself, and mkdir without -p refuses whatever reappears.
|
|
rm -rf "$_tmp"; mkdir -m 0700 "$_tmp" || die "cannot create $_tmp"
|
|
|
|
_cn=$(container_name)
|
|
echo "==> Stopping $SERVICE_NAME (its reconciler would restart the container mid-snapshot)..."
|
|
systemctl stop "$SERVICE_NAME" || die "could not stop $SERVICE_NAME"
|
|
_restart_daemon() { umask "$_umask"; restart_controller 2>/dev/null || true; }
|
|
trap _restart_daemon EXIT
|
|
if [ -n "$_cn" ]; then
|
|
echo "==> Stopping $_cn (cold snapshot — OPS-10)..."
|
|
stop_app_container "$_cn" "a hot snapshot"
|
|
fi
|
|
|
|
echo "==> Snapshotting $_root/pgdata..."
|
|
tar -C "$_root" -czf "$_tmp/pgdata.tar.gz" pgdata || die "snapshot failed"
|
|
cp "$MANIFEST" "$_tmp/host-manifest.json" 2>/dev/null || true
|
|
{
|
|
echo "{"
|
|
echo " \"created_utc\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\","
|
|
echo " \"image\": \"$(json_str "$_img")\","
|
|
echo " \"data_root\": \"$(json_str "$_root")\","
|
|
echo " \"kind\": \"cold-pgdata-snapshot\""
|
|
echo "}"
|
|
} > "$_tmp/backup-manifest.json"
|
|
(cd "$_tmp" && sha256sum ./* > SHA256SUMS) || die "checksums failed"
|
|
chmod 0700 "$_tmp"
|
|
mv -T "$_tmp" "$_out" || die "cannot publish $_out"
|
|
|
|
echo "==> Restarting $SERVICE_NAME and the app container..."
|
|
trap - EXIT
|
|
umask "$_umask"
|
|
restart_controller || die "could not restart GPU Kitchen — run: sudo gpuk apply"
|
|
echo "backup: $_out"
|
|
if [ "$_offsite" -eq 1 ]; then
|
|
echo "==> Copying $_out off this host..."
|
|
GPUK_OFFSITE_ENV="$_offsite_env" "$_offsite_cmd" "$_out" \
|
|
|| die "the off-site copy of $_out failed: the archive is on this host only"
|
|
echo "Off-site copy done. Keep the recovery set off this host too"
|
|
echo "(ENCRYPTION_KEY above all — without it the data is unrecoverable, OPS-04)."
|
|
return 0
|
|
fi
|
|
echo "Copy it to encrypted OFF-HOST storage together with the recovery set"
|
|
echo "(ENCRYPTION_KEY above all — without it the data is unrecoverable, OPS-04)."
|
|
echo "A physical pgdata restore requires the same Postgres major and a throwaway"
|
|
echo "host rehearsal first (OPS-10)."
|
|
}
|
|
|
|
# ── carry-over ─────────────────────────────────────────────────────────────────
|
|
# [OPS-100] [OPS-101] [OPS-102] Copies the recipes, templates, benchmarks, evaluations and baskets of a
|
|
# backup into THIS installation's database — what a reinstall on a new database baseline would
|
|
# otherwise lose. Not a restore (OPS-09): the live database is never dropped or replaced; it
|
|
# receives those rows, with the engines, models and GPU configs they use, in one transaction.
|
|
# The work is the image's own (deployments/controller/carry-over.sh: reset-db's table list and
|
|
# rules), in a one-off container of the installed image, the controller stopped as for a backup.
|
|
CARRY_OVER_SCRIPT=/usr/local/lib/gpuk-controller/carry-over/carry-over.sh
|
|
CARRY_OVER_CONTAINER=gpu-kitchen-carry-over
|
|
|
|
# Prints the SHA256SUMS line of one file, named as `sha256sum -c` reads it from its folder.
|
|
checksum_line() { # $1 = folder, $2 = file name
|
|
while read -r _sum _name; do
|
|
case "$_name" in
|
|
"$2"|"./$2"|"*$2"|"*./$2") printf '%s %s\n' "$_sum" "$2" ;;
|
|
esac
|
|
done <"$1/SHA256SUMS"
|
|
}
|
|
|
|
cmd_carry_over() {
|
|
# [OPS-109] Whatever this writes beside the copied database stays private; the
|
|
# restart gets the caller's umask back.
|
|
_umask=$(umask)
|
|
umask 077
|
|
need_root
|
|
lifecycle_lock
|
|
_archive=""
|
|
_replace=""
|
|
for _a in "$@"; do
|
|
case "$_a" in
|
|
--replace) _replace=--replace ;;
|
|
-*) die "unknown carry-over option: $_a" ;;
|
|
*) [ -z "$_archive" ] || die "carry-over takes one backup"; _archive="$_a" ;;
|
|
esac
|
|
done
|
|
[ -n "$_archive" ] || die "name the backup: gpuk carry-over <backup folder or .dump file> [--replace]"
|
|
_img=$(manifest_image)
|
|
[ -n "$_img" ] || die "this is a worker node — recipes and benchmarks live on the controller"
|
|
if grep -q '"DATABASE_URL"' "$MANIFEST" 2>/dev/null; then
|
|
die "this install uses an external DATABASE_URL — gpuk carry-over only writes into the embedded database"
|
|
fi
|
|
_root=$(manifest_data_root)
|
|
[ -n "$_root" ] || die "no dataRoot in $MANIFEST"
|
|
_pgdata=$(manifest_env GPUK_PGDATA)
|
|
_pgdata="${_pgdata:-$_root/pgdata}"
|
|
[ -s "$_pgdata/PG_VERSION" ] || die "no database yet under $_pgdata — start GPU Kitchen once first"
|
|
command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required"
|
|
|
|
# The archive: a `gpuk backup` folder, a Compose backup folder, or one pg_dump -Fc file.
|
|
if [ -d "$_archive" ]; then
|
|
_dir=$(cd "$_archive" && pwd)
|
|
if [ -f "$_dir/backup-manifest.json" ] && [ -f "$_dir/pgdata.tar.gz" ]; then
|
|
grep -q '"kind": *"cold-pgdata-snapshot"' "$_dir/backup-manifest.json" \
|
|
|| die "$_dir/backup-manifest.json does not describe a gpuk backup"
|
|
_kind=pgdata
|
|
_file=pgdata.tar.gz
|
|
elif [ -f "$_dir/manifest.env" ] && [ -f "$_dir/backend.dump" ]; then
|
|
grep -qx 'format=gpuk-compose-backup-v1' "$_dir/manifest.env" \
|
|
|| die "$_dir/manifest.env does not describe a Compose backup"
|
|
_kind=dump
|
|
_file=backend.dump
|
|
else
|
|
die "$_dir is neither a gpuk backup (pgdata.tar.gz) nor a Compose backup (backend.dump)"
|
|
fi
|
|
[ -f "$_dir/SHA256SUMS" ] || die "$_dir has no SHA256SUMS: refusing a backup that cannot be checked"
|
|
elif [ -f "$_archive" ]; then
|
|
_dir=$(cd "$(dirname "$_archive")" && pwd)
|
|
_file=$(basename "$_archive")
|
|
_kind=dump
|
|
else
|
|
die "no backup at $_archive"
|
|
fi
|
|
_sum=""
|
|
[ ! -f "$_dir/SHA256SUMS" ] || _sum=$(checksum_line "$_dir" "$_file")
|
|
if [ -n "$_sum" ]; then
|
|
(cd "$_dir" && printf '%s\n' "$_sum" | sha256sum -c --quiet -) >/dev/null 2>&1 \
|
|
|| die "$_dir/$_file does not match its SHA256SUMS: refusing it"
|
|
echo "==> $_file matches its checksum."
|
|
else
|
|
[ "$_kind" = dump ] && [ ! -f "$_dir/backup-manifest.json" ] && [ ! -f "$_dir/manifest.env" ] \
|
|
|| die "$_dir/SHA256SUMS does not list $_file: refusing a backup that cannot be checked"
|
|
echo "==> No checksum next to $_file: PostgreSQL checks the archive as it reads it."
|
|
fi
|
|
|
|
docker image inspect "$_img" >/dev/null 2>&1 \
|
|
|| die "the image $_img is not on this host: run 'gpuk apply' first"
|
|
docker run --rm --network none --entrypoint /bin/sh "$_img" -c "test -x $CARRY_OVER_SCRIPT" \
|
|
>/dev/null 2>&1 || die "this release cannot carry a backup over: update GPU Kitchen first (gpuk update)"
|
|
|
|
_work="$_root/carry-over.$(date -u +%Y%m%dT%H%M%SZ)"
|
|
[ ! -e "$_work" ] || die "refusing to reuse existing $_work"
|
|
_cn=$(container_name)
|
|
echo "==> Stopping $SERVICE_NAME (its reconciler would restart the container during the copy)..."
|
|
systemctl stop "$SERVICE_NAME" || die "could not stop $SERVICE_NAME"
|
|
_carry_over_cleanup() {
|
|
docker rm -f "$CARRY_OVER_CONTAINER" >/dev/null 2>&1 || true
|
|
rm -rf "$_work"
|
|
umask "$_umask"
|
|
restart_controller 2>/dev/null \
|
|
|| echo "gpuk: GPU Kitchen did not restart — run: sudo gpuk apply" >&2
|
|
}
|
|
trap _carry_over_cleanup EXIT
|
|
if [ -n "$_cn" ]; then
|
|
echo "==> Stopping $_cn..."
|
|
stop_app_container "$_cn" "to open its database twice"
|
|
fi
|
|
# Traversable, not listable: the copy's server runs as the image's postgres user.
|
|
mkdir -m 0711 "$_work" || die "cannot create $_work"
|
|
_mount=""
|
|
if [ "$_kind" = pgdata ]; then
|
|
echo "==> Unpacking the backup..."
|
|
tar -C "$_work" -xzf "$_dir/pgdata.tar.gz" || die "could not unpack $_dir/pgdata.tar.gz"
|
|
[ -s "$_work/pgdata/PG_VERSION" ] || die "$_dir/pgdata.tar.gz holds no database"
|
|
_source="$_work/pgdata"
|
|
else
|
|
# The archive's folder, read-only, outside the data root.
|
|
_mount="$_dir:/carry-over/archive:ro"
|
|
_source="/carry-over/archive/$_file"
|
|
fi
|
|
_rc=0
|
|
docker run --rm --name "$CARRY_OVER_CONTAINER" --network none --entrypoint "$CARRY_OVER_SCRIPT" \
|
|
-v "$_root:$_root" ${_mount:+-v "$_mount"} "$_img" \
|
|
--live-pgdata "$_pgdata" "--$_kind" "$_source" $_replace || _rc=$?
|
|
if [ "$_rc" -ne 0 ]; then
|
|
echo "gpuk: nothing was carried over; the installation's database is as it was." >&2
|
|
exit "$_rc"
|
|
fi
|
|
trap - EXIT
|
|
umask "$_umask"
|
|
rm -rf "$_work"
|
|
echo "==> Restarting $SERVICE_NAME and the app container..."
|
|
restart_controller || die "could not restart GPU Kitchen — run: sudo gpuk apply"
|
|
echo "Carried over: recipes, templates, benchmarks, evaluations, baskets and saved charts,"
|
|
echo "with the engines, models and GPU configs they use."
|
|
echo "Not carried over: nodes, GPUs, containers, accounts, keys and settings."
|
|
}
|
|
|
|
# ── channel ────────────────────────────────────────────────────────────────────
|
|
# Diagnostic (no root): fetch + VERIFY the channel document, print what it
|
|
# offers. Exercises exactly the trust chain `update` relies on — the CI probes
|
|
# it with a throwaway keypair, an operator uses it to debug a mirror.
|
|
cmd_channel() {
|
|
channel_fetch || die "cannot fetch $CHANNEL_URL"
|
|
echo "channel : $CHANNEL_URL"
|
|
echo "version : $(channel_field "$CHANNEL_DOC" version)"
|
|
_d=$(channel_field "$CHANNEL_DOC" controllerImageDigest)
|
|
[ -n "$_d" ] && echo "digest : $_d"
|
|
_d=$(channel_field "$CHANNEL_DOC" controllerImageDigestEnterprise)
|
|
[ -n "$_d" ] && echo "digest ee : $_d"
|
|
if [ "${GPUK_CHANNEL_INSECURE:-}" = "1" ]; then
|
|
echo "signature : SKIPPED (GPUK_CHANNEL_INSECURE=1)"
|
|
else
|
|
echo "signature : verified"
|
|
fi
|
|
}
|
|
|
|
# ── status ─────────────────────────────────────────────────────────────────────
|
|
# No control socket any more. Status = the systemd unit state + the daemon's own
|
|
# /health endpoint + whether a worker has enrolled (identity present).
|
|
# [INS-74] Why the daemon is or is not serving, in plain sentences, and how far it is
|
|
# from the release channel. Never a "no" it could not read: without root the identity,
|
|
# the manifest and worker.env are unreadable (0600/0700), which once printed
|
|
# "enrolled: no" for an enrolled worker the controller had refused for its version.
|
|
STATUS_NEEDS_ROOT=0
|
|
readable_or_flag() { # $1 = path; 0 when it can be judged, 1 (and flags) when only root could
|
|
[ -e "$1" ] && [ ! -r "$1" ] && { STATUS_NEEDS_ROOT=1; return 1; }
|
|
[ -x "$(dirname "$1")" ] || { STATUS_NEEDS_ROOT=1; return 1; }
|
|
return 0
|
|
}
|
|
|
|
json_string_field() { # $1 = json text, $2 = key
|
|
printf '%s' "$1" | sed -n 's/.*"'"$2"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1
|
|
}
|
|
|
|
# [INS-74] The sentence for each `connection` code of the daemon's /health answer. The codes
|
|
# are the contract packages/contracts/data/worker-connection-states.json, which a gate holds
|
|
# this function to (every code mapped, no other one).
|
|
connection_sentence() { # $1 = connection code
|
|
case "$1" in
|
|
starting) echo "Starting: not connected to a controller yet." ;;
|
|
connected) echo "Connected to its controller." ;;
|
|
disconnected) echo "Not connected: the controller closed the connection. It reconnects by itself." ;;
|
|
unreachable) echo "Not connected: the controller cannot be reached. It tries again by itself." ;;
|
|
registration_rejected) echo "Not connected: the controller rejected this node. It tries again by itself." ;;
|
|
refused_identity) echo "Refused: the controller removed this node. Enroll it again with a new token." ;;
|
|
refused_trust_anchor) echo "Refused: the controller changed its identity. Enroll this node again with a new token." ;;
|
|
refused_version) echo "Refused by the controller: this node runs a different version. Update it: sudo gpuk update" ;;
|
|
self_updating) echo "Updating itself to the version of its controller." ;;
|
|
*) return 1 ;;
|
|
esac
|
|
}
|
|
|
|
# One sentence from the daemon's own state: systemd's active state, then its /health
|
|
# answer (mode, then connection code). An answer without a connection code is a daemon
|
|
# older than this gpuk; a code this gpuk does not know is a daemon NEWER than it — the
|
|
# daemon updates itself (self-heal, the UI's Update), while gpuk is replaced by
|
|
# `gpuk update` (update_cli).
|
|
daemon_state_sentence() { # $1 = active state, $2 = /health body
|
|
case "$1" in
|
|
active|reloading) ;;
|
|
failed) echo "The service stopped after an error. See why: sudo gpuk logs"; return ;;
|
|
activating) echo "The service is starting."; return ;;
|
|
*) echo "The service is not running. Start it: sudo systemctl start $SERVICE_NAME"; return ;;
|
|
esac
|
|
if [ -z "$2" ]; then echo "The service runs but does not answer yet."; return; fi
|
|
_mode=$(json_string_field "$2" mode)
|
|
_detail=$(json_string_field "$2" detail)
|
|
_connection=$(json_string_field "$2" connection)
|
|
if [ "$_mode" = awaiting_enrollment ]; then
|
|
case "$_detail" in
|
|
explicit_token_required)
|
|
echo "Not enrolled. It needs an enrollment token: on the controller, open Nodes & GPU, then Add nodes." ;;
|
|
ambiguous_controllers)
|
|
echo "Not enrolled. Several controllers answer on this network: enroll it with a token from the right one." ;;
|
|
*)
|
|
echo "Not enrolled yet. It waits for a controller on this network to admit it." ;;
|
|
esac
|
|
return
|
|
fi
|
|
connection_sentence "$_connection" && return
|
|
if [ "$_mode" = protocol_mismatch ]; then
|
|
connection_sentence refused_version
|
|
elif [ -n "$_connection" ]; then
|
|
echo "This daemon is newer than this gpuk, which cannot read its state. Get the current gpuk: sudo gpuk update"
|
|
else
|
|
echo "This daemon is older than this gpuk and does not say its state. Update it: sudo gpuk update"
|
|
fi
|
|
}
|
|
|
|
NVIDIA_SMI="${GPUK_NVIDIA_SMI:-nvidia-smi}"
|
|
gpu_sentence() {
|
|
if ! command -v "$NVIDIA_SMI" >/dev/null 2>&1; then
|
|
echo "none found (the NVIDIA driver tool nvidia-smi is not installed)"; return
|
|
fi
|
|
_n=$(timeout 10 "$NVIDIA_SMI" -L 2>/dev/null | grep -c '^GPU ' || true)
|
|
if [ "${_n:-0}" -eq 0 ]; then echo "none found (nvidia-smi lists no GPU: check the NVIDIA driver)"
|
|
else echo "$_n found"; fi
|
|
}
|
|
|
|
# "<version> <worker build for this arch>" from the verified channel, in a subshell with a
|
|
# short timeout: a mute or unverifiable channel must not stop the status (channel_fetch dies).
|
|
status_channel_offer() {
|
|
(
|
|
CHANNEL_MAX_TIME="${GPUK_STATUS_CHANNEL_TIMEOUT:-5}"
|
|
channel_fetch >/dev/null 2>&1 || exit 1
|
|
case "$(uname -m)" in
|
|
aarch64|arm64) _bkey=workerBuildIdAarch64 ;;
|
|
*) _bkey=workerBuildIdX86_64 ;;
|
|
esac
|
|
_v=$(channel_field "$CHANNEL_DOC" version)
|
|
_b=$(channel_field "$CHANNEL_DOC" "$_bkey")
|
|
rm -f "$CHANNEL_DOC"
|
|
[ -n "$_v" ] || exit 1
|
|
printf '%s %s\n' "$_v" "$_b"
|
|
) 2>/dev/null
|
|
}
|
|
|
|
cmd_status() {
|
|
_active=$(systemctl is-active "$SERVICE_NAME" 2>/dev/null || true)
|
|
echo "service : ${_active:-unknown}"
|
|
|
|
if [ -f "$IDENTITY_DIR/identity.json" ]; then
|
|
echo "enrolled : yes"
|
|
elif { [ -d "$IDENTITY_DIR" ] && [ ! -x "$IDENTITY_DIR" ]; } || ! readable_or_flag "$IDENTITY_DIR"; then
|
|
STATUS_NEEDS_ROOT=1
|
|
echo "enrolled : unknown (run 'sudo gpuk status' to see it)"
|
|
else
|
|
echo "enrolled : no"
|
|
fi
|
|
|
|
_hp=""
|
|
readable_or_flag "$WORKER_ENV" && _hp=$(health_port)
|
|
[ -n "$_hp" ] || _hp=8001
|
|
_h=""
|
|
if command -v curl >/dev/null 2>&1; then
|
|
_h=$(curl -fsS --max-time 3 "http://127.0.0.1:$_hp/health" 2>/dev/null || true)
|
|
fi
|
|
echo "state : $(daemon_state_sentence "$_active" "$_h")"
|
|
echo "GPUs : $(gpu_sentence)"
|
|
|
|
_installed=$("$BIN_DEST" --version 2>/dev/null | sed -n 's/^gpu-kitchen-worker //p' | head -1)
|
|
echo "daemon : ${_installed:-unknown}"
|
|
|
|
_img=""; _role_known=1
|
|
if readable_or_flag "$MANIFEST"; then _img=$(manifest_image); else _role_known=0; fi
|
|
_offer=$(status_channel_offer || true)
|
|
_offer_version=${_offer%% *}
|
|
_offer_build=""; [ "$_offer" = "${_offer#* }" ] || _offer_build=${_offer#* }
|
|
if [ -z "$_offer" ]; then
|
|
echo "channel : unknown (the update channel cannot be read now)"
|
|
else
|
|
echo "channel : $_offer_version (daemon build ${_offer_build:-not listed})"
|
|
_behind=0
|
|
[ -z "$_offer_build" ] || [ "$_installed" = "$_offer_build" ] || _behind=1
|
|
if [ -n "$_img" ]; then
|
|
[ "$(image_tag "$_img")" = "$_offer_version" ] || _behind=1
|
|
fi
|
|
if [ "$_role_known" -eq 0 ]; then
|
|
echo "update : unknown (run 'sudo gpuk status' to see it)"
|
|
elif [ "$_behind" -eq 1 ]; then
|
|
echo "update : $_offer_version is available. Update: sudo gpuk update"
|
|
else
|
|
echo "update : up to date"
|
|
fi
|
|
fi
|
|
|
|
if [ "$_role_known" -eq 0 ]; then
|
|
echo "role : unknown (run 'sudo gpuk status' to see it)"
|
|
elif [ -n "$_img" ]; then
|
|
echo "app image : $_img"
|
|
echo "app cont. : $(docker inspect -f '{{.State.Status}}' "$(container_name)" 2>/dev/null || echo 'not running')"
|
|
echo "proxy : $(docker inspect -f '{{.State.Status}} {{.State.Health.Status}}' "$(proxy_container_name)" 2>/dev/null || echo 'not running')"
|
|
_setup=$(setup_url)
|
|
[ -z "$_setup" ] || echo "setup link: $_setup (works once; shown until the first account exists)"
|
|
else
|
|
echo "role : worker (no app container)"
|
|
fi
|
|
[ "$STATUS_NEEDS_ROOT" -eq 0 ] || echo "Some details need root. Run: sudo gpuk status"
|
|
}
|
|
|
|
# ── enroll ─────────────────────────────────────────────────────────────────────
|
|
cmd_enroll() {
|
|
need_root
|
|
_url=""; _tok=""
|
|
while [ $# -gt 0 ]; do
|
|
case "$1" in
|
|
--controller) _url="$2"; shift 2 ;;
|
|
--enroll-token|--token) _tok="$2"; shift 2 ;;
|
|
*) die "unknown enroll option: $1" ;;
|
|
esac
|
|
done
|
|
[ -n "$_url" ] || die "enroll needs --controller wss://<controller>:<port>"
|
|
[ -n "$_tok" ] || die "enroll needs --token - (asked on the terminal, or read from a pipe) or --token gk_enroll_..."
|
|
if [ "$_tok" = "-" ] && [ -t 0 ]; then
|
|
_tok=$(enroll_token_from_tty) || exit 1
|
|
elif [ "$_tok" = "-" ]; then
|
|
# [WRK-237] A script pipes it: printf '%s\n' "$TOKEN" | sudo gpuk enroll ... --token -
|
|
IFS= read -r _tok || true
|
|
# A token has no blank in it: strip any, so a line of spaces is no token.
|
|
_tok=$(printf '%s' "$_tok" | tr -d '[:space:]')
|
|
[ -n "$_tok" ] || die "--token - read no enrollment token on stdin"
|
|
fi
|
|
enroll_worker "$_url" "$_tok"
|
|
systemctl restart "$SERVICE_NAME" 2>/dev/null || true
|
|
}
|
|
|
|
# [WRK-237] `--token -` asks for the enrollment token on the terminal, without echo: it
|
|
# never enters a command line (`ps`) nor the shell history. Prompts go to the terminal,
|
|
# only the token to stdout.
|
|
enroll_token_from_tty() {
|
|
(: </dev/tty) 2>/dev/null || die "--token - needs a terminal to ask for the enrollment token"
|
|
printf 'Enrollment token: ' >/dev/tty
|
|
_stty=$(stty -g </dev/tty 2>/dev/null) || _stty=""
|
|
stty -echo </dev/tty 2>/dev/null || true
|
|
IFS= read -r _entered </dev/tty || _entered=""
|
|
[ -z "$_stty" ] || stty "$_stty" </dev/tty 2>/dev/null || true
|
|
printf '\n' >/dev/tty
|
|
_entered=$(printf '%s' "$_entered" | tr -d '[:space:]')
|
|
[ -n "$_entered" ] || die "no enrollment token entered"
|
|
printf '%s' "$_entered"
|
|
}
|
|
|
|
# [WRK-237] The token reaches the worker on stdin: printf is a shell builtin, so the
|
|
# secret never appears in a process's arguments.
|
|
enroll_worker() {
|
|
printf '%s\n' "$2" | GPUK_IDENTITY_DIR="$IDENTITY_DIR" GPUK_MACHINE_ID_FILE="$MACHINE_ID_FILE" \
|
|
"$BIN_DEST" enroll --controller "$1" --token-stdin
|
|
}
|
|
|
|
# ── apply ──────────────────────────────────────────────────────────────────────
|
|
# Controller: reconcile the app container from the manifest, in-process. A worker
|
|
# has no app container — `apply` there is a no-op with a clear message.
|
|
cmd_apply() {
|
|
need_root
|
|
lifecycle_lock
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" apply
|
|
}
|
|
|
|
# ── update ─────────────────────────────────────────────────────────────────────
|
|
# Controller: decide WHICH image TAG to pin, write it into the manifest, then let
|
|
# workerd pull + recreate (health-gate + rollback are the daemon's — apply()).
|
|
# Worker: the signed-binary self-update is DRIVEN FROM THE CONTROLLER (its Update
|
|
# button → POST /api/nodes/:id/host/update → cmd:host_update → verified swap).
|
|
# There is no local unverified swap path.
|
|
# [INS-03] `gpuk update` moves the WHOLE host to the release the signed channel
|
|
# vouches for: the root daemon as well as the app container. Updating only the
|
|
# container leaves the co-located worker on the previous protocol, which the new
|
|
# controller refuses — and a refused worker cannot receive the UI's Update either.
|
|
# The binary is held to the same chain as install.sh's: minisign signature by the
|
|
# pinned key, trusted comment naming the build the channel designates for this
|
|
# architecture, never older than the daemon already installed. Sets DAEMON_UPDATED.
|
|
DAEMON_UPDATED=0
|
|
DAEMON_CANDIDATE_READY=0
|
|
# The gpu-kitchen-worker build the verified channel ($CHANNEL_DOC) names for this host.
|
|
channel_worker_build() {
|
|
case "$(uname -m)" in
|
|
x86_64|amd64) _bkey="workerBuildIdX86_64" ;;
|
|
aarch64|arm64) _bkey="workerBuildIdAarch64" ;;
|
|
*) die "unsupported architecture: $(uname -m)" ;;
|
|
esac
|
|
_named=$(channel_field "$CHANNEL_DOC" "$_bkey")
|
|
[ -n "$_named" ] \
|
|
|| die "the signed release channel names no gpu-kitchen-worker build for $(uname -m) — refusing to leave the daemon on another release (OPS-20)"
|
|
printf '%s' "$_named"
|
|
}
|
|
|
|
# Never older than the daemon already installed.
|
|
refuse_daemon_downgrade() {
|
|
_installed=$("$BIN_DEST" --version 2>/dev/null | sed -n 's/^gpu-kitchen-worker //p' | head -1)
|
|
case "$_installed" in
|
|
[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]-*)
|
|
# buildId = YYYYMMDDHHMMSS-<commit>: the timestamp orders builds.
|
|
[ "${1%%-*}" -ge "${_installed%%-*}" ] \
|
|
|| die "the channel's gpu-kitchen-worker $1 is OLDER than the installed $_installed — refusing a downgrade" ;;
|
|
esac
|
|
}
|
|
|
|
# Downloads <url> to $BIN_DEST.new and keeps it only if it is signed by the pinned
|
|
# release key FOR gpu-kitchen-worker@<build> (OPS-20, INS-05): a valid signature of
|
|
# another, older build is refused too.
|
|
fetch_signed_daemon() {
|
|
echo "==> downloading $1"
|
|
# Not -s: the binary is tens of MB and a silent download reads as a hang.
|
|
curl -fL --progress-bar "$1" -o "$BIN_DEST.new" \
|
|
|| { rm -f "$BIN_DEST.new"; die "cannot download $1"; }
|
|
if [ "${GPUK_CHANNEL_INSECURE:-}" = "1" ]; then
|
|
echo "WARNING: GPUK_CHANNEL_INSECURE=1 — $1 NOT verified" >&2
|
|
return 0
|
|
fi
|
|
require_release_key
|
|
curl -fsSL "$1.minisig" -o "$BIN_DEST.new.minisig" \
|
|
|| { rm -f "$BIN_DEST.new" "$BIN_DEST.new.minisig"; die "no signature at $1.minisig — refusing an unsigned daemon binary"; }
|
|
_verified=$("$MINISIGN" -V -m "$BIN_DEST.new" -x "$BIN_DEST.new.minisig" -P "$CHANNEL_PUBKEY" 2>/dev/null) \
|
|
|| { rm -f "$BIN_DEST.new" "$BIN_DEST.new.minisig"; die "$1: signature verification FAILED — refusing it (OPS-20)"; }
|
|
rm -f "$BIN_DEST.new.minisig"
|
|
_comment=$(printf '%s\n' "$_verified" | sed -n 's/^Trusted comment: //p' | head -1)
|
|
[ "$_comment" = "gpu-kitchen-worker@$2" ] \
|
|
|| { rm -f "$BIN_DEST.new"; die "$1 is signed for '${_comment:-nothing}', not gpu-kitchen-worker@$2 — refusing it (OPS-20)"; }
|
|
echo "==> signature verified (build $2)"
|
|
}
|
|
|
|
prepare_daemon() {
|
|
_base=$(channel_field "$CHANNEL_DOC" workerBase)
|
|
[ -n "$_base" ] \
|
|
|| die "the signed release channel names no gpu-kitchen-worker base — refusing to leave the daemon on another release (OPS-20)"
|
|
_build=$(channel_worker_build) || exit 1
|
|
_installed=$("$BIN_DEST" --version 2>/dev/null | sed -n 's/^gpu-kitchen-worker //p' | head -1)
|
|
if [ "$_installed" = "$_build" ]; then
|
|
check_candidate_release "$BIN_DEST"
|
|
echo "==> worker daemon already on build $_build"
|
|
return 0
|
|
fi
|
|
refuse_daemon_downgrade "$_build"
|
|
echo "==> gpu-kitchen-worker ${_installed:-(unknown build)} → $_build"
|
|
command -v curl >/dev/null || die "curl is required to download the daemon"
|
|
fetch_signed_daemon "$_base/$(arch_asset)" "$_build"
|
|
chmod 0755 "$BIN_DEST.new"
|
|
check_candidate_release "$BIN_DEST.new" "$BIN_DEST.new"
|
|
DAEMON_CANDIDATE_READY=1
|
|
}
|
|
|
|
install_prepared_daemon() {
|
|
if [ "$DAEMON_CANDIDATE_READY" -eq 1 ]; then
|
|
check_candidate_release "$BIN_DEST.new" "$BIN_DEST.new"
|
|
mv "$BIN_DEST.new" "$BIN_DEST"
|
|
DAEMON_UPDATED=1
|
|
fi
|
|
# Refresh even an unchanged worker's unit, before applying the app. A failed
|
|
# app update must not leave the installed beta without its retirement hook.
|
|
write_unit
|
|
systemctl daemon-reload
|
|
}
|
|
|
|
# [INS-74] gpuk replaces itself with the gpuk the verified channel names, before anything
|
|
# else: a gpuk older than its daemon cannot read the daemon's state. Only an installed gpuk
|
|
# is replaced, and only by bytes whose sha256 the signed document gives AND which pin the
|
|
# same release key: a key change stays a reinstall, never something a channel can push. The
|
|
# new copy is written beside the old one, then renamed over it (a new inode: sh is still
|
|
# reading the old file), and an update run from the installed gpuk continues in the new one.
|
|
# $1 = the update's --version, or empty.
|
|
update_cli() {
|
|
[ "${GPUK_CLI_UPDATED:-}" != "1" ] || return 0
|
|
[ -f "$CLI_DEST" ] || return 0
|
|
if [ "${GPUK_CHANNEL_INSECURE:-}" = "1" ]; then
|
|
echo "WARNING: GPUK_CHANNEL_INSECURE=1 — gpuk itself is not updated" >&2
|
|
return 0
|
|
fi
|
|
_url=$(channel_field "$CHANNEL_DOC" gpukScript)
|
|
_sum=$(channel_field "$CHANNEL_DOC" gpukScriptSha256)
|
|
if [ -z "$_url" ] || [ -z "$_sum" ]; then
|
|
echo "==> the release channel names no gpuk; keeping this one"
|
|
return 0
|
|
fi
|
|
[ "$(sha256sum "$CLI_DEST" | cut -d' ' -f1)" != "$_sum" ] || return 0
|
|
curl -fsSL --max-time 60 "$_url" -o "$CLI_DEST.new" 2>/dev/null \
|
|
|| { rm -f "$CLI_DEST.new"; die "cannot download gpuk from $_url"; }
|
|
if [ "$(sha256sum "$CLI_DEST.new" | cut -d' ' -f1)" != "$_sum" ]; then
|
|
rm -f "$CLI_DEST.new"
|
|
die "the gpuk at $_url does not match the signed channel — refusing it (OPS-20)"
|
|
fi
|
|
# shellcheck disable=SC2016 # the literal ${GPUK_UPDATE_PUBKEY:-…} line of the new gpuk
|
|
_key=$(sed -n 's/^CHANNEL_PUBKEY="\${GPUK_UPDATE_PUBKEY:-\(.*\)}"$/\1/p' "$CLI_DEST.new" | head -1)
|
|
if [ "$_key" != "$CHANNEL_PUBKEY" ]; then
|
|
rm -f "$CLI_DEST.new"
|
|
echo "WARNING: the channel's gpuk pins another release key; keeping this one. A new key needs a reinstall." >&2
|
|
return 0
|
|
fi
|
|
sh -n "$CLI_DEST.new" 2>/dev/null \
|
|
|| { rm -f "$CLI_DEST.new"; die "the gpuk at $_url is not a valid script — refusing it"; }
|
|
_self=0
|
|
[ "$(readlink -f "$0" 2>/dev/null)" != "$(readlink -f "$CLI_DEST")" ] || _self=1
|
|
chmod 0755 "$CLI_DEST.new"
|
|
mv "$CLI_DEST.new" "$CLI_DEST"
|
|
echo "==> gpuk updated from the release channel"
|
|
[ "$_self" -eq 1 ] || return 0
|
|
rm -f "$CHANNEL_DOC"
|
|
if [ -n "$1" ]; then
|
|
GPUK_CLI_UPDATED=1 exec "$CLI_DEST" update --version "$1"
|
|
fi
|
|
GPUK_CLI_UPDATED=1 exec "$CLI_DEST" update
|
|
}
|
|
|
|
# The running daemon still executes the replaced binary until it restarts.
|
|
restart_updated_daemon() {
|
|
[ "$DAEMON_UPDATED" -eq 1 ] || return 0
|
|
systemctl restart "$SERVICE_NAME" \
|
|
|| die "the daemon binary was updated but $SERVICE_NAME did not restart — run: systemctl restart $SERVICE_NAME"
|
|
echo "==> $SERVICE_NAME restarted on the new build"
|
|
}
|
|
|
|
cmd_update() {
|
|
need_root
|
|
_want=""; _check=0
|
|
while [ $# -gt 0 ]; do
|
|
case "$1" in
|
|
--version) _want="$2"; shift 2 ;;
|
|
--check) _check=1; shift ;;
|
|
*) die "unknown update option: $1" ;;
|
|
esac
|
|
done
|
|
|
|
[ "$_check" -eq 1 ] || lifecycle_lock
|
|
_image=$(manifest_image)
|
|
if [ -z "$_image" ]; then
|
|
# A worker node: the daemon is the whole install. The controller UI's Update
|
|
# button drives the same swap, but only for a worker it still accepts.
|
|
[ "$_check" -eq 0 ] || { echo "This is a worker node: 'gpuk update' moves its daemon to the channel's build."; return 0; }
|
|
channel_fetch || die "cannot read the release channel at $CHANNEL_URL"
|
|
prepare_daemon
|
|
update_cli ""
|
|
install_prepared_daemon
|
|
restart_updated_daemon
|
|
return 0
|
|
fi
|
|
|
|
_repo=$(image_repo "$_image")
|
|
_current=$(image_tag "$_image")
|
|
[ -n "$_current" ] || _current="(untagged)"
|
|
|
|
if [ "$_check" -eq 1 ]; then
|
|
_latest=$(channel_version) || true
|
|
echo "installed : $_current"
|
|
if [ -z "$_latest" ]; then
|
|
echo "available : unknown (cannot reach $CHANNEL_URL)"
|
|
exit 1
|
|
fi
|
|
echo "available : $_latest"
|
|
if [ "$_latest" = "$_current" ]; then echo "up to date."; else echo "run 'gpuk update' to move to $_latest"; fi
|
|
return 0
|
|
fi
|
|
|
|
_digest=""
|
|
# channel_fetch runs in THIS shell (not a $(…) subshell) so a signature
|
|
# failure is fatal here — fail-closed — and $CHANNEL_DOC survives. The
|
|
# verified signature closes the document half of OPS-20; the digest read
|
|
# from it pins CONTENT, closing the mutable-tag half. A named --version goes
|
|
# through the same document: it vouches for ONE release, the one it names.
|
|
_latest=""
|
|
if channel_fetch; then
|
|
_latest=$(channel_field "$CHANNEL_DOC" version)
|
|
fi
|
|
if [ -z "$_latest" ]; then
|
|
[ -z "$_want" ] \
|
|
|| die "cannot read the release channel at $CHANNEL_URL — refusing to pin $_want unverified"
|
|
echo "==> cannot reach $CHANNEL_URL — re-applying the pinned $_current"
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" apply
|
|
return 0
|
|
fi
|
|
if [ -n "$_want" ] && [ "$_want" != "$_latest" ]; then
|
|
[ "${GPUK_CHANNEL_INSECURE:-}" = "1" ] \
|
|
|| die "the signed channel vouches for $_latest only, not $_want — refusing an unpinned tag (OPS-20)"
|
|
else
|
|
_want="$_latest"
|
|
# Pick the digest matching the installed edition by image basename — the
|
|
# repo itself may be a mirror, the basename is the edition marker.
|
|
case "${_repo##*/}" in
|
|
*-ee) _digest=$(channel_field "$CHANNEL_DOC" controllerImageDigestEnterprise) ;;
|
|
*) _digest=$(channel_field "$CHANNEL_DOC" controllerImageDigest) ;;
|
|
esac
|
|
case "$_digest" in
|
|
sha256:*) ;;
|
|
*) [ "${GPUK_CHANNEL_INSECURE:-}" = "1" ] \
|
|
|| die "the signed release channel names no image digest for $_want — refusing to pin a mutable tag (OPS-20)" ;;
|
|
esac
|
|
fi
|
|
|
|
# Validate the candidate before changing the installed manifest.
|
|
[ "$_want" != "$_latest" ] || prepare_daemon
|
|
update_cli "$_want"
|
|
install_prepared_daemon
|
|
|
|
_new="$_repo:$_want"
|
|
[ -n "$_digest" ] && _new="$_repo:$_want@$_digest"
|
|
_installed=$(manifest_image)
|
|
if [ "$_new" != "$_installed" ]; then
|
|
echo "==> $_current → $_want${_digest:+ (pinned by digest)}"
|
|
# Pin the new reference into the manifest, then apply. sed edits the single
|
|
# "image" line in place (atomic tmp + move).
|
|
_tmp="$MANIFEST.new"
|
|
sed "s#\"image\"[[:space:]]*:[[:space:]]*\"[^\"]*\"#\"image\": \"$(json_str "$_new")\"#" "$MANIFEST" > "$_tmp" \
|
|
|| die "could not rewrite the image in $MANIFEST"
|
|
chmod 0600 "$_tmp"; mv "$_tmp" "$MANIFEST"
|
|
else
|
|
echo "==> already on $_current — re-pulling and recreating"
|
|
fi
|
|
GPUK_MANIFEST_PATH="$MANIFEST" "$BIN_DEST" apply \
|
|
|| die "the update did not apply — the [worker] lines above say why. A manifest refused for a field
|
|
an older release wrote is repaired by re-running the same install command with --reset-manifest:
|
|
the file is archived beside itself and rebuilt from this install's settings."
|
|
restart_updated_daemon
|
|
}
|
|
|
|
# ── uninstall ──────────────────────────────────────────────────────────────────
|
|
# Plain: stop and remove the service, touch nothing else (a pause, reversible by
|
|
# `gpuk install`). --purge: everything the installer created goes — the app
|
|
# container (and its -old / -failed twins), $ETC_DIR with the manifest and the
|
|
# enrolled identity, the binary — EXCEPT the data root: database, models and the
|
|
# secrets (ENCRYPTION_KEY above all, OPS-04) are the operator's to delete, by
|
|
# hand, knowingly. After a purge the next install is a first install (INS-03);
|
|
# without it, install.sh sees the manifest and treats the re-run as an update.
|
|
# Called by the expired worker's stop hook or retirement timer, while that
|
|
# process owns the host node lock. Never use the ordinary purge path: all configuration, identity,
|
|
# databases, models, secrets, backups and Docker volumes must survive retirement.
|
|
retirement_docker() { timeout 10 docker "$@"; }
|
|
|
|
# An inspect error alone never proves absence: query Docker's complete ID list.
|
|
retirement_image_present() {
|
|
_known_images=$(retirement_docker image ls --no-trunc -q) || return 2
|
|
printf '%s\n' "$_known_images" | grep -Fx -- "$1" >/dev/null
|
|
}
|
|
|
|
retirement_remove_image() {
|
|
_remove_id="$1"
|
|
_present_status=0
|
|
retirement_image_present "$_remove_id" || _present_status=$?
|
|
[ "$_present_status" -ne 1 ] || return 0
|
|
[ "$_present_status" -eq 0 ] || die "cannot list beta images; installed files were kept for a retry"
|
|
_remove_stamp=$(retirement_docker image inspect --format '{{index .Config.Labels "io.gpukitchen.beta-expires-at"}}' "$_remove_id") \
|
|
|| die "cannot inspect beta image; installed files were kept for a retry"
|
|
[ "$_remove_stamp" = "$_expiry" ] || die "image ownership changed; installed files were kept for a retry"
|
|
_image_users=$(retirement_docker ps -aq --filter "ancestor=$_remove_id" --no-trunc) \
|
|
|| die "cannot check image users; installed files were kept for a retry"
|
|
if [ -n "$_image_users" ]; then
|
|
echo "==> kept a beta image used by another container"
|
|
return 0
|
|
fi
|
|
# Docker refuses to remove a multiply tagged ID without --force. Remove only
|
|
# references still resolving to this proven image, then the immutable ID.
|
|
_image_refs=$(retirement_docker image inspect --format '{{range .RepoTags}}{{println .}}{{end}}{{range .RepoDigests}}{{println .}}{{end}}' "$_remove_id") \
|
|
|| die "cannot list image references; installed files were kept for a retry"
|
|
for _image_ref in $_image_refs; do
|
|
case "$_image_ref" in -*|'<none>'|'<none>:<none>') continue ;; esac
|
|
_ref_id=$(retirement_docker image inspect --format '{{.Id}}' "$_image_ref" 2>/dev/null) || continue
|
|
[ "$_ref_id" = "$_remove_id" ] || continue
|
|
# A reference can disappear with another reference to the same repository.
|
|
# The final ID inventory below, not this command's output, is the verdict.
|
|
retirement_docker image rm "$_image_ref" >/dev/null 2>&1 || true
|
|
done
|
|
retirement_docker image rm "$_remove_id" >/dev/null 2>&1 || true
|
|
_present_status=0
|
|
retirement_image_present "$_remove_id" || _present_status=$?
|
|
[ "$_present_status" -ne 1 ] || return 0
|
|
[ "$_present_status" -eq 0 ] || die "cannot confirm image removal; installed files were kept for a retry"
|
|
_image_users=$(retirement_docker ps -aq --filter "ancestor=$_remove_id" --no-trunc) \
|
|
|| die "cannot confirm image users; installed files were kept for a retry"
|
|
[ -z "$_image_users" ] || { echo "==> kept a beta image now used by another container"; return 0; }
|
|
die "cannot remove all beta image references; installed files were kept for a retry"
|
|
}
|
|
|
|
cmd_retire_beta() {
|
|
[ "$#" -eq 0 ] || die "retire-beta takes no arguments"
|
|
need_root
|
|
lifecycle_lock nonblocking || { echo "==> beta cleanup deferred: installation is being changed"; return 0; }
|
|
[ -x "$BIN_DEST" ] && [ -f "$MANIFEST" ] || return 0
|
|
# A replaced symlink or owner is not an installation resource we can retire.
|
|
for _program in "$BIN_DEST" "$CLI_DEST" "$MANIFEST"; do
|
|
[ -f "$_program" ] && [ ! -L "$_program" ] || return 0
|
|
[ "$(stat -c %u "$_program")" = "$(id -u)" ] || return 0
|
|
done
|
|
[ -n "${GPUK_RETIRE_WORKER_SHA256:-}" ] || return 0
|
|
[ "$(sha256sum "$BIN_DEST" | cut -d' ' -f1)" = "$GPUK_RETIRE_WORKER_SHA256" ] || return 0
|
|
_expiry=$("$BIN_DEST" --beta-expiry 2>/dev/null) || return 0
|
|
if [ "$_expiry" = 0 ]; then
|
|
# A remote normal upgrade can finish without running gpuk install/update.
|
|
# Its explicit retirement invocation only retires the beta retry policy.
|
|
# No Docker resource or ordinary installation file is removed here.
|
|
for _program in "$UNIT_DEST" "$RETIRE_UNIT" "$RETIRE_TIMER" "$RETIRE_PENDING" "$RETIRE_STATE"; do
|
|
[ ! -L "$_program" ] || return 0
|
|
[ ! -e "$_program" ] || { [ -f "$_program" ] && [ "$(stat -c %u "$_program")" = "$(id -u)" ]; } || return 0
|
|
done
|
|
if [ -f "$RETIRE_UNIT" ] || [ -f "$RETIRE_TIMER" ] || [ -f "$RETIRE_PENDING" ] || [ -f "$RETIRE_STATE" ]; then
|
|
# The file may already be normal while the old beta MainPID still owns
|
|
# the service. Only a running normal MainPID can cancel beta recovery.
|
|
_normal_pid=$(timeout 10 systemctl show -p MainPID --value "$SERVICE_NAME" 2>/dev/null) || return 0
|
|
case "$_normal_pid" in ''|*[!0-9]*) return 0 ;; esac
|
|
[ "$_normal_pid" -gt 1 ] || return 0
|
|
[ "$(sha256sum "/proc/$_normal_pid/exe" 2>/dev/null | cut -d' ' -f1)" = "$GPUK_RETIRE_WORKER_SHA256" ] || return 0
|
|
write_unit
|
|
systemctl daemon-reload
|
|
fi
|
|
return 0
|
|
fi
|
|
[ "$_expiry" = "$((0xce8c74e7 ^ 0xa5c39e17))" ] || return 0
|
|
[ -f "$RETIRE_PENDING" ] && [ ! -L "$RETIRE_PENDING" ] || return 0
|
|
[ "$(stat -c %u "$RETIRE_PENDING")" = "$(id -u)" ] || return 0
|
|
[ "$(cat "$RETIRE_PENDING")" = "$_expiry" ] || return 0
|
|
[ "$(stat -c %a "$RETIRE_PENDING")" = 600 ] || return 0
|
|
[ "$(stat -c %s "$RETIRE_PENDING")" -eq "$((${#_expiry} + 1))" ] || return 0
|
|
for _program in "$UNIT_DEST" "$RETIRE_UNIT" "$RETIRE_TIMER" "$RETIRE_STATE"; do
|
|
[ ! -L "$_program" ] || return 0
|
|
[ ! -e "$_program" ] || { [ -f "$_program" ] && [ "$(stat -c %u "$_program")" = "$(id -u)" ]; } || return 0
|
|
done
|
|
# The durable pending marker records authenticated expiry. Local wall time
|
|
# and the timer's unrelated exit status cannot revoke that decision.
|
|
_state_key="$_expiry $GPUK_RETIRE_WORKER_SHA256 $(sha256sum "$MANIFEST" | cut -d' ' -f1)"
|
|
_images=""
|
|
if [ -f "$RETIRE_STATE" ]; then
|
|
[ "$(stat -c %a "$RETIRE_STATE")" = 600 ] || return 0
|
|
[ "$(head -n 1 "$RETIRE_STATE")" = "$_state_key" ] || return 0
|
|
_images=$(tail -n +2 "$RETIRE_STATE")
|
|
for _image_id in $_images; do
|
|
case "$_image_id" in sha256:*) ;; *) return 0 ;; esac
|
|
_image_hex=${_image_id#sha256:}
|
|
case "$_image_hex" in ''|*[!a-f0-9]*) return 0 ;; esac
|
|
[ "${#_image_hex}" -eq 64 ] || return 0
|
|
done
|
|
fi
|
|
|
|
# Every destructive Docker operation uses an immutable ID captured under the
|
|
# lifecycle + node locks. A normal or unknown app image protects the entire
|
|
# installation, including a normal upgrade whose worker has not restarted yet.
|
|
command -v docker >/dev/null 2>&1 && command -v timeout >/dev/null 2>&1 || return 0
|
|
retirement_docker info >/dev/null 2>&1 || return 0
|
|
_image=$(manifest_image)
|
|
_mode=$(manifest_env_value mode)
|
|
_containers=""
|
|
if [ -n "$_image" ]; then
|
|
if _image_expiry=$(retirement_docker image inspect --format '{{index .Config.Labels "io.gpukitchen.beta-expires-at"}}' "$_image" 2>/dev/null); then
|
|
[ "$_image_expiry" = "$_expiry" ] || return 0
|
|
_image_id=$(retirement_docker image inspect --format '{{.Id}}' "$_image" 2>/dev/null) || return 0
|
|
_images="$_images $_image_id"
|
|
else
|
|
# A previous attempt may already have removed this reference or image.
|
|
# Only the journal bound to these exact installed files permits resuming.
|
|
[ -f "$RETIRE_STATE" ] && [ -n "$_images" ] || return 0
|
|
fi
|
|
_cn=$(container_name)
|
|
_pcn=$(proxy_container_name)
|
|
[ -n "$_cn" ] || return 0
|
|
# A stopped/failed generation is still executable beta software. Names come
|
|
# from this installation's manifest; the image stamp is checked independently.
|
|
_names="$_cn $_cn-old $_cn-failed $_pcn $_pcn-next $_pcn-failed"
|
|
_draining=$(retirement_docker ps -a --format '{{.Names}}' 2>/dev/null) || return 0
|
|
for _name in $_draining; do
|
|
case "$_name" in "$_pcn-draining-"*) _names="$_names $_name" ;; esac
|
|
done
|
|
for _name in $_names; do
|
|
printf '%s\n' "$_draining" | grep -Fx -- "$_name" >/dev/null || continue
|
|
_facts=$(retirement_docker inspect --format '{{.Id}}|{{index .Config.Labels "io.gpukitchen.beta-expires-at"}}|{{.Image}}' "$_name" 2>/dev/null) || return 0
|
|
_id=${_facts%%|*}; _rest=${_facts#*|}; _stamp=${_rest%%|*}; _image_id=${_rest#*|}
|
|
[ "$_stamp" = "$_expiry" ] || return 0
|
|
_image_expiry=$(retirement_docker image inspect --format '{{index .Config.Labels "io.gpukitchen.beta-expires-at"}}' "$_image_id" 2>/dev/null) || return 0
|
|
[ "$_image_expiry" = "$_expiry" ] || return 0
|
|
case "$_id" in ''|*[!a-f0-9]*) return 0 ;; esac
|
|
_containers="$_containers $_id"
|
|
_images="$_images $_image_id"
|
|
done
|
|
else
|
|
# An empty image is only legitimate for an explicitly headless worker.
|
|
[ "$_mode" = "worker" ] || return 0
|
|
fi
|
|
|
|
# Engine image names and container-name prefixes do not establish ownership.
|
|
# Only workloads stamped by this beta worker for this machine are removed.
|
|
_machine_id=$(cat "$MACHINE_ID_FILE" 2>/dev/null) || return 0
|
|
case "$_machine_id" in ''|*[!A-Za-z0-9_-]*) return 0 ;; esac
|
|
_engines=$(retirement_docker ps -aq --filter "label=io.gpukitchen.beta-expires-at=$_expiry" \
|
|
--filter "label=io.gpukitchen.machine-id=$_machine_id" --no-trunc) || return 0
|
|
for _id in $_engines; do
|
|
case "$_id" in ''|*[!a-f0-9]*) return 0 ;; esac
|
|
_containers="$_containers $_id"
|
|
done
|
|
[ "$(sha256sum "$BIN_DEST" | cut -d' ' -f1)" = "$GPUK_RETIRE_WORKER_SHA256" ] || return 0
|
|
_images=$(printf '%s\n' "$_images" | tr ' ' '\n' | sed '/^$/d' | sort -u)
|
|
# Commit the complete proven image inventory before the first mutation. A
|
|
# restart after containers/tags disappeared resumes from this durable plan.
|
|
_journal=$(mktemp "$RETIRE_STATE.new.XXXXXX")
|
|
{ printf '%s\n' "$_state_key"; [ -z "$_images" ] || printf '%s\n' "$_images"; } > "$_journal"
|
|
chmod 0600 "$_journal"
|
|
sync -f "$_journal"
|
|
mv "$_journal" "$RETIRE_STATE"
|
|
sync -f "$ETC_DIR"
|
|
echo "==> This beta has expired. Removing its installed programs; keeping your data."
|
|
if [ -n "$_containers" ]; then
|
|
# Give the controller's Postgres and active engines a bounded graceful stop.
|
|
# IDs were validated above. No volumes are removed and Docker is never pruned.
|
|
# shellcheck disable=SC2086
|
|
set -- $_containers
|
|
if ! timeout 45 docker stop --time 30 "$@" >/dev/null; then
|
|
# A container can disappear or already be stopped during cleanup. Accept
|
|
# only states Docker independently proves safe to remove; all other stop
|
|
# failures retain the installed programs for the next retirement attempt.
|
|
_present=$(retirement_docker ps -aq --no-trunc) \
|
|
|| die "cannot confirm beta containers stopped; installed files were kept for a retry"
|
|
_stopped=""
|
|
for _id in $_containers; do
|
|
printf '%s\n' "$_present" | grep -Fx -- "$_id" >/dev/null || continue
|
|
_state=$(retirement_docker inspect --format '{{.State.Status}}' "$_id") \
|
|
|| die "cannot confirm beta container $_id stopped; installed files were kept for a retry"
|
|
case "$_state" in
|
|
created|exited|dead) _stopped="$_stopped $_id" ;;
|
|
*) die "beta container $_id did not stop; installed files were kept for a retry" ;;
|
|
esac
|
|
done
|
|
_containers="$_stopped"
|
|
fi
|
|
if [ -n "$_containers" ]; then
|
|
# No --force: a container restarted outside this lifecycle is preserved.
|
|
# shellcheck disable=SC2086
|
|
set -- $_containers
|
|
timeout 30 docker rm "$@" >/dev/null \
|
|
|| die "cannot remove all beta containers; cleanup left installed files for a retry"
|
|
fi
|
|
fi
|
|
for _image_id in $_images; do
|
|
retirement_remove_image "$_image_id"
|
|
done
|
|
# ExecStopPost is already inside a stop job: --now/stop would deadlock it.
|
|
timeout 10 systemctl disable "$SERVICE_NAME" >/dev/null 2>&1 \
|
|
|| die "cannot disable the beta service; installed programs were kept for a retry"
|
|
if [ -f "$RETIRE_TIMER" ]; then
|
|
timeout 10 systemctl disable --now "$RETIRE_SERVICE.timer" >/dev/null 2>&1 \
|
|
|| die "cannot disable the retirement timer; installed programs were kept for a retry"
|
|
fi
|
|
_unit_backup=$(mktemp -d "$ETC_DIR/.beta-retirement-units.XXXXXX")
|
|
for _program in "$UNIT_DEST" "$RETIRE_UNIT" "$RETIRE_TIMER"; do
|
|
[ ! -f "$_program" ] || cp -p "$_program" "$_unit_backup/$(basename "$_program")"
|
|
rm -f "$_program"
|
|
done
|
|
if ! timeout 10 systemctl daemon-reload >/dev/null 2>&1; then
|
|
for _program in "$UNIT_DEST" "$RETIRE_UNIT" "$RETIRE_TIMER"; do
|
|
[ ! -f "$_unit_backup/$(basename "$_program")" ] || cp -p "$_unit_backup/$(basename "$_program")" "$_program"
|
|
done
|
|
[ ! -f "$RETIRE_TIMER" ] || timeout 10 systemctl enable --now "$RETIRE_SERVICE.timer" >/dev/null 2>&1 || true
|
|
rm -rf "$_unit_backup"
|
|
die "cannot reload the service manager; installed programs were kept for a retry"
|
|
fi
|
|
rm -rf "$_unit_backup"
|
|
# This state lets the normal installer recover over the retained manifest
|
|
# without mistaking the intentionally removed CLI for an incomplete old install.
|
|
(umask 077; printf '%s\n' "$_expiry" > "$ETC_DIR/beta-retired.new")
|
|
mv "$ETC_DIR/beta-retired.new" "$ETC_DIR/beta-retired"
|
|
rm -f "$BIN_DEST" "$CLI_DEST"
|
|
rm -f "$RETIRE_PENDING" "$RETIRE_STATE"
|
|
echo "Kept: $ETC_DIR and all data, models, secrets and backups. Install the current release to reuse them."
|
|
}
|
|
|
|
cmd_uninstall() {
|
|
need_root
|
|
lifecycle_lock
|
|
_purge=0
|
|
while [ $# -gt 0 ]; do
|
|
case "$1" in
|
|
--purge) _purge=1; shift ;;
|
|
*) die "unknown uninstall option: $1 (expected: --purge)" ;;
|
|
esac
|
|
done
|
|
_cn=$(container_name)
|
|
_pcn=$(proxy_container_name)
|
|
_root=$(manifest_data_root)
|
|
systemctl disable --now "$SERVICE_NAME" 2>/dev/null || true
|
|
rm -f "$UNIT_DEST"; systemctl daemon-reload 2>/dev/null || true
|
|
echo "==> removed the systemd service"
|
|
if [ "$_purge" -eq 0 ]; then
|
|
echo "Left in place: $BIN_DEST, $ETC_DIR (manifest, identity), the data root and any"
|
|
echo "app container — 'gpuk install' brings the service back on them."
|
|
echo "For a clean slate (everything but the data root): gpuk uninstall --purge"
|
|
return 0
|
|
fi
|
|
if [ -n "$_cn" ] && command -v docker >/dev/null 2>&1; then
|
|
for _c in "$_cn" "$_cn-old" "$_cn-failed"; do
|
|
docker rm -f "$_c" >/dev/null 2>&1 && echo "==> removed container $_c"
|
|
done
|
|
# The proxy container and the generations a handover left (PRX-83).
|
|
for _c in "$_pcn" "$_pcn-next" "$_pcn-failed" \
|
|
$(docker ps -a --filter "name=^$_pcn-draining-" --format '{{.Names}}' 2>/dev/null); do
|
|
docker rm -f "$_c" >/dev/null 2>&1 && echo "==> removed container $_c"
|
|
done
|
|
fi
|
|
for _d in "$ETC_DIR" "$IDENTITY_DIR"; do
|
|
case "$_d" in ""|/|/etc|/usr|/var) die "refusing to remove $_d" ;; esac
|
|
[ ! -e "$_d" ] || { rm -rf "$_d"; echo "==> removed $_d"; }
|
|
done
|
|
[ ! -e "$MACHINE_ID_FILE" ] || rm -f "$MACHINE_ID_FILE"
|
|
[ ! -e "$BIN_DEST" ] || { rm -f "$BIN_DEST"; echo "==> removed $BIN_DEST"; }
|
|
[ ! -e "$CLI_DEST" ] || { rm -f "$CLI_DEST"; echo "==> removed $CLI_DEST"; }
|
|
echo
|
|
echo "Kept: the data root${_root:+ $_root} — database, models and secrets (ENCRYPTION_KEY)."
|
|
echo "A new install over it reuses them. To delete it too, knowingly: rm -rf ${_root:-<data-root>}"
|
|
}
|
|
|
|
usage() {
|
|
cat <<EOF
|
|
gpuk — GPU Kitchen host daemon (gpu-kitchen-worker)
|
|
|
|
gpuk install --mode controller --image <ref> [--profile homelab|small-team|managed-network|public]
|
|
[--domain D] [--cluster N] [--cache-dir P] [--data-root P]
|
|
[--http-port P] [--mtls-port P] [--inference-port P]
|
|
[--network bridge|host|<net>] [--binary <path>] [--reset-manifest]
|
|
--network: bridge by default — the container publishes its three
|
|
ports and nothing else it listens on touches the host; host makes
|
|
every listener a host-wide claim (a re-run keeps the mode installed)
|
|
--domain: the name the UI is reached by through a reverse proxy, any
|
|
profile — allowed as a host, trusted proxy on, filled Caddyfile written;
|
|
kept by a re-run, dropped with --no-domain
|
|
gpuk install --mode worker --controller wss://<host>:<port> --enroll-token -
|
|
(asks for the token on the terminal: never on a command line)
|
|
[--cluster N] [--cache-dir P] [--binary <path>]
|
|
[--health-port P] [--data-port P] [--transfer-port P] [--handover-port P]
|
|
gpuk install ... --dry-run Validate inputs and print the manifest without changing the host
|
|
gpuk status Service state, enrollment, /health, app container status
|
|
gpuk enroll --controller wss://<host>:<port> --token -
|
|
(asks on the terminal; a script pipes the token into --token - instead)
|
|
gpuk apply (controller) Reconcile the app container, then the proxy container
|
|
by handover, from the manifest
|
|
gpuk update Move gpuk, the daemon and (controller) the app to the current release
|
|
(pull + recreate, rollback)
|
|
gpuk update --check (controller) Compare the installed version with the release
|
|
gpuk update --version <tag> (controller) Move to a specific release
|
|
gpuk channel Fetch + VERIFY the release channel and print what it offers
|
|
gpuk backup [DIR] [--offsite] (controller) Cold snapshot of the embedded pgdata (stop → tar → restart);
|
|
--offsite then copies it with the command in /etc/gpu-kitchen/offsite.env
|
|
gpuk carry-over <backup> [--replace] (controller) Copy the recipes, benchmarks, evaluations and
|
|
baskets of a backup (gpuk backup folder or pg_dump file) into this database;
|
|
--replace first deletes the ones it already has
|
|
gpuk manifest Print the current manifest
|
|
gpuk logs Follow the app container logs (controller) or the daemon journal;
|
|
after a failed start, the kept <container>-failed log
|
|
gpuk uninstall Remove the systemd service, leave everything else in place
|
|
gpuk uninstall --purge Also remove the app container, /etc/gpu-kitchen, the binary and gpuk
|
|
(never the data root: database, models, secrets)
|
|
|
|
The GPU Kitchen installer installs this tool:
|
|
curl -fsSL https://gpu.kitchen/install.sh | sudo sh
|
|
EOF
|
|
}
|
|
|
|
# ── dispatch ────────────────────────────────────────────────────────────────────
|
|
cmd="${1:-help}"; if [ $# -gt 0 ]; then shift; fi
|
|
case "$cmd" in
|
|
install) cmd_install "$@" ;;
|
|
status) cmd_status ;;
|
|
enroll) cmd_enroll "$@" ;;
|
|
apply) cmd_apply ;;
|
|
update) cmd_update "$@" ;;
|
|
channel) cmd_channel ;;
|
|
backup) cmd_backup "$@" ;;
|
|
carry-over) cmd_carry_over "$@" ;;
|
|
manifest) cat "$MANIFEST" ;;
|
|
logs)
|
|
_img=$(manifest_image)
|
|
if [ -n "$_img" ]; then
|
|
_cn=$(container_name)
|
|
if docker inspect "$_cn" >/dev/null 2>&1; then
|
|
exec docker logs -f "$_cn"
|
|
elif docker inspect "$_cn-failed" >/dev/null 2>&1; then
|
|
# No live app container, but the last failed start was kept (INS-15):
|
|
# its whole log is the diagnosis, not the daemon journal.
|
|
echo "==> no running app container; showing the full log of the last failed start ($_cn-failed)" >&2
|
|
exec docker logs "$_cn-failed"
|
|
else
|
|
exec journalctl -u "$SERVICE_NAME" -f
|
|
fi
|
|
else
|
|
exec journalctl -u "$SERVICE_NAME" -f
|
|
fi
|
|
;;
|
|
uninstall) cmd_uninstall "$@" ;;
|
|
retire-beta) cmd_retire_beta "$@" ;;
|
|
help|-h|--help) usage ;;
|
|
*) usage; exit 1 ;;
|
|
esac
|