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

+11 -3
View File
@@ -86,9 +86,17 @@ the dashboard views themselves load fine.
but this. The login is sent as Uptime Kuma's own `login` event over `ws://` or `wss://` to the same address but this. The login is sent as Uptime Kuma's own `login` event over `ws://` or `wss://` to the same address
as the integration, so use an `https://` address if it crosses anything but a trusted network. as the integration, so use an `https://` address if it crosses anything but a trusted network.
- For each window Uptime Kuma reports (its running time slot and the next one), the app finds the - For each window Uptime Kuma reports (its running time slot and the next one), the app finds the
monitors it covers, matches their targets to servers the same way the Uptime Kuma page does, and makes a monitors it covers and matches each monitor's address to something here: a **server** (the monitor's host
maintenance window on each matched server. A window that hasn't started shows as *Scheduled* and silences is one of its IP addresses, its hostname or its short name — the same matching the Uptime Kuma page
nothing yet. uses), an **integration** or a **DNS provider** (the monitor's host is the host of the address it was
added with, as the same name or the same IP). It then makes a maintenance window on each match. A window
that hasn't started shows as *Scheduled* and silences nothing yet.
- Matching is exact. Nothing is worked out through DNS, so a website that only resolves to the same address
as a reverse proxy does not put the proxy into maintenance. A monitor that matches nothing is listed in the
result as `name (address)` so you can see why. The usual fix is to make the address agree: a Proxmox
integration added by IP will not match a monitor that watches its hostname, and vice versa.
- A window on an integration silences that integration's alerts, including "integration down" for that
type of service — see the Maintenance page for the full list.
- Tick *Keep maintenance windows in step with Uptime Kuma's schedule* to run this automatically every - Tick *Keep maintenance windows in step with Uptime Kuma's schedule* to run this automatically every
15 minutes. Without it, the *Sync schedule* button does the same once. 15 minutes. Without it, the *Sync schedule* button does the same once.
- Windows are capped at 31 days, and only slots starting within two weeks are mirrored. A window Uptime - Windows are capped at 31 days, and only slots starting within two weeks are mirrored. A window Uptime
+3 -2
View File
@@ -327,8 +327,9 @@ a problem that began during a window and is still present when it ends alerts
then — a forgotten window can't hide an outage. A banner shows what's currently then — a forgotten window can't hide an outage. A banner shows what's currently
silenced to every signed-in user. If you also run Uptime Kuma, the Maintenance silenced to every signed-in user. If you also run Uptime Kuma, the Maintenance
page can take its maintenance windows over: "Sync schedule" reads each window page can take its maintenance windows over: "Sync schedule" reads each window
(daily, weekly, one-off, cron or switched on by hand), finds the servers its (daily, weekly, one-off, cron or switched on by hand), finds the servers,
monitors belong to, and makes a window here for the one running now and the next integrations and DNS providers its monitors are the address of, and makes a
window here for each, for the slot running now and the next
one — listed under Scheduled until it starts, then silencing alerts like any one — listed under Scheduled until it starts, then silencing alerts like any
other. Tick "Keep maintenance windows in step" on the Uptime Kuma integration other. Tick "Keep maintenance windows in step" on the Uptime Kuma integration
and this happens by itself every 15 minutes, so a daily window needs no and this happens by itself every 15 minutes, so a daily window needs no
+64 -36
View File
@@ -2,21 +2,23 @@
* Keeps this app's maintenance windows in step with Uptime Kuma's maintenance schedule. * 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). * 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 * A monitor belongs to a server here when its target matches (the same matching the Uptime Kuma page uses), and to an
* such server becomes an ordinary maintenance window: one that has started silences alerts exactly like one started by hand, * 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. * 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: * 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 * 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. * 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 { 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 { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js"; import { createUptimeKumaAdapter } from "../integrations/uptimekuma/adapter.js";
import type { KumaMaintenance } from "../integrations/uptimekuma/maintenanceFeed.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. */ /** 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; export const LOOKAHEAD_MS = 14 * 24 * 3600_000;
@@ -29,7 +31,8 @@ const KEEP_ENDED_MS = 24 * 3600_000;
export interface DesiredWindow { export interface DesiredWindow {
source: string; 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. */ /** ISO. Null for a window with no fixed start (manual): it continues the one already running, else starts now. */
start: string | null; start: string | null;
end: string; end: string;
@@ -39,13 +42,14 @@ export interface DesiredWindow {
export interface ExistingWindow { export interface ExistingWindow {
id: number; id: number;
source: string; source: string;
targetType: MaintenanceTargetType;
targetId: number; targetId: number;
startedAt: string; startedAt: string;
endsAt: string; endsAt: string;
} }
export interface WindowPlan { 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 }[]; setEnd: { id: number; endsAt: string }[];
remove: number[]; remove: number[];
} }
@@ -54,25 +58,25 @@ export interface WindowPlan {
export function planWindowSync(desired: DesiredWindow[], existing: ExistingWindow[], now: Date): WindowPlan { export function planWindowSync(desired: DesiredWindow[], existing: ExistingWindow[], now: Date): WindowPlan {
const nowIso = now.toISOString(); const nowIso = now.toISOString();
const plan: WindowPlan = { insert: [], setEnd: [], remove: [] }; const plan: WindowPlan = { insert: [], setEnd: [], remove: [] };
const keyOf = (source: string, serverId: number, start: string) => `${source}|${serverId}|${start}`; 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.targetId, w.startedAt), w])); const byKey = new Map(existing.map((w) => [keyOf(w.source, w.targetType, w.targetId, w.startedAt), w]));
const wanted = new Set<string>(); const wanted = new Set<string>();
for (const d of desired) { for (const d of desired) {
let start = d.start; let start = d.start;
if (start === null) { 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 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]; .sort((a, b) => b.startedAt.localeCompare(a.startedAt))[0];
start = carrying ? carrying.startedAt : nowIso; 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); wanted.add(key);
const row = byKey.get(key); const row = byKey.get(key);
if (!row) { 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) { } 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. // 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) { } else if (row.endsAt !== d.end) {
@@ -81,7 +85,7 @@ export function planWindowSync(desired: DesiredWindow[], existing: ExistingWindo
} }
for (const w of existing) { 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 (wanted.has(key)) continue;
if (w.endsAt < new Date(now.getTime() - KEEP_ENDED_MS).toISOString()) { if (w.endsAt < new Date(now.getTime() - KEEP_ENDED_MS).toISOString()) {
plan.remove.push(w.id); // long over: tidy away 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). */ /** How many monitors the window covers in Uptime Kuma, and the time slots Kuma reported for it (running and next). */
monitorCount: number; monitorCount: number;
slots: { start: string; end: string }[]; slots: { start: string; end: string }[];
/** Windows that apply here, by server name. */ /** What the window applies to here: servers, integrations or DNS providers. */
servers: string[]; targets: { type: MaintenanceTargetType; name: string }[];
/** Monitors the window covers that match no server. */ /** Monitors the window covers that match nothing here, as "name (address)". */
unmatched: string[]; unmatched: string[];
/** Why it produced nothing, when it did not. */ /** Why it produced nothing, when it did not. */
note: string | null; note: string | null;
@@ -121,7 +125,7 @@ export function desiredWindows(
integrationId: number, integrationId: number,
integrationName: string, integrationName: string,
maintenances: KumaMaintenance[], maintenances: KumaMaintenance[],
serverForMonitor: (monitorId: string) => { id: number; name: string } | null, targetsForMonitor: (monitorId: string) => WindowTarget[],
monitorLabel: (monitorId: string) => string, monitorLabel: (monitorId: string) => string,
now: Date, now: Date,
): { desired: DesiredWindow[]; summary: MaintenanceSyncSummary["maintenances"] } { ): { desired: DesiredWindow[]; summary: MaintenanceSyncSummary["maintenances"] } {
@@ -133,12 +137,12 @@ export function desiredWindows(
const source = `kuma:${integrationId}:${m.id}`; const source = `kuma:${integrationId}:${m.id}`;
const reason = `Uptime Kuma (${integrationName}): ${m.title}`.slice(0, 200); 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[] = []; const unmatched: string[] = [];
for (const monitorId of m.monitorIds) { for (const monitorId of m.monitorIds) {
const server = serverForMonitor(monitorId); const found = targetsForMonitor(monitorId);
if (server) matched.set(server.id, server.name); for (const t of found) matched.set(`${t.type}:${t.id}`, t);
else unmatched.push(monitorLabel(monitorId)); if (found.length === 0) unmatched.push(monitorLabel(monitorId));
} }
// The slots this window asks for. // 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) 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 (slots.length > 0 && matched.size === 0) note = m.monitorIds.length === 0 ? "covers no monitors" : "no monitor matches a server, integration or DNS provider";
if (matched.size > 0) { for (const t of matched.values()) {
for (const [serverId] of matched) { for (const slot of slots) desired.push({ source, targetType: t.type, targetId: t.id, start: slot.start, end: slot.end, reason });
for (const slot of slots) desired.push({ source, serverId, start: slot.start, end: slot.end, reason });
}
} }
summary.push({ summary.push({
id: m.id, id: m.id,
@@ -172,7 +174,7 @@ export function desiredWindows(
status: m.status, status: m.status,
monitorCount: m.monitorIds.length, monitorCount: m.monitorIds.length,
slots: m.timeslots.slice(0, 3), 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, unmatched,
note, 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 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 matchableServers = toMatchableServers(serverRows);
const byMonitor = new Map(matched.map((m) => [m.id, m])); 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( const { desired, summary } = desiredWindows(
integrationId, integrationId,
loaded.integration.name, loaded.integration.name,
maintenances, maintenances,
(id) => byMonitor.get(id)?.matchedServer ?? null, (id) => targetsForHost(byMonitor.get(id)?.target ?? null, matchableServers, addressed),
(id) => byMonitor.get(id)?.name ?? `monitor #${id}`, (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, now,
); );
const prefix = `kuma:${integrationId}:`; const prefix = `kuma:${integrationId}:`;
const existing = await db 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) .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); const plan = planWindowSync(desired, existing as ExistingWindow[], now);
for (const row of plan.insert) { for (const row of plan.insert) {
await db.insert(maintenanceWindows).values({ await db.insert(maintenanceWindows).values({
targetType: "server", targetType: row.targetType,
targetId: row.serverId, targetId: row.targetId,
reason: row.reason, reason: row.reason,
startedAt: row.start, startedAt: row.start,
endsAt: row.end, 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;
}
+72 -9
View File
@@ -23,11 +23,12 @@ process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
const express = (await import("express")).default; const express = (await import("express")).default;
const { Server: IOServer } = await import("socket.io"); const { Server: IOServer } = await import("socket.io");
const { db } = await import("../src/db/client.js"); const { db } = await import("../src/db/client.js");
const { users, servers, integrations, maintenanceWindows } = await import("../src/db/schema.js"); const { users, servers, integrations, dnsProviders, maintenanceWindows } = await import("../src/db/schema.js");
const { runMigrations } = await import("../src/db/migrate.js"); const { runMigrations } = await import("../src/db/migrate.js");
const { maintenanceRouter } = await import("../src/routes/maintenance.js"); const { maintenanceRouter } = await import("../src/routes/maintenance.js");
const { kumaInstant, normalizeMaintenanceList, monitorIdsFromReply } = await import("../src/integrations/uptimekuma/maintenanceFeed.js"); const { kumaInstant, normalizeMaintenanceList, monitorIdsFromReply } = await import("../src/integrations/uptimekuma/maintenanceFeed.js");
const { planWindowSync, desiredWindows, MANUAL_WINDOW_MS } = await import("../src/services/kumaMaintenanceSync.js"); const { planWindowSync, desiredWindows, MANUAL_WINDOW_MS } = await import("../src/services/kumaMaintenanceSync.js");
const { hostOfAddress, targetsForHost } = await import("../src/services/kumaTargets.js");
const { listActiveWindows, listUpcomingWindows } = await import("../src/services/maintenance.js"); const { listActiveWindows, listUpcomingWindows } = await import("../src/services/maintenance.js");
await runMigrations(); await runMigrations();
@@ -77,11 +78,47 @@ describe("reading Kuma's lists", () => {
}); });
}); });
describe("which things a monitor's address belongs to", () => {
const serverList = [{ id: 1, name: "elsa", hostname: "elsa.lab.example", ips: ["10.0.0.5", "fd00::5"] }];
const addressed = [
{ type: "integration" as const, id: 2, name: "Proxmox", host: "pve.lab.example" },
{ type: "integration" as const, id: 3, name: "NAS", host: "10.0.0.20" },
{ type: "dns_provider" as const, id: 4, name: "Technitium", host: "fd00:0:0:0:0:0:0:53" },
];
const names = (host: string | null) => targetsForHost(host, serverList, addressed).map((t) => `${t.type}:${t.name}`);
test("the address a monitor watches is matched to a server, an integration or a DNS provider", () => {
assert.deepEqual(names("10.0.0.5"), ["server:elsa"]);
assert.deepEqual(names("pve.lab.example"), ["integration:Proxmox"]);
assert.deepEqual(names("PVE.lab.example."), ["integration:Proxmox"]);
assert.deepEqual(names("10.0.0.20"), ["integration:NAS"]);
});
test("an IPv6 address matches however it is written", () => {
assert.deepEqual(names("fd00::53"), ["dns_provider:Technitium"]);
});
test("nothing is inferred: a name that is merely near, or no address, matches nothing", () => {
assert.deepEqual(names("www.lab.example"), []);
assert.deepEqual(names("10.0.0.21"), []);
assert.deepEqual(names(null), []);
assert.deepEqual(names(""), []);
});
test("the host is read out of an address as typed", () => {
assert.equal(hostOfAddress("https://PVE.lab.example:8006/"), "pve.lab.example");
assert.equal(hostOfAddress("10.0.0.5:8006"), "10.0.0.5");
assert.equal(hostOfAddress("http://[fd00::1]:5380"), "fd00::1");
assert.equal(hostOfAddress(""), null);
assert.equal(hostOfAddress(null), null);
});
});
describe("planWindowSync", () => { describe("planWindowSync", () => {
const now = new Date("2026-10-10T12:00:00.000Z"); const now = new Date("2026-10-10T12:00:00.000Z");
const S = "kuma:1:5"; const S = "kuma:1:5";
const want = (start: string | null, end: string, serverId = 7) => ({ source: S, serverId, start, end, reason: "r" }); const want = (start: string | null, end: string, targetId = 7) => ({ source: S, targetType: "server" as const, targetId, start, end, reason: "r" });
const row = (id: number, startedAt: string, endsAt: string, targetId = 7) => ({ id, source: S, targetId, startedAt, endsAt }); const row = (id: number, startedAt: string, endsAt: string, targetId = 7) => ({ id, source: S, targetType: "server" as const, targetId, startedAt, endsAt });
test("a slot Kuma reports that isn't here yet is added", () => { test("a slot Kuma reports that isn't here yet is added", () => {
const plan = planWindowSync([want("2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], [], now); const plan = planWindowSync([want("2026-10-11T00:00:00.000Z", "2026-10-11T01:00:00.000Z")], [], now);
@@ -142,7 +179,8 @@ describe("planWindowSync", () => {
describe("desiredWindows", () => { describe("desiredWindows", () => {
const now = new Date("2026-10-10T12:00:00.000Z"); const now = new Date("2026-10-10T12:00:00.000Z");
const server = (id: string) => (id === "1" ? { id: 10, name: "elsa" } : id === "2" ? { id: 20, name: "anna" } : null); const server = (id: string) =>
id === "1" ? [{ type: "server" as const, id: 10, name: "elsa" }] : id === "2" ? [{ type: "server" as const, id: 20, name: "anna" }] : [];
const label = (id: string) => `monitor ${id}`; const label = (id: string) => `monitor ${id}`;
const base = { id: 5, title: "Nightly", strategy: "recurring-interval", active: true, status: "scheduled", timezone: "UTC", timeslots: [] as { start: string; end: string }[], monitorIds: ["1", "2", "3"] }; const base = { id: 5, title: "Nightly", strategy: "recurring-interval", active: true, status: "scheduled", timezone: "UTC", timeslots: [] as { start: string; end: string }[], monitorIds: ["1", "2", "3"] };
const run = (m: Partial<typeof base>) => desiredWindows(1, "Kuma", [{ ...base, ...m }], server, label, now); const run = (m: Partial<typeof base>) => desiredWindows(1, "Kuma", [{ ...base, ...m }], server, label, now);
@@ -150,8 +188,8 @@ describe("desiredWindows", () => {
test("each slot on each matching server; monitors that match no server are reported", () => { test("each slot on each matching server; monitors that match no server are reported", () => {
const { desired, summary } = run({ timeslots: [{ start: iso(now.getTime() + 2 * HOUR), end: iso(now.getTime() + 3 * HOUR) }] }); const { desired, summary } = run({ timeslots: [{ start: iso(now.getTime() + 2 * HOUR), end: iso(now.getTime() + 3 * HOUR) }] });
assert.equal(desired.length, 2); assert.equal(desired.length, 2);
assert.deepEqual(desired.map((d) => d.serverId).sort(), [10, 20]); assert.deepEqual(desired.map((d) => d.targetId).sort(), [10, 20]);
assert.deepEqual(summary[0].servers, ["anna", "elsa"]); assert.deepEqual(summary[0].targets.map((t) => t.name), ["anna", "elsa"]);
assert.deepEqual(summary[0].unmatched, ["monitor 3"]); assert.deepEqual(summary[0].unmatched, ["monitor 3"]);
assert.equal(summary[0].note, null); assert.equal(summary[0].note, null);
}); });
@@ -211,7 +249,7 @@ describe("syncing from a stand-in Uptime Kuma", () => {
before(async () => { before(async () => {
httpServer = http.createServer((req, res) => { httpServer = http.createServer((req, res) => {
if (req.url === "/metrics") { if (req.url === "/metrics") {
res.end([metric(1, "elsa.lab.example"), metric(2, "anna.lab.example"), metric(3, "10.9.9.9")].join("\n")); res.end([metric(1, "elsa.lab.example"), metric(2, "anna.lab.example"), metric(3, "10.9.9.9"), metric(4, "pve.lab.example"), metric(5, "10.0.0.53")].join("\n"));
} else { } else {
res.statusCode = 404; res.statusCode = 404;
res.end(); res.end();
@@ -248,6 +286,10 @@ describe("syncing from a stand-in Uptime Kuma", () => {
.returning() .returning()
)[0].id; )[0].id;
// Things that are not servers: a Proxmox integration reached by name, and a DNS provider reached by IP.
await db.insert(integrations).values({ type: "proxmox", name: "Proxmox Felicia", baseUrl: "https://pve.lab.example:8006", config: "{}" });
await db.insert(dnsProviders).values({ providerType: "technitium", name: "Technitium Ginny", config: JSON.stringify({ url: "http://10.0.0.53:5380" }) });
const a = express(); const a = express();
a.use(express.json()); a.use(express.json());
a.use((req, _res, next) => { a.use((req, _res, next) => {
@@ -298,8 +340,8 @@ describe("syncing from a stand-in Uptime Kuma", () => {
const { status, body } = await sync(); const { status, body } = await sync();
assert.equal(status, 200); assert.equal(status, 200);
assert.equal(body.started, 2); assert.equal(body.started, 2);
assert.deepEqual(body.maintenances[0].servers, ["anna", "elsa"]); assert.deepEqual(body.maintenances[0].targets.map((t: { name: string }) => t.name), ["anna", "elsa"]);
assert.deepEqual(body.maintenances[0].unmatched, ["m3"]); assert.deepEqual(body.maintenances[0].unmatched, ["m3 (10.9.9.9)"]);
assert.equal((await listActiveWindows()).length, 0, "it hasn't begun, so it silences nothing yet"); assert.equal((await listActiveWindows()).length, 0, "it hasn't begun, so it silences nothing yet");
const upcoming = await listUpcomingWindows(); const upcoming = await listUpcomingWindows();
@@ -308,6 +350,27 @@ describe("syncing from a stand-in Uptime Kuma", () => {
assert.match(upcoming[0].reason ?? "", /Nightly patching/); assert.match(upcoming[0].reason ?? "", /Nightly patching/);
}); });
test("monitors on an integration's or a DNS provider's own address get windows there too", async () => {
await db.delete(maintenanceWindows);
const start = Date.now() + 4 * HOUR;
kuma.list = { "6": daily(start, start + HOUR, { id: 6, title: "Sunday" }) };
kuma.monitorsOf = { "6": [4, 5] };
const { body } = await sync();
assert.equal(body.started, 2);
assert.deepEqual(
body.maintenances[0].targets.map((t: { type: string; name: string }) => `${t.type}:${t.name}`).sort(),
["dns_provider:Technitium Ginny", "integration:Proxmox Felicia"],
);
const types = (await listUpcomingWindows()).map((w) => w.targetType).sort();
assert.deepEqual(types, ["dns_provider", "integration"]);
// Back to the first scenario, for the tests that follow.
kuma.list = { "5": daily(start, start + HOUR) };
kuma.monitorsOf = { "5": [1, 2, 3] };
await db.delete(maintenanceWindows);
await sync();
});
test("syncing again adds nothing", async () => { test("syncing again adds nothing", async () => {
const { body } = await sync(); const { body } = await sync();
assert.deepEqual([body.started, body.updated, body.removed], [0, 0, 0]); assert.deepEqual([body.started, body.updated, body.removed], [0, 0, 0]);
+1 -1
View File
@@ -783,7 +783,7 @@ export interface UptimeKumaSyncResult {
status: string; status: string;
monitorCount: number; monitorCount: number;
slots: { start: string; end: string }[]; slots: { start: string; end: string }[];
servers: string[]; targets: { type: MaintenanceTargetType; name: string }[];
unmatched: string[]; unmatched: string[];
/** Why it produced no window, when it did not. */ /** Why it produced no window, when it did not. */
note: string | null; note: string | null;
+2 -2
View File
@@ -296,8 +296,8 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
<span className="text-secondary"> <span className="text-secondary">
({m.strategy}, {m.status}) ({m.strategy}, {m.status})
</span> </span>
{m.servers.length > 0 ? ` → ${m.servers.join(", ")}` : m.note ? ` — nothing to schedule: ${m.note}` : ""} {m.targets.length > 0 ? ` → ${m.targets.map((t) => `${t.name} (${t.type === "dns_provider" ? "DNS provider" : t.type})`).join(", ")}` : m.note ? ` — nothing to schedule: ${m.note}` : ""}
{m.unmatched.length > 0 && <span className="text-secondary"> · no server for {m.unmatched.join(", ")}</span>} {m.unmatched.length > 0 && <span className="text-secondary"> · nothing here for {m.unmatched.join(", ")}</span>}
<div className="text-secondary small"> <div className="text-secondary small">
Covers {m.monitorCount} monitor{m.monitorCount === 1 ? "" : "s"} in Uptime Kuma ·{" "} Covers {m.monitorCount} monitor{m.monitorCount === 1 ? "" : "s"} in Uptime Kuma ·{" "}
{m.slots.length === 0 {m.slots.length === 0