Duplicati: know when a backup failed or has gone quiet

Duplicati reports each operation to a secret address (its own send-http-url option), so
nothing calls Duplicati and no password for it is kept. Each machine is a source; each job
is learned by name and shows its last result, duration, size, changes and a history.
A failed run is a warning (critical from the second in a row); one that has not succeeded
for longer than expected (per job, 2 days by default) is a warning, critical at three
times that. Maintenance on the machine's server silences them; /metrics series added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
bobbanandClaude Sonnet 5.5 committed 2026-10-24 21:36:13 +02:00
1 parent 12f2662465
commit 2f082ca5c2
23 files changed
+8047 -4

No files matched your search

+5 -1
View File
@@ -74,6 +74,7 @@ const SOURCES: Record<string, { label: string; link: string }> = {
homeassistant: { label: "Home Assistant", link: "/home-assistant" },
ups: { label: "UPS", link: "/ups" },
slo: { label: "Service level", link: "/service-levels" },
duplicati: { label: "Duplicati", link: "/duplicati" },
secrets: { label: "Secrets", link: "/secrets" },
domains: { label: "Domains", link: "/dns?view=domains" },
endpoint: { label: "Endpoint", link: "/endpoints" },
@@ -110,6 +111,8 @@ function originOfConditionKey(key: string): { type: string; id: number | null; c
if (m) return { type: "slo", id: Number(m[1]), category: "monitoring" };
m = /^container-(?:restarting|unhealthy|stopped|created|host):(\d+):/.exec(key);
if (m) return { type: "dockhand", id: Number(m[1]), category: "services" };
m = /^duplicati-(?:failed|stale):(\d+)/.exec(key);
if (m) return { type: "duplicati", id: Number(m[1]), category: "backup" };
return { type: "server", id: null, category: "disk" };
}
@@ -232,12 +235,13 @@ export async function collectAlerts(): Promise<AlertsReport> {
type: origin.type,
message: c.message,
key: c.key,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : c.key.startsWith("rule:") || c.key.startsWith("baseline:") ? "?view=history" : ""}` : origin.type === "unifi" ? "/network/devices" : origin.type === "ups" ? "/ups" : origin.type === "slo" ? "/service-levels" : origin.type === "dockhand" ? "/docker" : undefined,
link: origin.type === "server" && origin.id !== null ? `/servers/${origin.id}${/^(failed-units|smart|zfs):/.test(c.key) ? "?view=health" : c.key.startsWith("new-port:") ? "?view=network" : c.key.startsWith("rule:") || c.key.startsWith("baseline:") ? "?view=history" : ""}` : origin.type === "unifi" ? "/network/devices" : origin.type === "ups" ? "/ups" : origin.type === "slo" ? "/service-levels" : origin.type === "dockhand" ? "/docker" : origin.type === "duplicati" ? "/duplicati" : undefined,
silenced: subject !== null && subjects.has(subject), target: targetOfSubject(subject),
});
}
// Integrations the check couldn't read this time. (A whole-integration entry covers its nodes, so skip those.)
if (held.has("server:rules")) cannotCheck("Alert rules", "couldn't be judged — see the server log", "Server and storage health");
if (held.has("duplicati")) cannotCheck("Duplicati backups", "couldn't be judged — see the server log", "Server and storage health");
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) {
+11
View File
@@ -43,6 +43,7 @@ const KIND_OF_CATEGORY: Record<string, ChangeKind> = {
alert_rule: "alerts",
service_level: "endpoints",
away: "settings",
duplicati: "backups",
todo: "other",
note: "servers",
webhook: "settings",
@@ -183,6 +184,16 @@ export function describeChange(category: string, action: string, detail: Record<
return { title: detail.change === "undo" ? "A change to several pieces of hardware was undone" : `${typeof detail.changed === "number" ? detail.changed : "Several"} piece${detail.changed === 1 ? "" : "s"} of hardware changed at once`, tone: "neutral", detail: genericSummary(detail, ["ids", "changed", "change"]) };
case "webhook/retry":
return { title: `A webhook message was sent again${name ? `: ${name}` : str(detail.label) ? `: ${str(detail.label)}` : ""}`, tone: detail.ok === false ? "bad" : "neutral", detail: str(detail.event) };
case "duplicati/create_source":
return { title: `Duplicati machine added${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "duplicati/update_source":
return { title: `Duplicati machine changed${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "duplicati/delete_source":
return { title: `Duplicati machine removed${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "duplicati/update_backup":
return { title: `Duplicati backup changed${name ? `: ${name}` : ""}`, tone: "neutral", detail: genericSummary(detail) };
case "duplicati/forget_backup":
return { title: `Duplicati backup forgotten${name ? `: ${name}` : ""}`, tone: "neutral", detail: null };
case "away/start":
return { title: `Away mode started${str(detail.note) ? `: ${str(detail.note)}` : ""}`, tone: "neutral", detail: `until ${str(detail.until)?.slice(0, 16).replace("T", " ") ?? "?"} UTC${detail.criticalThrough ? ", critical alerts still sent" : ", everything held"}` };
case "away/end":
+261
View File
@@ -0,0 +1,261 @@
/**
* Duplicati: whether the backups it makes are being made. Duplicati can tell a URL how each operation went (its own "send-http-url" option, with the report as JSON), so this
* is the other way round from most of the app: nothing here calls Duplicati, no password for it is kept, and it works on every version. Each machine running Duplicati is a
* *source* with a secret address; each report on that address is read, the backup job it is about is learned by name, and what it says — how it ended, how long it took, how big
* the source was, what changed — is kept with a history.
*
* What makes an alert: a backup whose last run **failed** (Error or Fatal; critical from the second failure in a row), and one that has **not succeeded for longer than it is
* expected to** (a day or two by default, set per job; critical at three times that). A run that finished with warnings still counts as a backup. Only runs of the *Backup*
* operation count: a compact, a repair or a verification does not say whether the data is safe.
*/
import { createHash, randomBytes } from "node:crypto";
import { and, asc, desc, eq, lt, notInArray } from "drizzle-orm";
import { db } from "../db/client.js";
import { duplicatiBackups, duplicatiRuns, duplicatiSources } from "../db/schema.js";
export type SourceRow = typeof duplicatiSources.$inferSelect;
export type BackupRow = typeof duplicatiBackups.$inferSelect;
export const MAX_SOURCES = 50;
export const DEFAULT_EXPECTED_HOURS = 48;
export const KEEP_RUNS = 400;
export const KEEP_RUN_DAYS = 400;
const HOUR_MS = 3_600_000;
const DAY_MS = 86_400_000;
const hash = (token: string) => createHash("sha256").update(token).digest("hex");
// ─── Reading a report ───────────────────────────────────────────────────────
export interface ParsedReport {
operation: string;
/** Success, Warning, Error or Fatal (whatever Duplicati said, if it said something else). */
result: string;
backupName: string;
begin: string | null;
end: string | null;
durationSeconds: number | null;
examinedFiles: number | null;
sizeBytes: number | null;
addedFiles: number | null;
modifiedFiles: number | null;
deletedFiles: number | null;
warnings: number;
errors: number;
message: string | null;
}
/** "00:05:12.7" or "1.02:03:04" in seconds. */
export function parseDuration(text: unknown): number | null {
if (typeof text !== "string") return null;
const m = /^(?:(\d+)\.)?(\d+):(\d{2}):(\d{2})(?:\.\d+)?$/.exec(text.trim());
return m ? Number(m[1] ?? 0) * 86_400 + Number(m[2]) * 3600 + Number(m[3]) * 60 + Number(m[4]) : null;
}
const asInt = (v: unknown): number | null => {
const n = typeof v === "string" ? Number(v.replace(/,/g, "")) : v;
return typeof n === "number" && Number.isFinite(n) ? Math.round(n) : null;
};
const asIso = (v: unknown): string | null => {
if (typeof v !== "string") return null;
const t = Date.parse(v);
return Number.isFinite(t) ? new Date(t).toISOString() : null;
};
const obj = (v: unknown): Record<string, unknown> => (v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {});
const lineOf = (v: unknown): string | null => {
const text = typeof v === "string" ? v : v !== null && typeof v === "object" ? JSON.stringify(v) : null;
return text ? text.replace(/\s+/g, " ").trim().slice(0, 300) : null;
};
/**
* Pure: the report Duplicati sent — JSON (`send-http-result-output-format=Json`: the results at the top, or under `Data`, with the job's name among `Extra`), or the plain text it sends
* by default ("ParsedResult: Success" lines). Null when it is neither. Read defensively; the exact fields have not been checked against every Duplicati version.
*/
export function parseReport(body: unknown): ParsedReport | null {
let payload: Record<string, unknown> | null = null;
if (typeof body === "string") {
const trimmed = body.trim();
if (trimmed.startsWith("{")) {
try {
payload = obj(JSON.parse(trimmed));
} catch {
payload = null;
}
} else return parseText(trimmed);
} else payload = obj(body);
if (!payload || Object.keys(payload).length === 0) return null;
const data = Object.keys(obj(payload.Data)).length > 0 ? obj(payload.Data) : payload;
const extra = { ...obj(payload.Extra), ...obj(data.Extra) };
const result = typeof data.ParsedResult === "string" ? data.ParsedResult : null;
if (!result) return null;
const list = (v: unknown) => (Array.isArray(v) ? v : []);
const warnings = list(data.Warnings);
const errors = list(data.Errors);
const named = [extra["backup-name"], extra.backupName, extra.BackupName, data.BackupName].find((n) => typeof n === "string" && n.trim() !== "");
return {
operation: String(data.MainOperation ?? extra.OperationName ?? extra.operationname ?? extra.operation ?? "Backup"),
result,
backupName: typeof named === "string" ? named.trim().slice(0, 100) : typeof extra["backup-id"] === "string" ? `Backup ${extra["backup-id"]}`.slice(0, 100) : "Unnamed backup",
begin: asIso(data.BeginTime),
end: asIso(data.EndTime),
durationSeconds: parseDuration(data.Duration),
examinedFiles: asInt(data.ExaminedFiles),
sizeBytes: asInt(data.SizeOfExaminedFiles),
addedFiles: asInt(data.AddedFiles),
modifiedFiles: asInt(data.ModifiedFiles),
deletedFiles: asInt(data.DeletedFiles),
warnings: asInt(data.WarningsActualLength) ?? warnings.length,
errors: asInt(data.ErrorsActualLength) ?? errors.length,
message: lineOf(errors[0]) ?? lineOf(warnings[0]),
};
}
function parseText(text: string): ParsedReport | null {
const value = (key: string) => new RegExp(`^\\s*${key}\\s*:\\s*(.+?)\\s*$`, "im").exec(text)?.[1] ?? null;
const result = value("ParsedResult");
if (!result) return null;
const name = value("backup-name");
return {
operation: value("MainOperation") ?? value("OperationName") ?? "Backup",
result,
backupName: name ? name.slice(0, 100) : "Unnamed backup",
begin: null,
end: null,
durationSeconds: parseDuration(value("Duration")),
examinedFiles: asInt(value("ExaminedFiles")?.match(/^[\d,]+/)?.[0]),
sizeBytes: asInt(value("SizeOfExaminedFiles")?.match(/^[\d,]+/)?.[0]),
addedFiles: asInt(value("AddedFiles")?.match(/^[\d,]+/)?.[0]),
modifiedFiles: asInt(value("ModifiedFiles")?.match(/^[\d,]+/)?.[0]),
deletedFiles: asInt(value("DeletedFiles")?.match(/^[\d,]+/)?.[0]),
warnings: asInt(value("WarningsActualLength")?.match(/^[\d,]+/)?.[0]) ?? 0,
errors: asInt(value("ErrorsActualLength")?.match(/^[\d,]+/)?.[0]) ?? 0,
message: null,
};
}
const isGood = (result: string) => /^(success|warning)$/i.test(result);
// ─── What a report does ────────────────────────────────────────────────────
/** Makes a source and its secret address; the secret is shown once, and only its hash is kept. */
export async function createSource(params: { name: string; serverId: number | null; createdBy: string }): Promise<{ row: SourceRow; token: string }> {
const token = `hlm_d_${randomBytes(24).toString("base64url")}`;
const [row] = await db.insert(duplicatiSources).values({ name: params.name, tokenHash: hash(token), tokenPrefix: token.slice(0, 12), serverId: params.serverId, createdBy: params.createdBy }).returning();
return { row, token };
}
export async function sourceForToken(token: string): Promise<SourceRow | null> {
if (typeof token !== "string" || token.length < 20 || token.length > 128) return null;
return (await db.select().from(duplicatiSources).where(eq(duplicatiSources.tokenHash, hash(token))).limit(1))[0] ?? null;
}
export type RecordOutcome = { recorded: true; backupId: number; result: string } | { recorded: false; reason: "unknown_token" | "unreadable" | "not_a_backup" };
/** Reads a report that arrived on a secret address and writes it down. Other operations than a backup are said to have been seen and set aside. */
export async function recordReport(token: string, body: unknown, now: Date = new Date()): Promise<RecordOutcome> {
const source = await sourceForToken(token);
if (!source) return { recorded: false, reason: "unknown_token" };
const nowIso = now.toISOString();
await db.update(duplicatiSources).set({ lastReportAt: nowIso }).where(eq(duplicatiSources.id, source.id));
const report = parseReport(body);
if (!report) return { recorded: false, reason: "unreadable" };
if (!/^backup$/i.test(report.operation)) return { recorded: false, reason: "not_a_backup" };
const [before] = await db.select().from(duplicatiBackups).where(and(eq(duplicatiBackups.sourceId, source.id), eq(duplicatiBackups.name, report.backupName))).limit(1);
const good = isGood(report.result);
const at = report.end ?? nowIso;
const values = {
lastReportAt: nowIso,
lastResult: report.result,
lastBegin: report.begin,
lastEnd: report.end,
durationSeconds: report.durationSeconds,
examinedFiles: report.examinedFiles,
sizeBytes: report.sizeBytes,
addedFiles: report.addedFiles,
modifiedFiles: report.modifiedFiles,
deletedFiles: report.deletedFiles,
warnings: report.warnings,
errors: report.errors,
message: report.message,
lastSuccessAt: good ? at : (before?.lastSuccessAt ?? null),
consecutiveFailures: good ? 0 : (before?.consecutiveFailures ?? 0) + 1,
};
let id: number;
if (before) {
await db.update(duplicatiBackups).set(values).where(eq(duplicatiBackups.id, before.id));
id = before.id;
} else {
id = (await db.insert(duplicatiBackups).values({ sourceId: source.id, name: report.backupName, ...values }).returning({ id: duplicatiBackups.id }))[0].id;
}
const changed = (report.addedFiles ?? 0) + (report.modifiedFiles ?? 0) + (report.deletedFiles ?? 0);
await db.insert(duplicatiRuns).values({ backupId: id, at, result: report.result, durationSeconds: report.durationSeconds, sizeBytes: report.sizeBytes, filesChanged: report.addedFiles === null && report.modifiedFiles === null && report.deletedFiles === null ? null : changed, warnings: report.warnings, errors: report.errors });
await pruneRuns(id, now);
return { recorded: true, backupId: id, result: report.result };
}
async function pruneRuns(backupId: number, now: Date): Promise<void> {
await db.delete(duplicatiRuns).where(and(eq(duplicatiRuns.backupId, backupId), lt(duplicatiRuns.at, new Date(now.getTime() - KEEP_RUN_DAYS * DAY_MS).toISOString())));
const keep = await db.select({ id: duplicatiRuns.id }).from(duplicatiRuns).where(eq(duplicatiRuns.backupId, backupId)).orderBy(desc(duplicatiRuns.at), desc(duplicatiRuns.id)).limit(KEEP_RUNS);
if (keep.length === KEEP_RUNS) await db.delete(duplicatiRuns).where(and(eq(duplicatiRuns.backupId, backupId), notInArray(duplicatiRuns.id, keep.map((k) => k.id))));
}
// ─── Where a backup stands ──────────────────────────────────────────────────
export type BackupState = "ok" | "warning" | "failed" | "stale";
/** Pure: where a backup stands. A failed last run is "failed"; one that has not succeeded for longer than expected is "stale"; one with warnings is "warning". */
export function backupState(b: Pick<BackupRow, "lastResult" | "lastSuccessAt" | "expectedHours" | "createdAt">, nowMs: number): BackupState {
if (b.lastResult && !isGood(b.lastResult)) return "failed";
const since = b.lastSuccessAt ? Date.parse(b.lastSuccessAt) : NaN;
if (Number.isFinite(since) && nowMs - since > b.expectedHours * HOUR_MS) return "stale";
return b.lastResult && /^warning$/i.test(b.lastResult) ? "warning" : "ok";
}
const ago = (ms: number) => {
const h = Math.floor(ms / HOUR_MS);
return h < 1 ? "less than an hour" : h < 48 ? `${h} h` : `${Math.floor(h / 24)} days`;
};
export interface DuplicatiProblem {
key: string;
kind: "failed" | "stale";
severity: "critical" | "warning";
message: string;
}
/** Pure: what is wrong with the backups, for those that are to alert. The key carries the server a source runs on, so maintenance on it silences them. */
export function duplicatiProblems(sources: Pick<SourceRow, "id" | "name" | "serverId">[], backups: BackupRow[], nowMs: number): DuplicatiProblem[] {
const byId = new Map(sources.map((s) => [s.id, s]));
const out: DuplicatiProblem[] = [];
for (const b of backups) {
const source = byId.get(b.sourceId);
if (!source || !b.alert) continue;
const suffix = source.serverId !== null ? `:server:${source.serverId}` : "";
const state = backupState(b, nowMs);
const lastGood = b.lastSuccessAt ? `the last good one was ${ago(nowMs - Date.parse(b.lastSuccessAt))} ago` : "there has been no good one yet";
if (state === "failed") {
out.push({ key: `duplicati-failed:${b.id}${suffix}`, kind: "failed", severity: b.consecutiveFailures >= 2 ? "critical" : "warning", message: `The backup “${b.name}” on ${source.name} failed${b.message ? `: ${b.message}` : ""} (${lastGood})` });
} else if (state === "stale") {
const left = nowMs - Date.parse(b.lastSuccessAt as string);
out.push({ key: `duplicati-stale:${b.id}${suffix}`, kind: "stale", severity: left > 3 * b.expectedHours * HOUR_MS ? "critical" : "warning", message: `The backup “${b.name}” on ${source.name} hasn't succeeded for ${ago(left)} — it should run at least every ${b.expectedHours >= 48 && b.expectedHours % 24 === 0 ? `${b.expectedHours / 24} days` : `${b.expectedHours} h`}` });
}
}
return out;
}
export async function listAll(): Promise<{ sources: SourceRow[]; backups: BackupRow[] }> {
const [sources, backups] = await Promise.all([db.select().from(duplicatiSources).orderBy(asc(duplicatiSources.name)), db.select().from(duplicatiBackups).orderBy(asc(duplicatiBackups.name))]);
return { sources, backups };
}
/** What is wrong with the backups right now, from what is stored. */
export async function currentProblems(nowMs: number = Date.now()): Promise<DuplicatiProblem[]> {
const { sources, backups } = await listAll();
return sources.length === 0 ? [] : duplicatiProblems(sources, backups, nowMs);
}
/** A source as lists show it: everything but the hash. */
export function publicSource(row: SourceRow) {
return { id: row.id, name: row.name, tokenPrefix: row.tokenPrefix, serverId: row.serverId, createdBy: row.createdBy, createdAt: row.createdAt, lastReportAt: row.lastReportAt };
}
+14
View File
@@ -19,6 +19,7 @@ import { computeRuleFindings, findingKey, listRules, type RuleFinding } from "./
import { baselineKey, computeBaselineFindings, type BaselineFinding } from "./baselines.js";
import { levelFindings, levelKey, type LevelFinding } from "./serviceLevels.js";
import { createDockhandAdapter } from "../integrations/dockhand/adapter.js";
import { currentProblems as duplicatiProblemsNow, type DuplicatiProblem } from "./duplicati.js";
import { evaluateContainers, loadContainerMemory, saveContainerMemory, type ContainerMemory, type DockerSnapshot } from "./containerHealth.js";
import { recordStorageSamples } from "./storageHistory.js";
import { isUpsFresh, upsProblems, upsSyncStatuses, type UpsStateRow } from "./upsSync.js";
@@ -86,6 +87,8 @@ export interface HealthSnapshot {
baselines?: BaselineFinding[];
/** Service-level targets whose error budget for the month is mostly or wholly used (services/serviceLevels.ts). */
levels?: LevelFinding[];
/** Duplicati backups that failed or have not succeeded in time (services/duplicati.ts). */
duplicati?: DuplicatiProblem[];
/** Each Docker integration's containers as last read, with what was remembered of them (services/containerHealth.ts). */
docker?: DockerSnapshot[];
dockerMemory?: ContainerMemory;
@@ -195,6 +198,9 @@ export function evaluateHealth(snapshot: HealthSnapshot, thresholds: Thresholds,
}
}
// Duplicati backups that failed, or have not succeeded for longer than they should.
for (const p of snapshot.duplicati ?? []) out.push({ key: p.key, source: "duplicati", message: p.message, severity: p.severity });
// Containers that are broken, stopped unexpectedly or never started, and Docker hosts that cannot be reached.
if (snapshot.docker && snapshot.docker.length > 0) {
for (const c of evaluateContainers(snapshot.docker, snapshot.dockerMemory ?? {}, snapshot.dockerNow ?? now, snapshot.dockerIgnore ?? []).conditions) out.push(c);
@@ -422,6 +428,14 @@ export async function collectSnapshot(): Promise<{ snapshot: HealthSnapshot; hel
}
}
// Duplicati: what its reports say, read from what is stored (nothing is asked of Duplicati). A failure here costs only this check.
try {
snapshot.duplicati = await duplicatiProblemsNow(Date.now());
} catch (err) {
console.error("[health] couldn't judge the Duplicati backups:", err instanceof Error ? err.message : err);
held.add("duplicati");
}
// Docker containers, from Dockhand: what is broken, what stopped unexpectedly. A Dockhand that cannot be read holds its containers' alerts rather than clearing them.
if (checks.containerAlerts) {
snapshot.dockerIgnore = checks.containerIgnore;
+2
View File
@@ -31,6 +31,8 @@ export function subjectOfConditionKey(key: string): string | null {
if (m) return `server:${m[1]}`;
m = /^container-(?:restarting|unhealthy|stopped|created|host):(\d+):/.exec(key);
if (m) return `integration:${m[1]}`;
m = /^duplicati-(?:failed|stale):\d+:server:(\d+)$/.exec(key);
if (m) return `server:${m[1]}`;
m = /^(?:endpoint(?:-cert)?|heartbeat(?:-fail)?):\d+:server:(\d+)$/.exec(key);
if (m) return `server:${m[1]}`;
m = /^offline:device:(\d+)$/.exec(key);
+15
View File
@@ -8,6 +8,7 @@ import { db } from "../db/client.js";
import { assets, endpointChecks, heartbeats, integrations, maintenanceWindows, secrets, servers, upsState } from "../db/schema.js";
import { isUpsFresh, upsSyncStatuses } from "./upsSync.js";
import { levelStatuses } from "./serviceLevels.js";
import { backupState, listAll as listDuplicati } from "./duplicati.js";
import { latestTests } from "./restoreTests.js";
import { heartbeatState, parseStamp } from "./heartbeats.js";
import { env } from "../env.js";
@@ -59,6 +60,19 @@ class Exposition {
}
}
/** Each Duplicati backup, for /metrics: whether it is in order, how long since it last succeeded, and how big what it backs up is. */
async function addDuplicatiMetrics(out: Exposition, now: Date) {
const { sources, backups } = await listDuplicati();
const names = new Map(sources.map((s) => [s.id, s.name]));
for (const b of backups) {
const labels = { backup: b.name, source: names.get(b.sourceId) ?? "" };
const state = backupState(b, now.getTime());
out.add("homelab_duplicati_backup_ok", "gauge", "1 if the Duplicati backup's last run worked and it is not overdue, else 0.", state === "ok" || state === "warning" ? 1 : 0, labels);
if (b.lastSuccessAt) out.add("homelab_duplicati_last_success_age_seconds", "gauge", "Seconds since the Duplicati backup last succeeded (a run with warnings counts).", Math.max(0, Math.round((now.getTime() - Date.parse(b.lastSuccessAt)) / 1000)), labels);
if (b.sizeBytes !== null) out.add("homelab_duplicati_source_size_bytes", "gauge", "The size of what the Duplicati backup examined, as its last report said.", b.sizeBytes, labels);
}
}
/** Each service-level target, for /metrics: its target, how it is doing this month and how much error budget is left. */
async function addServiceLevelMetrics(out: Exposition, now: Date) {
for (const s of await levelStatuses(now, { history: false })) {
@@ -252,6 +266,7 @@ export async function buildMetrics(now: Date = new Date()): Promise<string> {
await addEndpointMetrics(out, now);
await addUpsMetrics(out, now);
await addServiceLevelMetrics(out, now);
await addDuplicatiMetrics(out, now);
await addHeartbeatMetrics(out, now);
return out.toString();
}