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:
1 parent
e4cd01e9ba
commit
312093d3f7
24 files changed
+10189
-7
No files matched your search
@@ -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");
|
||||
|
||||
@@ -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)));
|
||||
|
||||
@@ -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"] },
|
||||
];
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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`);
|
||||
}
|
||||
Reference in new issue
Block a user