Make the Uptime Kuma maintenance import say what it found
The import route returned its errors as {error} while the page reads
{message}, so a wrong API key or an unreachable Uptime Kuma showed as raw
JSON. Every failure now carries a readable message. An empty result now
says how many monitors were read and that only maintenance active right
now can be imported, and a disabled integration is explained instead of
leaving a greyed-out button. Adds route tests against a stand-in Uptime Kuma.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3daec601fd
commit
5e416b0273
4 files changed
+134
-7
No files matched your search
@@ -90,15 +90,16 @@ maintenanceRouter.post("/import/uptimekuma", requireRole("operator"), asyncHandl
|
||||
const { integrationId, minutes } = parsed.data;
|
||||
|
||||
const loaded = await loadIntegrationConfig(integrationId);
|
||||
if (!loaded) return res.status(404).json({ error: "not_found" });
|
||||
if (loaded.integration.type !== "uptimekuma") return res.status(400).json({ error: "wrong_type" });
|
||||
if (!loaded.integration.enabled) return res.status(400).json({ error: "integration_disabled" });
|
||||
if (!loaded) return res.status(404).json({ error: "not_found", message: "That Uptime Kuma integration no longer exists." });
|
||||
if (loaded.integration.type !== "uptimekuma") return res.status(400).json({ error: "wrong_type", message: "That integration isn't an Uptime Kuma one." });
|
||||
if (!loaded.integration.enabled) return res.status(400).json({ error: "integration_disabled", message: "That integration is disabled. Enable it under Integrations first." });
|
||||
|
||||
let monitors;
|
||||
try {
|
||||
monitors = await createUptimeKumaAdapter(loaded.config as any).listMonitors();
|
||||
} catch (err) {
|
||||
return res.status(502).json({ error: err instanceof Error ? err.message : String(err) });
|
||||
const message = err instanceof Error ? err.message : String(err);
|
||||
return res.status(502).json({ error: "uptimekuma_unreachable", message: `Couldn't read Uptime Kuma: ${message}` });
|
||||
}
|
||||
|
||||
const serverRows = await db.select({ id: servers.id, name: servers.name, hostname: servers.hostname, ips: servers.ipAddresses }).from(servers);
|
||||
@@ -134,7 +135,7 @@ maintenanceRouter.post("/import/uptimekuma", requireRole("operator"), asyncHandl
|
||||
imported.push({ serverId: m.matchedServer.id, serverName: result.target.name, monitorName: m.name, extended: result.extended });
|
||||
}
|
||||
|
||||
res.json({ imported, unmatched, monitorsInMaintenance: inMaintenance.length });
|
||||
res.json({ imported, unmatched, monitorsInMaintenance: inMaintenance.length, monitorsChecked: monitors.length });
|
||||
}));
|
||||
|
||||
maintenanceRouter.delete("/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
/**
|
||||
* Importing maintenance windows from Uptime Kuma, end to end through the real route.
|
||||
* A stand-in Uptime Kuma serves /metrics; the database is a scratch one; only the sign-in is stubbed.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtempSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import http from "node:http";
|
||||
import type { AddressInfo } from "node:net";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-kuma-import-"));
|
||||
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||
process.env.SESSION_DIR = join(dir, "sessions");
|
||||
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||
|
||||
const express = (await import("express")).default;
|
||||
const { db } = await import("../src/db/client.js");
|
||||
const { users, servers, integrations, maintenanceWindows } = await import("../src/db/schema.js");
|
||||
const { runMigrations } = await import("../src/db/migrate.js");
|
||||
const { maintenanceRouter } = await import("../src/routes/maintenance.js");
|
||||
|
||||
await runMigrations();
|
||||
|
||||
function metric(id: number, name: string, host: string, status: number) {
|
||||
return `monitor_status{monitor_id="${id}",monitor_name="${name}",monitor_type="ping",monitor_url="",monitor_hostname="${host}",monitor_port=""} ${status}`;
|
||||
}
|
||||
|
||||
describe("import maintenance from Uptime Kuma", () => {
|
||||
let kuma: http.Server;
|
||||
let app: http.Server;
|
||||
let base = "";
|
||||
let metricsBody = "";
|
||||
let kumaStatus = 200;
|
||||
let integrationId = 0;
|
||||
|
||||
before(async () => {
|
||||
kuma = await new Promise<http.Server>((resolve) => {
|
||||
const s = http.createServer((req, res) => {
|
||||
res.statusCode = kumaStatus;
|
||||
res.end(req.url === "/metrics" ? metricsBody : "");
|
||||
});
|
||||
s.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
const kumaUrl = `http://127.0.0.1:${(kuma.address() as AddressInfo).port}`;
|
||||
|
||||
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "admin" });
|
||||
await db.insert(servers).values({ name: "elsa", hostname: "elsa.lab.example", apiTokenHash: "x", apiTokenPrefix: "x" });
|
||||
const [row] = await db
|
||||
.insert(integrations)
|
||||
.values({ type: "uptimekuma", name: "Kuma", baseUrl: kumaUrl, config: JSON.stringify({ url: kumaUrl, password: "key" }) })
|
||||
.returning();
|
||||
integrationId = row.id;
|
||||
|
||||
const a = express();
|
||||
a.use(express.json());
|
||||
a.use((req, _res, next) => {
|
||||
(req as unknown as { session: unknown }).session = { user: { sub: "tester" } };
|
||||
next();
|
||||
});
|
||||
a.use("/api/maintenance", maintenanceRouter);
|
||||
app = await new Promise<http.Server>((resolve) => {
|
||||
const s = a.listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api/maintenance/import/uptimekuma`;
|
||||
});
|
||||
|
||||
after(() => {
|
||||
kuma.close();
|
||||
app.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
async function runImport() {
|
||||
const res = await fetch(base, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ integrationId, minutes: 60 }),
|
||||
});
|
||||
return { status: res.status, body: await res.json() };
|
||||
}
|
||||
|
||||
test("a monitor in maintenance on a known server starts a window there", async () => {
|
||||
kumaStatus = 200;
|
||||
metricsBody = [metric(1, "elsa ping", "elsa.lab.example", 3), metric(2, "other", "10.9.9.9", 3), metric(3, "up one", "elsa.lab.example", 1)].join("\n");
|
||||
const { status, body } = await runImport();
|
||||
assert.equal(status, 200);
|
||||
assert.equal(body.monitorsInMaintenance, 2);
|
||||
assert.deepEqual(body.imported.map((i: { serverName: string }) => i.serverName), ["elsa"]);
|
||||
assert.deepEqual(body.unmatched, ["other"]);
|
||||
assert.equal((await db.select().from(maintenanceWindows)).length, 1);
|
||||
});
|
||||
|
||||
test("nothing in maintenance reports zero", async () => {
|
||||
metricsBody = metric(1, "elsa ping", "elsa.lab.example", 1);
|
||||
const { body } = await runImport();
|
||||
assert.equal(body.monitorsInMaintenance, 0);
|
||||
assert.equal(body.monitorsChecked, 1);
|
||||
});
|
||||
|
||||
test("Uptime Kuma rejecting the credentials comes back with a readable message", async () => {
|
||||
kumaStatus = 401;
|
||||
const { status, body } = await runImport();
|
||||
assert.equal(status, 502);
|
||||
assert.equal(typeof body.message, "string", "the page shows body.message; without it the user sees raw JSON");
|
||||
assert.match(body.message, /rejected the credentials/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user