Add Back up now for Fragnet game servers
Operators can ask the game panel for a backup of a server whose plan has room for backups (Back up on the row, Back up now beside its backups). The panel makes it in the background; the page re-reads every 20 s until it is done. Refused here for a plan with no room, a suspended server, one already being backed up, or the same server within 30 s; the panel's own refusals (plan full, rate limit, permission) are shown in its words. Written to the audit log. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
31f4debb9a
commit
f9991a49af
9 files changed
+326
-11
No files matched your search
@@ -6,7 +6,7 @@
|
||||
*
|
||||
* Reading: the servers of the account (`GET /api/client`, paged, with the game — the egg — and the addresses) and, for each, `…/resources` (running or not, memory, CPU, disk, uptime), `…/backups`,
|
||||
* `…/schedules` and `…/databases`. A part that cannot be read (a sub-user without that permission gets a 403) is null for that server, which is not the same as none. The only thing ever
|
||||
* written is a **power signal** (`POST …/power`: start, stop, restart or kill), and only when someone asks for it on the page.
|
||||
* written are a **power signal** (`POST …/power`: start, stop, restart or kill) and a **backup** (`POST …/backups`: make one now, with a name that says it was asked for here), each only when someone asks for it on the page.
|
||||
*
|
||||
* Endpoints and field names are from Pterodactyl's source (ServerTransformer, StatsTransformer, BackupTransformer, ScheduleTransformer) and the panel's own documentation (docs.fragnet.net),
|
||||
* not from a live account: Fragnet's fork may differ, so every field is read defensively. The panel allows a limited number of requests a minute (429); a pass makes four per server.
|
||||
@@ -114,6 +114,8 @@ export interface FragnetAdapter {
|
||||
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
|
||||
read(): Promise<FragnetRead>;
|
||||
power(serverId: string, signal: PowerSignal): Promise<void>;
|
||||
/** Asks the panel to make a backup now (it is made in the background: what comes back is the one being made, with no completion time yet). Throws what the panel says when it refuses. */
|
||||
backup(serverId: string, name: string): Promise<FragnetBackup | null>;
|
||||
}
|
||||
|
||||
const PER_PAGE = 50;
|
||||
@@ -229,6 +231,16 @@ export function parseBackups(raw: unknown): FragnetBackup[] {
|
||||
return out.sort((x, y) => (y.createdAt ?? "").localeCompare(x.createdAt ?? ""));
|
||||
}
|
||||
|
||||
/** Pure: what a refusing panel says in its own words — the first of its `errors`. */
|
||||
export function panelDetail(raw: unknown): string | null {
|
||||
return str(obj(arr(obj(raw).errors)[0]).detail);
|
||||
}
|
||||
|
||||
/** Pure: the backup a `POST …/backups` made, as the panel answers (one backup, not a list). */
|
||||
export function parseNewBackup(raw: unknown): FragnetBackup | null {
|
||||
return parseBackups({ data: [raw] })[0] ?? null;
|
||||
}
|
||||
|
||||
/** Pure: `…/schedules` — the tasks that run on their own (a restart every night, a backup every Sunday). */
|
||||
export function parseSchedules(raw: unknown): FragnetSchedule[] {
|
||||
const out: FragnetSchedule[] = [];
|
||||
@@ -343,6 +355,24 @@ export function createFragnetAdapter(config: FragnetConfig): FragnetAdapter {
|
||||
if (res.status < 200 || res.status >= 300) throw new Error(`The panel answered with an error: HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
async function backup(serverId: string, name: string): Promise<FragnetBackup | null> {
|
||||
if (!SERVER_ID.test(serverId)) throw new Error("That isn't a server id of the panel");
|
||||
const label = name.trim().slice(0, 100);
|
||||
if (label === "") throw new Error("A backup needs a name");
|
||||
const res = await requestJson(`${base}/servers/${serverId}/backups`, { method: "POST", headers, body: { name: label } });
|
||||
const said = panelDetail(res.json);
|
||||
if (res.status === 429) throw new Error("The panel only lets a few backups be made in a short while (HTTP 429) — try again in ten minutes");
|
||||
if (res.status === 401) throw refusal(401, true) as Error;
|
||||
// 403 here is this server's permission for the key's user (a sub-user), not a key the panel refuses.
|
||||
if (res.status === 403) throw new Error("The account may not make backups on this server (HTTP 403) — as a sub-user it needs the Backups → Create permission");
|
||||
if (res.status === 409) throw new Error("The panel says the server is busy (HTTP 409) — it is being installed, transferred or restored, or is suspended");
|
||||
if (res.status === 404) throw new Error("The panel does not know that server (HTTP 404)");
|
||||
// A server that is at the number of backups its plan allows is refused with a 400 that says so.
|
||||
if (res.status === 400) throw new Error(`The panel refused to make a backup: ${said ?? "HTTP 400"}`);
|
||||
if (res.status < 200 || res.status >= 300) throw new Error(`The panel answered with an error: HTTP ${res.status}${said ? ` — ${said}` : ""}`);
|
||||
return parseNewBackup(res.json);
|
||||
}
|
||||
|
||||
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
|
||||
const start = Date.now();
|
||||
try {
|
||||
@@ -355,5 +385,5 @@ export function createFragnetAdapter(config: FragnetConfig): FragnetAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
return withDiagLogging("fragnet", { ping, read, power });
|
||||
return withDiagLogging("fragnet", { ping, read, power, backup });
|
||||
}
|
||||
@@ -62,6 +62,60 @@ fragnetRouter.post("/:id/refresh", requireRole("operator"), asyncHandler(async (
|
||||
res.json({ status });
|
||||
}));
|
||||
|
||||
/** A server that has just been asked for a backup is not asked again for this long (the panel itself allows only two in ten minutes, and a double click must not use one up). */
|
||||
export const BACKUP_COOLDOWN_MS = 30_000;
|
||||
const lastBackupAsked = new Map<string, number>();
|
||||
/** A backup that has been "being made" for longer than this is taken to have failed or been lost, and no longer stops another being asked for. */
|
||||
const BACKUP_STALE_MS = 2 * 60 * 60_000;
|
||||
|
||||
/**
|
||||
* Asks the panel to make a backup of one game server now — before a risky change, say. Only a server the last read found can be backed up, as with a power signal. Refused here, before the panel is
|
||||
* asked, when its plan has no room for backups, or one is already being made. The backup is made by the panel in the background (the page reads again a little later to show it); a server at the number
|
||||
* of backups its plan allows is refused by the panel, which says so.
|
||||
*/
|
||||
fragnetRouter.post("/:id/servers/:server/backup", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
|
||||
const serverId = String(req.params.server);
|
||||
if (!SERVER_ID.test(serverId)) return res.status(400).json({ error: "invalid_server" });
|
||||
const loaded = await loadIntegrationConfig(id);
|
||||
if (!loaded) return res.status(404).json({ error: "not_found" });
|
||||
if (loaded.integration.type !== "fragnet") return res.status(400).json({ error: "wrong_type" });
|
||||
if (!loaded.integration.enabled) return res.status(400).json({ error: "integration_disabled" });
|
||||
const [state] = await db.select().from(fragnetState).where(eq(fragnetState.integrationId, id)).limit(1);
|
||||
const server = state ? serversOf(state).find((s) => s.id === serverId) : undefined;
|
||||
if (!server) return res.status(404).json({ error: "server_not_found" });
|
||||
if (!server.backupLimit) return res.status(400).json({ error: "no_backups_on_plan", message: `${server.name}'s plan has no room for backups.` });
|
||||
if (server.suspended || server.installing) return res.status(409).json({ error: "server_busy", message: `${server.name} is suspended or being installed.` });
|
||||
const now = Date.now();
|
||||
if ((server.backups ?? []).some((b) => b.completedAt === null && now - Date.parse(b.createdAt ?? "") < BACKUP_STALE_MS)) return res.status(409).json({ error: "already_being_made", message: `A backup of ${server.name} is already being made.` });
|
||||
const key = `${id}:${serverId}`;
|
||||
const before = lastBackupAsked.get(key);
|
||||
if (before !== undefined && now - before < BACKUP_COOLDOWN_MS) {
|
||||
const retryAfterSeconds = Math.ceil((BACKUP_COOLDOWN_MS - (now - before)) / 1000);
|
||||
return res.status(429).set("Retry-After", String(retryAfterSeconds)).json({ error: "too_soon", message: `A backup of ${server.name} was just asked for — try again in ${retryAfterSeconds} s.`, retryAfterSeconds });
|
||||
}
|
||||
lastBackupAsked.set(key, now);
|
||||
const name = `Homelab Manager — ${new Date(now).toISOString().slice(0, 16).replace("T", " ")} UTC`;
|
||||
let made;
|
||||
try {
|
||||
made = await createFragnetAdapter(loaded.config as never).backup(serverId, name);
|
||||
} catch (err) {
|
||||
// Nothing was made, so nothing is held against the next try.
|
||||
lastBackupAsked.delete(key);
|
||||
return res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
||||
}
|
||||
await recordAudit({
|
||||
actor: req.currentUser!,
|
||||
category: "integration",
|
||||
action: "backup_game_server",
|
||||
targetType: "fragnet_server",
|
||||
targetId: serverId,
|
||||
detail: { integrationId: id, name: server.name, game: server.game, backupName: name, backup: made?.uuid ?? null },
|
||||
});
|
||||
res.status(201).json({ name, uuid: made?.uuid ?? null });
|
||||
}));
|
||||
|
||||
/** Sends a power signal (start, stop, restart or kill) to one game server. Only a server the last read found can be signalled — what is typed in the address is never put into a call to the panel. */
|
||||
fragnetRouter.post("/:id/servers/:server/power", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const id = Number(req.params.id);
|
||||
|
||||
Reference in new issue
Block a user