Files
Homelab-manager/web/src/pages/Backups.tsx
T
bobbanandClaude Sonnet 5.5 07ce2b0305 Put Backup coverage and Proxmox Backup Server on one page, in two tabs
Backups → Proxmox backups has a Backup coverage tab and a Proxmox Backup
Server tab (?view=pbs), each keeping its own title and buttons. /pbs redirects
to the second tab so old links and favourites still work; the sidebar's two
entries become one, and the Backup Server's alert and integration links go
to the tab. Docs updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-03 20:19:24 +01:00

445 lines
21 KiB
TypeScript

import { removeWithUndo } from "../utils/undoable";
import { useEffect, useState, type ReactNode } 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 { 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";
import { EmptyRow } from "../components/EmptyState";
interface Row extends CoverageGuest {
/** Worst first, so a default sort puts what needs attention at the top. */
rank: number;
}
const RANK: Record<CoverageStatus, number> = { failed: 0, none: 1, stale: 2, unknown: 3, ok: 4 };
const STATUS: Record<CoverageStatus, { label: string; badge: string; hint: string }> = {
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<RestoreStatus, { label: string; badge: string }> = {
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<RestoreResult, string> = { 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, tabs }: { user?: CurrentUser; /** The tabs of the page this is one view of (see BackupsHub), shown under the title. */ tabs?: ReactNode }) {
const canRecord = user?.role === "admin" || user?.role === "operator";
const isAdmin = user?.role === "admin";
const [tests, setTests] = useState<RestoreTestEntry[] | null>(null);
const [custom, setCustom] = useState<(RestoreInfo & { key: string; label: string })[]>([]);
const [draft, setDraft] = useState<TestDraft | null>(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) {
await removeWithUndo({
remove: () => api.backups.removeRestoreTest(t.id),
restore: () => api.backups.recordRestoreTest({ key: t.subjectKey, label: t.label, testedAt: t.testedAt, result: t.result, note: t.note ?? undefined }),
message: `Removed the test of "${t.label}" from ${t.testedAt}.`,
reload: () => {
loadTests();
load();
},
onError: setError,
});
}
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<BackupCoverage | null>(null);
const [error, setError] = useState<string | null>(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 (
<>
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
<h2 className="page-title mb-0">Backup coverage</h2>
<button className="btn btn-outline-secondary ms-auto" onClick={() => load(true)} disabled={checking}>
{checking ? "Checking…" : "Check now"}
</button>
</div>
{tabs}
<p className="text-secondary">
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.` : ""}
</p>
<ErrorNotice error={error} />
{badSources.length > 0 && (
<div className="alert alert-warning">
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("; ")}.
</div>
)}
<div className="row row-cards mb-3">
{cards.map((card) => (
<div className="col-6 col-lg-2" key={card.label}>
<div className="card card-sm">
<div className="card-body">
<div className={`h2 mb-0 ${card.color}`}>{card.value}</div>
<div className="text-secondary">{card.label}</div>
{card.note && <div className="text-secondary small">{card.note}</div>}
</div>
</div>
</div>
))}
</div>
<div className="card">
<TableToolbar
search={tableSearch.query}
onSearch={tableSearch.setQuery}
placeholder="Search guests…"
filters={
<>
<select className="form-select form-select-sm w-auto" aria-label="Show guests that are" value={status} onChange={(e) => setParam("status", e.target.value)}>
<option value="">All guests</option>
<option value="attention">Needing attention</option>
{(Object.keys(RANK) as CoverageStatus[]).map((s) => (
<option key={s} value={s}>
{STATUS[s].label}
</option>
))}
</select>
<select className="form-select form-select-sm w-auto" aria-label="Stale after" value={staleDays} onChange={(e) => setParam("stale", e.target.value === "2" ? null : e.target.value)}>
{STALE_CHOICES.map((d) => (
<option key={d} value={d}>
Stale after {d} {d === 1 ? "day" : "days"}
</option>
))}
</select>
</>
}
shown={sorted?.length}
total={rows.length}
onExport={exportCsv}
exportDisabled={!sorted || sorted.length === 0}
/>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<Row> label="Guest" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="In a job" sortKeyName="inJob" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Last backup" sortKeyName="lastBackupAt" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<Row> label="Status" sortKeyName="rank" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<th>Restore test</th>
</tr>
</thead>
<tbody>
{report === null && !error && (
<tr>
<td colSpan={5}>
<BlockSkeleton lines={4} />
</td>
</tr>
)}
{page.pageItems?.map((r) => (
<tr key={`${r.integrationId}:${r.type}:${r.vmid}`}>
<td>
{r.name}
<div className="text-secondary small">
{r.type === "qemu" ? "VM" : "Container"} {r.vmid} · {r.node}
{report && report.sources.filter((s) => s.kind === "proxmox").length > 1 ? ` · ${r.integrationName}` : ""}
</div>
{r.server && (
<div className="small">
is <Link to={`/servers/${r.server.id}`}>{r.server.name}</Link>
</div>
)}
</td>
<td>{r.inJob ? <span className="text-green">yes</span> : <span className="text-red">no</span>}</td>
<td>
{r.lastBackupAt ? (
<>
<TimeAgo value={r.lastBackupAt} />
<div className="text-secondary small">{r.lastSource === "pbs" ? "Backup Server" : "Proxmox task"}</div>
</>
) : (
<span className="text-secondary">—</span>
)}
</td>
<td>
<span className={`badge ${STATUS[r.status].badge}`} title={STATUS[r.status].hint}>
{STATUS[r.status].label}
</span>
{r.failure && <div className="text-secondary small">{r.failure}</div>}
</td>
<td>
{r.restoreTest && (
<>
<span className={`badge ${RESTORE[r.restoreTest.status].badge}`} title={r.restoreTest.note ?? undefined}>
{RESTORE[r.restoreTest.status].label}
</span>
{r.restoreTest.testedAt && <div className="text-secondary small">{ageWords(r.restoreTest)}</div>}
</>
)}
{canRecord && r.restoreKey && (
<div>
<button type="button" className="btn btn-link btn-sm p-0" onClick={() => setDraft({ key: r.restoreKey!, label: r.name, testedAt: todayIso(), result: "ok", note: "" })}>
Record a test
</button>
</div>
)}
</td>
</tr>
))}
{report !== null && sorted?.length === 0 && (
<EmptyRow colSpan={5} {...(rows.length === 0 ? { title: "No Proxmox guests to show", hint: "Connect a Proxmox integration and its virtual machines and containers appear here, with when each was last backed up.", action: { label: "Connect Proxmox", to: "/integrations" } } : { filtered: () => { tableSearch.setQuery(""); setParam("status", null); } })} />
)}
</tbody>
</table>
</div>
<Pagination page={page.page} pageCount={page.pageCount} totalCount={page.totalCount} onPageChange={page.setPage} />
<div className="card-footer text-secondary small">
“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.
</div>
</div>
{draft && (
<form className="card mt-3" onSubmit={saveTest}>
<div className="card-header">
<h3 className="card-title">Record a restore test{draft.key ? ` of ${draft.label}` : ""}</h3>
</div>
<div className="card-body row g-3">
{draft.key === null && (
<div className="col-md-5">
<label className="form-label" htmlFor="rt-label">
What was restored
</label>
<input id="rt-label" className="form-control" required maxLength={120} placeholder="e.g. Photos share, Gitea database" value={draft.label} onChange={(e) => setDraft({ ...draft, label: e.target.value })} />
</div>
)}
<div className="col-md-3">
<label className="form-label" htmlFor="rt-date">
On
</label>
<input id="rt-date" type="date" className="form-control" required max={todayIso()} value={draft.testedAt} onChange={(e) => setDraft({ ...draft, testedAt: e.target.value })} />
</div>
<div className="col-md-4">
<label className="form-label" htmlFor="rt-result">
How it went
</label>
<select id="rt-result" className="form-select" value={draft.result} onChange={(e) => setDraft({ ...draft, result: e.target.value as RestoreResult })}>
{(Object.keys(RESULT_WORDS) as RestoreResult[]).map((r) => (
<option key={r} value={r}>
{RESULT_WORDS[r]}
</option>
))}
</select>
</div>
<div className="col-12">
<label className="form-label" htmlFor="rt-note">
Note (optional)
</label>
<input id="rt-note" className="form-control" maxLength={500} placeholder="e.g. restored to a scratch VM, booted, the database was there" value={draft.note} onChange={(e) => setDraft({ ...draft, note: e.target.value })} />
</div>
</div>
<div className="card-footer d-flex gap-2">
<button type="submit" className="btn btn-primary" disabled={saving || draft.label.trim() === ""}>
{saving ? "Saving…" : "Record it"}
</button>
<button type="button" className="btn" onClick={() => setDraft(null)}>
Cancel
</button>
</div>
</form>
)}
<div className="card mt-3">
<div className="card-header">
<h3 className="card-title">Restore tests</h3>
{canRecord && !draft && (
<div className="card-actions">
<button className="btn btn-sm" onClick={() => setDraft({ key: null, label: "", testedAt: todayIso(), result: "ok", note: "" })}>
Record a test of something else
</button>
</div>
)}
</div>
<div className="card-body text-secondary small pb-0">
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&rsquo;t had one in a while{report?.restoreTestDays ? ` (now: ${report.restoreTestDays} days)` : ""}.
</div>
{custom.length > 0 && (
<div className="card-body pb-0">
<div className="text-secondary small mb-1">Other things being tracked</div>
<div className="d-flex flex-wrap gap-2">
{custom.map((c) => (
<span key={c.key} className={`badge ${RESTORE[c.status].badge}`}>
{c.label} · {RESTORE[c.status].label.toLowerCase()} {ageWords(c)}
</span>
))}
</div>
</div>
)}
<div className="table-responsive">
<table className="table table-vcenter card-table table-stack">
<thead>
<tr>
<th>Date</th>
<th>What</th>
<th>Result</th>
<th>Note</th>
{isAdmin && <th className="w-1">Actions</th>}
</tr>
</thead>
<tbody>
{tests === null && (
<tr>
<td colSpan={isAdmin ? 5 : 4}>
<BlockSkeleton lines={2} />
</td>
</tr>
)}
{tests?.map((t) => (
<tr key={t.id}>
<td className="stack-label" data-label="Date">{t.testedAt}</td>
<td>{t.label}</td>
<td>
<span className={`badge ${RESTORE[t.result].badge}`}>{RESTORE[t.result].label}</span>
</td>
<td className="text-secondary stack-wide">
{t.note ?? "—"}
{t.testedBy && <span className="small"> · {t.testedBy}</span>}
</td>
{isAdmin && (
<td className="stack-wide">
<button className="btn btn-sm btn-outline-danger" onClick={() => void removeTest(t)}>
Remove
</button>
</td>
)}
</tr>
))}
{tests !== null && tests.length === 0 && (
<EmptyRow colSpan={isAdmin ? 5 : 4} title="No restore recorded yet" hint="A backup nobody has restored is a hope, not a backup. Try restoring one — to a scratch machine is fine — and record how it went." action={canRecord ? { label: "Record a test", onClick: () => setDraft({ key: null, label: "", testedAt: todayIso(), result: "ok", note: "" }) } : undefined} />
)}
</tbody>
</table>
</div>
</div>
</>
);
}