Fragnet game servers: games, addresses, backups, power actions
New integration kind "fragnet" reading Fragnet's Pterodactyl-based panel through the client API (account key). Game servers page under Infrastructure with game, IP:port, state, memory/disk, backups, schedules and databases; alerts for late backups and nearly full disk/memory; operators can start/stop/restart/kill (audited). Metrics, docs and tests included; migration 0071 adds fragnet_state. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f86661f6c9
commit
9a3d5c466a
29 files changed
+9836
-8
No files matched your search
@@ -0,0 +1,505 @@
|
||||
/**
|
||||
* Fragnet game servers (a Pterodactyl panel): reading what the client API says, what is stored and carried between reads, what is wrong (late backups, a disk or memory nearly full), the
|
||||
* health pass, the alerts, the page's routes, the power signals and /metrics.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer as createHttpServer, type Server } from "node:http";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-fragnet-"));
|
||||
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||
process.env.SESSION_DIR = join(dir, "sessions");
|
||||
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||
process.env.HEALTH_STARTUP_GRACE_MS = "0";
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { users, integrations, fragnetState, auditLog } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const adapter = await import("../src/integrations/fragnet/adapter.js");
|
||||
const fn = await import("../src/services/fragnetSync.js");
|
||||
const { evaluateHealth, collectSnapshot } = await import("../src/services/healthMonitor.js");
|
||||
const { subjectOfConditionKey } = await import("../src/services/maintenance.js");
|
||||
const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js");
|
||||
const { fragnetRouter } = await import("../src/routes/fragnet.js");
|
||||
const { buildMetrics } = await import("../src/services/metrics.js");
|
||||
const { setInternalFlag } = await import("../src/services/settingsStore.js");
|
||||
const { eq } = await import("drizzle-orm");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
const MIN = 60_000;
|
||||
const HOUR = 60 * MIN;
|
||||
const DAY = 24 * HOUR;
|
||||
const MB = 1024 ** 2;
|
||||
const GB = 1024 ** 3;
|
||||
const iso = (ms: number) => new Date(ms).toISOString();
|
||||
|
||||
type Srv = import("../src/integrations/fragnet/adapter.js").FragnetServer;
|
||||
type Read = import("../src/integrations/fragnet/adapter.js").FragnetRead;
|
||||
type Backup = import("../src/integrations/fragnet/adapter.js").FragnetBackup;
|
||||
|
||||
const server = (extra: Partial<Srv> = {}): Srv => ({
|
||||
id: "abcd1234",
|
||||
uuid: "abcd1234-0000-0000-0000-000000000000",
|
||||
name: "survival",
|
||||
description: null,
|
||||
node: "stockholm-1",
|
||||
game: "Minecraft: Paper",
|
||||
dockerImage: "ghcr.io/pterodactyl/yolks:java_21",
|
||||
panelStatus: null,
|
||||
suspended: false,
|
||||
installing: false,
|
||||
transferring: false,
|
||||
owner: true,
|
||||
state: "running",
|
||||
allocations: [{ ip: "203.0.113.20", alias: null, port: 25565, isDefault: true, notes: null }],
|
||||
sftp: "sftp.fragnet.net:2022",
|
||||
memoryLimitMb: 4096,
|
||||
diskLimitMb: 20_480,
|
||||
cpuLimit: 200,
|
||||
databaseLimit: 1,
|
||||
backupLimit: 3,
|
||||
allocationLimit: 1,
|
||||
usage: { memoryBytes: 2 * GB, cpu: 35, diskBytes: 5 * GB, rxBytes: 1000, txBytes: 2000, uptimeMs: 3 * HOUR },
|
||||
backups: [],
|
||||
schedules: [],
|
||||
databases: 0,
|
||||
...extra,
|
||||
});
|
||||
const read = (...s: Srv[]): Read => ({ servers: s });
|
||||
const okBackup = (ageMs: number, extra: Partial<Backup> = {}, now = Date.now()): Backup => ({ uuid: `b-${ageMs}-${extra.successful}`, name: "auto", bytes: 5 * MB, createdAt: iso(now - ageMs - MIN), completedAt: iso(now - ageMs), successful: true, locked: false, ...extra });
|
||||
|
||||
// What Pterodactyl's client API sends ({ object, attributes } wrappers).
|
||||
const apiServer = (identifier: string, name: string, extra: Record<string, unknown> = {}) => ({
|
||||
object: "server",
|
||||
attributes: {
|
||||
server_owner: true,
|
||||
identifier,
|
||||
uuid: `${identifier}-1111-2222-3333-444444444444`,
|
||||
name,
|
||||
node: "stockholm-1",
|
||||
sftp_details: { ip: "sftp.fragnet.net", port: 2022 },
|
||||
description: "",
|
||||
limits: { memory: 4096, swap: 0, disk: 20_480, io: 500, cpu: 200 },
|
||||
feature_limits: { databases: 1, allocations: 1, backups: 3 },
|
||||
is_suspended: false,
|
||||
is_installing: false,
|
||||
is_transferring: false,
|
||||
docker_image: "ghcr.io/pterodactyl/yolks:java_21",
|
||||
relationships: {
|
||||
allocations: { object: "list", data: [{ object: "allocation", attributes: { id: 2, ip: "203.0.113.20", ip_alias: null, port: 25566, is_default: false, notes: "query" } }, { object: "allocation", attributes: { id: 1, ip: "203.0.113.20", ip_alias: null, port: 25565, is_default: true, notes: null } }] },
|
||||
egg: { object: "egg", attributes: { id: 3, name: "Minecraft: Paper" } },
|
||||
},
|
||||
...extra,
|
||||
},
|
||||
});
|
||||
const apiResources = (state: string, extra: Record<string, unknown> = {}) => ({ object: "stats", attributes: { current_state: state, is_suspended: false, resources: { memory_bytes: 2 * GB, cpu_absolute: 35.5, disk_bytes: 5 * GB, network_rx_bytes: 10, network_tx_bytes: 20, uptime: 60_000, ...extra } } });
|
||||
const apiBackup = (uuid: string, createdAt: string, completedAt: string | null, ok = true) => ({ object: "backup", attributes: { uuid, name: uuid, ignored_files: [], checksum: "sha1:x", bytes: 1048576, created_at: createdAt, completed_at: completedAt, is_successful: ok, is_locked: false } });
|
||||
|
||||
describe("what the panel's API says", () => {
|
||||
test("servers: the id the panel uses, the game, the addresses (the main one first), the limits and the plan's room for backups", () => {
|
||||
const [s] = adapter.parseServers({ data: [apiServer("abcd1234", "survival")] });
|
||||
assert.deepEqual([s.id, s.name, s.game, s.node, s.sftp], ["abcd1234", "survival", "Minecraft: Paper", "stockholm-1", "sftp.fragnet.net:2022"]);
|
||||
assert.deepEqual(s.allocations.map((a) => `${a.ip}:${a.port}${a.isDefault ? "*" : ""}`), ["203.0.113.20:25565*", "203.0.113.20:25566"]);
|
||||
assert.deepEqual([s.memoryLimitMb, s.diskLimitMb, s.cpuLimit, s.backupLimit, s.databaseLimit], [4096, 20_480, 200, 3, 1]);
|
||||
assert.deepEqual([s.suspended, s.installing, s.owner, s.state, s.usage, s.backups], [false, false, true, "unknown", null, null]);
|
||||
});
|
||||
|
||||
test("a server without a proper id or a name is skipped; a panel that did not say the game leaves it null; suspended and installing show from the status too", () => {
|
||||
const list = adapter.parseServers({ data: [apiServer("short", "x"), apiServer("abcd1234", ""), apiServer("eeee5555", "bare", { relationships: {}, status: "suspended" }), apiServer("ffff6666", "setup", { status: "installing" }), "junk"] });
|
||||
assert.deepEqual(list.map((s) => s.name), ["bare", "setup"]);
|
||||
assert.deepEqual([list[0].game, list[0].allocations, list[0].suspended, list[1].installing], [null, [], true, true]);
|
||||
assert.deepEqual(adapter.parseServers(null), []);
|
||||
});
|
||||
|
||||
test("resources: whether it runs, and what it uses; something that is not that is not read", () => {
|
||||
const r = adapter.parseResources(apiResources("running"))!;
|
||||
assert.deepEqual([r.state, r.usage.memoryBytes, r.usage.cpu, r.usage.diskBytes, r.usage.uptimeMs], ["running", 2 * GB, 35.5, 5 * GB, 60_000]);
|
||||
assert.equal(adapter.parseResources({ errors: [] }), null);
|
||||
});
|
||||
|
||||
test("backups come newest first, and one with no finish time is still being made", () => {
|
||||
const list = adapter.parseBackups({ data: [apiBackup("old", "2026-05-01T00:00:00Z", "2026-05-01T00:05:00Z"), apiBackup("new", "2026-06-01T00:00:00Z", null, false), apiBackup("failed", "2026-05-20T00:00:00Z", "2026-05-20T00:01:00Z", false), { attributes: {} }] });
|
||||
assert.deepEqual(list.map((b) => [b.uuid, b.completedAt === null, b.successful]), [["new", true, false], ["failed", false, false], ["old", false, true]]);
|
||||
});
|
||||
|
||||
test("schedules: the name, when it runs, whether it is on", () => {
|
||||
const [s] = adapter.parseSchedules({ data: [{ attributes: { id: 4, name: "Nightly restart", cron: { day_of_week: "*", day_of_month: "*", month: "*", hour: "4", minute: "0" }, is_active: true, is_processing: false, only_when_online: true, last_run_at: "2026-06-01T04:00:00+00:00", next_run_at: "2026-06-02T04:00:00+00:00" } }, { attributes: { name: "no id" } }] });
|
||||
assert.deepEqual([s.id, s.name, s.cron, s.active, s.onlyWhenOnline, s.nextRunAt], [4, "Nightly restart", "0 4 * * *", true, true, "2026-06-02T04:00:00.000Z"]);
|
||||
});
|
||||
|
||||
test("the next page is the one after this, up to the last", () => {
|
||||
assert.equal(adapter.nextPage({ meta: { pagination: { current_page: 1, total_pages: 2 } } }), 2);
|
||||
assert.equal(adapter.nextPage({ meta: { pagination: { current_page: 2, total_pages: 2 } } }), null);
|
||||
assert.equal(adapter.nextPage({}), null);
|
||||
});
|
||||
|
||||
describe("the adapter against a panel that answers", () => {
|
||||
let fake: Server;
|
||||
let url = "";
|
||||
let keyOk = true;
|
||||
let rateLimited = false;
|
||||
let databasesStatus = 200;
|
||||
let rejectIncludes = false;
|
||||
let powerStatus = 204;
|
||||
const seen: { method: string | undefined; path: string; auth: string | undefined; body: string }[] = [];
|
||||
before(async () => {
|
||||
fake = createHttpServer((req, res) => {
|
||||
const u = new URL(req.url ?? "", "http://x");
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
seen.push({ method: req.method, path: u.pathname + u.search, auth: req.headers.authorization, body });
|
||||
const send = (code: number, json: unknown) => {
|
||||
res.writeHead(code, { "content-type": "application/json" });
|
||||
res.end(code === 204 ? "" : JSON.stringify(json));
|
||||
};
|
||||
if (!keyOk) return send(401, { errors: [{ code: "AuthenticationException" }] });
|
||||
if (rateLimited) return send(429, { errors: [{ code: "TooManyRequestsHttpException" }] });
|
||||
const page = Number(u.searchParams.get("page") ?? 1);
|
||||
if (u.pathname === "/api/client") {
|
||||
if (rejectIncludes && u.searchParams.has("include")) return send(400, { errors: [{ code: "BadRequest" }] });
|
||||
return send(200, { object: "list", data: [apiServer(page === 1 ? "abcd1234" : "eeee5555", page === 1 ? "survival" : "rust")], meta: { pagination: { total: 2, count: 1, per_page: 1, current_page: page, total_pages: 2 } } });
|
||||
}
|
||||
const m = /^\/api\/client\/servers\/([a-z0-9]{8})\/(resources|backups|schedules|databases|power)$/.exec(u.pathname);
|
||||
if (!m) return send(404, {});
|
||||
if (m[2] === "power") return req.method === "POST" ? send(powerStatus, {}) : send(405, {});
|
||||
if (m[2] === "resources") return send(200, apiResources(m[1] === "abcd1234" ? "running" : "offline"));
|
||||
if (m[2] === "backups") return send(200, { object: "list", data: [apiBackup("b1", "2026-06-01T00:00:00Z", "2026-06-01T00:03:00Z")], meta: { pagination: { current_page: 1, total_pages: 1 } } });
|
||||
if (m[2] === "schedules") return send(200, { object: "list", data: [{ attributes: { id: 1, name: "Restart", cron: { minute: "0", hour: "4", day_of_month: "*", month: "*", day_of_week: "*" }, is_active: true } }] });
|
||||
return databasesStatus === 200 ? send(200, { object: "list", data: [{ attributes: { id: "x" } }, { attributes: { id: "y" } }] }) : send(databasesStatus, {});
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => fake.listen(0, "127.0.0.1", resolve));
|
||||
url = `http://127.0.0.1:${(fake.address() as AddressInfo).port}`;
|
||||
});
|
||||
after(() => fake.close());
|
||||
|
||||
test("every page of the servers is read, and for each its resources, backups, schedules and databases; only GET is ever sent by a read", async () => {
|
||||
seen.length = 0;
|
||||
const r = await adapter.createFragnetAdapter({ token: "ptlc_x", url }).read();
|
||||
assert.deepEqual(r.servers.map((s) => [s.id, s.name, s.state]), [["abcd1234", "survival", "running"], ["eeee5555", "rust", "offline"]]);
|
||||
const [a] = r.servers;
|
||||
assert.deepEqual([a.usage?.diskBytes, a.backups?.length, a.schedules?.[0].name, a.databases, a.game], [5 * GB, 1, "Restart", 2, "Minecraft: Paper"]);
|
||||
assert.ok(seen.every((s) => s.method === "GET" && s.auth === "Bearer ptlc_x"));
|
||||
assert.ok(seen.some((s) => s.path.startsWith("/api/client?include=egg,allocations&per_page=50&page=2")));
|
||||
});
|
||||
|
||||
test("a part a server will not give (a sub-user without that permission) is null, not none; the servers themselves must work", async () => {
|
||||
databasesStatus = 403;
|
||||
const r = await adapter.createFragnetAdapter({ token: "ptlc_x", url }).read();
|
||||
assert.deepEqual([r.servers[0].databases, r.servers[0].backups?.length], [null, 1]);
|
||||
databasesStatus = 200;
|
||||
});
|
||||
|
||||
test("a panel that refuses the extras is asked again plainly", async () => {
|
||||
rejectIncludes = true;
|
||||
seen.length = 0;
|
||||
const r = await adapter.createFragnetAdapter({ token: "ptlc_x", url }).read();
|
||||
assert.equal(r.servers.length, 2);
|
||||
assert.ok(seen.some((s) => s.path.startsWith("/api/client?per_page=50")));
|
||||
rejectIncludes = false;
|
||||
});
|
||||
|
||||
test("a key that is refused, an Application key and a panel over its limit are said", async () => {
|
||||
keyOk = false;
|
||||
const ping = await adapter.createFragnetAdapter({ token: "bad", url }).ping();
|
||||
assert.equal(ping.ok, false);
|
||||
assert.match(ping.error ?? "", /did not accept the key \(HTTP 401\).*ptlc_/);
|
||||
assert.match((await adapter.createFragnetAdapter({ token: "ptla_app", url }).ping()).error ?? "", /Application key \(ptla_\)/);
|
||||
keyOk = true;
|
||||
rateLimited = true;
|
||||
await assert.rejects(() => adapter.createFragnetAdapter({ token: "t", url }).read(), /too many requests/);
|
||||
rateLimited = false;
|
||||
assert.equal((await adapter.createFragnetAdapter({ token: "t", url }).ping()).ok, true);
|
||||
assert.equal((await adapter.createFragnetAdapter({ token: "t", url: "http://127.0.0.1:1" }).ping()).ok, false);
|
||||
});
|
||||
|
||||
test("a power signal is a POST of exactly that signal to that server; a busy server and an unknown one are said; nothing else is accepted", async () => {
|
||||
seen.length = 0;
|
||||
await adapter.createFragnetAdapter({ token: "t", url }).power("abcd1234", "restart");
|
||||
assert.deepEqual(seen.map((s) => [s.method, s.path, s.body]), [["POST", "/api/client/servers/abcd1234/power", JSON.stringify({ signal: "restart" })]]);
|
||||
powerStatus = 409;
|
||||
await assert.rejects(() => adapter.createFragnetAdapter({ token: "t", url }).power("abcd1234", "start"), /busy/);
|
||||
powerStatus = 204;
|
||||
await assert.rejects(() => adapter.createFragnetAdapter({ token: "t", url }).power("../../x", "start"), /isn't a server id/);
|
||||
await assert.rejects(() => adapter.createFragnetAdapter({ token: "t", url }).power("abcd1234", "format" as never), /isn't a power signal/);
|
||||
});
|
||||
|
||||
test("the panel address is optional: without it the panel is Fragnet's", () => {
|
||||
assert.equal(adapter.DEFAULT_URL, "https://panel.fragnet.net");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("what is carried between reads", () => {
|
||||
const t0 = new Date("2026-06-01T10:00:00Z");
|
||||
test("a server first seen starts its clocks now; the state's clock restarts only when the state changes", () => {
|
||||
const t1 = new Date(t0.getTime() + 5 * MIN);
|
||||
const t2 = new Date(t0.getTime() + 10 * MIN);
|
||||
const a = fn.carryTimes([server()], [], t0);
|
||||
assert.deepEqual([a[0].stateSince, a[0].firstSeenAt], [t0.toISOString(), t0.toISOString()]);
|
||||
const off = fn.carryTimes([server({ state: "offline" })], a, t1);
|
||||
assert.deepEqual([off[0].stateSince, off[0].firstSeenAt], [t1.toISOString(), t0.toISOString()]);
|
||||
const still = fn.carryTimes([server({ state: "offline" })], off, t2);
|
||||
assert.deepEqual([still[0].stateSince, still[0].firstSeenAt], [t1.toISOString(), t0.toISOString()]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("what is wrong", () => {
|
||||
const NOW = Date.parse("2026-06-10T12:00:00Z");
|
||||
const opts = (extra: Partial<import("../src/services/fragnetSync.js").FragnetOptions> = {}) => ({ ...fn.optionsOf(null), ...extra });
|
||||
const stored = (extra: Partial<Srv> = {}, times: Partial<import("../src/services/fragnetSync.js").StoredServer> = {}) => ({ ...server(extra), stateSince: iso(NOW - HOUR), firstSeenAt: iso(NOW - 30 * DAY), ...times });
|
||||
const keys = (list: ReturnType<typeof fn.fragnetProblems>) => list.map((p) => `${p.key}=${p.severity}`);
|
||||
const problems = (s: ReturnType<typeof stored>, o = opts()) => fn.fragnetProblems(1, "Fragnet", [s], NOW, o);
|
||||
|
||||
test("a server that is well says nothing, and one that is stopped is not an alert", () => {
|
||||
assert.deepEqual(problems(stored({ backups: [okBackup(DAY, {}, NOW)] })), []);
|
||||
assert.deepEqual(problems(stored({ state: "offline", usage: { memoryBytes: 0, cpu: 0, diskBytes: 5 * GB, rxBytes: 0, txBytes: 0, uptimeMs: 0 }, backups: [okBackup(DAY, {}, NOW)] })), []);
|
||||
});
|
||||
|
||||
describe("backups", () => {
|
||||
test("recent is fine; older than the limit is a warning that says how old; none for a server known for long is a warning", () => {
|
||||
assert.deepEqual(problems(stored({ backups: [okBackup(6 * DAY, {}, NOW)] })), []);
|
||||
const old = problems(stored({ backups: [okBackup(9 * DAY, {}, NOW)] }));
|
||||
assert.deepEqual(keys(old), ["fragnet-backup:1:abcd1234=warning"]);
|
||||
assert.match(old[0].message, /Fragnet: survival has no backup newer than 9 days — it should have one at least every 7 days/);
|
||||
assert.match(problems(stored({ backups: [] }))[0].message, /survival has no backup — it should/);
|
||||
});
|
||||
|
||||
test("a backup that failed does not count, and the message says the newest attempt failed", () => {
|
||||
const p = problems(stored({ backups: [okBackup(HOUR, { successful: false }, NOW), okBackup(9 * DAY, {}, NOW)] }));
|
||||
assert.match(p[0].message, /no backup newer than 9 days \(the newest attempt failed\)/);
|
||||
assert.deepEqual(problems(stored({ backups: [okBackup(HOUR, { successful: false }, NOW), okBackup(2 * DAY, {}, NOW)] })), []);
|
||||
});
|
||||
|
||||
test("a backup still being made does not count either way", () => {
|
||||
const making = okBackup(0, { completedAt: null, successful: false }, NOW);
|
||||
assert.deepEqual(problems(stored({ backups: [making, okBackup(DAY, {}, NOW)] })), []);
|
||||
assert.match(problems(stored({ backups: [making] }))[0].message, /has no backup/);
|
||||
});
|
||||
|
||||
test("a server this app has only just met has had no time; the limit is the setting, 0 turns it off; a list that could not be read, a plan without backups, a name left out, and a server in no state to judge say nothing", () => {
|
||||
assert.deepEqual(problems(stored({ backups: [] }, { firstSeenAt: iso(NOW - 2 * DAY) })), []);
|
||||
assert.deepEqual(problems(stored({ backups: [okBackup(9 * DAY, {}, NOW)] }), opts({ backupDays: 14 })), []);
|
||||
assert.deepEqual(problems(stored({ backups: [] }), opts({ backupDays: 0 })), []);
|
||||
assert.deepEqual(problems(stored({ backups: null })), []);
|
||||
assert.deepEqual(problems(stored({ backups: [], backupLimit: 0 })), []);
|
||||
assert.deepEqual(problems(stored({ backups: [] }), opts({ ignoreBackups: ["survival"] })), []);
|
||||
assert.deepEqual(problems(stored({ backups: [], suspended: true })), []);
|
||||
assert.deepEqual(problems(stored({ backups: [], installing: true })), []);
|
||||
});
|
||||
});
|
||||
|
||||
describe("disk and memory", () => {
|
||||
const use = (diskGb: number, memGb: number) => ({ memoryBytes: memGb * GB, cpu: 10, diskBytes: diskGb * GB, rxBytes: 0, txBytes: 0, uptimeMs: HOUR });
|
||||
const fine = [okBackup(DAY, {}, NOW)];
|
||||
test("disk: a warning from 90% of its limit, critical from 98%, in the units the page shows", () => {
|
||||
assert.deepEqual(problems(stored({ backups: fine, usage: use(17, 1) })), []);
|
||||
const warn = problems(stored({ backups: fine, usage: use(18.5, 1) }));
|
||||
assert.deepEqual(keys(warn), ["fragnet-disk:1:abcd1234=warning"]);
|
||||
assert.match(warn[0].message, /survival has used 18\.5 GB of its 20\.0 GB disk \(92%\)/);
|
||||
assert.deepEqual(keys(problems(stored({ backups: fine, usage: use(19.8, 1) }))), ["fragnet-disk:1:abcd1234=critical"]);
|
||||
});
|
||||
test("memory: judged only while it runs; no limit (0) and no reading say nothing", () => {
|
||||
assert.deepEqual(keys(problems(stored({ backups: fine, usage: use(1, 3.7) }))), ["fragnet-memory:1:abcd1234=warning"]);
|
||||
assert.match(problems(stored({ backups: fine, usage: use(1, 3.7) }))[0].message, /using 3.7 GB of its 4\.0 GB memory \(92%\)/);
|
||||
assert.deepEqual(problems(stored({ backups: fine, state: "offline", usage: use(1, 3.7) })), []);
|
||||
assert.deepEqual(problems(stored({ backups: fine, memoryLimitMb: 0, diskLimitMb: 0, usage: use(500, 500) })), []);
|
||||
assert.deepEqual(problems(stored({ backups: fine, usage: null })), []);
|
||||
});
|
||||
test("the limit is the setting", () => {
|
||||
assert.deepEqual(problems(stored({ backups: fine, usage: use(15, 1) }), opts({ fullPercent: 70 })).map((p) => p.key), ["fragnet-disk:1:abcd1234"]);
|
||||
});
|
||||
});
|
||||
|
||||
test("the settings: what is given is used, nonsense falls back to the defaults, names are compared without regard to case", () => {
|
||||
assert.deepEqual({ ...fn.optionsOf(null) }, { backupDays: 7, fullPercent: 90, ignoreBackups: [] });
|
||||
assert.deepEqual({ ...fn.optionsOf({ backupDays: "3", fullPercent: "85,5", ignoreBackups: "Test, Rust\nBuild" }) }, { backupDays: 3, fullPercent: 85.5, ignoreBackups: ["test", "rust", "build"] });
|
||||
assert.deepEqual({ ...fn.optionsOf({ backupDays: "0", fullPercent: "x" }) }, { backupDays: 0, fullPercent: 90, ignoreBackups: [] });
|
||||
assert.deepEqual({ ...fn.optionsOf({ backupDays: "-4" }) }, { backupDays: 7, fullPercent: 90, ignoreBackups: [] });
|
||||
});
|
||||
});
|
||||
|
||||
describe("what is stored", () => {
|
||||
let id = 0;
|
||||
before(async () => {
|
||||
id = (await db.insert(integrations).values({ type: "fragnet", name: "Account", baseUrl: "https://panel.fragnet.net", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
|
||||
});
|
||||
const row = async () => (await db.select().from(fragnetState).where(eq(fragnetState.integrationId, id)))[0];
|
||||
after(async () => {
|
||||
await fn.forgetFragnet(id);
|
||||
await db.delete(integrations).where(eq(integrations.id, id));
|
||||
});
|
||||
|
||||
test("the state is replaced at each read, carrying what was seen between them", async () => {
|
||||
const t0 = new Date();
|
||||
await fn.storeRead(id, read(server()), t0);
|
||||
await fn.storeRead(id, read(server({ state: "offline" })), new Date(t0.getTime() + 5 * MIN));
|
||||
const [s] = fn.serversOf(await row());
|
||||
assert.deepEqual([s.state, s.firstSeenAt, s.stateSince], ["offline", t0.toISOString(), new Date(t0.getTime() + 5 * MIN).toISOString()]);
|
||||
});
|
||||
|
||||
test("a read that failed is said, and what was stored is left alone", async () => {
|
||||
const ok = await fn.syncFragnet(id, new Date(), async () => read(server({ name: "kept" })));
|
||||
assert.equal(ok.ok, true);
|
||||
const failed = await fn.syncFragnet(id, new Date(), async () => {
|
||||
throw new Error("connection refused");
|
||||
});
|
||||
assert.deepEqual([failed.ok, failed.error], [false, "connection refused"]);
|
||||
assert.equal(failed.at, ok.at);
|
||||
assert.equal(fn.serversOf(await row())[0].name, "kept");
|
||||
assert.equal(fn.isFragnetFresh((await fn.fragnetSyncStatuses())[id], Date.now()), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the health pass, the page, the power signals and /metrics", () => {
|
||||
let fgId = 0;
|
||||
let app: Server;
|
||||
let panel: Server;
|
||||
let base = "";
|
||||
const signals: string[] = [];
|
||||
const fresh = () => setInternalFlag("fragnetSync", JSON.stringify({ [fgId]: { at: new Date().toISOString(), ok: true, error: null } }));
|
||||
const stale = () => setInternalFlag("fragnetSync", JSON.stringify({ [fgId]: { at: new Date(Date.now() - 30 * MIN).toISOString(), ok: true, error: null } }));
|
||||
const as = (sub: string) => ({ headers: { "x-sub": sub } });
|
||||
|
||||
before(async () => {
|
||||
await db.insert(users).values([{ oidcSub: "viewer", name: "Vic", role: "viewer" }, { oidcSub: "operator", name: "Olle", role: "operator" }]);
|
||||
// A panel that takes power signals.
|
||||
panel = createHttpServer((req, res) => {
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
signals.push(`${req.method} ${req.url} ${body}`);
|
||||
res.writeHead(204);
|
||||
res.end();
|
||||
});
|
||||
});
|
||||
await new Promise<void>((resolve) => panel.listen(0, "127.0.0.1", resolve));
|
||||
const panelUrl = `http://127.0.0.1:${(panel.address() as AddressInfo).port}`;
|
||||
fgId = (await db.insert(integrations).values({ type: "fragnet", name: "Fragnet account", baseUrl: panelUrl, config: JSON.stringify({ token: "ptlc_x", url: panelUrl, ignoreBackups: "scratch" }) }).returning({ id: integrations.id }))[0].id;
|
||||
const t0 = new Date(Date.now() - 3 * HOUR);
|
||||
const servers = read(
|
||||
// survival: running, disk nearly full, newest backup is old; rust: stopped, no backup but its name is left out; modded: fine.
|
||||
server({ backups: [okBackup(10 * DAY)], usage: { memoryBytes: GB, cpu: 5, diskBytes: 19.9 * GB, rxBytes: 0, txBytes: 0, uptimeMs: HOUR } }),
|
||||
server({ id: "eeee5555", name: "scratch", game: "Rust", state: "offline", backups: [], allocations: [{ ip: "203.0.113.21", alias: "rust.example", port: 28015, isDefault: true, notes: null }] }),
|
||||
server({ id: "ffff6666", name: "modded", game: "Valheim", backups: [okBackup(HOUR)] }),
|
||||
);
|
||||
await fn.storeRead(fgId, servers, t0);
|
||||
await fn.storeRead(fgId, servers, new Date());
|
||||
await fresh();
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: String(req.headers["x-sub"] ?? "viewer") } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/fragnet", fragnetRouter);
|
||||
app = await new Promise<Server>((resolve) => {
|
||||
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/fragnet`;
|
||||
});
|
||||
after(() => {
|
||||
app.close();
|
||||
panel.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("the health pass judges it from what is stored (with the integration's own settings), and holds it when the last read is old", async () => {
|
||||
let { snapshot, held } = await collectSnapshot();
|
||||
assert.deepEqual(snapshot.fragnet?.map((f) => f.integrationId), [fgId]);
|
||||
const list = evaluateHealth(snapshot, { serverOfflineMinutes: 60, diskUsagePercent: 90 }, Date.now(), { skipServers: true });
|
||||
const mine = list.filter((x) => x.key.startsWith("fragnet-")).map((x) => `${x.key}=${x.severity}`).sort();
|
||||
assert.deepEqual(mine, [`fragnet-backup:${fgId}:abcd1234=warning`, `fragnet-disk:${fgId}:abcd1234=critical`].sort(), "scratch is left out of the backups by name; modded is fine");
|
||||
assert.equal(list.find((x) => x.key === `fragnet-disk:${fgId}:abcd1234`)!.source, `fragnet:${fgId}`);
|
||||
for (const k of ["disk", "memory", "backup"]) assert.equal(subjectOfConditionKey(`fragnet-${k}:${fgId}:abcd1234`), `integration:${fgId}`, "maintenance on the integration silences its alerts");
|
||||
await stale();
|
||||
({ snapshot, held } = await collectSnapshot());
|
||||
assert.deepEqual([snapshot.fragnet ?? [], held.has(`fragnet:${fgId}`)], [[], true]);
|
||||
await fresh();
|
||||
});
|
||||
|
||||
test("the Alerts page shows them with where to look: the disk under Disk, the backup under Backups", async () => {
|
||||
invalidateAlertsCache();
|
||||
const report = await getAlerts(true);
|
||||
const find = (kind: string) => report.alerts.find((x) => x.id.endsWith(`fragnet-${kind}:${fgId}:abcd1234`))!;
|
||||
assert.deepEqual([find("disk").category, find("disk").source, find("disk").link, find("disk").target?.type], ["disk", "Fragnet", "/game-servers", "integration"]);
|
||||
assert.equal(find("backup").category, "backup");
|
||||
});
|
||||
|
||||
test("the page: each game server with its game, addresses, use, backups and what is wrong; an old reading says nothing is wrong", async () => {
|
||||
const body = (await (await fetch(base)).json()) as { accounts: { id: number; fresh: boolean; problems: { key: string }[]; options: { ignoreBackups: string[] }; state: { servers: { name: string; game: string; allocations: { ip: string; port: number }[]; newestBackup: { at: string | null } | null }[] } }[] };
|
||||
const a = body.accounts.find((x) => x.id === fgId)!;
|
||||
assert.equal(a.fresh, true);
|
||||
assert.deepEqual(a.state.servers.map((s) => [s.name, s.game, `${s.allocations[0].ip}:${s.allocations[0].port}`]), [["survival", "Minecraft: Paper", "203.0.113.20:25565"], ["scratch", "Rust", "203.0.113.21:28015"], ["modded", "Valheim", "203.0.113.20:25565"]]);
|
||||
assert.equal(a.state.servers[0].newestBackup?.at !== null, true);
|
||||
assert.equal(a.state.servers[1].newestBackup?.at, null);
|
||||
assert.deepEqual(a.options.ignoreBackups, ["scratch"]);
|
||||
assert.equal(a.problems.length, 2);
|
||||
await stale();
|
||||
const old = (await (await fetch(base)).json()) as typeof body;
|
||||
assert.deepEqual(old.accounts.find((x) => x.id === fgId)!.problems, []);
|
||||
await fresh();
|
||||
});
|
||||
|
||||
test("a power signal: an operator may, a viewer may not; it goes to the panel as that signal for that server, and is written in the audit log", async () => {
|
||||
const post = (sub: string, server: string, signal: unknown) => fetch(`${base}/${fgId}/servers/${server}/power`, { method: "POST", headers: { "content-type": "application/json", "x-sub": sub }, body: JSON.stringify({ signal }) });
|
||||
assert.equal((await post("viewer", "abcd1234", "restart")).status, 403);
|
||||
assert.deepEqual(signals, []);
|
||||
assert.equal((await post("operator", "abcd1234", "restart")).status, 204);
|
||||
assert.deepEqual(signals, [`POST /api/client/servers/abcd1234/power ${JSON.stringify({ signal: "restart" })}`]);
|
||||
const [entry] = (await db.select().from(auditLog)).filter((e) => e.action === "restart_game_server");
|
||||
assert.deepEqual([entry.category, entry.targetType, entry.targetId], ["integration", "fragnet_server", "abcd1234"]);
|
||||
assert.match(entry.detail ?? "", /survival/);
|
||||
});
|
||||
|
||||
test("only a server the last read found, and only a real signal, are accepted — nothing typed in the address reaches the panel", async () => {
|
||||
const post = (server: string, signal: unknown) => fetch(`${base}/${fgId}/servers/${server}/power`, { method: "POST", headers: { "content-type": "application/json", "x-sub": "operator" }, body: JSON.stringify({ signal }) });
|
||||
signals.length = 0;
|
||||
assert.equal((await post("zzzz9999", "start")).status, 404, "a well-formed id the panel account does not have");
|
||||
assert.equal((await post("..%2F..%2Fx", "start")).status, 400);
|
||||
assert.equal((await post("abcd1234", "format")).status, 400);
|
||||
assert.equal((await post("abcd1234", undefined)).status, 400);
|
||||
assert.equal((await fetch(`${base}/999999/servers/abcd1234/power`, { method: "POST", headers: { "content-type": "application/json", "x-sub": "operator" }, body: JSON.stringify({ signal: "start" }) })).status, 404);
|
||||
assert.deepEqual(signals, []);
|
||||
});
|
||||
|
||||
test("a row of another kind does not crash the server", async () => {
|
||||
const other = (await db.insert(integrations).values({ type: "hetzner", name: "Other", baseUrl: "https://api.hetzner.cloud", config: JSON.stringify({}) }).returning({ id: integrations.id }))[0].id;
|
||||
const res = await fetch(`${base}/${other}/servers/abcd1234/power`, { method: "POST", headers: { "content-type": "application/json", "x-sub": "operator" }, body: JSON.stringify({ signal: "start" }) });
|
||||
assert.equal(res.status, 400);
|
||||
assert.equal((await fetch(`${base}/${other}/refresh`, { method: "POST", ...as("operator") })).status, 400);
|
||||
await db.delete(integrations).where(eq(integrations.id, other));
|
||||
});
|
||||
|
||||
test("/metrics has whether each server runs, its disk and memory against the limits and when it was last backed up — only while the reading is recent", async () => {
|
||||
let text = await buildMetrics(new Date());
|
||||
assert.match(text, /homelab_fragnet_server_running\{account="Fragnet account",server="survival",game="Minecraft: Paper"\} 1/);
|
||||
assert.match(text, /homelab_fragnet_server_running\{account="Fragnet account",server="scratch",game="Rust"\} 0/);
|
||||
assert.match(text, /homelab_fragnet_disk_limit_bytes\{[^}]*server="survival"[^}]*\} 21474836480/);
|
||||
assert.match(text, /homelab_fragnet_newest_backup_timestamp_seconds\{[^}]*server="modded"[^}]*\} \d/);
|
||||
await stale();
|
||||
text = await buildMetrics(new Date());
|
||||
assert.doesNotMatch(text, /homelab_fragnet/);
|
||||
await fresh();
|
||||
});
|
||||
|
||||
test("taking the integration away takes what was read with it", async () => {
|
||||
await fn.forgetFragnet(fgId);
|
||||
assert.equal((await fn.fragnetSyncStatuses())[fgId], undefined);
|
||||
await db.delete(integrations).where(eq(integrations.id, fgId));
|
||||
assert.deepEqual(await db.select().from(fragnetState).where(eq(fragnetState.integrationId, fgId)), []);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user