import { useEffect, useState } from "react"; import { Link, useSearchParams } from "react-router-dom"; import { api, type BackupCoverage, type CoverageGuest, type CoverageStatus, type CurrentUser, type RestoreInfo, type RestoreResult, type RestoreStatus, type RestoreTestEntry } from "../api/client"; import { confirmDialog } from "../utils/dialogs"; import { toast } from "../utils/toast"; import Pagination from "../components/Pagination"; import SortableTh from "../components/SortableTh"; import TableToolbar from "../components/TableToolbar"; import TimeAgo from "../components/TimeAgo"; import { ErrorNotice } from "../components/Notice"; import { BlockSkeleton } from "../components/Skeleton"; import { usePagination } from "../hooks/usePagination"; import { useSortable } from "../hooks/useSortable"; import { useTableSearch } from "../hooks/useTableSearch"; import { downloadCsv } from "../utils/csv"; import { readableError } from "../utils/errors"; interface Row extends CoverageGuest { /** Worst first, so a default sort puts what needs attention at the top. */ rank: number; } const RANK: Record = { failed: 0, none: 1, stale: 2, unknown: 3, ok: 4 }; const STATUS: Record = { ok: { label: "Recent backup", badge: "bg-green-lt text-green", hint: "Backed up within the limit, and nothing failed." }, stale: { label: "Stale", badge: "bg-yellow-lt text-yellow", hint: "Its newest backup is older than the limit." }, failed: { label: "Failed", badge: "bg-red-lt text-red", hint: "The latest backup didn't succeed, or the newest snapshot failed verification." }, none: { label: "No backup", badge: "bg-red-lt text-red", hint: "No backup found, and no backup job covers it." }, unknown: { label: "Unknown", badge: "bg-secondary-lt text-secondary", hint: "A backup job covers it, but nothing here says when it last ran — typical when backups go somewhere other than a Backup Server." }, }; const STALE_CHOICES = [1, 2, 3, 7, 14]; const RESTORE: Record = { never: { label: "Never tested", badge: "bg-secondary-lt text-secondary" }, ok: { label: "Restored fine", badge: "bg-green-lt text-green" }, partial: { label: "Partly worked", badge: "bg-yellow-lt text-yellow" }, failed: { label: "Restore failed", badge: "bg-red-lt text-red" }, stale: { label: "Test is old", badge: "bg-yellow-lt text-yellow" }, not_needed: { label: "No need to test", badge: "bg-secondary-lt text-secondary" }, }; const RESULT_WORDS: Record = { ok: "It restored and worked", partial: "It restored, but not everything worked", failed: "It failed", not_needed: "No need to test this one" }; interface TestDraft { /** A guest's key, or null for something that isn't a Proxmox guest. */ key: string | null; label: string; testedAt: string; result: RestoreResult; note: string; } const todayIso = () => new Date().toISOString().slice(0, 10); const ageWords = (r: RestoreInfo) => (r.ageDays === null ? "" : r.ageDays === 0 ? "today" : r.ageDays === 1 ? "yesterday" : `${r.ageDays} days ago`); /** * What is and isn't backed up: every Proxmox guest, whether a backup job covers it, when it was last backed up (from Proxmox Backup Server * snapshots and Proxmox's own backup tasks), and whether that went well — one page instead of an alert per gap. */ export default function Backups({ user }: { user?: CurrentUser }) { const canRecord = user?.role === "admin" || user?.role === "operator"; const isAdmin = user?.role === "admin"; const [tests, setTests] = useState(null); const [custom, setCustom] = useState<(RestoreInfo & { key: string; label: string })[]>([]); const [draft, setDraft] = useState(null); const [saving, setSaving] = useState(false); function loadTests() { api.backups .restoreTests() .then((res) => { setTests(res.tests); setCustom(res.custom); }) .catch(() => setTests([])); } useEffect(loadTests, []); async function saveTest(e: React.FormEvent) { e.preventDefault(); if (!draft) return; setSaving(true); try { await api.backups.recordRestoreTest({ key: draft.key ?? undefined, label: draft.label.trim(), testedAt: draft.testedAt, result: draft.result, note: draft.note.trim() || undefined }); toast.success("Recorded."); setDraft(null); loadTests(); load(); } catch (err) { setError(readableError(err)); } finally { setSaving(false); } } async function removeTest(t: RestoreTestEntry) { if (!(await confirmDialog({ title: "Remove a restore test", message: `Remove the test of "${t.label}" from ${t.testedAt}?`, confirmLabel: "Remove", danger: true }))) return; try { await api.backups.removeRestoreTest(t.id); loadTests(); load(); } catch (err) { setError(readableError(err)); } } const [params, setParams] = useSearchParams(); const staleParam = Number(params.get("stale")); const staleDays = STALE_CHOICES.includes(staleParam) ? staleParam : 2; const statusParam = params.get("status"); const status: CoverageStatus | "attention" | "" = statusParam === "attention" || (statusParam && statusParam in RANK) ? (statusParam as CoverageStatus | "attention") : ""; const [report, setReport] = useState(null); const [error, setError] = useState(null); const [checking, setChecking] = useState(false); function load(refresh = false) { setChecking(true); api.backups .coverage(staleDays, refresh) .then((r) => { setReport(r); setError(null); }) .catch((err) => setError(readableError(err))) .finally(() => setChecking(false)); } useEffect(() => load(), [staleDays]); function setParam(key: string, value: string | null) { setParams( (prev) => { const next = new URLSearchParams(prev); if (value) next.set(key, value); else next.delete(key); return next; }, { replace: true }, ); } const rows: Row[] = (report?.guests ?? []).map((g) => ({ ...g, rank: RANK[g.status] })); const shown = rows.filter((r) => (status === "" ? true : status === "attention" ? r.status === "failed" || r.status === "none" || r.status === "stale" : r.status === status)); const tableSearch = useTableSearch(shown); const { sorted, sortKey, sortDir, requestSort } = useSortable(tableSearch.filtered, "rank", "asc", { url: true }); const page = usePagination(sorted); const c = report?.counts; const trouble = (c?.failed ?? 0) + (c?.none ?? 0) + (c?.stale ?? 0); const badSources = (report?.sources ?? []).filter((s) => !s.ok); function exportCsv() { if (!sorted) return; downloadCsv( "backup-coverage.csv", ["Guest", "Type", "ID", "Node", "Cluster", "In a backup job", "Last backup", "Source", "Status", "Problem", "Restore test", "Tested on"], sorted.map((r) => [r.name, r.type === "qemu" ? "VM" : "Container", r.vmid, r.node, r.integrationName, r.inJob ? "yes" : "no", r.lastBackupAt ?? "", r.lastSource === "pbs" ? "Backup Server" : r.lastSource === "task" ? "Proxmox task" : "", STATUS[r.status].label, r.failure ?? "", r.restoreTest ? RESTORE[r.restoreTest.status].label : "", r.restoreTest?.testedAt ?? ""]), ); } const cards: { label: string; value: string | number; color: string; note?: string }[] = [ { label: "Guests", value: report ? (c?.total ?? 0) : "…", color: "" }, { label: "Recent backup", value: report ? (c?.ok ?? 0) : "…", color: "text-green" }, { label: "Failed", value: report ? (c?.failed ?? 0) : "…", color: (c?.failed ?? 0) > 0 ? "text-red" : "" }, { label: "No backup", value: report ? (c?.none ?? 0) : "…", color: (c?.none ?? 0) > 0 ? "text-red" : "" }, { label: "Stale", value: report ? (c?.stale ?? 0) : "…", color: (c?.stale ?? 0) > 0 ? "text-yellow" : "", note: `older than ${staleDays} ${staleDays === 1 ? "day" : "days"}` }, { label: "Unknown", value: report ? (c?.unknown ?? 0) : "…", color: "text-secondary", note: (c?.unknown ?? 0) > 0 ? "in a job, last run not visible" : undefined }, ]; return ( <>

Backup coverage

Every Proxmox guest: is a backup job covering it, when was it last backed up, and did that go well. {report && trouble > 0 ? `${trouble} need a look.` : ""}

{badSources.length > 0 && (
Couldn't read everything — what is missing below isn't necessarily wrong:{" "} {badSources.map((s) => `${s.kind === "pbs" ? "Backup Server" : "Proxmox"} “${s.name}” (${s.error})`).join("; ")}.
)}
{cards.map((card) => (
{card.value}
{card.label}
{card.note &&
{card.note}
}
))}
} shown={sorted?.length} total={rows.length} onExport={exportCsv} exportDisabled={!sorted || sorted.length === 0} />
label="Guest" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="In a job" sortKeyName="inJob" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Last backup" sortKeyName="lastBackupAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> label="Status" sortKeyName="rank" activeKey={sortKey} direction={sortDir} onSort={requestSort} /> {report === null && !error && ( )} {page.pageItems?.map((r) => ( ))} {report !== null && sorted?.length === 0 && ( )}
Restore test
{r.name}
{r.type === "qemu" ? "VM" : "Container"} {r.vmid} · {r.node} {report && report.sources.filter((s) => s.kind === "proxmox").length > 1 ? ` · ${r.integrationName}` : ""}
{r.server && (
is {r.server.name}
)}
{r.inJob ? yes : no} {r.lastBackupAt ? ( <>
{r.lastSource === "pbs" ? "Backup Server" : "Proxmox task"}
) : ( — )}
{STATUS[r.status].label} {r.failure &&
{r.failure}
}
{r.restoreTest && ( <> {RESTORE[r.restoreTest.status].label} {r.restoreTest.testedAt &&
{ageWords(r.restoreTest)}
} )} {canRecord && r.restoreKey && (
)}
{rows.length === 0 ? ( <> No Proxmox guests to show. Connect a Proxmox integration under Integrations. ) : ( "Nothing matches that." )}
“Last backup” is the newest snapshot of the guest on a Proxmox Backup Server, or the last successful Proxmox backup task that names it. A task from an “all guests” job doesn't name its guests, so a guest backed up to something other than a Backup Server reads “Unknown” rather than being guessed at. The result is kept for a minute; “Check now” asks again.
{draft && (

Record a restore test{draft.key ? ` of ${draft.label}` : ""}

{draft.key === null && (
setDraft({ ...draft, label: e.target.value })} />
)}
setDraft({ ...draft, testedAt: e.target.value })} />
setDraft({ ...draft, note: e.target.value })} />
)}

Restore tests

{canRecord && !draft && (
)}
A backup nobody has restored is a hope, not a backup. Record each time you try one — for a guest above, or for anything else (a share, a database). A failed test is raised on the Alerts page; under Settings → Notifications you can also ask to be reminded when a guest with backups hasn’t had one in a while{report?.restoreTestDays ? ` (now: ${report.restoreTestDays} days)` : ""}.
{custom.length > 0 && (
Other things being tracked
{custom.map((c) => ( {c.label} · {RESTORE[c.status].label.toLowerCase()} {ageWords(c)} ))}
)}
{isAdmin && } {tests === null && ( )} {tests?.map((t) => ( {isAdmin && ( )} ))} {tests !== null && tests.length === 0 && ( )}
Date What Result NoteActions
{t.testedAt} {t.label} {RESTORE[t.result].label} {t.note ?? "—"} {t.testedBy && · {t.testedBy}}
No restore has been recorded yet.{canRecord ? " After you next try one, record it here." : ""}
); }