UniFi: servers plugged into switches; server page in sections; My work; settings search and undo

UniFi: the controller's client list is matched to servers by IP address, so a
server is connected through a switch or access point (and port). That is a
dependency made by itself, shown on the server page, the Network devices page
and the Connections map. IP Addresses can sync the devices' addresses.

A server's page is split into Overview, Health, Network, History, Tasks and
Settings, by ?view=; alerts link to the section they are about.

My work lists what has your name on it: alerts you have, maintenance you
started (extend, end with undo) and update runs you started, with a badge.

Settings has a search box (and the command palette lists every setting).
Removing a dependency, admin link, runbook, hand-made IP address, port opening
or restore test is undone from the message instead of asked about first.

Two backup tests used a fixed date and failed as days passed; they follow the
real clock now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 19:35:45 +02:00
1 parent 396e074108
commit 5e26e77340
45 files changed
+6224 -194

No files matched your search

+1 -1
View File
@@ -212,7 +212,7 @@ export async function collectAlerts(): Promise<AlertsReport> {
type: origin.type,
message: c.message,
key: c.key,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}` : origin.type === "unifi" ? "/network/devices" : undefined,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : ""}` : origin.type === "unifi" ? "/network/devices" : undefined,
silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject),
});
}
+16 -3
View File
@@ -11,7 +11,7 @@
*/
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { dependencies, integrations, networkDevices, servers } from "../db/schema.js";
import { dependencies, integrations, networkDevices, networkServerLinks, servers } from "../db/schema.js";
import { getInternalFlag } from "./settingsStore.js";
import { listActiveWindows } from "./maintenance.js";
import { loadParentRows, resolveParents, type ParentLink } from "./serverParents.js";
@@ -129,12 +129,13 @@ export interface Graph {
}
export async function loadGraph(): Promise<Graph> {
const [serverRows, intRows, depRows, parentRows, deviceRows] = await Promise.all([
const [serverRows, intRows, depRows, parentRows, deviceRows, linkRows] = await Promise.all([
db.select({ id: servers.id, name: servers.name }).from(servers),
db.select({ id: integrations.id, name: integrations.name, type: integrations.type, enabled: integrations.enabled }).from(integrations),
db.select().from(dependencies),
loadParentRows(),
db.select({ id: networkDevices.id, name: networkDevices.name, integrationId: networkDevices.integrationId, externalId: networkDevices.externalId, uplinkExternalId: networkDevices.uplinkExternalId }).from(networkDevices),
db.select({ integrationId: networkServerLinks.integrationId, serverId: networkServerLinks.serverId, deviceExternalId: networkServerLinks.deviceExternalId }).from(networkServerLinks),
]);
const names = new Map<string, string>();
for (const s of serverRows) names.set(nodeKey("server", s.id), s.name);
@@ -144,7 +145,8 @@ export async function loadGraph(): Promise<Graph> {
const instances = new Map<string, number[]>();
for (const i of intRows) if (i.enabled) instances.set(i.type, [...(instances.get(i.type) ?? []), i.id]);
// A device needs the one it is connected through: the controller says so, and nobody has to write it.
const uplinks = uplinkEdges(deviceRows);
// And a server needs the device it is plugged into, as the controller says.
const uplinks = [...uplinkEdges(deviceRows), ...serverLinkEdges(linkRows, deviceRows)];
return { edges: buildEdges(resolveParents(parentRows), [...rows, ...uplinks], (k) => names.has(k)), names, rows, instances, intRows };
}
@@ -160,6 +162,17 @@ export function uplinkEdges(devices: { id: number; integrationId: number; extern
return out;
}
/** The edges from each server to the devices it is plugged into. */
export function serverLinkEdges(links: { integrationId: number; serverId: number; deviceExternalId: string }[], devices: { id: number; integrationId: number; externalId: string }[]): DependencyEdge[] {
const idOf = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d.id]));
const out: DependencyEdge[] = [];
for (const l of links) {
const to = idOf.get(`${l.integrationId}:${l.deviceExternalId}`);
if (to !== undefined) out.push({ fromType: "server", fromId: l.serverId, toType: "device", toId: to });
}
return out;
}
/** The id of the alert about a node being down, when it has one (a server's "offline", a kind of service's "failing"). */
export function alertIdOfNode(key: string, graph: Graph): string | null {
const m = /^(server|integration|device):(\d+)$/.exec(key);
+116
View File
@@ -0,0 +1,116 @@
/**
* "My work": what one person has taken on, in one place — the alerts handed to them, the acknowledgements about to run out, the maintenance windows they
* started that are about to end, and the update runs they started that are still going (or just finished). Everything here already exists elsewhere in the app;
* this only gathers the parts that have this person's name on them, and says which of them need a look soon.
*
* Who did what is recorded as a label — the person's name, or their email, or their sign-in id — so those three are what are matched.
*/
import { and, eq, gte, inArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { servers, updateRuns } from "../db/schema.js";
import { getAlerts } from "./alerts.js";
import { loadAcks } from "./alertAcks.js";
import { describeTarget, listActiveWindows } from "./maintenance.js";
/** An acknowledgement that runs out within this long is flagged. */
export const ACK_ENDS_SOON_MS = 24 * 3600_000;
/** A maintenance window that ends within this long is flagged. */
export const WINDOW_ENDS_SOON_MS = 2 * 3600_000;
/** A finished update run stays on the list this long, so the result is seen. */
export const RUN_KEPT_MS = 24 * 3600_000;
export interface MyWorkUser {
id: number;
name: string | null;
email: string | null;
oidcSub: string;
}
export interface MyWork {
/** Alerts that are on the Alerts page now and that this person has acknowledged or been handed, worst-first-ending first. */
alerts: {
alertId: string;
message: string;
severity: string;
source: string;
link: string | null;
note: string;
/** "handed" = somebody gave it to them (or they gave it to themselves); "acked" = they acknowledged it for nobody in particular. */
role: "handed" | "acked";
ackedBy: string;
ackedAt: string;
until: string | null;
endsSoon: boolean;
}[];
windows: { id: number; targetType: string; targetId: number; targetName: string; targetKind: string; reason: string | null; startedAt: string; endsAt: string; endsSoon: boolean }[];
updateRuns: { id: number; serverId: number; serverName: string; templateName: string; status: string; message: string | null; startedAt: string; finishedAt: string | null; running: boolean; updatesBefore: number | null; updatesAfter: number | null; rebootRequired: boolean }[];
/** How many of the above want a look: acknowledgements and windows that end soon, alerts handed to them, update runs still going. */
needsAttention: number;
}
/** The labels an action by this person may have been recorded under. */
export function labelsOf(user: MyWorkUser): string[] {
return [...new Set([user.name, user.email, user.oidcSub].filter((v): v is string => typeof v === "string" && v !== ""))];
}
export async function buildMyWork(user: MyWorkUser, now: Date = new Date()): Promise<MyWork> {
const labels = new Set(labelsOf(user));
const nowMs = now.getTime();
const report = await getAlerts(false);
const acks = await loadAcks(now);
const alerts: MyWork["alerts"] = [];
for (const a of report.alerts) {
const ack = acks.get(a.id);
if (!ack || !ack.active) continue;
const handed = ack.assignee?.id === user.id;
const acked = labels.has(ack.ackedBy);
if (!handed && !acked) continue;
alerts.push({
alertId: a.id,
message: a.message,
severity: a.severity,
source: a.source,
link: a.link,
note: ack.note,
role: handed ? "handed" : "acked",
ackedBy: ack.ackedBy,
ackedAt: ack.ackedAt,
until: ack.until,
endsSoon: ack.until !== null && Date.parse(ack.until) - nowMs <= ACK_ENDS_SOON_MS,
});
}
// What runs out first, first; then what has no end, worst first.
const SEV: Record<string, number> = { critical: 0, warning: 1, info: 2 };
alerts.sort((a, b) => (a.until === null ? Infinity : Date.parse(a.until)) - (b.until === null ? Infinity : Date.parse(b.until)) || (SEV[a.severity] ?? 3) - (SEV[b.severity] ?? 3) || a.message.localeCompare(b.message));
const windows: MyWork["windows"] = [];
for (const w of await listActiveWindows(now)) {
if (!w.createdBy || !labels.has(w.createdBy)) continue;
const target = await describeTarget(w.targetType, w.targetId);
if (!target) continue;
windows.push({ id: w.id, targetType: w.targetType, targetId: w.targetId, targetName: target.name, targetKind: target.kind, reason: w.reason, startedAt: w.startedAt, endsAt: w.endsAt, endsSoon: Date.parse(w.endsAt) - nowMs <= WINDOW_ENDS_SOON_MS });
}
windows.sort((a, b) => a.endsAt.localeCompare(b.endsAt));
const labelList = [...labels];
const runRows =
labelList.length === 0
? []
: await db
.select({ run: updateRuns, serverName: servers.name })
.from(updateRuns)
.innerJoin(servers, eq(servers.id, updateRuns.serverId))
.where(and(inArray(updateRuns.startedBy, labelList), gte(updateRuns.startedAt, new Date(nowMs - 7 * 86_400_000).toISOString())));
const runs: MyWork["updateRuns"] = [];
for (const { run, serverName } of runRows) {
const running = run.finishedAt === null;
// Still going, or finished recently enough that its result is news.
if (!running && nowMs - Date.parse(run.finishedAt!) > RUN_KEPT_MS) continue;
runs.push({ id: run.id, serverId: run.serverId, serverName, templateName: run.templateName, status: run.status, message: run.message, startedAt: run.startedAt, finishedAt: run.finishedAt, running, updatesBefore: run.updatesBefore, updatesAfter: run.updatesAfter, rebootRequired: run.rebootRequired });
}
runs.sort((a, b) => Number(b.running) - Number(a.running) || b.startedAt.localeCompare(a.startedAt));
const needsAttention = alerts.filter((a) => a.role === "handed" || a.endsSoon).length + windows.filter((w) => w.endsSoon).length + runs.filter((r) => r.running).length;
return { alerts, windows, updateRuns: runs, needsAttention };
}
+22 -2
View File
@@ -6,7 +6,7 @@
*/
import { and, eq, inArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { dnsRecordsCache, dnsZonesCache, integrations, servers } from "../db/schema.js";
import { dnsRecordsCache, dnsZonesCache, integrations, networkDevices, networkServerLinks, servers } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
import { getSettings } from "./settingsStore.js";
@@ -17,7 +17,7 @@ export type MapStatus = "ok" | "bad" | "warn" | "unknown";
export interface MapNode {
id: string;
kind: "host" | "server" | "dns" | "monitor";
kind: "host" | "server" | "dns" | "monitor" | "device";
label: string;
sub: string | null;
status: MapStatus;
@@ -91,6 +91,26 @@ export async function buildTopology(now: Date = new Date()): Promise<MapData> {
}
}
// The switches and access points servers are plugged into, as a UniFi controller says. Only devices with a server on them are drawn: the rest of the
// network is on the dependency map.
const links = await db.select().from(networkServerLinks);
if (links.length > 0) {
const devices = await db.select().from(networkDevices);
const deviceOf = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d]));
const serverIds = new Set(serverRows.map((s) => s.id));
const drawn = new Set<number>();
for (const l of links) {
const d = deviceOf.get(`${l.integrationId}:${l.deviceExternalId}`);
if (!d || !serverIds.has(l.serverId)) continue;
if (!drawn.has(d.id)) {
drawn.add(d.id);
const status: MapStatus = d.state === "online" ? "ok" : d.state === "offline" ? "bad" : d.state === "updating" ? "warn" : "unknown";
nodes.push({ id: `device:${d.id}`, kind: "device", label: d.name, sub: [d.kind.replace("_", " "), d.model].filter(Boolean).join(" · "), status, href: "/network/devices" });
}
if (!edges.some((e) => e.from === `device:${d.id}` && e.to === `server:${l.serverId}`)) edges.push({ from: `device:${d.id}`, to: `server:${l.serverId}` });
}
}
// DNS names that point at a server's own address.
const serversByIp = new Map<string, number[]>();
for (const s of serverRows) for (const ip of parseIps(s.ipAddresses)) serversByIp.set(ip, [...(serversByIp.get(ip) ?? []), s.id]);
+47 -2
View File
@@ -7,9 +7,9 @@
*/
import { and, eq, inArray, or } from "drizzle-orm";
import { db } from "../db/client.js";
import { dependencies, integrations, networkDevices, networkSegments } from "../db/schema.js";
import { dependencies, integrations, networkDevices, networkSegments, networkServerLinks, servers } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUnifiAdapter, type UnifiDevice, type UnifiInventory } from "../integrations/unifi/adapter.js";
import { createUnifiAdapter, type UnifiClient, type UnifiDevice, type UnifiInventory } from "../integrations/unifi/adapter.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
export const SYNC_INTERVAL_MS = 5 * 60_000;
@@ -39,6 +39,43 @@ export function trackOffline(previous: { offlineSince: string | null; lastOnline
return { offlineSince: previous?.offlineSince ?? null, lastOnlineAt };
}
export interface ServerLink {
serverId: number;
deviceExternalId: string;
clientMac: string;
port: number | null;
wired: boolean;
}
/**
* Which servers are plugged into which device: a client the controller lists whose IP address is one of a server's own. Only an exact, unambiguous address counts
* (an address two servers both report matches neither), and only a client whose switch or access point is a device that is known. Pure.
*/
export function matchClientsToServers(clients: UnifiClient[], serverRows: { id: number; ipAddresses: string | null }[], deviceMacs: Set<string>): ServerLink[] {
const owners = new Map<string, number[]>();
for (const s of serverRows) {
let ips: unknown = [];
try {
ips = s.ipAddresses ? JSON.parse(s.ipAddresses) : [];
} catch {
// a malformed list matches nothing
}
for (const ip of Array.isArray(ips) ? ips : []) if (typeof ip === "string") owners.set(ip, [...new Set([...(owners.get(ip) ?? []), s.id])]);
}
const out: ServerLink[] = [];
const seen = new Set<string>();
for (const c of clients) {
if (!c.ip || !c.uplinkExternalId || !deviceMacs.has(c.uplinkExternalId)) continue;
const who = owners.get(c.ip);
if (!who || who.length !== 1) continue;
const key = `${who[0]}|${c.mac}`;
if (seen.has(key)) continue;
seen.add(key);
out.push({ serverId: who[0], deviceExternalId: c.uplinkExternalId, clientMac: c.mac, port: c.port, wired: c.wired });
}
return out;
}
async function readStatuses(): Promise<Record<string, SyncStatus>> {
try {
const raw = await getInternalFlag(STATUS_FLAG);
@@ -91,6 +128,13 @@ export async function storeInventory(integrationId: number, inventory: UnifiInve
const gone = existing.filter((r) => !seen.has(r.externalId)).map((r) => r.id);
if (gone.length > 0) await db.delete(networkDevices).where(inArray(networkDevices.id, gone));
// Which servers are plugged into which device. A controller that listed no clients at all (a key that may not read them) says nothing, so what was known stays.
if (inventory.clients.length > 0) {
const links = matchClientsToServers(inventory.clients, await db.select({ id: servers.id, ipAddresses: servers.ipAddresses }).from(servers), new Set(inventory.devices.map((d) => d.externalId)));
await db.delete(networkServerLinks).where(eq(networkServerLinks.integrationId, integrationId));
if (links.length > 0) await db.insert(networkServerLinks).values(links.map((l) => ({ integrationId, ...l, updatedAt: nowIso })));
}
const segments: (typeof networkSegments.$inferInsert)[] = [
...inventory.networks.map((n) => ({ integrationId, kind: "network" as const, externalId: n.externalId, siteName: n.siteName, name: n.name, enabled: n.enabled, vlanId: n.vlanId, subnet: n.subnet, purpose: n.purpose, security: null, networkName: null, updatedAt: nowIso })),
...inventory.ssids.map((s) => ({ integrationId, kind: "ssid" as const, externalId: s.externalId, siteName: s.siteName, name: s.name, enabled: s.enabled, vlanId: s.vlanId, subnet: null, purpose: null, security: s.security, networkName: s.networkName, updatedAt: nowIso })),
@@ -140,6 +184,7 @@ export async function removeIntegrationData(integrationId: number): Promise<void
await db.delete(networkDevices).where(inArray(networkDevices.id, ids));
}
await db.delete(networkSegments).where(eq(networkSegments.integrationId, integrationId));
await db.delete(networkServerLinks).where(eq(networkServerLinks.integrationId, integrationId));
const all = await readStatuses();
if (String(integrationId) in all) {
delete all[String(integrationId)];