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
+103
-5
@@ -20,12 +20,14 @@ process.env.HEALTH_STARTUP_GRACE_MS = "0";
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, dependencies, maintenanceWindows } = await import("../src/db/schema.js");
|
||||
const { users, servers, integrations, integrationCredentials, networkDevices, networkSegments, networkServerLinks, ipamEntries, dependencies, maintenanceWindows } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const { encryptSecret } = await import("../src/crypto.js");
|
||||
const adapterModule = await import("../src/integrations/unifi/adapter.js");
|
||||
const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy } = adapterModule;
|
||||
const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses } = await import("../src/services/unifiSync.js");
|
||||
const { createUnifiAdapter, normaliseMac, deviceKind, stateFromApi, stateFromLegacy, deviceFromApi, deviceFromLegacy, ssidFromLegacy, clientFromApi, clientFromLegacy } = adapterModule;
|
||||
const { syncUnifiIntegration, trackOffline, isFresh, removeIntegrationData, syncStatuses, matchClientsToServers } = await import("../src/services/unifiSync.js");
|
||||
const { buildTopology } = await import("../src/services/topology.js");
|
||||
const { ipamRouter } = await import("../src/routes/ipam.js");
|
||||
const { evaluateHealth } = await import("../src/services/healthMonitor.js");
|
||||
const { dependencyCover, uplinkEdges, loadGraph, alertIdOfNode } = await import("../src/services/dependencies.js");
|
||||
const { subjectOfConditionKey, describeTarget } = await import("../src/services/maintenance.js");
|
||||
@@ -69,6 +71,21 @@ const wifiList = {
|
||||
],
|
||||
};
|
||||
|
||||
const clientList = {
|
||||
offset: 0,
|
||||
limit: 200,
|
||||
count: 3,
|
||||
totalCount: 3,
|
||||
data: [
|
||||
{ id: "c1", type: "WIRED", name: "web", ipAddress: "192.168.1.50", macAddress: "aa:bb:cc:00:00:50", uplinkDeviceId: "d-sw" },
|
||||
{ id: "c2", type: "WIRELESS", name: "phone", ipAddress: "192.168.1.60", macAddress: "aa:bb:cc:00:00:60", uplinkDeviceId: "d-ap" },
|
||||
{ id: "c3", type: "WIRED", name: "stranger", ipAddress: "192.168.1.99", macAddress: "aa:bb:cc:00:00:99", uplinkDeviceId: "d-gone" },
|
||||
],
|
||||
};
|
||||
const legacyClients = [
|
||||
{ mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", hostname: "web", is_wired: true, sw_mac: "00:11:22:33:44:02", sw_port: 7 },
|
||||
{ mac: "aa:bb:cc:00:00:60", ip: "192.168.1.60", name: "phone", is_wired: false, ap_mac: "00:11:22:33:44:03" },
|
||||
];
|
||||
const legacyDevices = [
|
||||
{ _id: "x1", mac: "00:11:22:33:44:01", ip: "192.168.1.1", name: "Gateway", model: "UDMPRO", type: "udm", state: 1, uptime: 1000, version: "4.0.6", upgradable: false },
|
||||
{ _id: "x2", mac: "00:11:22:33:44:02", ip: "192.168.1.2", name: "Rack switch", model: "US24PRO", type: "usw", state: 1, uptime: 500, version: "7.0.50", upgradable: true, uplink: { uplink_mac: "00:11:22:33:44:01", type: "wire" } },
|
||||
@@ -93,6 +110,7 @@ function handleApi(url: URL, res: ServerResponse, strip: string) {
|
||||
const path = url.pathname.slice(strip.length);
|
||||
const m = /^\/sites\/site-1\/(devices|networks|wifi\/broadcasts)(?:\/([^/]+?)(\/statistics\/latest)?)?$/.exec(path);
|
||||
if (path === "/sites") return reply(res, 200, siteList);
|
||||
if (path === "/sites/site-1/clients") return reply(res, 200, clientList);
|
||||
if (!m) return reply(res, 404, { message: "no such endpoint" });
|
||||
if (m[1] === "devices") return reply(res, 200, m[2] ? (m[3] ? (stats[m[2]] ?? {}) : (detail[m[2]] ?? {})) : deviceList);
|
||||
if (m[1] === "networks") return reply(res, 200, m[2] ? (networkDetail[m[2]] ?? {}) : networkList);
|
||||
@@ -103,6 +121,7 @@ function handleLegacy(url: URL, res: ServerResponse, strip: string) {
|
||||
const path = url.pathname.slice(strip.length);
|
||||
if (path === "/api/self/sites") return reply(res, 200, { data: [{ name: "default", desc: "Default" }] });
|
||||
if (path === "/api/s/default/stat/device") return reply(res, 200, { data: legacyDevices });
|
||||
if (path === "/api/s/default/stat/sta") return reply(res, 200, { data: legacyClients });
|
||||
if (path === "/api/s/default/rest/networkconf") return reply(res, 200, { data: legacyNetworks });
|
||||
if (path === "/api/s/default/rest/wlanconf") return reply(res, 200, { data: legacyWlans });
|
||||
return reply(res, 404, {});
|
||||
@@ -206,6 +225,23 @@ describe("normalising what a controller says", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("what is connected where", () => {
|
||||
test("a client from either API: its address, whether it is wired, and the device it is on (and the port, on the classic one)", () => {
|
||||
const macById = new Map([["d-sw", MAC.sw]]);
|
||||
assert.deepEqual(clientFromApi(clientList.data[0], macById, "Default"), { mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", name: "web", wired: true, uplinkExternalId: MAC.sw, port: null, siteName: "Default" });
|
||||
assert.equal(clientFromApi(clientList.data[2], macById, "Default")!.uplinkExternalId, null, "an unknown device is no uplink");
|
||||
assert.deepEqual(clientFromLegacy(legacyClients[0], "Default"), { mac: "aa:bb:cc:00:00:50", ip: "192.168.1.50", name: "web", wired: true, uplinkExternalId: MAC.sw, port: 7, siteName: "Default" });
|
||||
assert.deepEqual([clientFromLegacy(legacyClients[1], "Default")!.wired, clientFromLegacy(legacyClients[1], "Default")!.uplinkExternalId], [false, MAC.ap]);
|
||||
});
|
||||
|
||||
test("a server is plugged into a device only by an exact, unambiguous address on a device that is known", () => {
|
||||
const servers = [{ id: 1, ipAddresses: JSON.stringify(["10.0.0.1", "10.0.0.2"]) }, { id: 2, ipAddresses: JSON.stringify(["10.0.0.2", "10.0.0.3"]) }, { id: 3, ipAddresses: "not json" }, { id: 4, ipAddresses: null }];
|
||||
const c = (mac: string, ip: string | null, up: string | null) => ({ mac, ip, name: null, wired: true, uplinkExternalId: up, port: 3, siteName: "Default" });
|
||||
const links = matchClientsToServers([c("m1", "10.0.0.1", MAC.sw), c("m2", "10.0.0.2", MAC.sw), c("m3", "10.0.0.3", MAC.ap), c("m4", "10.0.0.1", "ff:ff:ff:ff:ff:ff"), c("m5", null, MAC.sw), c("m1", "10.0.0.1", MAC.sw)], servers, new Set([MAC.sw, MAC.ap]));
|
||||
assert.deepEqual(links.map((l) => [l.serverId, l.deviceExternalId, l.clientMac]), [[1, MAC.sw, "m1"], [2, MAC.ap, "m3"]], "10.0.0.2 belongs to two servers, so to neither; an unknown device and no address count for nothing; a repeat is one link");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reading a controller", () => {
|
||||
const cfg = (extra: Record<string, unknown>) => ({ url: controllerUrl, ...extra }) as never;
|
||||
|
||||
@@ -321,7 +357,7 @@ describe("a controller in the database", () => {
|
||||
const [cred] = await db.insert(integrationCredentials).values({ name: "unifi:Home", encryptedSecret: encryptSecret(JSON.stringify({ apiKey: "good-key" })) }).returning();
|
||||
const [row] = await db.insert(integrations).values({ type: "unifi", name: "Home UniFi", baseUrl: controllerUrl, credentialId: cred.id, config: JSON.stringify({ url: controllerUrl }) }).returning();
|
||||
integrationId = row.id;
|
||||
webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString() }).returning({ id: servers.id }))[0].id;
|
||||
webId = (await db.insert(servers).values({ name: "web", apiTokenHash: "w", apiTokenPrefix: "w", lastSeenAt: new Date().toISOString(), ipAddresses: JSON.stringify(["192.168.1.50"]) }).returning({ id: servers.id }))[0].id;
|
||||
});
|
||||
|
||||
test("the first read stores the devices, the networks and the Wi-Fi names, and says how it went", async () => {
|
||||
@@ -361,6 +397,33 @@ describe("a controller in the database", () => {
|
||||
assert.equal((await syncUnifiIntegration(integrationId)).ok, true);
|
||||
});
|
||||
|
||||
test("the server whose address is on the controller's client list is plugged into the switch the controller says, and needs it", async () => {
|
||||
const links = await db.select().from(networkServerLinks);
|
||||
assert.equal(links.length, 1, "the phone and the stranger match no server");
|
||||
assert.deepEqual([links[0].serverId, links[0].deviceExternalId, links[0].wired, links[0].clientMac], [webId, MAC.sw, true, "aa:bb:cc:00:00:50"]);
|
||||
const graph = await loadGraph();
|
||||
assert.ok(graph.edges.get(`server:${webId}`)?.includes(`device:${swId}`));
|
||||
// the switch is down: the server (offline too) is explained by it, with nothing written by hand
|
||||
const cover = await dependencyCover([webId], [], [swId]);
|
||||
assert.equal(cover.cause.get(`server:${webId}`), `device:${swId}`);
|
||||
});
|
||||
|
||||
test("a controller that lists no clients says nothing, so what was known stays", async () => {
|
||||
const [row] = await db.select().from(integrations);
|
||||
const before = (await db.select().from(networkServerLinks)).length;
|
||||
const { storeInventory } = await import("../src/services/unifiSync.js");
|
||||
await storeInventory(row.id, { mode: "api_key", sites: ["Default"], devices: [], networks: [], ssids: [], clients: [] });
|
||||
assert.equal((await db.select().from(networkServerLinks)).length, before);
|
||||
assert.equal((await db.select().from(networkDevices)).length, 0, "the devices, on the other hand, are gone from it");
|
||||
assert.equal((await syncUnifiIntegration(row.id)).ok, true, "and come back on the next read");
|
||||
// device ids are new now: look them up again
|
||||
const rows = await db.select().from(networkDevices);
|
||||
gwId = rows.find((r) => r.name === "Gateway")!.id;
|
||||
swId = rows.find((r) => r.name === "Rack switch")!.id;
|
||||
apId = rows.find((r) => r.name === "Hallway AP")!.id;
|
||||
await db.delete(dependencies);
|
||||
});
|
||||
|
||||
test("uplinks are dependencies nobody had to write: the access point needs the switch, which needs the gateway", async () => {
|
||||
const graph = await loadGraph();
|
||||
assert.deepEqual(graph.edges.get(`device:${apId}`), [`device:${swId}`]);
|
||||
@@ -433,6 +496,15 @@ describe("a controller in the database", () => {
|
||||
invalidateAlertsCache();
|
||||
});
|
||||
|
||||
test("the Connections map draws a device that has a server on it, with its state", async () => {
|
||||
const map = await buildTopology();
|
||||
const sw = map.nodes.find((n) => n.kind === "device");
|
||||
assert.ok(sw, "the switch is on the map");
|
||||
assert.deepEqual([sw!.label, sw!.status, sw!.href], ["Rack switch", "ok", "/network/devices"]);
|
||||
assert.ok(map.edges.some((e) => e.from === sw!.id && e.to === `server:${webId}`));
|
||||
assert.equal(map.nodes.filter((n) => n.kind === "device").length, 1, "the access point and gateway have no server on them");
|
||||
});
|
||||
|
||||
describe("the page's data", () => {
|
||||
let app: Server;
|
||||
let base = "";
|
||||
@@ -459,7 +531,9 @@ describe("a controller in the database", () => {
|
||||
const by = Object.fromEntries(body.devices.map((d: any) => [d.name, d]));
|
||||
assert.deepEqual([by["Rack switch"].ip, by["Rack switch"].uptimeSeconds, by["Rack switch"].uplink.name, by["Rack switch"].firmwareUpdatable], ["192.168.1.2", 3600, "Gateway", true]);
|
||||
assert.equal(by["Hallway AP"].state, "offline");
|
||||
assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind them");
|
||||
assert.equal(by["Gateway"].dependents, 3, "the switch, the access point and the server behind it");
|
||||
assert.deepEqual(by["Rack switch"].servers.map((x: any) => [x.serverName, x.port, x.wired]), [["web", null, true]]);
|
||||
assert.deepEqual(body.serverLinks.map((l: any) => [l.serverName, l.deviceName]), [["web", "Rack switch"]]);
|
||||
assert.equal(by["Hallway AP"].needs, 2);
|
||||
assert.equal(by["Rack switch"].inMaintenance, true);
|
||||
assert.deepEqual(body.networks.map((n: any) => [n.name, n.vlanId, n.subnet]), [["Default", 1, "192.168.1.1/24"], ["IoT", 20, "192.168.20.1/24"]]);
|
||||
@@ -468,6 +542,29 @@ describe("a controller in the database", () => {
|
||||
assert.ok(!JSON.stringify(body).includes(SECRET_PASSPHRASE));
|
||||
});
|
||||
|
||||
test("the devices' addresses can be added to the IP addresses, and a hand-made entry is left alone", async () => {
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: "operator" } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/ipam", ipamRouter);
|
||||
const s = await new Promise<Server>((resolve) => {
|
||||
const x = a.listen(0, "127.0.0.1", () => resolve(x));
|
||||
});
|
||||
const ipam = `http://127.0.0.1:${(s.address() as AddressInfo).port}/api/ipam/sync-unifi`;
|
||||
await db.insert(ipamEntries).values({ ipAddress: "192.168.1.3", label: "mine" });
|
||||
const res = await fetch(ipam, { method: "POST" });
|
||||
const body = (await res.json()) as any;
|
||||
assert.deepEqual([body.added, body.skipped, body.skippedIps], [2, 1, ["192.168.1.3"]]);
|
||||
const rows = await db.select().from(ipamEntries);
|
||||
assert.deepEqual(rows.find((r) => r.ipAddress === "192.168.1.2")!.label, "Rack switch");
|
||||
assert.equal(rows.find((r) => r.ipAddress === "192.168.1.3")!.label, "mine");
|
||||
assert.equal(rows.find((r) => r.ipAddress === "192.168.1.1")!.source, "unifi");
|
||||
s.close();
|
||||
});
|
||||
|
||||
test("reading again needs an operator", async () => {
|
||||
who = "viewer";
|
||||
assert.equal((await fetch(`${base}/sync`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })).status, 403);
|
||||
@@ -484,6 +581,7 @@ describe("a controller in the database", () => {
|
||||
await removeIntegrationData(integrationId);
|
||||
assert.equal((await db.select().from(networkDevices)).length, 0);
|
||||
assert.equal((await db.select().from(networkSegments)).length, 0);
|
||||
assert.equal((await db.select().from(networkServerLinks)).length, 0);
|
||||
assert.equal((await db.select().from(dependencies)).length, 0);
|
||||
assert.equal((await syncStatuses())[integrationId], undefined);
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user