feat: system/http/traefik collectors and docker auto-discovery (M3)
Adds the remaining monitor types: a systeminformation-backed system widget (single-flight cached so multiple widgets don't force concurrent samples), an http widget with per-widget consecutive- failure tracking, and a traefik widget that reads router/entrypoint/ middleware status from Traefik's own API. Also adds opt-in label-based docker auto-discovery (discovery.docker in config.yml): containers carrying traefik.enable=true are turned into docker widgets in a synthetic "Discovered" group, re-scanned on a timer and whenever config.yml changes, with manual widgets always taking precedence over a discovered one for the same container. Fixes a real bug surfaced while testing discovery: Next's App Router bundles app/** through its own compiler pass, separate from server.ts (run directly via tsx), so configStore/effectiveConfigStore were silently instantiated twice - one instance watched and updated by server.ts, another frozen instance read by SSR. Live config edits were never reflected on page load without a full process restart. Both stores now key their singleton off globalThis, which both module graphs share within the same process. Verified against a real Traefik v3 container (API-driven router list, ping-based http check) and a labeled nginx container (auto-discovery), including that a config.yml edit now shows up in a fresh page load without restarting the server, in both dev and the production build.
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
import type { HttpCheckResult } from "@/lib/types/http-result";
|
||||
|
||||
export async function collectHttp(
|
||||
url: string,
|
||||
method: string,
|
||||
timeoutMs: number,
|
||||
expectedStatus: number
|
||||
): Promise<Omit<HttpCheckResult, "consecutiveFailures">> {
|
||||
const start = performance.now();
|
||||
try {
|
||||
const response = await fetch(url, { method, signal: AbortSignal.timeout(timeoutMs), redirect: "follow" });
|
||||
const latencyMs = Math.round(performance.now() - start);
|
||||
return { up: response.status === expectedStatus, statusCode: response.status, latencyMs, error: null };
|
||||
} catch (err) {
|
||||
const latencyMs = Math.round(performance.now() - start);
|
||||
return { up: false, statusCode: null, latencyMs, error: (err as Error).message };
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,13 @@ import type { Config, Widget } from "@/lib/config/schema";
|
||||
import { flattenWidgets } from "@/lib/config/widgets";
|
||||
import { parseDuration } from "@/lib/config/duration";
|
||||
import { collectDockerContainer } from "./docker";
|
||||
import { collectSystem } from "./system";
|
||||
import { collectHttp } from "./http";
|
||||
import { collectTraefik } from "./traefik";
|
||||
import type { WidgetResult } from "@/lib/types/widget-result";
|
||||
|
||||
const dockerLimit = pLimit(4);
|
||||
const httpLimit = pLimit(8);
|
||||
|
||||
type ResultListener = (widgetId: string, result: WidgetResult) => void;
|
||||
|
||||
@@ -13,14 +17,23 @@ interface Job {
|
||||
widget: Widget;
|
||||
intervalMs: number;
|
||||
timer: ReturnType<typeof setInterval>;
|
||||
consecutiveFailures: number;
|
||||
}
|
||||
|
||||
const COLLECTOR_TYPES = new Set<Widget["type"]>(["docker", "database", "system", "http", "traefik"]);
|
||||
|
||||
function isCollectorWidget(widget: Widget): boolean {
|
||||
return widget.type === "docker" || widget.type === "database";
|
||||
return COLLECTOR_TYPES.has(widget.type);
|
||||
}
|
||||
|
||||
function getIntervalMs(widget: Widget): number {
|
||||
if (widget.type === "docker" || widget.type === "database") {
|
||||
if (
|
||||
widget.type === "docker" ||
|
||||
widget.type === "database" ||
|
||||
widget.type === "system" ||
|
||||
widget.type === "http" ||
|
||||
widget.type === "traefik"
|
||||
) {
|
||||
return parseDuration(widget.interval);
|
||||
}
|
||||
return 30_000;
|
||||
@@ -33,6 +46,15 @@ function sameTarget(a: Widget, b: Widget): boolean {
|
||||
if (a.type === "database" && b.type === "database") {
|
||||
return a.containerName === b.containerName;
|
||||
}
|
||||
if (a.type === "system" && b.type === "system") {
|
||||
return true;
|
||||
}
|
||||
if (a.type === "http" && b.type === "http") {
|
||||
return a.url === b.url && a.method === b.method && a.expect.status === b.expect.status;
|
||||
}
|
||||
if (a.type === "traefik" && b.type === "traefik") {
|
||||
return a.apiUrl === b.apiUrl;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -45,6 +67,20 @@ async function collect(widget: Widget): Promise<WidgetResult> {
|
||||
const data = await dockerLimit(() => collectDockerContainer(widget.containerName, true));
|
||||
return { type: "database", data };
|
||||
}
|
||||
if (widget.type === "system") {
|
||||
const data = await collectSystem();
|
||||
return { type: "system", data };
|
||||
}
|
||||
if (widget.type === "http") {
|
||||
const data = await httpLimit(() =>
|
||||
collectHttp(widget.url, widget.method, parseDuration(widget.timeout), widget.expect.status)
|
||||
);
|
||||
return { type: "http", data: { ...data, consecutiveFailures: 0 } };
|
||||
}
|
||||
if (widget.type === "traefik") {
|
||||
const data = await collectTraefik(widget.apiUrl);
|
||||
return { type: "traefik", data };
|
||||
}
|
||||
throw new Error(`No collector for widget type "${widget.type}"`);
|
||||
}
|
||||
|
||||
@@ -87,9 +123,9 @@ class CollectorScheduler {
|
||||
|
||||
if (existing) clearInterval(existing.timer);
|
||||
|
||||
const run = () => this.runJob(instance.id, instance.widget);
|
||||
const run = () => this.runJob(instance.id);
|
||||
const timer = setInterval(run, intervalMs);
|
||||
this.jobs.set(instance.id, { widget: instance.widget, intervalMs, timer });
|
||||
this.jobs.set(instance.id, { widget: instance.widget, intervalMs, timer, consecutiveFailures: 0 });
|
||||
run();
|
||||
}
|
||||
|
||||
@@ -107,13 +143,22 @@ class CollectorScheduler {
|
||||
this.jobs.clear();
|
||||
}
|
||||
|
||||
private async runJob(id: string, widget: Widget): Promise<void> {
|
||||
private async runJob(id: string): Promise<void> {
|
||||
const job = this.jobs.get(id);
|
||||
if (!job) return;
|
||||
|
||||
let result: WidgetResult;
|
||||
try {
|
||||
result = await collect(widget);
|
||||
result = await collect(job.widget);
|
||||
if (result.type === "http") {
|
||||
job.consecutiveFailures = result.data.up ? 0 : job.consecutiveFailures + 1;
|
||||
result = { type: "http", data: { ...result.data, consecutiveFailures: job.consecutiveFailures } };
|
||||
}
|
||||
} catch (err) {
|
||||
result = { type: "error", message: (err as Error).message };
|
||||
}
|
||||
|
||||
if (!this.jobs.has(id)) return;
|
||||
this.lastResults.set(id, result);
|
||||
for (const listener of this.listeners) listener(id, result);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import si from "systeminformation";
|
||||
import type { SystemResult } from "@/lib/types/system-result";
|
||||
|
||||
const CACHE_MS = 1_000;
|
||||
|
||||
let lastSample: { data: SystemResult; ts: number } | null = null;
|
||||
let inFlight: Promise<SystemResult> | null = null;
|
||||
|
||||
function pickDisk(disks: si.Systeminformation.FsSizeData[]): si.Systeminformation.FsSizeData | undefined {
|
||||
return disks.find((disk) => disk.mount === "/") ?? disks.sort((a, b) => b.size - a.size)[0];
|
||||
}
|
||||
|
||||
async function sample(): Promise<SystemResult> {
|
||||
const [load, mem, disks, net] = await Promise.all([
|
||||
si.currentLoad(),
|
||||
si.mem(),
|
||||
si.fsSize(),
|
||||
si.networkStats(),
|
||||
]);
|
||||
|
||||
const disk = pickDisk(disks);
|
||||
const primaryNet = net[0];
|
||||
|
||||
return {
|
||||
cpuPercent: load.currentLoad,
|
||||
memUsedBytes: mem.active,
|
||||
memTotalBytes: mem.total,
|
||||
diskUsedBytes: disk?.used ?? 0,
|
||||
diskTotalBytes: disk?.size ?? 0,
|
||||
netRxBytesPerSec: primaryNet?.rx_sec ?? 0,
|
||||
netTxBytesPerSec: primaryNet?.tx_sec ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
export async function collectSystem(): Promise<SystemResult> {
|
||||
const now = Date.now();
|
||||
if (lastSample && now - lastSample.ts < CACHE_MS) {
|
||||
return lastSample.data;
|
||||
}
|
||||
if (inFlight) return inFlight;
|
||||
|
||||
inFlight = sample()
|
||||
.then((data) => {
|
||||
lastSample = { data, ts: Date.now() };
|
||||
return data;
|
||||
})
|
||||
.finally(() => {
|
||||
inFlight = null;
|
||||
});
|
||||
|
||||
return inFlight;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { TraefikResult } from "@/lib/types/traefik-result";
|
||||
|
||||
interface RawRouter {
|
||||
name: string;
|
||||
rule: string;
|
||||
service: string;
|
||||
status: string;
|
||||
tls?: unknown;
|
||||
entryPoints?: string[];
|
||||
}
|
||||
|
||||
interface RawEntrypoint {
|
||||
name: string;
|
||||
address: string;
|
||||
}
|
||||
|
||||
async function fetchJson<T>(url: string): Promise<T | null> {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(5_000) });
|
||||
if (!response.ok) return null;
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
export async function collectTraefik(apiUrl: string): Promise<TraefikResult> {
|
||||
const base = apiUrl.replace(/\/$/, "");
|
||||
|
||||
const [routers, entrypoints, middlewares] = await Promise.all([
|
||||
fetchJson<RawRouter[]>(`${base}/http/routers`),
|
||||
fetchJson<RawEntrypoint[]>(`${base}/entrypoints`),
|
||||
fetchJson<unknown[]>(`${base}/http/middlewares`),
|
||||
]);
|
||||
|
||||
if (routers === null) {
|
||||
throw new Error(`Traefik API at ${base}/http/routers is unreachable or returned an error`);
|
||||
}
|
||||
|
||||
return {
|
||||
routers: routers.map((router) => ({
|
||||
name: router.name,
|
||||
rule: router.rule,
|
||||
service: router.service,
|
||||
status: router.status,
|
||||
tls: Boolean(router.tls),
|
||||
entryPoints: router.entryPoints ?? [],
|
||||
})),
|
||||
entrypoints: (entrypoints ?? []).map((ep) => ({ name: ep.name, address: ep.address })),
|
||||
middlewaresCount: middlewares?.length ?? 0,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user