Alert rules of your own, storage forecasts for Proxmox and Synology, and snooze

- Monitoring -> Alert rules: CPU, memory, disk use and disk temperature limits with a time, severity and scope (all, one server, a tag); try before saving; findings are ordinary health conditions
- Proxmox storages and Synology volumes are written down on each health pass (hourly, 400 days) and forecast like server disks: badge and history chart on the pages, alert, digest line, /metrics gauge
- Snooze an alert until a time; held back like maintenance, messages held, announced once again if still there when it ends
- Docs updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-20 23:38:36 +02:00
1 parent 788b3e073c
commit 24ae8db380
38 files changed
+7847 -8

No files matched your search

+1
View File
@@ -74,6 +74,7 @@ export function mostWithin(times: number[], windowMs: number): number {
/** What to try, from the kind of alert and the key it has. Plain advice; nothing it says is done for anyone. */
export function hintFor(category: string, alertId: string): string {
const key = keyOfAlertId(alertId, category);
if (key.startsWith("rule:")) return "A limit of your own (Monitoring → Alert rules): if it keeps coming back, raise the limit or make it hold for longer before it raises.";
if (key.startsWith("new-port:")) return "If this port should be listening, mark it as expected on the server's Ports card.";
if (key.startsWith("heartbeat")) return "If the job is just sometimes late, give its heartbeat more grace; if it fails, look at what it printed.";
if (key.startsWith("endpoint:")) return "Raise “Alert after … failures in a row” on the check, or its timeout or interval — or fix what is making it fail.";
+211
View File
@@ -0,0 +1,211 @@
/**
* Alert rules of your own: "CPU above 90% for 15 minutes", "memory above 85%", "a disk is warmer than 55 °C". Each is a limit on one figure of the servers it covers (all of
* them, one, or those with a tag), with the severity it should have. They are judged on the same pass as the built-in checks — what they find becomes ordinary health
* conditions (`rule:<id>:server:<server>[:<disk>]`) — so they are announced, recovered, held back while flapping, silenced by maintenance and routed like the rest.
*
* Load, memory and disk use are judged from the history the agents' reports build (a sample every ten to fifteen minutes): a rule with a time says the figure must have been
* past its limit on every sample for that long. A disk's temperature is only known as of its last report, so it is judged right now. A server that is not reporting is not
* judged — its own offline alert says that.
*/
import { eq, gte } from "drizzle-orm";
import { db } from "../db/client.js";
import { alertRules, serverMetrics, servers, type AlertRuleMetric } from "../db/schema.js";
import { parseHostHealth } from "./hostHealth.js";
import { InvalidTagError, normalizeTag, parseTags } from "./serverTags.js";
export type RuleRow = typeof alertRules.$inferSelect;
export const MAX_FOR_MINUTES = 24 * 60;
export const MAX_RULES = 100;
/** A server whose newest sample is older than this is not judged: the figure is no longer "now". */
export const STALE_AFTER_MS = 45 * 60_000;
export const METRIC_WORDS: Record<AlertRuleMetric, { label: string; unit: string }> = {
cpu: { label: "CPU load", unit: "%" },
mem: { label: "Memory in use", unit: "%" },
disk: { label: "Disk use", unit: "%" },
disk_temp: { label: "Disk temperature", unit: " °C" },
};
export interface RuleFinding {
ruleId: number;
ruleName: string;
serverId: number;
serverName: string;
/** The disk (mount point, or device for a temperature) it is about, if any. */
detail: string | null;
value: number;
severity: "warning" | "critical";
/** When this run of samples past the limit began (epoch ms); null when it is judged right now. */
since: number | null;
message: string;
}
export interface RuleServer {
id: number;
name: string;
tags: string[];
/** What the last report said about each disk's temperature. */
smart: { device: string; temperatureC: number | null }[];
}
export type RuleSamples = Map<string, { t: number; v: number }[]>;
export const sampleKey = (serverId: number, metric: string) => `${serverId}|${metric}`;
const durationWords = (minutes: number) => (minutes < 60 ? `${minutes} min` : minutes % 60 === 0 ? `${minutes / 60} h` : `${Math.floor(minutes / 60)} h ${minutes % 60} min`);
const breaches = (rule: Pick<RuleRow, "operator" | "threshold">, v: number) => (rule.operator === "above" ? v > rule.threshold : v < rule.threshold);
export function ruleCovers(rule: Pick<RuleRow, "serverId" | "tag">, server: Pick<RuleServer, "id" | "tags">): boolean {
if (rule.serverId !== null) return rule.serverId === server.id;
if (rule.tag) return server.tags.some((t) => t.toLowerCase() === rule.tag!.toLowerCase());
return true;
}
/**
* Pure: how long the newest samples have been past the limit without a break. Returns the figure now and when the unbroken run began, or null when the newest sample is
* not past the limit (or is too old to say).
*/
export function currentRun(rule: Pick<RuleRow, "operator" | "threshold">, samples: { t: number; v: number }[], now: number): { value: number; since: number; latest: number } | null {
if (samples.length === 0) return null;
const sorted = [...samples].sort((a, b) => a.t - b.t);
const newest = sorted[sorted.length - 1];
if (now - newest.t > STALE_AFTER_MS || !breaches(rule, newest.v)) return null;
let since = newest.t;
for (let i = sorted.length - 2; i >= 0; i--) {
if (!breaches(rule, sorted[i].v)) break;
since = sorted[i].t;
}
return { value: newest.v, since, latest: newest.t };
}
/** Pure: what the rules find on these servers, from their samples (and, for temperatures, the last report). */
export function evaluateRules(rules: RuleRow[], serversIn: RuleServer[], samples: RuleSamples, now: number): RuleFinding[] {
const out: RuleFinding[] = [];
for (const rule of rules) {
if (!rule.enabled) continue;
const word = METRIC_WORDS[rule.metric];
const limit = `${rule.operator} ${rule.threshold}${word.unit}`;
for (const s of serversIn) {
if (!ruleCovers(rule, s)) continue;
if (rule.metric === "disk_temp") {
for (const d of s.smart) {
if (d.temperatureC === null || !breaches(rule, d.temperatureC)) continue;
out.push({ ruleId: rule.id, ruleName: rule.name, serverId: s.id, serverName: s.name, detail: d.device, value: d.temperatureC, severity: rule.severity, since: null, message: `${s.name}: ${d.device} is ${Math.round(d.temperatureC)}${word.unit}, ${limit} [${rule.name}]` });
}
continue;
}
const metrics = rule.metric === "disk" ? [...samples.keys()].filter((k) => k.startsWith(`${s.id}|disk:`) && (rule.mount === null || k === sampleKey(s.id, `disk:${rule.mount}`))) : [sampleKey(s.id, rule.metric)];
for (const k of metrics) {
const run = currentRun(rule, samples.get(k) ?? [], now);
if (!run) continue;
// The figure must have been past the limit for the whole time: the run began that long before the newest sample.
const heldFor = Math.floor((run.latest - run.since) / 60_000);
if (rule.forMinutes > 0 && heldFor < rule.forMinutes) continue;
const detail = rule.metric === "disk" ? k.slice(`${s.id}|disk:`.length) : null;
const what = rule.metric === "disk" ? `${s.name}: ${detail} use` : `${s.name}: ${word.label.toLowerCase()}`;
out.push({
ruleId: rule.id,
ruleName: rule.name,
serverId: s.id,
serverName: s.name,
detail,
value: run.value,
severity: rule.severity,
since: run.since,
message: `${what} is ${Math.round(run.value)}${word.unit}, ${limit}${rule.forMinutes > 0 ? ` for ${durationWords(rule.forMinutes)}` : ""} [${rule.name}]`,
});
}
}
}
return out;
}
/** The condition key a finding has: the same finding always has the same key, so it is announced once. */
export const findingKey = (f: Pick<RuleFinding, "ruleId" | "serverId" | "detail">) => `rule:${f.ruleId}:server:${f.serverId}${f.detail ? `:${f.detail}` : ""}`;
export async function listRules(): Promise<RuleRow[]> {
return (await db.select().from(alertRules)).sort((a, b) => a.name.localeCompare(b.name) || a.id - b.id);
}
/** What the given rules find right now, from the stored history. Reads nothing when no rule is on. */
export async function computeRuleFindings(rules: RuleRow[], now: number = Date.now()): Promise<RuleFinding[]> {
const on = rules.filter((r) => r.enabled);
if (on.length === 0) return [];
const rows = await db.select({ id: servers.id, name: servers.name, tags: servers.tags, hostHealth: servers.hostHealth }).from(servers);
const serverList: RuleServer[] = rows.map((r) => ({
id: r.id,
name: r.name,
tags: parseTags(r.tags),
smart: (parseHostHealth(r.hostHealth)?.smart ?? []).map((d) => ({ device: d.device, temperatureC: d.temperatureC })),
}));
const samples: RuleSamples = new Map();
if (on.some((r) => r.metric !== "disk_temp")) {
const longest = Math.max(...on.filter((r) => r.metric !== "disk_temp").map((r) => r.forMinutes));
const since = new Date(now - (longest * 60_000 + 3 * 3600_000)).toISOString();
for (const r of await db.select().from(serverMetrics).where(gte(serverMetrics.recordedAt, since))) {
if (r.metric !== "cpu" && r.metric !== "mem" && !r.metric.startsWith("disk:")) continue;
const k = sampleKey(r.serverId, r.metric);
const list = samples.get(k) ?? [];
list.push({ t: Date.parse(r.recordedAt), v: r.value });
samples.set(k, list);
}
}
return evaluateRules(on, serverList, samples, now);
}
// ─── Making and changing rules ─────────────────────────────────────────────
export class RuleError extends Error {
constructor(
readonly status: number,
readonly code: string,
message: string,
) {
super(message);
}
}
export interface RuleInput {
name: string;
enabled?: boolean;
metric: AlertRuleMetric;
mount?: string | null;
operator?: "above" | "below";
threshold: number;
forMinutes?: number;
severity?: "warning" | "critical";
serverId?: number | null;
tag?: string | null;
}
/** Checks and tidies what was asked for; says plainly what is wrong with it. */
export async function checkedRule(input: RuleInput): Promise<Omit<RuleRow, "id" | "createdAt" | "createdBy">> {
const name = input.name.trim();
if (name === "" || name.length > 80) throw new RuleError(400, "invalid_name", "Give the rule a name, up to 80 characters.");
const operator = input.operator ?? "above";
if (!Number.isFinite(input.threshold)) throw new RuleError(400, "invalid_threshold", "The limit has to be a number.");
const percent = input.metric !== "disk_temp";
if (percent && (input.threshold < 0 || input.threshold > 100)) throw new RuleError(400, "invalid_threshold", "A percentage limit is between 0 and 100.");
if (!percent && (input.threshold < 0 || input.threshold > 150)) throw new RuleError(400, "invalid_threshold", "A temperature limit is between 0 and 150 °C.");
const forMinutes = percent ? Math.round(input.forMinutes ?? 0) : 0;
if (!Number.isInteger(forMinutes) || forMinutes < 0 || forMinutes > MAX_FOR_MINUTES) throw new RuleError(400, "invalid_for", "How long it has to hold is from 0 to 1440 minutes (a day).");
const mount = input.metric === "disk" ? input.mount?.trim() || null : null;
if (mount && mount.length > 200) throw new RuleError(400, "invalid_mount", "That disk name is too long.");
let tag: string | null = null;
if (input.tag?.trim()) {
try {
tag = normalizeTag(input.tag);
} catch (err) {
if (err instanceof InvalidTagError) throw new RuleError(400, "invalid_tag", err.message);
throw err;
}
}
const serverId = input.serverId ?? null;
if (serverId !== null && tag) throw new RuleError(400, "invalid_scope", "A rule is for one server, or for servers with a tag, not both.");
if (serverId !== null) {
const [row] = await db.select({ id: servers.id }).from(servers).where(eq(servers.id, serverId)).limit(1);
if (!row) throw new RuleError(400, "unknown_server", "That server is not there.");
}
return { name, enabled: input.enabled ?? true, metric: input.metric, mount, operator, threshold: input.threshold, forMinutes, severity: input.severity ?? "warning", serverId, tag };
}
+99
View File
@@ -0,0 +1,99 @@
/**
* Snooze: "remind me tomorrow at 09:00". An alert that is snoozed is hidden — on the Alerts page it is held back like one under maintenance, so it is not counted in the
* badges, the dashboard or the digest — and the messages about it from the health and automation checks are not sent. It is not maintenance: nothing is promised about
* the thing, only that nobody wants to hear about it until then. When the time comes, an alert that is still there is announced again, once, as a reminder; one that
* went away in the meantime is simply forgotten.
*
* A snooze belongs to the alert's id and goes away, like an acknowledgement, once the alert has been gone for half an hour — the same problem coming back later is new.
*/
import { eq, inArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { alertSnoozes } from "../db/schema.js";
export const MAX_DAYS = 90;
/** At least this far ahead, so a snooze cannot end before it has begun. */
export const MIN_AHEAD_MS = 60_000;
/** A snoozed alert that has been absent this long loses its snooze. */
export const GONE_AFTER_MS = 30 * 60_000;
export class SnoozeError extends Error {
constructor(
readonly status: number,
readonly code: string,
message: string,
) {
super(message);
}
}
export interface SnoozeInfo {
until: string;
snoozedBy: string;
snoozedAt: string;
}
const shape = (r: typeof alertSnoozes.$inferSelect): SnoozeInfo => ({ until: r.until, snoozedBy: r.snoozedBy, snoozedAt: r.snoozedAt });
/** The snoozes still running, by alert id. */
export async function loadSnoozes(now: Date = new Date()): Promise<Map<string, SnoozeInfo>> {
return new Map((await db.select().from(alertSnoozes)).filter((r) => Date.parse(r.until) > now.getTime()).map((r) => [r.alertId, shape(r)]));
}
/** Pure: whether a notification about this condition key is held because it is snoozed. */
export function isSnoozedKey(rows: { conditionKey: string; until: string }[], key: string | undefined, now: Date): boolean {
return key !== undefined && rows.some((r) => r.conditionKey === key && Date.parse(r.until) > now.getTime());
}
/** Drops from a list of messages the ones about alerts that are snoozed. */
export async function withoutSnoozed<T extends { key?: string }>(items: T[], now: Date = new Date()): Promise<T[]> {
if (!items.some((i) => i.key)) return items;
const rows = await db.select({ conditionKey: alertSnoozes.conditionKey, until: alertSnoozes.until }).from(alertSnoozes);
if (rows.length === 0) return items;
return items.filter((i) => !isSnoozedKey(rows, i.key, now));
}
export async function setSnooze(input: { alertId: string; conditionKey: string; message: string; until: Date; actor: string }, now: Date = new Date()): Promise<SnoozeInfo> {
if (!(input.until.getTime() >= now.getTime() + MIN_AHEAD_MS)) throw new SnoozeError(400, "invalid_until", "Choose a time that has not come yet.");
if (input.until.getTime() > now.getTime() + MAX_DAYS * 86_400_000) throw new SnoozeError(400, "invalid_until", `A snooze can be at most ${MAX_DAYS} days.`);
const values = { conditionKey: input.conditionKey, message: input.message.slice(0, 500), until: input.until.toISOString(), snoozedBy: input.actor, snoozedAt: now.toISOString(), lastSeenAt: now.toISOString() };
await db.insert(alertSnoozes).values({ alertId: input.alertId, ...values }).onConflictDoUpdate({ target: alertSnoozes.alertId, set: values });
return { until: values.until, snoozedBy: values.snoozedBy, snoozedAt: values.snoozedAt };
}
export async function clearSnooze(alertId: string): Promise<{ message: string } | null> {
const [row] = await db.select().from(alertSnoozes).where(eq(alertSnoozes.alertId, alertId)).limit(1);
if (!row) return null;
await db.delete(alertSnoozes).where(eq(alertSnoozes.id, row.id));
return { message: row.message };
}
export interface Reminder {
key: string;
message: string;
severity?: string;
}
/**
* One look, with the alerts that are there now: snoozes that have run out are removed, and each whose alert is still there becomes a reminder; the others' alerts are
* marked as seen, and those that have been gone for half an hour are dropped. Returns the reminders to send.
*/
export async function settleSnoozes(present: { id: string; message: string; severity: string; key: string }[], now: Date = new Date()): Promise<Reminder[]> {
const rows = await db.select().from(alertSnoozes);
if (rows.length === 0) return [];
const byId = new Map(present.map((a) => [a.id, a]));
const reminders: Reminder[] = [];
const done: number[] = [];
const seen: number[] = [];
const cutoff = new Date(now.getTime() - GONE_AFTER_MS).toISOString();
for (const r of rows) {
const there = byId.get(r.alertId);
if (Date.parse(r.until) <= now.getTime()) {
if (there) reminders.push({ key: r.conditionKey, message: there.message, severity: there.severity });
done.push(r.id);
} else if (there) seen.push(r.id);
else if (r.lastSeenAt < cutoff) done.push(r.id);
}
if (seen.length > 0) await db.update(alertSnoozes).set({ lastSeenAt: now.toISOString() }).where(inArray(alertSnoozes.id, seen));
if (done.length > 0) await db.delete(alertSnoozes).where(inArray(alertSnoozes.id, done));
return reminders;
}
+2
View File
@@ -23,6 +23,8 @@ export interface Alert {
causedBy?: { name: string; alertId?: string };
/** On a host's alert: the servers on it whose own alerts are folded under this one. */
affects?: string[];
/** Snoozed until then (services/alertSnoozes.ts): held back like one under maintenance, and announced again if it is still there. */
snoozed?: { until: string; by: string };
/** Raised and cleared over and over: its raised and cleared messages are being held back (services/flapGuard.ts). */
flapping?: boolean;
/** What a maintenance window would have to be on to silence it, when there is such a thing — which is what "Silence" acts on. */
+39 -2
View File
@@ -13,6 +13,7 @@ import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { endpointChecks, haEntities, haWatched, heartbeats, integrations, networkDevices, secrets, servers } from "../db/schema.js";
import { disksFillingSoon, getForecastSeries } from "./serverMetrics.js";
import { storageFillingSoon, storageOverview } from "./storageHistory.js";
import { daysOfSupportLeft, lifecycleOf } from "./osLifecycle.js";
import { npmIntegrationIds, npmProblems, readNpm } from "./npmReader.js";
import { haProblems, haSyncStatuses, isHaFresh } from "./homeAssistantSync.js";
@@ -21,6 +22,7 @@ import { getBackupCoverage, staleBackups } from "./backupCoverage.js";
import { recordFromReport } from "./incidents.js";
import { reconcileAcks } from "./alertAcks.js";
import { flappingKeys, keyOfAlertId } from "./flapGuard.js";
import { loadSnoozes } from "./alertSnoozes.js";
import { lastAttempt as lastSelfBackup, newestSnapshot, STALE_AFTER_HOURS as SELF_BACKUP_STALE_HOURS } from "./selfBackup.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
@@ -88,7 +90,9 @@ const SEVERITY_ORDER: Record<AlertSeverity, number> = { critical: 0, warning: 1,
function originOfConditionKey(key: string): { type: string; id: number | null; category: AlertCategory } {
const device = /^offline:device:(\d+)$/.exec(key);
if (device) return { type: "unifi", id: Number(device[1]), category: "offline" };
let m = /^(?:offline|disk|failed-units|smart|zfs|new-port):server:(\d+)/.exec(key);
let m = /^rule:\d+:server:(\d+)/.exec(key);
if (m) return { type: "server", id: Number(m[1]), category: "monitoring" };
m = /^(?:offline|disk|failed-units|smart|zfs|new-port):server:(\d+)/.exec(key);
if (m) return { type: "server", id: Number(m[1]), category: key.startsWith("offline") ? "offline" : key.startsWith("failed-units") ? "services" : key.startsWith("new-port") ? "monitoring" : "disk" };
m = /^disk:proxmox:(\d+):/.exec(key);
if (m) return { type: "proxmox", id: Number(m[1]), category: "disk" };
@@ -217,11 +221,12 @@ export async function collectAlerts(): Promise<AlertsReport> {
type: origin.type,
message: c.message,
key: c.key,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : ""}` : origin.type === "unifi" ? "/network/devices" : undefined,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : c.key.startsWith("rule:") ? "?view=history" : ""}` : origin.type === "unifi" ? "/network/devices" : undefined,
silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject),
});
}
// Integrations the check couldn't read this time. (A whole-integration entry covers its nodes, so skip those.)
if (held.has("server:rules")) cannotCheck("Alert rules", "couldn't be judged — see the server log", "Server and storage health");
for (const h of held) {
const m = /^(proxmox|synology|unifi):(\d+)(?::(.+))?$/.exec(h);
if (!m || (m[3] && held.has(`${m[1]}:${m[2]}`))) continue;
@@ -520,6 +525,26 @@ export async function collectAlerts(): Promise<AlertsReport> {
}
}),
// The same for the pools the integrations report (a Proxmox storage, a Synology volume), from the history kept on each health pass.
check("Storage forecasts", async () => {
const { healthChecks } = await getSettings();
if (!(healthChecks.diskForecastDays > 0)) return;
const nowMs = Date.now();
const rows = (await storageOverview()).filter((r) => nowMs - Date.parse(r.updatedAt) < 2 * 86_400_000 && intById.get(r.integrationId)?.enabled);
for (const f of storageFillingSoon(rows, healthChecks.diskForecastDays, healthChecks.diskUsagePercent)) {
const row = intById.get(f.integrationId)!;
push({
category: "disk",
severity: f.daysToFull <= 3 ? "critical" : "warning",
type: row.type,
message: `${f.label} is filling by about ${f.perDay.toFixed(1)} points a day — full in about ${plural(f.daysToFull, "day")} (${Math.round(f.latest)}% used now)`,
key: `storage-forecast:${f.integrationId}:${f.key}`,
silenced: silencedIntegration(f.integrationId),
target: integrationTarget(f.integrationId),
});
}
}),
// Certificates in use by Nginx Proxy Manager that are running out, and hosts it could not set up.
check("Nginx Proxy Manager", async () => {
for (const i of await npmIntegrationIds()) {
@@ -617,6 +642,18 @@ export async function collectAlerts(): Promise<AlertsReport> {
const flapping = await flappingKeys().catch(() => new Set<string>());
if (flapping.size > 0) for (const a of alerts) if (flapping.has(keyOfAlertId(a.id, a.category))) a.flapping = true;
// Those somebody has snoozed are held back like those under maintenance, with when they come back.
const snoozes = await loadSnoozes().catch(() => new Map<string, { until: string; snoozedBy: string }>());
if (snoozes.size > 0) {
for (const a of alerts) {
const sn = snoozes.get(a.id);
if (sn) {
a.snoozed = { until: sn.until, by: sn.snoozedBy };
a.silenced = true;
}
}
}
const active = alerts.filter((a) => !a.silenced);
const grouped = alerts.filter((a) => a.causedBy).length;
return {
+14
View File
@@ -40,6 +40,7 @@ const KIND_OF_CATEGORY: Record<string, ChangeKind> = {
share_link: "settings",
metrics_token: "settings",
api_token: "settings",
alert_rule: "alerts",
todo: "other",
note: "servers",
webhook: "settings",
@@ -178,6 +179,19 @@ export function describeChange(category: string, action: string, detail: Record<
return { title: "Acknowledging several alerts at once was undone", tone: "neutral", detail: null };
case "inventory/bulk_change":
return { title: detail.change === "undo" ? "A change to several pieces of hardware was undone" : `${typeof detail.changed === "number" ? detail.changed : "Several"} piece${detail.changed === 1 ? "" : "s"} of hardware changed at once`, tone: "neutral", detail: genericSummary(detail, ["ids", "changed", "change"]) };
case "alert_rule/create":
return { title: `Alert rule added${name ? `: ${name}` : ""}`, tone: "neutral", detail: genericSummary(detail) };
case "alert_rule/update":
return { title: `Alert rule changed${name ? `: ${name}` : ""}`, tone: "neutral", detail: genericSummary(detail) };
case "alert_rule/enable":
case "alert_rule/disable":
return { title: `Alert rule switched ${action === "enable" ? "on" : "off"}${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "alert_rule/delete":
return { title: `Alert rule removed${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "alert/snooze":
return { title: `Alert snoozed${typeof detail.message === "string" ? `: ${detail.message}` : ""}`, tone: "neutral", detail: str(detail.until) ? `until ${str(detail.until)}` : null };
case "alert/unsnooze":
return { title: `Snooze ended early${typeof detail.message === "string" ? `: ${detail.message}` : ""}`, tone: "neutral", detail: null };
case "alert/flapping_started":
return { title: `Alert began flapping${str(detail.message) ? `: ${str(detail.message)}` : ""}`, tone: "bad", detail: typeof detail.raises === "number" ? `raised ${detail.raises} times within an hour; its messages are held back` : null };
case "alert/flapping_ended":
+23
View File
@@ -15,6 +15,8 @@ import { hostHealthConditions, parseHostHealth, withoutIgnoredServices, type Hos
import { newListeningPorts, newPortMessage, parseBaseline, portKey, type NewPort } from "./newPorts.js";
import { parseJson, type AgentPort } from "./agentPorts.js";
import { diskLimit, parseThresholds, type ServerThresholds } from "./serverThresholds.js";
import { computeRuleFindings, findingKey, listRules, type RuleFinding } from "./alertRules.js";
import { recordStorageSamples } from "./storageHistory.js";
const STATE_FLAG = HEALTH_STATE_FLAG;
/** After a restart the agents haven't had a chance to report yet (they run every 15 min), so server-derived conditions are held rather than judged. */
@@ -66,6 +68,8 @@ export interface HealthSnapshot {
proxmox: ProxmoxSnapshot[];
synology: SynologySnapshot[];
unifi?: UnifiSnapshot[];
/** What the administrator's own alert rules find on the servers (services/alertRules.ts). */
rules?: RuleFinding[];
}
export interface Thresholds {
serverOfflineMinutes: number;
@@ -155,6 +159,15 @@ export function evaluateHealth(snapshot: HealthSnapshot, thresholds: Thresholds,
}
}
// The administrator's own rules: judged only for servers that are reporting (one that is not has its offline alert).
if (!opts.skipServers) {
const offlineIds = new Set(out.map((c) => /^offline:server:(\d+)$/.exec(c.key)?.[1]).filter((id): id is string => id !== undefined).map(Number));
for (const f of snapshot.rules ?? []) {
if (offlineIds.has(f.serverId)) continue;
out.push({ key: findingKey(f), source: "server:rules", message: f.message, severity: f.severity });
}
}
for (const u of snapshot.unifi ?? []) {
const limitMs = (thresholds.deviceOfflineMinutes ?? 10) * 60_000;
for (const d of u.devices) {
@@ -351,6 +364,14 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
snapshot.servers.push({ id: s.id, name: s.name, lastSeenAt: s.lastSeenAt, disks, health: withoutIgnoredServices(parseHostHealth(s.hostHealth), parseThresholds(s.thresholds)?.ignoreServices), thresholds: parseThresholds(s.thresholds), newPorts });
}
// Their own rules: what the stored history says. A failure here costs only the rules.
try {
snapshot.rules = await computeRuleFindings(await listRules());
} catch (err) {
console.error("[health] couldn't judge the alert rules:", err instanceof Error ? err.message : err);
held.add("server:rules");
}
const rows = await db
.select({ id: integrations.id, name: integrations.name, type: integrations.type })
.from(integrations)
@@ -446,6 +467,8 @@ export function alsoList(names: string[]): string {
export async function runHealthCheck(now: number = Date.now()): Promise<{ added: number; resolved: number }> {
const { healthChecks } = await getSettings();
const { snapshot, held } = await collectSnapshot();
// What the pools read this time go into their history (one reading an hour at most), so they can be forecast.
await recordStorageSamples(snapshot, new Date(now));
const inGrace = now - PROCESS_START < STARTUP_GRACE_MS;
if (inGrace) held.add("server");
+2
View File
@@ -25,6 +25,8 @@ export async function listUpcomingWindows(now: Date = new Date()): Promise<Activ
export function subjectOfConditionKey(key: string): string | null {
let m = /^(?:offline|disk|failed-units|smart|zfs|new-port):server:(\d+)(?::|$)/.exec(key);
if (m) return `server:${m[1]}`;
m = /^rule:\d+:server:(\d+)(?::|$)/.exec(key);
if (m) return `server:${m[1]}`;
m = /^(?:endpoint(?:-cert)?|heartbeat(?:-fail)?):\d+:server:(\d+)$/.exec(key);
if (m) return `server:${m[1]}`;
m = /^offline:device:(\d+)$/.exec(key);
+8
View File
@@ -20,6 +20,7 @@ import { lastAttempt as lastSelfBackup, listSnapshots } from "./selfBackup.js";
import { loadAcks, attentionCounts } from "./alertAcks.js";
import { listIncidents } from "./incidents.js";
import { disksFillingSoon, getForecastSeries } from "./serverMetrics.js";
import { storageFillingSoon, storageOverview } from "./storageHistory.js";
import { computeSecretStatus } from "./secretStatus.js";
import { getSettings } from "./settingsStore.js";
import { getUptime } from "./uptimeHistory.js";
@@ -139,6 +140,13 @@ export async function buildMetrics(now: Date = new Date()): Promise<string> {
} catch (err) {
console.error("[metrics] couldn't work out the disk forecasts:", err);
}
try {
for (const f of storageFillingSoon(await storageOverview(now), 3650, 101)) {
out.add("homelab_storage_days_to_full", "gauge", "Days until a Proxmox storage or Synology volume is full at its present rate of filling; only for those with a steady climb.", f.daysToFull, { pool: f.label });
}
} catch (err) {
console.error("[metrics] couldn't work out the storage forecasts:", err);
}
try {
const uptime = await getUptime(now, 30);
for (const s of serverRows) {
+19 -2
View File
@@ -8,6 +8,7 @@ import { inArray } from "drizzle-orm";
import { pushSubscriptions, servers } from "../db/schema.js";
import { parseTags } from "./serverTags.js";
import { dampRaised, dampRecovered } from "./flapGuard.js";
import { withoutSnoozed } from "./alertSnoozes.js";
import { firstMatchingRule, metaOfConditionKey, pushAccepts, type ChannelId, type NotifyMeta } from "./notifyRouting.js";
// ─── Channel senders (best-effort — failures are logged, never thrown) ──────
@@ -484,6 +485,9 @@ export async function notifyHealthIssues(issues: { message: string; key?: string
// The event webhooks hear of it whatever this notification is switched on for: they are a separate way of being told.
for (const i of issues) emitEvent("alert.opened", { alert: { key: i.key ?? null, source: i.source ?? null, severity: i.severity ?? "warning", message: i.message } });
if (issues.length === 0) return;
// One somebody has snoozed is not announced now; if it is still there when the snooze ends, it is announced then (services/alertSnoozes.ts).
issues = await withoutSnoozed(issues);
if (issues.length === 0) return;
// An alert that keeps coming and going is announced once as "flapping" and then left quiet (services/flapGuard.ts); that is tracked whether or not this is switched on.
const { pass, started } = await dampRaised(issues);
if (!(await eventEnabled("healthAlerts"))) return;
@@ -499,6 +503,8 @@ export async function notifyHealthIssues(issues: { message: string; key?: string
export async function notifyHealthRecovered(resolved: { message: string; key?: string; severity?: string }[]): Promise<void> {
for (const r of resolved) emitEvent("alert.resolved", { alert: { key: r.key ?? null, message: r.message } });
if (resolved.length === 0) return;
resolved = await withoutSnoozed(resolved);
if (resolved.length === 0) return;
const passed = await dampRecovered(resolved);
if (!(await eventEnabled("healthAlerts"))) return;
if (passed.length === 0) return;
@@ -509,6 +515,15 @@ export async function notifyHealthRecovered(resolved: { message: string; key?: s
}));
}
/** Alerts that were snoozed, whose time is up and that are still there: said once, as a reminder. */
export async function notifySnoozeEnded(items: { message: string; key?: string; severity?: string }[]): Promise<void> {
if (items.length === 0) return;
await notifyGrouped(items, issueMeta, (group) => ({
title: "Homelab Manager — Snooze ended",
message: `${group.length === 1 ? "An alert you snoozed is" : `${group.length} alerts you snoozed are`} still there:\n\n${group.map((i) => `⏰ ${i.message}`).join("\n")}`,
}));
}
/** An alert that has just been called flapping: said once, with how often it has come, instead of each time. */
export async function notifyFlapping(items: { message: string; key?: string; severity?: string; count: number }[]): Promise<void> {
if (items.length === 0) return;
@@ -531,7 +546,8 @@ export async function notifyAutomationFailed(issues: { message: string; key?: st
// The event webhooks hear of it whatever this notification is switched on for: they are a separate way of being told.
for (const i of issues) emitEvent("alert.opened", { alert: { key: i.key ?? null, source: i.source ?? null, severity: i.severity ?? "warning", message: i.message } });
if (issues.length === 0) return;
if (!(await eventEnabled("automationAlerts"))) return;
issues = await withoutSnoozed(issues);
if (issues.length === 0 || !(await eventEnabled("automationAlerts"))) return;
await notifyGrouped(issues, issueMeta, (group) => ({
title: "Homelab Manager — Automation Failed",
message: `${group.length} run${group.length !== 1 ? "s" : ""} failed:\n\n${group.map((i) => `✕ ${i.message}`).join("\n")}`,
@@ -541,7 +557,8 @@ export async function notifyAutomationFailed(issues: { message: string; key?: st
export async function notifyAutomationRecovered(resolved: { message: string; key?: string; severity?: string }[]): Promise<void> {
for (const r of resolved) emitEvent("alert.resolved", { alert: { key: r.key ?? null, message: r.message } });
if (resolved.length === 0) return;
if (!(await eventEnabled("automationAlerts"))) return;
resolved = await withoutSnoozed(resolved);
if (resolved.length === 0 || !(await eventEnabled("automationAlerts"))) return;
await notifyGrouped(resolved, issueMeta, (group) => ({
title: "Homelab Manager — Automation Recovered",
message: `${group.length} no longer failing:\n\n${group.map((i) => `✓ ${i.message}`).join("\n")}`,
+2 -1
View File
@@ -108,11 +108,12 @@ export function metaOfConditionKey(key: string, severity?: string): NotifyMeta {
if (key.startsWith("offline:")) category = "offline";
else if (key.startsWith("failed-units:")) category = "services";
else if (key.startsWith("new-port:")) category = "monitoring";
else if (key.startsWith("rule:")) category = "monitoring";
else if (/^(disk|smart|zfs|synology-volume|synology-disk):/.test(key)) category = "disk";
else if (key.startsWith("automation:")) category = "automation";
else if (key.startsWith("heartbeat")) category = "automation";
else if (key.startsWith("endpoint-cert:")) category = "expiry";
else if (key.startsWith("endpoint:")) category = "monitoring";
const server = /^(?:(?:offline|disk|failed-units|smart|zfs|new-port):server:|(?:endpoint(?:-cert)?|heartbeat(?:-fail)?):\d+:server:)(\d+)/.exec(key);
const server = /^(?:(?:offline|disk|failed-units|smart|zfs|new-port|rule:\d+):server:|(?:endpoint(?:-cert)?|heartbeat(?:-fail)?):\d+:server:)(\d+)/.exec(key);
return { category, severity: severity === "critical" ? "critical" : "warning", serverId: server ? Number(server[1]) : null };
}
+27
View File
@@ -0,0 +1,27 @@
/**
* Every minute: snoozes that have run out are looked at (see services/alertSnoozes.ts) — an alert that is still there is announced again, once; one that has gone is forgotten.
*/
import { getAlerts, invalidateAlertsCache } from "./alerts.js";
import { keyOfAlertId } from "./flapGuard.js";
import { settleSnoozes } from "./alertSnoozes.js";
import { notifySnoozeEnded } from "./notify.js";
/** One look: returns how many reminders were sent. */
export async function remindAboutSnoozed(now: Date = new Date()): Promise<number> {
const report = await getAlerts(false);
const reminders = await settleSnoozes(report.alerts.map((a) => ({ id: a.id, message: a.message, severity: a.severity, key: keyOfAlertId(a.id, a.category) })), now);
if (reminders.length > 0) {
// The page should show them again at once, not when its stored result expires.
invalidateAlertsCache();
await notifySnoozeEnded(reminders);
}
return reminders.length;
}
let timer: ReturnType<typeof setInterval> | null = null;
export function initSnoozeMonitor(): void {
if (timer) return;
timer = setInterval(() => void remindAboutSnoozed().catch((err) => console.error("[snooze] couldn't look at the snoozed alerts:", err)), 60_000);
timer.unref();
}
+180
View File
@@ -0,0 +1,180 @@
/**
* A history for the pools the integrations report — a Proxmox storage or root filesystem, a Synology volume — so they can be forecast the way an agent server's disk is
* ("this storage is full in 40 days"). The big disks of a homelab are usually these, not the machines the agents run on.
*
* Nothing new is read: on each scheduled health pass the figures it has just read are written down, one reading an hour at most, and kept for 400 days. A pool that stops
* being reported for a month is forgotten. The forecast itself is the same straight-line fit as for a server's disks (services/serverMetrics.ts): enough history, steady
* growth, and not already past the limit the ordinary "disk nearly full" alert uses.
*/
import { and, desc, eq, gte, lt } from "drizzle-orm";
import { db } from "../db/client.js";
import { storageSamples, storageSeries } from "../db/schema.js";
import type { HealthSnapshot } from "./healthMonitor.js";
import { disksFillingSoon, trendOf, type MetricSeries, type Trend } from "./serverMetrics.js";
/** Readings closer together than this add no sample. */
export const MIN_GAP_MS = 55 * 60_000;
export const KEEP_DAYS = 400;
/** A pool not reported for this long is dropped, with its history. */
export const FORGET_AFTER_DAYS = 30;
const DAY_MS = 86_400_000;
export interface PoolReading {
integrationId: number;
key: string;
label: string;
percent: number;
usedBytes: number | null;
totalBytes: number | null;
}
const pct = (used: number | null | undefined, total: number | null | undefined) => (typeof used === "number" && typeof total === "number" && total > 0 ? Math.min(100, Math.max(0, (used / total) * 100)) : null);
/** Pure: the pools in what the health pass has just read. A node or controller that could not be read is not in the snapshot, so it adds nothing. */
export function poolsOf(snapshot: Pick<HealthSnapshot, "proxmox" | "synology">): PoolReading[] {
const out: PoolReading[] = [];
for (const px of snapshot.proxmox) {
const seenShared = new Set<string>();
for (const node of px.nodes) {
if (node.error) continue;
const root = pct(node.rootfsUsedBytes, node.rootfsTotalBytes);
if (root !== null) out.push({ integrationId: px.integrationId, key: `${node.node}:rootfs`, label: `${px.integrationName} / ${node.node}: root filesystem`, percent: root, usedBytes: node.rootfsUsedBytes, totalBytes: node.rootfsTotalBytes });
for (const st of node.storages) {
if (!st.active) continue;
const p = pct(st.usedBytes, st.totalBytes);
if (p === null) continue;
if (st.shared) {
if (seenShared.has(st.id)) continue;
seenShared.add(st.id);
out.push({ integrationId: px.integrationId, key: `shared:${st.id}`, label: `${px.integrationName}: shared storage "${st.id}"`, percent: p, usedBytes: st.usedBytes, totalBytes: st.totalBytes });
} else {
out.push({ integrationId: px.integrationId, key: `${node.node}:storage:${st.id}`, label: `${px.integrationName} / ${node.node}: storage "${st.id}"`, percent: p, usedBytes: st.usedBytes, totalBytes: st.totalBytes });
}
}
}
}
for (const syn of snapshot.synology) {
for (const v of syn.storage.volumes) {
const p = pct(v.sizeUsed, v.sizeTotal);
if (p === null) continue;
out.push({ integrationId: syn.integrationId, key: `volume:${v.id}`, label: `${syn.integrationName}: volume ${v.id}`, percent: p, usedBytes: v.sizeUsed, totalBytes: v.sizeTotal });
}
}
return out;
}
const round1 = (n: number) => Math.round(n * 10) / 10;
/** Writes down what this pass read. Returns how many samples were added. Never throws: the health pass must not fail for want of a history. */
export async function recordStorageSamples(snapshot: Pick<HealthSnapshot, "proxmox" | "synology">, now: Date = new Date()): Promise<number> {
let added = 0;
try {
const nowIso = now.toISOString();
for (const r of poolsOf(snapshot)) {
const values = { label: r.label, latestPercent: round1(r.percent), usedBytes: r.usedBytes === null ? null : Math.round(r.usedBytes), totalBytes: r.totalBytes === null ? null : Math.round(r.totalBytes), updatedAt: nowIso };
const [series] = await db
.insert(storageSeries)
.values({ integrationId: r.integrationId, key: r.key, ...values })
.onConflictDoUpdate({ target: [storageSeries.integrationId, storageSeries.key], set: values })
.returning({ id: storageSeries.id });
const [newest] = await db.select({ at: storageSamples.at }).from(storageSamples).where(eq(storageSamples.seriesId, series.id)).orderBy(desc(storageSamples.at)).limit(1);
if (newest && now.getTime() - Date.parse(newest.at) < MIN_GAP_MS) continue;
await db.insert(storageSamples).values({ seriesId: series.id, at: nowIso, value: round1(r.percent) });
added++;
}
await db.delete(storageSamples).where(lt(storageSamples.at, new Date(now.getTime() - KEEP_DAYS * DAY_MS).toISOString()));
await db.delete(storageSeries).where(lt(storageSeries.updatedAt, new Date(now.getTime() - FORGET_AFTER_DAYS * DAY_MS).toISOString()));
} catch (err) {
console.error("[storage] couldn't write down the storage figures:", err instanceof Error ? err.message : err);
}
return added;
}
export interface StorageTrendInfo {
perDay: number;
daysToFull: number | null;
fit: number;
spanDays: number;
}
export interface StorageForecastRow {
seriesId: number;
integrationId: number;
key: string;
label: string;
latest: number;
usedBytes: number | null;
totalBytes: number | null;
updatedAt: string;
/** The straight-line trend, when there is enough history for one; `steady` says whether it is one to believe. */
trend: StorageTrendInfo | null;
steady: boolean;
}
/** How far back the longer look goes when the last two weeks say a pool is flat. */
export const LONG_DAYS = 90;
const MIN_SPAN_DAYS = 3;
const MIN_FIT = 0.9;
const toInfo = (t: Trend): StorageTrendInfo => ({ perDay: t.perDay, daysToFull: t.daysToFull, fit: t.fit, spanDays: t.spanDays });
/** Every pool with its latest figure and trend: the last two weeks, or — when those are flat — the last ninety days if they are really rising. */
export async function storageOverview(now: Date = new Date()): Promise<StorageForecastRow[]> {
const series = await db.select().from(storageSeries);
const since90 = new Date(now.getTime() - LONG_DAYS * DAY_MS).toISOString();
const rows: StorageForecastRow[] = [];
for (const s of series) {
const samples = (await db.select({ at: storageSamples.at, value: storageSamples.value }).from(storageSamples).where(and(eq(storageSamples.seriesId, s.id), gte(storageSamples.at, since90))).orderBy(storageSamples.at)).map((r) => ({ t: Date.parse(r.at), v: r.value }));
const cut14 = now.getTime() - 14 * DAY_MS;
let trend = trendOf(samples.filter((p) => p.t >= cut14));
if (!trend || trend.daysToFull === null) {
const longer = trendOf(samples);
if (longer && longer.daysToFull !== null) trend = longer;
}
rows.push({
seriesId: s.id,
integrationId: s.integrationId,
key: s.key,
label: s.label,
latest: s.latestPercent,
usedBytes: s.usedBytes,
totalBytes: s.totalBytes,
updatedAt: s.updatedAt,
trend: trend ? toInfo(trend) : null,
steady: !!trend && trend.spanDays >= MIN_SPAN_DAYS && trend.fit >= MIN_FIT,
});
}
return rows.sort((a, b) => a.label.localeCompare(b.label));
}
export interface StorageForecast {
integrationId: number;
key: string;
label: string;
latest: number;
perDay: number;
daysToFull: number;
}
/** The pools heading for full within `withinDays` — the ones already past `limitPercent` are left to the ordinary "nearly full" alert. */
export function storageFillingSoon(rows: StorageForecastRow[], withinDays: number, limitPercent: number): StorageForecast[] {
const asSeries: MetricSeries[] = rows.map((r) => ({
metric: `disk:${r.seriesId}`,
kind: "disk",
label: r.label,
points: [],
latest: r.latest,
trend: r.trend ? { perDay: r.trend.perDay, fit: r.trend.fit, spanDays: r.trend.spanDays, daysToFull: r.trend.daysToFull } : null,
}));
const byId = new Map(rows.map((r) => [String(r.seriesId), r]));
return disksFillingSoon(asSeries, withinDays, limitPercent).map((f) => {
const r = byId.get(f.mount)!;
return { integrationId: r.integrationId, key: r.key, label: r.label, latest: f.latest, perDay: f.perDay, daysToFull: f.daysToFull };
});
}
/** One pool's readings over the last `days`, for a chart. */
export async function storageHistory(seriesId: number, days: number, now: Date = new Date()): Promise<{ t: string; v: number }[]> {
const since = new Date(now.getTime() - Math.min(KEEP_DAYS, Math.max(1, days)) * DAY_MS).toISOString();
return (await db.select({ t: storageSamples.at, v: storageSamples.value }).from(storageSamples).where(and(eq(storageSamples.seriesId, seriesId), gte(storageSamples.at, since))).orderBy(storageSamples.at));
}
+6
View File
@@ -17,6 +17,7 @@ import { notify, notifyNow } from "./notify.js";
import { parsePendingUpdates } from "./pendingUpdates.js";
import { computeSecretStatus } from "./secretStatus.js";
import { disksFillingSoon, getForecastSeries } from "./serverMetrics.js";
import { storageFillingSoon, storageOverview } from "./storageHistory.js";
import { diskLimit, effectiveThresholds, parseThresholds } from "./serverThresholds.js";
import { getSettings } from "./settingsStore.js";
import { getUptime } from "./uptimeHistory.js";
@@ -167,6 +168,11 @@ export async function buildDigest(now: Date = new Date()): Promise<Digest> {
lines.push(`- ${s.name}: ${f.mount} is ${Math.round(f.latest)}% full and filling by about ${f.perDay.toFixed(1)} points a day — full in about ${plural(f.daysToFull, "day")}`);
}
}
if (settings.healthChecks.diskForecastDays > 0) {
for (const f of storageFillingSoon(await storageOverview(now), settings.healthChecks.diskForecastDays, diskUsagePercent)) {
lines.push(`- ${f.label} is ${Math.round(f.latest)}% full and filling by about ${f.perDay.toFixed(1)} points a day — full in about ${plural(f.daysToFull, "day")}`);
}
}
if (lines.length > 0) sections.push({ heading: "Disks heading for full", lines: listWithMore(lines), attention: true });
}
} catch (err) {