import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { Cron } from "croner"; import { log } from "./log"; import { Settings } from "./settings"; import { ValidationError } from "./util-server"; const exec = promisify(execFile); const kinds = [ "images", "volumes" ] as const; type Kind = typeof kinds[number]; const defaults = { enabled: false, time: "04:00", timezone: "UTC" }; type Schedule = typeof defaults; function resourceKind(value: unknown): Kind { if (value !== "images" && value !== "volumes") { throw new ValidationError("resourceInvalidSelection"); } return value; } function validSchedule(value: unknown): value is Schedule { const schedule = value as Partial | null; if (typeof schedule?.enabled !== "boolean" || typeof schedule.time !== "string" || !/^([01]\d|2[0-3]):[0-5]\d$/.test(schedule.time) || typeof schedule.timezone !== "string" || !/^[A-Za-z][A-Za-z0-9_+/-]{0,99}$/.test(schedule.timezone)) { return false; } try { new Intl.DateTimeFormat("en-CA", { timeZone: schedule.timezone }); return true; } catch { return false; } } export class ResourceCleanup { private readonly jobs = new Map(); private readonly running = new Set(); private readonly saving = new Set(); private readonly shutdown = new AbortController(); private initialization?: Promise; start() { this.initialization ??= this.initialize(); } stop() { this.shutdown.abort(); this.jobs.forEach(job => job.stop()); } private async initialize() { for (const kind of kinds) { try { this.schedule(kind, await this.read(kind)); } catch { log.warn("resource-cleanup", `Could not load ${kind} schedule`); } } } private async read(kind: Kind): Promise { const value = await Settings.get(`resourceCleanup:${kind}`, false); return validSchedule(value) ? value : { ...defaults }; } async status(value: unknown) { const kind = resourceKind(value); await this.initialization; const schedule = await this.read(kind); return { ...schedule, nextRun: this.jobs.get(kind)?.nextRun()?.toISOString(), lastRun: await Settings.get(`resourceCleanupRun:${kind}`, false) || null, }; } async set(value: unknown, schedule: unknown) { const kind = resourceKind(value); await this.initialization; if (!validSchedule(schedule)) { throw new ValidationError("resourceCleanupInvalidSchedule"); } if (this.saving.has(kind)) { throw new ValidationError("resourceCleanupBusy"); } this.saving.add(kind); try { const { enabled, time, timezone } = schedule; await Settings.set(`resourceCleanup:${kind}`, { enabled, time, timezone }); this.schedule(kind, schedule); return await this.status(kind); } finally { this.saving.delete(kind); } } private schedule(kind: Kind, schedule: Schedule) { this.jobs.get(kind)?.stop(); this.jobs.delete(kind); if (!schedule.enabled || this.shutdown.signal.aborted) { return; } const [ hours, minutes ] = schedule.time.split(":").map(Number); const job = new Cron(`${minutes} ${hours} * * *`, { timezone: schedule.timezone, protect: true, }, () => this.runScheduled(kind, schedule, job)); this.jobs.set(kind, job); } private async runScheduled(kind: Kind, schedule: Schedule, job: Cron) { const date = new Date(); const day = date.toLocaleDateString("en-CA", { timeZone: schedule.timezone }); const key = `resourceCleanupRun:${kind}`; try { const previous = await Settings.get(key, false); const current = await this.read(kind); if (this.jobs.get(kind) !== job || previous?.day === day || !current.enabled || current.time !== schedule.time || current.timezone !== schedule.timezone || this.shutdown.signal.aborted) { return; } await Settings.set(key, { at: date.toISOString(), day, result: "started" }); let result = "success"; try { await this.prune(kind); } catch { result = "failed"; } if (!this.shutdown.signal.aborted) { await Settings.set(key, { at: date.toISOString(), day, result }); log.info("resource-cleanup", `${kind}: ${result}`); } } catch { log.warn("resource-cleanup", `Could not run ${kind} schedule`); } } async prune(value: unknown) { const kind = resourceKind(value); if (this.running.has(kind) || this.shutdown.signal.aborted) { throw new ValidationError("resourceCleanupBusy"); } this.running.add(kind); try { // The Docker daemon determines which resources are currently unreferenced. await exec("docker", [ kind === "images" ? "image" : "volume", "prune", "--all", "--force" ], { timeout: 120000, maxBuffer: 8 * 1024 * 1024, signal: this.shutdown.signal, windowsHide: true, }); } finally { this.running.delete(kind); } } }