Public: anyone can read this; the crew can change it.

Game box: a new agent that does not check in is replaced by the one before (#18019) #18054

opened this

Merged 12h 54m ago, live in production

sold/agent-rollback → main 0 commits 1 thread · 1 unresolved

  • Merged. sold/agent-rollback was merged into main as d6960b3.

Review

Sign in to review this change.
4 files changed +195 −2
docs/features/games.md +1 −1
@@ -144,7 +144,7 @@ If the page says the proxy is left as it is:
144144
145145 The other servers come up as usual meanwhile. An address for a jar runs out after 6 hours; each full sync brings a new one, and the next try uses it.
146146
147 If the page says that no change reaches the box until its agent updates, wait: nothing is lost. The agent updates itself when it syncs, and the box then takes the newest commit.
147 If the page says that no change reaches the box until its agent updates, wait: nothing is lost. The agent updates itself when it syncs, and the box then takes the newest commit. The agent it replaced stays beside the new one until the new one has completed a sync: a new agent that completes none within 3 minutes, or exits 3 times within 10, is replaced by the old one, and the box's page says "agent update rolled back" and why. That update is not tried again until the forge answers a different agent.
148148
149149 The forge's AutoStopper takes the place of the one from Modrinth in the same commit, and sleep changes leave that one out while ours is there.
150150
src/games/agent.sh +56 −1
@@ -314,11 +314,59 @@ fi
314314 # starts the new one. A script whose sha is not the one answered never runs. ----
315315
316316 SELF="${FORGE_GAME_SELF:-${BASH_SOURCE[0]}}"
317
318 # A new agent is on trial (#18019). self_update keeps the script it replaces as `$SELF.prev` and writes
319 # `.trial` ("<epoch> <new sha>"). The new agent puts the old one back, and exits so systemd starts it,
320 # when it has not completed one full sync within TRIAL_S (3 minutes) of the update, or when it has
321 # exited TRIAL_EXITS times (3) within TRIAL_WINDOW (10 minutes). The old one says so in its diag
322 # (`rolledBack`) and does not try that sha again until the forge answers a different one.
323 TRIAL="$DIR/.trial"
324 TRIAL_STARTS="$DIR/.trial.starts"
325 ROLLED="$DIR/.rolled-back"
326 TRIAL_S="${FORGE_GAME_TRIAL_S:-180}"
327 TRIAL_WINDOW="${FORGE_GAME_TRIAL_WINDOW:-600}"
328 TRIAL_EXITS="${FORGE_GAME_TRIAL_EXITS:-3}"
329 trial_rollback() {
330 local why="$1" sha
331 sha="$(cut -d' ' -f2 "$TRIAL" 2>/dev/null)"
332 if [ -s "$SELF.prev" ] && bash -n "$SELF.prev" 2>/dev/null && mv -f "$SELF.prev" "$SELF"; then
333 printf '%s\n%s\n' "$sha" "agent update rolled back: $why" >"$ROLLED"
334 rm -f "$TRIAL" "$TRIAL_STARTS"
335 echo "forge-game-agent: agent update rolled back: $why; exiting so systemd starts the old one" >&2
336 exit 0
337 fi
338 # Nothing usable to go back to: stay, and stop judging.
339 rm -f "$TRIAL" "$TRIAL_STARTS"
340 }
341 trial_late() {
342 local t0
343 [ -f "$TRIAL" ] || return 0
344 read -r t0 _ <"$TRIAL"
345 [[ "$t0" =~ ^[0-9]+$ ]] || return 0
346 [ $(($(date +%s) - t0)) -lt "$TRIAL_S" ] || trial_rollback "the new agent completed no sync within ${TRIAL_S} s"
347 }
348 trial_start() {
349 local n now t
350 [ -f "$TRIAL" ] || return 0
351 [ "$(sha256sum "$SELF" 2>/dev/null | cut -d' ' -f1)" = "$(cut -d' ' -f2 "$TRIAL")" ] || return 0
352 now="$(date +%s)"
353 echo "$now" >>"$TRIAL_STARTS"
354 n=0
355 while read -r t; do if [[ "$t" =~ ^[0-9]+$ ]] && [ $((now - t)) -le "$TRIAL_WINDOW" ]; then n=$((n + 1)); fi; done <"$TRIAL_STARTS"
356 # The first start follows the update's own exit; each later one follows a failure.
357 [ $((n - 1)) -lt "$TRIAL_EXITS" ] || trial_rollback "the new agent exited $((n - 1)) times within ${TRIAL_WINDOW} s"
358 trial_late
359 }
360 [ "${1:-}" = "--boot-report" ] || trial_start
361
317362 self_update() {
318363 local want="$1" have next got
319364 [[ "$want" =~ ^[0-9a-f]{64}$ ]] || return 0
320365 have="$(sha256sum "$SELF" 2>/dev/null | cut -d' ' -f1)"
366 # A sha the forge answers that is not the one put back ends the refusal.
367 if [ -f "$ROLLED" ] && [ "$(head -n 1 "$ROLLED")" != "$want" ]; then rm -f "$ROLLED"; fi
321368 [ "$have" = "$want" ] && return 0
369 [ -f "$ROLLED" ] && return 0
322370 next="$SELF.next"
323371 curl -fsS -m 30 -H "@$AUTH" "${FORGE_URL%/}/api/v1/games/agent/script" -o "$next" || { echo "forge-game-agent: the new agent could not be fetched" >&2; return 0; }
324372 got="$(sha256sum "$next" | cut -d' ' -f1)"
@@ -327,6 +375,9 @@ self_update() {
327375 echo "forge-game-agent: refused the fetched agent: its sha is $got, the forge said $want" >&2
328376 return 0
329377 fi
378 cp -p "$SELF" "$SELF.prev" || { rm -f "$next"; echo "forge-game-agent: the agent could not be kept; not updating" >&2; return 0; }

This cp runs even while .trial exists. A second update then replaces the proven .prev with the unproven agent. Keep the existing .prev when .trial is present.

379 printf '%s %s\n' "$(date +%s)" "$want" >"$TRIAL"
380 rm -f "$TRIAL_STARTS"
330381 chmod 0755 "$next" && mv "$next" "$SELF"
331382 echo "forge-game-agent: updated to $want; exiting so systemd starts it" >&2
332383 exit 0
@@ -346,6 +397,7 @@ missing() {
346397 printf '%s' "${out# }"
347398 }
348399 while [ -n "$(missing)" ]; do
400 trial_late
349401 gone="$(missing)"
350402 echo "forge-game-agent: missing $gone; saying so and checking again in ${MISSING_EVERY}s" >&2
351403 case " $gone " in *" curl "*) ;; *) say_boot "missing $gone: $(boot_status)" ;; esac
@@ -1405,7 +1457,7 @@ sync() {
14051457 logs "$since" | json_or '{}' >"$DIR/.sync.logs"
14061458 between
14071459 host | json_or '{}' >"$DIR/.sync.host"
1408 bounded_diag | jq -c --argjson hold "$(held)" --argjson waits "$([ -f "$DIR/.jars.waits" ] && echo true || echo false)" '. + {hold: $hold} + (if $waits then {jarsWait: true} else {} end)' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
1460 bounded_diag | jq -c --argjson hold "$(held)" --argjson waits "$([ -f "$DIR/.jars.waits" ] && echo true || echo false)" --arg back "$(sed -n 2p "$ROLLED" 2>/dev/null)" '. + {hold: $hold} + (if $waits then {jarsWait: true} else {} end) + (if $back == "" then {} else {rolledBack: $back} end)' 2>/dev/null | json_or '{}' >"$DIR/.sync.diag"
14091461 between
14101462 people | json_or '{}' >"$DIR/.sync.people"
14111463 between
@@ -1479,6 +1531,8 @@ sync() {
14791531 self_update "$(jq -r '.agentSha // ""' <<<"$answer")"
14801532 apply "$answer"
14811533 lend_apply "$answer"
1534 # One full sync answered: the new agent is proven.
1535 if [ -f "$TRIAL" ]; then rm -f "$TRIAL" "$TRIAL_STARTS" "$SELF.prev"; fi
14821536 }
14831537
14841538 # ---- the box's firewall rules, beside ufw's: each is looked for and put first in its chain when it
@@ -1966,6 +2020,7 @@ if [ "${FORGE_GAME_VOLUME_CHECK:-1}" = 1 ] && [ -n "$(volume_device)" ] && [ -n
19662020 fi
19672021
19682022 while :; do
2023 trial_late
19692024 metadata_close
19702025 # The volume a held box waited for is there: systemd starts the agent again, which looks at it.
19712026 ! grep -q '^no-volume ' "$VOLUME_HOLD" 2>/dev/null || [ -z "$(volume_device)" ] || exit 0
src/games/diag.ts +3
@@ -24,6 +24,8 @@ export interface Diag {
2424 readonly hold?: Hold | null;
2525 /** The proxy's jars are on the box, and the proxy restarts for them when nobody is on. */
2626 readonly jarsWait?: boolean;
27 /** The agent put the previous script back after an update that did not check in, and says why (#18019). */
28 readonly rolledBack?: string;
2729 }
2830
2931 /** The last line of the agent's `up` that waits for the last player to leave (`agent.sh`, `up_job`). */
@@ -114,6 +116,7 @@ export function boxStatus(d: Diag): string[] {
114116 const out: string[] = [];
115117 const job = d.job ?? {};
116118 const log = d.upLog ?? "";
119 if (typeof d.rolledBack === "string" && d.rolledBack !== "") out.push(d.rolledBack.slice(0, 300));
117120 if (job.running === true) {
118121 const pulling = lastLine(log, /pull|download|extract|waiting/i);
119122 out.push(
test/game-agent-rollback.test.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * A game box's new agent is on trial (#18019): the agent it replaced stays beside it, and a new one
3 * that exits three times within ten minutes, or completes no sync within three minutes, is replaced by
4 * the old one, which says so in its next sync's diag and does not try that sha again.
5 */
6 import { $ } from "bun";
7 import { describe, expect, test } from "bun:test";
8 import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync } from "node:fs";
9 import { rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { boxStatus } from "../src/games/diag.ts";
13
14 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
15 const OLD = readFileSync(AGENT, "utf8");
16 const TOKEN = "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG";
17 const lacks = ["bash", "curl", "jq"].filter((t) => Bun.which(t) === null);
18 const sha = (text: string) => new Bun.CryptoHasher("sha256").update(text).digest("hex");
19 const GUARD = '[ "${1:-}" = "--boot-report" ] || trial_start\n';
20 /** The agent with one more line right after its trial guard: what a new agent that fails at runtime does. */
21 const failing = (line: string) => OLD.replace(GUARD, `${GUARD}${line}\n`);
22 const good = `${OLD}\n# a newer agent\n`;
23
24 async function box(initial: { want: string; served: string }) {
25 const root = mkdtempSync(join(tmpdir(), "forge-game-rollback-"));
26 mkdirSync(join(root, "game"));
27 const self = join(root, "agent.sh");
28 copyFileSync(AGENT, self);
29 const state = { ...initial, status: 200 };
30 const asked: string[] = [];
31 const diags: Record<string, unknown>[] = [];
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(path);
38 if (path === "/api/v1/games/agent/script") return new Response(state.served);
39 const body = (await req.json().catch(() => ({}))) as { diag?: Record<string, unknown> };
40 diags.push(body.diag ?? {});
41 if (state.status !== 200) return new Response("no", { status: state.status });
42 return Response.json({ composeSha: "", commands: [], agentSha: state.want });
43 },
44 });
45 const env = (more: Record<string, string>) => ({
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 ...more,
56 });
57 /** The agent once, as systemd would start it. */
58 const run = async (more: Record<string, string> = {}) => {
59 const ran = await $`bash ${self}`.env(env(more)).quiet().nothrow();
60 return { code: ran.exitCode, said: ran.stderr.toString() };
61 };
62 const text = () => readFileSync(self, "utf8");
63 const done = async () => {
64 forge.stop(true);
65 await rm(root, { recursive: true, force: true });
66 };
67 return { self, root, state, asked, diags, run, text, done };
68 }
69
70 describe("an agent update on trial", () => {
71 test.skipIf(lacks.length > 0)("a good update stays: its first answered sync ends the trial", async () => {
72 const b = await box({ want: sha(good), served: good });
73 try {
74 expect((await b.run()).said).toContain("updated to");
75 expect(readFileSync(`${b.self}.prev`, "utf8")).toBe(OLD);
76 expect(b.text()).toBe(good);
77 expect((await b.run()).code).toBe(0);
78 expect(b.text()).toBe(good);
79 expect(existsSync(`${b.self}.prev`)).toBe(false);
80 expect(existsSync(join(b.root, "game", ".trial"))).toBe(false);
81 expect(b.diags.at(-1)?.["rolledBack"]).toBeUndefined();
82 } finally {
83 await b.done();
84 }
85 });
86
87 test.skipIf(lacks.length > 0)("a new agent that exits three times is replaced by the old one, which says why and does not retry", async () => {
88 const bad = failing("exit 1");
89 const b = await box({ want: sha(bad), served: bad });
90 try {
91 expect((await b.run()).said).toContain("updated to");
92 for (let i = 0; i < 3; i++) expect((await b.run()).code).toBe(1);
93 const back = await b.run();
94 expect(back.code).toBe(0);
95 expect(back.said).toContain("agent update rolled back: the new agent exited 3 times within 600 s");
96 expect(b.text()).toBe(OLD);
97
98 // The old agent again: the forge still answers the bad sha; it is not fetched, and the diag says why.
99 const fetched = b.asked.filter((p) => p.endsWith("/agent/script")).length;
100 expect((await b.run()).code).toBe(0);
101 expect(b.asked.filter((p) => p.endsWith("/agent/script")).length).toBe(fetched);
102 expect(b.text()).toBe(OLD);
103 expect(b.diags.at(-1)?.["rolledBack"]).toContain("agent update rolled back");
104
105 // A different agentSha ends the refusal and is tried.
106 b.state.want = sha(good);
107 b.state.served = good;
108 expect((await b.run()).said).toContain("updated to");
109 expect(b.text()).toBe(good);
110 } finally {
111 await b.done();
112 }
113 });
114
115 test.skipIf(lacks.length > 0)("a new agent that completes no sync in time is replaced by the old one", async () => {
116 const b = await box({ want: sha(good), served: good });
117 try {
118 expect((await b.run()).said).toContain("updated to");
119 b.state.status = 500;
120 const late = await b.run({ FORGE_GAME_ONCE: "0", FORGE_GAME_EVERY: "1", FORGE_GAME_TRIAL_S: "2" });
121 expect(late.code).toBe(0);
122 expect(late.said).toContain("agent update rolled back: the new agent completed no sync within 2 s");
123 expect(b.text()).toBe(OLD);
124 } finally {
125 await b.done();
126 }
127 });
128 });
129
130 describe("the box's page", () => {
131 test("leads with why the agent was put back", () => {
132 expect(boxStatus({ rolledBack: "agent update rolled back: the new agent exited 3 times within 600 s" })[0]).toBe("agent update rolled back: the new agent exited 3 times within 600 s");
133 expect(boxStatus({})).toEqual([]);
134 });
135 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs