A UPS in the map: read over NUT or SNMP, alerts, shutdown order

New UPS integration (NUT or SNMP v2c, read only). Monitoring -> UPS shows charge,
runtime, load and mains voltage with history and the times mains power was lost.
Mains lost and a nearly empty battery are critical alerts; battery to be replaced
and a heavy load are warnings. The UPS is a node in the dependency map and counts
as down while on battery, so servers that go offline with it are folded under its
alert; the page lists what is on it in the order to shut it down. /metrics series
and docs added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-21 21:47:31 +02:00
1 parent 3cb3e4988f
commit 232a5661ab
38 files changed
+8049 -16

No files matched your search

+4
View File
@@ -27,6 +27,7 @@ import { attachMatchedServers, summarizeMonitors, toMatchableServers } from "../
import { getSourceStatus } from "../services/integrationHealthMonitor.js";
import { removeIntegrationData, syncUnifiIntegration } from "../services/unifiSync.js";
import { removeHomeAssistantData, syncHomeAssistant } from "../services/homeAssistantSync.js";
import { forgetUps, syncUps } from "../services/upsSync.js";
import { invalidateAlertsCache } from "../services/alerts.js";
import { asyncHandler } from "../utils/asyncHandler.js";
import { ID_PATTERNS, isValidId } from "../utils/pathSegment.js";
@@ -127,6 +128,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res)
// A new UniFi controller is read at once, so its equipment is there when the person opens the page (not waited for: a slow controller must not slow this).
if (type === "unifi") void syncUnifiIntegration(created.id).then(() => invalidateAlertsCache());
if (type === "homeassistant") void syncHomeAssistant(created.id).then(() => invalidateAlertsCache());
if (type === "ups") void syncUps(created.id).then(() => invalidateAlertsCache());
res.status(201).json({
integration: {
@@ -229,6 +231,7 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req,
if (updated.type === "unifi" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUnifiIntegration(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "homeassistant" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncHomeAssistant(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "ups" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncUps(updated.id).then(() => invalidateAlertsCache());
res.json({
integration: {
@@ -307,6 +310,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req,
if (existing.type === "unifi") await removeIntegrationData(id);
if (existing.type === "homeassistant") await removeHomeAssistantData(id);
if (existing.type === "ups") await forgetUps(id);
await db.delete(integrations).where(eq(integrations.id, id));
if (existing.credentialId) {
await db.delete(integrationCredentials).where(eq(integrationCredentials.id, existing.credentialId));
+77
View File
@@ -0,0 +1,77 @@
import { Router } from "express";
import { and, asc, eq, gte } from "drizzle-orm";
import { db } from "../db/client.js";
import { integrations, upsReadings, upsState } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { loadGraph } from "../services/dependencies.js";
import { bucketUps, isUpsFresh, READING_KEEP_DAYS, shutdownOrder, upsProblems, upsSyncStatuses } from "../services/upsSync.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const upsRouter = Router();
upsRouter.use(requireAuth);
const DAY_MS = 86_400_000;
const idOf = (v: string) => (/^\d+$/.test(v) ? Number(v) : NaN);
const isSnmp = (config: string | null) => {
try {
const c = config ? (JSON.parse(config) as Record<string, unknown>) : {};
return c.snmp === true || c.snmp === "true";
} catch {
return false;
}
};
/** Every UPS, how it is now, and what is on it in the order to shut it down. Everyone signed in can see it, like the other pages made of stored readings. */
upsRouter.get("/", asyncHandler(async (_req, res) => {
const [rows, states, statuses, graph] = await Promise.all([
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled, config: integrations.config }).from(integrations).where(eq(integrations.type, "ups")).orderBy(integrations.name),
db.select().from(upsState),
upsSyncStatuses(),
loadGraph(),
]);
const now = new Date();
const byId = new Map(states.map((s) => [s.integrationId, s]));
res.json({
ups: rows.map((r) => {
const state = byId.get(r.id) ?? null;
const status = statuses[r.id] ?? null;
const fresh = isUpsFresh(status ?? undefined, now.getTime());
const { order, looped } = shutdownOrder(graph.edges, `integration:${r.id}`);
return {
id: r.id,
name: r.name,
enabled: r.enabled,
protocol: isSnmp(r.config) ? "snmp" : "nut",
status,
fresh,
state,
problems: state && fresh ? upsProblems(r.id, r.name, state, now) : [],
// What needs this UPS, directly or through something else, in the order to shut it down (step 1 first).
carries: order.map((o) => {
const [type, id] = o.key.split(":");
return { key: o.key, type, id: Number(id), name: graph.names.get(o.key) ?? o.key, step: o.step };
}),
orderLooped: looped,
};
}),
});
}));
/** One UPS's charge, load and mains voltage over time (readings are kept 35 days). */
upsRouter.get("/:id/history", asyncHandler(async (req, res) => {
const id = idOf(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" });
const [row] = await db.select({ id: integrations.id, name: integrations.name, type: integrations.type }).from(integrations).where(eq(integrations.id, id)).limit(1);
if (!row || row.type !== "ups") return res.status(404).json({ error: "not_found" });
const asked = Number(req.query.days);
const days = Number.isFinite(asked) ? Math.min(READING_KEEP_DAYS, Math.max(1, Math.round(asked))) : 7;
const to = Date.now();
const from = to - days * DAY_MS;
const rows = await db
.select()
.from(upsReadings)
.where(and(eq(upsReadings.integrationId, id), gte(upsReadings.at, new Date(from).toISOString())))
.orderBy(asc(upsReadings.at));
res.json({ ups: { id: row.id, name: row.name }, days, ...bucketUps(rows, from, to, 200) });
}));