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:
1 parent
396e074108
commit
5e26e77340
45 files changed
+6224
-194
No files matched your search
@@ -46,6 +46,7 @@ import { portsRouter } from "./routes/ports.js";
|
||||
import { alertsRouter } from "./routes/alerts.js";
|
||||
import { mapRouter } from "./routes/map.js";
|
||||
import { networkRouter } from "./routes/network.js";
|
||||
import { myWorkRouter } from "./routes/myWork.js";
|
||||
import { generatorRouter } from "./routes/generator.js";
|
||||
import { alertTicketsRouter } from "./routes/alertTickets.js";
|
||||
import { avatarsRouter } from "./routes/avatars.js";
|
||||
@@ -163,6 +164,7 @@ export function createApp() {
|
||||
app.use("/api/alerts", alertsRouter);
|
||||
app.use("/api/map", mapRouter);
|
||||
app.use("/api/network", networkRouter);
|
||||
app.use("/api/my-work", myWorkRouter);
|
||||
app.use("/api/generator", generatorRouter);
|
||||
app.use("/api/alert-tickets", alertTicketsRouter);
|
||||
|
||||
|
||||
@@ -564,6 +564,27 @@ export const networkDevices = sqliteTable(
|
||||
(t) => [uniqueIndex("network_devices_unique").on(t.integrationId, t.externalId)],
|
||||
);
|
||||
|
||||
// Which server is plugged into which network device, worked out on every read from what the controller says is connected (matched by the server's IP address).
|
||||
// A server needs the device it is connected through, as far as the dependency map is concerned.
|
||||
export const networkServerLinks = sqliteTable(
|
||||
"network_server_links",
|
||||
{
|
||||
id: integer("id").primaryKey({ autoIncrement: true }),
|
||||
integrationId: integer("integration_id")
|
||||
.notNull()
|
||||
.references(() => integrations.id, { onDelete: "cascade" }),
|
||||
serverId: integer("server_id")
|
||||
.notNull()
|
||||
.references(() => servers.id, { onDelete: "cascade" }),
|
||||
deviceExternalId: text("device_external_id").notNull(), // the MAC of the switch or access point
|
||||
clientMac: text("client_mac").notNull(),
|
||||
port: integer("port"), // the switch port, when the controller says (the classic API does)
|
||||
wired: integer("wired", { mode: "boolean" }).notNull().default(true),
|
||||
updatedAt: text("updated_at").notNull(),
|
||||
},
|
||||
(t) => [uniqueIndex("network_server_links_unique").on(t.integrationId, t.serverId, t.clientMac)],
|
||||
);
|
||||
|
||||
// The networks (VLANs) and Wi-Fi names (SSIDs) a UniFi controller has set up, kept beside the devices. Passphrases are never read.
|
||||
export const networkSegments = sqliteTable(
|
||||
"network_segments",
|
||||
|
||||
@@ -75,12 +75,27 @@ export interface UnifiSsid {
|
||||
siteName: string;
|
||||
}
|
||||
|
||||
/** Something connected to the network (a computer, a phone, a server), and the device it is connected through. */
|
||||
export interface UnifiClient {
|
||||
mac: string;
|
||||
ip: string | null;
|
||||
name: string | null;
|
||||
wired: boolean;
|
||||
/** The MAC of the switch or access point it is on, when the controller says. */
|
||||
uplinkExternalId: string | null;
|
||||
/** The switch port, for a wired client on the classic API. */
|
||||
port: number | null;
|
||||
siteName: string;
|
||||
}
|
||||
|
||||
export interface UnifiInventory {
|
||||
mode: "api_key" | "login";
|
||||
sites: string[];
|
||||
devices: UnifiDevice[];
|
||||
networks: UnifiNetwork[];
|
||||
ssids: UnifiSsid[];
|
||||
/** Everything connected right now; [] when the controller would not say (an account or key that may not read clients). */
|
||||
clients: UnifiClient[];
|
||||
}
|
||||
|
||||
export interface UnifiAdapter {
|
||||
@@ -236,6 +251,22 @@ export function networkFromLegacy(raw: unknown, siteName: string): UnifiNetwork
|
||||
};
|
||||
}
|
||||
|
||||
export function clientFromApi(raw: unknown, macById: Map<string, string>, siteName: string): UnifiClient | null {
|
||||
const d = obj(raw);
|
||||
const mac = normaliseMac(d.macAddress);
|
||||
if (!mac) return null;
|
||||
const uplinkId = str(d.uplinkDeviceId);
|
||||
return { mac, ip: str(d.ipAddress), name: str(d.name), wired: String(d.type ?? "").toUpperCase() === "WIRED", uplinkExternalId: uplinkId ? (macById.get(uplinkId) ?? null) : null, port: null, siteName };
|
||||
}
|
||||
|
||||
export function clientFromLegacy(raw: unknown, siteName: string): UnifiClient | null {
|
||||
const d = obj(raw);
|
||||
const mac = normaliseMac(d.mac);
|
||||
if (!mac) return null;
|
||||
const wired = d.is_wired === true;
|
||||
return { mac, ip: str(d.ip), name: str(d.name) ?? str(d.hostname), wired, uplinkExternalId: normaliseMac(wired ? d.sw_mac : d.ap_mac), port: wired ? num(d.sw_port) : null, siteName };
|
||||
}
|
||||
|
||||
const API_SECURITY: Record<string, string> = { OPEN: "Open", WPA2_PERSONAL: "WPA2", WPA3_PERSONAL: "WPA3", WPA2_WPA3_PERSONAL: "WPA2/WPA3", WPA2_ENTERPRISE: "WPA2 Enterprise", WPA3_ENTERPRISE: "WPA3 Enterprise" };
|
||||
|
||||
export function ssidFromApi(raw: unknown, networkNames: Map<string, string>, siteName: string): UnifiSsid | null {
|
||||
@@ -406,7 +437,7 @@ export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter {
|
||||
sites = sites.filter((s) => s.name.toLowerCase() === wantSite);
|
||||
if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`);
|
||||
}
|
||||
const inventory: UnifiInventory = { mode: "api_key", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [] };
|
||||
const inventory: UnifiInventory = { mode: "api_key", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [], clients: [] };
|
||||
for (const site of sites) {
|
||||
const base = `/sites/${site.id}`;
|
||||
const entries = await apiPaged(prefix, `${base}/devices`);
|
||||
@@ -428,6 +459,12 @@ export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter {
|
||||
if (d) inventory.devices.push(d);
|
||||
});
|
||||
|
||||
// What is connected where. A key that may not read clients costs only the links from servers to the devices they are plugged into.
|
||||
for (const raw of await apiPaged(prefix, `${base}/clients`).catch(() => [])) {
|
||||
const c = clientFromApi(raw, macById, site.name);
|
||||
if (c) inventory.clients.push(c);
|
||||
}
|
||||
|
||||
const netEntries = await apiPaged(prefix, `${base}/networks`).catch(() => []);
|
||||
const netDetails = await pooled(netEntries, async (e) => {
|
||||
const id = str(obj(e).id);
|
||||
@@ -508,12 +545,16 @@ export function createUnifiAdapter(config: UnifiConfig): UnifiAdapter {
|
||||
sites = sites.filter((s) => s.name.toLowerCase() === wantSite || s.key.toLowerCase() === wantSite);
|
||||
if (sites.length === 0) throw new Error(`UniFi has no site called “${config.site}”`);
|
||||
}
|
||||
const inventory: UnifiInventory = { mode: "login", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [] };
|
||||
const inventory: UnifiInventory = { mode: "login", sites: sites.map((s) => s.name), devices: [], networks: [], ssids: [], clients: [] };
|
||||
for (const site of sites) {
|
||||
for (const raw of await legacyGet(session, `/api/s/${site.key}/stat/device`)) {
|
||||
const d = deviceFromLegacy(raw, site.name);
|
||||
if (d) inventory.devices.push(d);
|
||||
}
|
||||
for (const raw of await legacyGet(session, `/api/s/${site.key}/stat/sta`).catch(() => [])) {
|
||||
const c = clientFromLegacy(raw, site.name);
|
||||
if (c) inventory.clients.push(c);
|
||||
}
|
||||
const networkNames = new Map<string, string>();
|
||||
for (const raw of await legacyGet(session, `/api/s/${site.key}/rest/networkconf`).catch(() => [])) {
|
||||
const n = networkFromLegacy(raw, site.name);
|
||||
|
||||
@@ -64,7 +64,7 @@ dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => {
|
||||
for (const [needing, needed] of graph.edges) {
|
||||
for (const n of needed) {
|
||||
// A device connected through another is an uplink (the controller says so); a server's "runs on" is the other kind of link nobody wrote.
|
||||
edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : needing.startsWith("device:") && n.startsWith("device:") ? "uplink" : "runs-on" });
|
||||
edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : n.startsWith("device:") ? "uplink" : "runs-on" });
|
||||
taking.add(needing);
|
||||
taking.add(n);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { isIP } from "node:net";
|
||||
import { and, eq, inArray } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { ipamEntries, integrations, dnsRecordsCache } from "../db/schema.js";
|
||||
import { ipamEntries, integrations, dnsRecordsCache, networkDevices } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { recordAudit } from "../services/audit.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
@@ -290,6 +290,32 @@ ipamRouter.post("/sync-proxmox", requireRole("operator"), asyncHandler(async (re
|
||||
res.json({ added, updated, skipped, skippedIps, errors });
|
||||
}));
|
||||
|
||||
ipamRouter.post("/sync-unifi", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const controllers = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "unifi"), eq(integrations.enabled, true)));
|
||||
if (controllers.length === 0) {
|
||||
return res.status(400).json({ error: "no_unifi_integration" });
|
||||
}
|
||||
let added = 0;
|
||||
let updated = 0;
|
||||
let skipped = 0;
|
||||
const skippedIps: string[] = [];
|
||||
// What was last read from the controllers (the page's own copy), not a new call: a device is as current as the Network devices page says.
|
||||
for (const d of await db.select().from(networkDevices)) {
|
||||
if (!d.ip) continue;
|
||||
const kind = d.kind.replace("_", " ");
|
||||
const notes = [`${kind}${d.model ? `, ${d.model}` : ""}`, d.mac ? `MAC ${d.mac}` : null].filter((v): v is string => !!v).join(" — ");
|
||||
const result = await upsertSyncedEntry(d.ip, d.name, "UniFi", notes, d.siteName && d.siteName !== "Default" ? d.siteName : null, "unifi");
|
||||
if (result === "added") added++;
|
||||
else if (result === "updated") updated++;
|
||||
else {
|
||||
skipped++;
|
||||
skippedIps.push(d.ip);
|
||||
}
|
||||
}
|
||||
await recordAudit({ actor: req.currentUser!, category: "ipam", action: "sync_unifi", detail: { added, updated, skipped } });
|
||||
res.json({ added, updated, skipped, skippedIps, errors: [] });
|
||||
}));
|
||||
|
||||
ipamRouter.post("/sync-phpipam", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
const phpIpamIntegrations = await db
|
||||
.select()
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import { Router } from "express";
|
||||
import { requireAuth } from "../auth/middleware.js";
|
||||
import { buildMyWork } from "../services/myWork.js";
|
||||
import { asyncHandler } from "../utils/asyncHandler.js";
|
||||
|
||||
export const myWorkRouter = Router();
|
||||
|
||||
myWorkRouter.use(requireAuth);
|
||||
|
||||
// What the signed-in person has taken on. Only ever their own: the answer is worked out from who is asking.
|
||||
myWorkRouter.get("/", asyncHandler(async (req, res) => {
|
||||
const user = req.currentUser!;
|
||||
res.json(await buildMyWork({ id: user.id, name: user.name ?? null, email: user.email ?? null, oidcSub: user.oidcSub }));
|
||||
}));
|
||||
@@ -2,7 +2,7 @@ import { Router } from "express";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { db } from "../db/client.js";
|
||||
import { integrations, networkDevices, networkSegments } from "../db/schema.js";
|
||||
import { integrations, networkDevices, networkSegments, networkServerLinks, servers } from "../db/schema.js";
|
||||
import { requireAuth, requireRole } from "../auth/middleware.js";
|
||||
import { invalidateAlertsCache } from "../services/alerts.js";
|
||||
import { dependentsOf, loadGraph, needsOfNode, nodeKey } from "../services/dependencies.js";
|
||||
@@ -19,17 +19,31 @@ networkRouter.use(requireAuth);
|
||||
* names. Everyone signed in can see it (it is the same picture the dependency map and the alerts draw on); only starting a fresh read needs more.
|
||||
*/
|
||||
networkRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
const [intRows, devices, segments, statuses, graph, silenced] = await Promise.all([
|
||||
const [intRows, devices, segments, statuses, graph, silenced, linkRows, serverRows] = await Promise.all([
|
||||
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "unifi")),
|
||||
db.select().from(networkDevices),
|
||||
db.select().from(networkSegments),
|
||||
syncStatuses(),
|
||||
loadGraph(),
|
||||
activeSubjects(),
|
||||
db.select().from(networkServerLinks),
|
||||
db.select({ id: servers.id, name: servers.name }).from(servers),
|
||||
]);
|
||||
const serverName = new Map(serverRows.map((s) => [s.id, s.name]));
|
||||
const intName = new Map(intRows.map((i) => [i.id, i.name]));
|
||||
const byExternal = new Map(devices.map((d) => [`${d.integrationId}:${d.externalId}`, d]));
|
||||
// The servers plugged into each device, by what the controller says is connected (see unifiSync.matchClientsToServers).
|
||||
const plugged = new Map<number, { serverId: number; serverName: string; port: number | null; wired: boolean }[]>();
|
||||
const serverLinks: { serverId: number; serverName: string; deviceId: number; deviceName: string; port: number | null; wired: boolean }[] = [];
|
||||
for (const l of linkRows) {
|
||||
const device = byExternal.get(`${l.integrationId}:${l.deviceExternalId}`);
|
||||
const name = serverName.get(l.serverId);
|
||||
if (!device || !name) continue;
|
||||
plugged.set(device.id, [...(plugged.get(device.id) ?? []), { serverId: l.serverId, serverName: name, port: l.port, wired: l.wired }]);
|
||||
serverLinks.push({ serverId: l.serverId, serverName: name, deviceId: device.id, deviceName: device.name, port: l.port, wired: l.wired });
|
||||
}
|
||||
res.json({
|
||||
serverLinks,
|
||||
integrations: intRows.map((i) => ({ id: i.id, name: i.name, enabled: i.enabled, status: statuses[i.id] ?? null })),
|
||||
devices: devices
|
||||
.map((d) => {
|
||||
@@ -57,6 +71,7 @@ networkRouter.get("/", asyncHandler(async (_req, res) => {
|
||||
dependents: dependentsOf(graph.edges, key).length,
|
||||
needs: needsOfNode(graph.edges, key).length,
|
||||
inMaintenance: silenced.has(key),
|
||||
servers: (plugged.get(d.id) ?? []).sort((a, b) => a.serverName.localeCompare(b.serverName)),
|
||||
};
|
||||
})
|
||||
.sort((a, b) => a.name.localeCompare(b.name)),
|
||||
|
||||
@@ -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),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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]);
|
||||
|
||||
@@ -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)];
|
||||
|
||||
Reference in new issue
Block a user