All checks were successful
Docker image / publish (push) Successful in 59s
Update the shadcn preset and visual Compose editor. Add deployment previews, history, attention notices, and cleanup safeguards. Use the supplied icon in the app header and authentication screens.
340 lines
14 KiB
TypeScript
340 lines
14 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
import { execFile } from "node:child_process";
|
|
import { promises as fs } from "node:fs";
|
|
import path from "node:path";
|
|
import { promisify } from "node:util";
|
|
import { Cron } from "croner";
|
|
import dotenv from "dotenv";
|
|
import yaml from "yaml";
|
|
import { envsubstYAML } from "../common/util-common";
|
|
import type { DockgeServer } from "./dockge-server";
|
|
import { log } from "./log";
|
|
import { Settings } from "./settings";
|
|
import { Stack } from "./stack";
|
|
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",
|
|
minAgeHours: 0,
|
|
excludes: [] as string[] };
|
|
type Schedule = typeof defaults;
|
|
type Resource = { id: string; name: string; tags?: string[]; created: string | null; size?: number | null; driver?: string; reason?: string };
|
|
|
|
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<Schedule> | 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;
|
|
}
|
|
if (!Number.isSafeInteger(schedule.minAgeHours) || schedule.minAgeHours! < 0 || schedule.minAgeHours! > 87600
|
|
|| !Array.isArray(schedule.excludes) || schedule.excludes.length > 200
|
|
|| schedule.excludes.some(item => typeof item !== "string" || !item.trim() || item.length > 512 || /[\r\n\0]/.test(item))) {
|
|
return false;
|
|
}
|
|
try {
|
|
new Intl.DateTimeFormat("en-CA", { timeZone: schedule.timezone });
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
export class ResourceCleanup {
|
|
private readonly jobs = new Map<Kind, Cron>();
|
|
private readonly running = new Set<Kind>();
|
|
private readonly saving = new Set<Kind>();
|
|
private readonly shutdown = new AbortController();
|
|
private initialization?: Promise<void>;
|
|
private readonly previews = new Map<string, { kind: Kind; expires: number; resources: Set<string> }>();
|
|
|
|
constructor(private readonly server: DockgeServer) {}
|
|
|
|
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<Schedule> {
|
|
const value = await Settings.get(`resourceCleanup:${kind}`, false);
|
|
const schedule = { ...defaults,
|
|
...value };
|
|
return validSchedule(schedule) ? schedule : { ...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, minAgeHours, excludes } = schedule;
|
|
await Settings.set(`resourceCleanup:${kind}`, { enabled,
|
|
time,
|
|
timezone,
|
|
minAgeHours,
|
|
excludes: Array.from(new Set(excludes.map(item => item.trim()))) });
|
|
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 {
|
|
const result = await this.prune(kind, undefined, true);
|
|
if (result.failed) {
|
|
throw new Error("Could not remove some resources");
|
|
}
|
|
} 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 preview(value: unknown) {
|
|
const kind = resourceKind(value);
|
|
const items = await this.inventory(kind);
|
|
const id = randomUUID();
|
|
const now = Date.now();
|
|
for (const [ key, preview ] of this.previews) {
|
|
if (preview.expires <= now) {
|
|
this.previews.delete(key);
|
|
}
|
|
}
|
|
if (this.previews.size >= 24) {
|
|
this.previews.delete(this.previews.keys().next().value!);
|
|
}
|
|
this.previews.set(id, { kind,
|
|
expires: now + 5 * 60 * 1000,
|
|
resources: new Set(items.filter(item => !item.reason).map(item => this.resourceKey(item))) });
|
|
return { id,
|
|
items };
|
|
}
|
|
|
|
private resourceKey(item: Resource) {
|
|
return JSON.stringify([ item.id, item.created ]);
|
|
}
|
|
|
|
private async inventory(kind: Kind): Promise<Resource[]> {
|
|
const schedule = await this.read(kind);
|
|
const exclusions = new Set(schedule.excludes);
|
|
const now = Date.now();
|
|
const resources: Resource[] = [];
|
|
const protectedImages = this.server.stackDeployments.protectedImages();
|
|
if (kind === "images") {
|
|
const images = await this.server.dockerResources.listImages();
|
|
for (const item of images) {
|
|
if (!item.containers.length && !item.referenceOnly) {
|
|
resources.push({ id: item.id,
|
|
name: item.tags[0] || item.id,
|
|
tags: item.tags,
|
|
created: item.created,
|
|
size: item.size,
|
|
reason: protectedImages.has(item.id) ? "cleanupProtectedImage" : undefined });
|
|
}
|
|
}
|
|
} else {
|
|
const [ volumes, declarations ] = await Promise.all([ this.server.dockerResources.listVolumes(), this.volumeDeclarations() ]);
|
|
for (const item of volumes) {
|
|
if (!item.containers.length) {
|
|
const reason = declarations.names.has(item.name) ? "cleanupDeclaredVolume"
|
|
: declarations.unresolved.some(prefix => item.name.startsWith(prefix)) ? "cleanupUnresolvedVolume"
|
|
: item.driver !== "local" ? "cleanupExternalVolume" : undefined;
|
|
resources.push({ id: item.name,
|
|
name: item.name,
|
|
created: item.created,
|
|
driver: item.driver,
|
|
reason });
|
|
}
|
|
}
|
|
}
|
|
for (const item of resources) {
|
|
if (item.reason) {
|
|
continue;
|
|
}
|
|
if (exclusions.has(item.id) || item.tags?.some(tag => exclusions.has(tag))) {
|
|
item.reason = "cleanupExcluded";
|
|
} else if (schedule.minAgeHours && (!item.created || !Number.isFinite(Date.parse(item.created))
|
|
|| now - Date.parse(item.created) < schedule.minAgeHours * 3600000)) {
|
|
item.reason = "cleanupTooNew";
|
|
}
|
|
}
|
|
return resources.sort((a, b) => a.name.localeCompare(b.name));
|
|
}
|
|
|
|
private async volumeDeclarations() {
|
|
const names = new Set<string>();
|
|
const unresolved: string[] = [];
|
|
const directory = this.server.stacksDir;
|
|
const global = await fs.readFile(path.join(directory, "global.env"), "utf8").catch(() => "");
|
|
const entries = (await fs.readdir(directory, { withFileTypes: true }))
|
|
.filter(entry => entry.isDirectory() && /^[a-z0-9_-]+$/.test(entry.name));
|
|
const add = async (stack: Stack) => {
|
|
if (!stack.composeYAML) {
|
|
return;
|
|
}
|
|
try {
|
|
const args = stack.getComposeOptions("config", "--format", "json", "--no-env-resolution");
|
|
args.splice(1, 0, "--all-resources");
|
|
const { stdout } = await exec("docker", args, {
|
|
cwd: stack.fullPath,
|
|
timeout: 10000,
|
|
maxBuffer: 4 * 1024 * 1024,
|
|
signal: this.shutdown.signal,
|
|
windowsHide: true,
|
|
});
|
|
const config = JSON.parse(stdout);
|
|
for (const [ key, value ] of Object.entries(config.volumes || {})) {
|
|
const volume = value as { name?: string; external?: boolean } | null;
|
|
names.add(volume?.name || (volume?.external ? key : `${config.name || stack.name}_${key}`));
|
|
}
|
|
return;
|
|
} catch {
|
|
unresolved.push(stack.name + "_");
|
|
}
|
|
try {
|
|
const env = { ...dotenv.parse(global),
|
|
...dotenv.parse(stack.composeENV) };
|
|
const config = yaml.parse(envsubstYAML(stack.composeYAML, env), { merge: true });
|
|
const project = config?.name || env.COMPOSE_PROJECT_NAME || stack.name;
|
|
for (const [ key, value ] of Object.entries(config?.volumes || {})) {
|
|
const volume = value as { name?: string; external?: boolean | { name?: string } } | null;
|
|
const externalName = typeof volume?.external === "object" ? volume.external?.name : undefined;
|
|
names.add(volume?.name || externalName || (volume?.external ? key : `${project}_${key}`));
|
|
}
|
|
} catch {
|
|
// Keep the default project prefix if even the raw draft is invalid.
|
|
}
|
|
};
|
|
for (let index = 0; index < entries.length; index += 6) {
|
|
await Promise.all(entries.slice(index, index + 6).map(entry => add(new Stack(this.server, entry.name))));
|
|
}
|
|
return { names,
|
|
unresolved };
|
|
}
|
|
|
|
async prune(value: unknown, id?: unknown, scheduled = false) {
|
|
const kind = resourceKind(value);
|
|
if (this.running.has(kind) || this.shutdown.signal.aborted) {
|
|
throw new ValidationError("resourceCleanupBusy");
|
|
}
|
|
const approval = typeof id === "string" ? this.previews.get(id) : undefined;
|
|
if (!scheduled && (!approval || approval.kind !== kind || approval.expires <= Date.now())) {
|
|
throw new ValidationError("cleanupPreviewExpired");
|
|
}
|
|
if (typeof id === "string") {
|
|
this.previews.delete(id);
|
|
}
|
|
this.running.add(kind);
|
|
try {
|
|
const remove = async () => {
|
|
let removed = 0;
|
|
let failed = 0;
|
|
const items = await this.inventory(kind);
|
|
for (const item of items) {
|
|
if (this.shutdown.signal.aborted || item.reason || (approval && !approval.resources.has(this.resourceKey(item)))) {
|
|
continue;
|
|
}
|
|
try {
|
|
if (kind === "images") {
|
|
for (const tag of item.tags?.length ? item.tags : [ "" ]) {
|
|
await this.server.dockerResources.removeImage(item.id, tag);
|
|
}
|
|
} else {
|
|
await this.server.dockerResources.removeVolume(item.id, item.created);
|
|
}
|
|
removed++;
|
|
} catch {
|
|
failed++;
|
|
}
|
|
}
|
|
return { removed,
|
|
failed,
|
|
retained: Math.max(0, (approval?.resources.size ?? items.length) - removed - failed) };
|
|
};
|
|
return kind === "images" ? await this.server.stackDeployments.withImageChanges(remove) : await remove();
|
|
} finally {
|
|
this.running.delete(kind);
|
|
}
|
|
}
|
|
}
|