Public: anyone can read this; the crew can change it.
The game agent puts the proxy's pinned jars in place before an up #17679
Merged 18h 37m ago, live in production
sold/game-jars → main 0 commits
2 files
changed +238
−0
src/games/agent.sh +86
| @@ -769,12 +769,97 @@ job_tick() { | ||
| 769 | 769 | # shellcheck disable=SC2086,SC2016 # the verb and its words, each a safe name; the script is single-quoted on purpose |
| 770 | 770 | if [ "" = world ]; then |
| 771 | 771 | DOCKER="" DIR="" bash -c 'world_job "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" & |
| 772 | elif [ "" = up ]; then | |
| 773 | DOCKER="" DIR="" bash -c 'up_job "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" & | |
| 772 | 774 | else |
| 773 | 775 | DIR="" bash -c '"$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "" "" & |
| 774 | 776 | fi |
| 775 | 777 | echo $! >"/.job.pid" |
| 776 | 778 | } |
| 777 | 779 | |
| 780 | # ---- the proxy's own jars: the answer's `jars` ({name, url, sha256}) come with its compose file, which | |
| 781 | # mounts jars/ read-only at /forge-jars and names each file in the proxy's PLUGINS. They are fetched and | |
| 782 | # checked before an up. When one is missing or wrong, the proxy is left as it is and the rest comes up. ---- | |
| 783 | ||
| 784 | # The AutoStopper the image fetches from Modrinth (games/sleep.ts): its project, and its jar's sha512. | |
| 785 | AUTOSTOPPER_PROJECT="PG4gqnzX" | |
| 786 | AUTOSTOPPER_SHA512="" | |
| 787 | ||
| 788 | # Every jar in place with its sha256, or 1. The image skips a file of the same name and size, so a name | |
| 789 | # holds its sha256's first 12 characters. A link can be signed: it is never on a command line or said. | |
| 790 | jars_ready() { | |
| 791 | local name url sha next | |
| 792 | jq -e 'type == "array" and length <= 8 and all(.[]; | |
| 793 | (.sha256 | test("\\A[0-9a-f]{64}\\z")) and (.url | test("\\Ahttps?://[^\\s\"\\\\]+\\z")) | |
| 794 | and (.name | test("\\A[A-Za-z0-9][A-Za-z0-9._-]{0,99}[.]jar\\z")) and (.sha256[0:12] as | .name | contains()))' \ | |
| 795 | "/.jars.json" >/dev/null 2>&1 || { echo "the jars the forge named are not as they should be"; return 1; } | |
| 796 | mkdir -p "/jars" && chmod 0755 "/jars" || return 1 | |
| 797 | while IFS=$'\t' read -r name url sha <&3; do | |
| 798 | [ "$(sha256sum "/jars/" 2>/dev/null | cut -d' ' -f1)" = "" ] && continue | |
| 799 | next="/.jar.next" | |
| 800 | printf 'url = "%s"\n' "" >"/.jar.curl" | |
| 801 | curl -fsSL --proto '=https,http' --max-filesize 67108864 -m 120 --retry 3 -K "/.jar.curl" -o "" 2>/dev/null | |
| 802 | rm -f "/.jar.curl" | |
| 803 | if [ "$(sha256sum "" 2>/dev/null | cut -d' ' -f1)" != "" ]; then | |
| 804 | rm -f "" | |
| 805 | echo " could not be fetched with sha256 " | |
| 806 | return 1 | |
| 807 | fi | |
| 808 | chmod 0644 "" && mv "" "/jars/" || return 1 | |
| 809 | done 3< <(jq -r '.[] | [.name, .url, .sha256] | @tsv' "/.jars.json") | |
| 810 | } | |
| 811 | # Rename the AutoStopper the image fetched, in the proxy's plugins folder: from *$1 to what $2 makes of | |
| 812 | # it. A helper container has the proxy's volumes, running or not; only a regular file moves. | |
| 813 | autostopper_mv() { | |
| 814 | local cid | |
| 815 | cid="$(compose ps -a -q velocity 2>/dev/null | head -n 1)" | |
| 816 | [ -n "" ] || return 0 | |
| 817 | "" run --rm --network none --volumes-from "" -w /server "" sh -euc "[ ! -L plugins ] && cd plugins 2>/dev/null || exit 0 | |
| 818 | for f in *; do | |
| 819 | [ -f \"\$f\" ] && [ ! -L \"\$f\" ] || continue | |
| 820 | [ \"\$(sha512sum < \"\$f\" | cut -d' ' -f1)\" = '' ] || continue | |
| 821 | mv \"\$f\" \"$2\" | |
| 822 | echo \"$3: \$f sha512 \" | |
| 823 | done" | |
| 824 | } | |
| 825 | # Ours and the image's have one id, and Velocity loads only one of them. While the compose file still | |
| 826 | # names the project, the image would fetch its jar again, so it stays. | |
| 827 | autostopper_aside() { | |
| 828 | jq -e 'any(.[]; .name | startswith("AutoStopper-"))' "/.jars.json" >/dev/null 2>&1 || return 0 | |
| 829 | grep -q "" "/compose.yml" && return 0 | |
| 830 | : >"/.jar.aside" | |
| 831 | autostopper_mv .jar "\$f.aside" "moved aside" | |
| 832 | } | |
| 833 | # Only what this up moved (an interrupted one counts) comes back. | |
| 834 | autostopper_back() { | |
| 835 | [ -f "/.jar.aside" ] || return 0 | |
| 836 | autostopper_mv .jar.aside "\${f%.aside}" "put back" && rm -f "/.jar.aside" | |
| 837 | } | |
| 838 | # `compose up …`, with the jars first when the forge named any. | |
| 839 | up_job() { | |
| 840 | local rc rest | |
| 841 | if [ ! -s "/.jars.json" ]; then | |
| 842 | compose "$@" | |
| 843 | return | |
| 844 | fi | |
| 845 | if jars_ready && autostopper_aside; then | |
| 846 | compose "$@" | |
| 847 | rc= | |
| 848 | if [ "" = 0 ]; then rm -f "/.jar.aside"; else autostopper_back; fi | |
| 849 | return "" | |
| 850 | fi | |
| 851 | autostopper_back | |
| 852 | echo "the proxy is left as it is" | |
| 853 | # An up of one service is a person's recreate: nothing else is touched for it. | |
| 854 | [ "" = --remove-orphans ] || return 1 | |
| 855 | rest="$(compose config --services 2>/dev/null | grep -vx velocity)" | |
| 856 | # shellcheck disable=SC2086 # service names, one word each | |
| 857 | [ -z "" ] || compose up -d --no-deps --remove-orphans | |
| 858 | return 1 | |
| 859 | } | |
| 860 | export -f jars_ready autostopper_mv autostopper_aside autostopper_back up_job | |
| 861 | export AUTOSTOPPER_PROJECT AUTOSTOPPER_SHA512 | |
| 862 | ||
| 778 | 863 | # ---- the owner's shell (#17151 V4): `bash -lc` under `capped`, at most FORGE_GAME_SHELL_S |
| 779 | 864 | # seconds (30) with no terminal and no input, so an interactive program ends at once; its output, |
| 780 | 865 | # at most 16 KB, is the command's result at the next sync. Each runs beside the sync. ---- |
| @@ -814,6 +899,7 @@ apply() { | ||
| 814 | 899 | if jq -e 'has("compose") and (.compose | type == "string")' <<<"" >/dev/null 2>&1 && |
| 815 | 900 | [ "" != "$(cat "/.compose-sha" 2>/dev/null)" ] && [ "" != "$(cat "/.up.failed" 2>/dev/null)" ]; then |
| 816 | 901 | jq -j '.compose' <<<"" >"/compose.yml.next" && mv "/compose.yml.next" "/compose.yml" |
| 902 | jq -c '.jars // empty' <<<"" >"/.jars.json.next" && mv "/.jars.json.next" "/.jars.json" | |
| 817 | 903 | changed=1 |
| 818 | 904 | fi |
| 819 | 905 | while IFS= read -r name <&3; do |
test/game-jars.test.ts added +152
| @@ -0,0 +1,152 @@ | ||
| 1 | /** | |
| 2 | * The proxy's own jars: pinned by sha256, fetched to a folder the proxy only reads, and checked before | |
| 3 | * an `up` that starts the proxy. A jar that is missing or wrong holds back the proxy alone. The | |
| 4 | * AutoStopper the image fetched is moved aside by its sha512, and comes back when the `up` fails. | |
| 5 | * Docker here is a script that writes down what it was asked. | |
| 6 | */ | |
| 7 | import { afterEach, expect, test } from "bun:test"; | |
| 8 | import { createHash } from "node:crypto"; | |
| 9 | import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; | |
| 10 | import { rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { AUTOSTOPPER, AUTOSTOPPER_SHA512 } from "../src/games/sleep.ts"; | |
| 14 | import { pollUntil } from "./helpers/poll.ts"; | |
| 15 | ||
| 16 | const AGENT = join(import.meta.dir, "../src/games/agent.sh"); | |
| 17 | const cleanups: (() => Promise<void>)[] = []; | |
| 18 | afterEach(async () => { | |
| 19 | for (const c of cleanups.splice(0)) await c(); | |
| 20 | }); | |
| 21 | const sha = (kind: "sha256" | "sha512", text: string): string => createHash(kind).update(text).digest("hex"); | |
| 22 | const OLD = "the AutoStopper the image fetched"; | |
| 23 | const JAR = "our AutoStopper"; | |
| 24 | const NAME = `AutoStopper-${sha("sha256", JAR).slice(0, 12)}.jar`; | |
| 25 | ||
| 26 | /** A box whose forge hands out `compose` and `jars`, and serves `served` as every jar. */ | |
| 27 | function made(o: { compose?: string; jars?: boolean; served?: string; upFails?: boolean; name?: string }) { | |
| 28 | const root = mkdtempSync(join(tmpdir(), "forge-game-jars-")); | |
| 29 | const dir = join(root, "game"); | |
| 30 | const plugins = join(root, "server/plugins"); | |
| 31 | mkdirSync(plugins, { recursive: true }); | |
| 32 | writeFileSync(join(plugins, "AutoStopper-3.0.0.jar"), OLD); | |
| 33 | writeFileSync(join(plugins, "other.jar"), "another plugin"); | |
| 34 | const fake = join(root, "docker"); | |
| 35 | writeFileSync( | |
| 36 | fake, | |
| 37 | `#!/usr/bin/env bash | |
| 38 | case "$*" in | |
| 39 | *" config --services"*) printf 'velocity\\nhub\\nsurvival\\n' ;; | |
| 40 | *" ps -a -q velocity"*) echo c1 ;; | |
| 41 | "run "*"--volumes-from c1"*) cd "${root}/server" && exec sh -euc "\${@: -1}" ;; | |
| 42 | *" up "*) | |
| 43 | all="$*" | |
| 44 | echo "up \${all#* up }" >>"${root}/ups" | |
| 45 | ls "${plugins}" >"${root}/at-up" | |
| 46 | ls "${dir}/jars" >"${root}/jars-at-up" 2>/dev/null | |
| 47 | exit ${o.upFails === true ? "1" : "0"} ;; | |
| 48 | esac | |
| 49 | exit 0 | |
| 50 | `, | |
| 51 | ); | |
| 52 | chmodSync(fake, 0o755); | |
| 53 | const compose = o.compose ?? "services: {}\n"; | |
| 54 | const forge: ReturnType<typeof Bun.serve> = Bun.serve({ | |
| 55 | port: 0, | |
| 56 | hostname: "127.0.0.1", | |
| 57 | fetch(req): Response { | |
| 58 | if (new URL(req.url).pathname === "/jar") return new Response(o.served ?? JAR); | |
| 59 | const jars = [{ name: o.name ?? NAME, url: `http://127.0.0.1:${String(forge.port)}/jar?sig=secret`, sha256: sha("sha256", JAR) }]; | |
| 60 | return Response.json({ composeSha: sha("sha256", compose), compose, commands: [], ...(o.jars === false ? {} : { jars }) }); | |
| 61 | }, | |
| 62 | }); | |
| 63 | cleanups.push(async () => { | |
| 64 | forge.stop(true); | |
| 65 | await rm(root, { recursive: true, force: true }); | |
| 66 | }); | |
| 67 | /** Run the agent until its first job has ended and been reaped. */ | |
| 68 | const run = async (): Promise<void> => { | |
| 69 | const p = Bun.spawn(["bash", AGENT], { | |
| 70 | env: { | |
| 71 | PATH: process.env["PATH"] ?? "", | |
| 72 | FORGE_URL: `http://127.0.0.1:${String(forge.port)}`, | |
| 73 | FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG", | |
| 74 | FORGE_GAME_DIR: dir, | |
| 75 | FORGE_GAME_DOCKER: fake, | |
| 76 | FORGE_GAME_AUTOSTOPPER_SHA512: sha("sha512", OLD), | |
| 77 | FORGE_GAME_DIAG_S: "0", | |
| 78 | FORGE_GAME_VOLUME_CHECK: "0", | |
| 79 | FORGE_GAME_ONCE: "0", | |
| 80 | }, | |
| 81 | stdout: "ignore", | |
| 82 | stderr: "ignore", | |
| 83 | }); | |
| 84 | try { | |
| 85 | await pollUntil(() => existsSync(join(dir, ".job.last")), "the job to end", 30_000); | |
| 86 | } finally { | |
| 87 | p.kill(); | |
| 88 | await p.exited; | |
| 89 | } | |
| 90 | }; | |
| 91 | const read = (f: string): string => (existsSync(join(root, f)) ? readFileSync(join(root, f), "utf8") : ""); | |
| 92 | return { dir, plugins, run, read, log: () => readFileSync(join(dir, ".up.log"), "utf8") }; | |
| 93 | } | |
| 94 | ||
| 95 | test("the agent moves aside the jar the forge pins, and no other", () => { | |
| 96 | const agent = readFileSync(AGENT, "utf8"); | |
| 97 | expect(agent.includes(AUTOSTOPPER_SHA512)).toBe(true); | |
| 98 | expect(agent.includes(`AUTOSTOPPER_PROJECT="${AUTOSTOPPER.split(":")[0]!}"`)).toBe(true); | |
| 99 | }); | |
| 100 | ||
| 101 | test("without jars, an up is what it was", async () => { | |
| 102 | const box = made({ jars: false }); | |
| 103 | await box.run(); | |
| 104 | expect(box.read("ups")).toBe("up -d --remove-orphans\n"); | |
| 105 | expect(existsSync(join(box.dir, "jars"))).toBe(false); | |
| 106 | expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar", "other.jar"]); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a jar is checked and in place before the up, readable, and the old AutoStopper is aside", async () => { | |
| 110 | const box = made({}); | |
| 111 | await box.run(); | |
| 112 | expect(box.read("ups")).toBe("up -d --remove-orphans\n"); | |
| 113 | expect(box.read("jars-at-up")).toBe(`${NAME}\n`); | |
| 114 | expect(readFileSync(join(box.dir, "jars", NAME), "utf8")).toBe(JAR); | |
| 115 | expect(statSync(join(box.dir, "jars", NAME)).mode & 0o777).toBe(0o644); | |
| 116 | expect(statSync(join(box.dir, "jars")).mode & 0o777).toBe(0o755); | |
| 117 | expect(box.read("at-up").trim().split("\n").sort()).toEqual(["AutoStopper-3.0.0.jar.aside", "other.jar"]); | |
| 118 | expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar.aside", "other.jar"]); | |
| 119 | expect(box.log()).toContain(`AutoStopper-3.0.0.jar sha512 ${sha("sha512", OLD)}`); | |
| 120 | expect(box.log()).not.toContain("sig=secret"); | |
| 121 | }); | |
| 122 | ||
| 123 | test("an up that fails puts the old AutoStopper back", async () => { | |
| 124 | const box = made({ upFails: true }); | |
| 125 | await box.run(); | |
| 126 | expect(box.read("at-up")).toContain("AutoStopper-3.0.0.jar.aside"); | |
| 127 | expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar", "other.jar"]); | |
| 128 | expect(readFileSync(join(box.dir, ".up.failed"), "utf8")).not.toBe(""); | |
| 129 | }); | |
| 130 | ||
| 131 | test("while the compose file still fetches AutoStopper, its jar stays", async () => { | |
| 132 | const box = made({ compose: `# MODRINTH_PROJECTS: ${AUTOSTOPPER}\nservices: {}\n` }); | |
| 133 | await box.run(); | |
| 134 | expect(box.read("at-up")).toContain("AutoStopper-3.0.0.jar\n"); | |
| 135 | }); | |
| 136 | ||
| 137 | for (const [why, o] of [ | |
| 138 | ["whose sha256 differs", { served: "something else" }], | |
| 139 | ["whose name lacks its sha256", { name: "AutoStopper-3.0.0-forge.1.jar" }], | |
| 140 | ["whose name is a path", { name: `../${NAME}` }], | |
| 141 | ] as const) | |
| 142 | test(`a jar ${why} holds back the proxy alone, and nothing is moved`, async () => { | |
| 143 | const box = made(o); | |
| 144 | await box.run(); | |
| 145 | expect(box.read("ups")).toBe("up -d --no-deps --remove-orphans hub survival\n"); | |
| 146 | const jars = join(box.dir, "jars"); | |
| 147 | expect(existsSync(jars) ? readdirSync(jars) : []).toEqual([]); | |
| 148 | expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar", "other.jar"]); | |
| 149 | expect(box.log()).toContain("the proxy is left as it is"); | |
| 150 | expect(existsSync(join(box.dir, ".compose-sha"))).toBe(false); | |
| 151 | expect(readFileSync(join(box.dir, ".up.failed"), "utf8")).not.toBe(""); | |
| 152 | }); |
new above
offline