Uptime Kuma often watches a host by another address than the one it was added with here (a Proxmox host monitored over Tailscale, say). Address aliases on the Maintenance page say that an address belongs to a server, integration or DNS provider, so the sync puts the window there; matching stays exact. Migration 0018 adds maintenance_aliases. Also fixes monitors whose empty hostname/URL/port arrive from Kuma's metrics as the text "null": they were taken as an address, hiding the real URL. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
258 lines
13 KiB
TypeScript
258 lines
13 KiB
TypeScript
import { Router } from "express";
|
|
import { and, eq } from "drizzle-orm";
|
|
import { z } from "zod";
|
|
import { db } from "../db/client.js";
|
|
import { dnsProviders, integrations, maintenanceAliases, maintenanceTargetTypes, maintenanceWindows, servers } from "../db/schema.js";
|
|
import { hostOfAddress } from "../services/kumaTargets.js";
|
|
import { requireAuth, requireRole } from "../auth/middleware.js";
|
|
import { recordAudit } from "../services/audit.js";
|
|
import { describeTarget, listActiveWindows, listUpcomingWindows, startOrExtendWindow } from "../services/maintenance.js";
|
|
import { KumaSyncError, syncKumaMaintenance } from "../services/kumaMaintenanceSync.js";
|
|
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
|
|
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
|
|
import { attachMatchedServers, toMatchableServers } from "../services/uptimeKumaMatch.js";
|
|
import { asyncHandler } from "../utils/asyncHandler.js";
|
|
|
|
export const maintenanceRouter = Router();
|
|
|
|
// Anyone signed in can see what's currently silenced (so nobody is surprised by missing alerts);
|
|
// starting and ending a window is an operator action, like the other things that change how the homelab behaves.
|
|
maintenanceRouter.use(requireAuth);
|
|
|
|
maintenanceRouter.get("/", asyncHandler(async (_req, res) => {
|
|
const describe = async (rows: Awaited<ReturnType<typeof listActiveWindows>>) => {
|
|
const out = [];
|
|
for (const w of rows) {
|
|
const target = await describeTarget(w.targetType, w.targetId);
|
|
if (!target) continue; // target was deleted — nothing left to silence
|
|
out.push({ ...w, targetName: target.name, targetKind: target.kind });
|
|
}
|
|
return out;
|
|
};
|
|
const windows = await describe(await listActiveWindows());
|
|
windows.sort((a, b) => a.endsAt.localeCompare(b.endsAt));
|
|
const upcoming = await describe(await listUpcomingWindows());
|
|
upcoming.sort((a, b) => a.startedAt.localeCompare(b.startedAt));
|
|
|
|
const [serverRows, integrationRows, providerRows] = await Promise.all([
|
|
db.select({ id: servers.id, name: servers.name }).from(servers).orderBy(servers.name),
|
|
db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).orderBy(integrations.name),
|
|
db.select({ id: dnsProviders.id, name: dnsProviders.name, providerType: dnsProviders.providerType }).from(dnsProviders).orderBy(dnsProviders.name),
|
|
]);
|
|
const aliases = [];
|
|
for (const a of await db.select().from(maintenanceAliases).orderBy(maintenanceAliases.address)) {
|
|
const target = await describeTarget(a.targetType, a.targetId);
|
|
if (!target) continue; // target was deleted — the alias has nothing left to point at
|
|
aliases.push({ id: a.id, address: a.address, targetType: a.targetType, targetId: a.targetId, targetName: target.name, targetKind: target.kind });
|
|
}
|
|
res.json({ windows, upcoming, aliases, targets: { servers: serverRows, integrations: integrationRows, dnsProviders: providerRows } });
|
|
}));
|
|
|
|
const startSchema = z.object({
|
|
targetType: z.enum(maintenanceTargetTypes),
|
|
targetId: z.number().int().positive(),
|
|
// Required and capped: an open-ended window is the way this feature could quietly hide a real outage.
|
|
minutes: z.number().int().min(5).max(7 * 24 * 60),
|
|
reason: z.string().max(200).optional(),
|
|
});
|
|
|
|
maintenanceRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => {
|
|
const parsed = startSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() });
|
|
}
|
|
const { targetType, targetId, minutes, reason } = parsed.data;
|
|
|
|
const actor = req.currentUser!;
|
|
const createdBy = actor.name ?? actor.email ?? actor.oidcSub;
|
|
// Starting maintenance on something already in maintenance restarts its clock rather than stacking windows.
|
|
const result = await startOrExtendWindow(targetType, targetId, minutes, reason ?? null, createdBy);
|
|
if (!result) {
|
|
return res.status(404).json({ error: "not_found", message: "That target doesn't exist." });
|
|
}
|
|
|
|
await recordAudit({
|
|
actor,
|
|
category: "maintenance",
|
|
action: result.extended ? "extend" : "start",
|
|
targetType,
|
|
targetId,
|
|
detail: { name: result.target.name, minutes, reason: reason ?? null },
|
|
});
|
|
|
|
res.status(201).json({ window: { ...result.window, targetName: result.target.name, targetKind: result.target.kind } });
|
|
}));
|
|
|
|
const importUptimeKumaSchema = z.object({
|
|
integrationId: z.number().int().positive(),
|
|
// Same bounds as a manual window: required and capped, so an import can't quietly create an open-ended one.
|
|
minutes: z.number().int().min(5).max(7 * 24 * 60),
|
|
});
|
|
|
|
/**
|
|
* Uptime Kuma has no scheduled-maintenance API to read (see the integration's own notes) — only each monitor's
|
|
* *current* status, which is "maintenance" for exactly as long as a window is active there. So rather than
|
|
* mirroring Kuma's schedule, this reads what's in maintenance right now and starts (or extends) a matching
|
|
* window here for that long, on whichever server the monitor's target matches. Re-running it while Kuma is
|
|
* still in maintenance just extends the same window rather than stacking a new one.
|
|
*/
|
|
maintenanceRouter.post("/import/uptimekuma", requireRole("operator"), asyncHandler(async (req, res) => {
|
|
const parsed = importUptimeKumaSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", message: "Choose an integration and a duration.", details: parsed.error.flatten() });
|
|
}
|
|
const { integrationId, minutes } = parsed.data;
|
|
|
|
const loaded = await loadIntegrationConfig(integrationId);
|
|
if (!loaded) return res.status(404).json({ error: "not_found", message: "That Uptime Kuma integration no longer exists." });
|
|
if (loaded.integration.type !== "uptimekuma") return res.status(400).json({ error: "wrong_type", message: "That integration isn't an Uptime Kuma one." });
|
|
if (!loaded.integration.enabled) return res.status(400).json({ error: "integration_disabled", message: "That integration is disabled. Enable it under Integrations first." });
|
|
|
|
let monitors;
|
|
try {
|
|
monitors = await createUptimeKumaAdapter(loaded.config as any).listMonitors();
|
|
} catch (err) {
|
|
const message = err instanceof Error ? err.message : String(err);
|
|
return res.status(502).json({ error: "uptimekuma_unreachable", message: `Couldn't read Uptime Kuma: ${message}` });
|
|
}
|
|
|
|
const serverRows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers);
|
|
const inMaintenance = attachMatchedServers(monitors, toMatchableServers(serverRows)).filter((m) => m.status === "maintenance");
|
|
|
|
const actor = req.currentUser!;
|
|
const createdBy = actor.name ?? actor.email ?? actor.oidcSub;
|
|
const imported: { serverId: number; serverName: string; monitorName: string; extended: boolean }[] = [];
|
|
const unmatched: string[] = [];
|
|
|
|
// Two monitors on the same server would otherwise start, then immediately re-extend, the same window —
|
|
// harmless, but the response would misleadingly list the server twice.
|
|
const seenServers = new Set<number>();
|
|
for (const m of inMaintenance) {
|
|
if (!m.matchedServer) {
|
|
unmatched.push(m.name);
|
|
continue;
|
|
}
|
|
if (seenServers.has(m.matchedServer.id)) continue;
|
|
seenServers.add(m.matchedServer.id);
|
|
|
|
const reason = `Imported from Uptime Kuma (${loaded.integration.name}): ${m.name}`;
|
|
const result = await startOrExtendWindow("server", m.matchedServer.id, minutes, reason, createdBy);
|
|
if (!result) continue; // the server was removed between the query above and now
|
|
await recordAudit({
|
|
actor,
|
|
category: "maintenance",
|
|
action: result.extended ? "extend" : "start",
|
|
targetType: "server",
|
|
targetId: m.matchedServer.id,
|
|
detail: { name: result.target.name, minutes, reason },
|
|
});
|
|
imported.push({ serverId: m.matchedServer.id, serverName: result.target.name, monitorName: m.name, extended: result.extended });
|
|
}
|
|
|
|
res.json({ imported, unmatched, monitorsInMaintenance: inMaintenance.length, monitorsChecked: monitors.length });
|
|
}));
|
|
|
|
const aliasSchema = z.object({
|
|
address: z.string().min(1).max(253),
|
|
targetType: z.enum(maintenanceTargetTypes),
|
|
targetId: z.number().int().positive(),
|
|
});
|
|
|
|
maintenanceRouter.post("/aliases", requireRole("operator"), asyncHandler(async (req, res) => {
|
|
const parsed = aliasSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", message: "Give an address and say what it belongs to.", details: parsed.error.flatten() });
|
|
}
|
|
const host = hostOfAddress(parsed.data.address);
|
|
if (!host) {
|
|
return res.status(400).json({ error: "invalid_address", message: "That isn't an address — use a host name or IP, like 100.64.0.7 or pve.example.lan." });
|
|
}
|
|
const target = await describeTarget(parsed.data.targetType, parsed.data.targetId);
|
|
if (!target) return res.status(404).json({ error: "not_found", message: "That target doesn't exist." });
|
|
|
|
const [existing] = await db
|
|
.select()
|
|
.from(maintenanceAliases)
|
|
.where(and(eq(maintenanceAliases.address, host), eq(maintenanceAliases.targetType, parsed.data.targetType), eq(maintenanceAliases.targetId, parsed.data.targetId)))
|
|
.limit(1);
|
|
if (existing) return res.status(409).json({ error: "exists", message: `${host} is already an alias of ${target.name}.` });
|
|
|
|
const [created] = await db.insert(maintenanceAliases).values({ address: host, targetType: parsed.data.targetType, targetId: parsed.data.targetId }).returning();
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "maintenance",
|
|
action: "alias_add",
|
|
targetType: parsed.data.targetType,
|
|
targetId: parsed.data.targetId,
|
|
detail: { name: target.name, address: host },
|
|
});
|
|
res.status(201).json({ alias: { ...created, targetName: target.name, targetKind: target.kind } });
|
|
}));
|
|
|
|
maintenanceRouter.delete("/aliases/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
|
const id = Number(req.params.id);
|
|
const [existing] = await db.select().from(maintenanceAliases).where(eq(maintenanceAliases.id, id)).limit(1);
|
|
if (!existing) return res.status(404).json({ error: "not_found" });
|
|
await db.delete(maintenanceAliases).where(eq(maintenanceAliases.id, id));
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "maintenance",
|
|
action: "alias_remove",
|
|
targetType: existing.targetType,
|
|
targetId: existing.targetId,
|
|
detail: { address: existing.address },
|
|
});
|
|
res.status(204).end();
|
|
}));
|
|
|
|
const syncUptimeKumaSchema = z.object({ integrationId: z.number().int().positive() });
|
|
|
|
/** Reads Uptime Kuma's maintenance schedule now and brings the mirrored windows in line with it (the same pass that runs every 15 minutes when switched on). */
|
|
maintenanceRouter.post("/sync/uptimekuma", requireRole("operator"), asyncHandler(async (req, res) => {
|
|
const parsed = syncUptimeKumaSchema.safeParse(req.body);
|
|
if (!parsed.success) {
|
|
return res.status(400).json({ error: "invalid_body", message: "Choose an Uptime Kuma integration.", details: parsed.error.flatten() });
|
|
}
|
|
try {
|
|
const result = await syncKumaMaintenance(parsed.data.integrationId);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "maintenance",
|
|
action: "sync",
|
|
targetType: "integration",
|
|
targetId: parsed.data.integrationId,
|
|
detail: { started: result.started, updated: result.updated, removed: result.removed },
|
|
});
|
|
res.json(result);
|
|
} catch (err) {
|
|
if (err instanceof KumaSyncError) {
|
|
const status = err.code === "not_found" ? 404 : err.code === "unreachable" ? 502 : 400;
|
|
return res.status(status).json({ error: err.code, message: err.message });
|
|
}
|
|
throw err;
|
|
}
|
|
}));
|
|
|
|
maintenanceRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
|
const id = Number(req.params.id);
|
|
const [existing] = await db.select().from(maintenanceWindows).where(eq(maintenanceWindows.id, id)).limit(1);
|
|
if (!existing) {
|
|
return res.status(404).json({ error: "not_found" });
|
|
}
|
|
// Ending moves the end to now, so it stops applying immediately; the row is pruned later like any expired one.
|
|
// A window that hasn't begun is cancelled instead: its end goes back to its start, so it never applies.
|
|
const now = new Date().toISOString();
|
|
await db.update(maintenanceWindows).set({ endsAt: existing.startedAt > now ? existing.startedAt : now }).where(eq(maintenanceWindows.id, id));
|
|
|
|
const target = await describeTarget(existing.targetType, existing.targetId);
|
|
await recordAudit({
|
|
actor: req.currentUser!,
|
|
category: "maintenance",
|
|
action: "end",
|
|
targetType: existing.targetType,
|
|
targetId: existing.targetId,
|
|
detail: { name: target?.name ?? null },
|
|
});
|
|
res.status(204).end();
|
|
}));
|