#!/usr/bin/env bash # # proxmox-lxc.sh — create a Debian LXC on a Proxmox VE host and install # node-stats (native single binary + systemd) inside it. Inspired by the # community-scripts.org (Proxmox VE Helper-Scripts) one-liners, but fully # self-contained — it does not depend on their build.func framework, so you # can run it straight from this repo. # # Run ON THE PROXMOX VE HOST (the hypervisor), as root: # # bash -c "$(curl -fsSL https://git.example.com/owner/node-page/releases/download//proxmox-lxc.sh)" # # (the release asset has the release sources filled in; the in-repo copy needs # NODE_STATS_REPO=owner/name (GitHub) and/or # NODE_STATS_UPDATE_MIRROR=https://git.example.com/owner/name (Gitea/Forgejo)) # # Subcommands (default: create): # create create the LXC and install node-stats # reconnect (re)wire Proxmox auto-connect into an existing container # update self-update node-stats inside an existing container # (follows the container's channel; prefix # NODE_STATS_CHANNEL=beta to switch it to beta + update) # uninstall stop + destroy the container (asks first) # # Non-interactive overrides (env vars): # CTID, CT_HOSTNAME, DISK_SIZE (GB), CORE_COUNT, RAM_SIZE (MB), # BRIDGE (vmbr0), NET (dhcp | ), GATEWAY, DNS, UNPRIVILEGED (1|0), # ENABLE_NESTING (1|0), START_ON_BOOT (1|0), HTTP_PORT (8080), # TEMPLATE_STORAGE, CONTAINER_STORAGE, NODE_STATS_VERSION (vX.Y.Z), # NODE_STATS_CHANNEL=beta (follow the beta release line: latest prerelease # .deb; persisted in the container so the self-updater keeps following it), # VERBOSE (1 to stream apt output). Set ADVANCED=1 for the whiptail wizard. # # Join an existing cluster in the same run (Admin → Nodes → Add a node → # Proxmox · LXC prints the command with both filled in): # NODE_STATS_JOIN_URL URL of any node already in the cluster # NODE_STATS_JOIN_KEY the one-shot join token issued there # RAFT_PORT Raft TCP port inside the container (default 7000) # RAFT_NODE_ID node id in the cluster (default -<4 hex>) # # The whole script is one function, called on its last line: bash parses it in # full before running anything, so a download cut short (curl | bash) runs # nothing instead of a prefix of the script. main() { set -euo pipefail # Release sources: GitHub owner/name, and a Gitea/Forgejo mirror used when GitHub # does not answer. Filled in by CI in the release asset, from the env otherwise. REPO="${NODE_STATS_REPO-LastSkywalkerER/node-page}" MIRROR="${NODE_STATS_UPDATE_MIRROR-https://gitea.sky-apps.uk/LastSkywalker/node-page}" case "$REPO" in __*__) REPO="" ;; esac case "$MIRROR" in __*__ | off | none) MIRROR="" ;; esac MIRROR="${MIRROR%/}"; MIRROR="${MIRROR%.git}" if [ -z "$REPO" ] && [ -z "$MIRROR" ]; then echo "error: no release source. Use the proxmox-lxc.sh attached to a release, or set NODE_STATS_REPO=owner/name and/or NODE_STATS_UPDATE_MIRROR=https://git.example.com/owner/name" >&2 exit 1 fi # Where this script itself is served from (for hints). # A forge serves main's files through its API (its web /raw/branch/ form may # redirect to an HTML login page). if [ -n "$MIRROR" ]; then SELF_RAW="$(printf '%s' "$MIRROR" | sed -E 's#^(https?://[^/]+)/(.*)$#\1/api/v1/repos/\2/raw/main#')" else SELF_RAW="https://raw.githubusercontent.com/${REPO}/main" fi APP="node-stats" HTTP_PORT_DEFAULT="${HTTP_PORT:-8080}" # Release channel for a fresh create: stable (default) or beta. CHANNEL="$(printf '%s' "${NODE_STATS_CHANNEL:-stable}" | tr '[:upper:]' '[:lower:]')" [ "$CHANNEL" = beta ] || CHANNEL=stable # ---- pretty output (mirrors the community-scripts look) -------------------- if [ -t 1 ]; then RD=$'\033[01;31m'; GN=$'\033[1;92m'; YW=$'\033[33m'; BL=$'\033[36m'; CL=$'\033[m' else RD=''; GN=''; YW=''; BL=''; CL='' fi CM="${GN}✓${CL}"; CROSS="${RD}✗${CL}"; INFO="${BL}ℹ${CL}" msg_info() { printf ' %s %s...\n' "${YW}…${CL}" "$1"; } msg_ok() { printf ' %s %s\n' "$CM" "$1"; } msg_warn() { printf ' %s %s\n' "${YW}!${CL}" "$1"; } msg_error(){ printf ' %s %s\n' "$CROSS" "$1" >&2; } die() { msg_error "$1"; exit 1; } # Run a command quietly unless VERBOSE=1. STD="silent" [ "${VERBOSE:-0}" = "1" ] && STD="verbose" run() { if [ "$STD" = verbose ]; then "$@"; else "$@" >/dev/null 2>&1; fi; } header() { printf '%s' "$BL" cat <<'EOF' _ _ _ ____ _ _ | \ | | ___ __| | ___ / ___|| |_ __ _| |_ ___ | \| |/ _ \ / _` |/ _ \ \___ \| __/ _` | __/ __| | |\ | (_) | (_| | __/ ___) | || (_| | |_\__ \ |_| \_|\___/ \__,_|\___| |____/ \__\__,_|\__|___/ LXC on Proxmox VE EOF printf '%s\n' "$CL" } # ---- preflight ------------------------------------------------------------- preflight() { [ "$(id -u)" = "0" ] || die "run this on the Proxmox VE host as root." command -v pveversion >/dev/null 2>&1 || die "this is not a Proxmox VE host (pveversion not found). Run it on the hypervisor, not inside a VM/LXC." command -v pct >/dev/null 2>&1 || die "pct (LXC tooling) not found — is this a full PVE install?" for c in pveam pvesm; do command -v "$c" >/dev/null 2>&1 || die "$c not found."; done } # next free CTID (>= 100). Prefer pvesh; fall back to scanning pct list. next_ctid() { local id id="$(pvesh get /cluster/nextid 2>/dev/null || true)" if [ -z "$id" ]; then id=100 while pct status "$id" >/dev/null 2>&1 || qm status "$id" >/dev/null 2>&1; do id=$((id + 1)); done fi printf '%s' "$id" } # first storage that advertises a given content type (vztmpl / rootdir). storages_for() { pvesm status -content "$1" 2>/dev/null | awk 'NR>1 {print $1}'; } first_storage() { storages_for "$1" | head -1; } HOST_ARCH="" detect_arch() { HOST_ARCH="$(dpkg --print-architecture 2>/dev/null || echo amd64)" case "$HOST_ARCH" in amd64 | arm64) : ;; *) HOST_ARCH=amd64 ;; esac } # ---- settings -------------------------------------------------------------- set_defaults() { CTID="${CTID:-$(next_ctid)}" # NB: read CT_HOSTNAME, not HOSTNAME — bash auto-sets $HOSTNAME to the PVE # host's name, which would otherwise override our default and name the # container after the hypervisor. CT_HOSTNAME="${CT_HOSTNAME:-node-stats}" DISK_SIZE="${DISK_SIZE:-4}" CORE_COUNT="${CORE_COUNT:-1}" RAM_SIZE="${RAM_SIZE:-1024}" BRIDGE="${BRIDGE:-vmbr0}" NET="${NET:-dhcp}" GATEWAY="${GATEWAY:-}" DNS="${DNS:-}" UNPRIVILEGED="${UNPRIVILEGED:-1}" ENABLE_NESTING="${ENABLE_NESTING:-1}" START_ON_BOOT="${START_ON_BOOT:-1}" HTTP_PORT="${HTTP_PORT_DEFAULT}" TEMPLATE_STORAGE="${TEMPLATE_STORAGE:-$(first_storage vztmpl)}" CONTAINER_STORAGE="${CONTAINER_STORAGE:-$(first_storage rootdir)}" [ -n "$TEMPLATE_STORAGE" ] || die "no storage with 'vztmpl' content type found (need somewhere to keep the LXC template, usually 'local')." [ -n "$CONTAINER_STORAGE" ] || die "no storage with 'rootdir' content type found (need somewhere for the container rootfs, e.g. 'local-lvm')." # Proxmox auto-connect: the app self-attaches to this hypervisor on first # boot. Default on; disable with PROXMOX_AUTOCONNECT=0. The script (running on # the PVE host as root) mints a read-only API token unless you pass your own. PROXMOX_AUTOCONNECT="${PROXMOX_AUTOCONNECT:-1}" PROXMOX_URL="${PROXMOX_URL:-}" # default: https://:8006 PROXMOX_USER="${PROXMOX_USER:-node-stats@pam}" PROXMOX_ROLE="${PROXMOX_ROLE:-PVEAuditor}" # read-only; sees all nodes/guests/storage PROXMOX_TOKEN_NAME="${PROXMOX_TOKEN_NAME:-nodestats-c${CTID}}" PROXMOX_TOKEN_ID="${PROXMOX_TOKEN_ID:-}" # full id (user@realm!name) if you bring your own PROXMOX_TOKEN_SECRET="${PROXMOX_TOKEN_SECRET:-}" PROXMOX_SKIP_TLS_VERIFY="${PROXMOX_SKIP_TLS_VERIFY:-1}" } # host_ipv4 — the PVE host's primary IPv4 (the address a container reaches it on). host_ipv4() { local ip ip="$(ip -4 route get 1.1.1.1 2>/dev/null | sed -n 's/.*src \([0-9.]*\).*/\1/p' | head -1 || true)" [ -z "$ip" ] && ip="$(hostname -I 2>/dev/null | awk '{print $1}' || true)" printf '%s' "$ip" } # gen_secret — 64 hex chars (openssl, /dev/urandom fallback). gen_secret() { if command -v openssl >/dev/null 2>&1; then openssl rand -hex 32 else head -c 32 /dev/urandom | od -An -tx1 | tr -d ' \n' fi } is_off() { case "$(printf '%s' "$1" | tr 'A-Z' 'a-z')" in 0 | false | off | no) return 0 ;; *) return 1 ;; esac; } # whiptail wizard (ADVANCED=1 or no env CTID + a terminal). Falls back silently. advanced_settings() { command -v whiptail >/dev/null 2>&1 || { msg_warn "whiptail missing — using defaults."; return; } exec 3>/dev/tty || { msg_warn "no terminal — using defaults."; return; } local v v=$(whiptail --inputbox "Container ID (CTID)" 8 60 "$CTID" --title "node-stats LXC" 3>&1 1>&2 2>&3) && CTID="$v" v=$(whiptail --inputbox "Hostname" 8 60 "$CT_HOSTNAME" --title "node-stats LXC" 3>&1 1>&2 2>&3) && CT_HOSTNAME="$v" v=$(whiptail --inputbox "Disk size (GB)" 8 60 "$DISK_SIZE" --title "node-stats LXC" 3>&1 1>&2 2>&3) && DISK_SIZE="$v" v=$(whiptail --inputbox "CPU cores" 8 60 "$CORE_COUNT" --title "node-stats LXC" 3>&1 1>&2 2>&3) && CORE_COUNT="$v" v=$(whiptail --inputbox "RAM (MB)" 8 60 "$RAM_SIZE" --title "node-stats LXC" 3>&1 1>&2 2>&3) && RAM_SIZE="$v" v=$(whiptail --inputbox "Network bridge" 8 60 "$BRIDGE" --title "node-stats LXC" 3>&1 1>&2 2>&3) && BRIDGE="$v" v=$(whiptail --inputbox "IP (dhcp or CIDR e.g. 192.168.1.50/24)" 8 70 "$NET" --title "node-stats LXC" 3>&1 1>&2 2>&3) && NET="$v" if [ "$NET" != dhcp ]; then v=$(whiptail --inputbox "Gateway" 8 60 "$GATEWAY" --title "node-stats LXC" 3>&1 1>&2 2>&3) && GATEWAY="$v" fi if whiptail --yesno "Unprivileged container? (recommended)" 8 60 --title "node-stats LXC" 3>&1 1>&2 2>&3; then UNPRIVILEGED=1; else UNPRIVILEGED=0; fi exec 3>&- || true } confirm_settings() { cat </dev/null | awk '{print $1}' \ | sed 's|.*vztmpl/||' | grep -E "^${search}.*${HOST_ARCH}.*\.tar\.(zst|gz|xz)$" \ | sort -V | tail -1 || true)" if [ -z "${TEMPLATE:-}" ]; then run pveam update || true # Match the file name itself, not a column: the table's layout differs between PVE releases. TEMPLATE="$(pveam available -section system 2>/dev/null \ | grep -oE "${search}_[^[:space:]]*_${HOST_ARCH}\.tar\.(zst|gz|xz)" \ | sort -V | tail -1 || true)" [ -n "$TEMPLATE" ] || die "could not find a ${search}_*_${HOST_ARCH} template via 'pveam available'." msg_info "Downloading template ${TEMPLATE} to ${TEMPLATE_STORAGE}" local out if ! out="$(pveam download "$TEMPLATE_STORAGE" "$TEMPLATE" 2>&1)"; then printf '%s\n' "$out" | tail -15 >&2 die "template download failed (pveam output above)." fi fi TEMPLATE_VOLID="${TEMPLATE_STORAGE}:vztmpl/${TEMPLATE}" msg_ok "Template ready: ${TEMPLATE}" } # ---- create ---------------------------------------------------------------- build_netline() { local line="name=eth0,bridge=${BRIDGE}" if [ "$NET" = dhcp ]; then line="${line},ip=dhcp" else line="${line},ip=${NET}" [ -n "$GATEWAY" ] && line="${line},gw=${GATEWAY}" fi printf '%s' "$line" } create_lxc() { pct status "$CTID" >/dev/null 2>&1 && die "CTID ${CTID} already exists — pick another (set CTID=...)." msg_info "Creating LXC ${CTID}" local args=( "$CTID" "$TEMPLATE_VOLID" --hostname "$CT_HOSTNAME" --cores "$CORE_COUNT" --memory "$RAM_SIZE" --swap "$RAM_SIZE" --rootfs "${CONTAINER_STORAGE}:${DISK_SIZE}" --net0 "$(build_netline)" --unprivileged "$UNPRIVILEGED" --onboot "$START_ON_BOOT" --ostype debian --tags "node-stats;monitoring" ) [ -n "$DNS" ] && args+=(--nameserver "$DNS") [ "$ENABLE_NESTING" = "1" ] && args+=(--features "nesting=1") run pct create "${args[@]}" || die "pct create failed (re-run with VERBOSE=1 to see the error)." msg_ok "Created LXC ${CTID}" msg_info "Starting LXC ${CTID}" run pct start "$CTID" || die "pct start failed." # wait for an IPv4 (DHCP) / networking to settle local ip="" for _ in $(seq 1 30); do ip="$(pct exec "$CTID" -- hostname -I 2>/dev/null | awk '{print $1}')" || true [ -n "$ip" ] && break sleep 1 done CONTAINER_IP="${ip:-unknown}" msg_ok "Started — container IP ${CONTAINER_IP}" } # ---- install node-stats inside the container ------------------------------- install_app() { msg_info "Installing dependencies inside the container" run pct exec "$CTID" -- bash -c 'export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get install -y -qq curl ca-certificates' \ || die "apt dependency install failed." msg_ok "Dependencies installed" msg_info "Installing ${APP} (latest release .deb)" # Resolve tag + arch and apt-install the .deb (its postinstall enables the # node-stats systemd service on :8080). NODE_STATS_VERSION pins a release. pct exec "$CTID" -- bash -c " set -e export DEBIAN_FRONTEND=noninteractive REPO='${REPO}' CHANNEL='${CHANNEL}' ARCH=\$(dpkg --print-architecture) TAG='${NODE_STATS_VERSION:-}' MIRROR='${MIRROR}' MIRROR_API=\$(printf '%s' \"\$MIRROR\" | sed -E 's#^(https?://[^/]+)/(.*)#\\1/api/v1/repos/\\2#') # The mirror first, then GitHub (same releases; /releases/latest skips # prereleases on both, so beta lists /releases and takes the newest). tag_of() { curl -fsSL \"\$1\" 2>/dev/null | grep -o '\"tag_name\": *\"[^\"]*\"' | head -1 | sed 's/.*\"\\([^\"]*\\)\"\$/\\1/'; } WHAT=releases/latest [ \"\$CHANNEL\" = beta ] && WHAT='releases?per_page=20&limit=20' BASE=\$MIRROR [ -n \"\$MIRROR\" ] || BASE=https://github.com/\$REPO if [ -z \"\$TAG\" ]; then [ -z \"\$MIRROR\" ] || TAG=\$(tag_of \"\$MIRROR_API/\$WHAT\") if [ -z \"\$TAG\" ] && [ -n \"\$REPO\" ]; then TAG=\$(tag_of https://api.github.com/repos/\$REPO/\$WHAT); BASE=https://github.com/\$REPO fi fi [ -n \"\$TAG\" ] || { echo 'could not resolve latest release tag'; exit 1; } # GitHub serves the prerelease .deb with '.' (it sanitizes nfpm's '~'): # tag v0.8.3-beta.14 → node-stats_0.8.3.beta.14_.deb. Gitea keeps # the '~'. A pinned NODE_STATS_VERSION tries the mirror, then GitHub. deb_for() { if [ \"\$1\" = \"https://github.com/\$REPO\" ]; then printf 'node-stats_%s_%s.deb' \"\$(printf '%s' \"\${TAG#v}\" | tr '-' '.')\" \"\$ARCH\"; else printf 'node-stats_%s_%s.deb' \"\$(printf '%s' \"\${TAG#v}\" | tr '-' '~')\" \"\$ARCH\"; fi; } DEB=\$(deb_for \"\$BASE\") echo \" downloading \$DEB\" if ! curl -fsSL -o /tmp/\$DEB \"\$BASE/releases/download/\$TAG/\$DEB\"; then if [ \"\$BASE\" = \"\$MIRROR\" ]; then [ -n \"\$REPO\" ] || exit 1; BASE=https://github.com/\$REPO; else [ -n \"\$MIRROR\" ] || exit 1; BASE=\$MIRROR; fi DEB=\$(deb_for \"\$BASE\") curl -fsSL -o /tmp/\$DEB \"\$BASE/releases/download/\$TAG/\$DEB\" fi apt-get install -y -qq /tmp/\$DEB rm -f /tmp/\$DEB " || die "node-stats install failed (re-run with VERBOSE=1)." msg_ok "${APP} installed" # Persist the beta channel in the container so the booted server + its # self-updater follow beta (the systemd unit's WorkingDirectory is # /var/lib/node-stats, where the server reads .env). if [ "$CHANNEL" = beta ]; then msg_info "Recording the beta release channel" run pct exec "$CTID" -- bash -c " mkdir -p /var/lib/node-stats && touch /var/lib/node-stats/.env grep -q '^NODE_STATS_RELEASE_CHANNEL=' /var/lib/node-stats/.env || echo 'NODE_STATS_RELEASE_CHANNEL=beta' >> /var/lib/node-stats/.env systemctl restart node-stats 2>/dev/null || true " && msg_ok "Beta release channel recorded" || msg_warn "could not record the beta channel; switch it in the UI" fi # Apply a custom HTTP port via a systemd drop-in (default service is :8080). if [ "$HTTP_PORT" != "8080" ]; then msg_info "Setting HTTP port to ${HTTP_PORT}" run pct exec "$CTID" -- bash -c " mkdir -p /etc/systemd/system/node-stats.service.d printf '[Service]\nEnvironment=ADDR=:${HTTP_PORT}\n' > /etc/systemd/system/node-stats.service.d/port.conf systemctl daemon-reload && systemctl restart node-stats " || msg_warn "could not apply custom port; service stays on :8080" msg_ok "HTTP port set to ${HTTP_PORT}" fi } # Mint (or accept) a read-only Proxmox API token and hand it to the container, # so node-stats auto-attaches to this hypervisor on first boot. Best-effort: # every failure degrades to "add the connector in the UI" without aborting the # install. Idempotent: an already-existing token is left untouched (its secret # can't be read back, so rotating it would break the existing connector). AUTOCONNECT_NOTE="" configure_proxmox_autoconnect() { if is_off "$PROXMOX_AUTOCONNECT"; then msg_warn "Proxmox auto-connect disabled (PROXMOX_AUTOCONNECT=0)." return fi local url token_id secret url="${PROXMOX_URL:-https://$(host_ipv4):8006}" if [ -n "$PROXMOX_TOKEN_ID" ] && [ -n "$PROXMOX_TOKEN_SECRET" ]; then token_id="$PROXMOX_TOKEN_ID" secret="$PROXMOX_TOKEN_SECRET" msg_ok "Using the Proxmox API token from env" else command -v pveum >/dev/null 2>&1 || { msg_warn "pveum not found — skipping auto-connect (add the connector in the UI)."; return; } token_id="${PROXMOX_USER}!${PROXMOX_TOKEN_NAME}" msg_info "Issuing read-only Proxmox API token ${token_id} (role ${PROXMOX_ROLE})" run pveum user add "$PROXMOX_USER" --comment "node-stats monitoring (auto-created)" 2>/dev/null || true run pveum acl modify / -user "$PROXMOX_USER" -role "$PROXMOX_ROLE" || { msg_warn "could not grant ${PROXMOX_ROLE} to ${PROXMOX_USER} — skipping auto-connect."; return; } # PVE API tokens live at the datacenter level and OUTLIVE the container, so # a leftover from a previous run on this CTID is still here after a # destroy+recreate. Rotate it (remove + re-add): a freshly created container # has an empty DB (no connector yet), so re-issuing the secret can't orphan # anything — and we can't read an existing token's secret back to reuse it. run pveum user token remove "$PROXMOX_USER" "$PROXMOX_TOKEN_NAME" 2>/dev/null || true local out out="$(pveum user token add "$PROXMOX_USER" "$PROXMOX_TOKEN_NAME" --privsep 0 --output-format json 2>/dev/null)" secret="$(printf '%s' "$out" | sed -n 's/.*"value"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' | head -1)" [ -n "$secret" ] || { msg_warn "could not create/parse the API token — skipping auto-connect."; return; } msg_ok "Issued Proxmox API token ${token_id}" fi local skip=true is_off "$PROXMOX_SKIP_TLS_VERIFY" && skip=false # Pre-seed stable JWT/REFRESH secrets (so the encrypted token survives the # setup wizard + restarts) and hand the Proxmox creds to the app via its .env. local jwt refresh jwt="$(gen_secret)" refresh="$(gen_secret)" msg_info "Wiring auto-connect into the container (${url})" pct exec "$CTID" -- bash -c " set -e mkdir -p /var/lib/node-stats f=/var/lib/node-stats/.env touch \"\$f\"; chmod 600 \"\$f\" set_kv() { if grep -q \"^\$1=\" \"\$f\" 2>/dev/null; then sed -i \"s#^\$1=.*#\$1=\$2#\" \"\$f\"; else echo \"\$1=\$2\" >>\"\$f\"; fi; } set_default() { grep -q \"^\$1=\" \"\$f\" 2>/dev/null || echo \"\$1=\$2\" >>\"\$f\"; } set_default JWT_SECRET '${jwt}' set_default REFRESH_SECRET '${refresh}' set_kv NODE_STATS_PROXMOX_URL '${url}' set_kv NODE_STATS_PROXMOX_TOKEN_ID '${token_id}' set_kv NODE_STATS_PROXMOX_TOKEN_SECRET '${secret}' set_kv NODE_STATS_PROXMOX_SKIP_TLS_VERIFY '${skip}' systemctl restart node-stats " || { msg_warn "could not wire auto-connect into the container."; return; } msg_ok "Proxmox auto-connect configured → app will attach to ${url} on boot" AUTOCONNECT_NOTE="${url}" } # ---- join an existing cluster ------------------------------------------------ # The same request the setup wizard's "Join an existing cluster" sends, made # from inside the container so the app sees its own loopback. The container's # address is known here (pct), so nothing has to be typed into the wizard. JOINED="" json_int() { grep -o "\"$1\":[0-9]*" | head -1 | grep -o '[0-9]*$' || true; } ct_api() { pct exec "$CTID" -- curl -sS -m "$1" "${@:2}"; } join_cluster() { local url="${NODE_STATS_JOIN_URL%/}" key="$NODE_STATS_JOIN_KEY" local raft_port="${RAFT_PORT:-7000}" api="http://127.0.0.1:${HTTP_PORT}/api/v1" [ "$CONTAINER_IP" != unknown ] || die "the container has no IPv4 yet — cannot tell the cluster where to reach it. Join from the setup wizard instead." msg_info "Waiting for ${APP} to answer inside the container" local status="" for _ in $(seq 1 60); do status="$(ct_api 3 -f "${api}/setup/status" 2>/dev/null || true)" [ -n "$status" ] && break sleep 2 done [ -n "$status" ] || die "${APP} did not come up (pct exec ${CTID} -- journalctl -u node-stats)." printf '%s' "$status" | grep -q '"setup_needed":true' || die "this node is already set up; join it from Admin → Nodes → Cluster sync instead." msg_ok "${APP} is up" # Our own node id: the Proxmox machine's name + a short random suffix # (pve-b-a3f1). Not the container's hostname — every container this script # makes is called "node-stats", and a joiner reusing a member's id makes an # older leader rewrite THAT member's address instead of adding us. local node_id machine machine="$(hostname -s 2>/dev/null | tr '[:upper:] ' '[:lower:]-' || true)" node_id="${RAFT_NODE_ID:-${machine:-pve}-$(od -An -N2 -tx1 /dev/urandom | tr -d ' \n')}" msg_info "Joining the cluster at ${url} as ${node_id}" local body resp code body="$(printf '{"peer_url":"%s","token":"%s","node_id":"%s","advertise_addr":"%s:%s","bind_addr":":%s","advertise_url":"http://%s:%s"}' \ "$url" "$key" "$node_id" "$CONTAINER_IP" "$raft_port" "$raft_port" "$CONTAINER_IP" "$HTTP_PORT")" resp="$(ct_api 90 -X POST "${api}/setup/join-raft-cluster" -H 'Content-Type: application/json' \ -d "$body" -w '\n%{http_code}' 2>&1 || true)" code="$(printf '%s' "$resp" | tail -1)" if [ "$code" != 200 ]; then printf '%s\n' "$resp" | sed '$d' >&2 die "the cluster refused the join (HTTP ${code}). Token expired or already used? Issue a new one under Admin → Nodes, then on this host: NODE_STATS_JOIN_URL=… NODE_STATS_JOIN_KEY=… NODE_STATS_REPO=${REPO} NODE_STATS_UPDATE_MIRROR=${MIRROR:-off} bash -c \"\$(curl -fsSL ${SELF_RAW}/scripts/proxmox-lxc.sh | awk 'NR==1&&substr(\$0,1,1)!=\"#\"{exit 1}{print}END{if(NR==0)exit 1}')\" _ join ${CTID}" fi msg_ok "Join accepted" msg_info "Pulling the cluster's state (users, settings, history — a large history takes minutes)" local progress applied commit leader i data free free_kb for i in $(seq 1 600); do progress="$(ct_api 5 -f "${api}/setup/raft-progress" 2>/dev/null || true)" applied="$(printf '%s' "$progress" | json_int applied_index)" commit="$(printf '%s' "$progress" | json_int commit_index)" if printf '%s' "$progress" | grep -q '"enabled":true' && [ -n "$applied" ] && [ -n "$commit" ] && [ "$commit" -gt 0 ] && [ "$applied" -ge "$commit" ]; then msg_ok "In sync with the cluster" JOINED="$url" return fi # Every 10 s: where it is, and whether the disk will hold the cluster's database. if [ $((i % 5)) -eq 1 ]; then leader="$(printf '%s' "$progress" | sed -n 's/.*"leader_id":"\([^"]*\)".*/\1/p')" data="$(pct exec "$CTID" -- du -sh /var/lib/node-stats 2>/dev/null | cut -f1 || true)" free_kb="$(pct exec "$CTID" -- df -Pk / 2>/dev/null | awk 'NR==2 {print $4}' || true)" free="$([ -n "$free_kb" ] && awk -v k="$free_kb" 'BEGIN {printf "%.1fG", k/1048576}')" printf ' applied %s / %s · leader %s · data %s · disk free %s\n' \ "${applied:-0}" "${commit:-?}" "${leader:-not yet}" "${data:-?}" "${free:-?}" if [ -n "$free_kb" ] && [ "$free_kb" -lt 262144 ]; then msg_warn "the container's disk is almost full — the cluster's database will not fit. Grow it: pct resize ${CTID} rootfs +8G (it carries on by itself)." fi fi sleep 2 done msg_warn "still catching up after 20 min — it continues on its own; check Admin → Nodes on ${url}." JOINED="$url" } summary() { local connector_line if [ -n "$AUTOCONNECT_NOTE" ]; then connector_line=" ${CM} Auto-connected to Proxmox at ${BL}${AUTOCONNECT_NOTE}${CL} — the hypervisor + every VM/LXC appear automatically once you finish setup." else connector_line=" ${INFO} The container monitors itself out of the box. To see the Proxmox host + every VM/LXC, add a ${BL}Proxmox connector${CL} after setup (admin → Connectors). See docs/PROXMOX.md." fi cat <" pct status "$id" >/dev/null 2>&1 || die "no container ${id}." CTID="$id" HTTP_PORT="$(pct exec "$id" -- sed -n 's/^Environment=ADDR=://p' /etc/systemd/system/node-stats.service.d/port.conf 2>/dev/null || true)" HTTP_PORT="${HTTP_PORT:-8080}" CONTAINER_IP="$(pct exec "$id" -- hostname -I 2>/dev/null | awk '{print $1}' || true)" CONTAINER_IP="${CONTAINER_IP:-unknown}" join_cluster # Proxmox auto-connect runs at boot; restart so it attaches this hypervisor # to the cluster (whatever it created while standalone was just replaced). run pct exec "$id" -- systemctl restart node-stats || true msg_ok "Done — open http://${CONTAINER_IP}:${HTTP_PORT} and sign in with your cluster account." } # Re-wire (or first-time wire) Proxmox auto-connect into an EXISTING container, # without recreating it — handy after upgrading to a release that supports # auto-connect, or to fix a container whose env was never wired. Preserves an # already-set JWT/REFRESH secret (won't log out an existing install); the # Proxmox token is rotated and re-handed to the app. cmd_reconnect() { preflight local id="${1:-}" [ -n "$id" ] || die "usage: proxmox-lxc.sh reconnect " pct status "$id" >/dev/null 2>&1 || die "no container ${id}." CTID="$id" set_defaults run pct start "$id" 2>/dev/null || true configure_proxmox_autoconnect [ -n "$AUTOCONNECT_NOTE" ] && msg_ok "Done — reload the dashboard; the hypervisor + guests appear within ~10s." || msg_warn "Nothing wired (auto-connect disabled or no token). See messages above." } cmd_update() { preflight local id="${1:-}" [ -n "$id" ] || die "usage: proxmox-lxc.sh update " pct status "$id" >/dev/null 2>&1 || die "no container ${id}." msg_info "Updating node-stats in LXC ${id} (latest release .deb)" run pct start "$id" 2>/dev/null || true # Explicit channel switch: NODE_STATS_CHANNEL=beta|stable persists the channel # into the container before updating (the running server follows it too). Without # it, update follows whatever channel the container is already on. if [ -n "${NODE_STATS_CHANNEL:-}" ]; then msg_info "Setting release channel to ${CHANNEL}" run pct exec "$id" -- bash -c " mkdir -p /var/lib/node-stats && touch /var/lib/node-stats/.env if grep -q '^NODE_STATS_RELEASE_CHANNEL=' /var/lib/node-stats/.env; then sed -i 's/^NODE_STATS_RELEASE_CHANNEL=.*/NODE_STATS_RELEASE_CHANNEL=${CHANNEL}/' /var/lib/node-stats/.env else echo 'NODE_STATS_RELEASE_CHANNEL=${CHANNEL}' >> /var/lib/node-stats/.env fi " && msg_ok "Channel set to ${CHANNEL}" || msg_warn "could not set channel; using the container's current one" fi # Install the latest release .deb directly (same path as a fresh install). # The binary's own `node-stats update` self-replace pulls a tarball asset and # is easy to break with release-asset naming drift; apt-installing the .deb is # the reliable path on a Debian LXC. NODE_STATS_VERSION pins a release. pct exec "$id" -- bash -c " set -e export DEBIAN_FRONTEND=noninteractive REPO='${REPO}' ARCH=\$(dpkg --print-architecture) # Follow whatever channel the container was installed on (persisted in .env). CHANNEL=\$(sed -n 's/^NODE_STATS_RELEASE_CHANNEL=//p' /var/lib/node-stats/.env 2>/dev/null | head -1) TAG='${NODE_STATS_VERSION:-}' MIRROR='${MIRROR}' MIRROR_API=\$(printf '%s' \"\$MIRROR\" | sed -E 's#^(https?://[^/]+)/(.*)#\\1/api/v1/repos/\\2#') # The mirror first, then GitHub (same releases; /releases/latest skips # prereleases on both, so beta lists /releases and takes the newest). tag_of() { curl -fsSL \"\$1\" 2>/dev/null | grep -o '\"tag_name\": *\"[^\"]*\"' | head -1 | sed 's/.*\"\\([^\"]*\\)\"\$/\\1/'; } WHAT=releases/latest [ \"\$CHANNEL\" = beta ] && WHAT='releases?per_page=20&limit=20' BASE=\$MIRROR [ -n \"\$MIRROR\" ] || BASE=https://github.com/\$REPO if [ -z \"\$TAG\" ]; then [ -z \"\$MIRROR\" ] || TAG=\$(tag_of \"\$MIRROR_API/\$WHAT\") if [ -z \"\$TAG\" ] && [ -n \"\$REPO\" ]; then TAG=\$(tag_of https://api.github.com/repos/\$REPO/\$WHAT); BASE=https://github.com/\$REPO fi fi [ -n \"\$TAG\" ] || { echo 'could not resolve latest release tag'; exit 1; } # GitHub serves the prerelease .deb with '.' (it sanitizes nfpm's '~'): # tag v0.8.3-beta.14 → node-stats_0.8.3.beta.14_.deb. Gitea keeps # the '~'. A pinned NODE_STATS_VERSION tries the mirror, then GitHub. deb_for() { if [ \"\$1\" = \"https://github.com/\$REPO\" ]; then printf 'node-stats_%s_%s.deb' \"\$(printf '%s' \"\${TAG#v}\" | tr '-' '.')\" \"\$ARCH\"; else printf 'node-stats_%s_%s.deb' \"\$(printf '%s' \"\${TAG#v}\" | tr '-' '~')\" \"\$ARCH\"; fi; } DEB=\$(deb_for \"\$BASE\") echo \" downloading \$DEB\" if ! curl -fsSL -o /tmp/\$DEB \"\$BASE/releases/download/\$TAG/\$DEB\"; then if [ \"\$BASE\" = \"\$MIRROR\" ]; then [ -n \"\$REPO\" ] || exit 1; BASE=https://github.com/\$REPO; else [ -n \"\$MIRROR\" ] || exit 1; BASE=\$MIRROR; fi DEB=\$(deb_for \"\$BASE\") curl -fsSL -o /tmp/\$DEB \"\$BASE/releases/download/\$TAG/\$DEB\" fi apt-get install -y -qq --allow-downgrades /tmp/\$DEB rm -f /tmp/\$DEB systemctl restart node-stats " || die "update failed (re-run with VERBOSE=1)." msg_ok "Updated node-stats in LXC ${id}" } cmd_uninstall() { preflight local id="${1:-}" [ -n "$id" ] || die "usage: proxmox-lxc.sh uninstall " pct status "$id" >/dev/null 2>&1 || die "no container ${id}." msg_warn "This will STOP and DESTROY container ${id} and all its data." if [ -e /dev/tty ]; then printf ' Type the CTID (%s) to confirm: ' "$id" >/dev/tty local reply=""; IFS= read -r reply |reconnect |update |uninstall }\n' ;; *) die "unknown command '${1}' (use create|join|reconnect|update|uninstall)" ;; esac } main "$@"