Public: anyone can read this; the crew can change it.
A game box says why it is up but not playing: installs wait out apt's lock, a missing tool is reported, the boot reports itself #17013
Check · Review · Land · Live done — Landed and live in production.
sold/game-boot → main 0 commits 4 threads · 4 unresolved
11 files
changed +288
−15
- docs/features/game-box.md
- src/core/migration-pins/20261201130000-game-box-boot.pin
- src/core/migrations/20261201130000-game-box-boot.ts
- src/games/agent.sh
- src/games/boot.ts
- src/games/store.ts
- src/generated/migrations.ts
- src/tui/screens/games.ts
- src/web/pages/games.ts
- test/game-boot.test.ts
- test/game-box.test.ts
docs/features/game-box.md +1
| @@ -14,6 +14,7 @@ experiment. | ||
| 14 | 14 | - **Plan one (agents):** `infra` with `{ action: "plan", want: { game: true, where: "digitalocean/main@digitalocean:nyc3:s-4vcpu-8gb", name?: "mc", repo?: "trevato/mc-network", host?: "mc.trevato.dev" } }`, then `apply` its id. The plan says "Start a 4 vCPU, 8 GB game box in New York running trevato/mc-network's compose file" and waits for the address and the DNS record, not for an https answer. The web and terminal doors are `/games` and the Games screen. |
| 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 | - **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: …". | |
| 17 | 18 | - **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. |
| 18 | 19 | - **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. |
| 19 | 20 |
src/core/migration-pins/20261201130000-game-box-boot.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | d0ea26cb82752c80ad233eed00d5048d7d6e12ad9fe3f67a4b255bbccea7a1b7 |
src/core/migrations/20261201130000-game-box-boot.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // A game box's word about its own boot (2026-12-01, box `mc` never synced): what the agent says when | |
| 2 | // a tool it needs is missing ("missing jq: …"), or the boot's own report of cloud-init's status, so | |
| 3 | // /games says why a box is up but not running its games. Empty once the agent syncs in full. | |
| 4 | // Additive: one column. | |
| 5 | export default ` | |
| 6 | ALTER TABLE game_box ADD COLUMN boot TEXT NOT NULL DEFAULT ''; | |
| 7 | `; |
src/games/agent.sh +50
| @@ -12,6 +12,15 @@ DIR="${FORGE_GAME_DIR:-/opt/forge-game}" | ||
| 12 | 12 | DOCKER="" |
| 13 | 13 | EVERY="" |
| 14 | 14 | ONCE="" |
| 15 | # How long the agent waits between word that a tool is missing. | |
| 16 | MISSING_EVERY="" | |
| 17 | # Run by the boot (`--boot-report`), it reads its own env file, as systemd does for the service. | |
| 18 | if [ -z "" ] && [ -r "/agent.env" ]; then | |
| 19 | set -a | |
| 20 | # shellcheck disable=SC1091 | |
| 21 | . "/agent.env" | |
| 22 | set +a | |
| 23 | fi | |
| 15 | 24 | : "" |
| 16 | 25 | : "" |
| 17 | 26 | |
| @@ -23,6 +32,47 @@ printf 'Authorization: Bearer %s\n' "$FORGE_GAME_TOKEN" >"$AUTH" | ||
| 23 | 32 | unset FORGE_GAME_TOKEN |
| 24 | 33 | |
| 25 | 34 | SAFE='^[A-Za-z0-9._-]{1,64}$' |
| 35 | ||
| 36 | # A string as JSON, by hand: before jq is there, the agent still says why it is not. | |
| 37 | json_str() { | |
| 38 | local s="" | |
| 39 | s="" | |
| 40 | s="" | |
| 41 | s="$(printf '%s' "" | tr '\n\t\r' ' ' | LC_ALL=C tr -cd '\040-\176')" | |
| 42 | printf '"%s"' "" | |
| 43 | } | |
| 44 | ||
| 45 | # What the boot said, condensed to a line: cloud-init's status and any error it kept. | |
| 46 | boot_status() { | |
| 47 | cloud-init status --long 2>/dev/null | grep -E '^(status|errors|recoverable_errors|detail):|^ - ' | head -12 | tr '\n' ' ' || true | |
| 48 | } | |
| 49 | ||
| 50 | # One word to the forge with a body built without jq; never fails the caller. | |
| 51 | say_boot() { | |
| 52 | curl -fsS -m 20 -H "@" -H 'content-type: application/json' \ | |
| 53 | --data-binary "{\"agent\":1,\"boot\":$(json_str "")}" "/api/v1/games/agent/sync" >/dev/null 2>&1 || true | |
| 54 | } | |
| 55 | ||
| 56 | # The boot's last step: say how it went, once, so a box whose agent cannot start still shows why. | |
| 57 | if [ "" = "--boot-report" ]; then | |
| 58 | say_boot "boot report: $(boot_status)" | |
| 59 | exit 0 | |
| 60 | fi | |
| 61 | ||
| 62 | # The tools the agent needs. Without curl it cannot say a word; without jq or docker it says which | |
| 63 | # is missing every 30 s (the forge shows "Box is up but missing jq: …") until they are there. | |
| 64 | missing() { | |
| 65 | local t out="" | |
| 66 | for t in curl jq ""; do command -v "" >/dev/null 2>&1 || out=" "; done | |
| 67 | printf '%s' "" | |
| 68 | } | |
| 69 | while [ -n "$(missing)" ]; do | |
| 70 | gone="$(missing)" | |
| 71 | echo "forge-game-agent: missing ; saying so and checking again in s" >&2 | |
| 72 | case " " in *" curl "*) ;; *) say_boot "missing : $(boot_status)" ;; esac | |
| 73 | [ "" = 1 ] && exit 0 | |
| 74 | sleep "" | |
| 75 | done | |
| 26 | 76 | # The project directory is the box's own, so compose reads the `.env` the forge writes beside it. |
| 27 | 77 | compose() { "" compose -p game --project-directory "" -f "/compose.yml" "$@"; } |
| 28 | 78 | now() { date -u +%Y-%m-%dT%H:%M:%SZ; } |
src/games/boot.ts +12 −11
| @@ -42,6 +42,15 @@ RestartSec=5 | ||
| 42 | 42 | WantedBy=multi-user.target |
| 43 | 43 | `; |
| 44 | 44 | |
| 45 | /** | |
| 46 | * What the box installs, in `runcmd` and not `packages:`: a first boot's unattended upgrade holds | |
| 47 | * apt's lock, and a `packages:` that fails leaves no Docker and no jq (box `mc`, 2026-12-01). Each | |
| 48 | * apt call waits up to ten minutes for the lock, and the whole is tried three times. No | |
| 49 | * `package_upgrade`: unattended-upgrades does that once the box is up. | |
| 50 | */ | |
| 51 | export const INSTALL = | |
| 52 | "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"; | |
| 53 | ||
| 45 | 54 | /** The cloud-config for a game box whose volume is mounted at `dataDir`. */ |
| 46 | 55 | export function gameBootConfig(g: GameBoot, dataDir: string): string { |
| 47 | 56 | const url = new URL(g.forgeUrl); |
| @@ -53,16 +62,6 @@ export function gameBootConfig(g: GameBoot, dataDir: string): string { | ||
| 53 | 62 | return `#cloud-config |
| 54 | 63 | ssh_pwauth: false |
| 55 | 64 | disable_root: true |
| 56 | package_update: true | |
| 57 | package_upgrade: true | |
| 58 | packages: | |
| 59 | - ufw | |
| 60 | - curl | |
| 61 | - jq | |
| 62 | - ca-certificates | |
| 63 | - unattended-upgrades | |
| 64 | - docker.io | |
| 65 | - docker-compose-v2 | |
| 66 | 65 | write_files: |
| 67 | 66 | - path: ${GAME_DIR}/agent.env |
| 68 | 67 | permissions: "0600" |
| @@ -84,8 +83,10 @@ runcmd: | ||
| 84 | 83 | - ufw --force enable |
| 85 | 84 | - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab |
| 86 | 85 | - mkdir -p ${dataDir}/docker |
| 87 | - systemctl restart docker | |
| 86 | - ${JSON.stringify(INSTALL)} | |
| 87 | - systemctl restart docker || true | |
| 88 | 88 | - systemctl daemon-reload |
| 89 | 89 | - systemctl enable --now forge-game-agent.service |
| 90 | - bash ${GAME_DIR}/agent.sh --boot-report | |
| 90 | 91 | `; |
| 91 | 92 | } |
src/games/store.ts +21 −1
| @@ -40,6 +40,8 @@ export interface GameBox { | ||
| 40 | 40 | readonly composeSha: string; |
| 41 | 41 | readonly seenAt: string; |
| 42 | 42 | readonly createdAt: string; |
| 43 | /** What the box last said about its boot ("missing jq: …", a boot report); empty once it syncs in full. */ | |
| 44 | readonly boot: string; | |
| 43 | 45 | } |
| 44 | 46 | |
| 45 | 47 | export interface GameService { |
| @@ -65,6 +67,7 @@ interface BoxRow { | ||
| 65 | 67 | compose_sha: string; |
| 66 | 68 | seen_at: string; |
| 67 | 69 | created_at: string; |
| 70 | boot: string; | |
| 68 | 71 | } |
| 69 | 72 | const toBox = (r: BoxRow): GameBox => { |
| 70 | 73 | let host: Record<string, number> = {}; |
| @@ -84,6 +87,7 @@ const toBox = (r: BoxRow): GameBox => { | ||
| 84 | 87 | composeSha: r.compose_sha, |
| 85 | 88 | seenAt: r.seen_at, |
| 86 | 89 | createdAt: r.created_at, |
| 90 | boot: r.boot, | |
| 87 | 91 | }; |
| 88 | 92 | }; |
| 89 | 93 | |
| @@ -156,6 +160,15 @@ export const servicesOf = (db: Database, boxId: string): GameService[] => | ||
| 156 | 160 | seenAt: r.seen_at, |
| 157 | 161 | })); |
| 158 | 162 | |
| 163 | /** A box's word about its boot as every door says it: "Box is up but missing jq: …". */ | |
| 164 | export const bootWords = (box: Pick<GameBox, "boot">): string => | |
| 165 | box.boot.startsWith("boot report:") | |
| 166 | ? `Box is up; setup says: ${/status:\s*(\S+)/.exec(box.boot)?.[1] ?? "nothing yet"}` | |
| 167 | : `Box is up but ${box.boot}`; | |
| 168 | ||
| 169 | /** Whether the box's word is trouble (a tool it lacks), the only word the terminal shows in the danger tone. */ | |
| 170 | export const bootTroubled = (box: Pick<GameBox, "boot">): boolean => box.boot.startsWith("missing"); | |
| 171 | ||
| 159 | 172 | /** The newest `limit` log lines of a service, oldest first, with the id of the last. */ |
| 160 | 173 | export function logsOf(db: Database, boxId: string, service: string, limit = 200, after = 0): { lines: string[]; last: number } { |
| 161 | 174 | const rows = db |
| @@ -396,6 +409,8 @@ export interface SyncBody { | ||
| 396 | 409 | readonly logs?: Record<string, unknown>; |
| 397 | 410 | readonly results?: readonly { id?: unknown; ok?: unknown; output?: unknown }[]; |
| 398 | 411 | readonly host?: Record<string, unknown>; |
| 412 | /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */ | |
| 413 | readonly boot?: string; | |
| 399 | 414 | } |
| 400 | 415 | |
| 401 | 416 | const str = (v: unknown, max = 200): string => (typeof v === "string" ? v.slice(0, max) : ""); |
| @@ -413,7 +428,12 @@ export function recordSync( | ||
| 413 | 428 | const host: Record<string, number> = {}; |
| 414 | 429 | for (const [k, v] of Object.entries(body.host ?? {})) |
| 415 | 430 | if (typeof v === "number" && Number.isFinite(v) && Object.keys(host).length < 16) host[k.slice(0, 40)] = v; |
| 416 | db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4 WHERE id = ?1").run( | |
| 431 | // A word about the boot (no services, no host) keeps what was known; a full sync clears it. | |
| 432 | if (typeof body.boot === "string") { | |
| 433 | db.query("UPDATE game_box SET seen_at = ?2, boot = ?3 WHERE id = ?1").run(box.id, at, str(body.boot, 2_000)); | |
| 434 | return; | |
| 435 | } | |
| 436 | db.query("UPDATE game_box SET seen_at = ?2, host_json = ?3, compose_sha = ?4, boot = '' WHERE id = ?1").run( | |
| 417 | 437 | box.id, |
| 418 | 438 | at, |
| 419 | 439 | JSON.stringify(host), |
src/generated/migrations.ts +2
| @@ -445,6 +445,7 @@ import m440 from "../core/migrations/20261201000000-games.ts"; | ||
| 445 | 445 | import m441 from "../core/migrations/20261201090000-app-vital-member.ts"; |
| 446 | 446 | import m442 from "../core/migrations/20261201120000-first-change-forge.ts"; |
| 447 | 447 | import m443 from "../core/migrations/20261201121000-repo-check-slots.ts"; |
| 448 | import m444 from "../core/migrations/20261201130000-game-box-boot.ts"; | |
| 448 | 449 | |
| 449 | 450 | /** Each migration file's name and its default export, in name order. */ |
| 450 | 451 | export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ |
| @@ -892,4 +893,5 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [ | ||
| 892 | 893 | ["20261201090000-app-vital-member.ts", m441], |
| 893 | 894 | ["20261201120000-first-change-forge.ts", m442], |
| 894 | 895 | ["20261201121000-repo-check-slots.ts", m443], |
| 896 | ["20261201130000-game-box-boot.ts", m444], | |
| 895 | 897 | ]; |
src/tui/screens/games.ts +6 −1
| @@ -13,6 +13,8 @@ import { getUserByName } from "../../core/users.ts"; | ||
| 13 | 13 | import { addPlugin, commitServiceEnv, pluginsOf, readCompose, serviceEnv } from "../../games/compose.ts"; |
| 14 | 14 | import { |
| 15 | 15 | SERVICE_NAME, |
| 16 | bootTroubled, | |
| 17 | bootWords, | |
| 16 | 18 | grant, |
| 17 | 19 | grantsOf, |
| 18 | 20 | listBoxes, |
| @@ -57,7 +59,10 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 57 | 59 | const c = ctx.theme.c; |
| 58 | 60 | const [head, list] = split(area, "v", [len(1), fill(1)]); |
| 59 | 61 | const all = rows(); |
| 60 | s.text(head!.x, head!.y, truncate(note !== "" ? note : all.length === 0 ? emptyText("gameServices") : "Each service of each game box you may see.", head!.w), style(c.mutedFg, c.bg), head!.x + head!.w); | |
| 62 | // A box that is up but not running its games says why, as /games does, before anything else. | |
| 63 | 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 | 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); | |
| 61 | 66 | const view: ListRow[] = all.map(({ box, service }) => ({ |
| 62 | 67 | title: `${box.name}/${service.name}`, |
| 63 | 68 | ...(service.state === "exited" ? { tone: "danger" as const } : {}), |
src/web/pages/games.ts +3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import { addPlugin, commitServiceEnv, composeServices, pluginsOf, readCompose, SECRET_KEY, serviceEnv } from "../../games/compose.ts"; |
| 10 | 10 | import { |
| 11 | bootWords, | |
| 11 | 12 | boxNamed, |
| 12 | 13 | COMMAND_KINDS, |
| 13 | 14 | commandOf, |
| @@ -81,6 +82,8 @@ export function gamesPage(ctx: Ctx): Response { | ||
| 81 | 82 | meta: html`${b.place || "no machine yet"} · ${dollars(b.monthlyCents)} a month · agent |
| 82 | 83 | ${b.seenAt === "" ? "never seen" : html`seen ${time(b.seenAt)}`} · host ${mib(b.host["memUsedMiB"])} of |
| 83 | 84 | ${mib(b.host["memMiB"])}`, |
| 85 | // The box's own word about its boot, until its agent syncs in full. | |
| 86 | ...(b.boot === "" ? {} : { facts: [{ label: "Boot", value: bootWords(b) }] }), | |
| 84 | 87 | }), |
| 85 | 88 | ), |
| 86 | 89 | )}`, |
test/game-boot.test.ts added +170
| @@ -0,0 +1,170 @@ | ||
| 1 | /** | |
| 2 | * A game box says why it is up but not running its games (box `mc`, 2026-12-01, booted and never | |
| 3 | * synced): the agent, missing jq or docker, still POSTs a hand-built `{"agent":1,"boot":"missing | |
| 4 | * jq: …"}` with curl; the boot's last step reports cloud-init's status the same way; the sync keeps | |
| 5 | * that word (a full sync clears it), and /games and the terminal's Games say "Box is up but …". | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { chmodSync, mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from "node:fs"; | |
| 9 | import { rm } from "node:fs/promises"; | |
| 10 | import { tmpdir } from "node:os"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createSession } from "../src/core/sessions.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { boxNamed, bootWords, createGameBox, recordSync } from "../src/games/store.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 18 | import { gamesScreen } from "../src/tui/screens/games.ts"; | |
| 19 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 20 | import { quietLogs } from "./helpers/globals.ts"; | |
| 21 | import { settleApp } from "./helpers/tui.ts"; | |
| 22 | ||
| 23 | quietLogs(); | |
| 24 | ||
| 25 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); | |
| 26 | const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG"; | |
| 27 | ||
| 28 | /** A PATH of only these tools (found where this machine keeps them), so the rest are missing. */ | |
| 29 | function pathOf(dir: string, tools: readonly string[], extra: Record<string, string> = {}): string { | |
| 30 | const bin = join(dir, "bin"); | |
| 31 | mkdirSync(bin, { recursive: true }); | |
| 32 | for (const t of tools) { | |
| 33 | const at = Bun.which(t); | |
| 34 | if (at !== null) symlinkSync(at, join(bin, t)); | |
| 35 | } | |
| 36 | for (const [name, body] of Object.entries(extra)) { | |
| 37 | writeFileSync(join(bin, name), body); | |
| 38 | chmodSync(join(bin, name), 0o755); | |
| 39 | } | |
| 40 | return bin; | |
| 41 | } | |
| 42 | ||
| 43 | /** A forge that keeps every body it is sent. */ | |
| 44 | function standIn(): { url: string; bodies: Record<string, unknown>[]; stop(): void } { | |
| 45 | const bodies: Record<string, unknown>[] = []; | |
| 46 | const server = Bun.serve({ | |
| 47 | port: 0, | |
| 48 | hostname: "127.0.0.1", | |
| 49 | async fetch(req) { | |
| 50 | bodies.push((await req.json()) as Record<string, unknown>); | |
| 51 | return Response.json({ composeSha: "", commands: [] }); | |
| 52 | }, | |
| 53 | }); | |
| 54 | return { url: `http://127.0.0.1:${String(server.port)}`, bodies, stop: () => server.stop(true) }; | |
| 55 | } | |
| 56 | ||
| 57 | const BASIC = ["bash", "curl", "tr", "grep", "head", "mkdir", "date", "cat", "printf"]; | |
| 58 | const lacks = ["bash", "curl"].filter((t) => Bun.which(t) === null); | |
| 59 | ||
| 60 | describe("the agent, missing a tool", () => { | |
| 61 | test.skipIf(lacks.length > 0)("without jq it still says so, in JSON it builds by hand, with the boot's status", async () => { | |
| 62 | const box = mkdtempSync(join(tmpdir(), "forge-game-boot-")); | |
| 63 | const forge = standIn(); | |
| 64 | try { | |
| 65 | // No jq; a docker; a cloud-init that says how the boot went, quotes and all. | |
| 66 | const bin = pathOf(box, BASIC, { | |
| 67 | docker: "#!/usr/bin/env bash\nexit 0\n", | |
| 68 | "cloud-init": "#!/usr/bin/env bash\nprintf 'status: error\\nerrors:\\n - \"package jq: apt lock held\"\\n'\n", | |
| 69 | }); | |
| 70 | const p = Bun.spawn(["bash", AGENT], { | |
| 71 | env: { | |
| 72 | PATH: bin, | |
| 73 | FORGE_URL: forge.url, | |
| 74 | FORGE_GAME_TOKEN: TOKEN, | |
| 75 | FORGE_GAME_DIR: join(box, "game"), | |
| 76 | FORGE_GAME_DOCKER: "docker", | |
| 77 | FORGE_GAME_ONCE: "1", | |
| 78 | }, | |
| 79 | stdout: "pipe", | |
| 80 | stderr: "pipe", | |
| 81 | }); | |
| 82 | expect(await p.exited).toBe(0); | |
| 83 | const said = await new Response(p.stderr).text(); | |
| 84 | expect(forge.bodies, `the agent said: ${said}`).toHaveLength(1); | |
| 85 | expect(forge.bodies[0]).toEqual({ agent: 1, boot: 'missing jq: status: error errors: - "package jq: apt lock held" ' }); | |
| 86 | expect(said).toContain("missing jq; saying so and checking again in 30s"); | |
| 87 | } finally { | |
| 88 | forge.stop(); | |
| 89 | await rm(box, { recursive: true, force: true }); | |
| 90 | } | |
| 91 | }); | |
| 92 | ||
| 93 | test.skipIf(lacks.length > 0)("--boot-report reads its env file and posts cloud-init's status once", async () => { | |
| 94 | const box = mkdtempSync(join(tmpdir(), "forge-game-report-")); | |
| 95 | const forge = standIn(); | |
| 96 | try { | |
| 97 | const dir = join(box, "game"); | |
| 98 | mkdirSync(dir, { recursive: true }); | |
| 99 | writeFileSync(join(dir, "agent.env"), `FORGE_URL=${forge.url}\nFORGE_GAME_TOKEN=${TOKEN}\n`, { mode: 0o600 }); | |
| 100 | const bin = pathOf(box, BASIC, { | |
| 101 | "cloud-init": "#!/usr/bin/env bash\nprintf 'status: running\\ndetail: DataSourceDigitalOcean\\n'\n", | |
| 102 | }); | |
| 103 | const p = Bun.spawn(["bash", AGENT, "--boot-report"], { env: { PATH: bin, FORGE_GAME_DIR: dir }, stdout: "pipe", stderr: "pipe" }); | |
| 104 | expect(await p.exited).toBe(0); | |
| 105 | expect(forge.bodies).toEqual([{ agent: 1, boot: "boot report: status: running detail: DataSourceDigitalOcean " }]); | |
| 106 | } finally { | |
| 107 | forge.stop(); | |
| 108 | await rm(box, { recursive: true, force: true }); | |
| 109 | } | |
| 110 | }); | |
| 111 | }); | |
| 112 | ||
| 113 | describe("on the forge", () => { | |
| 114 | let dir = ""; | |
| 115 | let app: App; | |
| 116 | let servers: Servers; | |
| 117 | let alice: User; | |
| 118 | ||
| 119 | beforeAll(async () => { | |
| 120 | dir = mkdtempSync(join(tmpdir(), "forge-game-boot-doors-")); | |
| 121 | app = createApp({ dataDir: dir, port: 0 }); | |
| 122 | servers = await serve(app); | |
| 123 | const made = await createUser(app.db, { | |
| 124 | origin: "seed", | |
| 125 | trusted: true, | |
| 126 | username: "alice", | |
| 127 | email: "[email protected]", | |
| 128 | password: "a-good-passphrase", | |
| 129 | adminIfFirst: true, | |
| 130 | }); | |
| 131 | if (!made.ok) throw new Error(made.error); | |
| 132 | alice = made.value; | |
| 133 | createGameBox(app.db, { name: "mc" }); | |
| 134 | }); | |
| 135 | afterAll(async () => { | |
| 136 | servers.stop(); | |
| 137 | app.close(); | |
| 138 | await rm(dir, { recursive: true, force: true }); | |
| 139 | }); | |
| 140 | ||
| 141 | test("a boot word is kept beside what was known, and a full sync clears it", () => { | |
| 142 | const box = () => boxNamed(app.db, "mc")!; | |
| 143 | recordSync(app.db, box(), { composeSha: "abc", host: { memMiB: 8000 } }); | |
| 144 | recordSync(app.db, box(), { boot: "missing jq: status: error" }); | |
| 145 | expect(box()).toMatchObject({ boot: "missing jq: status: error", composeSha: "abc", host: { memMiB: 8000 } }); | |
| 146 | expect(bootWords(box())).toBe("Box is up but missing jq: status: error"); | |
| 147 | expect(bootWords({ boot: "boot report: status: running detail: DataSourceDigitalOcean " })).toBe("Box is up; setup says: running"); | |
| 148 | recordSync(app.db, box(), { composeSha: "abc", host: { memMiB: 8000 } }); | |
| 149 | expect(box().boot).toBe(""); | |
| 150 | recordSync(app.db, box(), { boot: "missing jq docker: status: error" }); | |
| 151 | }); | |
| 152 | ||
| 153 | test("/games and the terminal's Games say the box is up but missing what it misses", async () => { | |
| 154 | const page = await ( | |
| 155 | await fetch(`${servers.url}/games`, { headers: { cookie: `forge_session=${createSession(app.db, alice.id).token}` } }) | |
| 156 | ).text(); | |
| 157 | expect(page).toContain("Box is up but missing jq docker: status: error"); | |
| 158 | const terminal = headlessTerminal(140, 20); | |
| 159 | const { app: tui, session } = createForgeApp( | |
| 160 | app, | |
| 161 | { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, | |
| 162 | { terminal, exitHooks: false }, | |
| 163 | ); | |
| 164 | tui.start(); | |
| 165 | tui.ctx.push(gamesScreen(session, tui.ctx)); | |
| 166 | await settleApp(tui); | |
| 167 | expect(tui.screen.toText()).toContain("mc: Box is up but missing jq docker: status: error"); | |
| 168 | tui.stop?.(); | |
| 169 | }); | |
| 170 | }); |
test/game-box.test.ts +15 −2
| @@ -17,7 +17,7 @@ import { readPlaces } from "../src/cloud/places_read.ts"; | ||
| 17 | 17 | import { bootConfig } from "../src/cloud/droplet.ts"; |
| 18 | 18 | import { insertPinned } from "../src/core/pinned.ts"; |
| 19 | 19 | import { createUser, type User } from "../src/core/users.ts"; |
| 20 | import { AGENT_SH, GAME_PORT, gameBootConfig } from "../src/games/boot.ts"; | |
| 20 | import { AGENT_SH, GAME_PORT, INSTALL, gameBootConfig } from "../src/games/boot.ts"; | |
| 21 | 21 | import { boxByToken, boxNamed, createGameBox, rotateGameBoxToken } from "../src/games/store.ts"; |
| 22 | 22 | import { sha256 } from "../src/kernel/hash.ts"; |
| 23 | 23 | |
| @@ -32,11 +32,24 @@ describe("the boot config", () => { | ||
| 32 | 32 | expect(cfg).toContain(`path: /opt/forge-game/agent.sh\n permissions: "0755"\n content: ${JSON.stringify(AGENT_SH)}`); |
| 33 | 33 | expect(cfg).toContain("path: /etc/systemd/system/forge-game-agent.service"); |
| 34 | 34 | expect(cfg).toContain("systemctl enable --now forge-game-agent.service"); |
| 35 | for (const pkg of ["docker.io", "docker-compose-v2", "jq", "curl", "ufw"]) expect(cfg).toContain(` - ${pkg}\n`); | |
| 35 | for (const pkg of ["docker.io", "docker-compose-v2", "jq", "curl", "ufw"]) expect(INSTALL).toContain(` ${pkg}`); | |
| 36 | 36 | expect(cfg).toContain('{\\"data-root\\":\\"/mnt/forge_box_data/docker\\"'); |
| 37 | 37 | expect(cfg).toContain("mkswap /swapfile"); |
| 38 | 38 | }); |
| 39 | 39 | |
| 40 | test("installs in runcmd, waiting out apt's lock, three tries, before the agent starts; reports the boot last", () => { | |
| 41 | // A first boot's unattended upgrade holds the lock: \`packages:\` failed and left no jq (box mc). | |
| 42 | expect(cfg).not.toContain("package_upgrade"); | |
| 43 | expect(cfg).not.toContain("packages:"); | |
| 44 | expect(INSTALL).toStartWith("for try in 1 2 3; do apt-get -o DPkg::Lock::Timeout=600 update && "); | |
| 45 | expect(INSTALL).toContain("apt-get -o DPkg::Lock::Timeout=600 install -y docker.io docker-compose-v2 jq"); | |
| 46 | const runcmd = cfg.slice(cfg.indexOf("runcmd:\n")).split("\n").filter((l) => l.startsWith(" - ")); | |
| 47 | const at = (needle: string) => runcmd.findIndex((l) => l.includes(needle)); | |
| 48 | expect(at("DPkg::Lock::Timeout=600")).toBeGreaterThan(-1); | |
| 49 | expect(at("DPkg::Lock::Timeout=600")).toBeLessThan(at("systemctl enable --now forge-game-agent.service")); | |
| 50 | expect(runcmd.at(-1)).toBe(" - bash /opt/forge-game/agent.sh --boot-report"); | |
| 51 | }); | |
| 52 | ||
| 40 | 53 | test("opens only the game's port: no SSH, no backend, no web", () => { |
| 41 | 54 | const allowed = cfg.split("\n").filter((l) => l.includes("ufw allow")); |
| 42 | 55 | expect(allowed).toEqual([` - ufw allow ${GAME_PORT}/tcp`]); |
new above
offline
Non-UTF-8 bytes from cloud-init output survive this and make the body invalid JSON, which the forge rejects, so the word is lost. Pipe through
iconv -c -t UTF-8(or tr -cd printable ASCII) before building the string.