Files
Homelab-manager/server/src/routes/patchPlans.ts
T
bobbanandClaude Sonnet 5.5 e4f3a54189 Restart a server after its updates, and check that it came back
An update run can name a second Semaphore playbook that restarts the server
once the updates are in and it says a restart is due. The run keeps the
maintenance window up, follows the restart, waits for the server to report
again and checks from its uptime (or its restart flag clearing) that it did
start again. A server that only needs a restart has a Restart button on the
Updates page, and a patch plan can carry the restart playbook too.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:45:52 +01:00

208 lines
10 KiB
TypeScript

import { Router } from "express";
import { eq } from "drizzle-orm";
import { z } from "zod";
import { db } from "../db/client.js";
import { patchPlans, servers } from "../db/schema.js";
import { requireAuth, requireRole } from "../auth/middleware.js";
import { recordAudit } from "../services/audit.js";
import { isValidTimeZone } from "../services/maintenanceSchedules.js";
import { activeRunOf, cancelPlanRun, listPlanRuns, MAX_PLANS, parseItems, planDays, planOccurrences, planServerIds, planServers, planTags, PlanError, startPlanRun, type PlanRow, type PlanRunRow } from "../services/patchPlans.js";
import { InvalidTagError, normalizeTags, parseTags } from "../services/serverTags.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const patchPlansRouter = Router();
// Everyone signed in can see what is planned and how it went, like the Updates page. Making a plan is an administrator's (it will run on its own, at night);
// starting one now or stopping one that is running is an operator's, like an update run.
patchPlansRouter.use(requireAuth);
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const planSchema = z
.object({
name: z.string().trim().min(1).max(100),
enabled: z.boolean().default(true),
days: z.array(z.number().int().min(0).max(6)).min(1).max(7),
startTime: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/, "Use a time like 02:00"),
timezone: z.string().trim().min(1).max(60),
tags: z.array(z.string()).max(12).default([]),
serverIds: z.array(z.number().int().positive()).max(200).default([]),
integrationId: z.number().int().positive(),
projectId: z.number().int().positive(),
templateId: z.number().int().positive(),
templateName: z.string().trim().min(1).max(200),
limitFrom: z.enum(["name", "hostname"]).default("name"),
stopOnFailure: z.boolean().default(true),
onlyWithUpdates: z.boolean().default(true),
silenceDependents: z.boolean().default(true),
windowMinutes: z.number().int().min(15).max(480).default(90),
// A playbook that restarts a server that says a restart is due after its updates (all three or none).
restartProjectId: z.number().int().positive().nullable().default(null),
restartTemplateId: z.number().int().positive().nullable().default(null),
restartTemplateName: z.string().trim().min(1).max(200).nullable().default(null),
})
.refine((d) => (d.restartProjectId === null) === (d.restartTemplateId === null) && (d.restartTemplateId === null) === (d.restartTemplateName === null), { message: "The restart playbook needs its project, its template and its name — or none of them.", path: ["restartTemplateId"] })
.refine((d) => isValidTimeZone(d.timezone), { message: "That isn't a time zone the system knows (use a name like Europe/Stockholm).", path: ["timezone"] })
.refine((d) => d.tags.length > 0 || d.serverIds.length > 0, { message: "Choose which servers: give a tag, or name at least one server.", path: ["tags"] });
function valuesOf(d: z.infer<typeof planSchema>) {
return {
name: d.name,
enabled: d.enabled,
days: JSON.stringify([...new Set(d.days)].sort()),
startTime: d.startTime,
timezone: d.timezone,
tags: JSON.stringify(normalizeTags(d.tags)),
serverIds: JSON.stringify([...new Set(d.serverIds)]),
integrationId: d.integrationId,
projectId: d.projectId,
templateId: d.templateId,
templateName: d.templateName,
limitFrom: d.limitFrom,
stopOnFailure: d.stopOnFailure,
onlyWithUpdates: d.onlyWithUpdates,
silenceDependents: d.silenceDependents,
windowMinutes: d.windowMinutes,
restartProjectId: d.restartProjectId,
restartTemplateId: d.restartTemplateId,
restartTemplateName: d.restartTemplateName,
};
}
const shapeRun = (r: PlanRunRow) => ({
id: r.id,
planId: r.planId,
planName: r.planName,
trigger: r.trigger,
startedBy: r.startedBy,
status: r.status,
message: r.message,
startedAt: r.startedAt,
finishedAt: r.finishedAt,
items: parseItems(r.items).map(({ windowIds: _w, ...i }) => i),
});
async function shapePlan(p: PlanRow, all: { id: number; name: string; tags: string | null }[], now: Date) {
const covered = planServers(p, all);
const next = planOccurrences(p, now, new Date(now.getTime() + 15 * 86_400_000)).filter((o) => o.start.getTime() > now.getTime()).slice(0, 3);
const active = await activeRunOf(p.id);
return {
id: p.id,
name: p.name,
enabled: p.enabled,
days: planDays(p),
startTime: p.startTime,
timezone: p.timezone,
tags: planTags(p),
serverIds: planServerIds(p),
integrationId: p.integrationId,
projectId: p.projectId,
templateId: p.templateId,
templateName: p.templateName,
limitFrom: p.limitFrom,
stopOnFailure: p.stopOnFailure,
onlyWithUpdates: p.onlyWithUpdates,
silenceDependents: p.silenceDependents,
windowMinutes: p.windowMinutes,
restartProjectId: p.restartProjectId,
restartTemplateId: p.restartTemplateId,
restartTemplateName: p.restartTemplateName,
createdBy: p.createdBy,
servers: covered,
next: next.map((o) => o.start.toISOString()),
running: active !== null,
};
}
patchPlansRouter.get("/", asyncHandler(async (_req, res) => {
const now = new Date();
const rows = await db.select().from(patchPlans).orderBy(patchPlans.name);
const all = await db.select({ id: servers.id, name: servers.name, tags: servers.tags }).from(servers);
const tags = [...new Set(all.flatMap((s) => parseTags(s.tags)))].sort((a, b) => a.localeCompare(b, "sv"));
res.json({
plans: await Promise.all(rows.map((p) => shapePlan(p, all, now))),
runs: (await listPlanRuns({ limit: 15 })).map(shapeRun),
servers: all.map((s) => ({ id: s.id, name: s.name, tags: parseTags(s.tags) })).sort((a, b) => a.name.localeCompare(b.name)),
tags,
});
}));
/** The message for a rejected body, as a sentence. */
const reason = (parsed: { error: z.ZodError }) => parsed.error.issues[0]?.message ?? "That isn't a plan.";
patchPlansRouter.post("/", requireRole("admin"), asyncHandler(async (req, res) => {
const parsed = planSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: reason(parsed), details: parsed.error.flatten() });
if ((await db.select({ id: patchPlans.id }).from(patchPlans)).length >= MAX_PLANS) return res.status(409).json({ error: "too_many", message: `At most ${MAX_PLANS} plans.` });
let values;
try {
values = valuesOf(parsed.data);
} catch (err) {
if (err instanceof InvalidTagError) return res.status(400).json({ error: "invalid_tag", message: err.message });
throw err;
}
const actor = req.currentUser!;
const [row] = await db.insert(patchPlans).values({ ...values, createdBy: actor.name ?? actor.email ?? actor.oidcSub }).returning();
await recordAudit({ actor, category: "patch_plan", action: "create", targetType: "patch_plan", targetId: row.id, detail: { name: row.name, days: planDays(row), time: row.startTime } });
res.status(201).json({ plan: await shapePlan(row, await db.select({ id: servers.id, name: servers.name, tags: servers.tags }).from(servers), new Date()) });
}));
patchPlansRouter.put("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
const parsed = planSchema.safeParse(req.body);
if (!Number.isInteger(id) || !parsed.success) return res.status(400).json({ error: "invalid_body", message: parsed.success ? "That isn't a plan." : reason(parsed) });
const [before] = await db.select().from(patchPlans).where(eq(patchPlans.id, id)).limit(1);
if (!before) return res.status(404).json({ error: "not_found" });
let values;
try {
values = valuesOf(parsed.data);
} catch (err) {
if (err instanceof InvalidTagError) return res.status(400).json({ error: "invalid_tag", message: err.message });
throw err;
}
// A changed day or time is a new schedule: what it last started on no longer says whether today's has happened.
const rescheduled = values.days !== before.days || values.startTime !== before.startTime || values.timezone !== before.timezone;
const [row] = await db.update(patchPlans).set({ ...values, ...(rescheduled ? { lastRunDate: null } : {}) }).where(eq(patchPlans.id, id)).returning();
await recordAudit({ actor: req.currentUser!, category: "patch_plan", action: "update", targetType: "patch_plan", targetId: id, detail: { name: row.name, days: planDays(row), time: row.startTime } });
res.json({ plan: await shapePlan(row, await db.select({ id: servers.id, name: servers.name, tags: servers.tags }).from(servers), new Date()) });
}));
patchPlansRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [before] = await db.select().from(patchPlans).where(eq(patchPlans.id, id)).limit(1);
if (!before) return res.status(404).json({ error: "not_found" });
if (await activeRunOf(id)) return res.status(409).json({ error: "running", message: "It is running now. Stop the run first." });
await db.delete(patchPlans).where(eq(patchPlans.id, id));
await recordAudit({ actor: req.currentUser!, category: "patch_plan", action: "delete", targetType: "patch_plan", targetId: id, detail: { name: before.name } });
res.status(204).end();
}));
// Run it now, instead of at its time (it still starts again at its time).
patchPlansRouter.post("/:id/run", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const actor = req.currentUser!;
try {
const run = await startPlanRun(id, { trigger: "manual", actor: actor.name ?? actor.email ?? actor.oidcSub });
res.status(201).json({ run: shapeRun(run) });
} catch (err) {
if (err instanceof PlanError) return res.status(err.status).json({ error: err.code, message: err.message });
throw err;
}
}));
patchPlansRouter.post("/runs/:id/cancel", requireRole("operator"), asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const actor = req.currentUser!;
try {
const run = await cancelPlanRun(id, actor.name ?? actor.email ?? actor.oidcSub);
if (!run) return res.status(404).json({ error: "not_found" });
res.json({ run: shapeRun(run) });
} catch (err) {
if (err instanceof PlanError) return res.status(err.status).json({ error: err.code, message: err.message });
throw err;
}
}));