Public: anyone can read this; the crew can change it.
Game box: refuse a wake or a mod install the box has no memory for #18057
Merged 9h 28m ago, live in production
sold/memory-check → main 0 commits 3 threads · 3 unresolved
10 files
changed +141
−21
src/games/box_memory.ts added +45
| @@ -0,0 +1,45 @@ | ||
| 1 | import { agoWords } from "../kernel/ago.ts"; | |
| 2 | ||
| 3 | /** | |
| 4 | * Room on a game box (#18025): a server that starts, or a mod that is added, on a box whose host | |
| 5 | * memory (as its agent last said it) leaves less than the server's own heap plus a margin for the | |
| 6 | * system, gets the box killed by the kernel's memory killer instead of a refusal. Said in words, here. | |
| 7 | */ | |
| 8 | ||
| 9 | /** Kept free beyond the server's heap: the box's own processes and the page cache. */ | |
| 10 | export const MARGIN_MIB = 512; | |
| 11 | ||
| 12 | /** A heap in MiB from itzg's MEMORY ("1G", "1536M", "512m"); 1 GiB when it says nothing. */ | |
| 13 | export function heapMiB(memory: string | undefined): number { | |
| 14 | const m = /^(\d+(?:\.\d+)?)\s*([gGmM])?$/.exec((memory ?? "").trim()); | |
| 15 | if (m === null) return 1024; | |
| 16 | return Math.round(Number(m[1]) * (m[2]?.toLowerCase() === "m" ? 1 : 1024)); | |
| 17 | } | |
| 18 | ||
| 19 | /** A reading older than this is not acted on: the box may have changed since. */ | |
| 20 | export const STALE_MS = 10 * 60_000; | |
| 21 | ||
| 22 | /** What a refusal needs of a box: its last host numbers, and when it said them. */ | |
| 23 | export interface BoxRoom { | |
| 24 | readonly host: Readonly<Record<string, number>>; | |
| 25 | readonly seenAt: string; | |
| 26 | } | |
| 27 | ||
| 28 | /** | |
| 29 | * Why `what` should not go ahead, or undefined when the box has room, has not said its memory, or | |
| 30 | * said it too long ago to trust. `memory` is the server's MEMORY setting. `running`: the server is | |
| 31 | * up, so its heap is already in what the box uses and only the margin is asked for. | |
| 32 | */ | |
| 33 | export function memoryRefusal(box: BoxRoom, memory: string | undefined, what: string, running: boolean, now = Date.now()): string | undefined { | |
| 34 | const total = box.host["memMiB"]; | |
| 35 | const used = box.host["memUsedMiB"]; | |
| 36 | if (typeof total !== "number" || typeof used !== "number" || total <= 0) return undefined; | |
| 37 | const age = now - Date.parse(box.seenAt); | |
| 38 | if (!Number.isFinite(age) || age > STALE_MS) return undefined; | |
| 39 | const free = Math.max(0, total - used); | |
| 40 | const heap = running ? 0 : heapMiB(memory); | |
| 41 | const need = heap + MARGIN_MIB; | |
| 42 | if (free >= need) return undefined; | |
| 43 | const asked = running ? `${MARGIN_MIB} MiB for the box` : `the server's memory ${heap} MiB plus ${MARGIN_MIB} MiB for the box`; | |
| 44 | return `${what} needs ${need} MiB free (${asked}), and the box said ${agoWords(box.seenAt, now)} that it has ${free} MiB free of ${total} MiB. Stop a server you are not using, or move to a bigger box, then try again.`; | |
| 45 | } |
src/games/mods.ts +7 −1
| @@ -20,8 +20,9 @@ import type { App } from "../app.ts"; | ||
| 20 | 20 | import type { User } from "../core/users.ts"; |
| 21 | 21 | import { commitCompose, composeDir, pluginUrls, readCompose, readRepoFile, serviceEnv, setServiceEnv } from "./compose.ts"; |
| 22 | 22 | import { byVersion, latestRelease, newestPack, packUpdate, readPack, resolve, targetOf, updates, type Locked, type LockedPack, type Result, type Target, type Version } from "./modrinth.ts"; |
| 23 | import { memoryRefusal, type BoxRoom } from "./box_memory.ts"; | |
| 23 | 24 | import { AUTOSTOPPER } from "./sleep.ts"; |
| 24 | import type { GameBox } from "./store.ts"; | |
| 25 | import { servicesOf, type GameBox } from "./store.ts"; | |
| 25 | 26 | |
| 26 | 27 | /** What a service has, as its repository says at the compose file's commit. */ |
| 27 | 28 | export interface Mods { |
| @@ -38,6 +39,8 @@ export interface Mods { | ||
| 38 | 39 | readonly env: Readonly<Record<string, string>>; |
| 39 | 40 | /** The modpack the server runs (TYPE=MODRINTH), every file of it locked. */ |
| 40 | 41 | readonly pack: LockedPack | undefined; |
| 42 | /** The box's last host numbers and when it said them, and whether the server is up: for the memory check. */ | |
| 43 | readonly room?: BoxRoom & { readonly running: boolean }; | |
| 41 | 44 | } |
| 42 | 45 | |
| 43 | 46 | /** A change, previewed: its lines in words, and what the commit writes. */ |
| @@ -134,6 +137,7 @@ export async function modsOf(app: App, box: GameBox, service: string): Promise<R | ||
| 134 | 137 | sha: compose.sha, |
| 135 | 138 | env, |
| 136 | 139 | pack: target.value.pack ? pack : undefined, |
| 140 | room: { host: box.host, seenAt: box.seenAt, running: servicesOf(app.db, box.id).some((x) => x.name === service && x.state === "running") }, | |
| 137 | 141 | }, |
| 138 | 142 | }; |
| 139 | 143 | } |
| @@ -197,6 +201,8 @@ export async function planInstall(app: App, m: Mods, service: string, ref: strin | ||
| 197 | 201 | return { ok: false, error: "Name a Modrinth project by its slug or id, like luckperms." }; |
| 198 | 202 | const had = find(m.lock, wantedRef); |
| 199 | 203 | if (had?.top) return { ok: false, error: `${had.title} ${had.version} is installed.` }; |
| 204 | const crowded = m.room === undefined ? undefined : memoryRefusal(m.room, m.env["MEMORY"], `Adding ${wantedRef} restarts ${service}, and that`, m.room.running); | |
| 205 | if (crowded !== undefined) return { ok: false, error: crowded }; | |
| 200 | 206 | // A bare slug already in MODRINTH_PROJECTS is taken into the lock, pinned, with this change. |
| 201 | 207 | const adopt = m.loose.filter(bareSlug); |
| 202 | 208 | const kept = m.loose.filter((e) => !bareSlug(e)); |
src/games/power.ts +15 −5
| @@ -5,8 +5,10 @@ | ||
| 5 | 5 | * and pull go through, as they do at the agent. Whether a person may ask is the door's own check. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import type { Database } from "bun:sqlite"; | |
| 8 | import type { App } from "../app.ts"; | |
| 9 | 9 | import type { User } from "../core/users.ts"; |
| 10 | import { memoryRefusal } from "./box_memory.ts"; | |
| 11 | import { readCompose, serviceEnv } from "./compose.ts"; | |
| 10 | 12 | import { heldRefusal, startsNothing } from "./hold.ts"; |
| 11 | 13 | import { queueCommand, type GameBox } from "./store.ts"; |
| 12 | 14 | |
| @@ -18,9 +20,17 @@ const starts = (kind: Power): boolean => kind !== "stop" && kind !== "pull"; | ||
| 18 | 20 | /** Whether the box would refuse it now, as it last said. */ |
| 19 | 21 | export const refusesNow = (box: GameBox, kind: Power): boolean => starts(kind) && startsNothing(box, Date.now()); |
| 20 | 22 | |
| 21 | /** Ask the box for it, or say why it was not asked. */ | |
| 22 | export function askPower(db: Database, by: User | undefined, box: GameBox, service: string, kind: Power): { readonly ok: true; readonly id: string } | { readonly ok: false; readonly error: string } { | |
| 23 | const error = starts(kind) ? heldRefusal(db, by, box, `${kind[0]!.toUpperCase()}${kind.slice(1)} ${service}`) : undefined; | |
| 23 | /** | |
| 24 | * Ask the box for it, or say why it was not asked: held, or (for a start, the wake of a stopped | |
| 25 | * server) too little free memory on the box, as it last said, for the server's heap and a margin. | |
| 26 | */ | |
| 27 | export async function askPower(app: App, by: User | undefined, box: GameBox, service: string, kind: Power): Promise<{ readonly ok: true; readonly id: string } | { readonly ok: false; readonly error: string }> { | |
| 28 | const error = starts(kind) ? heldRefusal(app.db, by, box, `${kind[0]!.toUpperCase()}${kind.slice(1)} ${service}`) : undefined; | |
| 24 | 29 | if (error !== undefined) return { ok: false, error }; |
| 25 | return { ok: true, id: queueCommand(db, box.id, service, kind, "", by?.id ?? "") }; | |
| 30 | if (kind === "start") { | |
| 31 | const compose = await readCompose(app, box); | |
| 32 | const crowded = compose === undefined ? undefined : memoryRefusal(box, serviceEnv(compose.text, service)["MEMORY"], `Starting ${service}`, false); | |
| 33 | if (crowded !== undefined) return { ok: false, error: crowded }; | |
| 34 | } | |
| 35 | return { ok: true, id: queueCommand(app.db, box.id, service, kind, "", by?.id ?? "") }; | |
| 26 | 36 | } |
src/games/presets.ts +1 −6
| @@ -12,6 +12,7 @@ | ||
| 12 | 12 | import type { App } from "../app.ts"; |
| 13 | 13 | import type { User } from "../core/users.ts"; |
| 14 | 14 | import { commitCompose, composeServices, readCompose, serviceEnv, setTopEntry } from "./compose.ts"; |
| 15 | import { heapMiB } from "./box_memory.ts"; | |
| 15 | 16 | import { lockPath, lockText, planInstall, type Mods } from "./mods.ts"; |
| 16 | 17 | import { targetOf, type Locked, type Result } from "./modrinth.ts"; |
| 17 | 18 | import { isGameServer, policyOf, proxyOf, setPolicy } from "./sleep.ts"; |
| @@ -75,12 +76,6 @@ export async function wishOn(app: App, box: GameBox, words: string): Promise<Wis | ||
| 75 | 76 | return parseWish(words, [...servicesOf(app.db, box.id).map((s) => s.name), ...(compose === undefined ? [] : composeServices(compose.text))]); |
| 76 | 77 | } |
| 77 | 78 | |
| 78 | /** A heap in MiB from itzg's MEMORY ("1G", "1536M", "512m"); 1 GiB when it says nothing. */ | |
| 79 | export function heapMiB(memory: string | undefined): number { | |
| 80 | const m = /^(\d+(?:\.\d+)?)\s*([gGmM])?$/.exec((memory ?? "").trim()); | |
| 81 | if (m === null) return 1024; | |
| 82 | return Math.round(Number(m[1]) * (m[2]?.toLowerCase() === "m" ? 1 : 1024)); | |
| 83 | } | |
| 84 | 79 | const gb = (mib: number): string => (mib % 1024 === 0 ? `${mib / 1024}G` : `${(mib / 1024).toFixed(1)}G`); |
| 85 | 80 | |
| 86 | 81 | /** |
src/http/mcp/tools/games.ts +1 −1
| @@ -170,7 +170,7 @@ export const tool: Tool = { | ||
| 170 | 170 | if (action === "power") { |
| 171 | 171 | const kind = str(args["kind"]); |
| 172 | 172 | if (!isPower(kind)) return bad("invalid", "kind is start, stop, restart, recreate or pull"); |
| 173 | const asked = askPower(db, user, box, service, kind); | |
| 173 | const asked = await askPower(ctx.app, user, box, service, kind); | |
| 174 | 174 | return asked.ok ? good({ says: `${kind} ${service}: asked.`, id: asked.id }) : bad("refused", asked.error); |
| 175 | 175 | } |
| 176 | 176 | if (action === "env") { |
src/tui/screens/games.ts +11 −4
| @@ -35,7 +35,7 @@ import { spareRow } from "../../games/spare_row.ts"; | ||
| 35 | 35 | import { healWords } from "../../games/heal.ts"; |
| 36 | 36 | import { boxStatus, boxStatusShared, boxTails } from "../../games/diag.ts"; |
| 37 | 37 | import { heldLines, heldOn } from "../../games/hold.ts"; |
| 38 | import { askPower, type Power } from "../../games/power.ts"; | |
| 38 | import { askPower, refusesNow, type Power } from "../../games/power.ts"; | |
| 39 | 39 | import { cloudLine, pinnedOfBox } from "../../actions/cloud_says.ts"; |
| 40 | 40 | import { getUserByName } from "../../core/users.ts"; |
| 41 | 41 | import { commitServiceEnv, readCompose, serviceEnv } from "../../games/compose.ts"; |
| @@ -279,9 +279,16 @@ export function gamesScreen(f: Session, ctx: Ctx): Screen { | ||
| 279 | 279 | if (kind === undefined || at === undefined || e.ctrl || e.alt) return false; |
| 280 | 280 | if (!mayDo(roleOn(f.app.db, f.user, at.box.id, at.service.name), "operator")) note = `You are not an operator of ${at.service.name}.`; |
| 281 | 281 | else { |
| 282 | const asked = askPower(f.app.db, f.user, at.box, at.service.name, kind); | |
| 283 | // Why is above the list, on every draw. | |
| 284 | note = !asked.ok ? `${kind} ${at.box.name}/${at.service.name}: not asked, ${at.box.name} is held.` : `${kind} ${at.box.name}/${at.service.name}: asked. It shows on the server until the server answers.`; | |
| 282 | const { box, service } = at; | |
| 283 | void askPower(f.app, f.user, box, service.name, kind) | |
| 284 | .then((asked) => { | |
| 285 | // Why is above the list, on every draw. | |
| 286 | note = !asked.ok ? `${kind} ${box.name}/${service.name}: not asked, ${refusesNow(box, kind) ? `${box.name} is held.` : asked.error}` : `${kind} ${box.name}/${service.name}: asked. It shows on the server until the server answers.`; | |
| 287 | }) | |
| 288 | .catch(() => { | |
| 289 | note = `${kind} ${box.name}/${service.name}: not asked, the forge could not check the box. Try again.`; | |
| 290 | }) | |
| 291 | .finally(() => ctx.invalidate()); | |
| 285 | 292 | } |
| 286 | 293 | ctx.invalidate(); |
| 287 | 294 | return true; |
src/web/pages/games.ts +1 −1
| @@ -1074,7 +1074,7 @@ export async function gamePowerSubmit(ctx: Ctx): Promise<Response> { | ||
| 1074 | 1074 | if (got instanceof Response) return got; |
| 1075 | 1075 | const kind = field(got.form, "kind"); |
| 1076 | 1076 | if (!isPower(kind)) return notFoundPage(ctx); |
| 1077 | const asked = askPower(ctx.app.db, ctx.auth.user, got.box, got.service, kind); | |
| 1077 | const asked = await askPower(ctx.app, ctx.auth.user, got.box, got.service, kind); | |
| 1078 | 1078 | return flashTo(ctx, `/games/${got.box.name}/${got.service}`, !asked.ok ? { tone: "danger", message: asked.error } : { message: `${kind[0]!.toUpperCase()}${kind.slice(1)} ${got.service}: asked. It shows on the server until the server answers.` }); |
| 1079 | 1079 | } |
| 1080 | 1080 |
test/game-hold.test.ts +15 −1
| @@ -2,7 +2,7 @@ | ||
| 2 | 2 | * A held game box says so first, at every door (#17532): why, and the next step, to its owner; that |
| 3 | 3 | * its owner has to look, to anyone else. The words come from a code, so no log line is read. |
| 4 | 4 | */ |
| 5 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 5 | import { afterAll, beforeAll, expect, spyOn, test } from "bun:test"; | |
| 6 | 6 | import { mkdtempSync } from "node:fs"; |
| 7 | 7 | import { rm } from "node:fs/promises"; |
| 8 | 8 | import { tmpdir } from "node:os"; |
| @@ -16,6 +16,7 @@ import { createToken } from "../src/core/tokens.ts"; | ||
| 16 | 16 | import { createUser, type User } from "../src/core/users.ts"; |
| 17 | 17 | import { boxStatus, DIAG_MOST, holdOf, keptDiag, readDiag } from "../src/games/diag.ts"; |
| 18 | 18 | import { heldOn } from "../src/games/hold.ts"; |
| 19 | import * as power from "../src/games/power.ts"; | |
| 19 | 20 | import { POWER, type Power } from "../src/games/power.ts"; |
| 20 | 21 | import { boxNamed, createGameBox, grant, recordSync } from "../src/games/store.ts"; |
| 21 | 22 | import { serve, type Servers } from "../src/http/server.ts"; |
| @@ -297,3 +298,16 @@ test("a world's import, restore and snapshot end by starting the server, so a he | ||
| 297 | 298 | expect(asked()).toEqual(Array(6).fill("world")); |
| 298 | 299 | expect(await get(alice, "/games/mc/hub")).not.toContain("snapshot: held"); |
| 299 | 300 | }); |
| 301 | ||
| 302 | test("the terminal says why a start was refused, and says so when the check itself throws", async () => { | |
| 303 | sync(null); | |
| 304 | const spy = spyOn(power, "askPower"); | |
| 305 | try { | |
| 306 | spy.mockResolvedValueOnce({ ok: false, error: "Starting hub needs 1536 MiB free." }); | |
| 307 | expect(await keys("s")).toContain("start mc/hub: not asked, Starting hub needs 1536 MiB free."); | |
| 308 | spy.mockRejectedValueOnce(new Error("repo unreadable")); | |
| 309 | expect(await keys("s")).toContain("start mc/hub: not asked, the forge could not check the box. Try again."); | |
| 310 | } finally { | |
| 311 | spy.mockRestore(); | |
| 312 | } | |
| 313 | }); |
test/game-mods.test.ts +43 −1
| @@ -16,9 +16,10 @@ import { createUser, getUserByName, type User } from "../src/core/users.ts"; | ||
| 16 | 16 | import { readCompose, readRepoFile, serviceEnv } from "../src/games/compose.ts"; |
| 17 | 17 | import { search, searchPacks, targetOf } from "../src/games/modrinth.ts"; |
| 18 | 18 | import { commitPlan, lockPath, modsOf, packUpdateOf, planInstall, planPack, planPackUpdate, planRemove, planUpdate, updatesOf } from "../src/games/mods.ts"; |
| 19 | import { boxNamed, createGameBox, type GameBox } from "../src/games/store.ts"; | |
| 19 | import { boxNamed, createGameBox, recordSync, type GameBox } from "../src/games/store.ts"; | |
| 20 | 20 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; |
| 21 | 21 | import { packVerdict } from "../src/games/pack_check.ts"; |
| 22 | import { askPower } from "../src/games/power.ts"; | |
| 22 | 23 | import { AUTOSTOPPER, commitPolicy } from "../src/games/sleep.ts"; |
| 23 | 24 | import { quietLogs } from "./helpers/globals.ts"; |
| 24 | 25 | |
| @@ -691,3 +692,44 @@ describe("the page and the MCP tool", () => { | ||
| 691 | 692 | expect((listed.value["installed"] as { project: string }[]).map((p) => p.project)).toContain("chunkylib"); |
| 692 | 693 | }); |
| 693 | 694 | }); |
| 695 | ||
| 696 | describe("room on the box (#18025)", () => { | |
| 697 | // The hub sets no MEMORY: its heap is 1 GiB, so a stopped one needs 1536 MiB free. | |
| 698 | const said = (free: number, ago = 60_000): GameBox => ({ ...box, seenAt: new Date(Date.now() - ago).toISOString(), host: { memMiB: 8000, memUsedMiB: 8000 - free } }); | |
| 699 | const planFor = async (b: GameBox) => { | |
| 700 | const m = await modsOf(app, b, "hub"); | |
| 701 | if (!m.ok) throw new Error(m.error); | |
| 702 | return planInstall(app, m.value, "hub", "worldedit"); | |
| 703 | }; | |
| 704 | const refusal = (r: { ok: boolean; error?: string }): string => (r.ok ? "" : (r.error ?? "")); | |
| 705 | ||
| 706 | test("a mod install on a stopped server is refused in words, with how old the reading is", async () => { | |
| 707 | const no = refusal(await planFor(said(1535))); | |
| 708 | expect(no).toContain("needs 1536 MiB free"); | |
| 709 | expect(no).toContain("the box said 1 minute ago that it has 1535 MiB free of 8000 MiB"); | |
| 710 | // Anything else it says (this mod may need more than the stand-in has) is not about memory. | |
| 711 | expect(refusal(await planFor(said(1536)))).not.toContain("MiB free"); | |
| 712 | expect(refusal(await planFor(box))).not.toContain("MiB free"); | |
| 713 | }); | |
| 714 | ||
| 715 | test("a reading older than ten minutes is not acted on", async () => { | |
| 716 | expect(refusal(await planFor(said(0, 11 * 60_000)))).not.toContain("MiB free"); | |
| 717 | expect(refusal(await planFor(said(0, 9 * 60_000)))).toContain("needs 1536 MiB free"); | |
| 718 | }); | |
| 719 | ||
| 720 | test("a wake (start) is refused the same way, and queues nothing; a stop is not", async () => { | |
| 721 | const no = await askPower(app, alice, said(1535), "hub", "start"); | |
| 722 | expect(no.ok).toBe(false); | |
| 723 | if (!no.ok) expect(no.error).toContain("Starting hub needs 1536 MiB free"); | |
| 724 | expect((await askPower(app, alice, said(1536), "hub", "start")).ok).toBe(true); | |
| 725 | expect((await askPower(app, alice, said(0), "hub", "stop")).ok).toBe(true); | |
| 726 | expect((await askPower(app, alice, said(0, 11 * 60_000), "hub", "start")).ok).toBe(true); | |
| 727 | }); | |
| 728 | ||
| 729 | test("a running server's heap is already in what the box uses: only the 512 MiB margin is asked", async () => { | |
| 730 | recordSync(app.db, box, { services: [{ name: "hub", state: "running" }] }); | |
| 731 | const no = refusal(await planFor(said(511))); | |
| 732 | expect(no).toContain("needs 512 MiB free (512 MiB for the box)"); | |
| 733 | expect(refusal(await planFor(said(512)))).not.toContain("MiB free"); | |
| 734 | }); | |
| 735 | }); |
test/game-presets.test.ts +2 −1
| @@ -18,7 +18,8 @@ import { createToken } from "../src/core/tokens.ts"; | ||
| 18 | 18 | import { createUser, type User } from "../src/core/users.ts"; |
| 19 | 19 | import { readCompose, readRepoFile, serviceEnv, serviceLabels } from "../src/games/compose.ts"; |
| 20 | 20 | import { lockPath } from "../src/games/mods.ts"; |
| 21 | import { commitServer, heapMiB, memoryMath, parseWish, planRemoveServer, planServer, wishOn, proxyLines } from "../src/games/presets.ts"; | |
| 21 | import { heapMiB } from "../src/games/box_memory.ts"; | |
| 22 | import { commitServer, memoryMath, parseWish, planRemoveServer, planServer, wishOn, proxyLines } from "../src/games/presets.ts"; | |
| 22 | 23 | import { policyOf, WAKER } from "../src/games/sleep.ts"; |
| 23 | 24 | import { boxNamed, createGameBox, recordSync } from "../src/games/store.ts"; |
| 24 | 25 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; |
new above
offline
A running server's heap is already in memUsedMiB, and the restart frees it. This refuses installs on tight boxes that would fit. Count the heap only for a stopped server, or leave the install unchecked when it is running.