UniFi integration: network devices, Wi-Fi and networks, as part of the dependency map

A UniFi controller (API key on Network 9+, or a read-only local login on any
version) is read every five minutes. Its switches, access points and gateways
are kept with state, IP, uptime, firmware and uplink; its networks and Wi-Fi
names beside them (passphrases are never read). Nothing is written to the
controller.

Network > Network devices lists them. Devices are a new node type in the
dependency map: uplinks become dependencies by themselves, others can be
written by hand. A device offline past a limit is an offline alert, folds what
depends on it, can be silenced with maintenance and have runbooks.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 00:35:48 +02:00
1 parent 73a06ebe63
commit 396e074108
48 files changed
+6893 -102

No files matched your search

+2
View File
@@ -6,6 +6,7 @@ import Dashboard from "./pages/Dashboard";
import Users from "./pages/Users";
import Secrets from "./pages/Secrets";
import Ipam from "./pages/Ipam";
import NetworkDevices from "./pages/NetworkDevices";
import Ports from "./pages/Ports";
import Dns from "./pages/Dns";
import Servers from "./pages/Servers";
@@ -139,6 +140,7 @@ function Shelled({ user }: { user: CurrentUser }) {
<Route path="/servers/:id" element={<ServerDetail user={user} />} />
<Route path="/dns" element={<Dns user={user} />} />
<Route path="/ipam" element={<Ipam user={user} />} />
<Route path="/network/devices" element={<NetworkDevices user={user} />} />
<Route path="/ports" element={<Ports user={user} />} />
<Route path="/secrets" element={<Secrets user={user} />} />
<Route path="/integrations" element={<Integrations user={user} />} />
+78 -5
View File
@@ -173,10 +173,10 @@ export interface SessionSummary {
expiresAt: string | null;
}
export type MaintenanceTargetType = "server" | "integration" | "dns_provider";
export type MaintenanceTargetType = "server" | "integration" | "dns_provider" | "device";
/** A whole group at once: every server, every enabled integration, every enabled DNS provider, or all of those. */
export type MaintenanceBulkScope = "everything" | "servers" | "integrations" | "dns_providers";
export type MaintenanceBulkScope = "everything" | "servers" | "integrations" | "dns_providers" | "devices";
export interface MaintenanceWindow {
id: number;
@@ -206,6 +206,8 @@ export interface MaintenanceTargets {
servers: { id: number; name: string }[];
integrations: { id: number; name: string; type: string }[];
dnsProviders: { id: number; name: string; providerType: string }[];
/** Network devices read from a UniFi controller. */
devices: { id: number; name: string; kind: string }[];
}
export interface AuditLogEntry {
@@ -512,6 +514,8 @@ export interface HealthCheckSettings {
newPortAlerts: boolean;
/** An alert raised this many times within an hour is "flapping": one message says so and its further messages are held until it has been quiet for an hour. 0 is off. */
flapRaises: number;
/** Minutes a UniFi device may be offline before it is raised. */
deviceOfflineMinutes: number;
}
/** The monthly report: last month's availability, incidents, updates and renewals, in one message on a day of the month. */
@@ -1109,7 +1113,7 @@ export interface LifecycleReport {
export type AssetKind = "server" | "storage" | "network" | "power" | "client" | "other";
export type DependencyNodeType = "server" | "integration";
export type DependencyNodeType = "server" | "integration" | "device";
/** Something that would be affected if another went down (or that it needs): `distance` 1 is directly, 2 through one other, and so on. */
export interface DependencyImpactItem {
@@ -1136,7 +1140,7 @@ export interface DependencyGraphNode {
export interface DependencyGraph {
nodes: DependencyGraphNode[];
/** From the thing that is needed to the thing that needs it. */
edges: { from: string; to: string; kind: "written" | "runs-on" }[];
edges: { from: string; to: string; kind: "written" | "runs-on" | "uplink" }[];
}
export interface DependencyNode {
key: string;
@@ -1152,6 +1156,71 @@ export interface DependenciesResponse {
nodes: DependencyNode[];
}
export type NetworkDeviceKind = "gateway" | "switch" | "access_point" | "other";
export type NetworkDeviceState = "online" | "offline" | "updating" | "pending" | "other";
/** A switch, access point or gateway read from a UniFi controller. */
export interface NetworkDevice {
id: number;
integrationId: number;
integrationName: string;
siteName: string | null;
name: string;
model: string | null;
kind: NetworkDeviceKind;
ip: string | null;
mac: string | null;
state: NetworkDeviceState;
uptimeSeconds: number | null;
firmware: string | null;
firmwareUpdatable: boolean;
/** The device it is connected through, as the controller says. */
uplink: { id: number; name: string } | null;
offlineSince: string | null;
lastOnlineAt: string | null;
updatedAt: string;
/** How many things need it (directly or through others), and how many it needs. */
dependents: number;
needs: number;
inMaintenance: boolean;
}
/** A network (VLAN) or a Wi-Fi name a controller has set up. */
export interface NetworkSegment {
id: number;
integrationId: number;
integrationName: string;
externalId: string;
siteName: string | null;
name: string;
enabled: boolean;
vlanId: number | null;
subnet: string | null;
purpose: string | null;
security: string | null;
networkName: string | null;
updatedAt: string;
}
export interface UnifiSyncStatus {
/** When the controller was last read successfully. */
at: string;
ok: boolean;
error: string | null;
sites: string[];
mode: "api_key" | "login" | null;
devices: number;
networks: number;
ssids: number;
}
export interface NetworkOverview {
integrations: { id: number; name: string; enabled: boolean; status: UnifiSyncStatus | null }[];
devices: NetworkDevice[];
networks: NetworkSegment[];
ssids: NetworkSegment[];
}
/** A piece of hardware in the inventory. */
export interface Asset {
id: number;
@@ -1566,7 +1635,7 @@ export interface ManualTaskInput {
enabled?: boolean;
}
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket";
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi";
export interface IntegrationField {
key: string;
@@ -2154,6 +2223,10 @@ export const api = {
request<{ minSeverity: string | null; categories: AlertCategory[] | null }>(`/api/push/${id}`, { method: "PATCH", body: JSON.stringify(data) }),
test: () => request<{ sent: number; removed: number; failed: number }>("/api/push/test", { method: "POST" }),
},
network: {
overview: () => request<NetworkOverview>("/api/network"),
sync: (integrationId?: number) => request<{ statuses: Record<number, UnifiSyncStatus> }>("/api/network/sync", { method: "POST", body: JSON.stringify(integrationId ? { integrationId } : {}) }),
},
dependencies: {
list: () => request<DependenciesResponse>("/api/dependencies"),
impact: (type: DependencyNodeType, id: number) => request<DependencyImpact>(`/api/dependencies/impact?type=${type}&id=${id}`),
+2
View File
@@ -42,6 +42,7 @@ const INTEGRATION_TYPE_LABELS: Record<IntegrationType, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
const DNS_PROVIDER_LABELS: Record<DnsProviderType, string> = {
@@ -350,6 +351,7 @@ export default function CommandPalette({
...targets.servers.map((s) => ({ type: "server" as const, id: s.id, name: s.name, kind: "server" })),
...targets.integrations.map((i) => ({ type: "integration" as const, id: i.id, name: i.name, kind: i.type })),
...targets.dnsProviders.map((p) => ({ type: "dns_provider" as const, id: p.id, name: p.name, kind: "DNS provider" })),
...targets.devices.map((d) => ({ type: "device" as const, id: d.id, name: d.name, kind: "network device" })),
];
for (const t of targetList) {
for (const [minutes, words] of [
+6 -4
View File
@@ -13,6 +13,8 @@ const COL_GAP = 120;
const STATUS_SYMBOL: Record<DependencyGraphNode["status"], string> = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" };
const STATUS_WORD: Record<DependencyGraphNode["status"], string> = { ok: "working", bad: "problem", warn: "check", unknown: "no status" };
const KIND_LABEL: Record<DependencyGraphNode["type"], string> = { server: "Server", integration: "Integration", device: "Network device" };
interface Placed extends DependencyGraphNode {
x: number;
y: number;
@@ -142,17 +144,17 @@ export default function DependencyMap() {
const upPath = (e.to === active || sets.up.has(e.to)) && sets.up.has(e.from);
cls = downPath ? "map-edge map-edge-down" : upPath ? "map-edge map-edge-up" : "map-edge map-dim";
}
return <path key={`${e.from}>${e.to}`} d={`M${x1},${y1} C${mid},${y1} ${mid},${y2} ${x2},${y2}`} className={cls} fill="none" strokeDasharray={e.kind === "runs-on" ? "5 4" : undefined} />;
return <path key={`${e.from}>${e.to}`} d={`M${x1},${y1} C${mid},${y1} ${mid},${y2} ${x2},${y2}`} className={cls} fill="none" strokeDasharray={e.kind !== "written" ? "5 4" : undefined} />;
})}
</svg>
{[...view.placed.values()].map((n) => (
<button
key={n.key}
type="button"
className={`map-node map-node-${n.type === "server" ? "server" : "monitor"} ${state(n.key)}`}
className={`map-node map-node-${n.type === "server" ? "server" : n.type === "device" ? "device" : "monitor"} ${state(n.key)}`}
style={{ left: n.x, top: n.y, width: NODE_W, height: NODE_H, textAlign: "left" }}
aria-pressed={selected === n.key}
aria-label={`${n.type === "server" ? "Server" : "Integration"}: ${n.name}, ${STATUS_WORD[n.status]}. Show what depends on it.`}
aria-label={`${KIND_LABEL[n.type]}: ${n.name}, ${STATUS_WORD[n.status]}. Show what depends on it.`}
onClick={() => setSelected((s) => (s === n.key ? null : n.key))}
onMouseEnter={() => setHover(n.key)}
onMouseLeave={() => setHover((h) => (h === n.key ? null : h))}
@@ -164,7 +166,7 @@ export default function DependencyMap() {
</span>
<span className="map-label">
<span className="map-title">{n.name}</span>
<span className="map-sub">{n.type === "server" ? "Server" : "Integration"}</span>
<span className="map-sub">{KIND_LABEL[n.type]}</span>
</span>
</button>
))}
+2 -2
View File
@@ -26,14 +26,14 @@ export default function ImpactNote({
const keyOf = targets.map((t) => `${t.type}:${t.id}`).sort().join(",");
useEffect(() => {
const own = targets.filter((t) => t.type === "server" || t.type === "integration");
const own = targets.filter((t) => t.type === "server" || t.type === "integration" || t.type === "device");
if (own.length === 0) {
setItems([]);
return;
}
let alive = true;
setItems(null);
Promise.all(own.map((t) => api.dependencies.impact(t.type as "server" | "integration", t.id).catch(() => null)))
Promise.all(own.map((t) => api.dependencies.impact(t.type as "server" | "integration" | "device", t.id).catch(() => null)))
.then((all) => {
if (!alive) return;
const selected = new Set(own.map((t) => `${t.type}:${t.id}`));
+3 -1
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import { api, type IntegrationField, type IntegrationSummary, type IntegrationType } from "../api/client";
import { readableError } from "../utils/errors";
import { BlockSkeleton } from "./Skeleton";
const TYPE_LABELS: Record<IntegrationType, string> = {
@@ -13,6 +14,7 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
export default function IntegrationEditForm({
@@ -85,7 +87,7 @@ export default function IntegrationEditForm({
await api.integrations.update(integration.id, { name, config: collectOverrides() });
onSaved();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
setError(readableError(err));
} finally {
setSaving(false);
}
+4 -2
View File
@@ -1,5 +1,6 @@
import { useEffect, useState } from "react";
import { api, type IntegrationField, type IntegrationType } from "../api/client";
import { readableError } from "../utils/errors";
const TYPE_LABELS: Record<IntegrationType, string> = {
tailscale: "Tailscale",
@@ -12,6 +13,7 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
export default function IntegrationForm({ onCreated, onCancel }: { onCreated: () => void; onCancel: () => void }) {
@@ -52,7 +54,7 @@ export default function IntegrationForm({ onCreated, onCancel }: { onCreated: ()
const result = await api.integrations.test({ type, config: values });
setTestResult(result);
} catch (err) {
setTestResult({ ok: false, error: err instanceof Error ? err.message : String(err) });
setTestResult({ ok: false, error: readableError(err) });
} finally {
setTesting(false);
}
@@ -67,7 +69,7 @@ export default function IntegrationForm({ onCreated, onCancel }: { onCreated: ()
await api.integrations.create({ type, name, config: values });
onCreated();
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
setError(readableError(err));
} finally {
setSaving(false);
}
@@ -87,6 +87,7 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
const groups: { label: string; type: MaintenanceTargetType; items: { id: number; name: string }[] }[] = [
{ label: "Servers", type: "server", items: targets?.servers ?? [] },
{ label: "Integrations", type: "integration", items: targets?.integrations ?? [] },
{ label: "Network devices", type: "device", items: targets?.devices ?? [] },
{ label: "DNS providers", type: "dns_provider", items: targets?.dnsProviders ?? [] },
];
+5 -5
View File
@@ -1,5 +1,5 @@
import { useState } from "react";
import { api, type AlertItem } from "../api/client";
import { api, type AlertItem, type MaintenanceTargetType } from "../api/client";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
@@ -14,11 +14,11 @@ const CHOICES = [
* about that server or integration, not just this one alert — which is what a maintenance window is — so it says so, and the
* Maintenance page is where to end it early. The choices open in place, so nothing is clipped by the table around it.
*/
export default function SilenceButton({ alert, onDone }: { alert: AlertItem; onDone: () => void }) {
export default function SilenceButton({ alert, target: given, onDone }: { alert?: AlertItem; /** Instead of an alert: silence this thing directly. */ target?: { type: MaintenanceTargetType; id: number; name: string }; onDone: () => void }) {
const [choosing, setChoosing] = useState(false);
const [busy, setBusy] = useState(false);
const target = alert.target;
if (!target || alert.silenced) return null;
const target = alert?.target ?? given;
if (!target || alert?.silenced) return null;
async function silence(minutes: number, words: string) {
if (!target) return;
@@ -28,7 +28,7 @@ export default function SilenceButton({ alert, onDone }: { alert: AlertItem; onD
targetType: target.type,
targetId: target.id,
minutes,
reason: `Silenced from the Alerts page: ${alert.message}`.slice(0, 200),
reason: (alert ? `Silenced from the Alerts page: ${alert.message}` : `Silenced from the Network devices page`).slice(0, 200),
});
toast.success(`${target.name} is silenced for ${words} — every alert about it. End it early under Maintenance.`);
// The sidebar badge and the maintenance banner listen for this.
+1
View File
@@ -15,6 +15,7 @@ const TYPE_LABELS: Record<string, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup",
osticket: "osTicket",
unifi: "UniFi",
};
export type WallLevel = "critical" | "warning" | "ok" | "unsure";
+2
View File
@@ -4,6 +4,7 @@ import {
IconServer2,
IconWorld,
IconNetwork,
IconRouter,
IconKey,
IconPlugConnected,
IconBrandDocker,
@@ -92,6 +93,7 @@ export const NAV: NavEntry[] = [
icon: <IconWorld size={20} />,
items: [
{ to: "/dns", label: "DNS", icon: <IconWorld size={20} /> },
{ to: "/network/devices", label: "Network devices", icon: <IconRouter size={20} /> },
{ to: "/ipam", label: "IP Addresses", icon: <IconNetwork size={20} /> },
{ to: "/ports", label: "Ports", icon: <IconPlug size={20} /> },
{ to: "/consistency", label: "Consistency", icon: <IconListCheck size={20} /> },
+2
View File
@@ -25,6 +25,7 @@ const TYPE_LABELS: Record<IntegrationType, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
/** The page each kind of integration gets once it is connected. */
@@ -39,6 +40,7 @@ const TYPE_PAGES: Record<IntegrationType, string> = {
phpipam: "/ipam",
pbs: "/pbs",
osticket: "/osticket",
unifi: "/network/devices",
};
/** "pve.example.lan" out of "https://pve.example.lan:8006/", or the text itself when it isn't an address. */
+12 -2
View File
@@ -265,9 +265,10 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
<label className="form-label">What are you working on?</label>
<select className="form-select" required value={target} onChange={(e) => setTarget(e.target.value)}>
<option value="">Choose…</option>
{targets && targets.servers.length + targets.integrations.length + targets.dnsProviders.length > 1 && (
{targets && targets.servers.length + targets.integrations.length + targets.dnsProviders.length + targets.devices.length > 1 && (
<optgroup label="Many at once">
<option value="all:everything">Everything — every server, integration and DNS provider</option>
<option value="all:everything">Everything — every server, integration, network device and DNS provider</option>
{targets.devices.length > 1 && <option value="all:devices">All network devices ({targets.devices.length})</option>}
{targets.servers.length > 1 && <option value="all:servers">All servers ({targets.servers.length})</option>}
{targets.integrations.length > 1 && <option value="all:integrations">All integrations (the enabled ones)</option>}
{targets.dnsProviders.length > 1 && <option value="all:dns_providers">All DNS providers (the enabled ones)</option>}
@@ -291,6 +292,15 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
))}
</optgroup>
)}
{targets && targets.devices.length > 0 && (
<optgroup label="Network devices">
{targets.devices.map((d) => (
<option key={`n${d.id}`} value={`device:${d.id}`}>
{d.name} ({d.kind.replace("_", " ")})
</option>
))}
</optgroup>
)}
{targets && targets.dnsProviders.length > 0 && (
<optgroup label="DNS providers">
{targets.dnsProviders.map((p) => (
+420
View File
@@ -0,0 +1,420 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { api, type CurrentUser, type NetworkDevice, type NetworkDeviceKind, type NetworkOverview, type NetworkSegment } from "../api/client";
import SortableTh from "../components/SortableTh";
import Pagination from "../components/Pagination";
import TableToolbar from "../components/TableToolbar";
import TimeAgo from "../components/TimeAgo";
import ViewTabs from "../components/ViewTabs";
import SilenceButton from "../components/SilenceButton";
import RunbookEntry from "../components/RunbookEntry";
import CopyButton from "../components/CopyButton";
import EmptyState, { EmptyRow } from "../components/EmptyState";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { useSortable } from "../hooks/useSortable";
import { useTableSearch } from "../hooks/useTableSearch";
import { usePagination } from "../hooks/usePagination";
import { downloadCsv } from "../utils/csv";
import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
const KIND_LABELS: Record<NetworkDeviceKind, string> = { gateway: "Gateway", switch: "Switch", access_point: "Access point", other: "Other" };
/** "12 d 3 h", "5 h 20 min", "40 min". */
export function uptimeWords(seconds: number | null): string {
if (seconds === null) return "—";
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return `${minutes} min`;
const hours = Math.floor(minutes / 60);
if (hours < 48) return `${hours} h ${minutes % 60} min`;
const days = Math.floor(hours / 24);
return `${days} d ${hours % 24} h`;
}
type Row = NetworkDevice & { uplinkName: string; stateRank: number };
const STATE_RANK: Record<NetworkDevice["state"], number> = { offline: 0, updating: 1, pending: 2, other: 3, online: 4 };
function StateBadge({ d }: { d: NetworkDevice }) {
switch (d.state) {
case "online":
return <span className="badge bg-green-lt text-green">Online</span>;
case "offline":
return (
<span className="badge bg-red-lt text-red" title="The controller has not seen it online">
Offline{d.offlineSince ? <> · <TimeAgo value={d.offlineSince} /></> : null}
</span>
);
case "updating":
return <span className="badge bg-yellow-lt text-yellow">Updating</span>;
case "pending":
return <span className="badge bg-blue-lt text-blue">Being adopted</span>;
default:
return <span className="badge bg-secondary-lt text-secondary">Unknown</span>;
}
}
/**
* The switches, access points and gateways a UniFi controller knows: how each is doing, its address, how long it has been up, what it is connected through and what
* depends on it — and, on the other tab, the networks and Wi-Fi names. Read from the controller every few minutes; what is shown is what was last read.
*/
export default function NetworkDevices({ user }: { user: CurrentUser }) {
const canAct = user.role === "admin" || user.role === "operator";
const [params] = useSearchParams();
const view = params.get("view") === "wifi" ? "wifi" : "devices";
const [data, setData] = useState<NetworkOverview | null>(null);
const [error, setError] = useState<string | null>(null);
const [reading, setReading] = useState(false);
const [kind, setKind] = useState<"all" | NetworkDeviceKind>("all");
const [status, setStatus] = useState<"all" | "problem">("all");
const load = useCallback(() => {
return api.network
.overview()
.then((res) => {
setData(res);
setError(null);
})
.catch((err) => setError(readableError(err)));
}, []);
useEffect(() => {
void load();
const timer = setInterval(() => void load(), 60_000);
return () => clearInterval(timer);
}, [load]);
async function readNow() {
setReading(true);
try {
const res = await api.network.sync();
const failed = Object.values(res.statuses).filter((s) => !s.ok);
if (failed.length > 0) toast.error(`Couldn't read ${failed.length === 1 ? "a controller" : `${failed.length} controllers`}: ${failed[0].error ?? "no answer"}`);
else toast.success("Read from the controller.");
await load();
} catch (err) {
toast.error(readableError(err));
} finally {
setReading(false);
}
}
const rows: Row[] = useMemo(
() =>
(data?.devices ?? [])
.filter((d) => (kind === "all" || d.kind === kind) && (status === "all" || d.state === "offline" || d.firmwareUpdatable))
.map((d) => ({ ...d, uplinkName: d.uplink?.name ?? "", stateRank: STATE_RANK[d.state] })),
[data, kind, status],
);
const tableSearch = useTableSearch(rows);
const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "stateRank", "asc", { url: true });
const { pageItems, page, setPage, pageCount, totalCount } = usePagination(sorted);
const devices = data?.devices ?? [];
const offline = devices.filter((d) => d.state === "offline").length;
const updates = devices.filter((d) => d.firmwareUpdatable).length;
const controllers = data?.integrations.filter((i) => i.enabled) ?? [];
const tabs = (
<ViewTabs
label="Network devices view"
tabs={[
{ to: "/network/devices", label: "Devices", active: view === "devices" },
{ to: "/network/devices?view=wifi", label: "Networks & Wi-Fi", active: view === "wifi" },
]}
/>
);
function exportCsv() {
downloadCsv(
"network-devices.csv",
["Name", "Kind", "Model", "State", "IP address", "MAC address", "Uptime (seconds)", "Firmware", "Update available", "Connected through", "Needed by", "Controller", "Site"],
(sorted ?? []).map((d) => [d.name, KIND_LABELS[d.kind], d.model ?? "", d.state, d.ip ?? "", d.mac ?? "", d.uptimeSeconds ?? "", d.firmware ?? "", d.firmwareUpdatable ? "yes" : "no", d.uplinkName, d.dependents, d.integrationName, d.siteName ?? ""]),
);
}
const noController = data !== null && data.integrations.length === 0;
return (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-1">
<h2 className="page-title mb-0">Network devices</h2>
{canAct && controllers.length > 0 && (
<div className="ms-auto btn-list">
<button className="btn btn-outline-secondary" onClick={() => void readNow()} disabled={reading}>
{reading ? "Reading…" : "Read now"}
</button>
</div>
)}
</div>
{tabs}
<div className="text-secondary mb-3">
Switches, access points and gateways from your UniFi controller: whether each is up, its address, how long it has been running, and what it is connected through. The same devices take part in the
dependency map, so when one is down what hangs off it is folded under its alert.
</div>
<ErrorNotice error={error} />
{data === null && !error && <BlockSkeleton lines={4} />}
{noController && (
<div className="card">
<EmptyState
title="No UniFi controller connected"
hint="Add a UniFi integration — an API key from the controller's Integrations settings, or a read-only local account — and its switches, access points and gateways appear here."
action={user.role === "admin" ? { label: "Add a UniFi controller", to: "/integrations" } : undefined}
/>
</div>
)}
{data && data.integrations.length > 0 && (
<div className="mb-3 small">
{data.integrations.map((i) => (
<div key={i.id} className={i.status && !i.status.ok ? "text-red" : "text-secondary"}>
<strong>{i.name}</strong>
{!i.enabled ? (
" — switched off"
) : !i.status ? (
" — not read yet"
) : i.status.ok ? (
<>
{" "}
— read <TimeAgo value={i.status.at} /> · {i.status.devices} {i.status.devices === 1 ? "device" : "devices"}
{i.status.sites.length > 0 ? `, ${i.status.sites.length === 1 ? "site" : "sites"} ${i.status.sites.join(", ")}` : ""}
{i.status.mode ? ` · via ${i.status.mode === "api_key" ? "API key" : "login"}` : ""}
</>
) : (
<>
{" "}
— couldn&rsquo;t be read: {i.status.error}. Showing what was read <TimeAgo value={i.status.at} />; alerts for its devices are held until it can be read again.
</>
)}
</div>
))}
</div>
)}
{data && data.integrations.length > 0 && view === "devices" && (
<>
<div className="row row-cards mb-3">
{[
{ label: "Devices", value: devices.length, color: "" },
{ label: "Offline", value: offline, color: offline > 0 ? "text-red" : "text-green" },
{ label: "Firmware updates", value: updates, color: updates > 0 ? "text-yellow" : "" },
{ label: "Controllers", value: controllers.length, color: "" },
].map((c) => (
<div className="col-6 col-lg-3" key={c.label}>
<div className="card card-sm">
<div className="card-body">
<div className={`h2 mb-0 ${c.color}`}>{c.value}</div>
<div className="text-secondary">{c.label}</div>
</div>
</div>
</div>
))}
</div>
<div className="card">
<TableToolbar
search={tableSearch.query}
onSearch={tableSearch.setQuery}
placeholder="Search devices…"
filters={
<>
<select className="form-select form-select-sm w-auto" aria-label="Kind of device" value={kind} onChange={(e) => setKind(e.target.value as typeof kind)}>
<option value="all">Every kind</option>
{(Object.keys(KIND_LABELS) as NetworkDeviceKind[]).map((k) => (
<option key={k} value={k}>
{KIND_LABELS[k]}
</option>
))}
</select>
<select className="form-select form-select-sm w-auto" aria-label="Which devices" value={status} onChange={(e) => setStatus(e.target.value as typeof status)}>
<option value="all">All devices</option>
<option value="problem">Offline or with an update waiting</option>
</select>
</>
}
shown={sorted?.length}
total={devices.length}
onExport={exportCsv}
exportDisabled={!sorted || sorted.length === 0}
/>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<SortableTh<Row> label="Status" sortKeyName="stateRank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Name" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="IP address" sortKeyName="ip" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Uptime" sortKeyName="uptimeSeconds" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Firmware" sortKeyName="firmware" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Connected through" sortKeyName="uplinkName" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Needed by" sortKeyName="dependents" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
{canAct && (
<th className="w-1">
<span className="visually-hidden">Actions</span>
</th>
)}
</tr>
</thead>
<tbody>
{(pageItems ?? []).map((d) => (
<tr key={d.id}>
<td>
<StateBadge d={d} />
{d.inMaintenance && (
<span className="badge bg-secondary-lt text-secondary ms-1" title="Under a maintenance window — its alerts are held back">
maintenance
</span>
)}
</td>
<td className="stack-wide">
<strong>{d.name}</strong>
<div className="text-secondary small">
{KIND_LABELS[d.kind]}
{d.model ? ` · ${d.model}` : ""}
{data.integrations.length > 1 ? ` · ${d.integrationName}` : ""}
{d.siteName && d.siteName !== "Default" ? ` · ${d.siteName}` : ""}
</div>
{d.mac && <div className="text-secondary small font-monospace">{d.mac}</div>}
</td>
<td className="stack-label" data-label="IP address">
{d.ip ? (
<span className="d-inline-flex align-items-center gap-2">
<span className="font-monospace">{d.ip}</span>
<CopyButton text={d.ip} />
</span>
) : (
<span className="text-secondary">—</span>
)}
</td>
<td className="stack-label text-nowrap" data-label="Uptime">
{d.state === "online" ? uptimeWords(d.uptimeSeconds) : <span className="text-secondary">—</span>}
</td>
<td className="stack-label" data-label="Firmware">
{d.firmware ?? <span className="text-secondary">—</span>}
{d.firmwareUpdatable && <span className="badge bg-yellow-lt text-yellow ms-1">update available</span>}
</td>
<td className="stack-label" data-label="Connected through">
{d.uplink ? d.uplink.name : <span className="text-secondary">{d.kind === "gateway" ? "(the internet)" : "—"}</span>}
</td>
<td className="stack-label" data-label="Needed by">
{d.dependents > 0 ? (
<Link to="/map?view=dependencies" title="Open the dependency map">
{d.dependents} {d.dependents === 1 ? "thing" : "things"}
</Link>
) : (
<span className="text-secondary">nothing</span>
)}
</td>
{canAct && (
<td className="text-nowrap stack-wide">
<div className="btn-list flex-nowrap align-items-center">
{!d.inMaintenance && <SilenceButton target={{ type: "device", id: d.id, name: d.name }} onDone={() => void load()} />}
<RunbookEntry targetType="device" targetId={d.id} targetName={d.name} canEdit={canAct} offerAdd />
</div>
</td>
)}
</tr>
))}
{(sorted ?? []).length === 0 && (
<EmptyRow
colSpan={canAct ? 8 : 7}
{...(tableSearch.active || kind !== "all" || status !== "all"
? { filtered: () => { tableSearch.setQuery(""); setKind("all"); setStatus("all"); } }
: { title: "No devices yet", hint: "The controller has not reported any, or has not been read yet. Press Read now." })}
/>
)}
</tbody>
</table>
</div>
<Pagination page={page} pageCount={pageCount} totalCount={totalCount} onPageChange={setPage} />
</div>
</>
)}
{data && data.integrations.length > 0 && view === "wifi" && <NetworksAndWifi data={data} />}
</>
);
}
function enabledBadge(on: boolean) {
return on ? <span className="badge bg-green-lt text-green">On</span> : <span className="badge bg-secondary-lt text-secondary">Off</span>;
}
function NetworksAndWifi({ data }: { data: NetworkOverview }) {
const many = data.integrations.length > 1;
const where = (s: NetworkSegment) => [many ? s.integrationName : null, s.siteName && s.siteName !== "Default" ? s.siteName : null].filter(Boolean).join(" · ");
return (
<>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Networks</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Name</th>
<th>VLAN</th>
<th>Address range</th>
<th>Purpose</th>
<th>State</th>
</tr>
</thead>
<tbody>
{data.networks.map((n) => (
<tr key={n.id}>
<td className="stack-wide">
<strong>{n.name}</strong>
{where(n) && <div className="text-secondary small">{where(n)}</div>}
</td>
<td className="stack-label" data-label="VLAN">{n.vlanId ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label font-monospace" data-label="Address range">{n.subnet ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="Purpose">{n.purpose ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="State">{enabledBadge(n.enabled)}</td>
</tr>
))}
{data.networks.length === 0 && <EmptyRow colSpan={5} title="No networks read" hint="The controller reported none, or the account or key may not be allowed to read them." />}
</tbody>
</table>
</div>
</div>
<div className="card">
<div className="card-header">
<h3 className="card-title">Wi-Fi names</h3>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Name (SSID)</th>
<th>Security</th>
<th>Network</th>
<th>VLAN</th>
<th>State</th>
</tr>
</thead>
<tbody>
{data.ssids.map((s) => (
<tr key={s.id}>
<td className="stack-wide">
<strong>{s.name}</strong>
{where(s) && <div className="text-secondary small">{where(s)}</div>}
</td>
<td className="stack-label" data-label="Security">{s.security ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="Network">{s.networkName ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="VLAN">{s.vlanId ?? <span className="text-secondary">—</span>}</td>
<td className="stack-label" data-label="State">{enabledBadge(s.enabled)}</td>
</tr>
))}
{data.ssids.length === 0 && <EmptyRow colSpan={5} title="No Wi-Fi names read" hint="The controller reported none, or the account or key may not be allowed to read them." />}
</tbody>
</table>
</div>
<div className="card-footer text-secondary small">Passphrases are never read from the controller.</div>
</div>
</>
);
}
+1
View File
@@ -23,6 +23,7 @@ const INTEGRATION_NAMES: Record<string, string> = {
phpipam: "phpIPAM",
pbs: "Proxmox Backup Server",
osticket: "osTicket",
unifi: "UniFi",
};
function ColorList({
@@ -82,7 +82,7 @@ const DIGEST_DAYS: { value: number; label: string }[] = [
{ value: 6, label: "Saturday" },
{ value: 0, label: "Sunday" },
];
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3 };
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10 };
const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, day: 1, time: "08:00" };
type TestResult = { ok: boolean; message: string } | null;
@@ -735,6 +735,15 @@ export default function NotificationSettings() {
hint="From each agent server's own history, shown on the Alerts page and dashboard (not sent as a notification). Needs a few days of steady growth to say anything. 0 turns it off."
onChange={(v) => setHealthChecks((h) => ({ ...h, diskForecastDays: v }))}
/>
<NumberField
label="Alert when a network device is offline for"
value={healthChecks.deviceOfflineMinutes}
min={5}
max={1440}
unit="minutes"
hint="Switches, access points and gateways read from a UniFi controller (Network devices). The controller is read every five minutes, and what a device needs or what needs it is folded under it when it is down."
onChange={(v) => setHealthChecks((h) => ({ ...h, deviceOfflineMinutes: v }))}
/>
<label className="form-check mt-3 mb-0">
<input type="checkbox" className="form-check-input" checked={healthChecks.newPortAlerts} onChange={(e) => setHealthChecks((h) => ({ ...h, newPortAlerts: e.target.checked }))} />
<span className="form-check-label">
+4
View File
@@ -988,6 +988,10 @@ a.map-node:focus-visible {
border-left-color: #f6ad55;
}
.map-node-device {
border-left-color: #48bb78;
}
.map-label {
display: flex;
flex-direction: column;
+17 -14
View File
@@ -8,9 +8,9 @@ import { readableError } from "../utils/errors";
import { toast } from "../utils/toast";
import { EmptyRow } from "../components/EmptyState";
const TYPE_LABELS = { server: "Server", integration: "Integration" } as const;
const TYPE_LABELS = { server: "Server", integration: "Integration", device: "Network device" } as const;
const linkTo = (type: string, id: number) => (type === "server" ? `/servers/${id}` : "/integrations");
const linkTo = (type: string, id: number) => (type === "server" ? `/servers/${id}` : type === "device" ? "/network/devices" : "/integrations");
/** The options of a node picker, grouped by what they are. */
function NodeSelect({ id, label, nodes, value, onChange }: { id: string; label: string; nodes: DependencyNode[]; value: string; onChange: (key: string) => void }) {
@@ -21,17 +21,18 @@ function NodeSelect({ id, label, nodes, value, onChange }: { id: string; label:
</label>
<select id={id} className="form-select" value={value} onChange={(e) => onChange(e.target.value)}>
<option value="">— choose —</option>
{(["server", "integration"] as const).map((type) => (
<optgroup key={type} label={`${TYPE_LABELS[type]}s`}>
{nodes
.filter((n) => n.type === type)
.map((n) => (
{(["server", "integration", "device"] as const).map((type) => {
const group = nodes.filter((n) => n.type === type);
return group.length === 0 ? null : (
<optgroup key={type} label={`${TYPE_LABELS[type]}s`}>
{group.map((n) => (
<option key={n.key} value={n.key}>
{n.name}
</option>
))}
</optgroup>
))}
</optgroup>
);
})}
</select>
</>
);
@@ -59,7 +60,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
const parse = (key: string) => {
const [type, id] = key.split(":");
return { type: type as "server" | "integration", id: Number(id) };
return { type: type as "server" | "integration" | "device", id: Number(id) };
};
async function add(e: React.FormEvent) {
@@ -95,7 +96,7 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
return (
<>
<p className="text-secondary">
Say what needs what: Gitea needs the server it is installed on; a Proxmox guest needs the Proxmox it runs on. When the thing that is needed is down, what needs it is down too — and its alert is
Say what needs what: Gitea needs the server it is installed on; a Proxmox guest needs the Proxmox it runs on; a server needs the switch it is plugged into. When the thing that is needed is down, what needs it is down too — and its alert is
held back under the first one on the Alerts page instead of adding to the noise. A service that was down for its own reasons still alerts once what it needs is back.
</p>
<ErrorNotice error={error} />
@@ -170,16 +171,18 @@ export default function DependencyEditor({ user }: { user: CurrentUser }) {
{data && data.runsOn.length > 0 && (
<div className="card">
<div className="card-header">
<h3 className="card-title">Servers that run on servers</h3>
<h3 className="card-title">Set elsewhere</h3>
</div>
<div className="card-body text-secondary small pb-0">
A server&rsquo;s &ldquo;runs on&rdquo; is set on the server itself, or worked out from the Proxmox node it is a guest of. A network device&rsquo;s &ldquo;connected through&rdquo; is what its UniFi controller says. They count here too.
</div>
<div className="card-body text-secondary small pb-0">These are set on each server (&ldquo;runs on&rdquo;), or worked out from the Proxmox node it is a guest of. They count here too.</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<tbody>
{data.runsOn.map((r) => (
<tr key={`${r.from.key}>${r.to.key}`}>
<td>{r.from.name}</td>
<td className="text-secondary">runs on</td>
<td className="text-secondary">{r.from.key.startsWith("device:") && r.to.key.startsWith("device:") ? "is connected through" : "runs on"}</td>
<td>{r.to.name}</td>
</tr>
))}