249 lines
11 KiB
TypeScript
249 lines
11 KiB
TypeScript
// PEP-287: the server's disk does not fill up by itself. Three sweeps of the watchdog:
|
||
// • `$PEPPA_HOME/sandboxes/s<id>` — the agent container's HOME (its conversation for --resume) —
|
||
// is removed once the session is over, its container is gone and the story is closed or archived
|
||
// (sessions without a story — a day after their end);
|
||
// • the docker build cache is pruned hourly down to `buildCacheGb` (never `-a`: with it the entries
|
||
// shared with images count too and the limit is not held; images, containers, volumes — untouched);
|
||
// • free space below `diskFreeAlertPct` — one message to the superadmins per episode.
|
||
import { execFile } from "node:child_process";
|
||
import { lstatSync, readdirSync, realpathSync, rmSync, statfsSync } from "node:fs";
|
||
import { join, sep } from "node:path";
|
||
import { promisify } from "node:util";
|
||
import { alertAdmins, deleteSetting, getProject, getSetting, logEvent, parseDockerPs, platformProjectKey, setSetting } from "@peppa/core";
|
||
import { sessions, tasks, type Db } from "@peppa/db";
|
||
import { peppaHome } from "@peppa/shared";
|
||
import { m } from "@peppa/shared/i18n";
|
||
import { eq } from "drizzle-orm";
|
||
import { getWatchdogSettings } from "./recovery.ts";
|
||
import { dockerBin } from "./sandbox.ts";
|
||
|
||
const run = promisify(execFile);
|
||
const off = () => process.env.PEPPA_DISK_CLEANUP === "off";
|
||
|
||
/** Folders removed in one pass — the rest wait for the next one. */
|
||
export const SANDBOX_MAX_PER_PASS = 20;
|
||
/** A finished session without a story (free runner, launch smoke) keeps its folder this long. */
|
||
export const SANDBOX_FREE_KEEP_MS = 24 * 3600_000;
|
||
const SANDBOX_EVERY_MS = 10 * 60_000;
|
||
const PRUNE_EVERY_MS = 3600_000;
|
||
/** The low-space episode ends only this many percent above the threshold (no flapping). */
|
||
const DISK_RECOVER_MARGIN = 2;
|
||
|
||
const DIR_RE = /^s(\d+)$/;
|
||
const sandboxesDir = () => join(peppaHome(), "sandboxes");
|
||
|
||
async function platformProjectId(db: Db): Promise<number | null> {
|
||
return (await getProject(db, platformProjectKey()).catch(() => null))?.id ?? null;
|
||
}
|
||
|
||
// ── agents' folders ────────────────────────────────────────────────────────────────
|
||
|
||
export interface SandboxRemoved {
|
||
sessionId: number;
|
||
reason: "task_closed" | "no_task" | "no_session";
|
||
}
|
||
|
||
let lastSandboxPass = 0;
|
||
|
||
/** Why the folder of this session may go, or null — it stays. */
|
||
async function sandboxVerdict(db: Db, sessionId: number, dir: string, now: number, running: Set<string>): Promise<SandboxRemoved["reason"] | null> {
|
||
if (running.has(`peppa-s${sessionId}`)) return null;
|
||
const [row] = await db
|
||
.select({ status: sessions.status, endedAt: sessions.endedAt, hostId: sessions.hostId, taskId: sessions.taskId, taskStatus: tasks.status, archivedAt: tasks.archivedAt })
|
||
.from(sessions)
|
||
.leftJoin(tasks, eq(tasks.id, sessions.taskId))
|
||
.where(eq(sessions.id, sessionId));
|
||
if (!row) {
|
||
// The row is gone (a deleted project): nothing can resume it; still, a day of quiet first.
|
||
return now - lstatSync(dir).mtimeMs >= SANDBOX_FREE_KEEP_MS ? "no_session" : null;
|
||
}
|
||
if (row.status !== "done" && row.status !== "failed") return null;
|
||
if (row.hostId != null) return null; // its HOME lives on the runner host — not ours to clean
|
||
if (row.taskId != null && row.taskStatus != null) {
|
||
// An open story may get the same conversation back — the folder holds it.
|
||
return row.taskStatus === "done" || row.archivedAt != null ? "task_closed" : null;
|
||
}
|
||
const ended = row.endedAt?.getTime() ?? lstatSync(dir).mtimeMs;
|
||
return now - ended >= SANDBOX_FREE_KEEP_MS ? "no_task" : null;
|
||
}
|
||
|
||
/** The folder is a real directory right inside `sandboxes` — never a link, never elsewhere. */
|
||
function safeSandboxDir(root: string, sessionId: number): string | null {
|
||
const dir = join(root, `s${sessionId}`);
|
||
try {
|
||
const st = lstatSync(dir);
|
||
if (!st.isDirectory() || st.isSymbolicLink()) return null;
|
||
const real = realpathSync(dir);
|
||
const realRoot = realpathSync(root);
|
||
return real === join(realRoot, `s${sessionId}`) && real.startsWith(realRoot + sep) ? dir : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
async function runningAgentContainers(): Promise<Set<string>> {
|
||
const { stdout } = await run(dockerBin(null), ["ps", "--no-trunc", "--format", "{{.ID}}\t{{.Names}}\t{{.Ports}}\t{{.Labels}}"], { timeout: 20_000, maxBuffer: 16 * 1024 * 1024 });
|
||
return new Set(parseDockerPs(stdout).map((c) => c.name));
|
||
}
|
||
|
||
/** Removes folders of finished sessions; every ten minutes unless `force`. */
|
||
export async function sandboxCleanupTick(db: Db, o: { now?: Date; log?: (m: string) => void; force?: boolean } = {}): Promise<SandboxRemoved[]> {
|
||
if (off()) return [];
|
||
const log = o.log ?? (() => {});
|
||
const now = (o.now ?? new Date()).getTime();
|
||
if (!o.force && now - lastSandboxPass < SANDBOX_EVERY_MS) return [];
|
||
lastSandboxPass = now;
|
||
const root = sandboxesDir();
|
||
let names: string[];
|
||
try {
|
||
names = readdirSync(root);
|
||
} catch {
|
||
return [];
|
||
}
|
||
const ids = names.map((n) => DIR_RE.exec(n)).filter((x): x is RegExpExecArray => !!x).map((x) => Number(x[1])).sort((a, b) => a - b);
|
||
if (!ids.length) return [];
|
||
let running: Set<string>;
|
||
try {
|
||
running = await runningAgentContainers();
|
||
} catch (e) {
|
||
log(`sandbox cleanup: docker ps: ${(e as Error).message.split("\n")[0]} — skipped`);
|
||
return [];
|
||
}
|
||
const removed: SandboxRemoved[] = [];
|
||
const pid = await platformProjectId(db);
|
||
for (const id of ids) {
|
||
if (removed.length >= SANDBOX_MAX_PER_PASS) break;
|
||
const dir = safeSandboxDir(root, id);
|
||
if (!dir) continue;
|
||
const reason = await sandboxVerdict(db, id, dir, now, running);
|
||
if (!reason) continue;
|
||
try {
|
||
rmSync(dir, { recursive: true, force: true });
|
||
} catch (e) {
|
||
log(`sandbox cleanup: s${id}: ${(e as Error).message}`);
|
||
continue;
|
||
}
|
||
removed.push({ sessionId: id, reason });
|
||
if (pid) await logEvent(db, { projectId: pid, type: "sandbox_removed", payload: { sessionId: id, reason, dir } });
|
||
}
|
||
if (removed.length) log(`sandbox cleanup: removed ${removed.length} (${removed.map((r) => `s${r.sessionId}`).join(", ")})`);
|
||
return removed;
|
||
}
|
||
|
||
// ── docker build cache ─────────────────────────────────────────────────────────────
|
||
|
||
const PRUNE_KEY = "disk.prune.last";
|
||
let pruneRunning: Promise<unknown> | null = null;
|
||
/** The client in the platform image (20.10) does not know `--reserved-space`; remembered per process. */
|
||
let oldClient = false;
|
||
|
||
export interface PruneResult {
|
||
args: string[];
|
||
reclaimed: string | null;
|
||
}
|
||
|
||
const reclaimedOf = (out: string) => /Total reclaimed space:\s*(.+)/i.exec(out)?.[1]?.trim() ?? null;
|
||
|
||
async function prune(gb: number): Promise<PruneResult> {
|
||
const bin = dockerBin(null);
|
||
const opts = { timeout: 30 * 60_000, maxBuffer: 64 * 1024 * 1024 };
|
||
if (!oldClient) {
|
||
const args = ["builder", "prune", "-f", "--reserved-space", `${gb}GB`];
|
||
try {
|
||
const { stdout } = await run(bin, args, opts);
|
||
return { args, reclaimed: reclaimedOf(stdout) };
|
||
} catch (e) {
|
||
const err = e as Error & { stderr?: string };
|
||
if (!/unknown flag|flag provided but not defined/i.test(`${err.stderr ?? ""}${err.message}`)) throw e;
|
||
oldClient = true;
|
||
}
|
||
}
|
||
const args = ["builder", "prune", "-f", "--keep-storage", `${gb}GB`];
|
||
const { stdout } = await run(bin, args, opts);
|
||
return { args, reclaimed: reclaimedOf(stdout) };
|
||
}
|
||
|
||
/** Hourly prune of the build cache down to the limit. Does not block the watchdog loop unless `wait`. */
|
||
export async function buildCachePruneTick(db: Db, o: { now?: Date; log?: (m: string) => void; wait?: boolean } = {}): Promise<PruneResult | null> {
|
||
if (off() || pruneRunning) return null;
|
||
const log = o.log ?? (() => {});
|
||
const now = o.now ?? new Date();
|
||
const { buildCacheGb } = await getWatchdogSettings(db);
|
||
if (!buildCacheGb) return null;
|
||
const last = await getSetting<string>(db, PRUNE_KEY);
|
||
if (last && now.getTime() - new Date(last).getTime() < PRUNE_EVERY_MS) return null;
|
||
await setSetting(db, PRUNE_KEY, now.toISOString());
|
||
const job = prune(buildCacheGb)
|
||
.then(async (r) => {
|
||
log(`build cache: ${r.args.join(" ")} — reclaimed ${r.reclaimed ?? "?"}`);
|
||
const pid = await platformProjectId(db);
|
||
if (pid) await logEvent(db, { projectId: pid, type: "build_cache_pruned", payload: { limitGb: buildCacheGb, flag: r.args[3], reclaimed: r.reclaimed } });
|
||
return r;
|
||
})
|
||
.finally(() => {
|
||
pruneRunning = null;
|
||
});
|
||
pruneRunning = job;
|
||
if (o.wait) return job;
|
||
job.catch((e) => log(`build cache prune failed: ${(e as Error).message.split("\n")[0]}`));
|
||
return null;
|
||
}
|
||
|
||
/** Tests: forget the per-process state. */
|
||
export function resetDiskCleanupState(): void {
|
||
lastSandboxPass = 0;
|
||
oldClient = false;
|
||
pruneRunning = null;
|
||
}
|
||
|
||
// ── free space ─────────────────────────────────────────────────────────────────────
|
||
|
||
const LOW_KEY = "disk.low";
|
||
export interface DiskSpace {
|
||
freeBytes: number;
|
||
totalBytes: number;
|
||
}
|
||
type StatFs = (path: string) => DiskSpace;
|
||
const realStatFs: StatFs = (path) => {
|
||
const s = statfsSync(path);
|
||
return { freeBytes: s.bavail * s.bsize, totalBytes: s.blocks * s.bsize };
|
||
};
|
||
|
||
const gb = (b: number) => Math.round(b / 1024 ** 3);
|
||
|
||
/** One message to the superadmins when free space of `$PEPPA_HOME`'s disk drops below the threshold. */
|
||
export async function diskSpaceTick(db: Db, o: { now?: Date; log?: (m: string) => void; statfs?: StatFs } = {}): Promise<"alerted" | "low" | "ok" | null> {
|
||
if (off()) return null;
|
||
const log = o.log ?? (() => {});
|
||
const { diskFreeAlertPct } = await getWatchdogSettings(db);
|
||
if (!diskFreeAlertPct) return null;
|
||
let d: DiskSpace;
|
||
try {
|
||
d = (o.statfs ?? realStatFs)(peppaHome());
|
||
} catch {
|
||
return null;
|
||
}
|
||
if (!d.totalBytes) return null;
|
||
const pct = Math.round((d.freeBytes / d.totalBytes) * 1000) / 10;
|
||
const low = await getSetting<{ since: string; pct: number }>(db, LOW_KEY);
|
||
if (pct < diskFreeAlertPct) {
|
||
if (low) return "low";
|
||
const since = (o.now ?? new Date()).toISOString();
|
||
await setSetting(db, LOW_KEY, { since, pct });
|
||
await alertAdmins(
|
||
db,
|
||
`disk:low:${since}`,
|
||
m("💾 На диске сервера свободно {pct}% ({free} из {total} ГБ) — меньше порога {limit}%. Папки агентов и кэш сборки FORGE убирает сама; посмотрите, что ещё занимает место.", {
|
||
pct,
|
||
free: gb(d.freeBytes),
|
||
total: gb(d.totalBytes),
|
||
limit: diskFreeAlertPct,
|
||
}),
|
||
log,
|
||
);
|
||
return "alerted";
|
||
}
|
||
if (low && pct >= diskFreeAlertPct + DISK_RECOVER_MARGIN) await deleteSetting(db, LOW_KEY);
|
||
return "ok";
|
||
}
|