Public: anyone can read this; the crew can change it.
Game boxes keep their worlds on the volume, and the agent updates itself #17264
Merged 35h 11m ago, live in production
sold/game-volume → main 0 commits 3 threads · 3 unresolved
15 files
changed +837
−42
- docs/features/game-box.md
- src/contract/openapi/routes/getApiV1GamesAgentScript.ts
- src/contract/openapi/routes/index.ts
- src/contract/openapi/routes/postApiV1GamesAgentSync.ts
- src/games/agent.sh
- src/games/boot.ts
- src/games/diag.ts
- src/http/games_routes.ts
- src/http/lazy_lists.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/game-agent-update.test.ts
- test/game-box.test.ts
- test/game-diag.test.ts
- test/game-volume.test.ts
docs/features/game-box.md +9 −1
| @@ -15,7 +15,15 @@ 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 (Java) and 19132/udp (Bedrock, through Geyser on the proxy): no SSH, no web, no backend port. A cloud firewall the forge makes on request opens only the web ports, so a game box should not be given one. 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 | - **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 (`b` there opens the box: the same plain lines and raw tails) and the MCP games tool's `list` up to three. | |
| 19 | - **The volume:** the box's worlds live on its cloud volume, never on the root disk a replace destroys. The boot runs `agent.sh --mount-volume` before Docker is installed, and the agent runs the same check once at each start: | |
| 20 | - **Find:** the volume is the device the cloud attaches (`/dev/disk/by-id/scsi-0DO_Volume_*` on DigitalOcean, `scsi-0HC_Volume_*` on Hetzner), waited for up to a minute at boot. With none, nothing is mounted and the log says so. | |
| 21 | - **Mounted means the volume holds the data directory:** `findmnt -n -o SOURCE --target <dir>` is the device, by-id links resolved. Another device mounted there is not the volume. | |
| 22 | - **Format:** only a blank device is formatted (ext4, label `forge-data`). One with a filesystem is used as it is; one with any other signature (`wipefs` finds one) is refused, never formatted. | |
| 23 | - **Mount:** at the data directory (the boot's `FORGE_GAME_DATA`, `/mnt/<volume>`), in `/etc/fstab` by UUID with `nofail` (once), and a systemd drop-in (`docker.service.d/forge-volume.conf`, `RequiresMountsFor=`) so Docker never starts without the volume after a reboot, rather than on the old copy under the mount point. | |
| 24 | - **Move:** a data directory that already holds data on the root disk (a box made before this) is moved once: the volume is mounted aside, refused if it already holds anything, then compose stops, Docker stops, `rsync -aHAX` copies, and the volume is mounted at the data directory, put in fstab, the drop-in written and the compose sha dropped, all before Docker starts again; compose comes up at the next sync. The root disk's copy stays under the mount, untouched, until a person removes it. If rsync is missing, or compose, Docker or the copy fails, Docker starts again on the root disk's data as it was. If the final mount fails after the copy, Docker starts again on the root disk and the log says so with `failed:`. | |
| 25 | - **Reading it:** every step is a line of `/opt/forge-game/.volume.log` (the last 40 kept), each step of a move also posted to the forge as the box's word. Each sync's diag carries the volume's device and the log's last 12 lines (`disk.device`, `disk.log`). The owner reads them under "The volume (.volume.log)" in `/games/<box>`'s run log and on the terminal's box screen, and a last line starting `failed:` or `refused:` comes first in the Box section and the Games screen's top line as "The volume: …". | |
| 26 | - **Updating itself:** every sync answers `agentSha`, the sha256 of the agent this forge ships. An agent whose own sha differs fetches `GET /api/v1/games/agent/script` with its token, checks that the fetched script's sha is the one answered and that `bash -n` parses it, puts it in place (`agent.sh.next`, then a rename) and exits, and systemd starts the new one. A script whose sha is not the one answered is deleted and never runs; an agent already current fetches nothing. An agent older than this step does not update itself; it takes the new one with its machine's next replace. | |
| 19 | 27 | - **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. |
| 20 | 28 | - **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. |
| 21 | 29 |
src/contract/openapi/routes/getApiV1GamesAgentScript.ts added +13
| @@ -0,0 +1,13 @@ | ||
| 1 | import type { Route } from "../shared.ts"; | |
| 2 | ||
| 3 | export const route: Route = { | |
| 4 | method: "get", | |
| 5 | path: "/api/v1/games/agent/script", | |
| 6 | summary: "The game agent this forge runs, for a box to update itself", | |
| 7 | detail: | |
| 8 | "The game agent script this forge runs (text), for a game box whose own agent's sha256 differs from the agentSha the sync answered. Takes the box's token as the bearer, as the sync does. The box checks the script's sha256 against agentSha before it runs it; x-agent-sha carries it too.", | |
| 9 | auth: false, | |
| 10 | role: "anonymous", | |
| 11 | refusals: { unauthorized: "401: not a game box token" }, | |
| 12 | errorStatus: { 401: "`unauthorized`: not a game box token" }, | |
| 13 | }; |
src/contract/openapi/routes/index.ts +1
| @@ -124,6 +124,7 @@ export { route as getApiV1ForgesSizes } from "./getApiV1ForgesSizes.ts"; | ||
| 124 | 124 | export { route as getApiV1ForgesTemplates } from "./getApiV1ForgesTemplates.ts"; |
| 125 | 125 | export { route as getApiV1ForksFlows } from "./getApiV1ForksFlows.ts"; |
| 126 | 126 | export { route as getApiV1Front } from "./getApiV1Front.ts"; |
| 127 | export { route as getApiV1GamesAgentScript } from "./getApiV1GamesAgentScript.ts"; | |
| 127 | 128 | export { route as getApiV1Health } from "./getApiV1Health.ts"; |
| 128 | 129 | export { route as getApiV1Here } from "./getApiV1Here.ts"; |
| 129 | 130 | export { route as getApiV1Keeper } from "./getApiV1Keeper.ts"; |
src/contract/openapi/routes/postApiV1GamesAgentSync.ts +1 −1
| @@ -4,7 +4,7 @@ export const route: Route = { | ||
| 4 | 4 | method: "post", |
| 5 | 5 | path: "/api/v1/games/agent/sync", |
| 6 | 6 | summary: "A game box agent's sync: status, logs and results in; compose, .env and commands out", |
| 7 | detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands }`, each command handed out once", | |
| 7 | detail: "The bearer is the game box's token. Send `{ agent, composeSha, services, logs, results, host }`; the answer is `{ composeSha, compose? (only when the sha differs), env, commands, agentSha }`, each command handed out once; agentSha is the sha256 of the agent this forge runs, which a box whose own differs fetches from GET /api/v1/games/agent/script", | |
| 8 | 8 | auth: false, |
| 9 | 9 | role: "anonymous", |
| 10 | 10 | refuses: [401], |
src/games/agent.sh +203 −3
| @@ -53,6 +53,196 @@ say_boot() { | ||
| 53 | 53 | --data-binary "{\"agent\":1,\"boot\":$(json_str "")}" "/api/v1/games/agent/sync" >/dev/null 2>&1 || true |
| 54 | 54 | } |
| 55 | 55 | |
| 56 | # ---- the box's data volume (2026-12-01: box mc's worlds sat on the root disk, which a replace | |
| 57 | # destroys). The cloud attaches the volume; the box itself formats it (only when blank, never over | |
| 58 | # data), mounts it at the data directory and keeps it in fstab with nofail, before Docker starts. | |
| 59 | # A box that started with its data on the root disk moves it there once, step by step, each step | |
| 60 | # in .volume.log (and so in diag); any failure leaves the root disk's data as it was. No jq here: | |
| 61 | # the boot runs this before jq is installed. ---- | |
| 62 | ||
| 63 | VOLUME_LOG="/.volume.log" | |
| 64 | vol_say() { | |
| 65 | mkdir -p "" | |
| 66 | printf '%s %s\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$*" >>"" | |
| 67 | tail -n 40 "" >".next" 2>/dev/null && mv ".next" "" | |
| 68 | echo "forge-game-agent: volume: $*" >&2 | |
| 69 | } | |
| 70 | # Where the data lives: the boot's word, else Docker's data root less its /docker. | |
| 71 | data_dir() { | |
| 72 | if [ -n "" ]; then | |
| 73 | echo "" | |
| 74 | return | |
| 75 | fi | |
| 76 | sed -n 's/.*"data-root" *: *"\([^"]*\)\/docker".*/\1/p' "" 2>/dev/null | head -n 1 | |
| 77 | } | |
| 78 | # The attached volume's device, by the id the cloud gives it (DigitalOcean, Hetzner). | |
| 79 | volume_device() { | |
| 80 | local d | |
| 81 | if [ -n "" ]; then | |
| 82 | [ -e "" ] && echo "" | |
| 83 | return | |
| 84 | fi | |
| 85 | for d in /dev/disk/by-id/scsi-0DO_Volume_* /dev/disk/by-id/scsi-0HC_Volume_*; do | |
| 86 | [ -e "" ] && { echo ""; return; } | |
| 87 | done | |
| 88 | } | |
| 89 | # Format the volume only when it holds nothing at all: no filesystem and no signature of any kind. | |
| 90 | volume_fs() { | |
| 91 | local dev="$1" | |
| 92 | if [ -n "$(blkid -o value -s TYPE "" 2>/dev/null)" ]; then return 0; fi | |
| 93 | if [ -n "$(wipefs -n "" 2>/dev/null | tail -n +2)" ]; then | |
| 94 | vol_say "refused: has a signature but no filesystem this box knows; nothing was formatted" | |
| 95 | return 1 | |
| 96 | fi | |
| 97 | vol_say "formatting the blank volume (ext4)" | |
| 98 | mkfs.ext4 -q -L forge-data "" || { vol_say "failed: formatting "; return 1; } | |
| 99 | } | |
| 100 | # Keep the volume at `dir` across reboots; nofail, so a missing volume never stops a boot. | |
| 101 | volume_fstab() { | |
| 102 | local dev="$1" dir="$2" uuid | |
| 103 | uuid="$(blkid -o value -s UUID "" 2>/dev/null)" | |
| 104 | [ -n "" ] || { vol_say "failed: has no UUID for fstab"; return 1; } | |
| 105 | grep -q "UUID= " "" 2>/dev/null || | |
| 106 | printf 'UUID=%s %s ext4 defaults,nofail,discard 0 2\n' "" "" >>"" | |
| 107 | } | |
| 108 | # Whether the volume `dev` is what holds `dir`: the source of the mount `dir` sits on is the | |
| 109 | # device, by-id links resolved. A directory that is a mountpoint of anything else is not it. | |
| 110 | volume_here() { | |
| 111 | local dev="$1" dir="$2" src | |
| 112 | src="$(findmnt -n -o SOURCE --target "" 2>/dev/null | head -n 1)" | |
| 113 | [ -n "" ] || return 1 | |
| 114 | [ "$(readlink -f "" 2>/dev/null || echo "")" = "$(readlink -f "" 2>/dev/null || echo "")" ] | |
| 115 | } | |
| 116 | # Docker never starts without the volume at `dir`: a reboot whose mount fails (nofail) would | |
| 117 | # otherwise run the games on the root disk's old copy under the mount point. | |
| 118 | docker_needs_volume() { | |
| 119 | local dir="$1" d="/docker.service.d" | |
| 120 | mkdir -p "" && printf '[Unit]\nRequiresMountsFor=%s\n' "" >"/forge-volume.conf" && systemctl daemon-reload >/dev/null 2>&1 || | |
| 121 | vol_say "failed: Docker could not be made to wait for the volume at " | |
| 122 | } | |
| 123 | # Mount the volume at the data directory. At a fresh boot the directory is empty; one that holds | |
| 124 | # data is moved (`volume_move`), never mounted over silently. | |
| 125 | volume_mount() { | |
| 126 | local dir dev="" i | |
| 127 | dir="$(data_dir)" | |
| 128 | [ -n "" ] || { vol_say "no data directory known; nothing mounted"; return 1; } | |
| 129 | for ((i = 0; i < ; i++)); do | |
| 130 | dev="$(volume_device)" | |
| 131 | [ -n "" ] && break | |
| 132 | sleep 1 | |
| 133 | done | |
| 134 | [ -n "" ] || { vol_say "no volume device attached; the data stays on the root disk"; return 1; } | |
| 135 | if volume_here "" ""; then | |
| 136 | vol_say "the volume is mounted at " | |
| 137 | return 0 | |
| 138 | fi | |
| 139 | volume_fs "" || return 1 | |
| 140 | if [ -d "" ] && [ -n "$(ls -A "" 2>/dev/null)" ]; then | |
| 141 | volume_move "" "" | |
| 142 | return | |
| 143 | fi | |
| 144 | mkdir -p "" | |
| 145 | mount "" "" || { vol_say "failed: mount "; return 1; } | |
| 146 | volume_fstab "" "" | |
| 147 | docker_needs_volume "" | |
| 148 | vol_say "mounted at " | |
| 149 | } | |
| 150 | # A step of the move: in .volume.log, and to the forge at once as the box's word about its boot, | |
| 151 | # since no sync goes out while the move runs. | |
| 152 | vol_step() { | |
| 153 | vol_say "$*" | |
| 154 | [ -n "" ] && [ -f "" ] && say_boot "moving the data to the volume: $*" | |
| 155 | } | |
| 156 | # Move what the root disk holds at `dir` onto the volume, once. Compose and Docker are stopped so | |
| 157 | # nothing writes meanwhile; the volume must be empty. The volume is mounted at `dir`, in fstab, | |
| 158 | # and Docker made to wait for it, before Docker starts again. Any failure before that starts Docker | |
| 159 | # again on the root disk's data, as it was, and says so with "failed:" (diag shows it). | |
| 160 | volume_move() { | |
| 161 | local dev="$1" dir="$2" tmp="" rc | |
| 162 | vol_step "moving to the volume " | |
| 163 | mkdir -p "" | |
| 164 | mount "" "" || { vol_step "failed: mount ; the data stays on the root disk"; return 1; } | |
| 165 | if [ -n "$(ls -A "" 2>/dev/null | grep -v '^lost+found$')" ]; then | |
| 166 | umount "" | |
| 167 | vol_step "refused: the volume already holds data; nothing was copied, the data stays on the root disk" | |
| 168 | return 1 | |
| 169 | fi | |
| 170 | if ! command -v rsync >/dev/null 2>&1; then | |
| 171 | umount "" | |
| 172 | vol_step "failed: rsync is not installed; nothing was copied, the data stays on the root disk" | |
| 173 | return 1 | |
| 174 | fi | |
| 175 | vol_step "stopping compose and Docker" | |
| 176 | if [ -f "/compose.yml" ] && ! "" compose -p game --project-directory "" -f "/compose.yml" stop >/dev/null 2>&1; then | |
| 177 | umount "" | |
| 178 | vol_step "failed: compose would not stop; nothing was copied, the data stays on the root disk" | |
| 179 | return 1 | |
| 180 | fi | |
| 181 | # A box without Docker yet has nothing to stop; one whose Docker is still running is not copied. | |
| 182 | systemctl stop docker.socket docker >/dev/null 2>&1 | |
| 183 | if systemctl is-active --quiet docker 2>/dev/null; then | |
| 184 | umount "" | |
| 185 | systemctl start docker >/dev/null 2>&1 | |
| 186 | vol_step "failed: Docker would not stop; nothing was copied, the data stays on the root disk" | |
| 187 | return 1 | |
| 188 | fi | |
| 189 | vol_step "copying to the volume" | |
| 190 | rsync -aHAX --numeric-ids "/" "/" | |
| 191 | rc= | |
| 192 | if [ "" != 0 ]; then | |
| 193 | umount "" | |
| 194 | systemctl start docker >/dev/null 2>&1 | |
| 195 | vol_step "failed: rsync exited ; the data stays on the root disk, Docker started again" | |
| 196 | return 1 | |
| 197 | fi | |
| 198 | if ! umount ""; then | |
| 199 | systemctl start docker >/dev/null 2>&1 | |
| 200 | vol_step "failed: umount after the copy; Docker started again on the root disk's data, and the volume's copy is not used" | |
| 201 | return 1 | |
| 202 | fi | |
| 203 | if ! mount "" ""; then | |
| 204 | systemctl start docker >/dev/null 2>&1 | |
| 205 | vol_step "failed: mount after the copy; Docker started again on the root disk's data, and the volume's copy is not used" | |
| 206 | return 1 | |
| 207 | fi | |
| 208 | volume_fstab "" "" | |
| 209 | docker_needs_volume "" | |
| 210 | # Compose comes up again at the next sync: its sha is no longer current. | |
| 211 | rm -f "/.compose-sha" | |
| 212 | systemctl start docker >/dev/null 2>&1 || vol_step "failed: Docker would not start again on the volume" | |
| 213 | # The root disk's copy stays under the mount, untouched, until a person removes it. | |
| 214 | vol_step "moved: is on the volume now; the old copy under it on the root disk is untouched" | |
| 215 | } | |
| 216 | ||
| 217 | # The boot's own step, before Docker is installed: find, format if blank, mount, fstab. | |
| 218 | if [ "" = "--mount-volume" ]; then | |
| 219 | volume_mount | |
| 220 | exit 0 | |
| 221 | fi | |
| 222 | ||
| 223 | # ---- self-update: the sync answers the sha256 of the forge's agent.sh; on a mismatch the agent | |
| 224 | # fetches it, checks its sha and its syntax, puts it in place atomically and exits, and systemd | |
| 225 | # starts the new one. A script whose sha is not the one answered never runs. ---- | |
| 226 | ||
| 227 | SELF="" | |
| 228 | self_update() { | |
| 229 | local want="$1" have next got | |
| 230 | [[ "" =~ ^[0-9a-f]{64}$ ]] || return 0 | |
| 231 | have="$(sha256sum "" 2>/dev/null | cut -d' ' -f1)" | |
| 232 | [ "" = "" ] && return 0 | |
| 233 | next=".next" | |
| 234 | curl -fsS -m 30 -H "@" "/api/v1/games/agent/script" -o "" || { echo "forge-game-agent: the new agent could not be fetched" >&2; return 0; } | |
| 235 | got="$(sha256sum "" | cut -d' ' -f1)" | |
| 236 | if [ "" != "" ] || ! bash -n "" 2>/dev/null; then | |
| 237 | rm -f "" | |
| 238 | echo "forge-game-agent: refused the fetched agent: its sha is , the forge said " >&2 | |
| 239 | return 0 | |
| 240 | fi | |
| 241 | chmod 0755 "" && mv "" "" | |
| 242 | echo "forge-game-agent: updated to ; exiting so systemd starts it" >&2 | |
| 243 | exit 0 | |
| 244 | } | |
| 245 | ||
| 56 | 246 | # The boot's last step: say how it went, once, so a box whose agent cannot start still shows why. |
| 57 | 247 | if [ "" = "--boot-report" ]; then |
| 58 | 248 | say_boot "boot report: $(boot_status)" |
| @@ -343,7 +533,7 @@ apply() { | ||
| 343 | 533 | diag() { |
| 344 | 534 | local root mount_of volume |
| 345 | 535 | root="$(jq -r '."data-root" // ""' /etc/docker/daemon.json 2>/dev/null)" |
| 346 | volume="" | |
| 536 | volume="$(data_dir)" | |
| 347 | 537 | mount_of="$(probe 400 findmnt -n -o TARGET --target "")" |
| 348 | 538 | jq -cn \ |
| 349 | 539 | --arg label "$(cat "/.job.label" 2>/dev/null)" \ |
| @@ -352,6 +542,8 @@ diag() { | ||
| 352 | 542 | --arg last "$(cat "/.job.last" 2>/dev/null)" \ |
| 353 | 543 | --arg queued "$(wc -l <"" 2>/dev/null | tr -dc 0-9)" \ |
| 354 | 544 | --arg up "$(tail -n 40 "/.up.log" 2>/dev/null | tail -c 2000)" \ |
| 545 | --arg vlog "$(tail -n 12 "" 2>/dev/null | tail -c 1200)" \ | |
| 546 | --arg vdev "$(volume_device)" \ | |
| 355 | 547 | --arg ps "$(probe 4000 "" ps -a --format json)" \ |
| 356 | 548 | --arg images "$(probe 2000 "" images --format json)" \ |
| 357 | 549 | --arg agent "$(probe 1200 journalctl -u forge-game-agent -n 30 --no-pager -o cat)" \ |
| @@ -361,7 +553,7 @@ diag() { | ||
| 361 | 553 | --arg root "" \ |
| 362 | 554 | --arg volume "" \ |
| 363 | 555 | --arg mount "" \ |
| 364 | --arg mounted "$( [ -n "" ] && mountpoint -q "" 2>/dev/null && echo yes || echo no)" \ | |
| 556 | --arg mounted "$(dev=""; [ -n "" ] && [ -n "" ] && volume_here "" "" && echo yes || echo no)" \ | |
| 365 | 557 | --arg dockerv "$(probe 80 "" version --format '{{.Server.Version}}')" \ |
| 366 | 558 | --arg composev "$(probe 80 "" compose version --short)" \ |
| 367 | 559 | '{ |
| @@ -371,7 +563,7 @@ diag() { | ||
| 371 | 563 | images: [( | split("\n")[] | fromjson? | {image: ((.Repository // "") + ":" + (.Tag // "")), size: (.Size // "")})][0:20], |
| 372 | 564 | journal: {agent: , docker: }, |
| 373 | 565 | cloudInit: , |
| 374 | disk: {root: , dataRoot: , volume: , mountOfDataRoot: ( | rtrimstr("\n")), volumeMounted: ( == "yes"), onVolume: ( != "" and ( | rtrimstr("\n")) == )}, | |
| 566 | disk: {root: , dataRoot: , volume: , device: , log: , mountOfDataRoot: ( | rtrimstr("\n")), volumeMounted: ( == "yes"), onVolume: ( != "" and ( | rtrimstr("\n")) == )}, | |
| 375 | 567 | versions: {docker: ( | rtrimstr("\n")), compose: ( | rtrimstr("\n"))} |
| 376 | 568 | }' 2>/dev/null || echo '{}' |
| 377 | 569 | } |
| @@ -430,9 +622,17 @@ sync() { | ||
| 430 | 622 | # Delivered: the results and the log lines are the forge's now. |
| 431 | 623 | echo '[]' >"/.results" |
| 432 | 624 | since="" |
| 625 | # A newer agent first: nothing of this answer is applied by a script the forge has replaced. | |
| 626 | self_update "$(jq -r '.agentSha // ""' <<<"")" | |
| 433 | 627 | apply "" |
| 434 | 628 | } |
| 435 | 629 | |
| 630 | # Once at each start: a volume attached but not mounted at the data directory is mounted, or the | |
| 631 | # data the root disk holds is moved onto it. | |
| 632 | if [ "" = 1 ] && [ -n "$(volume_device)" ] && [ -n "$(data_dir)" ] && ! volume_here "$(volume_device)" "$(data_dir)"; then | |
| 633 | FORGE_GAME_VOLUME_WAIT=1 volume_mount || true | |
| 634 | fi | |
| 635 | ||
| 436 | 636 | while :; do |
| 437 | 637 | job_tick |
| 438 | 638 | shell_tick |
src/games/boot.ts +5 −12
| @@ -22,6 +22,8 @@ const SWAP_GIB = 4; | ||
| 22 | 22 | |
| 23 | 23 | /** The agent, as it ships beside this file. */ |
| 24 | 24 | export const AGENT_SH: string = agentScript; |
| 25 | /** Its sha256, hex: the sync answers it, and a box whose own differs updates itself. */ | |
| 26 | export const AGENT_SHA: string = new Bun.CryptoHasher("sha256").update(AGENT_SH).digest("hex"); | |
| 25 | 27 | |
| 26 | 28 | /** What only the box's own boot config carries: the forge it answers to and its token. */ |
| 27 | 29 | export interface GameBoot { |
| @@ -52,16 +54,7 @@ WantedBy=multi-user.target | ||
| 52 | 54 | * `package_upgrade`: unattended-upgrades does that once the box is up. |
| 53 | 55 | */ |
| 54 | 56 | export const INSTALL = |
| 55 | "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"; | |
| 56 | ||
| 57 | /** | |
| 58 | * Wait up to a minute for the cloud to mount the box's volume at `dataDir` (DigitalOcean mounts an | |
| 59 | * attached volume at /mnt/<its name> through its own setup), so Docker's data lands on the volume | |
| 60 | * and not on the root disk under it; say so in the journal when it never comes (the agent's diag | |
| 61 | * says it too: `volumeMounted`). | |
| 62 | */ | |
| 63 | export const volumeWait = (dataDir: string): string => | |
| 64 | `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"`; | |
| 57 | "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 rsync && break; sleep 30; done"; | |
| 65 | 58 | |
| 66 | 59 | /** The cloud-config for a game box whose volume is mounted at `dataDir`. */ |
| 67 | 60 | export function gameBootConfig(g: GameBoot, dataDir: string): string { |
| @@ -69,7 +62,7 @@ export function gameBootConfig(g: GameBoot, dataDir: string): string { | ||
| 69 | 62 | if (url.protocol !== "https:" && url.hostname !== "127.0.0.1" && url.hostname !== "localhost") throw new Error("a game box answers to its forge over https"); |
| 70 | 63 | if (!TOKEN.test(g.token)) throw new Error("that is not a game box token"); |
| 71 | 64 | if (!/^\/[A-Za-z0-9/_.-]+$/.test(dataDir)) throw new Error("the volume's mount is not a plain path"); |
| 72 | const env = `FORGE_URL=${url.origin}\nFORGE_GAME_TOKEN=${g.token}\n`; | |
| 65 | const env = `FORGE_URL=${url.origin}\nFORGE_GAME_TOKEN=${g.token}\nFORGE_GAME_DATA=${dataDir}\n`; | |
| 73 | 66 | const daemon = JSON.stringify({ "data-root": `${dataDir}/docker`, "log-driver": "local" }); |
| 74 | 67 | return `#cloud-config |
| 75 | 68 | ssh_pwauth: false |
| @@ -95,7 +88,7 @@ runcmd: | ||
| 95 | 88 | - ufw allow ${BEDROCK_PORT}/udp |
| 96 | 89 | - ufw --force enable |
| 97 | 90 | - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab |
| 98 | - ${yamlString(volumeWait(dataDir))} | |
| 91 | - ${yamlString(`bash ${GAME_DIR}/agent.sh --mount-volume`)} | |
| 99 | 92 | - mkdir -p ${dataDir}/docker |
| 100 | 93 | - ${yamlString(INSTALL)} |
| 101 | 94 | - systemctl restart docker || true |
src/games/diag.ts +32 −2
| @@ -16,7 +16,7 @@ export interface Diag { | ||
| 16 | 16 | readonly images?: readonly { readonly image?: string; readonly size?: string }[]; |
| 17 | 17 | readonly journal?: { readonly agent?: string; readonly docker?: string }; |
| 18 | 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 }; | |
| 19 | readonly disk?: { readonly root?: string; readonly dataRoot?: string; readonly volume?: string; readonly mountOfDataRoot?: string; readonly volumeMounted?: boolean; readonly onVolume?: boolean; readonly device?: string; readonly log?: string }; | |
| 20 | 20 | readonly versions?: { readonly docker?: string; readonly compose?: string }; |
| 21 | 21 | } |
| 22 | 22 | |
| @@ -58,6 +58,33 @@ export function boxStatusShared(d: Diag): string[] { | ||
| 58 | 58 | return out; |
| 59 | 59 | } |
| 60 | 60 | |
| 61 | /** | |
| 62 | * The raw tails a diag carries, each with its name, the empty ones left out: what an owner reads | |
| 63 | * under the plain lines, on /games/<box> and the terminal's box screen alike. The volume's names | |
| 64 | * its device and the last steps of `.volume.log` (format, mount, move). | |
| 65 | */ | |
| 66 | export function boxTails(d: Diag): [string, string][] { | |
| 67 | const disk = d.disk; | |
| 68 | return ( | |
| 69 | [ | |
| 70 | ["The job's output (.up.log)", d.upLog], | |
| 71 | ["Containers", (d.ps ?? []).map((c) => `${c.name} ${c.state} ${c.status} ${c.image}`).join("\n")], | |
| 72 | ["Images", (d.images ?? []).map((i) => `${i.image} ${i.size}`).join("\n")], | |
| 73 | ["The agent's journal", d.journal?.agent], | |
| 74 | ["Docker's journal", d.journal?.docker], | |
| 75 | ["cloud-init", d.cloudInit], | |
| 76 | ["Disks", [disk?.root, disk?.dataRoot ? `data-root ${disk.dataRoot} on ${disk.mountOfDataRoot || "?"}` : ""].filter(Boolean).join("\n")], | |
| 77 | [ | |
| 78 | "The volume (.volume.log)", | |
| 79 | (disk?.volume ?? "") === "" | |
| 80 | ? "" | |
| 81 | : `device ${disk?.device || "none attached"} · ${disk?.volumeMounted === true ? "mounted" : "not mounted"} at ${disk?.volume}${(disk?.log ?? "").trim() === "" ? "" : `\n${(disk?.log ?? "").trim()}`}`, | |
| 82 | ], | |
| 83 | ["Versions", d.versions ? `docker ${d.versions.docker ?? "?"} · compose ${d.versions.compose ?? "?"}` : ""], | |
| 84 | ] as [string, string | undefined][] | |
| 85 | ).filter((t): t is [string, string] => typeof t[1] === "string" && t[1] !== ""); | |
| 86 | } | |
| 87 | ||
| 61 | 88 | /** The plain lines a diag says, most telling first; none for a box that sent none. The owner's. */ |
| 62 | 89 | export function boxStatus(d: Diag): string[] { |
| 63 | 90 | const out: string[] = []; |
| @@ -75,7 +102,10 @@ export function boxStatus(d: Diag): string[] { | ||
| 75 | 102 | } |
| 76 | 103 | const disk = d.disk; |
| 77 | 104 | if (disk !== undefined && (disk.volume ?? "") !== "") { |
| 78 | if (disk.volumeMounted === false) out.push(`The volume is not mounted at ${disk.volume}`); | |
| 105 | // What the agent last did with the volume (format, mount, move), when it failed or refused. | |
| 106 | const last = (disk.log ?? "").trim().split("\n").at(-1)?.replace(/^\S+ /, "") ?? ""; | |
| 107 | if (/^(failed|refused):/.test(last)) out.push(`The volume: ${last}`); | |
| 108 | if (disk.volumeMounted === false) out.push(`The volume is not mounted at ${disk.volume}${disk.device ? "" : ": no volume device is attached"}`); | |
| 79 | 109 | else if (disk.onVolume === false) out.push("Docker's data is on the root disk, not the volume"); |
| 80 | 110 | } |
| 81 | 111 | const ps = d.ps ?? []; |
src/http/games_routes.ts +13
| @@ -4,6 +4,7 @@ | ||
| 4 | 4 | */ |
| 5 | 5 | |
| 6 | 6 | import { composeServices, readCompose } from "../games/compose.ts"; |
| 7 | import { AGENT_SH, AGENT_SHA } from "../games/boot.ts"; | |
| 7 | 8 | import { synced } from "../games/notify.ts"; |
| 8 | 9 | import { auditShellResults } from "../games/shell.ts"; |
| 9 | 10 | import { boxByToken, envFiles, recordSync, signJarUrls, type SyncBody } from "../games/store.ts"; |
| @@ -44,11 +45,23 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> { | ||
| 44 | 45 | commands, |
| 45 | 46 | }; |
| 46 | 47 | if (compose !== undefined && compose.sha !== (typeof body.composeSha === "string" ? body.composeSha : "")) reply["compose"] = signJarUrls(ctx.app, box, compose.text, ctx.url.origin); |
| 48 | // The agent this forge runs: a box whose own differs fetches it (`gameAgentScript`) and restarts. | |
| 49 | reply["agentSha"] = AGENT_SHA; | |
| 47 | 50 | return json(reply); |
| 48 | 51 | } |
| 49 | 52 | |
| 53 | // GET /api/v1/games/agent/script: the agent this forge runs, for a box that holds an older one. | |
| 54 | // The box's bearer token, as the sync; the box checks the sha the sync answered before running it. | |
| 55 | export function gameAgentScript(ctx: Ctx): Response { | |
| 56 | const auth = ctx.request.headers.get("authorization") ?? ""; | |
| 57 | const box = auth.startsWith("Bearer ") ? boxByToken(ctx.app.db, auth.slice(7).trim()) : undefined; | |
| 58 | if (box === undefined) return apiError("unauthorized", 401, "send the game box's token as the bearer"); | |
| 59 | return new Response(AGENT_SH, { headers: { "content-type": "text/x-shellscript; charset=utf-8", "cache-control": "no-store", "x-agent-sha": AGENT_SHA } }); | |
| 60 | } | |
| 61 | ||
| 50 | 62 | export function gamesApiRoutes(router: Router<Handler>): void { |
| 51 | 63 | router.add("POST", "/api/v1/games/agent/sync", gameAgentSync); |
| 64 | router.add("GET", "/api/v1/games/agent/script", gameAgentScript); | |
| 52 | 65 | } |
| 53 | 66 | |
| 54 | 67 | export function gamesRoutes(router: Router<Handler>): void { |
src/http/lazy_lists.ts +1
| @@ -1240,6 +1240,7 @@ export const API_ROUTES = [ | ||
| 1240 | 1240 | ["GET", "/api/v1/runner/jobs/:id/git/info/refs"], |
| 1241 | 1241 | ["POST", "/api/v1/runner/jobs/:id/git/git-upload-pack"], |
| 1242 | 1242 | ["POST", "/api/v1/games/agent/sync"], |
| 1243 | ["GET", "/api/v1/games/agent/script"], | |
| 1243 | 1244 | ["GET", "/api/v1/admin/maintenance"], |
| 1244 | 1245 | ["POST", "/api/v1/admin/maintenance/prepare"], |
| 1245 | 1246 | ["POST", "/api/v1/admin/maintenance/resume"], |
src/tui/screens/games.ts +48 −2
| @@ -7,14 +7,15 @@ | ||
| 7 | 7 | * plugins (`a` adds a Modrinth slug or a URL through `addPlugin`; uploading a jar is the page's |
| 8 | 8 | * alone); `c` opens its settings (server.properties and Paper's, as the page's Settings block: |
| 9 | 9 | * `enter` sets one, the preview shows on top, `y` commits it through `commitSettings`). `G` opens |
| 10 | * the box's grants, which an owner sets with `a` there, through `grant`. | |
| 10 | * the box's grants, which an owner sets with `a` there, through `grant`; `b` the box itself, as | |
| 11 | * /games/<box>'s Box block (its diagnosis, the volume's device and log among it). | |
| 11 | 12 | */ |
| 12 | 13 | |
| 13 | 14 | import { movedKey } from "./moved_key.ts"; |
| 14 | 15 | import { emptyText } from "../../core/empty_words.ts"; |
| 15 | 16 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 16 | 17 | import { onSync } from "../../games/notify.ts"; |
| 17 | import { boxStatus, boxStatusShared } from "../../games/diag.ts"; | |
| 18 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; | |
| 18 | 19 | import { getUserByName } from "../../core/users.ts"; |
| 19 | 20 | import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 20 | 21 | import { commitSettings, planSettings, settingsOf, type SettingsPlan, type SettingValue } from "../../games/settings.ts"; |
| @@ -59,6 +60,7 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 59 | 60 | binding(["enter"], "console, env, plugins"), |
| 60 | 61 | binding(["G"], "grants"), |
| 61 | 62 | binding(["!"], "console (the box's owner)"), |
| 63 | binding(["b"], "the box"), | |
| 62 | 64 | binding(["s"], "start"), |
| 63 | 65 | binding(["x"], "stop"), |
| 64 | 66 | binding(["r"], "restart"), |
| @@ -101,6 +103,10 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 101 | 103 | ctx.push(gameGrantsScreen(f, ctx, here.box)); |
| 102 | 104 | return true; |
| 103 | 105 | } |
| 106 | if (here !== undefined && !e.ctrl && !e.alt && e.key === "b") { | |
| 107 | ctx.push(gameBoxScreen(f, ctx, here.box)); | |
| 108 | return true; | |
| 109 | } | |
| 104 | 110 | if (state.key(e, all.length)) return true; |
| 105 | 111 | const at = all[state.index]; |
| 106 | 112 | if (at !== undefined && !e.ctrl && !e.alt && e.key === "enter") { |
| @@ -360,6 +366,46 @@ export function gameSettingsScreen(f: Session, ctx: Ctx, box: GameBox, service: | ||
| 360 | 366 | return screen; |
| 361 | 367 | } |
| 362 | 368 | |
| 369 | /** | |
| 370 | * A box itself, as /games/<box>'s Box block: its plain lines, then, for its owner, the raw tails of | |
| 371 | * its latest diagnosis (the job's output, containers, journals, disks, the volume's device and | |
| 372 | * `.volume.log`). Anyone else reads what it is doing and nothing inside it. `j`/`k` scroll. | |
| 373 | */ | |
| 374 | export function gameBoxScreen(f: Session, ctx: Ctx, box: GameBox): Screen { | |
| 375 | let top = 0; | |
| 376 | const lines = (): string[] => { | |
| 377 | const b = listBoxes(f.app.db).find((x) => x.id === box.id) ?? box; | |
| 378 | if (!mayDo(roleOn(f.app.db, f.user, b.id), "owner")) { | |
| 379 | const shared = boxStatusShared(b.diag); | |
| 380 | return shared.length === 0 ? ["The box has said nothing yet."] : shared; | |
| 381 | } | |
| 382 | const plain = boxStatus(b.diag); | |
| 383 | const tails = boxTails(b.diag); | |
| 384 | if (plain.length + tails.length === 0) return ["The box has sent no diagnosis yet: its agent sends one with every sync."]; | |
| 385 | return [...plain, ...tails.flatMap(([k, v]) => ["", `== ${k}`, ...v.split("\n")])]; | |
| 386 | }; | |
| 387 | return { | |
| 388 | title: `${box.name}: the box`, | |
| 389 | keys: [binding(["j", "k"], "scroll")], | |
| 390 | render(area, s) { | |
| 391 | const c = ctx.theme.c; | |
| 392 | const all = lines(); | |
| 393 | top = Math.max(0, Math.min(top, all.length - area.h)); | |
| 394 | all.slice(top, top + area.h).forEach((l, i) => | |
| 395 | s.text(area.x, area.y + i, truncate(l, area.w), style(l.startsWith("== ") ? c.mutedFg : c.fg, c.bg), area.x + area.w), | |
| 396 | ); | |
| 397 | }, | |
| 398 | key(e) { | |
| 399 | if (e.ctrl || e.alt) return false; | |
| 400 | if (e.key === "j" || e.key === "down") top++; | |
| 401 | else if (e.key === "k" || e.key === "up") top = Math.max(0, top - 1); | |
| 402 | else return false; | |
| 403 | ctx.invalidate(); | |
| 404 | return true; | |
| 405 | }, | |
| 406 | }; | |
| 407 | } | |
| 408 | ||
| 363 | 409 | /** A box's grants, as /games/<box> lists them; an owner sets one with `a` ("user role [service]"). */ |
| 364 | 410 | export function gameGrantsScreen(f: Session, ctx: Ctx, box: GameBox): Screen { |
| 365 | 411 | const state = new ListState(); |
src/web/pages/games.ts +2 −11
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; |
| 10 | 10 | import { SHELL_SERVICE, queueShell } from "../../games/shell.ts"; |
| 11 | import { boxStatus, boxStatusShared } from "../../games/diag.ts"; | |
| 11 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; | |
| 12 | 12 | import { commitSettings, planSettings, previewSettings, settingsOf, SETTINGS, type SettingValue, type SettingsPlan } from "../../games/settings.ts"; |
| 13 | 13 | import { |
| 14 | 14 | bootWords, |
| @@ -204,16 +204,7 @@ function sharedBoxBlock(box: GameBox): Html | null { | ||
| 204 | 204 | function boxBlock(box: GameBox): Html { |
| 205 | 205 | const d = box.diag; |
| 206 | 206 | const lines = boxStatus(d); |
| 207 | const raw = [ | |
| 208 | ["The job's output (.up.log)", d.upLog], | |
| 209 | ["Containers", (d.ps ?? []).map((c) => `${c.name} ${c.state} ${c.status} ${c.image}`).join("\n")], | |
| 210 | ["Images", (d.images ?? []).map((i) => `${i.image} ${i.size}`).join("\n")], | |
| 211 | ["The agent's journal", d.journal?.agent], | |
| 212 | ["Docker's journal", d.journal?.docker], | |
| 213 | ["cloud-init", d.cloudInit], | |
| 214 | ["Disks", [d.disk?.root, d.disk?.dataRoot ? `data-root ${d.disk.dataRoot} on ${d.disk.mountOfDataRoot || "?"}` : ""].filter(Boolean).join("\n")], | |
| 215 | ["Versions", d.versions ? `docker ${d.versions.docker ?? "?"} · compose ${d.versions.compose ?? "?"}` : ""], | |
| 216 | ].filter(([, v]) => typeof v === "string" && v !== "") as [string, string][]; | |
| 207 | const raw = boxTails(d); | |
| 217 | 208 | return html`<section class="settings-block"> |
| 218 | 209 | <h2>Box</h2> |
| 219 | 210 | ${lines.length === 0 && raw.length === 0 |
test/game-agent-update.test.ts added +142
| @@ -0,0 +1,142 @@ | ||
| 1 | /** | |
| 2 | * A game box takes a newer agent by itself (2026-12-01): the sync answers `agentSha`, the sha256 of | |
| 3 | * the agent this forge runs; an agent whose own differs fetches it from GET | |
| 4 | * /api/v1/games/agent/script with its token, checks the sha and the syntax, puts it in place and | |
| 5 | * exits for systemd to start it. A script whose sha is not the one answered never runs; one that | |
| 6 | * matches is never fetched. | |
| 7 | */ | |
| 8 | import { $ } from "bun"; | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { copyFileSync, mkdirSync, mkdtempSync, readFileSync } 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 { AGENT_SH, AGENT_SHA } from "../src/games/boot.ts"; | |
| 16 | import { createGameBox } from "../src/games/store.ts"; | |
| 17 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 18 | ||
| 19 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); | |
| 20 | const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"; | |
| 21 | const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null); | |
| 22 | const sha = (text: string) => new Bun.CryptoHasher("sha256").update(text).digest("hex"); | |
| 23 | ||
| 24 | describe("the agent", () => { | |
| 25 | /** A box running a copy of the agent against a forge that answers `want` and serves `served`. */ | |
| 26 | async function box(want: string, served: string) { | |
| 27 | const root = mkdtempSync(join(tmpdir(), "forge-game-update-")); | |
| 28 | mkdirSync(join(root, "game")); | |
| 29 | const self = join(root, "agent.sh"); | |
| 30 | copyFileSync(AGENT, self); | |
| 31 | const asked: string[] = []; | |
| 32 | const forge = Bun.serve({ | |
| 33 | port: 0, | |
| 34 | hostname: "127.0.0.1", | |
| 35 | async fetch(req) { | |
| 36 | const path = new URL(req.url).pathname; | |
| 37 | asked.push(`${req.method} ${path} ${req.headers.get("authorization") ?? ""}`); | |
| 38 | if (path === "/api/v1/games/agent/script") return new Response(served); | |
| 39 | return Response.json({ composeSha: "", commands: [], agentSha: want }); | |
| 40 | }, | |
| 41 | }); | |
| 42 | // The agent once, as systemd would start it: its exit code and what it said on stderr. | |
| 43 | const run = async () => { | |
| 44 | const ran = await $`bash ${self}` | |
| 45 | .env({ | |
| 46 | PATH: process.env["PATH"] ?? "", | |
| 47 | HOME: root, | |
| 48 | FORGE_URL: `http://127.0.0.1:${String(forge.port)}`, | |
| 49 | FORGE_GAME_TOKEN: TOKEN, | |
| 50 | FORGE_GAME_DIR: join(root, "game"), | |
| 51 | FORGE_GAME_DOCKER: "true", | |
| 52 | FORGE_GAME_ONCE: "1", | |
| 53 | FORGE_GAME_DIAG_S: "0", | |
| 54 | FORGE_GAME_VOLUME_CHECK: "0", | |
| 55 | }) | |
| 56 | .quiet() | |
| 57 | .nothrow(); | |
| 58 | return { code: ran.exitCode, said: ran.stderr.toString() }; | |
| 59 | }; | |
| 60 | const done = async () => { | |
| 61 | forge.stop(true); | |
| 62 | await rm(root, { recursive: true, force: true }); | |
| 63 | }; | |
| 64 | return { self, asked, run, done }; | |
| 65 | } | |
| 66 | ||
| 67 | test.skipIf(lacks.length > 0)( | |
| 68 | "a newer agent is fetched with its token, checked, put in place, and the agent exits for systemd", | |
| 69 | async () => { | |
| 70 | const next = `${AGENT_SH}\n# a newer agent\n`; | |
| 71 | const b = await box(sha(next), next); | |
| 72 | try { | |
| 73 | const { code, said } = await b.run(); | |
| 74 | expect(code).toBe(0); | |
| 75 | expect(said).toContain(`updated to ${sha(next)}; exiting so systemd starts it`); | |
| 76 | expect(readFileSync(b.self, "utf8")).toBe(next); | |
| 77 | expect(b.asked).toContain(`GET /api/v1/games/agent/script Bearer ${TOKEN}`); | |
| 78 | } finally { | |
| 79 | await b.done(); | |
| 80 | } | |
| 81 | }, | |
| 82 | ); | |
| 83 | ||
| 84 | test.skipIf(lacks.length > 0)("a fetched script whose sha is not the one answered is refused and never runs", async () => { | |
| 85 | const promised = `${AGENT_SH}\n# what the sync promised\n`; | |
| 86 | const b = await box(sha(promised), `${AGENT_SH}\n# something else\n`); | |
| 87 | try { | |
| 88 | const { code, said } = await b.run(); | |
| 89 | expect(code).toBe(0); | |
| 90 | expect(said).toContain("refused the fetched agent"); | |
| 91 | expect(readFileSync(b.self, "utf8")).toBe(AGENT_SH); | |
| 92 | } finally { | |
| 93 | await b.done(); | |
| 94 | } | |
| 95 | }); | |
| 96 | ||
| 97 | test.skipIf(lacks.length > 0)("an agent already current fetches nothing", async () => { | |
| 98 | const b = await box(AGENT_SHA, "never served"); | |
| 99 | try { | |
| 100 | expect((await b.run()).code).toBe(0); | |
| 101 | expect(b.asked.some((a) => a.includes("/agent/script"))).toBe(false); | |
| 102 | } finally { | |
| 103 | await b.done(); | |
| 104 | } | |
| 105 | }); | |
| 106 | }); | |
| 107 | ||
| 108 | describe("the forge", () => { | |
| 109 | let dir = ""; | |
| 110 | let app: App; | |
| 111 | let servers: Servers; | |
| 112 | let token = ""; | |
| 113 | ||
| 114 | beforeAll(async () => { | |
| 115 | dir = mkdtempSync(join(tmpdir(), "forge-game-script-")); | |
| 116 | app = createApp({ dataDir: dir, port: 0 }); | |
| 117 | servers = await serve(app); | |
| 118 | token = createGameBox(app.db, { name: "mc" }).token; | |
| 119 | }); | |
| 120 | afterAll(async () => { | |
| 121 | servers.stop(); | |
| 122 | app.close(); | |
| 123 | await rm(dir, { recursive: true, force: true }); | |
| 124 | }); | |
| 125 | ||
| 126 | test("the sync answers the agent's sha, and the script route serves it to a box's token alone", async () => { | |
| 127 | const synced = (await ( | |
| 128 | await fetch(`${servers.url}/api/v1/games/agent/sync`, { | |
| 129 | method: "POST", | |
| 130 | headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, | |
| 131 | body: "{}", | |
| 132 | }) | |
| 133 | ).json()) as { agentSha: string }; | |
| 134 | expect(synced.agentSha).toBe(AGENT_SHA); | |
| 135 | expect(AGENT_SHA).toBe(sha(AGENT_SH)); | |
| 136 | const script = await fetch(`${servers.url}/api/v1/games/agent/script`, { headers: { authorization: `Bearer ${token}` } }); | |
| 137 | expect(script.status).toBe(200); | |
| 138 | expect(await script.text()).toBe(AGENT_SH); | |
| 139 | expect(script.headers.get("x-agent-sha")).toBe(AGENT_SHA); | |
| 140 | expect((await fetch(`${servers.url}/api/v1/games/agent/script`, { headers: { authorization: "Bearer fgb_wrong" } })).status).toBe(401); | |
| 141 | }); | |
| 142 | }); |
test/game-box.test.ts +5 −4
| @@ -49,9 +49,10 @@ 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 | // The box mounts its own volume (formatting it only when blank) before Docker is installed. | |
| 53 | expect(at("agent.sh --mount-volume")).toBeGreaterThan(-1); | |
| 54 | expect(at("agent.sh --mount-volume")).toBeLessThan(at("DPkg::Lock::Timeout=600")); | |
| 55 | expect(cfg).toContain("FORGE_GAME_DATA=/mnt/forge_box_data"); | |
| 55 | 56 | }); |
| 56 | 57 | |
| 57 | 58 | test("opens only the game's ports, Java and Bedrock: no SSH, no backend, no web", () => { |
| @@ -64,7 +65,7 @@ describe("the boot config", () => { | ||
| 64 | 65 | test("the token is in the env file alone, mode 600", () => { |
| 65 | 66 | expect(cfg.split(TOKEN)).toHaveLength(2); |
| 66 | 67 | expect(cfg).toContain( |
| 67 | `path: /opt/forge-game/agent.env\n permissions: "0600"\n content: "FORGE_URL=https://forge.example\\nFORGE_GAME_TOKEN=${TOKEN}\\n"`, | |
| 68 | `path: /opt/forge-game/agent.env\n permissions: "0600"\n content: "FORGE_URL=https://forge.example\\nFORGE_GAME_TOKEN=${TOKEN}\\nFORGE_GAME_DATA=/mnt/forge_box_data\\n"`, | |
| 68 | 69 | ); |
| 69 | 70 | expect(AGENT_SH).not.toContain("forge_game_a"); |
| 70 | 71 | }); |
test/game-diag.test.ts +33 −6
| @@ -19,7 +19,7 @@ import { DIAG_MOST, boxStatus, boxStatusShared, keptDiag } from "../src/games/di | ||
| 19 | 19 | import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts"; |
| 20 | 20 | import { serve, type Servers } from "../src/http/server.ts"; |
| 21 | 21 | import { createForgeApp } from "../src/tui/forge.ts"; |
| 22 | import { gamesScreen } from "../src/tui/screens/games.ts"; | |
| 22 | import { gameBoxScreen, gamesScreen } from "../src/tui/screens/games.ts"; | |
| 23 | 23 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; |
| 24 | 24 | import { quietLogs } from "./helpers/globals.ts"; |
| 25 | 25 | import { mcpTool } from "./helpers/mcp.ts"; |
| @@ -216,8 +216,13 @@ describe("the diag in words", () => { | ||
| 216 | 216 | "Docker's data is on the root disk, not the volume", |
| 217 | 217 | ]); |
| 218 | 218 | expect(boxStatus({ disk: { volume: "/mnt/mc_data", volumeMounted: false, onVolume: false } })).toEqual([ |
| 219 | "The volume is not mounted at /mnt/mc_data", | |
| 219 | "The volume is not mounted at /mnt/mc_data: no volume device is attached", | |
| 220 | 220 | ]); |
| 221 | // What the agent last did with the volume, when it refused or failed, comes first. | |
| 222 | const refused = "refused: the volume already holds data; nothing was copied, the data stays on the root disk"; | |
| 223 | const device = "/dev/disk/by-id/scsi-0DO_Volume_forge-mc-data"; | |
| 224 | const log = `2026-12-01T20:00:00Z moving /mnt/mc_data\n2026-12-01T20:00:01Z ${refused}`; | |
| 225 | expect(boxStatus({ disk: { volume: "/mnt/mc_data", volumeMounted: false, onVolume: false, device, log } })).toEqual([`The volume: ${refused}`, "The volume is not mounted at /mnt/mc_data"]); | |
| 221 | 226 | expect(boxStatus({ disk: { root: "Filesystem Size Used Avail Use% Mounted on\n/dev/vda1 25G 23G 2G 92% /\n" } })).toEqual([ |
| 222 | 227 | "The root disk is 92% full", |
| 223 | 228 | ]); |
| @@ -295,7 +300,14 @@ describe("the doors", () => { | ||
| 295 | 300 | { name: "hub", state: "running", status: "Up", image: "itzg/nope" }, |
| 296 | 301 | { name: "lobby", state: "exited", status: "Exited (1)", image: "itzg/nope" }, |
| 297 | 302 | ], |
| 298 | disk: { volume: "/mnt/mc_data", volumeMounted: true, onVolume: false, root: "/dev/vda1 25G 5G 20G 20% /" }, | |
| 303 | disk: { | |
| 304 | volume: "/mnt/mc_data", | |
| 305 | volumeMounted: true, | |
| 306 | onVolume: false, | |
| 307 | root: "/dev/vda1 25G 5G 20G 20% /", | |
| 308 | device: "/dev/disk/by-id/scsi-0DO_Volume_mc-data", | |
| 309 | log: "2026-12-01T17:40:02Z mounted /dev/disk/by-id/scsi-0DO_Volume_mc-data at /mnt/mc_data\n", | |
| 310 | }, | |
| 299 | 311 | journal: { agent: "forge-game-agent: sync ok" }, |
| 300 | 312 | }, |
| 301 | 313 | }); |
| @@ -310,15 +322,16 @@ describe("the doors", () => { | ||
| 310 | 322 | |
| 311 | 323 | const pageAs = async (who: User) => |
| 312 | 324 | (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); | |
| 325 | const termAs = async (who: User, screen: "games" | "box" = "games") => { | |
| 326 | // The box screen is long: tall enough for its every tail. | |
| 327 | const terminal = headlessTerminal(140, screen === "games" ? 20 : 80); | |
| 315 | 328 | const { app: tui, session } = createForgeApp( |
| 316 | 329 | app, |
| 317 | 330 | { sshUsername: who.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: who }, |
| 318 | 331 | { terminal, exitHooks: false }, |
| 319 | 332 | ); |
| 320 | 333 | tui.start(); |
| 321 | tui.ctx.push(gamesScreen(session, tui.ctx)); | |
| 334 | tui.ctx.push(screen === "games" ? gamesScreen(session, tui.ctx) : gameBoxScreen(session, tui.ctx, boxNamed(app.db, "mc")!)); | |
| 322 | 335 | await settleApp(tui); |
| 323 | 336 | const text = tui.screen.toText(); |
| 324 | 337 | tui.stop?.(); |
| @@ -334,6 +347,20 @@ describe("the doors", () => { | ||
| 334 | 347 | expect(page).toContain("== The agent's journal"); |
| 335 | 348 | }); |
| 336 | 349 | |
| 350 | test("the volume's device and .volume.log: on the owner's page and terminal box screen, and nobody else's", async () => { | |
| 351 | const page = await pageAs(alice); | |
| 352 | expect(page).toContain("== The volume (.volume.log)\ndevice /dev/disk/by-id/scsi-0DO_Volume_mc-data · mounted at /mnt/mc_data"); | |
| 353 | expect(page).toContain("mounted /dev/disk/by-id/scsi-0DO_Volume_mc-data at /mnt/mc_data"); | |
| 354 | const term = await termAs(alice, "box"); | |
| 355 | expect(term).toContain("== The volume (.volume.log)"); | |
| 356 | expect(term).toContain("device /dev/disk/by-id/scsi-0DO_Volume_mc-data · mounted at /mnt/mc_data"); | |
| 357 | expect(term).toContain("2026-12-01T17:40:02Z mounted /dev/disk/by-id/scsi-0DO_Volume_mc-data at /mnt/mc_data"); | |
| 358 | expect(await pageAs(bob)).not.toContain("scsi-0DO_Volume"); | |
| 359 | const shared = await termAs(bob, "box"); | |
| 360 | expect(shared).toContain("1 of 2 running"); | |
| 361 | expect(shared).not.toContain("scsi-0DO_Volume"); | |
| 362 | }); | |
| 363 | ||
| 337 | 364 | test("a viewer of one service reads what the box is doing, and nothing inside it, at every door", async () => { |
| 338 | 365 | const page = await pageAs(bob); |
| 339 | 366 | expect(page).toContain("1 of 2 running"); |
test/game-volume.test.ts added +329
| @@ -0,0 +1,329 @@ | ||
| 1 | /** | |
| 2 | * A game box's data volume, as `agent.sh --mount-volume` handles it (#17264), run for real under | |
| 3 | * bash with every system tool stubbed on PATH: no root, no devices. A blank volume is formatted and | |
| 4 | * mounted; one with a signature but no filesystem is refused unformatted; a volume already holding | |
| 5 | * data is refused and the root disk's data is left alone; a move whose copy cannot run (no rsync, | |
| 6 | * rsync failing, compose not stopping) starts Docker again with the data in place; a move whose | |
| 7 | * final mount fails starts Docker again on the root disk and says so where diag reads it; a good | |
| 8 | * move mounts the volume, writes fstab once and drops the compose sha, all before Docker starts. | |
| 9 | * Whether the volume is mounted is read from the mount's source (by-id links resolved), not from | |
| 10 | * whether the directory is a mountpoint. | |
| 11 | * | |
| 12 | * The stubs keep the fake machine in a state directory: `mount` puts a link to the volume's | |
| 13 | * directory where the target was (keeping the target's own files aside, as a mount hides them), | |
| 14 | * `findmnt` answers from the mounts it recorded, `systemctl` keeps whether Docker is active. | |
| 15 | */ | |
| 16 | import { afterAll, afterEach, beforeAll, describe, expect, test } from "bun:test"; | |
| 17 | import { | |
| 18 | chmodSync, | |
| 19 | existsSync, | |
| 20 | lstatSync, | |
| 21 | mkdirSync, | |
| 22 | mkdtempSync, | |
| 23 | readFileSync, | |
| 24 | readlinkSync, | |
| 25 | realpathSync, | |
| 26 | symlinkSync, | |
| 27 | writeFileSync, | |
| 28 | } from "node:fs"; | |
| 29 | import { rm } from "node:fs/promises"; | |
| 30 | import { tmpdir } from "node:os"; | |
| 31 | import { join } from "node:path"; | |
| 32 | import { boxStatus } from "../src/games/diag.ts"; | |
| 33 | ||
| 34 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); | |
| 35 | const BASH = Bun.which("bash"); | |
| 36 | const REAL = [ | |
| 37 | "bash", | |
| 38 | "date", | |
| 39 | "tail", | |
| 40 | "mv", | |
| 41 | "mkdir", | |
| 42 | "ls", | |
| 43 | "grep", | |
| 44 | "sed", | |
| 45 | "head", | |
| 46 | "cut", | |
| 47 | "readlink", | |
| 48 | "rm", | |
| 49 | "cat", | |
| 50 | "tr", | |
| 51 | "sleep", | |
| 52 | "cp", | |
| 53 | "awk", | |
| 54 | "chmod", | |
| 55 | "touch", | |
| 56 | "ln", | |
| 57 | "wc", | |
| 58 | ]; | |
| 59 | const lacks = REAL.filter((t) => Bun.which(t) === null); | |
| 60 | ||
| 61 | const STUBS: Record<string, string> = { | |
| 62 | mount: `dev="$1"; tgt="$2" | |
| 63 | echo "mount $dev $tgt" >>"$STUB/calls" | |
| 64 | [ -f "$STUB/fail-mount" ] && grep -qxF "$tgt" "$STUB/fail-mount" && exit 32 | |
| 65 | key="$(printf %s "$tgt" | tr / _)" | |
| 66 | mkdir -p "$STUB/under" "$STUB/volume" | |
| 67 | [ -e "$tgt" ] && mv "$tgt" "$STUB/under/$key" | |
| 68 | ln -s "$STUB/volume" "$tgt" | |
| 69 | echo "$(readlink -f "$dev") $tgt" >>"$STUB/mounts"`, | |
| 70 | umount: `tgt="$1" | |
| 71 | echo "umount $tgt" >>"$STUB/calls" | |
| 72 | key="$(printf %s "$tgt" | tr / _)" | |
| 73 | rm -f "$tgt" | |
| 74 | [ -e "$STUB/under/$key" ] && mv "$STUB/under/$key" "$tgt" | |
| 75 | awk -v t="$tgt" '$2 != t' "$STUB/mounts" >"$STUB/mounts.next"; mv "$STUB/mounts.next" "$STUB/mounts"`, | |
| 76 | findmnt: `dir="\${@: -1}" | |
| 77 | src="$(awk -v t="$dir" '$2 == t { print $1 }' "$STUB/mounts" 2>/dev/null | tail -n 1)" | |
| 78 | echo "\${src:-/dev/root-disk}"`, | |
| 79 | mountpoint: `echo "mountpoint $*" >>"$STUB/calls"; exit 0`, | |
| 80 | "mkfs.ext4": `echo "mkfs.ext4 $*" >>"$STUB/calls"; echo ext4 >"$STUB/type"; echo 0f1e2d3c-volume >"$STUB/uuid"; mkdir -p "$STUB/volume"`, | |
| 81 | blkid: `case "$*" in *TYPE*) [ -f "$STUB/type" ] && cat "$STUB/type";; *UUID*) [ -f "$STUB/type" ] && cat "$STUB/uuid";; esac; exit 0`, | |
| 82 | wipefs: `[ -f "$STUB/sig" ] && printf 'DEVICE OFFSET TYPE UUID LABEL\\nsda 0x1fe dos\\n'; exit 0`, | |
| 83 | rsync: `echo "rsync $*" >>"$STUB/calls" | |
| 84 | [ -f "$STUB/rsync-fail" ] && exit 23 | |
| 85 | src="\${@: -2:1}"; dst="\${@: -1}" | |
| 86 | cp -R "$src." "$dst"`, | |
| 87 | systemctl: `echo "systemctl $* compose-sha=$([ -e "$FORGE_GAME_DIR/.compose-sha" ] && echo yes || echo no) data=$(readlink "$FORGE_GAME_DATA" >/dev/null && echo volume || echo root)" >>"$STUB/calls" | |
| 88 | case "$1" in | |
| 89 | is-active) [ -f "$STUB/docker-active" ];; | |
| 90 | stop) [ -f "$STUB/docker-stuck" ] || rm -f "$STUB/docker-active";; | |
| 91 | start) touch "$STUB/docker-active";; | |
| 92 | esac`, | |
| 93 | docker: `echo "docker $*" >>"$STUB/calls"; [ -f "$STUB/compose-fail" ] && exit 1; exit 0`, | |
| 94 | curl: `exit 0`, | |
| 95 | }; | |
| 96 | ||
| 97 | const made: string[] = []; | |
| 98 | afterEach(async () => { | |
| 99 | for (const d of made.splice(0)) await rm(d, { recursive: true, force: true }); | |
| 100 | }); | |
| 101 | ||
| 102 | // The stub PATH, made once: macOS checks a program the first time it runs, and paying that for | |
| 103 | // every stub in every test would cost a second a test. One PATH has rsync, the other has none. | |
| 104 | let bins = { with: "", without: "" }; | |
| 105 | beforeAll(() => { | |
| 106 | if (BASH === null || lacks.length > 0) return; | |
| 107 | const root = realpathSync(mkdtempSync(join(tmpdir(), "forge-game-volume-bin-"))); | |
| 108 | bins = { with: join(root, "with"), without: join(root, "without") }; | |
| 109 | for (const [bin, rsync] of [ | |
| 110 | [bins.with, true], | |
| 111 | [bins.without, false], | |
| 112 | ] as const) { | |
| 113 | mkdirSync(bin); | |
| 114 | for (const t of REAL) symlinkSync(Bun.which(t)!, join(bin, t)); | |
| 115 | for (const [name, body] of Object.entries(STUBS)) { | |
| 116 | if (name === "rsync" && !rsync) continue; | |
| 117 | writeFileSync(join(bin, name), `#!${BASH}\n${body}\n`); | |
| 118 | chmodSync(join(bin, name), 0o755); | |
| 119 | } | |
| 120 | // Each stub run once here, in a scratch state, so no test pays the first run. | |
| 121 | const scratch = join(root, `warm-${rsync ? "with" : "without"}`); | |
| 122 | mkdirSync(scratch); | |
| 123 | for (const name of Object.keys(STUBS)) | |
| 124 | if (name !== "rsync" || rsync) | |
| 125 | Bun.spawnSync([join(bin, name), "-n", "warm"], { env: { PATH: bin, STUB: scratch, FORGE_GAME_DIR: scratch, FORGE_GAME_DATA: scratch }, cwd: scratch }); | |
| 126 | } | |
| 127 | }); | |
| 128 | afterAll(async () => { | |
| 129 | if (bins.with !== "") await rm(join(bins.with, ".."), { recursive: true, force: true }); | |
| 130 | }); | |
| 131 | ||
| 132 | /** A fake box: its stub PATH, its state, its data directory and its volume (a by-id link to a device). */ | |
| 133 | function box(o: { data?: Record<string, string>; volume?: Record<string, string>; state?: string[]; rsync?: false } = {}) { | |
| 134 | const root = realpathSync(mkdtempSync(join(tmpdir(), "forge-game-volume-"))); | |
| 135 | made.push(root); | |
| 136 | const bin = o.rsync === false ? bins.without : bins.with; | |
| 137 | const st = join(root, "st"); | |
| 138 | const data = join(root, "data"); | |
| 139 | const game = join(root, "game"); | |
| 140 | for (const d of [st, game, join(root, "dev", "by-id")]) mkdirSync(d, { recursive: true }); | |
| 141 | writeFileSync(join(root, "dev", "sda"), ""); | |
| 142 | const dev = join(root, "dev", "by-id", "scsi-0DO_Volume_mc-data"); | |
| 143 | symlinkSync(join(root, "dev", "sda"), dev); | |
| 144 | if (o.data !== undefined) { | |
| 145 | mkdirSync(data, { recursive: true }); | |
| 146 | for (const [f, text] of Object.entries(o.data)) writeFileSync(join(data, f), text); | |
| 147 | } | |
| 148 | if (o.volume !== undefined) { | |
| 149 | writeFileSync(join(st, "type"), "ext4\n"); | |
| 150 | writeFileSync(join(st, "uuid"), "0f1e2d3c-volume\n"); | |
| 151 | mkdirSync(join(st, "volume")); | |
| 152 | for (const [f, text] of Object.entries(o.volume)) writeFileSync(join(st, "volume", f), text); | |
| 153 | } | |
| 154 | for (const f of o.state ?? []) writeFileSync(join(st, f.split("=")[0]!), f.includes("=") ? `${f.split("=")[1]}\n` : ""); | |
| 155 | writeFileSync(join(game, ".compose-sha"), "abc\n"); | |
| 156 | writeFileSync(join(game, "compose.yml"), "services: {}\n"); | |
| 157 | const env = { | |
| 158 | PATH: bin, | |
| 159 | HOME: root, | |
| 160 | STUB: st, | |
| 161 | FORGE_URL: "http://forge.invalid", | |
| 162 | FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG", | |
| 163 | FORGE_GAME_DIR: game, | |
| 164 | FORGE_GAME_DATA: data, | |
| 165 | FORGE_GAME_VOLUME: dev, | |
| 166 | FORGE_GAME_MOVE_DIR: join(root, "move"), | |
| 167 | FORGE_GAME_FSTAB: join(root, "fstab"), | |
| 168 | FORGE_GAME_SYSTEMD_DIR: join(root, "systemd"), | |
| 169 | FORGE_GAME_VOLUME_WAIT: "1", | |
| 170 | FORGE_GAME_DOCKER: join(bin, "docker"), | |
| 171 | }; | |
| 172 | const read = (p: string): string => (existsSync(p) ? readFileSync(p, "utf8") : ""); | |
| 173 | return { | |
| 174 | root, | |
| 175 | data, | |
| 176 | dev, | |
| 177 | sda: join(root, "dev", "sda"), | |
| 178 | run: () => { | |
| 179 | const r = Bun.spawnSync([BASH!, AGENT, "--mount-volume"], { env, cwd: root }); | |
| 180 | return { code: r.exitCode, err: r.stderr.toString() }; | |
| 181 | }, | |
| 182 | calls: () => read(join(st, "calls")).trim().split("\n").filter(Boolean), | |
| 183 | log: () => read(join(game, ".volume.log")), | |
| 184 | fstab: () => read(join(root, "fstab")), | |
| 185 | dropIn: () => read(join(root, "systemd", "docker.service.d", "forge-volume.conf")), | |
| 186 | mountedOnVolume: () => existsSync(data) && lstatSync(data).isSymbolicLink() && readlinkSync(data) === join(st, "volume"), | |
| 187 | file: (f: string) => read(join(data, f)), | |
| 188 | onVolume: (f: string) => read(join(st, "volume", f)), | |
| 189 | composeSha: () => existsSync(join(game, ".compose-sha")), | |
| 190 | state: (f: string) => existsSync(join(st, f)), | |
| 191 | }; | |
| 192 | } | |
| 193 | ||
| 194 | const FSTAB_LINE = (dir: string) => `UUID=0f1e2d3c-volume ${dir} ext4 defaults,nofail,discard 0 2\n`; | |
| 195 | ||
| 196 | describe.skipIf(BASH === null || lacks.length > 0)("agent.sh --mount-volume", () => { | |
| 197 | test("a blank device is formatted, mounted at the data directory, kept in fstab, and Docker waits for it", () => { | |
| 198 | const b = box(); | |
| 199 | expect(b.run().code).toBe(0); | |
| 200 | expect(b.calls()).toContain(`mkfs.ext4 -q -L forge-data ${b.dev}`); | |
| 201 | expect(b.calls()).toContain(`mount ${b.dev} ${b.data}`); | |
| 202 | expect(b.mountedOnVolume()).toBe(true); | |
| 203 | expect(b.fstab()).toBe(FSTAB_LINE(b.data)); | |
| 204 | expect(b.dropIn()).toBe(`[Unit]\nRequiresMountsFor=${b.data}\n`); | |
| 205 | expect(b.log()).toContain(`mounted ${b.dev} at ${b.data}`); | |
| 206 | // The mountpoint test is gone: what holds the directory is read from the mount's source. | |
| 207 | expect(b.calls().some((c) => c.startsWith("mountpoint"))).toBe(false); | |
| 208 | }); | |
| 209 | ||
| 210 | test("a device with a signature but no filesystem is refused, never formatted, never mounted", () => { | |
| 211 | const b = box({ state: ["sig"] }); | |
| 212 | expect(b.run().code).toBe(0); | |
| 213 | expect(b.calls().some((c) => c.startsWith("mkfs"))).toBe(false); | |
| 214 | expect(b.calls().some((c) => c.startsWith("mount "))).toBe(false); | |
| 215 | expect(b.log()).toContain(`refused: ${b.dev} has a signature but no filesystem this box knows; nothing was formatted`); | |
| 216 | expect(b.fstab()).toBe(""); | |
| 217 | }); | |
| 218 | ||
| 219 | test("a volume that already holds data is refused: nothing is copied or stopped, and the root disk's data is as it was", () => { | |
| 220 | const b = box({ data: { "level.dat": "the root disk's world" }, volume: { "level.dat": "another world" }, state: ["docker-active"] }); | |
| 221 | expect(b.run().code).toBe(0); | |
| 222 | expect(b.log()).toContain("refused: the volume already holds data; nothing was copied, the data stays on the root disk"); | |
| 223 | expect(b.file("level.dat")).toBe("the root disk's world"); | |
| 224 | expect(b.onVolume("level.dat")).toBe("another world"); | |
| 225 | expect(b.mountedOnVolume()).toBe(false); | |
| 226 | expect(b.calls().some((c) => c.startsWith("rsync") || c.startsWith("systemctl stop") || c.startsWith("mkfs"))).toBe(false); | |
| 227 | expect(b.state("docker-active")).toBe(true); | |
| 228 | expect(b.fstab()).toBe(""); | |
| 229 | }); | |
| 230 | ||
| 231 | test("with no rsync, nothing is stopped or copied and the data stays where it is", () => { | |
| 232 | const b = box({ data: { "level.dat": "world" }, state: ["docker-active"], rsync: false }); | |
| 233 | b.run(); | |
| 234 | expect(b.log()).toContain("failed: rsync is not installed; nothing was copied, the data stays on the root disk"); | |
| 235 | expect(b.file("level.dat")).toBe("world"); | |
| 236 | expect(b.mountedOnVolume()).toBe(false); | |
| 237 | expect(b.state("docker-active")).toBe(true); | |
| 238 | expect(b.calls().some((c) => c.startsWith("systemctl stop"))).toBe(false); | |
| 239 | }); | |
| 240 | ||
| 241 | test("when rsync fails, Docker starts again, the data stays in place and the volume is let go", () => { | |
| 242 | const b = box({ data: { "level.dat": "world" }, state: ["docker-active", "rsync-fail"] }); | |
| 243 | b.run(); | |
| 244 | expect(b.log()).toContain("failed: rsync exited 23; the data stays on the root disk, Docker started again"); | |
| 245 | expect(b.file("level.dat")).toBe("world"); | |
| 246 | expect(b.mountedOnVolume()).toBe(false); | |
| 247 | expect(b.state("docker-active")).toBe(true); | |
| 248 | expect(b.calls().at(-1)).toStartWith("systemctl start docker"); | |
| 249 | expect(b.fstab()).toBe(""); | |
| 250 | expect(b.composeSha()).toBe(true); | |
| 251 | }); | |
| 252 | ||
| 253 | test("when compose will not stop, nothing is copied and Docker is never stopped", () => { | |
| 254 | const b = box({ data: { "level.dat": "world" }, state: ["docker-active", "compose-fail"] }); | |
| 255 | b.run(); | |
| 256 | expect(b.log()).toContain("failed: compose would not stop; nothing was copied, the data stays on the root disk"); | |
| 257 | expect(b.calls().some((c) => c.startsWith("rsync") || c.startsWith("systemctl stop"))).toBe(false); | |
| 258 | expect(b.state("docker-active")).toBe(true); | |
| 259 | expect(b.file("level.dat")).toBe("world"); | |
| 260 | }); | |
| 261 | ||
| 262 | test("when Docker will not stop, nothing is copied", () => { | |
| 263 | const b = box({ data: { "level.dat": "world" }, state: ["docker-active", "docker-stuck"] }); | |
| 264 | b.run(); | |
| 265 | expect(b.log()).toContain("failed: Docker would not stop; nothing was copied, the data stays on the root disk"); | |
| 266 | expect(b.calls().some((c) => c.startsWith("rsync"))).toBe(false); | |
| 267 | expect(b.mountedOnVolume()).toBe(false); | |
| 268 | }); | |
| 269 | ||
| 270 | test("a move: the volume is mounted, in fstab once, Docker made to wait for it and the compose sha dropped, all before Docker starts", () => { | |
| 271 | const b = box({ data: { "level.dat": "world" }, state: ["docker-active"] }); | |
| 272 | b.run(); | |
| 273 | const calls = b.calls(); | |
| 274 | expect(calls).toContain( | |
| 275 | `docker compose -p game --project-directory ${join(b.root, "game")} -f ${join(b.root, "game", "compose.yml")} stop`, | |
| 276 | ); | |
| 277 | const stop = calls.findIndex((c) => c.startsWith("systemctl stop docker.socket docker")); | |
| 278 | const copy = calls.findIndex((c) => c.startsWith("rsync -aHAX --numeric-ids")); | |
| 279 | const mount = calls.indexOf(`mount ${b.dev} ${b.data}`); | |
| 280 | const start = calls.findIndex((c) => c.startsWith("systemctl start docker")); | |
| 281 | expect(stop).toBeGreaterThan(-1); | |
| 282 | expect(stop).toBeLessThan(copy); | |
| 283 | expect(copy).toBeLessThan(mount); | |
| 284 | expect(mount).toBeLessThan(start); | |
| 285 | // Docker starts on the volume, with the compose sha already gone. | |
| 286 | expect(calls[start]).toContain("compose-sha=no data=volume"); | |
| 287 | expect(b.mountedOnVolume()).toBe(true); | |
| 288 | expect(b.file("level.dat")).toBe("world"); | |
| 289 | expect(b.fstab()).toBe(FSTAB_LINE(b.data)); | |
| 290 | expect(b.dropIn()).toContain(`RequiresMountsFor=${b.data}`); | |
| 291 | expect(b.log()).toContain("moved: "); | |
| 292 | // Again: the volume is recognised by its source, and fstab keeps one line. | |
| 293 | b.run(); | |
| 294 | expect(b.log()).toContain(`the volume is mounted at ${b.data}`); | |
| 295 | expect(b.fstab()).toBe(FSTAB_LINE(b.data)); | |
| 296 | }); | |
| 297 | ||
| 298 | test("when the final mount fails, Docker starts again on the root disk and says so where diag reads it", () => { | |
| 299 | const b = box({ data: { "level.dat": "world" }, state: ["docker-active"] }); | |
| 300 | writeFileSync(join(b.root, "st", "fail-mount"), `${b.data}\n`); | |
| 301 | b.run(); | |
| 302 | const said = `failed: mount ${b.dev} ${b.data} after the copy; Docker started again on the root disk's data, and the volume's copy is not used`; | |
| 303 | expect(b.log()).toContain(said); | |
| 304 | expect(b.file("level.dat")).toBe("world"); | |
| 305 | expect(b.mountedOnVolume()).toBe(false); | |
| 306 | expect(b.state("docker-active")).toBe(true); | |
| 307 | expect(b.calls().at(-1)).toContain("data=root"); | |
| 308 | expect(b.fstab()).toBe(""); | |
| 309 | expect(b.dropIn()).toBe(""); | |
| 310 | // diag carries the log's tail as disk.log; the box's status names the failure. | |
| 311 | expect(boxStatus({ disk: { volume: b.data, volumeMounted: false, device: b.dev, log: b.log() } })).toContain(`The volume: ${said}`); | |
| 312 | }); | |
| 313 | ||
| 314 | test("mounted means the volume is the mount's source: a by-id link to it is, another device at the directory is not", () => { | |
| 315 | const mine = box(); | |
| 316 | mkdirSync(mine.data); | |
| 317 | writeFileSync(join(mine.root, "st", "mounts"), `${mine.sda} ${mine.data}\n`); | |
| 318 | writeFileSync(join(mine.root, "st", "type"), "ext4\n"); | |
| 319 | mine.run(); | |
| 320 | expect(mine.log()).toContain(`the volume is mounted at ${mine.data}`); | |
| 321 | expect(mine.calls().some((c) => c.startsWith("mount ") || c.startsWith("mkfs"))).toBe(false); | |
| 322 | const other = box(); | |
| 323 | mkdirSync(other.data); | |
| 324 | writeFileSync(join(other.root, "st", "mounts"), `/dev/vdb ${other.data}\n`); | |
| 325 | other.run(); | |
| 326 | expect(other.log()).not.toContain("the volume is mounted at"); | |
| 327 | expect(other.calls()).toContain(`mount ${other.dev} ${other.data}`); | |
| 328 | }); | |
| 329 | }); |
new above
offline
mountpoint -qaccepts any mount at$dir. Check that the source is$devbefore reporting the volume mounted.