Add a Technitium DNS Server integration for its statistics and health

A new integration type (Network, next to AdGuard Home) reads Technitium's API
every two minutes with a non-expiring API token in the Authorization header:
version and uptime, whether blocking is on, block lists and their next update,
the last day's queries and how they ended, cache and zone counts, the top
clients and names, zone health (expired or unsynced secondary zones), DHCP
leases — and puts one real DNS question to it over UDP. A Technitium page
shows it; alerts: DNS not answering (critical), blocking left off, block lists
overdue, zones expired or not syncing; /metrics gets homelab_technitium_*.
Nothing is changed on the server. Technitium's API has no CPU, memory or disk
figures; the page says a server agent covers that. New table technitium_state
(migration 0081).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-11-01 21:48:46 +01:00
1 parent e4cd01e9ba
commit 312093d3f7
24 files changed
+10189 -7

No files matched your search

+2
View File
@@ -72,6 +72,7 @@ import { fragnetRouter } from "./routes/fragnet.js";
import { arrRouter } from "./routes/arr.js";
import { wallRouter } from "./routes/wall.js";
import { adguardRouter } from "./routes/adguard.js";
import { technitiumRouter } from "./routes/technitium.js";
import { grafanaRouter } from "./routes/grafana.js";
import { versionsRouter } from "./routes/versions.js";
import { portPresetsRouter } from "./routes/portPresets.js";
@@ -225,6 +226,7 @@ export function createApp() {
app.use("/api/arr", arrRouter);
app.use("/api/wall", wallRouter);
app.use("/api/adguard", adguardRouter);
app.use("/api/technitium", technitiumRouter);
app.use("/api/grafana", grafanaRouter);
app.use("/api/versions", versionsRouter);
app.use("/api/port-presets", portPresetsRouter);
+24
View File
@@ -571,6 +571,7 @@ export const integrationTypes = [
"radarr",
"prowlarr",
"adguard",
"technitium",
"grafana",
"lidarr",
"readarr",
@@ -1382,6 +1383,29 @@ export const adguardState = sqliteTable("adguard_state", {
updatedAt: text("updated_at").notNull(), // ISO
});
// ─── Technitium DNS Server ──────────────────────────────────────────────────
// How a Technitium DNS Server (an integration of type "technitium") is right now, one row each, replaced at every read: its version and when it started, whether blocking is on, its settings that
// matter (block lists and when they are next updated, the cache size, recursion), the statistics of the last day, the health of its zones, its DHCP leases and the result of a real DNS question
// put to it — plus since when blocking has been off and the question unanswered, which only this app can know. A column that is null could not be read. Read by services/technitiumSync.ts.
export const technitiumState = sqliteTable("technitium_state", {
integrationId: integer("integration_id")
.primaryKey()
.references(() => integrations.id, { onDelete: "cascade" }),
version: text("version"),
startedAt: text("started_at"), // ISO: when the DNS server last started; null when it did not say
dnsPort: integer("dns_port").notNull().default(53),
blockingEnabled: integer("blocking_enabled", { mode: "boolean" }).notNull().default(true),
blockingOffSince: text("blocking_off_since"), // ISO: the first read that showed blocking off; null while it is on
settings: text("settings").notNull(), // JSON: { blockLists: { count, intervalHours, nextUpdate }, cacheMaximumEntries, recursion, dnssecValidation }
stats: text("stats"), // JSON: the last day's queries and how they ended, cache and zone counts, top clients and names; null: could not be read
zones: text("zones"), // JSON: { total, disabled, issues: [{ name, problem }] }; null: could not be read
dhcp: text("dhcp"), // JSON: { scopes, enabledScopes, leases }; null: no DHCP server, or could not be read
probe: text("probe"), // JSON: the DNS question — { ok, ms, error, name, host }
probeFailSince: text("probe_fail_since"), // ISO: the first read in which the question went unanswered; null while it is answered
updatedAt: text("updated_at").notNull(), // ISO
});
// ─── Grafana ────────────────────────────────────────────────────────────────
// How a Grafana (an integration of type "grafana") is right now, one row each, replaced at every read: the alert rules that are firing, pending or cannot be evaluated (and how many there are), and
+2
View File
@@ -43,6 +43,7 @@ import { initSpeedtestSync } from "./services/speedtestSync.js";
import { initFragnetSync } from "./services/fragnetSync.js";
import { initArrSync } from "./services/arrSync.js";
import { initAdguardSync } from "./services/adguardSync.js";
import { initTechnitiumSync } from "./services/technitiumSync.js";
import { initGrafanaSync } from "./services/grafanaSync.js";
import { initVersionCheck } from "./services/appVersions.js";
import { backfillMetricRollups } from "./services/serverMetrics.js";
@@ -109,6 +110,7 @@ initSpeedtestSync();
initFragnetSync();
initArrSync();
initAdguardSync();
initTechnitiumSync();
initGrafanaSync();
initVersionCheck();
// The hourly and daily figures are built from what is already kept, once, the first time after they were added (in the background: nothing waits for it).
+7
View File
@@ -147,6 +147,13 @@ export const INTEGRATION_FIELDS: Partial<Record<IntegrationType, IntegrationFiel
{ key: "probeDomain", label: "Name to test DNS with (optional)", secret: false, optional: true, placeholder: "example.com" },
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
],
technitium: [
{ key: "url", label: "Technitium web console URL", secret: false, placeholder: "http://dns.example.lan:5380" },
{ key: "token", label: "API token", secret: true, type: "password", placeholder: "Administration → Sessions → Create Token (a user who may view the dashboard, settings and zones)" },
{ key: "dnsHost", label: "DNS server address (optional)", secret: false, optional: true, placeholder: "the host of the URL — only if its DNS server is somewhere else" },
{ key: "probeDomain", label: "Name to test DNS with (optional)", secret: false, optional: true, placeholder: "example.com" },
{ key: "insecure", label: "Allow self-signed certificate", secret: false, type: "checkbox" },
],
grafana: [
{ key: "url", label: "Grafana URL", secret: false, placeholder: "http://grafana.example.lan:3000" },
{ key: "token", label: "Service account token", secret: true, type: "password", placeholder: "Administration → Service accounts → add a token (role Viewer)" },
+3
View File
@@ -26,6 +26,7 @@ import { createSpeedtestAdapter } from "./speedtest/adapter.js";
import { createFragnetAdapter } from "./fragnet/adapter.js";
import { createArrAdapter } from "./arr/adapter.js";
import { createAdguardAdapter } from "./adguard/adapter.js";
import { createTechnitiumAdapter } from "./technitium/adapter.js";
import { createGrafanaAdapter } from "./grafana/adapter.js";
import { createNextcloudAdapter } from "./nextcloud/adapter.js";
@@ -96,6 +97,8 @@ export function createIntegrationAdapter(type: IntegrationType, config: Integrat
return createArrAdapter(type, config as any);
case "adguard":
return createAdguardAdapter(config as any);
case "technitium":
return createTechnitiumAdapter(config as any);
case "grafana":
return createGrafanaAdapter(config as any);
case "netbox":
@@ -0,0 +1,296 @@
/**
* Technitium DNS Server adapter — its health and statistics. (The adapter in dns/adapters/technitium.ts is the one for zones and records; this one only reads.) Config: url (its web console,
* port 5380 by default), token (a non-expiring API token: Administration → Sessions → Create Token, for a user who may view the dashboard, the settings and the zones), optionally dnsHost
* (where its DNS server is, when that is not the host of the web address), probeDomain (the name a test question is asked about; example.com unless told) and insecure.
*
* Reading only: what the server is and since when it has run, whether blocking is on and when its block lists are next updated (`/api/settings/get`), what it has done in the last day — queries and
* how each ended, cache and zone counts, the clients and names asked about most (`/api/dashboard/stats/get`), the health of its zones — a secondary zone that has expired or cannot sync
* (`/api/zones/list`), its DHCP scopes and leases (`/api/dhcp/…`) — and one real DNS question put to its DNS server over UDP (see ../adguard/dnsProbe.ts), because the console can be up while DNS is
* not. Technitium's API says nothing about the CPU, memory or disk of the machine it runs on: that is what a server agent on that machine reports. Nothing is changed.
*
* Endpoints and fields are from Technitium's published API documentation (APIDOCS.md) and have not been checked against a live install here; every field is read defensively. The token goes in an
* `Authorization: Bearer` header, which is what version 15.0 and later require.
*/
import { requestJson } from "../httpJson.js";
import { withDiagLogging } from "../../services/diagLog.js";
import { probeDns, type ProbeResult } from "../adguard/dnsProbe.js";
export interface TechnitiumConfig {
url: string;
token: string;
insecure?: boolean;
dnsHost?: string;
probeDomain?: string;
}
export const DEFAULT_PROBE_DOMAIN = "example.com";
export interface TechnitiumCounted {
name: string;
count: number;
}
export interface TechnitiumStats {
/** What Technitium's statistics cover: "LastDay". */
period: string;
queries: number;
noError: number;
serverFailure: number;
nxDomain: number;
refused: number;
authoritative: number;
recursive: number;
cached: number;
blocked: number;
dropped: number;
clients: number;
/** Counts as the server has them now (not over the period). */
zones: number | null;
cachedEntries: number | null;
allowedZones: number | null;
blockedZones: number | null;
allowListZones: number | null;
blockListZones: number | null;
/** Shares of the queries, in percent; null with no queries. */
blockedPercent: number | null;
cachedPercent: number | null;
failurePercent: number | null;
topClients: TechnitiumCounted[];
topDomains: TechnitiumCounted[];
topBlocked: TechnitiumCounted[];
}
export interface TechnitiumSettings {
version: string | null;
/** ISO; null when it did not say. */
startedAt: string | null;
dnsPort: number;
blockingEnabled: boolean;
blockLists: { count: number; intervalHours: number | null; nextUpdate: string | null };
cacheMaximumEntries: number | null;
recursion: string | null;
dnssecValidation: boolean | null;
}
export interface TechnitiumZoneIssue {
name: string;
problem: "expired" | "sync failed";
}
export interface TechnitiumZones {
total: number;
disabled: number;
issues: TechnitiumZoneIssue[];
}
export interface TechnitiumDhcp {
scopes: number;
enabledScopes: number;
leases: number;
}
export interface TechnitiumRead {
version: string | null;
startedAt: string | null;
dnsPort: number;
blockingEnabled: boolean;
settings: Pick<TechnitiumSettings, "blockLists" | "cacheMaximumEntries" | "recursion" | "dnssecValidation">;
/** Null when the statistics could not be read. */
stats: TechnitiumStats | null;
/** Null when the zones could not be listed. */
zones: TechnitiumZones | null;
/** Null when there is no DHCP server to ask, or it could not be read. */
dhcp: TechnitiumDhcp | null;
/** The real DNS question: whether it was answered, how fast, and about what. */
probe: ProbeResult & { name: string; host: string };
}
export interface TechnitiumAdapter {
ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }>;
read(): Promise<TechnitiumRead>;
}
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
/** A moment as Technitium writes it (up to seven fractional digits, which Date.parse does not always take) as ISO; null for none, or for the year 1 it writes for "never". */
const isoOf = (v: unknown): string | null => {
const s = str(v);
if (!s) return null;
const t = Date.parse(s.replace(/(\.\d{3})\d+/, "$1"));
return Number.isFinite(t) && t > Date.UTC(2000, 0, 1) ? new Date(t).toISOString() : null;
};
const percent = (part: number, whole: number): number | null => (whole > 0 ? Math.round((part / whole) * 1000) / 10 : null);
/** Pure: `/api/settings/get`'s answer. */
export function parseSettings(raw: unknown): TechnitiumSettings {
const s = obj(raw);
const port = arr(s.dnsServerLocalEndPoints)
.map((e) => (typeof e === "string" ? /:(\d{1,5})$/.exec(e.trim()) : null))
.find((m) => m !== null);
const interval = num(s.blockListUpdateIntervalHours);
return {
version: str(s.version),
startedAt: isoOf(s.uptimestamp),
dnsPort: port ? Number(port[1]) : 53,
blockingEnabled: s.enableBlocking !== false,
blockLists: { count: arr(s.blockListUrls).filter((u) => str(u) !== null).length, intervalHours: interval !== null && interval > 0 ? interval : null, nextUpdate: isoOf(s.blockListNextUpdatedOn) },
cacheMaximumEntries: num(s.cacheMaximumEntries),
recursion: str(s.recursion),
dnssecValidation: typeof s.dnssecValidation === "boolean" ? s.dnssecValidation : null,
};
}
/** Pure: the clients or names asked about most — `[{ name, hits }]`; a client may carry the name its address resolves to (`domain`). */
export function parseTop(raw: unknown, limit = 10): TechnitiumCounted[] {
const out: TechnitiumCounted[] = [];
for (const item of arr(raw)) {
const i = obj(item);
const name = str(i.name);
const hits = num(i.hits);
if (name === null || hits === null) continue;
const domain = str(i.domain);
out.push({ name: domain && domain !== name ? `${name} (${domain})` : name, count: hits });
}
return out.sort((a, b) => b.count - a.count).slice(0, limit);
}
/** Pure: `/api/dashboard/stats/get`'s `response`. No query count is not zero queries: it is "could not be read". */
export function parseStats(raw: unknown, period = "LastDay"): TechnitiumStats | null {
const r = obj(raw);
const s = obj(r.stats);
const queries = num(s.totalQueries);
if (queries === null) return null;
const n = (k: string) => num(s[k]) ?? 0;
return {
period,
queries,
noError: n("totalNoError"),
serverFailure: n("totalServerFailure"),
nxDomain: n("totalNxDomain"),
refused: n("totalRefused"),
authoritative: n("totalAuthoritative"),
recursive: n("totalRecursive"),
cached: n("totalCached"),
blocked: n("totalBlocked"),
dropped: n("totalDropped"),
clients: n("totalClients"),
zones: num(s.zones),
cachedEntries: num(s.cachedEntries),
allowedZones: num(s.allowedZones),
blockedZones: num(s.blockedZones),
allowListZones: num(s.allowListZones),
blockListZones: num(s.blockListZones),
blockedPercent: percent(n("totalBlocked"), queries),
cachedPercent: percent(n("totalCached"), queries),
failurePercent: percent(n("totalServerFailure"), queries),
topClients: parseTop(r.topClients),
topDomains: parseTop(r.topDomains),
topBlocked: parseTop(r.topBlockedDomains),
};
}
/** Pure: `/api/zones/list`'s `response`. Internal zones are the server's own; a disabled zone is not judged. A secondary zone that has expired no longer answers; one that cannot sync is going stale. */
export function parseZones(raw: unknown): TechnitiumZones | null {
const r = obj(raw);
if (!Array.isArray(r.zones)) return null;
const zones = r.zones.map(obj).filter((z) => str(z.name) !== null && z.internal !== true);
const issues: TechnitiumZoneIssue[] = [];
for (const z of zones) {
if (z.disabled === true) continue;
if (z.isExpired === true) issues.push({ name: str(z.name)!, problem: "expired" });
else if (z.syncFailed === true) issues.push({ name: str(z.name)!, problem: "sync failed" });
}
return { total: zones.length, disabled: zones.filter((z) => z.disabled === true).length, issues };
}
/** Pure: the DHCP scopes (`/api/dhcp/scopes/list`) and how many leases there are (`/api/dhcp/leases/list`, null when not asked). Null when the scopes are not a list. */
export function parseDhcp(scopesRaw: unknown, leasesRaw: unknown | null): TechnitiumDhcp | null {
const s = obj(scopesRaw);
if (!Array.isArray(s.scopes)) return null;
return { scopes: s.scopes.length, enabledScopes: s.scopes.filter((x) => obj(x).enabled === true).length, leases: leasesRaw === null ? 0 : arr(obj(leasesRaw).leases).length };
}
export function createTechnitiumAdapter(config: TechnitiumConfig): TechnitiumAdapter {
const raw = String(config.url ?? "").trim().replace(/\/+$/, "");
const insecure = config.insecure === true;
const headers = { Authorization: `Bearer ${config.token}`, Accept: "application/json" };
/** One call; what is returned is its `response` (the answer is `{ status, response }`, and a session or token that is not accepted is a `status`, not an HTTP error). */
async function get(path: string, params: Record<string, string> = {}): Promise<Record<string, unknown>> {
const qs = new URLSearchParams(params).toString();
const res = await requestJson(`${raw}${path}${qs ? `?${qs}` : ""}`, { headers, insecure });
if (res.status === 401 || res.status === 403) throw new Error(`Technitium did not accept the token (HTTP ${res.status})`);
if (res.status === 404) throw new Error("Technitium has no API at this address (HTTP 404) — check the address of its web console (port 5380 unless changed)");
if (res.status < 200 || res.status >= 300) throw new Error(`Technitium error: HTTP ${res.status}`);
if (res.json === null) throw new Error("Technitium answered with something that isn't JSON — is the address its own?");
const body = obj(res.json);
const status = str(body.status);
if (status === "invalid-token") throw new Error("Technitium did not accept the token — make a non-expiring API token (Administration → Sessions → Create Token); a server older than 15.0 does not take it in the header");
if (status === "error") throw new Error(`Technitium: ${str(body.errorMessage) ?? "an error"}`);
if (status !== "ok") throw new Error(`Technitium answered with status "${status ?? "none"}"`);
return obj(body.response);
}
const soft = async <T>(run: () => Promise<T>): Promise<T | null> => {
try {
return await run();
} catch {
return null;
}
};
function dnsHostOf(): string {
const given = str(config.dnsHost);
if (given) return given.replace(/^\[|\]$/g, "");
try {
return new URL(raw).hostname.replace(/^\[|\]$/g, "");
} catch {
return "";
}
}
async function readDhcp(): Promise<TechnitiumDhcp | null> {
const scopes = await get("/api/dhcp/scopes/list");
const withoutLeases = parseDhcp(scopes, null);
if (withoutLeases === null || withoutLeases.scopes === 0) return withoutLeases;
return parseDhcp(scopes, await get("/api/dhcp/leases/list"));
}
async function read(): Promise<TechnitiumRead> {
// The settings must work: they say it is there and the token is accepted.
const settings = parseSettings(await get("/api/settings/get"));
const name = str(config.probeDomain) ?? DEFAULT_PROBE_DOMAIN;
const host = dnsHostOf();
const [stats, zones, dhcp, probe] = await Promise.all([
soft(async () => parseStats(await get("/api/dashboard/stats/get", { type: "LastDay" }))),
soft(async () => parseZones(await get("/api/zones/list", { pageNumber: "1", zonesPerPage: "1000" }))),
soft(readDhcp),
host ? probeDns(host, settings.dnsPort, name) : Promise.resolve({ ok: false, ms: null, error: "no address to ask" } as ProbeResult),
]);
return {
version: settings.version,
startedAt: settings.startedAt,
dnsPort: settings.dnsPort,
blockingEnabled: settings.blockingEnabled,
settings: { blockLists: settings.blockLists, cacheMaximumEntries: settings.cacheMaximumEntries, recursion: settings.recursion, dnssecValidation: settings.dnssecValidation },
stats,
zones,
dhcp,
probe: { ...probe, name, host },
};
}
async function ping(): Promise<{ ok: boolean; latencyMs?: number; error?: string }> {
const start = Date.now();
try {
await get("/api/settings/get");
return { ok: true, latencyMs: Date.now() - start };
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
}
}
return withDiagLogging("technitium", { ping, read });
}
+4
View File
@@ -43,6 +43,7 @@ import { forgetFragnet, syncFragnet } from "../services/fragnetSync.js";
import { forgetArr, syncArr } from "../services/arrSync.js";
import { ARR_KINDS } from "../integrations/arr/adapter.js";
import { forgetAdguard, syncAdguard } from "../services/adguardSync.js";
import { forgetTechnitium, syncTechnitium } from "../services/technitiumSync.js";
import { forgetGrafana, syncGrafana } from "../services/grafanaSync.js";
import { forgetNextcloud, syncNextcloud } from "../services/nextcloudSync.js";
import { dockerVulnSyncStatuses, findingsOf, forgetDockerVulns, imageAgeDays, imagesOf, isDockerVulnFresh, syncDockerVulns } from "../services/dockerVulnSync.js";
@@ -160,6 +161,7 @@ integrationsRouter.post("/", requireRole("admin"), asyncHandler(async (req, res)
if (type === "fragnet") void syncFragnet(created.id).then(() => invalidateAlertsCache());
if ((ARR_KINDS as string[]).includes(type)) void syncArr(created.id).then(() => invalidateAlertsCache());
if (type === "adguard") void syncAdguard(created.id).then(() => invalidateAlertsCache());
if (type === "technitium") void syncTechnitium(created.id).then(() => invalidateAlertsCache());
if (type === "grafana") void syncGrafana(created.id).then(() => invalidateAlertsCache());
if (type === "nextcloud") void syncNextcloud(created.id).then(() => invalidateAlertsCache());
if (type === "dockhand") void syncDockerVulns(created.id).then(() => invalidateAlertsCache());
@@ -278,6 +280,7 @@ integrationsRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req,
if (updated.type === "fragnet" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncFragnet(updated.id).then(() => invalidateAlertsCache());
if ((ARR_KINDS as string[]).includes(updated.type) && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncArr(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "adguard" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncAdguard(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "technitium" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncTechnitium(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "grafana" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncGrafana(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "nextcloud" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncNextcloud(updated.id).then(() => invalidateAlertsCache());
if (updated.type === "dockhand" && updated.enabled && (parsed.data.config || parsed.data.enabled === true)) void syncDockerVulns(updated.id).then(() => invalidateAlertsCache());
@@ -403,6 +406,7 @@ integrationsRouter.delete("/:id", requireRole("admin"), asyncHandler(async (req,
if (existing.type === "fragnet") await forgetFragnet(id);
if ((ARR_KINDS as string[]).includes(existing.type)) await forgetArr(id);
if (existing.type === "adguard") await forgetAdguard(id);
if (existing.type === "technitium") await forgetTechnitium(id);
if (existing.type === "grafana") await forgetGrafana(id);
if (existing.type === "nextcloud") await forgetNextcloud(id);
if (existing.type === "dockhand") await forgetDockerVulns(id);
+39
View File
@@ -0,0 +1,39 @@
import { Router } from "express";
import { eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { integrations, technitiumState } from "../db/schema.js";
import { requireAuth } from "../auth/middleware.js";
import { blockListsOverdueMs, isTechnitiumFresh, storedOf, technitiumProblems, technitiumSyncStatuses } from "../services/technitiumSync.js";
import { asyncHandler } from "../utils/asyncHandler.js";
export const technitiumRouter = Router();
technitiumRouter.use(requireAuth);
/** Every Technitium DNS Server, how it is, from what the last reads stored: whether DNS answers, whether blocking is on, the last day's statistics, its zones and what is wrong. Everyone signed in can see it. */
technitiumRouter.get("/", asyncHandler(async (_req, res) => {
const [rows, states, statuses] = await Promise.all([
db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled, baseUrl: integrations.baseUrl }).from(integrations).where(eq(integrations.type, "technitium")).orderBy(integrations.name),
db.select().from(technitiumState),
technitiumSyncStatuses(),
]);
const byId = new Map(states.map((s) => [s.integrationId, s]));
const now = Date.now();
res.json({
instances: rows.map((r) => {
const row = byId.get(r.id);
const state = row ? storedOf(row) : null;
const status = statuses[r.id] ?? null;
const fresh = isTechnitiumFresh(status ?? undefined, now);
return {
id: r.id,
name: r.name,
enabled: r.enabled,
url: r.baseUrl,
status,
fresh,
state: state && { ...state, blockListsOverdueMs: blockListsOverdueMs(state, now) },
problems: state && fresh ? technitiumProblems(r.id, r.name, state, now) : [],
};
}),
});
}));
+4 -1
View File
@@ -92,6 +92,7 @@ const SOURCES: Record<string, { label: string; link: string }> = {
readarr: { label: "Readarr", link: "/media" },
prowlarr: { label: "Prowlarr", link: "/media" },
adguard: { label: "AdGuard Home", link: "/adguard" },
technitium: { label: "Technitium DNS", link: "/technitium" },
versions: { label: "Versions", link: "/versions" },
grafana: { label: "Grafana", link: "/grafana" },
secrets: { label: "Secrets", link: "/secrets" },
@@ -140,6 +141,8 @@ function originOfConditionKey(key: string): { type: string; id: number | null; c
if (m) return { type: "versions", id: Number(m[1]), category: "updates" };
m = /^adguard-(stopped|dns|protection|filters):(\d+)/.exec(key);
if (m) return { type: "adguard", id: Number(m[2]), category: m[1] === "stopped" || m[1] === "dns" ? "services" : "monitoring" };
m = /^technitium-(dns|blocking|lists|zones):(\d+)/.exec(key);
if (m) return { type: "technitium", id: Number(m[2]), category: m[1] === "dns" || m[1] === "zones" ? "services" : "monitoring" };
m = /^grafana-(firing|rule-error|ds):(\d+):/.exec(key);
if (m) return { type: "grafana", id: Number(m[2]), category: m[1] === "ds" ? "integration" : "monitoring" };
m = /^(sonarr|radarr|prowlarr|lidarr|readarr)-(health|queue|disk):(\d+)/.exec(key);
@@ -298,7 +301,7 @@ export async function collectAlerts(): Promise<AlertsReport> {
if (held.has("slo")) cannotCheck("Service-level targets", "couldn't be judged — see the server log", "Server and storage health");
if (held.has("server:baseline")) cannotCheck("What is usual for the time", "couldn't be judged — see the server log", "Server and storage health");
for (const h of held) {
const m = /^(proxmox|synology|unifi|ups|dockhand|jellyfin|authentik|prometheus|immich|paperless|nextcloud|netbox|n8n|hetzner|speedtest|fragnet|sonarr|radarr|prowlarr|lidarr|readarr|adguard|grafana):(\d+)(?::(.+))?$/.exec(h);
const m = /^(proxmox|synology|unifi|ups|dockhand|jellyfin|authentik|prometheus|immich|paperless|nextcloud|netbox|n8n|hetzner|speedtest|fragnet|sonarr|radarr|prowlarr|lidarr|readarr|adguard|technitium|grafana):(\d+)(?::(.+))?$/.exec(h);
if (!m || (m[3] && held.has(`${m[1]}:${m[2]}`))) continue;
const row = intById.get(Number(m[2]));
cannotCheck(`${SOURCES[m[1]].label} “${row?.name ?? `#${m[2]}`}”${m[3] === "vuln" ? " (vulnerability scans)" : m[3] === "images" ? " (age of the images)" : m[3] ? ` (node ${m[3]})` : ""}`, "couldn't be read — see the Diagnostic Log", "Server and storage health");
+23 -1
View File
@@ -1,6 +1,6 @@
import { and, eq, inArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { authentikState, n8nState, netboxState, nextcloudState, paperlessState, immichState, prometheusState, integrations, jellyfinState, networkDevices, serverPorts, servers, upsState , dockhandVulnerabilities , hetznerState , fragnetState , arrState , adguardState , grafanaState } from "../db/schema.js";
import { technitiumState, authentikState, n8nState, netboxState, nextcloudState, paperlessState, immichState, prometheusState, integrations, jellyfinState, networkDevices, serverPorts, servers, upsState , dockhandVulnerabilities , hetznerState , fragnetState , arrState , adguardState , grafanaState } from "../db/schema.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { createProxmoxAdapter, type ProxmoxNodeStats } from "../integrations/proxmox/adapter.js";
import { createSynologyAdapter, type SynologyStorageInfo } from "../integrations/synology/adapter.js";
@@ -36,6 +36,7 @@ import { hetznerProblems, hetznerSyncStatuses, imagesOf as hetznerImagesOf, load
import { ARR_KINDS, type ArrKind } from "../integrations/arr/adapter.js";
import { versionProblems, versionRows, type VersionProblem } from "./appVersions.js";
import { adguardProblems, adguardSyncStatuses, isAdguardFresh, storedOf as adguardStoredOf, type AdguardProblem } from "./adguardSync.js";
import { isTechnitiumFresh, storedOf as technitiumStoredOf, technitiumProblems, technitiumSyncStatuses, type TechnitiumProblem } from "./technitiumSync.js";
import { grafanaProblems, grafanaSyncStatuses, isGrafanaFresh, storedOf as grafanaStoredOf, type GrafanaProblem } from "./grafanaSync.js";
import { arrProblems, arrSyncStatuses, isArrFresh, storedOf as arrStoredOf, type ArrProblem } from "./arrSync.js";
import { fragnetProblems, fragnetSyncStatuses, isFragnetFresh, optionsOf as fragnetOptions, serversOf as fragnetServersOf, type FragnetProblem } from "./fragnetSync.js";
@@ -141,6 +142,8 @@ export interface HealthSnapshot {
arr?: { integrationId: number; kind: ArrKind; problems: ArrProblem[] }[];
/** What is wrong with each AdGuard Home (DNS not running or not answering, protection left off, filter lists not updating), only while that reading is recent (services/adguardSync.ts). */
adguard?: { integrationId: number; problems: AdguardProblem[] }[];
/** What is wrong with each Technitium DNS Server (DNS not answering, blocking left off, block lists not updating, zones expired or not syncing), only while that reading is recent (services/technitiumSync.ts). */
technitium?: { integrationId: number; problems: TechnitiumProblem[] }[];
/** Applications a newer release of which has been out for the number of days set (services/appVersions.ts), only while the lookup of releases is on. */
versions?: VersionProblem[];
/** What is wrong with each Grafana (rules firing or failing, data sources failing their check), only while that reading is recent (services/grafanaSync.ts). */
@@ -291,6 +294,7 @@ export function evaluateHealth(snapshot: HealthSnapshot, thresholds: Thresholds,
// AdGuard Home and Grafana.
for (const a of snapshot.adguard ?? []) for (const p of a.problems) out.push({ key: p.key, source: `adguard:${a.integrationId}`, message: p.message, severity: p.severity });
for (const t of snapshot.technitium ?? []) for (const p of t.problems) out.push({ key: p.key, source: `technitium:${t.integrationId}`, message: p.message, severity: p.severity });
for (const g of snapshot.grafana ?? []) for (const p of g.problems) out.push({ key: p.key, source: `grafana:${g.integrationId}`, message: p.message, severity: p.severity });
// Sonarr, Radarr and Prowlarr: what they say is wrong, downloads that are stuck, disks nearly full.
@@ -628,6 +632,24 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
console.error("[health] couldn't judge AdGuard Home:", err instanceof Error ? err.message : err);
}
// Technitium DNS Server: read by its own pass every two minutes; what is judged is what that pass stored, and only while it is recent.
try {
const rowsT = await db.select({ id: integrations.id, name: integrations.name }).from(integrations).where(and(eq(integrations.type, "technitium"), eq(integrations.enabled, true)));
if (rowsT.length > 0) {
const statuses = await technitiumSyncStatuses();
for (const r of rowsT) {
const [state] = await db.select().from(technitiumState).where(eq(technitiumState.integrationId, r.id)).limit(1);
if (!state || !isTechnitiumFresh(statuses[r.id], Date.now())) {
held.add(`technitium:${r.id}`);
continue;
}
(snapshot.technitium ??= []).push({ integrationId: r.id, problems: technitiumProblems(r.id, r.name, technitiumStoredOf(state), Date.now()) });
}
}
} catch (err) {
console.error("[health] couldn't judge Technitium DNS Server:", err instanceof Error ? err.message : err);
}
// Grafana: read by its own pass every five minutes; what is judged is what that pass stored, and only while it is recent.
try {
const rowsR = await db.select({ id: integrations.id, name: integrations.name }).from(integrations).where(and(eq(integrations.type, "grafana"), eq(integrations.enabled, true)));
+1 -1
View File
@@ -6,7 +6,7 @@ export const INTEGRATION_GROUPS: { id: string; label: string; types: string[] }[
{ id: "infrastructure", label: "Infrastructure", types: ["proxmox", "synology", "dockhand", "hetzner", "fragnet", "tailscale"] },
{ id: "apps", label: "Apps", types: ["homeassistant", "jellyfin", "sonarr", "radarr", "lidarr", "readarr", "prowlarr", "immich", "paperless", "nextcloud", "authentik"] },
{ id: "backups", label: "Backups", types: ["pbs"] },
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard"] },
{ id: "network", label: "Network", types: ["unifi", "npm", "phpipam", "netbox", "adguard", "technitium"] },
{ id: "monitoring", label: "Monitoring", types: ["uptimekuma", "prometheus", "grafana", "ups", "speedtest"] },
{ id: "automation", label: "Automation", types: ["semaphore", "gitea", "osticket", "n8n"] },
];
+2
View File
@@ -49,6 +49,8 @@ export function subjectOfConditionKey(key: string): string | null {
if (m) return `integration:${m[1]}`;
m = /^adguard-(?:stopped|dns|protection|filters):(\d+)/.exec(key);
if (m) return `integration:${m[1]}`;
m = /^technitium-(?:dns|blocking|lists|zones):(\d+)/.exec(key);
if (m) return `integration:${m[1]}`;
m = /^grafana-(?:firing|rule-error|ds):(\d+):/.exec(key);
if (m) return `integration:${m[1]}`;
m = /^netbox-(?:workers):(\d+)/.exec(key);
+37 -1
View File
@@ -5,7 +5,7 @@
*/
import { eq, inArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers, upsState, jellyfinState, authentikState, immichState, paperlessState, nextcloudState, netboxState, n8nState, dockhandVulnerabilities, hetznerState, fragnetState, arrState, adguardState, grafanaState } from "../db/schema.js";
import { technitiumState, assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers, upsState, jellyfinState, authentikState, immichState, paperlessState, nextcloudState, netboxState, n8nState, dockhandVulnerabilities, hetznerState, fragnetState, arrState, adguardState, grafanaState } from "../db/schema.js";
import { isUpsFresh, upsSyncStatuses } from "./upsSync.js";
import { levelStatuses } from "./serviceLevels.js";
import { backupState, listAll as listDuplicati } from "./duplicati.js";
@@ -17,6 +17,7 @@ import { costOf as hetznerCostOf, hetznerSyncStatuses, isHetznerFresh, serversOf
import { ARR_KINDS } from "../integrations/arr/adapter.js";
import { versionRows as appVersionRows } from "./appVersions.js";
import { adguardSyncStatuses, isAdguardFresh, storedOf as adguardStoredOf } from "./adguardSync.js";
import { blockListsOverdueMs, isTechnitiumFresh, storedOf as technitiumStoredOf, technitiumSyncStatuses } from "./technitiumSync.js";
import { grafanaSyncStatuses, isGrafanaFresh, storedOf as grafanaStoredOf } from "./grafanaSync.js";
import { arrSyncStatuses, distinctDisks as arrDisks, isArrFresh, stuckItems as arrStuck, storedOf as arrStoredOf } from "./arrSync.js";
import { fragnetSyncStatuses, isFragnetFresh, newestBackup as fragnetNewestBackup, serversOf as fragnetServersOf } from "./fragnetSync.js";
@@ -115,6 +116,40 @@ async function addVersionMetrics(out: Exposition) {
}
}
/** Each Technitium DNS Server, for /metrics: whether the test question was answered and how fast, whether blocking is on, how long it has run, the last day's queries and how they ended, the cache, the zones with a problem and the DHCP leases. Only while the reading is recent. */
async function addTechnitiumMetrics(out: Exposition, now: Date) {
const statuses = await technitiumSyncStatuses();
const rows = new Map((await db.select({ id: integrations.id, name: integrations.name, enabled: integrations.enabled }).from(integrations).where(eq(integrations.type, "technitium"))).map((r) => [r.id, r]));
for (const s of await db.select().from(technitiumState)) {
const row = rows.get(s.integrationId);
if (!row || !row.enabled || !isTechnitiumFresh(statuses[s.integrationId], now.getTime())) continue;
const state = technitiumStoredOf(s);
const labels = { name: row.name };
out.add("homelab_technitium_blocking_enabled", "gauge", "1 if Technitium's blocking is switched on, else 0.", state.blockingEnabled ? 1 : 0, labels);
if (state.startedAt !== null) out.add("homelab_technitium_uptime_seconds", "gauge", "How long the Technitium DNS server has been running, in seconds.", Math.max(0, (now.getTime() - Date.parse(state.startedAt)) / 1000), labels);
if (state.probe) {
out.add("homelab_technitium_dns_up", "gauge", "1 if Technitium's DNS server answered a test question, else 0.", state.probe.ok ? 1 : 0, labels);
if (state.probe.ok && state.probe.ms !== null) out.add("homelab_technitium_dns_probe_seconds", "gauge", "How long Technitium's DNS server took to answer a test question, in seconds.", state.probe.ms / 1000, labels);
}
const overdue = blockListsOverdueMs(state, now.getTime());
if (state.settings.blockLists.count > 0) out.add("homelab_technitium_block_lists_overdue", "gauge", "1 if the block lists were due for an update more than six hours ago, else 0.", overdue !== null ? 1 : 0, labels);
if (state.stats) {
out.add("homelab_technitium_queries", "gauge", "DNS queries Technitium answered in the last day.", state.stats.queries, labels);
out.add("homelab_technitium_blocked", "gauge", "Of them, the ones it blocked.", state.stats.blocked, labels);
out.add("homelab_technitium_cached", "gauge", "Of them, the ones answered from its cache.", state.stats.cached, labels);
out.add("homelab_technitium_recursive", "gauge", "Of them, the ones it had to resolve itself.", state.stats.recursive, labels);
out.add("homelab_technitium_server_failures", "gauge", "Of them, the ones that ended in a server failure.", state.stats.serverFailure, labels);
out.add("homelab_technitium_clients", "gauge", "Different clients that asked in the last day.", state.stats.clients, labels);
if (state.stats.cachedEntries !== null) out.add("homelab_technitium_cache_entries", "gauge", "Entries in Technitium's DNS cache now.", state.stats.cachedEntries, labels);
}
if (state.zones) {
out.add("homelab_technitium_zones", "gauge", "Zones Technitium holds (its own internal ones not counted).", state.zones.total, labels);
out.add("homelab_technitium_zone_problems", "gauge", "Zones that have expired or cannot sync.", state.zones.issues.length, labels);
}
if (state.dhcp) out.add("homelab_technitium_dhcp_leases", "gauge", "DHCP leases Technitium holds.", state.dhcp.leases, labels);
}
}
/** Each AdGuard Home, for /metrics: whether its DNS server runs and protects, whether the test question was answered and how fast, and what it has done over its statistics period. Only while the reading is recent. */
async function addAdguardMetrics(out: Exposition, now: Date) {
const statuses = await adguardSyncStatuses();
@@ -552,6 +587,7 @@ export async function buildMetrics(now: Date = new Date()): Promise<string> {
await addFragnetMetrics(out, now);
await addArrMetrics(out, now);
await addAdguardMetrics(out, now);
await addTechnitiumMetrics(out, now);
await addVersionMetrics(out);
await addGrafanaMetrics(out, now);
await addHeartbeatMetrics(out, now);
+223
View File
@@ -0,0 +1,223 @@
/**
* Keeps what Technitium DNS Server says up to date: every two minutes each Technitium integration is read — its version and when it started, whether blocking is on, its block lists, the
* statistics of the last day, the health of its zones, its DHCP leases — and one real DNS question is put to its DNS server; the state is stored. Pages and alerts are built from what is
* stored. (Two minutes, not five: DNS is what everything else leans on.)
*
* What is raised: **DNS is not answering** — the test question went unanswered, or was answered with an error, in every read for ten minutes (critical; one lost packet is not an outage);
* **blocking is switched off** for an hour or more while block lists are set up (someone paused it and forgot: warning); **the block lists are overdue** — their next update was due more than
* six hours ago (warning); **a zone has a problem** — a secondary zone that has expired no longer answers (critical), one that cannot sync is going stale (warning). "Since when" is what this
* app saw: the time of the first read that showed it.
*/
import { and, eq } from "drizzle-orm";
import { db } from "../db/client.js";
import { integrations, technitiumState } from "../db/schema.js";
import { createTechnitiumAdapter, type TechnitiumDhcp, type TechnitiumRead, type TechnitiumStats, type TechnitiumZones } from "../integrations/technitium/adapter.js";
import type { ProbeResult } from "../integrations/adguard/dnsProbe.js";
import { loadIntegrationConfig } from "../integrations/loadIntegration.js";
import { getInternalFlag, setInternalFlag } from "./settingsStore.js";
export const SYNC_INTERVAL_MS = 2 * 60_000;
/** After this long without a good read, what is stored is no longer believed. */
export const STALE_AFTER_MS = 10 * 60_000;
const STATUS_FLAG = "technitiumSync";
const MIN = 60_000;
const HOUR = 60 * MIN;
/** DNS that has not answered in any read for this long is down. */
export const DNS_FAIL_AFTER_MS = 10 * MIN;
/** Blocking off for this long is forgotten, not paused. */
export const BLOCKING_OFF_AFTER_MS = HOUR;
/** Block lists whose next update was due this long ago have stopped updating (Technitium tries again soon after a failed one). */
export const LISTS_OVERDUE_MS = 6 * HOUR;
export interface TechnitiumSyncStatus {
/** The last read that worked (kept when a later one failed). */
at: string;
ok: boolean;
error: string | null;
}
async function readStatuses(): Promise<Record<string, TechnitiumSyncStatus>> {
try {
const raw = await getInternalFlag(STATUS_FLAG);
return raw ? (JSON.parse(raw) as Record<string, TechnitiumSyncStatus>) : {};
} catch {
return {};
}
}
export async function technitiumSyncStatuses(): Promise<Record<number, TechnitiumSyncStatus>> {
return Object.fromEntries(Object.entries(await readStatuses()).map(([k, v]) => [Number(k), v]));
}
export const isTechnitiumFresh = (status: TechnitiumSyncStatus | undefined, nowMs: number) => !!status && status.ok && nowMs - Date.parse(status.at) <= STALE_AFTER_MS;
export type StateRow = typeof technitiumState.$inferSelect;
/** What is stored of one Technitium, as the read gave it, plus what the app has seen between reads. */
export interface StoredTechnitium {
version: string | null;
startedAt: string | null;
dnsPort: number;
blockingEnabled: boolean;
/** When the first read that showed blocking off was made; null while it is on. */
blockingOffSince: string | null;
settings: TechnitiumRead["settings"];
stats: TechnitiumStats | null;
zones: TechnitiumZones | null;
dhcp: TechnitiumDhcp | null;
probe: (ProbeResult & { name: string; host: string }) | null;
/** When the first read that showed the DNS test failing was made; null while it works. */
probeFailSince: string | null;
updatedAt: string;
}
function parse<T>(stored: string | null): T | null {
if (stored === null) return null;
try {
return JSON.parse(stored) as T;
} catch {
return null;
}
}
const NO_SETTINGS: TechnitiumRead["settings"] = { blockLists: { count: 0, intervalHours: null, nextUpdate: null }, cacheMaximumEntries: null, recursion: null, dnssecValidation: null };
export const storedOf = (row: StateRow): StoredTechnitium => ({
version: row.version,
startedAt: row.startedAt,
dnsPort: row.dnsPort,
blockingEnabled: row.blockingEnabled,
blockingOffSince: row.blockingOffSince,
settings: parse<TechnitiumRead["settings"]>(row.settings) ?? NO_SETTINGS,
stats: parse<TechnitiumStats>(row.stats),
zones: parse<TechnitiumZones>(row.zones),
dhcp: parse<TechnitiumDhcp>(row.dhcp),
probe: parse<StoredTechnitium["probe"]>(row.probe),
probeFailSince: row.probeFailSince,
updatedAt: row.updatedAt,
});
/** Pure: what the app has seen between reads, carried from the last read. A thing first seen wrong starts its clock now. */
export function carrySince(read: Pick<TechnitiumRead, "blockingEnabled" | "probe">, previous: Pick<StoredTechnitium, "blockingOffSince" | "probeFailSince"> | null, now: Date): { blockingOffSince: string | null; probeFailSince: string | null } {
const at = now.toISOString();
return {
blockingOffSince: read.blockingEnabled ? null : (previous?.blockingOffSince ?? at),
probeFailSince: read.probe.ok ? null : (previous?.probeFailSince ?? at),
};
}
/** Writes down one read, replacing the last (and carrying what was seen between reads). */
export async function storeRead(integrationId: number, r: TechnitiumRead, now: Date = new Date()): Promise<void> {
const [previous] = await db.select().from(technitiumState).where(eq(technitiumState.integrationId, integrationId)).limit(1);
const since = carrySince(r, previous ? storedOf(previous) : null, now);
const values = {
version: r.version,
startedAt: r.startedAt,
dnsPort: r.dnsPort,
blockingEnabled: r.blockingEnabled,
blockingOffSince: since.blockingOffSince,
settings: JSON.stringify(r.settings),
stats: r.stats && JSON.stringify(r.stats),
zones: r.zones && JSON.stringify(r.zones),
dhcp: r.dhcp && JSON.stringify(r.dhcp),
probe: JSON.stringify(r.probe),
probeFailSince: since.probeFailSince,
updatedAt: now.toISOString(),
};
await db.insert(technitiumState).values({ integrationId, ...values }).onConflictDoUpdate({ target: technitiumState.integrationId, set: values });
}
/** Reads one Technitium and stores it. Never throws: how it went is the answer, and what was stored is left alone when it failed. */
export async function syncTechnitium(integrationId: number, now: Date = new Date(), read?: (config: Record<string, unknown>) => Promise<TechnitiumRead>): Promise<TechnitiumSyncStatus> {
let status: TechnitiumSyncStatus;
try {
const loaded = await loadIntegrationConfig(integrationId);
if (!loaded || loaded.integration.type !== "technitium") throw new Error("not a Technitium integration");
const result = await (read ? read(loaded.config) : createTechnitiumAdapter(loaded.config as never).read());
await storeRead(integrationId, result, now);
status = { at: now.toISOString(), ok: true, error: null };
} catch (err) {
const previous = (await readStatuses())[String(integrationId)];
status = { at: previous?.at ?? now.toISOString(), ok: false, error: err instanceof Error ? err.message : String(err) };
console.error(`[technitium] couldn't read integration ${integrationId}:`, status.error);
}
try {
const all = await readStatuses();
all[String(integrationId)] = status;
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
} catch (err) {
console.error("[technitium] couldn't record the result:", err);
}
return status;
}
export async function syncAllTechnitium(now: Date = new Date()): Promise<Record<number, TechnitiumSyncStatus>> {
const rows = await db.select({ id: integrations.id }).from(integrations).where(and(eq(integrations.type, "technitium"), eq(integrations.enabled, true)));
const out: Record<number, TechnitiumSyncStatus> = {};
for (const r of rows) out[r.id] = await syncTechnitium(r.id, now);
return out;
}
export async function forgetTechnitium(integrationId: number): Promise<void> {
const all = await readStatuses();
if (String(integrationId) in all) {
delete all[String(integrationId)];
await setInternalFlag(STATUS_FLAG, JSON.stringify(all));
}
}
// ─── What is wrong ──────────────────────────────────────────────────────────
export interface TechnitiumProblem {
key: string;
message: string;
severity: "warning" | "critical";
}
const plural = (n: number, unit: string) => `${n} ${unit}${n === 1 ? "" : "s"}`;
const ago = (ms: number): string => (ms >= 48 * HOUR ? plural(Math.round(ms / (24 * HOUR)), "day") : ms >= HOUR ? plural(Math.round(ms / HOUR), "hour") : plural(Math.max(1, Math.round(ms / MIN)), "minute"));
/** Pure: how long ago the block lists were due for an update, when that is more than the grace; null when they are not overdue, or none are set up, or no time was said. */
export function blockListsOverdueMs(s: Pick<StoredTechnitium, "settings">, nowMs: number): number | null {
const l = s.settings.blockLists;
if (l.count === 0 || l.nextUpdate === null) return null;
const over = nowMs - Date.parse(l.nextUpdate);
return over > LISTS_OVERDUE_MS ? over : null;
}
/** Pure: what is wrong with one Technitium, from what is stored for it. */
export function technitiumProblems(id: number, name: string, s: StoredTechnitium, nowMs: number): TechnitiumProblem[] {
const out: TechnitiumProblem[] = [];
if (s.probe && !s.probe.ok && s.probeFailSince !== null && nowMs - Date.parse(s.probeFailSince) >= DNS_FAIL_AFTER_MS) {
out.push({ key: `technitium-dns:${id}`, severity: "critical", message: `${name}: DNS has not answered a question about ${s.probe.name} for ${ago(nowMs - Date.parse(s.probeFailSince))} (asked ${s.probe.host}:${s.dnsPort}) — ${s.probe.error ?? "no answer"}` });
}
if (!s.blockingEnabled && s.settings.blockLists.count > 0 && s.blockingOffSince !== null && nowMs - Date.parse(s.blockingOffSince) >= BLOCKING_OFF_AFTER_MS) {
out.push({ key: `technitium-blocking:${id}`, severity: "warning", message: `${name}: Technitium's blocking has been switched off for ${ago(nowMs - Date.parse(s.blockingOffSince))} — nothing is being blocked` });
}
const overdue = blockListsOverdueMs(s, nowMs);
if (overdue !== null) {
out.push({ key: `technitium-lists:${id}`, severity: "warning", message: `${name}: the block lists were due for an update ${ago(overdue)} ago and have not been updated` });
}
const issues = s.zones?.issues ?? [];
if (issues.length > 0) {
const expired = issues.some((i) => i.problem === "expired");
const names = issues.slice(0, 3).map((i) => `${i.name} (${i.problem})`);
out.push({
key: `technitium-zones:${id}`,
severity: expired ? "critical" : "warning",
message: `${name}: ${plural(issues.length, "zone")} ${issues.length === 1 ? "has" : "have"} a problem — ${names.join(", ")}${issues.length > 3 ? ` and ${issues.length - 3} more` : ""}${expired ? " (an expired secondary zone no longer answers)" : ""}`,
});
}
return out;
}
let timer: ReturnType<typeof setInterval> | null = null;
export function initTechnitiumSync(): void {
if (timer) return;
const pass = () => void syncAllTechnitium().catch((err) => console.error("[technitium] pass failed:", err));
timer = setInterval(pass, SYNC_INTERVAL_MS);
setTimeout(pass, 40_000);
console.log(`[technitium] reading Technitium DNS Server every ${SYNC_INTERVAL_MS / 60000} minutes`);
}