interplane-forge
INTERPLANE Forge
Brought by drakestapleton
interplane-forge / infra / spark / forged-service.sh
| 1 | #!/usr/bin/env bash |
| 2 | # forged on spark: supervised restart loop, pinned to cores 4-5 at nice 10. In production the loop |
| 3 | # runs as the systemd user unit interplane-forged.service (infra/spark/interplane-forged.service, |
| 4 | # Restart=always); without that unit, start runs it in the tmux session `forged`. |
| 5 | # forged binds 127.0.0.1:18480 only. seed/net servers serve a bounded number of connections |
| 6 | # per run and expect a supervisor to restart them: the loop below is that supervisor. |
| 7 | # |
| 8 | # Usage: infra/spark/forged-service.sh start|stop|restart|status|reload |
| 9 | # When the unit FORGED_UNIT (default interplane-forged.service) is loaded and runs this data |
| 10 | # directory (its Environment has FORGE_DATA=<this DATA>), start, stop, restart and status act |
| 11 | # through systemctl --user on that unit; a private run with another FORGE_DATA never touches it. |
| 12 | # reload = re-read the RIDS.md allow-list and social log without a restart. Per CONTRACT, |
| 13 | # forged checks the flag file <data>/reload between connections; this script creates it. |
| 14 | # `kill -HUP <supervisor pid>` (pid in <data>/forged-supervisor.pid) does the same: the |
| 15 | # supervisor turns SIGHUP into the flag file, and forged itself never sees the signal. |
| 16 | # Env: FORGED_BIN (default ~/work/forge/web/server/forged), FORGE_DATA (default ~/forge-data), |
| 17 | # FORGED_CPUS (default 4-5; never 3, 7 or 15), FORGED_SANDBOX and FORGED_NETNS (default on; |
| 18 | # off prints a loud warning). |
| 19 | # The port: the supervisor takes 127.0.0.1:PORT once, through forged-listen (beside FORGED_BIN), |
| 20 | # and holds that listening socket for its whole life. Every forged it starts gets the same |
| 21 | # socket on descriptor 0. The port is never unbound while the supervisor runs, so connections |
| 22 | # that arrive while forged restarts wait in the socket's queue for the next forged, and no |
| 23 | # other local process can take the port in between. If the port is taken at start, the |
| 24 | # supervisor does not start (forged-listen exits 3). |
| 25 | set -u |
| 26 | SESSION=${FORGED_SESSION:-forged} # FORGED_SESSION / FORGED_PORT: only for testing with a stand-in; |
| 27 | PORT=${FORGED_PORT:-18480} # forged itself always binds 127.0.0.1:18480 |
| 28 | BIN=${FORGED_BIN:-$HOME/work/forge/web/server/forged} |
| 29 | DATA=${FORGE_DATA:-$HOME/forge-data} |
| 30 | CPUS=${FORGED_CPUS:-4-5} |
| 31 | LOG=$DATA/logs/forged.log |
| 32 | SELF=$(cd "$(dirname "$0")" && pwd)/$(basename "$0") |
| 33 | SANDBOX=$(dirname "$SELF")/forged-sandbox.sh |
| 34 | UNIT=${FORGED_UNIT:-interplane-forged.service} |
| 35 | source "$(dirname "$SELF")/forged-public.sh" |
| 36 | source "$(dirname "$SELF")/forged-counts.sh" |
| 37 | INTERVAL=${FORGED_MIRROR_INTERVAL:-2} |
| 38 | [[ $INTERVAL =~ ^[1-9][0-9]?$ ]] || { echo "bad mirror interval" >&2; exit 2; } |
| 39 | |
| 40 | case ",$CPUS," in *[!0-9,-]*) echo "bad FORGED_CPUS '$CPUS'" >&2; exit 2;; esac |
| 41 | # Hive rule: never cores 3, 7 or 15. |
| 42 | IFS=, read -ra parts <<<"$CPUS" |
| 43 | for part in "${parts[@]}"; do |
| 44 | lo=${part%-*}; hi=${part#*-} |
| 45 | for c in 3 7 15; do |
| 46 | [ "$c" -ge "$lo" ] && [ "$c" -le "$hi" ] && { echo "FORGED_CPUS '$CPUS' includes forbidden core $c" >&2; exit 2; } |
| 47 | done |
| 48 | done |
| 49 | |
| 50 | listening() { ss -ltnH "sport = :$PORT" 2>/dev/null | grep -q .; } |
| 51 | pid_of() { local s; s=$(cat "$DATA/forged-supervisor.pid" 2>/dev/null); [ -n "$s" ] && pgrep -P "$s" -f "$BIN" | head -1; } |
| 52 | running() { tmux has-session -t "=$SESSION" 2>/dev/null; } |
| 53 | flag_file() { |
| 54 | # Never follow a symlink planted by the writable-data child into the owner's account. |
| 55 | local tmp |
| 56 | tmp=$(mktemp "$DATA/.$1.XXXXXX") || return 1 |
| 57 | mv -Tf -- "$tmp" "$DATA/$1" || { rm -f -- "$tmp"; return 1; } |
| 58 | } |
| 59 | reload_flag() { flag_file reload; } |
| 60 | # The settings the supervisor runs with, passed explicitly (tmux and forged-listen pass no |
| 61 | # environment of their own). |
| 62 | service_env() { |
| 63 | svc_env=(HOME="$HOME" PATH=/usr/bin:/bin |
| 64 | FORGED_SESSION="$SESSION" FORGED_PORT="$PORT" |
| 65 | FORGED_BIN="$BIN" FORGE_DATA="$DATA" FORGED_CPUS="$CPUS" FORGED_SANDBOX="${FORGED_SANDBOX:-on}" |
| 66 | FORGED_NETNS="${FORGED_NETNS:-on}" |
| 67 | FORGED_PUBLIC_DIR="${FORGED_PUBLIC_DIR:-$DATA/../forge-public}" |
| 68 | FORGED_PUBLIC_READER="${FORGED_PUBLIC_READER:-$(dirname "$BIN")/public-read}" |
| 69 | FORGED_READ_HOME="${FORGED_READ_HOME:-$HOME}" FORGED_PATH_HOME="${FORGED_PATH_HOME:-/home/drakestapleton}" |
| 70 | FORGED_COUNTS_INTERVAL="${FORGED_COUNTS_INTERVAL:-900}" |
| 71 | FORGED_COUNTS_STATE="${FORGED_COUNTS_STATE:-$DATA/../forge-counts-state}" |
| 72 | FORGED_MIRROR_INTERVAL="$INTERVAL" FORGED_SALVAGE="${FORGED_SALVAGE:-off}") |
| 73 | # the native store root of a store-reading build (forged-sandbox.sh binds it read-only) |
| 74 | svc_env+=(FORGED_PUBLIC_GIT="${FORGED_PUBLIC_GIT:-off}") |
| 75 | [[ -z ${FORGED_STORE:-} ]] || svc_env+=(FORGED_STORE="$FORGED_STORE") |
| 76 | [[ -z ${FORGED_PUBLIC_LIB:-} ]] || svc_env+=(FORGED_PUBLIC_LIB="$FORGED_PUBLIC_LIB") |
| 77 | [[ -z ${FORGED_LISTEN_HELPER:-} ]] || svc_env+=(FORGED_LISTEN_HELPER="$FORGED_LISTEN_HELPER") |
| 78 | [[ -z ${FORGED_SECCOMP:-} ]] || svc_env+=(FORGED_SECCOMP="$FORGED_SECCOMP") |
| 79 | } |
| 80 | listen_helper() { |
| 81 | local l d |
| 82 | l=$(realpath -e "${FORGED_LISTEN_HELPER:-$(dirname "$BIN")/forged-listen}") || |
| 83 | { echo "forged: missing forged-listen beside $BIN (./run.sh build makes it)" >&2; return 2; } |
| 84 | [[ -f $l && -x $l ]] || { echo "forged: $l is not an executable file" >&2; return 2; } |
| 85 | # The owner runs it unsandboxed: refuse one the sandboxed child could have written. |
| 86 | d=$(realpath -e "$DATA") || return 2 |
| 87 | case "$l" in "$d"/*|"$(realpath -m "${FORGED_PUBLIC_DIR:-$DATA/../forge-public}")"/*) |
| 88 | echo "forged: refusing forged-listen inside data or export: $l" >&2; return 2;; esac |
| 89 | printf '%s\n' "$l" |
| 90 | } |
| 91 | |
| 92 | # The systemd unit runs this data directory: it is loaded and its Environment names FORGE_DATA=DATA. |
| 93 | # Then, unless FORGED_BIN was given, BIN is the unit's build (FORGED_DIR/out/forged). |
| 94 | under_unit() { |
| 95 | command -v systemctl >/dev/null 2>&1 || return 1 |
| 96 | [ "$(systemctl --user show -p LoadState --value "$UNIT" 2>/dev/null)" = loaded ] || return 1 |
| 97 | local want e ok=1 dir= |
| 98 | want=$(realpath -m "$DATA") |
| 99 | for e in $(systemctl --user show -p Environment --value "$UNIT" 2>/dev/null); do |
| 100 | case $e in |
| 101 | FORGE_DATA=*) [ "$(realpath -m "${e#FORGE_DATA=}")" = "$want" ] && ok=0 ;; |
| 102 | FORGED_DIR=*) dir=${e#FORGED_DIR=} ;; |
| 103 | esac |
| 104 | done |
| 105 | [ "$ok" = 0 ] && [ -z "${FORGED_BIN:-}" ] && [ -n "$dir" ] && BIN=$dir/out/forged |
| 106 | return "$ok" |
| 107 | } |
| 108 | # Up means: the supervisor holds the port, forged runs, and an HTTP request gets an answer (20 s). |
| 109 | # $1: a check that the supervisor still runs (stop waiting when it fails), or none. |
| 110 | wait_up() { |
| 111 | local i code |
| 112 | for i in $(seq 1 40); do |
| 113 | [ -n "${1:-}" ] && ! "$1" && break |
| 114 | if listening && [ -n "$(pid_of)" ]; then |
| 115 | code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 2 "http://127.0.0.1:$PORT/") |
| 116 | [ "$code" != 000 ] && { echo "forged up on 127.0.0.1:$PORT (pid $(pid_of), supervisor $(cat "$DATA/forged-supervisor.pid"), GET / -> $code)"; return 0; } |
| 117 | fi |
| 118 | sleep 0.5 |
| 119 | done |
| 120 | return 1 |
| 121 | } |
| 122 | case "${1:-}" in |
| 123 | _loop) # runs inside tmux |
| 124 | if [ -L "$DATA/logs" ] || [ -L "$LOG" ] || [ -L "$DATA/forged-supervisor.pid" ]; then |
| 125 | echo 'forged: refusing symlink in supervisor log or control paths' >&2 |
| 126 | exit 2 |
| 127 | fi |
| 128 | mkdir -p "$DATA/logs" |
| 129 | # The listener. Without one on descriptor 0, take the port through forged-listen, which |
| 130 | # creates 127.0.0.1:PORT (exit 3 if the port is taken), puts it on descriptor 0 and executes |
| 131 | # this loop again under the same process id with exactly the settings below. |
| 132 | if [[ ! -S /dev/stdin ]]; then |
| 133 | listen=$(listen_helper) || exit 2 |
| 134 | service_env |
| 135 | echo "$(date -u +%FT%TZ) supervisor: taking 127.0.0.1:$PORT through $listen" >>"$LOG" |
| 136 | exec "$listen" "$PORT" /usr/bin/env "${svc_env[@]}" /usr/bin/bash "$SELF" _loop |
| 137 | fi |
| 138 | # Descriptor 0 must be the listener on our port, nothing else. |
| 139 | lino=$(readlink /proc/self/fd/0) |
| 140 | lino=${lino#socket:[}; lino=${lino%]} |
| 141 | if ! ss -ltnHe "sport = :$PORT" 2>/dev/null | grep -Eq "ino:$lino( |$)"; then |
| 142 | echo "forged: descriptor 0 is a socket but not the listener on 127.0.0.1:$PORT; refusing" >&2 |
| 143 | exit 2 |
| 144 | fi |
| 145 | # Keep it for the whole life of this loop on its own descriptor, hand it to each forged on |
| 146 | # descriptor 0, and close it in every other long-lived process the loop starts. |
| 147 | exec {LFD}<&0 </dev/null |
| 148 | echo "$(date -u +%FT%TZ) supervisor: holding 127.0.0.1:$PORT for every forged it starts" >>"$LOG" |
| 149 | echo $$ > "$DATA/forged-supervisor.pid" |
| 150 | trap 'reload_flag; echo "$(date -u +%FT%TZ) SIGHUP -> reload flag" >>"$LOG"' HUP |
| 151 | child= |
| 152 | counts_pid= |
| 153 | # stop_child drain: ask forged to finish the connection it is serving and exit (the restart |
| 154 | # flag), and TERM it if it has not within 10 s. Connections that arrive meanwhile wait in the |
| 155 | # listener's queue. stop_child alone: TERM at once (service stop). |
| 156 | stop_child() { |
| 157 | local t |
| 158 | if [[ -n $child ]]; then |
| 159 | if [[ ${1:-} = drain ]] && flag_file restart; then |
| 160 | sleep 10 {LFD}<&- & |
| 161 | t=$! |
| 162 | while kill -0 "$child" 2>/dev/null && kill -0 "$t" 2>/dev/null; do |
| 163 | wait -n "$child" "$t" 2>/dev/null || true |
| 164 | done |
| 165 | kill "$t" 2>/dev/null; wait "$t" 2>/dev/null |
| 166 | if kill -0 "$child" 2>/dev/null; then |
| 167 | echo "$(date -u +%FT%TZ) forged did not exit within 10 s of the restart flag; TERM" >>"$LOG" |
| 168 | fi |
| 169 | fi |
| 170 | kill -TERM "$child" 2>/dev/null || true |
| 171 | rc=0 |
| 172 | wait "$child" 2>/dev/null || rc=$? |
| 173 | child= |
| 174 | fi |
| 175 | } |
| 176 | trap 'exit 0' TERM INT |
| 177 | trap 'counts_stop; stop_child' EXIT |
| 178 | if [[ ${FORGED_SANDBOX:-on} != off ]]; then |
| 179 | public_init || exit 2 |
| 180 | counts_init || exit 2 |
| 181 | public_sync || exit 2 |
| 182 | fi |
| 183 | fast=0 |
| 184 | while true; do |
| 185 | digest=off |
| 186 | if [[ ${FORGED_SANDBOX:-on} != off ]]; then |
| 187 | public_sync || exit 2 |
| 188 | digest=$(public_digest) || exit 2 |
| 189 | counts_tick "$digest" |
| 190 | fi |
| 191 | t0=$(date +%s) |
| 192 | echo "$(date -u +%FT%TZ) start $BIN (cpus $CPUS nice 10)" | tee -a "$LOG" |
| 193 | # Background + wait, so a trapped SIGHUP is handled while forged keeps running. |
| 194 | # The child writes into a pipe, and a logger outside the sandbox appends to the log file. |
| 195 | # With the log file itself as stderr, the sandbox's 1 GiB file-size limit would kill forged |
| 196 | # (SIGXFSZ) once the shared service log grew past it. The pipe also hides the log path. |
| 197 | exec {logw}> >(exec cat >>"$LOG" {LFD}<&-) |
| 198 | taskset -c "$CPUS" nice -n 10 bash "$SANDBOX" "$BIN" <&"$LFD" >&"$logw" 2>&1 & |
| 199 | child=$! |
| 200 | exec {logw}>&- |
| 201 | rc=0; changed=0 |
| 202 | # Existing supervisor cadence, bounded by the mirror interval. No timer/unit. |
| 203 | while kill -0 "$child" 2>/dev/null; do |
| 204 | sleep "$INTERVAL" {LFD}<&- & |
| 205 | wait $! || true |
| 206 | if [[ ${FORGED_SANDBOX:-on} != off ]]; then |
| 207 | if ! public_sync; then stop_child; exit 2; fi |
| 208 | next=$(public_digest) || { stop_child; exit 2; } |
| 209 | counts_tick "$next" |
| 210 | if [[ $next != "$digest" ]]; then |
| 211 | echo "$(date -u +%FT%TZ) allowed repository set changed; restarting child (the port stays held)" >> "$LOG" |
| 212 | stop_child drain |
| 213 | changed=1 |
| 214 | break |
| 215 | fi |
| 216 | fi |
| 217 | done |
| 218 | if [[ -n $child ]]; then wait "$child"; rc=$?; child=; fi |
| 219 | echo "$(date -u +%FT%TZ) forged exited rc=$rc" | tee -a "$LOG" |
| 220 | [[ $changed = 1 ]] && { fast=0; continue; } |
| 221 | # Bounded-run servers exit normally; only back off when it dies within 5 s, 5 times running. |
| 222 | if [ $(( $(date +%s) - t0 )) -lt 5 ]; then fast=$((fast+1)); else fast=0; fi |
| 223 | if [ "$fast" -ge 5 ]; then echo "crash loop: sleeping 30s" | tee -a "$LOG"; sleep 30 {LFD}<&-; fast=0; else sleep 1; fi |
| 224 | done ;; |
| 225 | start) |
| 226 | if under_unit; then |
| 227 | systemctl --user start "$UNIT" || exit 1 |
| 228 | wait_up && exit 0 |
| 229 | echo "forged did not answer on 127.0.0.1:$PORT within 20 s of starting $UNIT. Tail of $LOG:" >&2 |
| 230 | tail -20 "$LOG" >&2; exit 1 |
| 231 | fi |
| 232 | running && { echo "tmux session $SESSION already running"; exit 0; } |
| 233 | [ -x "$BIN" ] || { echo "no executable $BIN (build forged first)" >&2; exit 1; } |
| 234 | listening && { echo "127.0.0.1:$PORT already in use by something else; refusing" >&2; exit 1; } |
| 235 | listen_helper >/dev/null || exit 1 |
| 236 | mkdir -p "$DATA/logs" |
| 237 | # The tmux server does not inherit this shell's environment, and its own environment can hold |
| 238 | # anything an operator shell exported when it started. env -i passes only these settings. |
| 239 | service_env |
| 240 | tmux new-session -d -s "$SESSION" "$(printf '%q ' env -i "${svc_env[@]}" /usr/bin/bash "$SELF" _loop)" |
| 241 | wait_up running && exit 0 |
| 242 | if running; then |
| 243 | echo "forged did not answer on 127.0.0.1:$PORT within 20 s; stopping the supervisor. Tail of $LOG:" >&2 |
| 244 | else |
| 245 | echo "the supervisor exited at start (forged-listen exits 3 when 127.0.0.1:$PORT is taken). Tail of $LOG:" >&2 |
| 246 | fi |
| 247 | tail -20 "$LOG" >&2; "$SELF" stop >/dev/null 2>&1; exit 1 ;; |
| 248 | stop) |
| 249 | if under_unit; then |
| 250 | # systemd sends TERM to the supervisor (its trap stops forged), then ends the rest of the unit. |
| 251 | systemctl --user stop "$UNIT" || exit 1 |
| 252 | for i in $(seq 1 20); do listening || { echo "forged stopped ($UNIT)"; exit 0; }; sleep 0.5; done |
| 253 | echo "port $PORT still bound after stopping $UNIT" >&2; exit 1 |
| 254 | fi |
| 255 | # Supervisor first (TERM; its HUP is trapped), then forged, then the tmux session. |
| 256 | s=$(cat "$DATA/forged-supervisor.pid" 2>/dev/null) |
| 257 | [ -n "$s" ] && kill -0 "$s" 2>/dev/null && kill -TERM "$s" |
| 258 | p=$(pid_of); [ -n "$p" ] && kill "$p" |
| 259 | running && tmux kill-session -t "=$SESSION" |
| 260 | rm -f "$DATA/forged-supervisor.pid" |
| 261 | for i in $(seq 1 20); do listening || { echo "forged stopped"; exit 0; }; sleep 0.5; done |
| 262 | echo "port $PORT still bound after stop" >&2; exit 1 ;; |
| 263 | restart) |
| 264 | if under_unit; then |
| 265 | systemctl --user restart "$UNIT" || exit 1 |
| 266 | wait_up && exit 0 |
| 267 | echo "forged did not answer on 127.0.0.1:$PORT within 20 s of restarting $UNIT" >&2; exit 1 |
| 268 | fi |
| 269 | "$SELF" stop && "$SELF" start ;; |
| 270 | reload) |
| 271 | under_unit || true # only to find the unit's build for pid_of |
| 272 | [ -n "$(pid_of)" ] || { echo "forged not running" >&2; exit 1; } |
| 273 | reload_flag && echo "reload flag $DATA/reload set; forged re-reads before its next connection" ;; |
| 274 | status) |
| 275 | if under_unit; then |
| 276 | echo "systemd $UNIT: $(systemctl --user is-active "$UNIT") ($(systemctl --user is-enabled "$UNIT")), supervisor $(systemctl --user show -p MainPID --value "$UNIT"), restarts $(systemctl --user show -p NRestarts --value "$UNIT")" |
| 277 | else |
| 278 | running && echo "tmux $SESSION: up" || echo "tmux $SESSION: down" |
| 279 | fi |
| 280 | p=$(pid_of); [ -n "$p" ] && echo "pid $p cpus $(taskset -cp "$p" 2>/dev/null | sed 's/.*: //') nice $(ps -o ni= -p "$p")" || echo "pid: none" |
| 281 | listening && echo "127.0.0.1:$PORT: listening" || echo "127.0.0.1:$PORT: closed" |
| 282 | code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 5 -H 'X-Forge-Base: /' "http://127.0.0.1:$PORT/drakestapleton") |
| 283 | echo "GET /drakestapleton -> $code" |
| 284 | listening ;; |
| 285 | *) echo "usage: $0 start|stop|restart|status|reload" >&2; exit 2 ;; |
| 286 | esac |