Match Uptime Kuma monitors to integrations and DNS providers as well as servers

A monitor whose address is the host of an integration's or DNS provider's own
address now gets a maintenance window there, alongside the existing match
against servers. Matching stays exact (no inference through DNS), and monitors
that match nothing are listed with their address in the sync result.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-12 00:13:04 +02:00
1 parent 27a191b54c
commit 3e6404371b
7 files changed
+217 -53

No files matched your search

+64 -36
View File
@@ -2,21 +2,23 @@
* Keeps this app's maintenance windows in step with Uptime Kuma's maintenance schedule.
*
* Kuma says, for each of its windows, which monitors it covers and when it runs (the running slot, if any, and the next one).
* A monitor belongs to a server here when its target matches (the same matching the Uptime Kuma page uses). Each slot on each
* such server becomes an ordinary maintenance window: one that has started silences alerts exactly like one started by hand,
* A monitor belongs to a server here when its target matches (the same matching the Uptime Kuma page uses), and to an
* integration or DNS provider when its target is the address that one was added with (see kumaTargets.ts). Each slot on each
* such thing becomes an ordinary maintenance window: one that has started silences alerts exactly like one started by hand,
* and one that hasn't yet is listed as scheduled and silences nothing until it begins.
*
* Windows made here carry a `source` (`kuma:<integration id>:<maintenance id>`), which is how a later pass finds them again:
* a slot Kuma still reports is left alone (or has its end adjusted), a future one Kuma no longer reports is removed, and one
* that is running but is no longer reported is cut short. A window someone ended by hand stays ended.
*/
import { and, eq, like, lt } from "drizzle-orm";
import { eq, like, lt } from "drizzle-orm";
import { db } from "../db/client.js";
import { maintenanceWindows, servers } from "../db/schema.js";
import { dnsProviders, integrations, maintenanceWindows, servers, type MaintenanceTargetType } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
import type { KumaMaintenance } from "../integrations/uptimekuma/maintenanceFeed.js";
import { attachMatchedServers, toMatchableServers } from "./uptimeKumaMatch.js";
import { toMatchableServers } from "./uptimeKumaMatch.js";
import { hostOfAddress, targetsForHost, type AddressedTarget, type WindowTarget } from "./kumaTargets.js";
/** A slot further ahead than this is left for a later pass — Kuma only reports the next one anyway, so this rarely matters. */
export const LOOKAHEAD_MS = 14 * 24 * 3600_000;
@@ -29,7 +31,8 @@ const KEEP_ENDED_MS = 24 * 3600_000;
export interface DesiredWindow {
source: string;
serverId: number;
targetType: MaintenanceTargetType;
targetId: number;
/** ISO. Null for a window with no fixed start (manual): it continues the one already running, else starts now. */
start: string | null;
end: string;
@@ -39,13 +42,14 @@ export interface DesiredWindow {
export interface ExistingWindow {
id: number;
source: string;
targetType: MaintenanceTargetType;
targetId: number;
startedAt: string;
endsAt: string;
}
export interface WindowPlan {
insert: { source: string; serverId: number; start: string; end: string; reason: string }[];
insert: { source: string; targetType: MaintenanceTargetType; targetId: number; start: string; end: string; reason: string }[];
setEnd: { id: number; endsAt: string }[];
remove: number[];
}
@@ -54,25 +58,25 @@ export interface WindowPlan {
export function planWindowSync(desired: DesiredWindow[], existing: ExistingWindow[], now: Date): WindowPlan {
const nowIso = now.toISOString();
const plan: WindowPlan = { insert: [], setEnd: [], remove: [] };
const keyOf = (source: string, serverId: number, start: string) => `${source}|${serverId}|${start}`;
const byKey = new Map(existing.map((w) => [keyOf(w.source, w.targetId, w.startedAt), w]));
const keyOf = (source: string, targetType: string, targetId: number, start: string) => `${source}|${targetType}:${targetId}|${start}`;
const byKey = new Map(existing.map((w) => [keyOf(w.source, w.targetType, w.targetId, w.startedAt), w]));
const wanted = new Set<string>();
for (const d of desired) {
let start = d.start;
if (start === null) {
// The window already carrying on for this server (recent enough to be the same run) is the one to renew.
// The window already carrying on for this target (recent enough to be the same run) is the one to renew.
const carrying = existing
.filter((w) => w.source === d.source && w.targetId === d.serverId && w.startedAt <= nowIso && w.endsAt > new Date(now.getTime() - 2 * 3600_000).toISOString())
.filter((w) => w.source === d.source && w.targetType === d.targetType && w.targetId === d.targetId && w.startedAt <= nowIso && w.endsAt > new Date(now.getTime() - 2 * 3600_000).toISOString())
.sort((a, b) => b.startedAt.localeCompare(a.startedAt))[0];
start = carrying ? carrying.startedAt : nowIso;
}
const key = keyOf(d.source, d.serverId, start);
const key = keyOf(d.source, d.targetType, d.targetId, start);
wanted.add(key);
const row = byKey.get(key);
if (!row) {
plan.insert.push({ source: d.source, serverId: d.serverId, start, end: d.end, reason: d.reason });
plan.insert.push({ source: d.source, targetType: d.targetType, targetId: d.targetId, start, end: d.end, reason: d.reason });
} else if (row.endsAt <= nowIso || row.endsAt <= row.startedAt) {
// Over already (it ran its course, or someone ended it by hand), or cancelled before it began. Either way it isn't brought back.
} else if (row.endsAt !== d.end) {
@@ -81,7 +85,7 @@ export function planWindowSync(desired: DesiredWindow[], existing: ExistingWindo
}
for (const w of existing) {
const key = keyOf(w.source, w.targetId, w.startedAt);
const key = keyOf(w.source, w.targetType, w.targetId, w.startedAt);
if (wanted.has(key)) continue;
if (w.endsAt < new Date(now.getTime() - KEEP_ENDED_MS).toISOString()) {
plan.remove.push(w.id); // long over: tidy away
@@ -104,9 +108,9 @@ export interface MaintenanceSyncSummary {
/** How many monitors the window covers in Uptime Kuma, and the time slots Kuma reported for it (running and next). */
monitorCount: number;
slots: { start: string; end: string }[];
/** Windows that apply here, by server name. */
servers: string[];
/** Monitors the window covers that match no server. */
/** What the window applies to here: servers, integrations or DNS providers. */
targets: { type: MaintenanceTargetType; name: string }[];
/** Monitors the window covers that match nothing here, as "name (address)". */
unmatched: string[];
/** Why it produced nothing, when it did not. */
note: string | null;
@@ -121,7 +125,7 @@ export function desiredWindows(
integrationId: number,
integrationName: string,
maintenances: KumaMaintenance[],
serverForMonitor: (monitorId: string) => { id: number; name: string } | null,
targetsForMonitor: (monitorId: string) => WindowTarget[],
monitorLabel: (monitorId: string) => string,
now: Date,
): { desired: DesiredWindow[]; summary: MaintenanceSyncSummary["maintenances"] } {
@@ -133,12 +137,12 @@ export function desiredWindows(
const source = `kuma:${integrationId}:${m.id}`;
const reason = `Uptime Kuma (${integrationName}): ${m.title}`.slice(0, 200);
const matched = new Map<number, string>();
const matched = new Map<string, WindowTarget>();
const unmatched: string[] = [];
for (const monitorId of m.monitorIds) {
const server = serverForMonitor(monitorId);
if (server) matched.set(server.id, server.name);
else unmatched.push(monitorLabel(monitorId));
const found = targetsForMonitor(monitorId);
for (const t of found) matched.set(`${t.type}:${t.id}`, t);
if (found.length === 0) unmatched.push(monitorLabel(monitorId));
}
// The slots this window asks for.
@@ -159,11 +163,9 @@ export function desiredWindows(
}
if (slots.length === 0) note = m.timeslots.length === 0 ? "no upcoming time slot" : "nothing within the next two weeks";
}
if (slots.length > 0 && matched.size === 0) note = m.monitorIds.length === 0 ? "covers no monitors" : "no monitor matches a server";
if (matched.size > 0) {
for (const [serverId] of matched) {
for (const slot of slots) desired.push({ source, serverId, start: slot.start, end: slot.end, reason });
}
if (slots.length > 0 && matched.size === 0) note = m.monitorIds.length === 0 ? "covers no monitors" : "no monitor matches a server, integration or DNS provider";
for (const t of matched.values()) {
for (const slot of slots) desired.push({ source, targetType: t.type, targetId: t.id, start: slot.start, end: slot.end, reason });
}
summary.push({
id: m.id,
@@ -172,7 +174,7 @@ export function desiredWindows(
status: m.status,
monitorCount: m.monitorIds.length,
slots: m.timeslots.slice(0, 3),
servers: [...matched.values()].sort(),
targets: [...matched.values()].map((t) => ({ type: t.type, name: t.name })).sort((a, b) => a.name.localeCompare(b.name)),
unmatched,
note,
});
@@ -214,29 +216,55 @@ export async function syncKumaMaintenance(integrationId: number, now: Date = new
}
const serverRows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers);
const matched = attachMatchedServers(monitors, toMatchableServers(serverRows));
const byMonitor = new Map(matched.map((m) => [m.id, m]));
const matchableServers = toMatchableServers(serverRows);
const addressed: AddressedTarget[] = [];
for (const i of await db.select({ id: integrations.id, name: integrations.name, baseUrl: integrations.baseUrl }).from(integrations)) {
const host = hostOfAddress(i.baseUrl);
if (host && i.id !== integrationId) addressed.push({ type: "integration", id: i.id, name: i.name, host });
}
for (const p of await db.select({ id: dnsProviders.id, name: dnsProviders.name, config: dnsProviders.config }).from(dnsProviders)) {
let url: unknown;
try {
url = p.config ? (JSON.parse(p.config) as Record<string, unknown>).url : undefined;
} catch {
url = undefined;
}
const host = typeof url === "string" ? hostOfAddress(url) : null;
if (host) addressed.push({ type: "dns_provider", id: p.id, name: p.name, host });
}
const byMonitor = new Map(monitors.map((m) => [m.id, m]));
const { desired, summary } = desiredWindows(
integrationId,
loaded.integration.name,
maintenances,
(id) => byMonitor.get(id)?.matchedServer ?? null,
(id) => byMonitor.get(id)?.name ?? `monitor #${id}`,
(id) => targetsForHost(byMonitor.get(id)?.target ?? null, matchableServers, addressed),
(id) => {
const m = byMonitor.get(id);
if (!m) return `monitor #${id}`;
return m.target ? `${m.name} (${m.target}${m.port ? `:${m.port}` : ""})` : `${m.name} (no address)`;
},
now,
);
const prefix = `kuma:${integrationId}:`;
const existing = await db
.select({ id: maintenanceWindows.id, source: maintenanceWindows.source, targetId: maintenanceWindows.targetId, startedAt: maintenanceWindows.startedAt, endsAt: maintenanceWindows.endsAt })
.select({
id: maintenanceWindows.id,
source: maintenanceWindows.source,
targetType: maintenanceWindows.targetType,
targetId: maintenanceWindows.targetId,
startedAt: maintenanceWindows.startedAt,
endsAt: maintenanceWindows.endsAt,
})
.from(maintenanceWindows)
.where(and(eq(maintenanceWindows.targetType, "server"), like(maintenanceWindows.source, `${prefix}%`)));
.where(like(maintenanceWindows.source, `${prefix}%`));
const plan = planWindowSync(desired, existing as ExistingWindow[], now);
for (const row of plan.insert) {
await db.insert(maintenanceWindows).values({
targetType: "server",
targetId: row.serverId,
targetType: row.targetType,
targetId: row.targetId,
reason: row.reason,
startedAt: row.start,
endsAt: row.end,
+64
View File
@@ -0,0 +1,64 @@
/**
* Which things in this app an Uptime Kuma monitor is about — a server, an integration (a Proxmox host, a NAS…) or a DNS provider.
*
* A server matches the way the Uptime Kuma page already matches it: the monitor's host is one of the server's IP addresses, its
* hostname, or its short name. An integration or DNS provider matches when the monitor's host is the host in its own address
* (the URL entered when it was added) — as the same name or the same IP, exactly. Nothing is inferred through DNS: a website that
* merely resolves to the same address as a proxy is not "the proxy", and guessing here would silence alerts that should fire.
*/
import * as net from "node:net";
import type { MaintenanceTargetType } from "../db/schema.js";
import { matchServerForTarget, type MatchableServer } from "./uptimeKumaMatch.js";
export interface WindowTarget {
type: MaintenanceTargetType;
id: number;
name: string;
}
export interface AddressedTarget extends WindowTarget {
/** The host from the address it was added with, e.g. "pve.example.lan" or "10.0.0.5". */
host: string;
}
const clean = (s: string) => s.trim().toLowerCase().replace(/\.$/, "");
/** The host part of an address as typed ("https://pve.example.lan:8006/", "10.0.0.5:8006", "pve.example.lan"), or null. */
export function hostOfAddress(address: string | null | undefined): string | null {
if (!address || !address.trim()) return null;
const text = address.trim();
try {
const url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(text) ? text : `http://${text}`);
const host = url.hostname.replace(/^\[|\]$/g, "");
return host ? clean(host) : null;
} catch {
return null;
}
}
/** Everything in the app that `host` (a monitor's target) is the address of. */
export function targetsForHost(host: string | null, servers: MatchableServer[], addressed: AddressedTarget[]): WindowTarget[] {
if (!host || !host.trim()) return [];
const found: WindowTarget[] = [];
const server = matchServerForTarget(host, servers);
if (server) found.push({ type: "server", id: server.id, name: server.name });
const wanted = clean(host);
for (const t of addressed) {
// An IP is compared as an IP, so "::1" and "0:0:0:0:0:0:0:1" are the same thing; a name is compared as a name.
const same = net.isIP(wanted) !== 0 && net.isIP(t.host) !== 0 ? sameIp(wanted, t.host) : t.host === wanted;
if (same) found.push({ type: t.type, id: t.id, name: t.name });
}
return found;
}
function sameIp(a: string, b: string): boolean {
if (a === b) return true;
if (net.isIPv6(a) && net.isIPv6(b)) {
const list = new net.BlockList();
list.addAddress(a, "ipv6");
return list.check(b, "ipv6");
}
return false;
}