From 9caa4148299cb5759e5141d733503e6e6003e66f Mon Sep 17 00:00:00 2001 From: Bobban Rydh Date: Sun, 18 Oct 2026 19:17:09 +0200 Subject: [PATCH] Dependency map, impact preview in maintenance, and a calmer Alerts page - Map: a Dependencies view showing what would go down with a picked box and what it relies on - Maintenance: lists what depends on a target and can silence those too (same time, audited); the recurring form and update drawer show the same note - Alerts: a headline on where things stand, held-back alerts nested under their cause, severity edge on rows; caused-by now carries the explaining alert's id Co-Authored-By: Claude Sonnet 5.5 --- README.md | 15 +- server/src/routes/dependencies.ts | 57 +++++- server/src/routes/maintenance.ts | 20 +- server/src/services/alertTypes.ts | 3 +- server/src/services/alerts.ts | 6 +- server/src/services/dependencies.ts | 67 +++++++ server/src/services/topology.ts | 11 +- server/test/dependencies.test.ts | 4 +- server/test/dependencyImpact.test.ts | 183 ++++++++++++++++++ server/test/parentsAndUpdates.test.ts | 2 +- web/src/api/client.ts | 36 +++- web/src/components/DependencyMap.tsx | 195 ++++++++++++++++++++ web/src/components/ImpactNote.tsx | 86 +++++++++ web/src/components/RecurringMaintenance.tsx | 10 + web/src/components/UpdateRunDrawer.tsx | 4 + web/src/pages/Alerts.tsx | 128 ++++++++++++- web/src/pages/Maintenance.tsx | 14 +- web/src/pages/Map.tsx | 66 +++++-- web/src/styles.css | 77 ++++++++ 19 files changed, 944 insertions(+), 40 deletions(-) create mode 100644 server/test/dependencyImpact.test.ts create mode 100644 web/src/components/DependencyMap.tsx create mode 100644 web/src/components/ImpactNote.tsx diff --git a/README.md b/README.md index a1ff053..fb37022 100644 --- a/README.md +++ b/README.md @@ -304,7 +304,10 @@ already failing, so old failures aren't announced. Toggle it under Settings → Notifications. For Gitea this follows the repo's most recent run on any workflow or branch, the same as the Gitea page shows. -**Alerts** (Operations → Alerts, visible to every role) lists everything that's +**Alerts** (Operations → Alerts, visible to every role) opens with one line on where things stand — how many problems need attention and, when some are +held back, which problem explains how many ("nasbox accounts for 3") — and marks each row with a coloured edge by severity. Held-back alerts are nested under +the alert that explains them (switch "Group under their cause" off for the flat list; the choice is remembered): the cause says "Show the 3 alerts held back +under this" and opens them. It lists everything that's wrong right now in one place, instead of waiting for a notification or visiting each page: servers that stopped reporting, full or nearly full disks and volumes (critical from 95%), Synology volume/disk problems, failed or uncovered Proxmox @@ -398,6 +401,10 @@ Uptime Kuma monitors watch it. Hover or tab to a box to light up its connections; each box links to its page. A monitor Uptime Kuma can't be read for leaves a note rather than a silent gap. +The Map's second view, **Dependencies**, draws what needs what with the foundations on the left (the servers and services that take part in +a dependency or a "runs on" link, each with its status). Pick a box and what would go down with it turns red and what it relies on blue, +with a sentence underneath — "If it goes down, 4 things go with it: …" — so the answer to "what breaks if I reboot this?" is there before you do it. + **Wall display** (`/wall`, also on the dashboard and the user menu) is a full-screen status board for a spare monitor or tablet: the overall state in large type, servers online, alerts, maintenance windows and failing integrations, @@ -429,6 +436,12 @@ so it is folded only when every enabled instance of that kind is explained. A se is offline isn't announced; if it is still failing once the server is back, the next failed call alerts. (DNS providers raise no alerts of their own, so they aren't part of this.) +**Seeing the impact before maintenance.** Choosing a server or integration under Maintenance → Start maintenance lists what depends on it and +will look down while it is — and offers to put those under maintenance too, for the same time, with the reason "Depends on …" (ticked by default; +each is its own window, listed and ended like any other, and audited). The recurring-schedule form shows the same note for what is picked and can add +the dependents to the selection. The "Update this server now" drawer shows what depends on the server and may look down while it restarts; it doesn't +silence them, because their windows would outlast the run — use Maintenance first if you want that. + **Recurring maintenance** (Maintenance → Recurring) repeats a window on the days and clock time you choose — "Sundays 02:00–04:00 on these servers" — in the time zone of the browser it was made in, so 02:00 stays 02:00 across summer and winter diff --git a/server/src/routes/dependencies.ts b/server/src/routes/dependencies.ts index e247397..9dd4868 100644 --- a/server/src/routes/dependencies.ts +++ b/server/src/routes/dependencies.ts @@ -2,11 +2,14 @@ import { Router } from "express"; import { eq } from "drizzle-orm"; import { z } from "zod"; import { db } from "../db/client.js"; -import { dependencies } from "../db/schema.js"; +import { dependencies, servers } from "../db/schema.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { invalidateAlertsCache } from "../services/alerts.js"; -import { loadGraph, nodeKey, nodeTypes, wouldLoop } from "../services/dependencies.js"; +import { dependentsOf, impactOf, loadGraph, nodeKey, nodeTypes, wouldLoop } from "../services/dependencies.js"; +import { getSettings } from "../services/settingsStore.js"; +import { getSourceStatus } from "../services/integrationHealthMonitor.js"; +import { serverStatus, type MapStatus } from "../services/topology.js"; import { asyncHandler } from "../utils/asyncHandler.js"; export const dependenciesRouter = Router(); @@ -41,6 +44,56 @@ dependenciesRouter.get("/", asyncHandler(async (_req, res) => { }); })); +// What a thing would take with it, and what it needs itself: for the maintenance and update pages, which say so before it is done. +dependenciesRouter.get("/impact", asyncHandler(async (req, res) => { + const type = nodeTypes.find((t) => t === req.query.type); + const id = typeof req.query.id === "string" && /^\d+$/.test(req.query.id) ? Number(req.query.id) : NaN; + if (!type || !Number.isInteger(id)) return res.status(400).json({ error: "invalid_query", message: "Say which server or integration." }); + const impact = await impactOf(type, id); + if (!impact) return res.status(404).json({ error: "not_found" }); + res.json(impact); +})); + +// The graph for the Map page: the servers and integrations that take part in any dependency, how each is doing, and who needs whom. An edge runs +// from the thing that is needed to the thing that needs it, so the foundations come first. +dependenciesRouter.get("/graph", asyncHandler(async (_req, res) => { + const graph = await loadGraph(); + const written = new Set(graph.rows.map((r) => `${nodeKey(r.fromType, r.fromId)}>${nodeKey(r.toType, r.toId)}`)); + const edges: { from: string; to: string; kind: "written" | "runs-on" }[] = []; + const taking = new Set(); + for (const [needing, needed] of graph.edges) { + for (const n of needed) { + edges.push({ from: n, to: needing, kind: written.has(`${needing}>${n}`) ? "written" : "runs-on" }); + taking.add(needing); + taking.add(n); + } + } + const { healthChecks } = await getSettings(); + const now = new Date(); + const serverRows = await db.select({ id: servers.id, lastSeenAt: servers.lastSeenAt, thresholds: servers.thresholds }).from(servers); + const serverById = new Map(serverRows.map((s) => [s.id, s])); + const intById = new Map(graph.intRows.map((i) => [i.id, i])); + const nodes = [...taking] + .map((key) => { + const [type, rawId] = key.split(":"); + const id = Number(rawId); + let status: MapStatus = "unknown"; + if (type === "server") { + const s = serverById.get(id); + if (s) status = serverStatus(s, healthChecks.serverOfflineMinutes, now); + } else { + const i = intById.get(id); + if (i?.enabled) { + const st = getSourceStatus(i.type).status; + status = st === "failing" ? "bad" : st === "ok" ? "ok" : "unknown"; + } + } + return { key, type: type as "server" | "integration", id, name: graph.names.get(key) ?? key, status, href: type === "server" ? `/servers/${id}` : "/integrations" }; + }) + .sort((a, b) => a.name.localeCompare(b.name)); + res.json({ nodes, edges }); +})); + dependenciesRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => { const parsed = edgeSchema.safeParse(req.body); if (!parsed.success) return res.status(400).json({ error: "invalid_body", message: "Say what needs what: a server or an integration each.", details: parsed.error.flatten() }); diff --git a/server/src/routes/maintenance.ts b/server/src/routes/maintenance.ts index 1790622..8dfc393 100644 --- a/server/src/routes/maintenance.ts +++ b/server/src/routes/maintenance.ts @@ -9,6 +9,7 @@ import { invalidateAlertsCache } from "../services/alerts.js"; import { requireAuth, requireRole } from "../auth/middleware.js"; import { recordAudit } from "../services/audit.js"; import { describeTarget, listActiveWindows, listUpcomingWindows, startOrExtendWindow } from "../services/maintenance.js"; +import { impactOf } from "../services/dependencies.js"; import { KumaSyncError, syncKumaMaintenance } from "../services/kumaMaintenanceSync.js"; import { loadIntegrationConfig } from "../integrations/loadIntegration.js"; import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js"; @@ -56,6 +57,8 @@ const startSchema = z.object({ // Required and capped: an open-ended window is the way this feature could quietly hide a real outage. minutes: z.number().int().min(5).max(7 * 24 * 60), reason: z.string().max(200).optional(), + // Also put what depends on the target under maintenance, for the same time: it will look down while the target is. + withDependents: z.boolean().optional(), }); maintenanceRouter.post("/", requireRole("operator"), asyncHandler(async (req, res) => { @@ -63,7 +66,7 @@ maintenanceRouter.post("/", requireRole("operator"), asyncHandler(async (req, re if (!parsed.success) { return res.status(400).json({ error: "invalid_body", details: parsed.error.flatten() }); } - const { targetType, targetId, minutes, reason } = parsed.data; + const { targetType, targetId, minutes, reason, withDependents } = parsed.data; const actor = req.currentUser!; const createdBy = actor.name ?? actor.email ?? actor.oidcSub; @@ -73,6 +76,19 @@ maintenanceRouter.post("/", requireRole("operator"), asyncHandler(async (req, re return res.status(404).json({ error: "not_found", message: "That target doesn't exist." }); } + // What depends on it goes down with it, so it is silenced for the same time (and says why). + const alsoSilenced: { type: "server" | "integration"; id: number; name: string }[] = []; + if (withDependents && (targetType === "server" || targetType === "integration")) { + const impact = await impactOf(targetType, targetId); + for (const d of impact?.dependents ?? []) { + const also = await startOrExtendWindow(d.type, d.id, minutes, `Depends on ${result.target.name}${reason ? ` — ${reason}` : ""}`.slice(0, 200), createdBy); + if (also) { + alsoSilenced.push({ type: d.type, id: d.id, name: also.target.name }); + await recordAudit({ actor, category: "maintenance", action: also.extended ? "extend" : "start", targetType: d.type, targetId: d.id, detail: { name: also.target.name, minutes, reason: `depends on ${result.target.name}`, dependsOn: result.target.name } }); + } + } + } + await recordAudit({ actor, category: "maintenance", @@ -83,7 +99,7 @@ maintenanceRouter.post("/", requireRole("operator"), asyncHandler(async (req, re }); invalidateAlertsCache(); - res.status(201).json({ window: { ...result.window, targetName: result.target.name, targetKind: result.target.kind } }); + res.status(201).json({ window: { ...result.window, targetName: result.target.name, targetKind: result.target.kind }, alsoSilenced }); })); const importUptimeKumaSchema = z.object({ diff --git a/server/src/services/alertTypes.ts b/server/src/services/alertTypes.ts index ee45119..5142417 100644 --- a/server/src/services/alertTypes.ts +++ b/server/src/services/alertTypes.ts @@ -19,7 +19,8 @@ export interface Alert { /** Under an active maintenance window: still a real problem, but notifications for it are held back. */ silenced: boolean; /** Set when this problem is explained by another one (a guest down because its host is): it is held back like a silenced one, but the reason is this, not maintenance. */ - causedBy?: { name: string }; + /** What explains it: the name of the thing that is down, and the id of the alert about that when there is one. */ + causedBy?: { name: string; alertId?: string }; /** On a host's alert: the servers on it whose own alerts are folded under this one. */ affects?: string[]; /** What a maintenance window would have to be on to silence it, when there is such a thing — which is what "Silence" acts on. */ diff --git a/server/src/services/alerts.ts b/server/src/services/alerts.ts index 60e532e..8a738c0 100644 --- a/server/src/services/alerts.ts +++ b/server/src/services/alerts.ts @@ -33,7 +33,7 @@ import { computeSecretStatus } from "./secretStatus.js"; import { getFailingSources } from "./integrationHealthMonitor.js"; import { getSettings } from "./settingsStore.js"; import { sourceLabel } from "./notify.js"; -import { dependencyCover, integrationTypeCause, takenByType } from "./dependencies.js"; +import { alertIdOfNode, dependencyCover, integrationTypeCause, takenByType } from "./dependencies.js"; import type { Alert, AlertCategory, AlertSeverity, SourceFailure } from "./alertTypes.js"; export interface AlertsReport { @@ -189,7 +189,7 @@ export async function collectAlerts(): Promise { const offlineId = /^offline:server:(\d+)$/.exec(c.key)?.[1]; const parentOf = offlineId ? cover.cause.get(`server:${offlineId}`) : undefined; push({ - causedBy: parentOf !== undefined ? { name: cover.graph.names.get(parentOf) ?? parentOf } : undefined, + causedBy: parentOf !== undefined ? { name: cover.graph.names.get(parentOf) ?? parentOf, alertId: alertIdOfNode(parentOf, cover.graph) ?? undefined } : undefined, affects: offlineId ? cover.taken.get(`server:${offlineId}`)?.sort((a, b) => a.localeCompare(b)) : undefined, category: origin.category, severity: c.severity ?? "warning", @@ -458,7 +458,7 @@ export async function collectAlerts(): Promise { const cause = cover ? integrationTypeCause(f.source, cover) : null; const affects = cover ? takenByType(f.source, cover) : []; push({ - causedBy: cause ? { name: cause.name } : undefined, + causedBy: cause ? { name: cause.name, alertId: (cover && alertIdOfNode(cause.key, cover.graph)) || undefined } : undefined, affects: affects.length > 0 ? affects.sort((a, b) => a.localeCompare(b)) : undefined, category: "integration", severity: f.alerted ? "critical" : "warning", diff --git a/server/src/services/dependencies.ts b/server/src/services/dependencies.ts index d745093..099dc91 100644 --- a/server/src/services/dependencies.ts +++ b/server/src/services/dependencies.ts @@ -12,6 +12,7 @@ import { eq } from "drizzle-orm"; import { db } from "../db/client.js"; import { dependencies, integrations, servers } from "../db/schema.js"; import { getInternalFlag } from "./settingsStore.js"; +import { listActiveWindows } from "./maintenance.js"; import { loadParentRows, resolveParents, type ParentLink } from "./serverParents.js"; /** Where the health monitor keeps the problems it is announcing; read here so a service's alert can tell a server it needs is down. */ @@ -89,6 +90,33 @@ export function wouldLoop(edges: Edges, from: string, to: string): boolean { return from === to || ancestorsOf(to, edges).order.includes(from) || ancestorsOf(to, edges).looped; } +/** Everything that needs `key`, directly or through others, nearest first. */ +export function dependentsOf(edges: Edges, key: string): { key: string; distance: number }[] { + const reverse = new Map(); + for (const [from, tos] of edges) for (const to of tos) reverse.set(to, [...(reverse.get(to) ?? []), from]); + const out: { key: string; distance: number }[] = []; + const seen = new Set([key]); + let layer = [key]; + for (let distance = 1; layer.length > 0; distance++) { + const next: string[] = []; + for (const k of layer) { + for (const d of (reverse.get(k) ?? []).sort()) { + if (seen.has(d)) continue; + seen.add(d); + out.push({ key: d, distance }); + next.push(d); + } + } + layer = next; + } + return out; +} + +/** Everything `key` needs, directly or through others, nearest first. */ +export function needsOfNode(edges: Edges, key: string): string[] { + return ancestorsOf(key, edges).order; +} + export interface Graph { edges: Edges; /** node → its name, for every node that exists. */ @@ -115,6 +143,45 @@ export async function loadGraph(): Promise { return { edges: buildEdges(resolveParents(parentRows), rows, (k) => names.has(k)), names, rows, instances, intRows }; } +/** 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):(\d+)$/.exec(key); + if (!m) return null; + if (m[1] === "server") return `offline:offline:server:${m[2]}`; + const row = graph.intRows.find((r) => r.id === Number(m[2])); + return row ? `integration:failing:${row.type}` : null; +} + +export interface ImpactItem { + key: string; + type: NodeType; + id: number; + name: string; + /** 1 = needs it directly, 2 = through one other, … */ + distance: number; + /** Already under a maintenance window. */ + silenced: boolean; +} + +/** What would be affected if `type`/`id` went down (everything that needs it) and what it needs itself. Null if it doesn't exist. */ +export async function impactOf(type: NodeType, id: number, now: Date = new Date()): Promise<{ target: { key: string; type: NodeType; id: number; name: string }; dependents: ImpactItem[]; needs: ImpactItem[] } | null> { + const graph = await loadGraph(); + const key = nodeKey(type, id); + const name = graph.names.get(key); + if (name === undefined) return null; + const windows = await listActiveWindows(now); + const silenced = new Set(windows.map((w) => `${w.targetType}:${w.targetId}`)); + const item = (k: string, distance: number): ImpactItem => { + const [t, i] = k.split(":"); + return { key: k, type: t as NodeType, id: Number(i), name: graph.names.get(k) ?? k, distance, silenced: silenced.has(k) }; + }; + return { + target: { key, type, id, name }, + dependents: dependentsOf(graph.edges, key).map((d) => item(d.key, d.distance)), + needs: needsOfNode(graph.edges, key).map((k, i) => item(k, i + 1)), + }; +} + export interface Cover { /** Each node that is down because of another → the root cause. */ cause: Map; diff --git a/server/src/services/topology.ts b/server/src/services/topology.ts index a0c9746..b3baad1 100644 --- a/server/src/services/topology.ts +++ b/server/src/services/topology.ts @@ -59,6 +59,13 @@ function parseIps(stored: string | null): string[] { } } +/** Whether a server is reporting: "ok", "bad" once it has been silent longer than its limit, "unknown" if it has never reported. */ +export function serverStatus(row: { lastSeenAt: string | null; thresholds: string | null }, offlineMinutes: number, now: Date): MapStatus { + const lastSeen = row.lastSeenAt ? Date.parse(row.lastSeenAt) : null; + const offlineAfterMs = (parseThresholds(row.thresholds)?.serverOfflineMinutes ?? offlineMinutes) * 60_000; + return lastSeen === null ? "unknown" : now.getTime() - lastSeen > offlineAfterMs ? "bad" : "ok"; +} + export async function buildTopology(now: Date = new Date()): Promise { const nodes: MapNode[] = []; const edges: MapEdge[] = []; @@ -72,9 +79,7 @@ export async function buildTopology(now: Date = new Date()): Promise { // Servers, and the Proxmox hosts they run on. const hostIds = new Set(); for (const s of serverRows) { - const lastSeen = s.lastSeenAt ? Date.parse(s.lastSeenAt) : null; - const offlineAfterMs = (parseThresholds(s.thresholds)?.serverOfflineMinutes ?? healthChecks.serverOfflineMinutes) * 60_000; - const status: MapStatus = lastSeen === null ? "unknown" : now.getTime() - lastSeen > offlineAfterMs ? "bad" : "ok"; + const status = serverStatus(s, healthChecks.serverOfflineMinutes, now); nodes.push({ id: `server:${s.id}`, kind: "server", label: s.name, sub: s.hostname, status, href: `/servers/${s.id}` }); if (s.proxmoxIntegrationId && s.proxmoxNode) { const hostId = `host:${s.proxmoxIntegrationId}:${s.proxmoxNode}`; diff --git a/server/test/dependencies.test.ts b/server/test/dependencies.test.ts index 8c0a1e8..f3e9043 100644 --- a/server/test/dependencies.test.ts +++ b/server/test/dependencies.test.ts @@ -164,7 +164,7 @@ describe("through the routes, the alerts and the notifications", () => { const failing = report.alerts.filter((a) => a.category === "integration"); assert.equal(failing.length, 2); for (const f of failing) { - assert.deepEqual(f.causedBy, { name: "box" }); + assert.deepEqual(f.causedBy, { name: "box", alertId: report.alerts.find((a) => a.category === "offline" && a.message.startsWith("box"))!.id }); assert.equal(f.silenced, true); } assert.equal(failing.find((f) => f.id.includes("gitea"))!.affects, undefined, "only the root says what it takes with it"); @@ -178,7 +178,7 @@ describe("through the routes, the alerts and the notifications", () => { const report = await getAlerts(true); const failing = report.alerts.filter((a) => a.category === "integration"); assert.equal(failing.find((f) => f.id.includes("gitea"))!.causedBy, undefined); - assert.deepEqual(failing.find((f) => f.id.includes("semaphore"))!.causedBy, { name: "Gitea" }); + assert.deepEqual(failing.find((f) => f.id.includes("semaphore"))!.causedBy, { name: "Gitea", alertId: "integration:failing:gitea" }); }); test("a kind of service is folded only if every enabled instance of it is explained", async () => { diff --git a/server/test/dependencyImpact.test.ts b/server/test/dependencyImpact.test.ts new file mode 100644 index 0000000..bf3602a --- /dev/null +++ b/server/test/dependencyImpact.test.ts @@ -0,0 +1,183 @@ +/** + * What a thing would take with it: the impact lookup, the graph for the map, silencing dependents along with the target, and an alert + * pointing at the alert that explains it. + * + * Run with: npm test --workspace server + */ +import { test, describe, before, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { AddressInfo } from "node:net"; +import type { Server } from "node:http"; + +const dir = mkdtempSync(join(tmpdir(), "hm-impact-")); +process.env.DATABASE_PATH = join(dir, "test.sqlite"); +process.env.SESSION_DIR = join(dir, "sessions"); +process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32); +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, auditLog } = await import("../src/db/schema.js"); +const { runMigrations } = await import("../src/db/migrate.js"); +const { buildEdges, dependentsOf, needsOfNode } = await import("../src/services/dependencies.js"); +const { dependenciesRouter } = await import("../src/routes/dependencies.js"); +const { maintenanceRouter } = await import("../src/routes/maintenance.js"); +const { getAlerts, invalidateAlertsCache } = await import("../src/services/alerts.js"); +const { trackIntegrationHealth } = await import("../src/services/integrationHealthMonitor.js"); +const { listActiveWindows } = await import("../src/services/maintenance.js"); + +await runMigrations(); + +const everything = () => true; +const edge = (fromType: "server" | "integration", fromId: number, toType: "server" | "integration", toId: number) => ({ fromType, fromId, toType, toId }); + +describe("walking the graph", () => { + const edges = buildEdges(new Map(), [edge("integration", 1, "server", 1), edge("integration", 2, "integration", 1), edge("server", 2, "integration", 1), edge("server", 3, "server", 2)], everything); + + test("what needs a thing, nearest first, each once, through others too", () => { + assert.deepEqual(dependentsOf(edges, "server:1"), [ + { key: "integration:1", distance: 1 }, + { key: "integration:2", distance: 2 }, + { key: "server:2", distance: 2 }, + { key: "server:3", distance: 3 }, + ]); + assert.deepEqual(dependentsOf(edges, "server:3"), [], "nothing needs it"); + }); + + test("what a thing needs, nearest first", () => { + assert.deepEqual(needsOfNode(edges, "server:3"), ["server:2", "integration:1", "server:1"]); + assert.deepEqual(needsOfNode(edges, "server:1"), []); + }); +}); + +describe("through the routes", () => { + let app: Server; + let base = ""; + let who = "operator"; + let box = 0; + let app1 = 0; + let gitea = 0; + let semaphore = 0; + + before(async () => { + await db.insert(users).values([ + { oidcSub: "operator", name: "Olga", role: "operator" }, + { oidcSub: "viewer", name: "Vic", role: "viewer" }, + ]); + const made = await db + .insert(servers) + .values([ + { name: "box", apiTokenHash: "b", apiTokenPrefix: "b", lastSeenAt: new Date(Date.now() - 3 * 3600_000).toISOString() }, + { name: "app", apiTokenHash: "a", apiTokenPrefix: "a", lastSeenAt: new Date().toISOString() }, + ]) + .returning({ id: servers.id }); + box = made[0].id; + app1 = made[1].id; + const ints = await db + .insert(integrations) + .values([ + { type: "gitea", name: "Gitea", baseUrl: "https://git.lab", config: "{}" }, + { type: "semaphore", name: "Semaphore", baseUrl: "https://sem.lab", config: "{}" }, + ]) + .returning({ id: integrations.id }); + gitea = ints[0].id; + semaphore = ints[1].id; + + const a = express(); + a.use(express.json()); + a.use((req, _res, next) => { + (req as unknown as { session: unknown }).session = { user: { sub: who } }; + next(); + }); + a.use("/api/dependencies", dependenciesRouter); + a.use("/api/maintenance", maintenanceRouter); + app = await new Promise((resolve) => { + const s = a.listen(0, "127.0.0.1", () => resolve(s)); + }); + base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`; + + const post = (body: unknown) => fetch(`${base}/dependencies`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + assert.equal((await post(edge("integration", gitea, "server", box))).status, 201); + assert.equal((await post(edge("integration", semaphore, "integration", gitea))).status, 201); + assert.equal((await post(edge("server", app1, "integration", gitea))).status, 201); + }); + + after(() => { + app.close(); + try { + rmSync(dir, { recursive: true, force: true }); + } catch { + // Windows keeps the database file locked until the process exits. + } + }); + + const get = (path: string) => fetch(`${base}${path}`); + const startMaintenance = (body: unknown) => fetch(`${base}/maintenance`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + + test("the impact of the server: everything that needs it, with how far away it is; what Semaphore needs, nearest first", async () => { + const impact = await (await get(`/dependencies/impact?type=server&id=${box}`)).json(); + assert.equal(impact.target.name, "box"); + assert.deepEqual(impact.dependents.map((d: { name: string; distance: number }) => [d.name, d.distance]).sort(), [["Gitea", 1], ["Semaphore", 2], ["app", 2]]); + assert.deepEqual(impact.needs, []); + const sem = await (await get(`/dependencies/impact?type=integration&id=${semaphore}`)).json(); + assert.deepEqual(sem.needs.map((n: { name: string }) => n.name), ["Gitea", "box"]); + assert.equal((await get(`/dependencies/impact?type=server&id=99999`)).status, 404); + assert.equal((await get(`/dependencies/impact?type=dns&id=1`)).status, 400); + assert.equal((await get(`/dependencies/impact?type=server`)).status, 400); + }); + + test("the graph for the map: only what takes part, the foundations first, with how each is doing", async () => { + const graph = await (await get("/dependencies/graph")).json(); + const byName = Object.fromEntries(graph.nodes.map((n: { name: string; status: string; href: string }) => [n.name, n])); + assert.deepEqual(Object.keys(byName).sort(), ["Gitea", "Semaphore", "app", "box"]); + assert.equal(byName.box.status, "bad", "silent for 3 hours"); + assert.equal(byName.app.status, "ok"); + assert.equal(byName.Gitea.status, "unknown", "nothing has called it yet"); + assert.equal(byName.box.href, `/servers/${box}`); + assert.deepEqual( + graph.edges.map((e: { from: string; to: string; kind: string }) => `${e.from}>${e.to}:${e.kind}`).sort(), + [`integration:${gitea}>integration:${semaphore}:written`, `integration:${gitea}>server:${app1}:written`, `server:${box}>integration:${gitea}:written`].sort(), + ); + }); + + test("an alert points at the alert that explains it", async () => { + await trackIntegrationHealth("gitea", false); + invalidateAlertsCache(); + const report = await getAlerts(true); + const offline = report.alerts.find((a) => a.category === "offline" && a.message.startsWith("box"))!; + const failing = report.alerts.find((a) => a.id === "integration:failing:gitea")!; + assert.deepEqual(failing.causedBy, { name: "box", alertId: offline.id }); + assert.ok(report.alerts.some((a) => a.id === failing.causedBy!.alertId), "and that alert exists"); + }); + + test("silencing a server for maintenance leaves what depends on it alone unless asked", async () => { + const res = await startMaintenance({ targetType: "server", targetId: box, minutes: 30, reason: "reboot" }); + assert.equal(res.status, 201); + assert.deepEqual((await res.json()).alsoSilenced, []); + assert.equal((await listActiveWindows()).length, 1); + }); + + test("asked to, it silences everything that depends on it too, for the same time, and says why", async () => { + const res = await startMaintenance({ targetType: "server", targetId: box, minutes: 30, reason: "reboot", withDependents: true }); + assert.equal(res.status, 201); + const body = await res.json(); + assert.deepEqual(body.alsoSilenced.map((s: { name: string }) => s.name).sort(), ["Gitea", "Semaphore", "app"]); + const windows = await listActiveWindows(); + assert.equal(windows.length, 4); + const gitea1 = windows.find((w) => w.targetType === "integration" && w.targetId === gitea)!; + assert.equal(gitea1.reason, "Depends on box — reboot"); + assert.equal(Math.round((Date.parse(gitea1.endsAt) - Date.parse(body.window.endsAt)) / 1000), 0, "the same end"); + const audits = (await db.select().from(auditLog)).filter((e) => e.category === "maintenance" && /depends on box/.test(e.detail ?? "")); + assert.equal(audits.length, 3); + }); + + test("a viewer can look at the impact but not start maintenance", async () => { + who = "viewer"; + assert.equal((await get(`/dependencies/impact?type=server&id=${box}`)).status, 200); + assert.equal((await startMaintenance({ targetType: "server", targetId: box, minutes: 30, withDependents: true })).status, 403); + who = "operator"; + }); +}); diff --git a/server/test/parentsAndUpdates.test.ts b/server/test/parentsAndUpdates.test.ts index 5ce0fd6..ff71470 100644 --- a/server/test/parentsAndUpdates.test.ts +++ b/server/test/parentsAndUpdates.test.ts @@ -165,7 +165,7 @@ describe("the alerts, folded", () => { assert.deepEqual(host.affects, ["db", "web"]); assert.equal(host.silenced, false); const web = offline.find((a) => a.message.startsWith("web"))!; - assert.deepEqual(web.causedBy, { name: "pve1" }); + assert.deepEqual(web.causedBy, { name: "pve1", alertId: host.id }); assert.equal(web.silenced, true, "held back like a silenced alert"); assert.equal(offline.find((a) => a.message.startsWith("elsewhere"))!.causedBy, undefined); assert.equal(report.counts.critical, 2, "pve1 and the unrelated one"); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 20a386d..6d6f991 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -778,6 +778,34 @@ export interface BackupCoverage { export type AssetKind = "server" | "storage" | "network" | "power" | "client" | "other"; export type DependencyNodeType = "server" | "integration"; + +/** 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 { + key: string; + type: DependencyNodeType; + id: number; + name: string; + distance: number; + silenced: boolean; +} +export interface DependencyImpact { + target: { key: string; type: DependencyNodeType; id: number; name: string }; + dependents: DependencyImpactItem[]; + needs: DependencyImpactItem[]; +} +export interface DependencyGraphNode { + key: string; + type: DependencyNodeType; + id: number; + name: string; + status: "ok" | "bad" | "warn" | "unknown"; + href: string; +} +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" }[]; +} export interface DependencyNode { key: string; type: DependencyNodeType; @@ -871,7 +899,7 @@ export interface AlertItem { /** What a maintenance window would go on to silence it — what the Silence button acts on. Null when nothing can silence it. */ target?: { type: MaintenanceTargetType; id: number; name: string } | null; /** Held back because another problem explains it (a guest down because its host is): the host's alert says so too. */ - causedBy?: { name: string }; + causedBy?: { name: string; alertId?: string }; /** On a host's alert: the servers on it whose own alerts are folded under this one. */ affects?: string[]; /** The osTicket ticket opened for it, if one was. */ @@ -1694,6 +1722,8 @@ export const api = { }, dependencies: { list: () => request("/api/dependencies"), + impact: (type: DependencyNodeType, id: number) => request(`/api/dependencies/impact?type=${type}&id=${id}`), + graph: () => request("/api/dependencies/graph"), create: (data: { fromType: DependencyNodeType; fromId: number; toType: DependencyNodeType; toId: number }) => request<{ id: number }>("/api/dependencies", { method: "POST", body: JSON.stringify(data) }), remove: (id: number) => request(`/api/dependencies/${id}`, { method: "DELETE" }), }, @@ -1759,8 +1789,8 @@ export const api = { addAlias: (data: { address: string; targetType: MaintenanceTargetType; targetId: number }) => request<{ alias: MaintenanceAlias }>("/api/maintenance/aliases", { method: "POST", body: JSON.stringify(data) }), removeAlias: (id: number) => request(`/api/maintenance/aliases/${id}`, { method: "DELETE" }), - start: (data: { targetType: MaintenanceTargetType; targetId: number; minutes: number; reason?: string }) => - request<{ window: MaintenanceWindow }>("/api/maintenance", { method: "POST", body: JSON.stringify(data) }), + start: (data: { targetType: MaintenanceTargetType; targetId: number; minutes: number; reason?: string; withDependents?: boolean }) => + request<{ window: MaintenanceWindow; alsoSilenced: { type: DependencyNodeType; id: number; name: string }[] }>("/api/maintenance", { method: "POST", body: JSON.stringify(data) }), end: (id: number) => request(`/api/maintenance/${id}`, { method: "DELETE" }), startBulk: (data: { scope: MaintenanceBulkScope; minutes: number; reason?: string }) => request<{ started: number; extended: number; total: number }>("/api/maintenance/bulk", { method: "POST", body: JSON.stringify(data) }), diff --git a/web/src/components/DependencyMap.tsx b/web/src/components/DependencyMap.tsx new file mode 100644 index 0000000..74b0b35 --- /dev/null +++ b/web/src/components/DependencyMap.tsx @@ -0,0 +1,195 @@ +import { useEffect, useMemo, useState } from "react"; +import { Link } from "react-router-dom"; +import { api, type DependencyGraph, type DependencyGraphNode } from "../api/client"; +import { ErrorNotice } from "./Notice"; +import { PageSkeleton } from "./Skeleton"; +import { readableError } from "../utils/errors"; + +const NODE_W = 200; +const NODE_H = 46; +const GAP_Y = 12; +const COL_GAP = 120; + +const STATUS_SYMBOL: Record = { ok: "✓", bad: "✕", warn: "▲", unknown: "·" }; +const STATUS_WORD: Record = { ok: "working", bad: "problem", warn: "check", unknown: "no status" }; + +interface Placed extends DependencyGraphNode { + x: number; + y: number; + layer: number; +} + +/** + * Columns by how deep each thing sits: what needs nothing on the left, then what needs only those, and so on. A column is ordered by where the + * things it needs sit, so the lines cross as little as is easy. (A loop can't be made, but if one ever got in the layering gives up rather than spin.) + */ +function layout(graph: DependencyGraph): { placed: Map; width: number; height: number } { + const needs = new Map(); + for (const e of graph.edges) needs.set(e.to, [...(needs.get(e.to) ?? []), e.from]); + const layer = new Map(graph.nodes.map((n) => [n.key, 0])); + for (let pass = 0; pass < graph.nodes.length; pass++) { + let moved = false; + for (const n of graph.nodes) { + const want = Math.max(-1, ...(needs.get(n.key) ?? []).map((k) => layer.get(k) ?? 0)) + 1; + if (want > (layer.get(n.key) ?? 0)) { + layer.set(n.key, want); + moved = true; + } + } + if (!moved) break; + } + const columns = new Map(); + for (const n of graph.nodes) columns.set(layer.get(n.key) ?? 0, [...(columns.get(layer.get(n.key) ?? 0) ?? []), n]); + + const placed = new Map(); + const step = NODE_H + GAP_Y; + let height = 0; + for (const depth of [...columns.keys()].sort((a, b) => a - b)) { + const wanted = columns.get(depth)!.map((n) => { + const ys = (needs.get(n.key) ?? []).map((k) => placed.get(k)?.y).filter((y): y is number => y !== undefined); + return { n, y: ys.length ? ys.reduce((a, b) => a + b, 0) / ys.length : 0 }; + }); + wanted.sort((a, b) => a.y - b.y || a.n.name.localeCompare(b.n.name)); + let next = 0; + for (const { n, y } of wanted) { + const at = Math.max(next, depth === 0 ? next : y); + placed.set(n.key, { ...n, x: depth * (NODE_W + COL_GAP), y: at, layer: depth }); + next = at + step; + height = Math.max(height, at + NODE_H); + } + } + const maxLayer = Math.max(0, ...[...placed.values()].map((p) => p.layer)); + return { placed, width: maxLayer * (NODE_W + COL_GAP) + NODE_W, height }; +} + +/** Everything reached from `start` by following edges one way (`forward`: to what needs it; otherwise to what it needs). */ +function reach(graph: DependencyGraph, start: string, forward: boolean): Set { + const out = new Set(); + const queue = [start]; + while (queue.length) { + const cur = queue.shift()!; + for (const e of graph.edges) { + const [a, b] = forward ? [e.from, e.to] : [e.to, e.from]; + if (a === cur && !out.has(b) && b !== start) { + out.add(b); + queue.push(b); + } + } + } + return out; +} + +const names = (graph: DependencyGraph, keys: Iterable) => [...keys].map((k) => graph.nodes.find((n) => n.key === k)?.name ?? k).sort((a, b) => a.localeCompare(b)); + +/** + * What needs what, drawn with the foundations on the left. Pick a box to see what would go down with it (red) and what it relies on (blue); + * hovering does the same for a moment. This is the answer to "what breaks if I reboot this?" before doing it. + */ +export default function DependencyMap() { + const [graph, setGraph] = useState(null); + const [error, setError] = useState(null); + const [selected, setSelected] = useState(null); + const [hover, setHover] = useState(null); + + useEffect(() => { + api.dependencies + .graph() + .then(setGraph) + .catch((err) => setError(readableError(err))); + }, []); + + const view = useMemo(() => (graph ? layout(graph) : null), [graph]); + const active = hover ?? selected; + const sets = useMemo(() => { + if (!graph || !active) return null; + return { down: reach(graph, active, true), up: reach(graph, active, false) }; + }, [graph, active]); + const activeNode = graph?.nodes.find((n) => n.key === active) ?? null; + + if (error) return ; + if (!graph || !view) return ; + if (graph.nodes.length === 0) { + return ( +
+
+ Nothing depends on anything yet. Say what needs what on the Dependencies page, or set which server another runs on, and it is drawn here. +
+
+ ); + } + + const state = (key: string) => (!sets || !active ? "" : key === active ? "map-active" : sets.down.has(key) ? "map-down" : sets.up.has(key) ? "map-up" : "map-dim"); + + return ( +
+
+
+ + {[...view.placed.values()].map((n) => ( + + ))} +
+
+
+ {activeNode && sets ? ( +
+
+ {activeNode.name}{" "} + + open + + {selected !== active && (click to keep this)} +
+
+ {sets.down.size ? `If it goes down, ${sets.down.size} ${sets.down.size === 1 ? "thing goes" : "things go"} with it: ${names(graph, sets.down).join(", ")}.` : "Nothing depends on it."} +
+
{sets.up.size ? `It relies on ${names(graph, sets.up).join(", ")}.` : "It relies on nothing here."}
+
+ ) : ( +
+ Lines run from what is needed (left) to what needs it (right). Dashed: “runs on”, set on the server. + Pick a box to see what would go down with it. +
+ )} +
+
+ ); +} diff --git a/web/src/components/ImpactNote.tsx b/web/src/components/ImpactNote.tsx new file mode 100644 index 0000000..486cf25 --- /dev/null +++ b/web/src/components/ImpactNote.tsx @@ -0,0 +1,86 @@ +import { useEffect, useState } from "react"; +import { Link } from "react-router-dom"; +import { api, type DependencyImpactItem } from "../api/client"; + +export interface ImpactTarget { + type: string; + id: number; +} + +/** + * Before something is worked on: what depends on it and will look down while it is. Says nothing when nothing does. With `silence` given it + * also offers to put those under maintenance too, and with `onAdd` to add them to the selection being made. + */ +export default function ImpactNote({ + targets, + silence, + onAdd, + verb = "will look down while it is", +}: { + targets: ImpactTarget[]; + silence?: { value: boolean; onChange: (on: boolean) => void }; + onAdd?: (items: DependencyImpactItem[]) => void; + verb?: string; +}) { + const [items, setItems] = useState(null); + const keyOf = targets.map((t) => `${t.type}:${t.id}`).sort().join(","); + + useEffect(() => { + const own = targets.filter((t) => t.type === "server" || t.type === "integration"); + 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))) + .then((all) => { + if (!alive) return; + const selected = new Set(own.map((t) => `${t.type}:${t.id}`)); + const seen = new Map(); + for (const impact of all) for (const d of impact?.dependents ?? []) if (!selected.has(d.key) && !seen.has(d.key)) seen.set(d.key, d); + setItems([...seen.values()].sort((a, b) => a.distance - b.distance || a.name.localeCompare(b.name))); + }) + .catch(() => alive && setItems([])); + return () => { + alive = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [keyOf]); + + if (!items || items.length === 0) return null; + const shown = items.slice(0, 8); + + return ( +
+
+ {items.length} {items.length === 1 ? "thing depends" : "things depend"} on {targets.length === 1 ? "this" : "these"} and {verb} +
+
+ {shown.map((d) => ( + 1 ? "Through something else that needs it" : "Needs it directly"}> + {d.name} + {d.silenced ? " · already silenced" : ""} + + ))} + {items.length > shown.length && and {items.length - shown.length} more} +
+ {silence && ( + + )} + {onAdd && ( + + )} + {!silence && !onAdd && ( +
+ To silence {items.length === 1 ? "it" : "them"} too, start maintenance on the Maintenance page with that option. +
+ )} +
+ ); +} diff --git a/web/src/components/RecurringMaintenance.tsx b/web/src/components/RecurringMaintenance.tsx index e751a31..9aade46 100644 --- a/web/src/components/RecurringMaintenance.tsx +++ b/web/src/components/RecurringMaintenance.tsx @@ -1,4 +1,5 @@ import { useEffect, useState } from "react"; +import ImpactNote from "./ImpactNote"; import { api, type MaintenanceSchedule, type MaintenanceTargetType, type MaintenanceTargets } from "../api/client"; import { confirmDialog } from "../utils/dialogs"; import { readableError } from "../utils/errors"; @@ -271,6 +272,15 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: { )} + {picked.size > 0 && ( +
+ ({ type: k.split(":")[0], id: Number(k.split(":")[1]) }))} + verb="will look down while they are" + onAdd={(items) => setPicked((prev) => new Set([...prev, ...items.map((i) => key(i.type, i.id))]))} + /> +
+ )}
diff --git a/web/src/components/UpdateRunDrawer.tsx b/web/src/components/UpdateRunDrawer.tsx index 3a1308b..69ac5d4 100644 --- a/web/src/components/UpdateRunDrawer.tsx +++ b/web/src/components/UpdateRunDrawer.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { Link } from "react-router-dom"; +import ImpactNote from "./ImpactNote"; import { api, type IntegrationSummary, type SemaphoreTemplate, type UpdatesServer } from "../api/client"; import { confirmDialog } from "../utils/dialogs"; import { readableError } from "../utils/errors"; @@ -108,6 +109,9 @@ export default function UpdateRunDrawer({ server, onClose, onStarted }: { server
No templates found in Semaphore.
) : ( <> +
+ +
  1. Alerts for this server are silenced (a maintenance window).
  2. The playbook runs in Semaphore, for this server only.
  3. diff --git a/web/src/pages/Alerts.tsx b/web/src/pages/Alerts.tsx index b743c39..be15ff6 100644 --- a/web/src/pages/Alerts.tsx +++ b/web/src/pages/Alerts.tsx @@ -1,4 +1,4 @@ -import { useEffect, useMemo, useState } from "react"; +import { Fragment, useEffect, useMemo, useState } from "react"; import { Link } from "react-router-dom"; import { api, type AlertCategory, type AlertItem, type AlertSeverity, type AlertsReport, type CurrentUser } from "../api/client"; import { useSortable } from "../hooks/useSortable"; @@ -52,6 +52,23 @@ export default function Alerts({ user }: { user: CurrentUser }) { // Which alerts to show by whether somebody is on them, and the one whose acknowledgement is being edited. const [attention, setAttention] = useState<"all" | "unacknowledged" | "acknowledged" | "mine">("all"); const [acking, setAcking] = useState(null); + // Held-back alerts are nested under the one that explains them (on by default; remembered), and each parent opens to show them. + const [grouped, setGrouped] = useState(() => { + try { + return localStorage.getItem("alerts.grouped") !== "0"; + } catch { + return true; + } + }); + const [open, setOpen] = useState>(new Set()); + function chooseGrouped(on: boolean) { + setGrouped(on); + try { + localStorage.setItem("alerts.grouped", on ? "1" : "0"); + } catch { + // a remembered choice is only a convenience + } + } function load(refresh = false) { setLoading(true); @@ -69,18 +86,47 @@ export default function Alerts({ user }: { user: CurrentUser }) { void load(); }, []); - const rows: Row[] = useMemo(() => { - if (!report) return []; + const { rows, childrenOf } = useMemo(() => { + const none = new Map(); + if (!report) return { rows: [] as Row[], childrenOf: none }; const q = search.trim().toLowerCase(); - return report.alerts - .filter((a) => (severity === "all" || a.severity === severity) && (category === "all" || a.category === category) && (showSilenced || !a.silenced)) + const base: Row[] = report.alerts + .filter((a) => (severity === "all" || a.severity === severity) && (category === "all" || a.category === category)) .filter((a) => { const on = !!a.ack?.active; return attention === "all" || (attention === "unacknowledged" ? !on : attention === "acknowledged" ? on : on && a.ack?.assignee?.id === user.id); }) .filter((a) => !q || [a.message, a.source, CATEGORY_LABELS[a.category]].some((v) => v.toLowerCase().includes(q))) .map((a) => ({ ...a, rank: SEVERITY[a.severity].rank })); - }, [report, severity, category, search, showSilenced, attention, user.id]); + // An alert held back by another is nested under it when that one is on the list too; otherwise it stands on its own. + const ids = new Set(base.map((a) => a.id)); + const children = new Map(); + const nested = new Set(); + if (grouped) { + for (const a of base) { + const parent = a.causedBy?.alertId; + if (parent && parent !== a.id && ids.has(parent)) { + children.set(parent, [...(children.get(parent) ?? []), a]); + nested.add(a.id); + } + } + } + return { rows: base.filter((a) => !nested.has(a.id) && (showSilenced || !a.silenced)), childrenOf: children }; + }, [report, severity, category, search, showSilenced, attention, user.id, grouped]); + + // One line on where things stand: how many need someone, and which problems explain the rest. + const headline = useMemo(() => { + if (!report || report.alerts.length === 0) return null; + const standing = report.alerts.filter((a) => !a.silenced); + const acknowledged = standing.filter((a) => a.ack?.active).length; + const held = report.alerts.filter((a) => a.causedBy).length; + const roots = standing + .filter((a) => (a.affects?.length ?? 0) > 0) + .map((a) => ({ name: a.target?.name ?? a.source, count: report.alerts.filter((x) => x.causedBy?.alertId === a.id).length })) + .filter((r) => r.count > 0); + const critical = standing.some((a) => a.severity === "critical"); + return { standing: standing.length, acknowledged, held, roots, tone: standing.length === 0 ? "green" : critical ? "red" : "yellow" }; + }, [report]); // No initial sort: the server already puts active problems first, worst first. const { sorted, sortKey, sortDir, requestSort } = useSortable(rows); @@ -143,6 +189,33 @@ export default function Alerts({ user }: { user: CurrentUser }) { {report && ( <> + {headline && ( +
    +
    +
    + {headline.standing === 0 ? "Nothing needs attention" : `${headline.standing} ${headline.standing === 1 ? "problem needs" : "problems need"} attention`} + {headline.acknowledged > 0 && headline.standing > 0 && · {headline.acknowledged} acknowledged} +
    + {headline.held > 0 && ( +
    + {headline.held} more {headline.held === 1 ? "is" : "are"} held back because something they depend on is down + {headline.roots.length > 0 && ( + <> + {" "} + — {headline.roots.map((r, i) => ( + + {i > 0 && ", "} + {r.name} accounts for {r.count} + + ))} + + )} + . +
    + )} +
    +
    + )}
    {cards.map((c) => (
    @@ -220,6 +293,12 @@ export default function Alerts({ user }: { user: CurrentUser }) { )} + {(counts?.grouped ?? 0) > 0 && ( + + )} {(counts?.silenced ?? 0) + (counts?.grouped ?? 0) > 0 && (
    + {(target.startsWith("server:") || target.startsWith("integration:")) && ( +
    + +
    + )}
    + +
    + + {view === "connections" ? ( + + ) : ( + <> +

    + What needs what: a server that runs on another, a service that needs the server it is installed on. Pick a box to see what would go down with it before you reboot it.{" "} + Edit dependencies +

    + + + )} + + ); +} + +function ConnectionsMap() { const [data, setData] = useState(null); const [error, setError] = useState(null); const [focus, setFocus] = useState(null); @@ -86,7 +129,7 @@ export default function MapPage() { .catch((err) => setError(readableError(err))); }, []); - const view = useMemo(() => (data ? layout(data) : null), [data]); + const drawing = useMemo(() => (data ? layout(data) : null), [data]); const lit = useMemo(() => { if (!data || !focus) return null; const set = new Set([focus]); @@ -99,7 +142,6 @@ export default function MapPage() { return ( <> -

    Map

    How things connect: which Proxmox host a server runs on, which DNS names point at it, and which Uptime Kuma monitors watch it. Hover or tab to a box to light up what it is connected to. @@ -111,22 +153,22 @@ export default function MapPage() { ))} {!data && !error && } - {data && view && data.nodes.length === 0 &&

    Nothing to draw yet — add a server first.
    } - {data && view && data.nodes.length > 0 && ( + {data && drawing && data.nodes.length === 0 &&
    Nothing to draw yet — add a server first.
    } + {data && drawing && data.nodes.length > 0 && (
    -
    - {view.columns.map((c) => ( +
    + {drawing.columns.map((c) => (
    {c.title}
    ))}
    -
    -
    + - {[...view.placed.values()].map((n) => { + {[...drawing.placed.values()].map((n) => { const dim = lit && !lit.has(n.id); const body = ( <> diff --git a/web/src/styles.css b/web/src/styles.css index a3c3b89..29241ca 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -1536,3 +1536,80 @@ html[data-density="roomy"] .table > :not(caption) > * > * { margin: 0 !important; } } + +/* ── The dependency map: what would go down with the box that is picked (red) and what it relies on (blue). ── */ +button.map-node { + font: inherit; + cursor: pointer; +} + +button.map-node:hover, +button.map-node:focus-visible { + border-color: var(--tblr-primary, #2563eb); +} + +.map-node.map-active { + border-color: var(--tblr-primary, #2563eb); + box-shadow: 0 0 0 2px var(--tblr-primary, #2563eb); +} + +.map-node.map-down { + border-color: #e05252; + box-shadow: 0 0 0 1px #e05252; +} + +.map-node.map-up { + border-color: #4299e1; + box-shadow: 0 0 0 1px #4299e1; +} + +.map-edge.map-edge-down { + stroke: #e05252; + stroke-opacity: 0.9; + stroke-width: 2.2; +} + +.map-edge.map-edge-up { + stroke: #4299e1; + stroke-opacity: 0.9; + stroke-width: 2.2; +} + +/* ── The Alerts page: a headline on where things stand, a coloured edge by severity, and held-back alerts nested under their cause. ── */ +.alerts-headline { + border-left: 4px solid var(--tblr-border-color); +} + +.alerts-headline-red { + border-left-color: #e05252; +} + +.alerts-headline-yellow { + border-left-color: #f0a82c; +} + +.alerts-headline-green { + border-left-color: #2fb344; +} + +tr.alert-row > td:first-child { + box-shadow: inset 3px 0 0 transparent; +} + +tr.alert-row-critical > td:first-child { + box-shadow: inset 3px 0 0 #e05252; +} + +tr.alert-row-warning > td:first-child { + box-shadow: inset 3px 0 0 #f0a82c; +} + +tr.alert-row-child > td { + background: var(--tblr-bg-surface-secondary, transparent); + font-size: 0.9em; +} + +tr.alert-row-child > td:first-child { + box-shadow: none; + padding-left: 1.5rem; +}