Public: anyone can read this; the crew can change it.
The game agent is never blind: compose up runs in the background, and every sync carries a diagnosis #17157
Merged 46h ago, live in production
sold/agent-visible → main 0 commits
14 files
changed +738
−22
- docs/features/game-box.md
- scripts/gate.ts
- src/core/migration-pins/20261201180000-game-box-diag.pin
- src/core/migrations/20261201180000-game-box-diag.ts
- src/games/agent.sh
- src/games/boot.ts
- src/games/diag.ts
- src/games/store.ts
- src/generated/migrations.ts
- src/http/mcp/tools/games.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/game-box.test.ts
- test/game-diag.test.ts
docs/features/game-box.md +1
| @@ -15,6 +15,7 @@ experiment. | ||
| 15 | 15 | - **The machine:** Ubuntu with Docker and its compose plugin (Ubuntu's packages, data on the box's volume), 4 GB of swap for the JVMs, and a firewall that lets in only 25565/tcp: no SSH, no web, no backend port. Password and root logins are off and updates are on, as on a forge. |
| 16 | 16 | - **The agent:** `/opt/forge-game/agent.sh` (`src/games/agent.sh`) under systemd (`forge-game-agent`). Every 5 s it POSTs the services, their CPU and memory, new log lines, command results and the host to `/api/v1/games/agent/sync`, and does what the answer asks: writes `compose.yml` and the answer's `.env` beside it (only that name: `FORWARDING_SECRET` and an `RCON_<SERVICE>` for every service; any other name is ignored and logged, so nothing can land on the agent's own files), runs `docker compose -p game --project-directory /opt/forge-game up -d --remove-orphans` when they change, and runs queued commands (rcon through `docker compose exec -T <service> rcon-cli -- <text>`, by service name, or restart, stop, start, pull, recreate). Nothing dials in to the box; a failed sync is tried again in 5 s, forever. |
| 17 | 17 | - **When it is up but not playing:** the boot installs Docker, its compose plugin and jq in `runcmd`, each apt call waiting up to ten minutes for the lock a first boot's unattended upgrade holds, three tries (a `packages:` list failed on that lock and left box `mc` with no jq). Its last step, `agent.sh --boot-report`, posts cloud-init's status to the sync once. An agent missing jq or docker still posts `{"agent":1,"boot":"missing jq: <cloud-init status>"}`, built by hand with curl, every 30 s until they are there. The forge keeps that word until a full sync clears it, and `/games` and the terminal's Games say "Box is up but missing jq: …". |
| 18 | - **Never blind:** compose up, pull and the power verbs run in a background job queue, one at a time, output to `.up.log`; the agent keeps syncing every 5 s whatever runs, and a failed up is not retried for the same compose. Every sync carries `diag`, about 8 KB: the job (label, since, running, last exit) and the tail of `.up.log`, `docker ps -a` and `docker images` (bounded), the agent's and Docker's journal, cloud-init's status, `df -h /`, where Docker's data root is mounted and whether the volume is, and the versions. The whole diag runs within one deadline (8 s; every docker read in a sync is capped at 5 s), and over it the sync carries `{"note":"diag ran over 8 s"}`, so a docker that hangs never holds the sync. A job interrupted under the agent (a stale pid with no exit status, or a pid that is now another program's, by its command line) is queued again, never marked failed. The forge keeps the latest (16 KB at most). The box's owner (and forge admins) read it whole; anyone else who may see one of its services reads only what it is doing ("Applying since …", "N of M running"), naming no container, image, error or journal. For the owner, `/games/<box>` has a Box section of plain lines ("Pulling …", "compose up failed: <its last error line>", "Docker's data is on the root disk, not the volume", "The volume is not mounted at …") over a folded run log of the raw tails; the terminal's Games shows the top line and the MCP games tool's `list` up to three. The boot waits up to a minute for the volume's mount before Docker starts. | |
| 18 | 19 | - **The token:** made whenever the box's machine is made (a create or a replace, which ends the old one's), kept only as its sha256 (`game_box.token_hash`, starting `fgb_`), and written only into the machine's `/opt/forge-game/agent.env` (mode 600), which the unit reads; the agent hands it to curl in a header file, never on a command line. `rotateGameBoxToken` makes a new one. |
| 19 | 20 | - **DNS:** an A record, not proxied, for the box's `host` in any Cloudflare zone a connected token can write; with none, the plan says to set it by hand. |
| 20 | 21 |
scripts/gate.ts +1
| @@ -64,6 +64,7 @@ export const SLOW: readonly Exclusion[] = [ | ||
| 64 | 64 | // A fresh module graph is what it tests: no process or fixture can be shared, and no clock is |
| 65 | 65 | // waited on (#17007). |
| 66 | 66 | { file: "test/load-order.test.ts", reason: "loads src/ first in 13 fresh processes at once; one parses 4,286 files (24 MB) in 2.4 s alone, 2.46 s under full-suite load", issue: 17007 }, |
| 67 | { file: "test/game-diag.test.ts", reason: "runs the real game agent against a stand-in forge through three syncs while a fake compose up sleeps; about 2 s a test", issue: 16840 }, | |
| 67 | 68 | { file: "test/spawn-cell-looks.test.ts", reason: "boots a real child forge in a cell (~30 s) and waits for its own looks job to take a picture", issue: 10620 }, |
| 68 | 69 | { file: "test/snapshot-stream.test.ts", reason: "its service test takes a real stream pass and a real snapshot of a forge with a database, about 1 s each; 3.1 s a test under full-suite load", issue: 16977 }, |
| 69 | 70 | // From the breach list closing this pull's check log at e2a5c15 (#12088): |
src/core/migration-pins/20261201180000-game-box-diag.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 3d89e67b236f7398afa009706a538e5dc5d073c8682ec1928b35a894a99275a2 |
src/core/migrations/20261201180000-game-box-diag.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // A game box's latest diagnosis (2026-12-01, box `mc` went silent inside compose up): what its agent | |
| 2 | // last sent of the job it runs, the containers, the journals, cloud-init and the disks, as JSON at | |
| 3 | // most 16 KB, replaced each sync, so /games/<box> can say why a box is not playing. | |
| 4 | // Additive: one column. | |
| 5 | export default ` | |
| 6 | ALTER TABLE game_box ADD COLUMN diag_json TEXT NOT NULL DEFAULT '{}'; | |
| 7 | `; |
src/games/agent.sh +187 −13
| @@ -76,6 +76,35 @@ done | ||
| 76 | 76 | # The project directory is the box's own, so compose reads the `.env` the forge writes beside it. |
| 77 | 77 | compose() { "" compose -p game --project-directory "" -f "/compose.yml" "$@"; } |
| 78 | 78 | now() { date -u +%Y-%m-%dT%H:%M:%SZ; } |
| 79 | # A quick command that must not hang the loop: at most 30 s where timeout(1) is there. | |
| 80 | # Run a command for at most `secs` seconds, timeout(1) or not: a docker that hangs never holds the | |
| 81 | # loop. Its output passes through; past the limit it is killed and says nothing more. | |
| 82 | capped() { | |
| 83 | local secs="$1" pid i | |
| 84 | shift | |
| 85 | if command -v timeout >/dev/null 2>&1; then | |
| 86 | timeout "" "$@" | |
| 87 | return | |
| 88 | fi | |
| 89 | "$@" & | |
| 90 | pid=$! | |
| 91 | for ((i = 0; i < secs * 20; i++)); do | |
| 92 | kill -0 "" 2>/dev/null || break | |
| 93 | sleep 0.05 | |
| 94 | done | |
| 95 | if kill -0 "" 2>/dev/null; then | |
| 96 | pkill -P "" 2>/dev/null | |
| 97 | kill "" 2>/dev/null | |
| 98 | fi | |
| 99 | wait "" 2>/dev/null | |
| 100 | } | |
| 101 | bounded30() { capped 30 "$@"; } | |
| 102 | # A diag probe: at most 5 s, its output cut to `max` bytes, nothing on failure. | |
| 103 | probe() { | |
| 104 | local max="$1" | |
| 105 | shift | |
| 106 | capped 5 "$@" 2>&1 | tail -c "" || true | |
| 107 | } | |
| 79 | 108 | |
| 80 | 109 | since="$(now)" |
| 81 | 110 | [ -f "/.results" ] || echo '[]' >"/.results" |
| @@ -83,9 +112,9 @@ since="$(now)" | ||
| 83 | 112 | # The services as compose sees them, with each one's CPU and memory from docker stats. |
| 84 | 113 | services() { |
| 85 | 114 | local ps stats |
| 86 | ps="$(compose ps -a --format json 2>/dev/null | jq -cs 'flatten' 2>/dev/null)" || ps='[]' | |
| 115 | ps="$(capped 5 compose ps -a --format json 2>/dev/null | jq -cs 'flatten' 2>/dev/null)" || ps='[]' | |
| 87 | 116 | [ -n "" ] || ps='[]' |
| 88 | stats="$("" stats --no-stream --format json 2>/dev/null | jq -cs '.' 2>/dev/null)" || stats='[]' | |
| 117 | stats="$(capped 5 "" stats --no-stream --format json 2>/dev/null | jq -cs '.' 2>/dev/null)" || stats='[]' | |
| 89 | 118 | [ -n "" ] || stats='[]' |
| 90 | 119 | jq -cn --argjson ps "" --argjson stats "" ' |
| 91 | 120 | def mib: (capture("^(?<n>[0-9.]+)\\s*(?<u>[KMGT]?i?B)") // {n: "0", u: "MiB"}) |
| @@ -103,7 +132,7 @@ services() { | ||
| 103 | 132 | |
| 104 | 133 | # New log lines since the last sync, at most 200 a service: "hub | text" split at the first bar. |
| 105 | 134 | logs() { |
| 106 | compose logs --no-color --since "$1" 2>/dev/null | jq -cRn ' | |
| 135 | capped 5 compose logs --no-color --since "$1" 2>/dev/null | jq -cRn ' | |
| 107 | 136 | [inputs | capture("^(?<s>[^ |]+)[ ]*\\| ?(?<l>.*)$")?] |
| 108 | 137 | | group_by(.s) | map({key: .[0].s, value: (map(.l) | .[-200:])}) | from_entries' 2>/dev/null || echo '{}' |
| 109 | 138 | } |
| @@ -131,9 +160,17 @@ run() { | ||
| 131 | 160 | else |
| 132 | 161 | case "" in |
| 133 | 162 | # Through compose, by service: a container is named game-<service>-1 unless the file says otherwise. |
| 134 | rcon) out="$(compose exec -T "" rcon-cli -- "" 2>&1)" || ok=false ;; | |
| 135 | restart | stop | start | pull) out="$(compose "" "" 2>&1)" || ok=false ;; | |
| 136 | recreate) out="$(compose up -d --force-recreate "" 2>&1)" || ok=false ;; | |
| 163 | rcon) out="$(bounded30 compose exec -T "" rcon-cli -- "" 2>&1)" || ok=false ;; | |
| 164 | # Anything that can take long goes to the job queue: the sync never waits on it, and its | |
| 165 | # result is sent when it ends. | |
| 166 | restart | stop | start | pull) | |
| 167 | queue_job "" " " "" "" "" | |
| 168 | return | |
| 169 | ;; | |
| 170 | recreate) | |
| 171 | queue_job "" "recreate " "" up -d --force-recreate "" | |
| 172 | return | |
| 173 | ;; | |
| 137 | 174 | *) |
| 138 | 175 | out="refused: is not a command this agent runs" |
| 139 | 176 | ok=false |
| @@ -144,12 +181,84 @@ run() { | ||
| 144 | 181 | mv "/.results.next" "/.results" |
| 145 | 182 | } |
| 146 | 183 | |
| 184 | # ---- the job queue: compose up, pull and the power verbs run here, one at a time, in the | |
| 185 | # background, output to .up.log; the loop keeps syncing every 5 s and says what is running. ---- | |
| 186 | ||
| 187 | JOBQ="/.jobs" | |
| 188 | # The job runs as `bash -c … forge-game-job`, so its command line names it: a pid the kernel has | |
| 189 | # since given to something else is not taken for our job. | |
| 190 | JOB_MARK="forge-game-job" | |
| 191 | job_running() { | |
| 192 | local pid | |
| 193 | pid="$(cat "/.job.pid" 2>/dev/null)" | |
| 194 | [ -n "" ] && kill -0 "" 2>/dev/null || return 1 | |
| 195 | [ -r "/proc//cmdline" ] || return 0 | |
| 196 | tr '\0' ' ' <"/proc//cmdline" | grep -q "" | |
| 197 | } | |
| 198 | ||
| 199 | # Queue `compose <args…>` under `label`; `id` is a command's (its result is sent when it ends), | |
| 200 | # `sha` the compose sha a successful up makes current. An up already queued or running for the | |
| 201 | # same sha is not queued twice. | |
| 202 | queue_job() { | |
| 203 | local id="$1" label="$2" sha="$3" | |
| 204 | shift 3 | |
| 205 | if [ -n "" ] && { [ "" = "$(cat "/.job.sha" 2>/dev/null)" ] && job_running || grep -q "||" "" 2>/dev/null; }; then return; fi | |
| 206 | # Fields split by "|", which no id, label, sha or safe name holds (a tab would fold empty fields). | |
| 207 | printf '%s|%s|%s|%s\n' "" "" "" "$*" >>"" | |
| 208 | } | |
| 209 | ||
| 210 | # Keep a command's result for the next sync. | |
| 211 | keep_result() { | |
| 212 | jq -c --arg id "$1" --argjson ok "$2" --arg out "" '. + [{id: $id, ok: $ok, output: $out}]' "/.results" >"/.results.next" && | |
| 213 | mv "/.results.next" "/.results" | |
| 214 | } | |
| 215 | ||
| 216 | # Each tick: reap a job that ended (its result, the sha an up made current), then start the next. | |
| 217 | job_tick() { | |
| 218 | local rc id sha line label args | |
| 219 | if [ -f "/.job.pid" ] && ! job_running; then | |
| 220 | id="$(cat "/.job.id" 2>/dev/null)" | |
| 221 | sha="$(cat "/.job.sha" 2>/dev/null)" | |
| 222 | # No exit status: the job was interrupted (the agent or the box restarted under it), not | |
| 223 | # failed. It goes back on the queue as it was, and nothing is marked failed. | |
| 224 | if [ ! -f "/.job.rc" ]; then | |
| 225 | printf '%s|%s|%s|%s\n' "" "$(cat "/.job.label" 2>/dev/null)" "" "$(cat "/.job.args" 2>/dev/null)" | cat - "" 2>/dev/null >".next" | |
| 226 | mv ".next" "" | |
| 227 | rm -f "/.job.pid" "/.job.id" "/.job.sha" "/.job.args" | |
| 228 | echo "forge-game-agent: the last job was interrupted; queued again" >&2 | |
| 229 | fi | |
| 230 | fi | |
| 231 | if [ -f "/.job.pid" ] && ! job_running; then | |
| 232 | rc="$(cat "/.job.rc" 2>/dev/null || echo 1)" | |
| 233 | if [ "" = 0 ] && [ -n "" ]; then printf '%s' "" >"/.compose-sha"; fi | |
| 234 | # A failed up is not retried for the same compose: it would fail again every 5 s. | |
| 235 | if [ "" != 0 ] && [ -n "" ]; then printf '%s' "" >"/.up.failed"; fi | |
| 236 | [ -n "" ] && keep_result "" "$([ "" = 0 ] && echo true || echo false)" "$(tail -c 4096 "/.up.log" 2>/dev/null)" | |
| 237 | printf '%s' "" >"/.job.last" | |
| 238 | rm -f "/.job.pid" "/.job.rc" "/.job.id" "/.job.sha" "/.job.args" | |
| 239 | fi | |
| 240 | job_running && return | |
| 241 | [ -s "" ] || return | |
| 242 | line="$(head -n 1 "")" | |
| 243 | tail -n +2 "" >".next" && mv ".next" "" | |
| 244 | IFS='|' read -r id label sha args <<<"" | |
| 245 | printf '%s' "" >"/.job.id" | |
| 246 | printf '%s' "" >"/.job.sha" | |
| 247 | printf '%s' "" >"/.job.label" | |
| 248 | printf '%s' "" >"/.job.args" | |
| 249 | now >"/.job.since" | |
| 250 | # Its own bash, named on its command line ($0), writing its exit status only when it ends. | |
| 251 | # shellcheck disable=SC2086,SC2016 # the verb and its words, each a safe name; the script is single-quoted on purpose | |
| 252 | DOCKER="" DIR="" bash -c '"$DOCKER" compose -p game --project-directory "$DIR" -f "$DIR/compose.yml" "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" & | |
| 253 | echo $! >"/.job.pid" | |
| 254 | } | |
| 255 | ||
| 147 | 256 | # Write what the answer carries; bring the project up when the compose or an env file changed. |
| 148 | 257 | apply() { |
| 149 | local answer="$1" sha changed=0 name | |
| 258 | local answer="$1" sha changed=0 changed_env=0 name | |
| 150 | 259 | sha="$(jq -r '.composeSha // ""' <<<"")" |
| 151 | 260 | if jq -e 'has("compose") and (.compose | type == "string")' <<<"" >/dev/null 2>&1 && |
| 152 | [ "" != "$(cat "/.compose-sha" 2>/dev/null)" ]; then | |
| 261 | [ "" != "$(cat "/.compose-sha" 2>/dev/null)" ] && [ "" != "$(cat "/.up.failed" 2>/dev/null)" ]; then | |
| 153 | 262 | jq -j '.compose' <<<"" >"/compose.yml.next" && mv "/compose.yml.next" "/compose.yml" |
| 154 | 263 | changed=1 |
| 155 | 264 | fi |
| @@ -160,19 +269,81 @@ apply() { | ||
| 160 | 269 | continue |
| 161 | 270 | fi |
| 162 | 271 | jq -j --arg n "" '.env[$n] // ""' <<<"" >"/.next" || continue |
| 163 | cmp -s "/.next" "/" || changed=1 | |
| 272 | cmp -s "/.next" "/" || { changed=1; changed_env=1; } | |
| 164 | 273 | mv "/.next" "/" |
| 165 | 274 | done < <(jq -r '(.env // {}) | keys[]' <<<"" 2>/dev/null) |
| 275 | # Queued, never waited on: an up that pulls gigabytes must not stop the box from syncing. | |
| 166 | 276 | if [ "" = 1 ] && [ -f "/compose.yml" ]; then |
| 167 | if compose up -d --remove-orphans >"/.up.log" 2>&1; then | |
| 168 | printf '%s' "" >"/.compose-sha" | |
| 169 | fi | |
| 277 | [ "" = 1 ] && rm -f "/.up.failed" | |
| 278 | [ "" = "$(cat "/.up.failed" 2>/dev/null)" ] || queue_job "" "compose up" "" up -d --remove-orphans | |
| 170 | 279 | fi |
| 171 | 280 | while IFS= read -r cmd; do |
| 172 | 281 | [ -n "" ] && run "" |
| 173 | 282 | done < <(jq -c '.commands // [] | .[]' <<<"" 2>/dev/null) |
| 174 | 283 | } |
| 175 | 284 | |
| 285 | # What a person needs to see why a box is not playing, in about 8 KB: the running job and the tail | |
| 286 | # of .up.log, the containers and images, the agent's and Docker's journal, cloud-init's status, the | |
| 287 | # disks (and whether Docker's data is on the volume), and the versions. | |
| 288 | diag() { | |
| 289 | local root mount_of volume | |
| 290 | root="$(jq -r '."data-root" // ""' /etc/docker/daemon.json 2>/dev/null)" | |
| 291 | volume="" | |
| 292 | mount_of="$(probe 400 findmnt -n -o TARGET --target "")" | |
| 293 | jq -cn \ | |
| 294 | --arg label "$(cat "/.job.label" 2>/dev/null)" \ | |
| 295 | --arg since "$(cat "/.job.since" 2>/dev/null)" \ | |
| 296 | --argjson running "$(job_running && echo true || echo false)" \ | |
| 297 | --arg last "$(cat "/.job.last" 2>/dev/null)" \ | |
| 298 | --arg queued "$(wc -l <"" 2>/dev/null | tr -dc 0-9)" \ | |
| 299 | --arg up "$(tail -n 40 "/.up.log" 2>/dev/null | tail -c 2000)" \ | |
| 300 | --arg ps "$(probe 4000 "" ps -a --format json)" \ | |
| 301 | --arg images "$(probe 2000 "" images --format json)" \ | |
| 302 | --arg agent "$(probe 1200 journalctl -u forge-game-agent -n 30 --no-pager -o cat)" \ | |
| 303 | --arg docker "$(probe 1000 journalctl -u docker -n 20 --no-pager -o cat)" \ | |
| 304 | --arg cloud "$(boot_status | tail -c 600)" \ | |
| 305 | --arg df "$(probe 300 df -h /)" \ | |
| 306 | --arg root "" \ | |
| 307 | --arg volume "" \ | |
| 308 | --arg mount "" \ | |
| 309 | --arg mounted "$( [ -n "" ] && mountpoint -q "" 2>/dev/null && echo yes || echo no)" \ | |
| 310 | --arg dockerv "$(probe 80 "" version --format '{{.Server.Version}}')" \ | |
| 311 | --arg composev "$(probe 80 "" compose version --short)" \ | |
| 312 | '{ | |
| 313 | job: {label: , since: , running: , last: , queued: ( | tonumber? // 0)}, | |
| 314 | upLog: , | |
| 315 | ps: [( | split("\n")[] | fromjson? | {name: (.Names // ""), state: (.State // ""), status: (.Status // ""), image: (.Image // "")})][0:30], | |
| 316 | images: [( | split("\n")[] | fromjson? | {image: ((.Repository // "") + ":" + (.Tag // "")), size: (.Size // "")})][0:20], | |
| 317 | journal: {agent: , docker: }, | |
| 318 | cloudInit: , | |
| 319 | disk: {root: , dataRoot: , volume: , mountOfDataRoot: ( | rtrimstr("\n")), volumeMounted: ( == "yes"), onVolume: ( != "" and ( | rtrimstr("\n")) == )}, | |
| 320 | versions: {docker: ( | rtrimstr("\n")), compose: ( | rtrimstr("\n"))} | |
| 321 | }' 2>/dev/null || echo '{}' | |
| 322 | } | |
| 323 | ||
| 324 | # The whole diag within one deadline (FORGE_GAME_DIAG_S, default 8 s): a probe that hangs (a docker | |
| 325 | # that does not answer) never holds the sync. Over it, an empty diag that says so. | |
| 326 | bounded_diag() { | |
| 327 | local out="/.diag.next" pid i limit | |
| 328 | limit="$(( * 5 ))" | |
| 329 | rm -f "" | |
| 330 | diag >"" 2>/dev/null & | |
| 331 | pid=$! | |
| 332 | for ((i = 0; i < limit; i++)); do | |
| 333 | kill -0 "" 2>/dev/null || break | |
| 334 | sleep 0.2 | |
| 335 | done | |
| 336 | if kill -0 "" 2>/dev/null; then | |
| 337 | pkill -P "" 2>/dev/null | |
| 338 | kill "" 2>/dev/null | |
| 339 | wait "" 2>/dev/null | |
| 340 | printf '{"note":"diag ran over %s s"}' "" | |
| 341 | return | |
| 342 | fi | |
| 343 | wait "" 2>/dev/null | |
| 344 | if [ -s "" ] && jq -e . "" >/dev/null 2>&1; then cat ""; else echo '{}'; fi | |
| 345 | } | |
| 346 | ||
| 176 | 347 | sync() { |
| 177 | 348 | local next body answer |
| 178 | 349 | next="$(now)" |
| @@ -182,7 +353,8 @@ sync() { | ||
| 182 | 353 | --argjson logs "$(logs "")" \ |
| 183 | 354 | --slurpfile results "/.results" \ |
| 184 | 355 | --argjson host "$(host)" \ |
| 185 | '{agent: 1, composeSha: $sha, services: $services, logs: $logs, results: $results[0], host: $host}')" || return 1 | |
| 356 | --argjson diag "$(bounded_diag)" \ | |
| 357 | '{agent: 1, composeSha: $sha, services: $services, logs: $logs, results: $results[0], host: $host, diag: $diag}')" || return 1 | |
| 186 | 358 | answer="$(curl -fsS -m 20 -H "@" -H 'content-type: application/json' --data-binary "" "/api/v1/games/agent/sync")" || return 1 |
| 187 | 359 | # Delivered: the results and the log lines are the forge's now. |
| 188 | 360 | echo '[]' >"/.results" |
| @@ -191,7 +363,9 @@ sync() { | ||
| 191 | 363 | } |
| 192 | 364 | |
| 193 | 365 | while :; do |
| 366 | job_tick | |
| 194 | 367 | sync || echo "forge-game-agent: sync failed; again in s" >&2 |
| 368 | job_tick | |
| 195 | 369 | [ "" = 1 ] && exit 0 |
| 196 | 370 | sleep "" |
| 197 | 371 | done |
src/games/boot.ts +10
| @@ -52,6 +52,15 @@ WantedBy=multi-user.target | ||
| 52 | 52 | export const INSTALL = |
| 53 | 53 | "for try in 1 2 3; do apt-get -o DPkg::Lock::Timeout=600 update && DEBIAN_FRONTEND=noninteractive apt-get -o DPkg::Lock::Timeout=600 install -y docker.io docker-compose-v2 jq curl ca-certificates ufw unattended-upgrades && break; sleep 30; done"; |
| 54 | 54 | |
| 55 | /** | |
| 56 | * Wait up to a minute for the cloud to mount the box's volume at `dataDir` (DigitalOcean mounts an | |
| 57 | * attached volume at /mnt/<its name> through its own setup), so Docker's data lands on the volume | |
| 58 | * and not on the root disk under it; say so in the journal when it never comes (the agent's diag | |
| 59 | * says it too: `volumeMounted`). | |
| 60 | */ | |
| 61 | export const volumeWait = (dataDir: string): string => | |
| 62 | `for i in $(seq 60); do mountpoint -q ${dataDir} && break; sleep 1; done; mountpoint -q ${dataDir} || logger -t forge-game "the volume is not mounted at ${dataDir}; Docker's data goes on the root disk"`; | |
| 63 | ||
| 55 | 64 | /** The cloud-config for a game box whose volume is mounted at `dataDir`. */ |
| 56 | 65 | export function gameBootConfig(g: GameBoot, dataDir: string): string { |
| 57 | 66 | const url = new URL(g.forgeUrl); |
| @@ -83,6 +92,7 @@ runcmd: | ||
| 83 | 92 | - ufw allow ${GAME_PORT}/tcp |
| 84 | 93 | - ufw --force enable |
| 85 | 94 | - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab |
| 95 | - ${yamlString(volumeWait(dataDir))} | |
| 86 | 96 | - mkdir -p ${dataDir}/docker |
| 87 | 97 | - ${yamlString(INSTALL)} |
| 88 | 98 | - systemctl restart docker || true |
src/games/diag.ts added +89
| @@ -0,0 +1,89 @@ | ||
| 1 | /** | |
| 2 | * A game box's diagnosis in words (2026-12-01): the agent sends `diag` with every sync (the job it | |
| 3 | * runs and the tail of its output, the containers, the journals, cloud-init, the disks); this turns | |
| 4 | * the latest into the plain lines /games/<box>, the terminal's Games and the MCP games tool say | |
| 5 | * first: "Pulling …", "compose up failed: <its last error line>", "Docker's data is on the root | |
| 6 | * disk, not the volume". The raw tails stay in the diag, for the page's collapsed run log. | |
| 7 | */ | |
| 8 | ||
| 9 | /** The most of a diag the forge keeps, as JSON; a bigger one is replaced by a note. */ | |
| 10 | export const DIAG_MOST = 16_384; | |
| 11 | ||
| 12 | export interface Diag { | |
| 13 | readonly job?: { readonly label?: string; readonly since?: string; readonly running?: boolean; readonly last?: string; readonly queued?: number }; | |
| 14 | readonly upLog?: string; | |
| 15 | readonly ps?: readonly { readonly name?: string; readonly state?: string; readonly status?: string; readonly image?: string }[]; | |
| 16 | readonly images?: readonly { readonly image?: string; readonly size?: string }[]; | |
| 17 | readonly journal?: { readonly agent?: string; readonly docker?: string }; | |
| 18 | readonly cloudInit?: string; | |
| 19 | readonly disk?: { readonly root?: string; readonly dataRoot?: string; readonly volume?: string; readonly mountOfDataRoot?: string; readonly volumeMounted?: boolean; readonly onVolume?: boolean }; | |
| 20 | readonly versions?: { readonly docker?: string; readonly compose?: string }; | |
| 21 | } | |
| 22 | ||
| 23 | /** A diag as kept: its JSON, or a note when it is not an object or is over `DIAG_MOST`. */ | |
| 24 | export function keptDiag(raw: unknown): string { | |
| 25 | if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return "{}"; | |
| 26 | const text = JSON.stringify(raw); | |
| 27 | return text.length <= DIAG_MOST ? text : JSON.stringify({ note: `the box sent ${text.length} bytes of diagnosis; at most ${DIAG_MOST} are kept` }); | |
| 28 | } | |
| 29 | ||
| 30 | export function readDiag(text: string): Diag { | |
| 31 | try { | |
| 32 | const v = JSON.parse(text) as unknown; | |
| 33 | return typeof v === "object" && v !== null ? (v as Diag) : {}; | |
| 34 | } catch { | |
| 35 | return {}; | |
| 36 | } | |
| 37 | } | |
| 38 | ||
| 39 | const lastLine = (text: string, pick: RegExp = /./): string => | |
| 40 | text | |
| 41 | .split("\n") | |
| 42 | .map((l) => l.trim()) | |
| 43 | .filter((l) => l !== "" && pick.test(l)) | |
| 44 | .at(-1) ?? ""; | |
| 45 | ||
| 46 | /** | |
| 47 | * The lines anyone who may see a service of the box is told: what the box is doing and how many | |
| 48 | * of its containers run, naming no container, image, error text or journal (those are the owner's, | |
| 49 | * `boxStatus`). | |
| 50 | */ | |
| 51 | export function boxStatusShared(d: Diag): string[] { | |
| 52 | const out: string[] = []; | |
| 53 | const job = d.job ?? {}; | |
| 54 | if (job.running === true) out.push(`${/pull/i.test(job.label ?? "") ? "Pulling" : "Applying"} since ${job.since ?? "?"}`); | |
| 55 | else if (job.last !== undefined && job.last !== "" && job.last !== "0") out.push("The box's last change did not apply; its owner can see why"); | |
| 56 | const ps = d.ps ?? []; | |
| 57 | if (ps.length > 0) out.push(`${ps.filter((c) => c.state === "running").length} of ${ps.length} running`); | |
| 58 | return out; | |
| 59 | } | |
| 60 | ||
| 61 | /** The plain lines a diag says, most telling first; none for a box that sent none. The owner's. */ | |
| 62 | export function boxStatus(d: Diag): string[] { | |
| 63 | const out: string[] = []; | |
| 64 | const job = d.job ?? {}; | |
| 65 | const log = d.upLog ?? ""; | |
| 66 | if (job.running === true) { | |
| 67 | const pulling = lastLine(log, /pull|download|extract|waiting/i); | |
| 68 | out.push( | |
| 69 | /pull/i.test(job.label ?? "") || pulling !== "" | |
| 70 | ? `Pulling${job.label ? ` (${job.label})` : ""} since ${job.since ?? "?"}${pulling === "" ? "" : `: ${pulling}`}` | |
| 71 | : `Applying (${job.label ?? "a job"}) since ${job.since ?? "?"}`, | |
| 72 | ); | |
| 73 | } else if (job.last !== undefined && job.last !== "" && job.last !== "0") { | |
| 74 | out.push(`${job.label || "compose up"} failed: ${lastLine(log, /error|failed|denied|no such|not found/i) || lastLine(log) || `exit ${job.last}`}`); | |
| 75 | } | |
| 76 | const disk = d.disk; | |
| 77 | if (disk !== undefined && (disk.volume ?? "") !== "") { | |
| 78 | if (disk.volumeMounted === false) out.push(`The volume is not mounted at ${disk.volume}`); | |
| 79 | else if (disk.onVolume === false) out.push("Docker's data is on the root disk, not the volume"); | |
| 80 | } | |
| 81 | const ps = d.ps ?? []; | |
| 82 | if (ps.length > 0) { | |
| 83 | const up = ps.filter((c) => c.state === "running").length; | |
| 84 | out.push(`${ps.length} container${ps.length === 1 ? "" : "s"}: ${up} running${ps.length - up > 0 ? `, ${ps.length - up} not` : ""}`); | |
| 85 | } else if (d.versions !== undefined && (d.versions.docker ?? "") === "") out.push("Docker is not answering"); | |
| 86 | const full = /(\d+)%\s+\/\s*$/m.exec(disk?.root ?? ""); | |
| 87 | if (full !== null && Number(full[1]) >= 85) out.push(`The root disk is ${full[1]}% full`); | |
| 88 | return out; | |
| 89 | } |
src/games/store.ts +9 −1
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | */ |
| 9 | 9 | |
| 10 | 10 | import type { Database } from "bun:sqlite"; |
| 11 | import { keptDiag, readDiag, type Diag } from "./diag.ts"; | |
| 11 | 12 | import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"; |
| 12 | 13 | import { rm } from "node:fs/promises"; |
| 13 | 14 | import type { App } from "../app.ts"; |
| @@ -42,6 +43,8 @@ export interface GameBox { | ||
| 42 | 43 | readonly createdAt: string; |
| 43 | 44 | /** What the box last said about its boot ("missing jq: …", a boot report); empty once it syncs in full. */ |
| 44 | 45 | readonly boot: string; |
| 46 | /** The latest diagnosis the agent sent (`diag.ts`), replaced each sync. */ | |
| 47 | readonly diag: Diag; | |
| 45 | 48 | } |
| 46 | 49 | |
| 47 | 50 | export interface GameService { |
| @@ -68,6 +71,7 @@ interface BoxRow { | ||
| 68 | 71 | seen_at: string; |
| 69 | 72 | created_at: string; |
| 70 | 73 | boot: string; |
| 74 | diag_json: string; | |
| 71 | 75 | } |
| 72 | 76 | const toBox = (r: BoxRow): GameBox => { |
| 73 | 77 | let host: Record<string, number> = {}; |
| @@ -88,6 +92,7 @@ const toBox = (r: BoxRow): GameBox => { | ||
| 88 | 92 | seenAt: r.seen_at, |
| 89 | 93 | createdAt: r.created_at, |
| 90 | 94 | boot: r.boot, |
| 95 | diag: readDiag(r.diag_json), | |
| 91 | 96 | }; |
| 92 | 97 | }; |
| 93 | 98 | |
| @@ -411,6 +416,8 @@ export interface SyncBody { | ||
| 411 | 416 | readonly host?: Record<string, unknown>; |
| 412 | 417 | /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */ |
| 413 | 418 | readonly boot?: string; |
| 419 | /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */ | |
| 420 | readonly diag?: unknown; | |
| 414 | 421 | } |
| 415 | 422 | |
| 416 | 423 | const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : ""); |
| @@ -433,11 +440,12 @@ export function recordSync( | ||
| 433 | 440 | db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000)); |
| 434 | 441 | return; |
| 435 | 442 | } |
| 436 | db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '' WHERE id = ?1").run( | |
| 443 | db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '', diag_json = ?5 WHERE id = ?1").run( | |
| 437 | 444 | box.id, |
| 438 | 445 | at, |
| 439 | 446 | JSON.stringify(host), |
| 440 | 447 | str(body.composeSha, 80), |
| 448 | keptDiag(body.diag), | |
| 441 | 449 | ); |
| 442 | 450 | for (const s of (body.services ?? []).slice(0, 64)) { |
| 443 | 451 | const name = str(s.name, 64); |
src/generated/migrations.ts +2
| @@ -452,6 +452,7 @@ import m447 from "../core/migrations/20261201140000-infra-snapshot.ts"; | ||
| 452 | 452 | import m448 from "../core/migrations/20261201140000-scan-finding-excerpt.ts"; |
| 453 | 453 | import m449 from "../core/migrations/20261201150000-pinned-firewall.ts"; |
| 454 | 454 | import m450 from "../core/migrations/20261201170000-managed-database.ts"; |
| 455 | import m451 from "../core/migrations/20261201180000-game-box-diag.ts"; | |
| 455 | 456 | |
| 456 | 457 | /** Each migration file's name and its default export, in name order. */ |
| 457 | 458 | export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ |
| @@ -906,4 +907,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ | ||
| 906 | 907 | ["20261201140000-scan-finding-excerpt.ts", m448], |
| 907 | 908 | ["20261201150000-pinned-firewall.ts", m449], |
| 908 | 909 | ["20261201170000-managed-database.ts", m450], |
| 910 | ["20261201180000-game-box-diag.ts", m451], | |
| 909 | 911 | ]; |
src/http/mcp/tools/games.ts +12 −1
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { addPlugin, commitServiceEnv } from "../../../games/compose.ts"; |
| 2 | import { boxStatus, boxStatusShared } from "../../../games/diag.ts"; | |
| 2 | 3 | import { boxNamed, listBoxes, mayDo, queueCommand, roleOn, seesBox, SERVICE_NAME, servicesOf, type CommandKind } from "../../../games/store.ts"; |
| 3 | 4 | import { good, bad, type Tool, str } from "../shared.ts"; |
| 4 | 5 | |
| @@ -32,7 +33,17 @@ export const tool: Tool = { | ||
| 32 | 33 | return good({ |
| 33 | 34 | items: listBoxes(db) |
| 34 | 35 | .filter((b) => seesBox(db, user, b.id)) |
| 35 | .map((b) => ({ name: b.name, place: b.place, monthlyCents: b.monthlyCents, seenAt: b.seenAt, host: b.host, services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")) })), | |
| 36 | .map((b) => ({ | |
| 37 | name: b.name, | |
| 38 | place: b.place, | |
| 39 | monthlyCents: b.monthlyCents, | |
| 40 | seenAt: b.seenAt, | |
| 41 | host: b.host, | |
| 42 | // The box's state in words, at most three lines: the owner's own, anyone else's naming | |
| 43 | // no container, image, error or journal. | |
| 44 | status: (mayDo(roleOn(db, user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)).slice(0, 3), | |
| 45 | services: servicesOf(db, b.id).filter((s) => mayDo(roleOn(db, user, b.id, s.name), "viewer")), | |
| 46 | })), | |
| 36 | 47 | }); |
| 37 | 48 | const box = boxNamed(db, str(args["box"])); |
| 38 | 49 | const service = str(args["service"]); |
src/tui/screens/games.ts +15 −1
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | 11 | import { emptyText } from "../../core/empty_words.ts"; |
| 12 | import { boxStatus, boxStatusShared } from "../../games/diag.ts"; | |
| 12 | 13 | import { getUserByName } from "../../core/users.ts"; |
| 13 | 14 | import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 14 | 15 | import { |
| @@ -61,7 +62,20 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 61 | 62 | const all = rows(); |
| 62 | 63 | // A box that is up but not running its games says why, as /games does, before anything else. |
| 63 | 64 | const booting = listBoxes(f.app.db).find((b) => b.boot !== "" && seesBox(f.app.db, f.user, b.id)); |
| 64 | const said = note !== "" ? note : booting !== undefined ? `${booting.name}: ${bootWords(booting)}` : all.length === 0 ? emptyText("gameServices") : "Each service of each game box you may see."; | |
| 65 | // Else the first box with something to say from its diagnosis (pulling, failed, wrong disk). | |
| 66 | // The owner reads the box's own words; anyone else what it is doing, naming nothing inside it. | |
| 67 | const lines = (b: GameBox) => (mayDo(roleOn(f.app.db, f.user, b.id), "owner") ? boxStatus(b.diag) : boxStatusShared(b.diag)); | |
| 68 | const told = listBoxes(f.app.db).find((b) => seesBox(f.app.db, f.user, b.id) && lines(b).length > 0); | |
| 69 | const said = | |
| 70 | note !== "" | |
| 71 | ? note | |
| 72 | : booting !== undefined | |
| 73 | ? `${booting.name}: ${bootWords(booting)}` | |
| 74 | : told !== undefined | |
| 75 | ? `${told.name}: ${lines(told)[0]}` | |
| 76 | : all.length === 0 | |
| 77 | ? emptyText("gameServices") | |
| 78 | : "Each service of each game box you may see."; | |
| 65 | 79 | s.text(head!.x, head!.y, truncate(said, head!.w), style(booting !== undefined && note === "" && bootTroubled(booting) ? c.danger : c.mutedFg, c.bg), head!.x + head!.w); |
| 66 | 80 | const view: ListRow[] = all.map(({ box, service }) => ({ |
| 67 | 81 | title: `${box.name}/${service.name}`, |
src/web/pages/games.ts +38 −2
| @@ -7,6 +7,7 @@ | ||
| 7 | 7 | */ |
| 8 | 8 | |
| 9 | 9 | import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; |
| 10 | import { boxStatus, boxStatusShared } from "../../games/diag.ts"; | |
| 10 | 11 | import { |
| 11 | 12 | bootWords, |
| 12 | 13 | boxNamed, |
| @@ -42,7 +43,7 @@ import { notFoundPage, pageHead, signInFirst } from "../chrome.ts"; | ||
| 42 | 43 | import { field, readForm, type Form } from "../form.ts"; |
| 43 | 44 | import { html, type Html } from "../html.ts"; |
| 44 | 45 | import { flashTo, page } from "../layout.ts"; |
| 45 | import { badge, btn, field as input, row, rowList, time } from "../ui.ts"; | |
| 46 | import { badge, btn, disclosure, field as input, row, rowList, time } from "../ui.ts"; | |
| 46 | 47 | import { onSync } from "../../games/notify.ts"; |
| 47 | 48 | import { emptyLine } from "../empty_words.ts"; |
| 48 | 49 | |
| @@ -137,10 +138,45 @@ export async function gameBoxPage(ctx: Ctx): Promise<Response> { | ||
| 137 | 138 | }); |
| 138 | 139 | }), |
| 139 | 140 | )} |
| 140 | ${role === "owner" ? grantsBlock(ctx, box) : null}`, | |
| 141 | ${role === "owner" ? boxBlock(box) : sharedBoxBlock(box)} ${role === "owner" ? grantsBlock(ctx, box) : null}`, | |
| 141 | 142 | })); |
| 142 | 143 | } |
| 143 | 144 | |
| 145 | /** What anyone who may see a service is told of the box: what it is doing, never its tails. */ | |
| 146 | function sharedBoxBlock(box: GameBox): Html | null { | |
| 147 | const lines = boxStatusShared(box.diag); | |
| 148 | return lines.length === 0 ? null : html`<section class="settings-block"><h2>Box</h2>${lines.map((l) => html`<p>${l}</p>`)}</section>`; | |
| 149 | } | |
| 150 | ||
| 151 | /** The box itself, from its latest diagnosis: plain lines first, the raw tails folded under them. The owner's. */ | |
| 152 | function boxBlock(box: GameBox): Html { | |
| 153 | const d = box.diag; | |
| 154 | const lines = boxStatus(d); | |
| 155 | const raw = [ | |
| 156 | ["The job's output (.up.log)", d.upLog], | |
| 157 | ["Containers", (d.ps ?? []).map((c) => `${c.name} ${c.state} ${c.status} ${c.image}`).join("\n")], | |
| 158 | ["Images", (d.images ?? []).map((i) => `${i.image} ${i.size}`).join("\n")], | |
| 159 | ["The agent's journal", d.journal?.agent], | |
| 160 | ["Docker's journal", d.journal?.docker], | |
| 161 | ["cloud-init", d.cloudInit], | |
| 162 | ["Disks", [d.disk?.root, d.disk?.dataRoot ? `data-root ${d.disk.dataRoot} on ${d.disk.mountOfDataRoot || "?"}` : ""].filter(Boolean).join("\n")], | |
| 163 | ["Versions", d.versions ? `docker ${d.versions.docker ?? "?"} · compose ${d.versions.compose ?? "?"}` : ""], | |
| 164 | ].filter(([, v]) => typeof v === "string" && v !== "") as [string, string][]; | |
| 165 | return html`<section class="settings-block"> | |
| 166 | <h2>Box</h2> | |
| 167 | ${lines.length === 0 && raw.length === 0 | |
| 168 | ? html`<p class="muted">The box has sent no diagnosis yet: its agent sends one with every sync.</p>` | |
| 169 | : html`${lines.map((l) => html`<p>${l}</p>`)} | |
| 170 | ${raw.length === 0 | |
| 171 | ? null | |
| 172 | : disclosure( | |
| 173 | "Run log", | |
| 174 | html`<pre class="run-log mono" tabindex="0" aria-label="What ${box.name} sent">${raw.map(([k, v]) => `== ${k}\n${v}\n`).join("\n")}</pre>`, | |
| 175 | { small: true }, | |
| 176 | )}`} | |
| 177 | </section>`; | |
| 178 | } | |
| 179 | ||
| 144 | 180 | function grantsBlock(ctx: Ctx, box: GameBox): Html { |
| 145 | 181 | const grants = grantsOf(ctx.app.db, box.id); |
| 146 | 182 | return html`<section class="settings-block"> |
test/game-box.test.ts +9 −4
| @@ -49,6 +49,9 @@ describe("the boot config", () => { | ||
| 49 | 49 | expect(at("DPkg::Lock::Timeout=600")).toBeGreaterThan(-1); |
| 50 | 50 | expect(at("DPkg::Lock::Timeout=600")).toBeLessThan(at("systemctl enable --now forge-game-agent.service")); |
| 51 | 51 | expect(runcmd.at(-1)).toBe(" - bash /opt/forge-game/agent.sh --boot-report"); |
| 52 | // The volume's mount is waited for (a minute) before Docker puts its data root on it. | |
| 53 | expect(at("mountpoint -q /mnt/forge_box_data && break")).toBeGreaterThan(-1); | |
| 54 | expect(at("mountpoint -q /mnt/forge_box_data && break")).toBeLessThan(at("DPkg::Lock::Timeout=600")); | |
| 52 | 55 | }); |
| 53 | 56 | |
| 54 | 57 | test("opens only the game's port: no SSH, no backend, no web", () => { |
| @@ -242,12 +245,14 @@ esac | ||
| 242 | 245 | expect(existsSync(join(box, "..", "escape.env"))).toBe(false); |
| 243 | 246 | expect(readFileSync(join(box, ".auth"), "utf8")).toBe(`Authorization: Bearer ${TOKEN}\n`); |
| 244 | 247 | expect(said).toContain("ignored env file agent.env: only .env is written"); |
| 245 | expect(readFileSync(join(box, ".compose-sha"), "utf8")).toBe("abc"); | |
| 248 | // The up runs in the background (the sync never waits on it); the next tick makes its sha current. | |
| 249 | const before = readFileSync(calls, "utf8"); | |
| 250 | expect(before).toContain(`compose -p game --project-directory ${box} -f ${box}/compose.yml exec -T hub rcon-cli -- say hi`); | |
| 251 | // The next sync carries the command's result and the sha the up made; the token never sat on a command line. | |
| 252 | expect(await run()).toBe(0); | |
| 246 | 253 | const called = readFileSync(calls, "utf8"); |
| 247 | 254 | expect(called).toContain(`compose -p game --project-directory ${box} -f ${box}/compose.yml up -d --remove-orphans`); |
| 248 | expect(called).toContain(`compose -p game --project-directory ${box} -f ${box}/compose.yml exec -T hub rcon-cli -- say hi`); | |
| 249 | // The next sync carries the command's result; the token never sat on a command line. | |
| 250 | expect(await run()).toBe(0); | |
| 255 | expect(readFileSync(join(box, ".compose-sha"), "utf8")).toBe("abc"); | |
| 251 | 256 | expect(bodies[1]!).toMatchObject({ composeSha: "abc", results: [{ id: "c1", ok: true, output: "said hi" }] }); |
| 252 | 257 | expect(called).not.toContain(TOKEN); |
| 253 | 258 | expect(statSync(join(box, ".auth")).mode & 0o777).toBe(0o600); |
test/game-diag.test.ts added +357
| @@ -0,0 +1,357 @@ | ||
| 1 | /** | |
| 2 | * A game box is never blind (box `mc`, 2026-12-01: one sync, then silent inside `compose up`): the | |
| 3 | * agent queues compose up in the background and keeps syncing every tick, each sync carrying `diag` | |
| 4 | * (the running job and its output, the containers, the journals, the disks) in about 8 KB, within | |
| 5 | * one deadline however a probe hangs; an interrupted job is queued again, never marked failed; the | |
| 6 | * forge keeps the latest; and /games/<box>, the terminal's Games and the MCP games tool say it in | |
| 7 | * plain lines: the box's owner its own words, anyone else what it is doing and nothing inside it. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; | |
| 11 | import { rm } from "node:fs/promises"; | |
| 12 | import { tmpdir } from "node:os"; | |
| 13 | import { join } from "node:path"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { createUser, type User } from "../src/core/users.ts"; | |
| 18 | import { DIAG_MOST, boxStatus, boxStatusShared, keptDiag } from "../src/games/diag.ts"; | |
| 19 | import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts"; | |
| 20 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 21 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 22 | import { gamesScreen } from "../src/tui/screens/games.ts"; | |
| 23 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 24 | import { quietLogs } from "./helpers/globals.ts"; | |
| 25 | import { mcpTool } from "./helpers/mcp.ts"; | |
| 26 | import { pollUntil } from "./helpers/poll.ts"; | |
| 27 | import { settleApp } from "./helpers/tui.ts"; | |
| 28 | ||
| 29 | quietLogs(); | |
| 30 | ||
| 31 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); | |
| 32 | const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"; | |
| 33 | const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null); | |
| 34 | ||
| 35 | /** A scratch box: a bin of fakes first on PATH, a forge that keeps every body, and a cleanup that stops all of it. */ | |
| 36 | function scratch(docker: string, answer: Record<string, unknown> = { composeSha: "", commands: [] }) { | |
| 37 | const root = mkdtempSync(join(tmpdir(), "forge-game-diag-")); | |
| 38 | const bin = join(root, "bin"); | |
| 39 | const dir = join(root, "game"); | |
| 40 | mkdirSync(bin); | |
| 41 | mkdirSync(dir); | |
| 42 | writeFileSync(join(bin, "docker"), docker); | |
| 43 | chmodSync(join(bin, "docker"), 0o755); | |
| 44 | const bodies: Record<string, any>[] = []; | |
| 45 | const forge = Bun.serve({ | |
| 46 | port: 0, | |
| 47 | hostname: "127.0.0.1", | |
| 48 | async fetch(req) { | |
| 49 | bodies.push((await req.json()) as Record<string, any>); | |
| 50 | return Response.json(answer); | |
| 51 | }, | |
| 52 | }); | |
| 53 | const env = (more: Record<string, string> = {}) => ({ | |
| 54 | PATH: `${bin}:${process.env["PATH"] ?? ""}`, | |
| 55 | FORGE_URL: `http://127.0.0.1:${String(forge.port)}`, | |
| 56 | FORGE_GAME_TOKEN: TOKEN, | |
| 57 | FORGE_GAME_DIR: dir, | |
| 58 | FORGE_GAME_DOCKER: join(bin, "docker"), | |
| 59 | ...more, | |
| 60 | }); | |
| 61 | /** Stop the job the agent started and everything under it, then the forge, then the files. */ | |
| 62 | const done = async (): Promise<void> => { | |
| 63 | const at = join(dir, ".job.pid"); | |
| 64 | const pid = existsSync(at) ? Number(readFileSync(at, "utf8")) : 0; | |
| 65 | if (Number.isInteger(pid) && pid > 0) { | |
| 66 | Bun.spawnSync(["pkill", "-P", String(pid)]); | |
| 67 | try { | |
| 68 | process.kill(pid); | |
| 69 | } catch { | |
| 70 | // Already gone. | |
| 71 | } | |
| 72 | } | |
| 73 | forge.stop(true); | |
| 74 | await rm(root, { recursive: true, force: true }); | |
| 75 | }; | |
| 76 | return { root, bin, dir, bodies, env, done }; | |
| 77 | } | |
| 78 | ||
| 79 | describe("the agent", () => { | |
| 80 | // One line each: the own-skips rule reads the line bun names for the case, so the condition sits on it. | |
| 81 | test.skipIf(lacks.length > 0)("a 30 s compose up never stops the sync: every tick carries diag, bounded", async () => { | |
| 82 | const box = scratch( | |
| 83 | `#!/usr/bin/env bash | |
| 84 | case "$*" in | |
| 85 | *" up -d --remove-orphans") echo "Pulling hub ... downloading 41%"; sleep 30 ;; | |
| 86 | "ps -a --format json") for i in $(seq 200); do echo "{\\"Names\\":\\"c$i\\",\\"State\\":\\"running\\",\\"Status\\":\\"Up 3 minutes\\",\\"Image\\":\\"itzg/minecraft-server:java21-$i\\"}"; done ;; | |
| 87 | "images --format json") for i in $(seq 200); do echo "{\\"Repository\\":\\"itzg/minecraft-server\\",\\"Tag\\":\\"t$i\\",\\"Size\\":\\"1.2GB\\"}"; done ;; | |
| 88 | "version --format"*) echo 27.5.1 ;; | |
| 89 | "compose version --short") echo 2.32.4 ;; | |
| 90 | esac | |
| 91 | `, | |
| 92 | { composeSha: "abc", compose: "services:\n hub:\n image: itzg/minecraft-server\n", commands: [] }, | |
| 93 | ); | |
| 94 | // A journal far longer than the diag keeps. | |
| 95 | writeFileSync( | |
| 96 | join(box.bin, "journalctl"), | |
| 97 | `#!/usr/bin/env bash\nfor i in $(seq 400); do echo "line $i of a long journal that goes on and on"; done\n`, | |
| 98 | ); | |
| 99 | chmodSync(join(box.bin, "journalctl"), 0o755); | |
| 100 | const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_EVERY: "0.2" }), stdout: "pipe", stderr: "pipe" }); | |
| 101 | try { | |
| 102 | await pollUntil(() => box.bodies.length >= 3, "three syncs while compose up runs", 15_000); | |
| 103 | // The first sync handed the compose file; every later one comes while the up still runs. | |
| 104 | const during = box.bodies.slice(2); | |
| 105 | for (const b of during) { | |
| 106 | expect(b["diag"]["job"]).toMatchObject({ label: "compose up", running: true }); | |
| 107 | expect(b["diag"]["upLog"]).toContain("downloading 41%"); | |
| 108 | expect(JSON.stringify(b["diag"]).length).toBeLessThan(9_000); | |
| 109 | expect(b["diag"]["ps"]).toHaveLength(30); | |
| 110 | expect(b["diag"]["images"]).toHaveLength(20); | |
| 111 | expect(b["diag"]["journal"]["agent"].length).toBeLessThanOrEqual(1_200); | |
| 112 | } | |
| 113 | expect(boxStatus(during.at(-1)!["diag"])[0]).toMatch(/^Pulling \(compose up\) since \S+: Pulling hub \.\.\. downloading 41%$/); | |
| 114 | expect(during.at(-1)!["composeSha"]).toBe(""); | |
| 115 | } finally { | |
| 116 | agent.kill(); | |
| 117 | await agent.exited; | |
| 118 | await box.done(); | |
| 119 | } | |
| 120 | }); | |
| 121 | ||
| 122 | test.skipIf(lacks.length > 0)("a hung docker never holds the sync: the diag says it ran over its deadline", async () => { | |
| 123 | const box = scratch(`#!/usr/bin/env bash\ncase "$*" in\n "ps -a --format json") sleep 20 ;;\nesac\n`); | |
| 124 | const started = Date.now(); | |
| 125 | const agent = Bun.spawn(["bash", AGENT], { | |
| 126 | env: box.env({ FORGE_GAME_ONCE: "1", FORGE_GAME_DIAG_S: "1" }), | |
| 127 | stdout: "pipe", | |
| 128 | stderr: "pipe", | |
| 129 | }); | |
| 130 | try { | |
| 131 | expect(await agent.exited).toBe(0); | |
| 132 | expect(box.bodies).toHaveLength(1); | |
| 133 | expect(box.bodies[0]!["diag"]).toEqual({ note: "diag ran over 1 s" }); | |
| 134 | // The hung probe was stopped at the deadline: the sync went out in seconds. | |
| 135 | expect(Date.now() - started).toBeLessThan(4_500); | |
| 136 | } finally { | |
| 137 | await box.done(); | |
| 138 | } | |
| 139 | }); | |
| 140 | ||
| 141 | test.skipIf(lacks.length > 0)("a job interrupted with no exit status is queued again, never marked failed", async () => { | |
| 142 | const box = scratch(`#!/usr/bin/env bash\necho "$*" >> "${"$"}{0%/*}/calls"\n`); | |
| 143 | // What an agent killed mid-up leaves: the job's files and a pid that is gone, no exit status. | |
| 144 | const gone = Bun.spawn(["true"]); | |
| 145 | await gone.exited; | |
| 146 | writeFileSync(join(box.dir, "compose.yml"), "services: {}\n"); | |
| 147 | for (const [f, v] of [ | |
| 148 | [".job.pid", String(gone.pid)], | |
| 149 | [".job.sha", "abc"], | |
| 150 | [".job.label", "compose up"], | |
| 151 | [".job.args", "up -d --remove-orphans"], | |
| 152 | [".job.id", ""], | |
| 153 | ] as const) | |
| 154 | writeFileSync(join(box.dir, f), v); | |
| 155 | const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_ONCE: "1" }), stdout: "pipe", stderr: "pipe" }); | |
| 156 | try { | |
| 157 | expect(await agent.exited).toBe(0); | |
| 158 | expect(await new Response(agent.stderr).text()).toContain("the last job was interrupted; queued again"); | |
| 159 | expect(existsSync(join(box.dir, ".up.failed"))).toBe(false); | |
| 160 | // Queued again and started: the up runs (or ran) as itself. | |
| 161 | await pollUntil( | |
| 162 | () => existsSync(join(box.bin, "calls")) && readFileSync(join(box.bin, "calls"), "utf8").includes("up -d --remove-orphans"), | |
| 163 | "the up started again", | |
| 164 | 5_000, | |
| 165 | ); | |
| 166 | // It ran to its end as the up it was: its compose is current once reaped, nothing marked failed. | |
| 167 | await pollUntil(() => existsSync(join(box.dir, ".job.rc")) || existsSync(join(box.dir, ".compose-sha")), "the up ended", 5_000); | |
| 168 | expect(existsSync(join(box.dir, ".up.failed"))).toBe(false); | |
| 169 | } finally { | |
| 170 | await box.done(); | |
| 171 | } | |
| 172 | }); | |
| 173 | }); | |
| 174 | ||
| 175 | // Where the kernel names a process's command line, a pid now held by another program is not our job. | |
| 176 | const procs = existsSync("/proc/self/cmdline"); | |
| 177 | describe("a reused pid", () => { | |
| 178 | test.skipIf(lacks.length > 0 || !procs)("a live pid that is not the job is an interrupted job: the up runs again", async () => { | |
| 179 | const box = scratch(`#!/usr/bin/env bash\necho "$*" >> "${"$"}{0%/*}/calls"\n`); | |
| 180 | const stranger = Bun.spawn(["sleep", "30"]); | |
| 181 | writeFileSync(join(box.dir, "compose.yml"), "services: {}\n"); | |
| 182 | for (const [f, v] of [ | |
| 183 | [".job.pid", String(stranger.pid)], | |
| 184 | [".job.sha", "abc"], | |
| 185 | [".job.label", "compose up"], | |
| 186 | [".job.args", "up -d --remove-orphans"], | |
| 187 | [".job.id", ""], | |
| 188 | ] as const) | |
| 189 | writeFileSync(join(box.dir, f), v); | |
| 190 | const agent = Bun.spawn(["bash", AGENT], { env: box.env({ FORGE_GAME_ONCE: "1" }), stdout: "pipe", stderr: "pipe" }); | |
| 191 | try { | |
| 192 | expect(await agent.exited).toBe(0); | |
| 193 | expect(await new Response(agent.stderr).text()).toContain("the last job was interrupted; queued again"); | |
| 194 | await pollUntil( | |
| 195 | () => existsSync(join(box.bin, "calls")) && readFileSync(join(box.bin, "calls"), "utf8").includes("up -d --remove-orphans"), | |
| 196 | "the up started again", | |
| 197 | 5_000, | |
| 198 | ); | |
| 199 | expect(existsSync(join(box.dir, ".up.failed"))).toBe(false); | |
| 200 | } finally { | |
| 201 | stranger.kill(); | |
| 202 | await box.done(); | |
| 203 | } | |
| 204 | }); | |
| 205 | }); | |
| 206 | ||
| 207 | describe("the diag in words", () => { | |
| 208 | test("a failed up says its last error line; the wrong disk, an unmounted volume and a full disk are said", () => { | |
| 209 | expect( | |
| 210 | boxStatus({ | |
| 211 | job: { label: "compose up", running: false, last: "1" }, | |
| 212 | upLog: "Pulling hub\nError response from daemon: no space left on device\n", | |
| 213 | }), | |
| 214 | ).toEqual(["compose up failed: Error response from daemon: no space left on device"]); | |
| 215 | expect(boxStatus({ disk: { volume: "/mnt/mc_data", volumeMounted: true, onVolume: false } })).toEqual([ | |
| 216 | "Docker's data is on the root disk, not the volume", | |
| 217 | ]); | |
| 218 | expect(boxStatus({ disk: { volume: "/mnt/mc_data", volumeMounted: false, onVolume: false } })).toEqual([ | |
| 219 | "The volume is not mounted at /mnt/mc_data", | |
| 220 | ]); | |
| 221 | expect(boxStatus({ disk: { root: "Filesystem Size Used Avail Use% Mounted on\n/dev/vda1 25G 23G 2G 92% /\n" } })).toEqual([ | |
| 222 | "The root disk is 92% full", | |
| 223 | ]); | |
| 224 | expect( | |
| 225 | boxStatus({ | |
| 226 | ps: [ | |
| 227 | { name: "hub", state: "running" }, | |
| 228 | { name: "lobby", state: "exited" }, | |
| 229 | ], | |
| 230 | }), | |
| 231 | ).toEqual(["2 containers: 1 running, 1 not"]); | |
| 232 | expect(boxStatus({ job: { label: "compose up", running: true, since: "2026-12-01T17:47:45Z" }, upLog: "Creating hub\n" })).toEqual([ | |
| 233 | "Applying (compose up) since 2026-12-01T17:47:45Z", | |
| 234 | ]); | |
| 235 | expect(boxStatus({})).toEqual([]); | |
| 236 | }); | |
| 237 | ||
| 238 | test("the lines anyone else is told name no container, image, error or journal", () => { | |
| 239 | const d = { | |
| 240 | job: { label: "compose up", running: false, last: "1" }, | |
| 241 | upLog: "Error: pull access denied for itzg/secret-thing", | |
| 242 | ps: [ | |
| 243 | { name: "hub", state: "running", image: "itzg/secret-thing" }, | |
| 244 | { name: "lobby", state: "exited" }, | |
| 245 | ], | |
| 246 | }; | |
| 247 | expect(boxStatusShared(d)).toEqual(["The box's last change did not apply; its owner can see why", "1 of 2 running"]); | |
| 248 | expect(boxStatusShared({ job: { label: "pull hub", running: true, since: "t" } })).toEqual(["Pulling since t"]); | |
| 249 | }); | |
| 250 | ||
| 251 | test("the forge keeps at most 16 KB of it", () => { | |
| 252 | expect(keptDiag({ job: { label: "x" } })).toBe('{"job":{"label":"x"}}'); | |
| 253 | expect(JSON.parse(keptDiag({ upLog: "x".repeat(DIAG_MOST) }))).toEqual({ note: expect.stringContaining("at most 16384 are kept") }); | |
| 254 | expect(keptDiag("nope")).toBe("{}"); | |
| 255 | }); | |
| 256 | }); | |
| 257 | ||
| 258 | describe("the doors", () => { | |
| 259 | let dir = ""; | |
| 260 | let app: App; | |
| 261 | let servers: Servers; | |
| 262 | let alice: User; | |
| 263 | let bob: User; | |
| 264 | const OWNERS = "compose up failed: Error response from daemon: pull access denied for itzg/nope"; | |
| 265 | ||
| 266 | beforeAll(async () => { | |
| 267 | dir = mkdtempSync(join(tmpdir(), "forge-game-diag-doors-")); | |
| 268 | app = createApp({ dataDir: dir, port: 0 }); | |
| 269 | servers = await serve(app); | |
| 270 | for (const [username, adminIfFirst] of [ | |
| 271 | ["alice", true], | |
| 272 | ["bob", false], | |
| 273 | ] as const) { | |
| 274 | const made = await createUser(app.db, { | |
| 275 | origin: "seed", | |
| 276 | trusted: true, | |
| 277 | username, | |
| 278 | email: `${username}@f.test`, | |
| 279 | password: "a-good-passphrase", | |
| 280 | adminIfFirst, | |
| 281 | }); | |
| 282 | if (!made.ok) throw new Error(made.error); | |
| 283 | if (username === "alice") alice = made.value; | |
| 284 | else bob = made.value; | |
| 285 | } | |
| 286 | createGameBox(app.db, { name: "mc" }); | |
| 287 | const box = boxNamed(app.db, "mc")!; | |
| 288 | recordSync(app.db, box, { | |
| 289 | composeSha: "", | |
| 290 | services: [{ name: "hub", state: "running" }], | |
| 291 | diag: { | |
| 292 | job: { label: "compose up", running: false, last: "1" }, | |
| 293 | upLog: "Pulling hub\nError response from daemon: pull access denied for itzg/nope\n", | |
| 294 | ps: [ | |
| 295 | { name: "hub", state: "running", status: "Up", image: "itzg/nope" }, | |
| 296 | { name: "lobby", state: "exited", status: "Exited (1)", image: "itzg/nope" }, | |
| 297 | ], | |
| 298 | disk: { volume: "/mnt/mc_data", volumeMounted: true, onVolume: false, root: "/dev/vda1 25G 5G 20G 20% /" }, | |
| 299 | journal: { agent: "forge-game-agent: sync ok" }, | |
| 300 | }, | |
| 301 | }); | |
| 302 | // Bob may see one service of the box, and nothing of the box itself. | |
| 303 | grant(app.db, box.id, bob.id, "viewer", "hub"); | |
| 304 | }); | |
| 305 | afterAll(async () => { | |
| 306 | servers.stop(); | |
| 307 | app.close(); | |
| 308 | await rm(dir, { recursive: true, force: true }); | |
| 309 | }); | |
| 310 | ||
| 311 | const pageAs = async (who: User) => | |
| 312 | (await fetch(`${servers.url}/games/mc`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } })).text(); | |
| 313 | const termAs = async (who: User) => { | |
| 314 | const terminal = headlessTerminal(140, 20); | |
| 315 | const { app: tui, session } = createForgeApp( | |
| 316 | app, | |
| 317 | { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: who }, | |
| 318 | { terminal, exitHooks: false }, | |
| 319 | ); | |
| 320 | tui.start(); | |
| 321 | tui.ctx.push(gamesScreen(session, tui.ctx)); | |
| 322 | await settleApp(tui); | |
| 323 | const text = tui.screen.toText(); | |
| 324 | tui.stop?.(); | |
| 325 | return text; | |
| 326 | }; | |
| 327 | ||
| 328 | test("/games/<box>: its owner reads the lines and the folded run log", async () => { | |
| 329 | const page = await pageAs(alice); | |
| 330 | expect(page).toContain("<h2>Box</h2>"); | |
| 331 | expect(page).toContain(OWNERS); | |
| 332 | expect(page).toContain("Docker's data is on the root disk, not the volume"); | |
| 333 | expect(page).toContain("Run log"); | |
| 334 | expect(page).toContain("== The agent's journal"); | |
| 335 | }); | |
| 336 | ||
| 337 | test("a viewer of one service reads what the box is doing, and nothing inside it, at every door", async () => { | |
| 338 | const page = await pageAs(bob); | |
| 339 | expect(page).toContain("1 of 2 running"); | |
| 340 | for (const secret of ["pull access denied", "itzg/nope", "Run log", "journal", "root disk"]) expect(page).not.toContain(secret); | |
| 341 | const term = await termAs(bob); | |
| 342 | expect(term).toContain("mc: The box's last change did not apply; its owner can see why".replace("'", "'")); | |
| 343 | expect(term).not.toContain("pull access denied"); | |
| 344 | const listed = await mcpTool(servers.url, createToken(app.db, bob.id, "rw", "rw").token, "games", { action: "list" }); | |
| 345 | expect(listed.value.items[0].status).toEqual(["The box's last change did not apply; its owner can see why", "1 of 2 running"]); | |
| 346 | }); | |
| 347 | ||
| 348 | test("the owner's terminal shows the top line; the owner's MCP games list carries at most three", async () => { | |
| 349 | expect(await termAs(alice)).toContain(`mc: ${OWNERS}`); | |
| 350 | const listed = await mcpTool(servers.url, createToken(app.db, alice.id, "admin", "admin").token, "games", { action: "list" }); | |
| 351 | expect(listed.value.items[0].status).toEqual([ | |
| 352 | OWNERS, | |
| 353 | "Docker's data is on the root disk, not the volume", | |
| 354 | "2 containers: 1 running, 1 not", | |
| 355 | ]); | |
| 356 | }); | |
| 357 | }); |
new above
offline