Files
Homelab-manager/web/src/pages/PbsBackup.tsx
T
bobbanandClaude Sonnet 5.5 645816d5a8 Add a Swedish interface with a per-person language switch
A small translation system (the English text is its own key, so anything
without a Swedish entry stays English) and a Language switch in the user menu,
saved on the account (users.language) and following the browser when no choice
has been made. Swedish covers the menu, shared parts (search, tables, dialogs,
relative times), the sign-in page and the everyday pages: Dashboard, Alerts,
Servers, Updates, Maintenance, My work, Coming up, To do, Integrations and the
display settings. Server-written messages stay English for now.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-12 21:49:49 +01:00

338 lines
14 KiB
TypeScript

import { useEffect, useState, type ReactNode } from "react";
import { Link } from "react-router-dom";
import {
api,
type CurrentUser,
type IntegrationSummary,
type PbsDatastore,
type PbsDatastoresResponse,
type PbsNodeStatus,
} from "../api/client";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import { formatDateTime } from "../utils/date";
import { downloadCsv } from "../utils/csv";
import IntegrationPageTitle from "../components/IntegrationPageTitle";
import { ErrorNotice } from "../components/Notice";
import ExportTableButton from "../components/ExportTableButton";
import { EmptyRow } from "../components/EmptyState";
import { t } from "../i18n";
function formatBytes(bytes: number | null): string {
if (bytes === null) return "—";
const units = ["B", "KB", "MB", "GB", "TB", "PB"];
let value = bytes;
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit++;
}
return `${value.toFixed(1)} ${units[unit]}`;
}
function formatDate(unixSeconds: number | null): string {
if (unixSeconds === null) return "—";
return formatDateTime(new Date(unixSeconds * 1000));
}
function formatUptime(seconds: number | null): string {
if (seconds === null) return "—";
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const parts: string[] = [];
if (days) parts.push(`${days}d`);
if (days || hours) parts.push(`${hours}h`);
parts.push(`${minutes}m`);
return parts.join(" ");
}
function verificationBadge(d: PbsDatastore) {
if (d.error) return <span className="badge bg-red-lt text-red">Unreadable</span>;
if (d.failedCount > 0) return <span className="badge bg-red-lt text-red">{d.failedCount} failed</span>;
if (d.unverifiedCount > 0) return <span className="badge bg-yellow-lt text-yellow">{d.unverifiedCount} unverified</span>;
return <span className="badge bg-green-lt text-green">All verified</span>;
}
export default function PbsBackup({ user: _user, tabs }: { user: CurrentUser; /** The tabs of the page this is one view of (see BackupsHub), shown under the title. */ tabs?: ReactNode }) {
const [integrations, setIntegrations] = useState<IntegrationSummary[] | null>(null);
const [selectedId, setSelectedId] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null);
const [data, setData] = useState<PbsDatastoresResponse | null>(null);
const [loading, setLoading] = useState(false);
const [status, setStatus] = useState<PbsNodeStatus | null>(null);
const [statusError, setStatusError] = useState<string | null>(null);
const [loadingStatus, setLoadingStatus] = useState(false);
useEffect(() => {
api.integrations
.list()
.then((res) => {
const pbsIntegrations = res.integrations.filter((i) => i.type === "pbs");
setIntegrations(pbsIntegrations);
if (!selectedId && pbsIntegrations.length > 0) setSelectedId(pbsIntegrations[0].id);
})
.catch((err) => setError(err instanceof Error ? err.message : String(err)));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const selected = integrations?.find((i) => i.id === selectedId) ?? null;
function loadDatastores(id: number) {
setLoading(true);
setError(null);
api.integrations.pbs
.datastores(id)
.then((res) => setData(res))
.catch((err) => setError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoading(false));
}
function loadStatus(id: number) {
setLoadingStatus(true);
setStatusError(null);
api.integrations.pbs
.status(id)
.then((res) => setStatus(res))
.catch((err) => setStatusError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoadingStatus(false));
}
useEffect(() => {
if (selected?.enabled) {
loadDatastores(selected.id);
loadStatus(selected.id);
} else {
setData(null);
setStatus(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedId]);
const { sorted: sortedDatastores, sortKey, sortDir, requestSort } = useSortable(data?.datastores);
function exportCsv() {
if (!sortedDatastores) return;
downloadCsv(
"pbs-datastores.csv",
["Datastore", "Used", "Total", "Snapshots", "Failed", "Unverified", "Latest snapshot"],
sortedDatastores.map((d) => [
d.name,
formatBytes(d.usedBytes),
formatBytes(d.totalBytes),
d.snapshotCount,
d.failedCount,
d.unverifiedCount,
formatDate(d.latestSnapshotAt),
]),
);
}
return (
<>
<IntegrationPageTitle title="Proxmox Backup Server" integration={selected} />
{tabs}
<ErrorNotice error={error} />
{integrations?.length === 0 ? (
<div className="card">
<div className="card-body text-secondary">
No Proxmox Backup Server integration configured yet. <Link to="/integrations">Add one under Integrations</Link>.
</div>
</div>
) : (
<>
{integrations && integrations.length > 1 && (
<div className="mb-3" style={{ maxWidth: 320 }}>
<select
className="form-select"
value={selectedId ?? ""}
onChange={(e) => setSelectedId(Number(e.target.value))}
>
{integrations.map((i) => (
<option key={i.id} value={i.id} disabled={!i.enabled}>
{i.name}
{!i.enabled ? " — disabled" : ""}
</option>
))}
</select>
</div>
)}
{selected && !selected.enabled ? (
<div className="card">
<div className="card-body text-secondary">
"{selected.name}" is disabled. Enable it under Integrations → Manage integrations to see its
datastores.
</div>
</div>
) : (
<div className="row g-3">
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">Node</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadStatus(selected.id)}
disabled={loadingStatus}
>
{loadingStatus ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="card-body">
{statusError ? (
<div className="text-danger">{statusError}</div>
) : (
<div className="row g-3">
<div className="col-6 col-md-3">
<div className="text-secondary">Uptime</div>
<div>{formatUptime(status?.uptime ?? null)}</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">CPU</div>
<div>
{status?.cpuUsagePercent !== null && status?.cpuUsagePercent !== undefined
? `${status.cpuUsagePercent.toFixed(0)}%`
: "—"}
{status?.cpuCores ? <span className="text-secondary"> ({status.cpuCores} cores)</span> : null}
</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Memory</div>
<div>
{formatBytes(status?.memUsedBytes ?? null)} / {formatBytes(status?.memTotalBytes ?? null)}
</div>
</div>
<div className="col-6 col-md-3">
<div className="text-secondary">Root filesystem</div>
<div>
{formatBytes(status?.rootfsUsedBytes ?? null)} / {formatBytes(status?.rootfsTotalBytes ?? null)}
</div>
</div>
</div>
)}
</div>
</div>
</div>
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">Datastores</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={exportCsv}
disabled={!sortedDatastores || sortedDatastores.length === 0}
>
{t("Export CSV")}
</button>
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadDatastores(selected.id)}
disabled={loading}
>
{loading ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<PbsDatastore> label="Datastore" sortKeyName="name" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<PbsDatastore> label="Used" sortKeyName="usedBytes" activeKey={sortKey} direction={sortDir} onSort={requestSort} />
<SortableTh<PbsDatastore>
label="Snapshots"
sortKeyName="snapshotCount"
activeKey={sortKey}
direction={sortDir}
onSort={requestSort}
/>
<SortableTh<PbsDatastore>
label="Latest snapshot"
sortKeyName="latestSnapshotAt"
activeKey={sortKey}
direction={sortDir}
onSort={requestSort}
/>
<SortableTh<PbsDatastore>
label="Verification"
sortKeyName="failedCount"
activeKey={sortKey}
direction={sortDir}
onSort={requestSort}
/>
</tr>
</thead>
<tbody>
{sortedDatastores?.map((d) => (
<tr key={d.name}>
<td>
{d.name}
{d.comment && <div className="text-secondary small">{d.comment}</div>}
</td>
<td className="text-secondary">
{formatBytes(d.usedBytes)} / {formatBytes(d.totalBytes)}
</td>
<td className="text-secondary">{d.snapshotCount}</td>
<td className="text-secondary">{formatDate(d.latestSnapshotAt)}</td>
<td>{verificationBadge(d)}</td>
</tr>
))}
{sortedDatastores?.length === 0 && (
<EmptyRow colSpan={5} title="No datastores found" hint="The Backup Server answered but listed none. Check that the API token has access to a datastore." action={{ label: "Check the integration", to: "/integrations" }} />
)}
</tbody>
</table>
</div>
</div>
</div>
{sortedDatastores?.some((d) => d.recentFailures.length > 0) && (
<div className="col-12">
<div className="card">
<div className="card-header">
<h3 className="card-title">Recent verification failures</h3>
<div className="card-actions">
<ExportTableButton filename="pbs-verification-failures" />
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<th>Datastore</th>
<th>Backup</th>
<th>{t("When")}</th>
</tr>
</thead>
<tbody>
{sortedDatastores
.flatMap((d) => d.recentFailures.map((f) => ({ datastore: d.name, ...f })))
.map((f, idx) => (
<tr key={`${f.datastore}-${f.backupType}-${f.backupId}-${f.backupTime}-${idx}`}>
<td>{f.datastore}</td>
<td className="text-secondary">
{f.backupType}/{f.backupId}
</td>
<td className="text-secondary">{formatDate(f.backupTime)}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
)}
</div>
)}
</>
)}
</>
);
}