AdGuard Home, Grafana, Docker image age, foldable server page cards

New integration kinds adguard (status, statistics, filter lists and a real DNS question
over UDP; alerts for DNS down/not running, protection left off, stale lists) and grafana
(alert rules firing or failing, data-source health). Optional warning for running Docker
images built more than N days ago (off by default). A server's overview cards can be
folded and arranged, kept per user. Migrations 0075-0077; docs, metrics and tests included.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-27 22:13:03 +01:00
1 parent 3d9a2310bb
commit 551eb1597a
53 files changed
+27700 -33

No files matched your search

+4
View File
@@ -22,6 +22,8 @@ import Nextcloud from "./pages/Nextcloud";
import Hetzner from "./pages/Hetzner";
import GameServers from "./pages/GameServers";
import Media from "./pages/Media";
import AdguardHome from "./pages/AdguardHome";
import Grafana from "./pages/Grafana";
import Speedtest from "./pages/Speedtest";
import Costs from "./pages/Costs";
import ServiceLevels from "./pages/ServiceLevels";
@@ -182,6 +184,8 @@ function Shelled({ user }: { user: CurrentUser }) {
<Route path="/hetzner" element={<Hetzner />} />
<Route path="/game-servers" element={<GameServers user={user} />} />
<Route path="/media" element={<Media />} />
<Route path="/adguard" element={<AdguardHome />} />
<Route path="/grafana" element={<Grafana />} />
<Route path="/speedtest" element={<Speedtest />} />
<Route path="/costs" element={<Costs user={user} />} />
<Route path="/service-levels" element={<ServiceLevels user={user} />} />
+65 -1
View File
@@ -12,6 +12,8 @@ export interface CurrentUser {
favorites?: string[];
/** How this person arranged the dashboard cards. */
dashboard?: DashboardLayout;
/** How this person arranged a server's overview page. */
serverPage?: PageLayout;
}
export type ShareLinkDetail = "summary" | "names";
@@ -101,6 +103,12 @@ export interface PublicWall {
display: { dateFormat: string; timeFormat: string };
}
/** How a person arranged a page of blocks: the ones they folded, and the order they put them in (a lower number comes first). */
export interface PageLayout {
folded: string[];
order: Record<string, number>;
}
/** The dashboard cards a person hid, and the order they put the rest in (a lower number comes first). */
export interface DashboardLayout {
hidden: string[];
@@ -561,6 +569,8 @@ export interface HealthCheckSettings {
vulnerabilityAlerts: boolean;
/** A Docker host with at least this many high findings is a warning too; 0 = off. */
vulnerabilityHighThreshold: number;
/** A Docker host with running images built more than this many days ago is a warning; 0 = off. */
imageAgeDays: number;
/** Containers to leave alone: a name, or "host/name"; * stands for anything. */
containerIgnore: string[];
}
@@ -1475,6 +1485,49 @@ export interface ArrApp {
problems: { key: string; message: string; severity: "warning" | "critical" }[];
}
/** One AdGuard Home (an integration of type adguard), as its page shows it. */
export interface AdguardInstance {
id: number;
name: string;
enabled: boolean;
url: string;
status: { at: string; ok: boolean; error: string | null } | null;
fresh: boolean;
state: {
version: string | null;
running: boolean;
protectionEnabled: boolean;
protectionOffSince: string | null;
dnsPort: number;
stats: { queries: number; blocked: number; blockedPercent: number | null; avgMs: number | null; safeBrowsing: number; parental: number; safeSearch: number; periodHours: number | null; topBlocked: { name: string; count: number }[]; topClients: { name: string; count: number }[]; topQueried: { name: string; count: number }[] } | null;
filters: { enabled: boolean; lists: { name: string; enabled: boolean; rules: number | null; updated: string | null }[] } | null;
/** The real DNS question put to it. */
probe: { ok: boolean; ms: number | null; error: string | null; name: string; host: string } | null;
probeFailSince: string | null;
updatedAt: string;
staleLists: string[];
} | null;
problems: { key: string; message: string; severity: "warning" | "critical" }[];
}
/** One Grafana (an integration of type grafana), as its page shows it. */
export interface GrafanaInstance {
id: number;
name: string;
enabled: boolean;
url: string;
status: { at: string; ok: boolean; error: string | null } | null;
fresh: boolean;
state: {
version: string | null;
/** The rules firing, pending or failing, and how many there are in all; null when they could not be read. */
rules: { total: number; items: { name: string; uid: string | null; group: string; folder: string | null; state: string; health: string; lastError: string | null; severity: string | null; summary: string | null; activeAt: string | null }[] } | null;
datasources: { uid: string; name: string; type: string; isDefault: boolean; ok: boolean | null; message: string | null }[] | null;
updatedAt: string;
} | null;
problems: { key: string; message: string; severity: "warning" | "critical" }[];
}
export type FragnetSignal = "start" | "stop" | "restart" | "kill";
export interface CostItem {
@@ -2610,7 +2663,7 @@ export interface ManualTaskInput {
enabled?: boolean;
}
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant" | "ups" | "jellyfin" | "authentik" | "prometheus" | "immich" | "paperless" | "nextcloud" | "netbox" | "n8n" | "hetzner" | "speedtest" | "fragnet" | "sonarr" | "radarr" | "prowlarr";
export type IntegrationType = "proxmox" | "synology" | "semaphore" | "tailscale" | "gitea" | "dockhand" | "uptimekuma" | "phpipam" | "pbs" | "osticket" | "unifi" | "npm" | "homeassistant" | "ups" | "jellyfin" | "authentik" | "prometheus" | "immich" | "paperless" | "nextcloud" | "netbox" | "n8n" | "hetzner" | "speedtest" | "fragnet" | "sonarr" | "radarr" | "prowlarr" | "adguard" | "grafana";
export interface IntegrationField {
key: string;
@@ -2834,6 +2887,8 @@ export interface DockhandVulnerabilityEnvironment {
totalImages: number | null;
/** The critical findings (at most 100). */
findings: DockhandVulnFinding[];
/** The images its running containers use by age; null when they were never read. `over` is how many are older than the setting (null while it is off). */
images: { at: string | null; running: number; undated: number; over: number | null; oldest: { image: string; ageDays: number; containers: string[] }[] } | null;
updatedAt: string;
}
@@ -2842,6 +2897,8 @@ export interface DockhandVulnerabilitiesResponse {
alerts: boolean;
/** A host with at least this many high findings is alerted too; 0 = never. */
highThreshold: number;
/** Running images older than this many days are alerted; 0 = off. */
imageAgeDays: number;
status: { at: string; ok: boolean; error: string | null } | null;
fresh: boolean;
environments: DockhandVulnerabilityEnvironment[];
@@ -3155,6 +3212,7 @@ async function request<T>(path: string, init?: RequestInit): Promise<T> {
export const api = {
me: Object.assign(() => request<{ user: CurrentUser }>("/api/me"), {
setFavorites: (paths: string[]) => request<{ favorites: string[] }>("/api/me/favorites", { method: "PUT", body: JSON.stringify({ paths }) }),
setServerPage: (layout: PageLayout) => request<{ serverPage: PageLayout }>("/api/me/server-page", { method: "PUT", body: JSON.stringify(layout) }),
setDashboard: (layout: DashboardLayout) => request<{ dashboard: DashboardLayout }>("/api/me/dashboard", { method: "PUT", body: JSON.stringify(layout) }),
changes: () => request<ChangesSummary>("/api/me/changes"),
markChangesSeen: () => request<{ lastLookedAt: string }>("/api/me/changes/seen", { method: "POST" }),
@@ -3207,6 +3265,12 @@ export const api = {
list: () => request<{ speedtests: SpeedtestInfo[] }>("/api/speedtest"),
history: (id: number, days: number) => request<SpeedtestHistory>(`/api/speedtest/${id}/history?days=${days}`),
},
adguard: {
list: () => request<{ instances: AdguardInstance[] }>("/api/adguard"),
},
grafana: {
list: () => request<{ instances: GrafanaInstance[] }>("/api/grafana"),
},
arr: {
list: () => request<{ apps: ArrApp[] }>("/api/arr"),
},
+79
View File
@@ -0,0 +1,79 @@
import { useRef, type ReactNode } from "react";
import { IconChevronDown, IconChevronUp, IconFoldDown, IconFoldUp } from "@tabler/icons-react";
import { moveBlock, resetServerPageLayout, setEditingServerPage, toggleFolded, useServerPageLayout } from "../utils/serverPageLayout";
/**
* A card (or a row of them) on a server's overview that its reader can fold — a click on the card's header does it, or the button while arranging — and, in a stack, move up or
* down. What is folded and the order are kept for the person (utils/serverPageLayout.ts). The block is only a wrapper: the card inside draws itself as it always did, and a block with
* no card in it (a Hetzner card for a server that is not at Hetzner) takes no room.
*
* `at` is where the block goes when nothing has been said (and what a stack is sorted by); a block without it is not moved, only folded — one of the columns of a row.
*/
export default function ServerBlock({ id, label, at, noFold = false, className = "", children }: { id: string; label: string; at?: number; noFold?: boolean; className?: string; children: ReactNode }) {
const { layout, editing } = useServerPageLayout();
const ref = useRef<HTMLDivElement>(null);
const folded = !noFold && layout.folded.includes(id);
const arrangeable = at !== undefined;
return (
<div
ref={ref}
className={`server-block ${folded ? "server-block-folded" : ""} ${className}`}
data-block={id}
{...(arrangeable ? { "data-arrange": "", "data-at": at } : {})}
style={arrangeable ? { order: layout.order[id] ?? at } : undefined}
onClick={
noFold
? undefined
: (e) => {
// A click on the card's own header folds it — unless it was on something in the header that does a thing of its own.
const target = e.target as HTMLElement;
const header = target.closest(".card-header");
if (!header || !ref.current?.contains(header) || target.closest("a, button, input, select, textarea, label, [role=button]")) return;
if (header.closest("[data-block]") !== ref.current) return;
void toggleFolded(id);
}
}
>
{editing && (
<div className="server-block-tools d-flex align-items-center gap-1 mb-1">
<span className="text-secondary small me-auto">{label}</span>
{arrangeable && (
<>
<button type="button" className="btn btn-sm btn-icon" aria-label={`Move ${label} up`} title="Move up" onClick={() => ref.current && void moveBlock(ref.current, -1)}>
<IconChevronUp size={16} aria-hidden="true" />
</button>
<button type="button" className="btn btn-sm btn-icon" aria-label={`Move ${label} down`} title="Move down" onClick={() => ref.current && void moveBlock(ref.current, 1)}>
<IconChevronDown size={16} aria-hidden="true" />
</button>
</>
)}
{!noFold && (
<button type="button" className="btn btn-sm d-inline-flex align-items-center gap-1" aria-pressed={folded} onClick={() => void toggleFolded(id)}>
{folded ? <IconFoldDown size={16} aria-hidden="true" /> : <IconFoldUp size={16} aria-hidden="true" />}
{folded ? "Unfold" : "Fold"}
</button>
)}
</div>
)}
{children}
</div>
);
}
/** The "Arrange cards" switch above the overview: while it is on, every card has its buttons; "Reset" puts the page back as it was drawn. */
export function ArrangeBar() {
const { layout, editing } = useServerPageLayout();
const changed = layout.folded.length > 0 || Object.keys(layout.order).length > 0;
return (
<div className="d-flex justify-content-end gap-2 mb-2">
{editing && changed && (
<button type="button" className="btn btn-sm" onClick={() => void resetServerPageLayout()}>
Reset
</button>
)}
<button type="button" className={`btn btn-sm ${editing ? "btn-primary" : "btn-outline-secondary"}`} aria-pressed={editing} onClick={() => setEditingServerPage(!editing)} title="Fold the cards you do not need and put the others in the order you like — for every server">
{editing ? "Done" : "Arrange cards"}
</button>
</div>
);
}
+2
View File
@@ -34,6 +34,8 @@ const TYPE_LABELS: Record<string, string> = {
sonarr: "Sonarr",
radarr: "Radarr",
prowlarr: "Prowlarr",
adguard: "AdGuard Home",
grafana: "Grafana",
};
export type WallLevel = "critical" | "warning" | "ok" | "unsure";
+2
View File
@@ -7,6 +7,7 @@ import { isCurrent, isGroup, visibleNav, type NavGroup } from "./nav";
import SidebarNav, { type NavBadge } from "./SidebarNav";
import { initFavorites } from "../utils/favorites";
import { initDashboardLayout } from "../utils/dashboardLayout";
import { initServerPageLayout } from "../utils/serverPageLayout";
import { formatRemaining } from "../utils/duration";
import { getTheme, setTheme, type Theme } from "../utils/theme";
import { DENSITIES, getDensity, setDensity, type Density } from "../utils/density";
@@ -55,6 +56,7 @@ export default function AppShell({ user, children }: { user: CurrentUser; childr
useState(() => {
initFavorites(user.favorites);
initDashboardLayout(user.dashboard);
initServerPageLayout(user.serverPage);
return null;
});
// The narrow, icon-only sidebar: remembered per browser (a laptop wants it, a big monitor may not), and only on wide screens.
+4
View File
@@ -48,6 +48,8 @@ import {
IconHeartbeat,
IconGitCommit,
IconShieldCheck,
IconShieldLock,
IconChartAreaLine,
IconActivityHeartbeat,
IconCopyCheck,
IconTicket,
@@ -133,6 +135,7 @@ export const NAV: NavEntry[] = [
icon: <IconWorld size={20} />,
items: [
{ to: "/dns", label: "DNS", icon: <IconWorld size={20} /> },
{ to: "/adguard", label: "AdGuard Home", icon: <IconShieldLock size={20} /> },
{ to: "/network/devices", label: "Network devices", icon: <IconRouter size={20} /> },
{ to: "/proxy-hosts", label: "Proxy hosts", icon: <IconArrowsSplit2 size={20} /> },
{ to: "/ipam", label: "IP Addresses", icon: <IconNetwork size={20} /> },
@@ -152,6 +155,7 @@ export const NAV: NavEntry[] = [
{ to: "/uptime-kuma", label: "Uptime Kuma", icon: <IconActivityHeartbeat size={20} /> },
{ to: "/ups", label: "UPS", icon: <IconBatteryCharging size={20} /> },
{ to: "/prometheus", label: "Prometheus", icon: <IconFlame size={20} /> },
{ to: "/grafana", label: "Grafana", icon: <IconChartAreaLine size={20} /> },
{ to: "/speedtest", label: "Speedtest", icon: <IconGauge size={20} /> },
{ to: "/service-levels", label: "Service levels", icon: <IconTargetArrow size={20} /> },
],
+179
View File
@@ -0,0 +1,179 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, type AdguardInstance } from "../api/client";
import EmptyState from "../components/EmptyState";
import TimeAgo from "../components/TimeAgo";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { formatAgo } from "../utils/duration";
import { readableError } from "../utils/errors";
function Badge({ a }: { a: AdguardInstance }) {
if (!a.enabled) return <span className="badge bg-secondary-lt text-secondary">Off</span>;
if (!a.state) return <span className="badge bg-secondary-lt text-secondary">Not read yet</span>;
if (!a.fresh) return <span className="badge bg-yellow-lt text-yellow">Can&rsquo;t be read</span>;
if (a.problems.some((x) => x.severity === "critical")) return <span className="badge bg-red-lt text-red">Needs a look</span>;
if (a.problems.length > 0) return <span className="badge bg-yellow-lt text-yellow">Needs a look</span>;
return <span className="badge bg-green-lt text-green">In order</span>;
}
function Tile({ label, value, sub, tone }: { label: string; value: string; sub?: string | null; tone?: "bad" | "warn" }) {
return (
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">{label}</div>
<div className={`h2 mb-0 ${tone === "bad" ? "text-red" : tone === "warn" ? "text-yellow" : ""}`}>{value}</div>
{sub && <div className="text-secondary small">{sub}</div>}
</div>
</div>
</div>
);
}
function Counted({ title, items, empty }: { title: string; items: { name: string; count: number }[]; empty: string }) {
const top = items[0]?.count ?? 0;
return (
<div className="col-lg-4">
<h4>{title}</h4>
{items.length === 0 && <div className="text-secondary small">{empty}</div>}
{items.slice(0, 7).map((i) => (
<div key={i.name} className="mb-1">
<div className="d-flex small">
<span className="text-break">{i.name}</span>
<span className="ms-auto text-secondary ps-2">{i.count.toLocaleString()}</span>
</div>
<div className="progress progress-sm">
<div className="progress-bar" style={{ width: `${top > 0 ? Math.max(2, (i.count / top) * 100) : 0}%` }} />
</div>
</div>
))}
</div>
);
}
function Card({ a }: { a: AdguardInstance }) {
const s = a.state;
const st = s?.stats ?? null;
const lists = s?.filters?.lists ?? [];
const on = lists.filter((l) => l.enabled);
const oldest = on.map((l) => l.updated).filter((u): u is string => u !== null).sort()[0] ?? null;
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">
{a.name} <span className="text-secondary fw-normal">{s?.version ?? ""}</span> <Badge a={a} />
</h3>
<div className="card-actions text-secondary small">{a.status ? <>read <TimeAgo value={a.status.at} /></> : "not read yet"}</div>
</div>
<div className="card-body">
{a.status && !a.status.ok && <div className="text-yellow mb-2">The last attempt to read it failed: {a.status.error ?? "no answer"}.</div>}
{a.problems.length > 0 && (
<ul className="mb-3">
{a.problems.map((x) => (
<li key={x.key} className={x.severity === "critical" ? "text-red" : ""}>
{x.message}
</li>
))}
</ul>
)}
{s && (
<>
<div className="row g-3 mb-3">
<Tile
label="DNS answers"
value={!s.running ? "Not running" : s.probe === null ? "—" : s.probe.ok ? `${s.probe.ms ?? "?"} ms` : "No"}
sub={s.probe ? (s.probe.ok ? `a question about ${s.probe.name}, asked ${s.probe.host}:${s.dnsPort}` : `${s.probe.error ?? "no answer"} (${s.probe.host}:${s.dnsPort})`) : "no test yet"}
tone={!s.running || (s.probe && !s.probe.ok) ? "bad" : undefined}
/>
<Tile label="Protection" value={s.protectionEnabled ? "On" : "Off"} sub={s.protectionEnabled ? null : s.protectionOffSince ? `since ${formatAgo(s.protectionOffSince)} — nothing is being blocked` : "nothing is being blocked"} tone={s.protectionEnabled ? undefined : "warn"} />
<Tile label={`Queries${st?.periodHours ? `, last ${st.periodHours >= 48 ? `${Math.round(st.periodHours / 24)} days` : `${st.periodHours} h`}` : ""}`} value={st ? st.queries.toLocaleString() : "—"} sub={st && st.avgMs !== null ? `${st.avgMs} ms on average` : st ? null : "could not be read"} />
<Tile label="Blocked" value={st ? st.blocked.toLocaleString() : "—"} sub={st ? (st.blockedPercent === null ? null : `${st.blockedPercent}% of the queries`) : "could not be read"} />
</div>
{st && (st.topBlocked.length > 0 || st.topClients.length > 0 || st.topQueried.length > 0) && (
<div className="row g-3 mb-3">
<Counted title="Blocked most" items={st.topBlocked} empty="Nothing blocked." />
<Counted title="Asked about most" items={st.topQueried} empty="No queries." />
<Counted title="Asking most" items={st.topClients} empty="No clients." />
</div>
)}
<h4>Filter lists</h4>
{s.filters === null ? (
<div className="text-secondary small">They could not be read.</div>
) : (
<>
<div className="text-secondary small mb-2">
Filtering is {s.filters.enabled ? "on" : "off"}; {on.length} of {lists.length} lists switched on
{oldest ? (
<>
, the longest since an update <TimeAgo value={oldest} />
</>
) : (
""
)}
.
</div>
{s.staleLists.length > 0 && <div className="text-yellow small mb-2">Not updated for over a week: {s.staleLists.join(", ")}.</div>}
<ul className="small mb-0">
{lists.map((l) => (
<li key={l.name} className={l.enabled ? "" : "text-secondary"}>
{l.name} {!l.enabled && <span className="badge bg-secondary-lt text-secondary">off</span>}{" "}
<span className="text-secondary">
{l.rules !== null ? `${l.rules.toLocaleString()} rules · ` : ""}
{l.updated ? (
<>
updated <TimeAgo value={l.updated} />
</>
) : (
"never updated"
)}
</span>
</li>
))}
</ul>
</>
)}
</>
)}
</div>
</div>
);
}
/** AdGuard Home: whether DNS really answers, whether it protects, what it has done and whether its lists are kept up to date. */
export default function AdguardHome() {
const [data, setData] = useState<AdguardInstance[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const load = () =>
api.adguard
.list()
.then((r) => {
setData(r.instances);
setError(null);
})
.catch((err) => setError(readableError(err)));
void load();
const t = setInterval(load, 60_000);
return () => clearInterval(t);
}, []);
return (
<>
<h2 className="page-title">AdGuard Home</h2>
<p className="text-secondary">
Read every two minutes (see <Link to="/integrations">Integrations</Link>), with a real DNS question put to it each time — its web interface can be up while DNS is not. Nothing is changed. <strong>DNS that stops answering</strong>, <strong>a DNS server that is not running</strong>,{" "}
<strong>protection left off for an hour</strong> and <strong>filter lists that stopped updating</strong> are alerts — see <Link to="/alerts">Alerts</Link>.
</p>
<ErrorNotice error={error} />
{!data && !error && <BlockSkeleton lines={4} />}
{data && data.length === 0 && (
<div className="card">
<div className="card-body">
<EmptyState title="No AdGuard Home connected" hint="Add one under Integrations with its address and, if it has a sign-in, a user name and password." />
</div>
</div>
)}
{data?.map((a) => <Card key={a.id} a={a} />)}
</>
);
}
+11 -2
View File
@@ -6,7 +6,9 @@ import { readableError } from "../utils/errors";
const count = (v: number | null) => (v === null ? "—" : v.toLocaleString());
function Host({ env }: { env: DockhandVulnerabilityEnvironment }) {
const ageText = (days: number) => (days >= 730 ? `${Math.floor(days / 365)} years` : days >= 60 ? `${Math.floor(days / 30)} months` : `${days} days`);
function Host({ env, imageAgeDays }: { env: DockhandVulnerabilityEnvironment; imageAgeDays: number }) {
const [open, setOpen] = useState(false);
const unscanned = env.totalImages !== null && env.imagesScanned !== null ? env.totalImages - env.imagesScanned : null;
return (
@@ -28,6 +30,13 @@ function Host({ env }: { env: DockhandVulnerabilityEnvironment }) {
{unscanned !== null && unscanned > 0 ? ` — ${unscanned} not scanned yet` : ""}
</span>
</div>
{env.images && env.images.oldest.length > 0 && (
<div className="small text-secondary mt-1">
Oldest running images: {env.images.oldest.slice(0, 3).map((i) => `${i.image} (${ageText(i.ageDays)})`).join(", ")}
{imageAgeDays > 0 && env.images.over !== null ? (env.images.over > 0 ? ` — ${env.images.over} built more than ${imageAgeDays} days ago (an alert)` : ` — none older than ${imageAgeDays} days`) : ""}
{env.images.undated > 0 ? ` · ${env.images.undated} with no build date` : ""}
</div>
)}
{env.findings.length > 0 && (
<>
<button className="btn btn-link btn-sm p-0 mt-1" onClick={() => setOpen((o) => !o)}>
@@ -128,7 +137,7 @@ export default function DockerVulnerabilities({ integrationId }: { integrationId
{data.environments.length === 0 && !data.status && <div className="text-secondary">Not read yet — it is read a few minutes after Dockhand is added, then every quarter of an hour.</div>}
{data.environments.length === 0 && data.status?.ok && <div className="text-secondary">Dockhand lists no Docker hosts.</div>}
{data.environments.map((e) => (
<Host key={e.environmentId} env={e} />
<Host key={e.environmentId} env={e} imageAgeDays={data.imageAgeDays} />
))}
</>
)}
+162
View File
@@ -0,0 +1,162 @@
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { api, type GrafanaInstance } from "../api/client";
import EmptyState from "../components/EmptyState";
import TimeAgo from "../components/TimeAgo";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { readableError } from "../utils/errors";
function Badge({ g }: { g: GrafanaInstance }) {
if (!g.enabled) return <span className="badge bg-secondary-lt text-secondary">Off</span>;
if (!g.state) return <span className="badge bg-secondary-lt text-secondary">Not read yet</span>;
if (!g.fresh) return <span className="badge bg-yellow-lt text-yellow">Can&rsquo;t be read</span>;
if (g.problems.some((x) => x.severity === "critical")) return <span className="badge bg-red-lt text-red">Needs a look</span>;
if (g.problems.length > 0) return <span className="badge bg-yellow-lt text-yellow">Needs a look</span>;
return <span className="badge bg-green-lt text-green">In order</span>;
}
function Tile({ label, value, sub, warn }: { label: string; value: string; sub?: string | null; warn?: boolean }) {
return (
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">{label}</div>
<div className={`h2 mb-0 ${warn ? "text-yellow" : ""}`}>{value}</div>
{sub && <div className="text-secondary small">{sub}</div>}
</div>
</div>
</div>
);
}
function Card({ g }: { g: GrafanaInstance }) {
const s = g.state;
const rules = s?.rules ?? null;
const firing = rules?.items.filter((r) => r.state === "firing") ?? [];
const pending = rules?.items.filter((r) => r.state === "pending") ?? [];
const broken = rules?.items.filter((r) => r.health === "error") ?? [];
const ds = s?.datasources ?? null;
const failing = ds?.filter((d) => d.ok === false) ?? [];
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">
{g.name} <span className="text-secondary fw-normal">{s?.version ?? ""}</span> <Badge g={g} />
</h3>
<div className="card-actions text-secondary small">{g.status ? <>read <TimeAgo value={g.status.at} /></> : "not read yet"}</div>
</div>
<div className="card-body">
{g.status && !g.status.ok && <div className="text-yellow mb-2">The last attempt to read it failed: {g.status.error ?? "no answer"}.</div>}
{g.problems.length > 0 && (
<ul className="mb-3">
{g.problems.map((x) => (
<li key={x.key} className={x.severity === "critical" ? "text-red" : ""}>
{x.message}
</li>
))}
</ul>
)}
{s && (
<>
<div className="row g-3 mb-3">
<Tile label="Alert rules" value={rules ? String(rules.total) : "—"} sub={rules ? "in Grafana-managed alerting" : "could not be read"} />
<Tile label="Firing" value={rules ? String(firing.length) : "—"} sub={rules ? (pending.length > 0 ? `and ${pending.length} pending` : "none pending") : null} warn={firing.length > 0} />
<Tile label="Cannot be evaluated" value={rules ? String(broken.length) : "—"} sub="rules in an error state" warn={broken.length > 0} />
<Tile label="Data sources" value={ds ? String(ds.length) : "—"} sub={ds ? (failing.length > 0 ? `${failing.length} failing its check` : "none failing") : "could not be listed"} warn={failing.length > 0} />
</div>
{rules && rules.items.length > 0 && (
<>
<h4>Rules that are not quiet</h4>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<th>Rule</th>
<th>State</th>
<th>Where</th>
<th>Since</th>
</tr>
</thead>
<tbody>
{rules.items.map((r) => (
<tr key={`${r.uid ?? r.group}-${r.name}`}>
<td className="text-break">
<strong>{r.name}</strong>
{r.summary && <div className="text-secondary small">{r.summary}</div>}
{r.health === "error" && <div className="text-red small">{r.lastError ?? "cannot be evaluated"}</div>}
</td>
<td>
{r.state === "firing" ? <span className={`badge ${r.severity === "critical" || r.severity === "page" ? "bg-red-lt text-red" : "bg-yellow-lt text-yellow"}`}>firing</span> : r.state === "pending" ? <span className="badge bg-blue-lt text-blue">pending</span> : <span className="badge bg-secondary-lt text-secondary">{r.state}</span>}
{r.severity && <span className="text-secondary small ms-1">{r.severity}</span>}
</td>
<td className="text-secondary small">{[r.folder, r.group].filter(Boolean).join(" / ") || "—"}</td>
<td className="text-secondary">
<TimeAgo value={r.activeAt} />
</td>
</tr>
))}
</tbody>
</table>
</div>
</>
)}
{rules && rules.items.length === 0 && <div className="text-secondary small mb-3">All {rules.total} rules are quiet.</div>}
{ds && ds.length > 0 && (
<>
<h4 className="mt-3">Data sources</h4>
<ul className="mb-0">
{ds.map((d) => (
<li key={d.uid}>
<strong>{d.name}</strong> <span className="text-secondary small">{d.type}{d.isDefault ? " · default" : ""}</span>{" "}
{d.ok === true ? <span className="badge bg-green-lt text-green">working</span> : d.ok === false ? <span className="badge bg-red-lt text-red">failing</span> : <span className="badge bg-secondary-lt text-secondary">not tested</span>}
{d.ok === false && d.message && <span className="text-red small"> {d.message}</span>}
</li>
))}
</ul>
</>
)}
</>
)}
</div>
</div>
);
}
/** Grafana: which alert rules are firing or cannot be evaluated, and which data sources fail their check. */
export default function Grafana() {
const [data, setData] = useState<GrafanaInstance[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const load = () =>
api.grafana
.list()
.then((r) => {
setData(r.instances);
setError(null);
})
.catch((err) => setError(readableError(err)));
void load();
const t = setInterval(load, 60_000);
return () => clearInterval(t);
}, []);
return (
<>
<h2 className="page-title">Grafana</h2>
<p className="text-secondary">
Read every few minutes (see <Link to="/integrations">Integrations</Link>) — nothing is silenced, paused or changed. <strong>A rule that is firing</strong>, <strong>a rule Grafana cannot evaluate</strong> and <strong>a data source that fails its check</strong> are alerts — see <Link to="/alerts">Alerts</Link>.
Grafana can notify about its own alerts too; with both you hear twice.
</p>
<ErrorNotice error={error} />
{!data && !error && <BlockSkeleton lines={4} />}
{data && data.length === 0 && (
<div className="card">
<div className="card-body">
<EmptyState title="No Grafana connected" hint="Add one under Integrations with its address and a service account token (Administration → Users and access → Service accounts; the Viewer role is enough)." />
</div>
</div>
)}
{data?.map((g) => <Card key={g.id} g={g} />)}
</>
);
}
+20 -4
View File
@@ -42,6 +42,7 @@ import { PageSkeleton } from "../components/Skeleton";
import ViewTabs from "../components/ViewTabs";
import ConnectedThrough from "../components/ConnectedThrough";
import HetznerServerCard from "../components/HetznerServerCard";
import ServerBlock, { ArrangeBar } from "../components/ServerBlock";
const SCHEDULE_TYPE_OPTIONS: { value: ScheduleType; label: string }[] = Object.entries(SCHEDULE_TYPE_LABELS).map(
([value, label]) => ({ value: value as ScheduleType, label }),
@@ -446,6 +447,9 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
{view === "overview" && (
<>
<ArrangeBar />
<div className="d-flex flex-column">
<ServerBlock id="admin-links" label="Admin Links" at={0}>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Admin Links</h3>
@@ -537,11 +541,15 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
)}
</div>
</div>
</ServerBlock>
<ServerBlock id="hetzner" label="Hetzner Cloud" at={10}>
<HetznerServerCard serverId={serverId} />
</ServerBlock>
<ServerBlock id="hardware-identity" label="Hardware, network and identity" at={20} noFold>
<div className="row row-cards mb-3">
<div className="col-lg-7">
<ServerBlock id="hardware" label="Hardware & Network" className="col-lg-7">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Hardware &amp; Network</h3>
@@ -687,9 +695,9 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
)}
</div>
</div>
</div>
</ServerBlock>
<div className="col-lg-5">
<ServerBlock id="identity" label="Identity" className="col-lg-5">
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">Identity</h3>
@@ -765,11 +773,17 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
</dl>
</div>
</div>
</div>
</ServerBlock>
</div>
</ServerBlock>
<ServerBlock id="todos" label="To do" at={30}>
<TodosCard targetType="server" targetId={server.id} canEdit={canEditTasks} />
</ServerBlock>
<ServerBlock id="notes" label="Notes" at={40}>
<NotesCard targetType="server" targetId={server.id} canEdit={canEditTasks} />
</ServerBlock>
<ServerBlock id="runbooks" label="Runbooks" at={50}>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Runbooks</h3>
@@ -777,6 +791,8 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
<div className="card-body">
<RunbookPanel targetType="server" targetId={server.id} targetName={server.name} canEdit={canEditTasks} />
</div>
</div>
</ServerBlock>
</div>
</>
)}
@@ -84,7 +84,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, deviceOfflineMinutes: 10, osSupportWarnDays: 90, baselineAlerts: true, containerAlerts: true, vulnerabilityAlerts: true, vulnerabilityHighThreshold: 0, containerIgnore: [] };
const DEFAULT_HEALTH_CHECKS: HealthCheckSettings = { serverOfflineMinutes: 60, diskUsagePercent: 90, domainWarnDays: 30, diskForecastDays: 14, backupStaleHours: 48, restoreTestDays: 0, newPortAlerts: true, flapRaises: 3, deviceOfflineMinutes: 10, osSupportWarnDays: 90, baselineAlerts: true, containerAlerts: true, vulnerabilityAlerts: true, vulnerabilityHighThreshold: 0, imageAgeDays: 0, containerIgnore: [] };
const DEFAULT_MONTHLY: MonthlyReportSettings = { enabled: false, quarterly: false, annual: false, day: 1, time: "08:00" };
type TestResult = { ok: boolean; message: string } | null;
@@ -920,6 +920,17 @@ export default function NotificationSettings() {
onChange={(v) => setHealthChecks((h) => ({ ...h, vulnerabilityHighThreshold: v }))}
/>
</div>
<div className="mt-3">
<NumberField
label="Warn about running Docker images that were built more than"
value={healthChecks.imageAgeDays}
min={0}
max={3650}
unit="days ago (0 = never)"
hint="Even when no scan has been run or the scan found nothing: an image that has not been rebuilt for months has not had its fixes. Needs Dockhand; the date is when the image was built, as Docker lists it (not when it was pulled). Off by default — try 180 and see how many it names before relying on it."
onChange={(v) => setHealthChecks((h) => ({ ...h, imageAgeDays: v }))}
/>
</div>
</div>
</div>
</div>
+31
View File
@@ -833,6 +833,37 @@ main:focus {
box-shadow: inset 0 0 0 3px #ffc247;
}
/* A server's overview: a card's header folds it, and the page can be arranged (components/ServerBlock.tsx). */
.server-block:not(:has(.card)) {
display: none;
}
.server-block .card-header {
cursor: pointer;
}
.server-block .card-header .card-title::after {
content: " ▾";
font-size: 0.8em;
opacity: 0.45;
}
.server-block-folded .card-header .card-title::after {
content: " ▸";
}
.server-block-folded .card > :not(.card-header) {
display: none;
}
.server-block-folded .card-header {
border-bottom: 0;
}
.server-block-tools {
min-height: 2rem;
}
.wall-tile-info {
box-shadow: inset 0 0 0 3px #4dabf7;
}
+6 -2
View File
@@ -30,6 +30,8 @@ export const TYPE_LABELS: Record<IntegrationType, string> = {
sonarr: "Sonarr",
radarr: "Radarr",
prowlarr: "Prowlarr",
adguard: "AdGuard Home",
grafana: "Grafana",
};
/** The page each kind of integration gets once it is connected. */
@@ -62,6 +64,8 @@ export const TYPE_PAGES: Record<IntegrationType, string> = {
sonarr: "/media",
radarr: "/media",
prowlarr: "/media",
adguard: "/adguard",
grafana: "/grafana",
};
/** The kinds of integration grouped the way the sidebar groups their pages, in the same order. */
@@ -69,8 +73,8 @@ export const TYPE_GROUPS: { id: string; label: string; types: IntegrationType[]
{ id: "infrastructure", label: "Infrastructure", types: ["proxmox", "synology", "dockhand", "hetzner", "fragnet", "tailscale"] },
{ id: "apps", label: "Apps", types: ["homeassistant", "jellyfin", "sonarr", "radarr", "prowlarr", "immich", "paperless", "nextcloud", "authentik"] },
{ id: "backups", label: "Backups", types: ["pbs"] },
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox"] },
{ id: "monitoring", label: "Monitoring", types: ["uptimekuma", "prometheus", "ups", "speedtest"] },
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard"] },
{ id: "monitoring", label: "Monitoring", types: ["uptimekuma", "prometheus", "grafana", "ups", "speedtest"] },
{ id: "automation", label: "Automation", types: ["semaphore", "gitea", "osticket", "n8n"] },
];
+93
View File
@@ -0,0 +1,93 @@
import { useSyncExternalStore } from "react";
import { api, type PageLayout } from "../api/client";
import { readableError } from "./errors";
import { toast } from "./toast";
// How this person arranged a server's overview page: which cards they folded and in what order the blocks come. It is kept on their user record on the
// server, so it follows them to any browser, and is the same for every server; here it is kept in step so every block, and the Arrange bar, see the same layout.
const EMPTY: PageLayout = { folded: [], order: {} };
interface State {
layout: PageLayout;
/** The person is arranging: each block shows its buttons. */
editing: boolean;
}
let state: State = { layout: EMPTY, editing: false };
const listeners = new Set<() => void>();
/** Only the answer to the latest change may overwrite the layout, however the replies are ordered. */
let latest = 0;
function set(next: State) {
state = next;
for (const l of listeners) l();
}
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
/** Loads the layout the server sent with the signed-in user. */
export function initServerPageLayout(layout: PageLayout | undefined): void {
set({ ...state, layout: layout ? { folded: [...layout.folded], order: { ...layout.order } } : EMPTY });
}
export function useServerPageLayout(): State {
return useSyncExternalStore(subscribe, () => state);
}
export function setEditingServerPage(editing: boolean): void {
set({ ...state, editing });
}
/** Shown at once; put back, with a message, if the server can't save it. */
async function save(next: PageLayout): Promise<void> {
const before = state.layout;
set({ ...state, layout: next });
const mine = ++latest;
try {
const res = await api.me.setServerPage(next);
if (mine === latest) set({ ...state, layout: res.serverPage });
} catch (err) {
if (mine === latest) {
set({ ...state, layout: before });
toast.error(`Couldn't save how the page is arranged: ${readableError(err)}`);
}
}
}
export function toggleFolded(id: string): Promise<void> {
const { layout } = state;
const folded = layout.folded.includes(id);
return save({ ...layout, folded: folded ? layout.folded.filter((f) => f !== id) : [...layout.folded, id] });
}
/**
* Moves a block one place earlier or later among the blocks of the same stack. Every block of the stack is given its place at the same time (blocks with nothing to show —
* a Hetzner card for a server that is not at Hetzner — are stepped over), so a stack is either left as drawn or fully placed.
*/
export function moveBlock(block: HTMLElement, direction: -1 | 1): Promise<void> {
const stack = block.parentElement;
if (!stack) return Promise.resolve();
const all = [...stack.children]
.filter((el): el is HTMLElement => el instanceof HTMLElement && el.dataset.arrange !== undefined)
.map((el, index) => ({ el, id: el.dataset.block!, index, shown: el.querySelector(".card") !== null }));
const placed = all.sort((a, b) => (state.layout.order[a.id] ?? Number(a.el.dataset.at)) - (state.layout.order[b.id] ?? Number(b.el.dataset.at)) || a.index - b.index);
const at = placed.findIndex((p) => p.el === block);
if (at === -1) return Promise.resolve();
let to = at + direction;
while (to >= 0 && to < placed.length && !placed[to].shown) to += direction;
if (to < 0 || to >= placed.length) return Promise.resolve();
[placed[at], placed[to]] = [placed[to], placed[at]];
const order = { ...state.layout.order };
placed.forEach((p, i) => (order[p.id] = i * 10));
return save({ ...state.layout, order });
}
export function resetServerPageLayout(): Promise<void> {
return save(EMPTY);
}