Files
Homelab-manager/web/src/pages/Proxmox.tsx
T
bobbanandClaude Sonnet 5.5 846af02851 Lifecycle planning, and consistent empty and loading states
- Inventory: end of support and replacement cost per asset; a Lifecycle page showing what ages out year by year and what replacing it will cost; support ending within 90 days in the weekly digest
- Lists: a shared empty state saying what is missing, why, and the one thing to do; "nothing matches" with a clear button; skeleton rows instead of empty-looking lists while loading

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-18 23:18:42 +02:00

613 lines
27 KiB
TypeScript

import { useEffect, useState } from "react";
import TimeAgo from "../components/TimeAgo";
import { Link } from "react-router-dom";
import {
api,
type CurrentUser,
type IntegrationSummary,
type ProxmoxGuest,
type ProxmoxGuestsResponse,
type ProxmoxNodeStats,
type ProxmoxBackupJob,
type ProxmoxBackupTask,
} from "../api/client";
import { useSortable } from "../hooks/useSortable";
import SortableTh from "../components/SortableTh";
import { usePagination } from "../hooks/usePagination";
import Pagination from "../components/Pagination";
import { downloadCsv } from "../utils/csv";
import { confirmDialog } from "../utils/dialogs";
import IntegrationPageTitle from "../components/IntegrationPageTitle";
import { ErrorNotice } from "../components/Notice";
import { toast } from "../utils/toast";
import { SearchBox } from "../components/TableToolbar";
import { useTableSearch } from "../hooks/useTableSearch";
import DetailDrawer, { ObjectDetails } from "../components/DetailDrawer";
import { useRowDetail } from "../hooks/useRowDetail";
import { formatDateTime } from "../utils/date";
import ExportTableButton from "../components/ExportTableButton";
import { EmptyRow } from "../components/EmptyState";
function proxmoxStatusBadge(status: string) {
return status === "running" ? (
<span className="badge bg-green-lt text-green">Running</span>
) : (
<span className="badge bg-secondary-lt text-secondary">Stopped</span>
);
}
function formatUptime(seconds: number | null): string {
if (!seconds) return "—";
const days = Math.floor(seconds / 86400);
const hours = Math.floor((seconds % 86400) / 3600);
if (days > 0) return `${days}d ${hours}h`;
const minutes = Math.floor((seconds % 3600) / 60);
return `${hours}h ${minutes}m`;
}
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 describeGuests(job: ProxmoxBackupJob): string {
if (job.allGuests) return job.exclude ? `All guests (except ${job.exclude})` : "All guests";
return job.vmids ? `Guests ${job.vmids}` : "—";
}
function formatDuration(startIso: string, endIso: string | null): string {
if (!endIso) return "running…";
const seconds = Math.max(0, Math.round((new Date(endIso).getTime() - new Date(startIso).getTime()) / 1000));
const minutes = Math.floor(seconds / 60);
const remSeconds = seconds % 60;
return minutes > 0 ? `${minutes}m ${remSeconds}s` : `${remSeconds}s`;
}
function backupStatusBadge(task: ProxmoxBackupTask) {
if (task.ok) return <span className="badge bg-green-lt text-green">OK</span>;
if (task.status === "running") return <span className="badge bg-blue-lt text-blue">Running</span>;
return (
<span className="badge bg-red-lt text-red" title={task.status}>
Failed
</span>
);
}
function usageBar(used: number | null, total: number | null) {
if (!total) return null;
const pct = Math.min(100, Math.round(((used ?? 0) / total) * 100));
return (
<div className="progress progress-sm mt-1">
<div className={`progress-bar ${pct > 90 ? "bg-red" : pct > 75 ? "bg-yellow" : "bg-green"}`} style={{ width: `${pct}%` }} />
</div>
);
}
export default function Proxmox({ user }: { user: CurrentUser }) {
const canEdit = user.role === "admin" || user.role === "operator";
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<ProxmoxGuestsResponse | null>(null);
const [loading, setLoading] = useState(false);
const [actingOnGuest, setActingOnGuest] = useState<number | null>(null);
const [nodeStats, setNodeStats] = useState<ProxmoxNodeStats[] | null>(null);
const [nodeStatsError, setNodeStatsError] = useState<string | null>(null);
const [loadingNodeStats, setLoadingNodeStats] = useState(false);
const [backupJobs, setBackupJobs] = useState<ProxmoxBackupJob[] | null>(null);
const [backupTasks, setBackupTasks] = useState<ProxmoxBackupTask[] | null>(null);
const [uncoveredGuests, setUncoveredGuests] = useState<ProxmoxGuest[] | null>(null);
const [backupsError, setBackupsError] = useState<string | null>(null);
const [loadingBackups, setLoadingBackups] = useState(false);
useEffect(() => {
api.integrations
.list()
.then((res) => {
const proxmoxIntegrations = res.integrations.filter((i) => i.type === "proxmox");
setIntegrations(proxmoxIntegrations);
if (!selectedId && proxmoxIntegrations.length > 0) setSelectedId(proxmoxIntegrations[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 loadGuests(id: number) {
setLoading(true);
setError(null);
api.integrations.proxmox
.guests(id)
.then((res) => setData(res))
.catch((err) => setError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoading(false));
}
function loadNodeStats(id: number) {
setLoadingNodeStats(true);
setNodeStatsError(null);
api.integrations.proxmox
.nodes(id)
.then((res) => setNodeStats(res.nodes))
.catch((err) => setNodeStatsError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoadingNodeStats(false));
}
function loadBackups(id: number) {
setLoadingBackups(true);
setBackupsError(null);
api.integrations.proxmox
.backups(id)
.then((res) => {
setBackupJobs(res.jobs);
setBackupTasks(res.tasks);
setUncoveredGuests(res.uncoveredGuests);
})
.catch((err) => setBackupsError(err instanceof Error ? err.message : String(err)))
.finally(() => setLoadingBackups(false));
}
useEffect(() => {
if (selected?.enabled) {
loadGuests(selected.id);
loadNodeStats(selected.id);
loadBackups(selected.id);
} else {
setData(null);
setNodeStats(null);
setBackupJobs(null);
setBackupTasks(null);
setUncoveredGuests(null);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedId]);
async function guestAction(g: ProxmoxGuest, action: "start" | "stop" | "restart" | "shutdown") {
if (!selectedId) return;
const kind = g.type === "qemu" ? "VM" : "container";
if (
action === "stop" &&
!(await confirmDialog({
title: `Stop ${kind}`,
message: `Stop ${kind} "${g.name}" immediately? Use Shutdown instead for a graceful power-off.`,
confirmLabel: "Stop now",
danger: true,
}))
)
return;
setActingOnGuest(g.vmid);
setError(null);
try {
await api.integrations.proxmox[action](selectedId, g.node, g.type, g.vmid);
toast.success(`${{ start: "Started", stop: "Stopped", restart: "Restarted", shutdown: "Shut down" }[action]} ${g.name}.`);
loadGuests(selectedId);
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setActingOnGuest(null);
}
}
const tableSearch = useTableSearch(data?.guests);
const { sorted: sortedGuests, sortKey: guestSortKey, sortDir: guestSortDir, requestSort: requestGuestSort } = useSortable(tableSearch.filtered, undefined, "asc", { url: true });
const { pageItems: guestPageItems, page: guestPage, setPage: setGuestPage, pageCount: guestPageCount, totalCount: guestTotalCount } =
usePagination(sortedGuests);
const detail = useRowDetail<NonNullable<typeof guestPageItems>[number]>();
function exportGuestsCsv() {
if (!sortedGuests) return;
downloadCsv(
"proxmox-guests.csv",
["Name", "VMID", "Node", "Type", "Uptime", "Status"],
sortedGuests.map((g) => [g.name, g.vmid, g.node, g.type === "qemu" ? "VM" : "LXC", formatUptime(g.uptime), g.status]),
);
}
return (
<>
<IntegrationPageTitle title="Proxmox" integration={selected} />
<ErrorNotice error={error} />
{integrations?.length === 0 ? (
<div className="card">
<div className="card-body text-secondary">
No Proxmox 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
VMs and containers.
</div>
</div>
) : (
<>
<ErrorNotice error={nodeStatsError} />
<div className="row row-cards mb-3">
{nodeStats?.map((n) => (
<div className="col-12" key={n.node}>
<div className="card h-100">
<div className="card-header">
<h3 className="card-title">
{n.node}
{n.pveVersion && <span className="text-secondary fw-normal ms-2">{n.pveVersion}</span>}
</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadNodeStats(selected.id)}
disabled={loadingNodeStats}
>
{loadingNodeStats ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="card-body">
{n.error && <div className="alert alert-danger">{n.error}</div>}
<div className="row g-3">
<div className="col-md-6">
<div className="mb-3">
<div className="text-secondary small">Uptime</div>
<div>{formatUptime(n.uptime)}</div>
</div>
<div className="mb-3">
<div className="text-secondary small">CPU</div>
<div>
{n.cpuUsagePercent !== null ? `${n.cpuUsagePercent.toFixed(1)}%` : "—"}
{n.cpuCores ? <span className="text-secondary"> ({n.cpuCores} cores)</span> : null}
</div>
{n.loadAverage && (
<div className="text-secondary small">Load: {n.loadAverage.map((l) => l.toFixed(2)).join(", ")}</div>
)}
</div>
<div className={n.swapTotalBytes ? "mb-3" : ""}>
<div className="text-secondary small">Memory</div>
<div>
{formatBytes(n.memUsedBytes)} / {formatBytes(n.memTotalBytes)}
</div>
{usageBar(n.memUsedBytes, n.memTotalBytes)}
</div>
{!!n.swapTotalBytes && (
<div>
<div className="text-secondary small">Swap</div>
<div>
{formatBytes(n.swapUsedBytes)} / {formatBytes(n.swapTotalBytes)}
</div>
{usageBar(n.swapUsedBytes, n.swapTotalBytes)}
</div>
)}
</div>
<div className="col-md-6">
<div className="text-secondary small mb-1">Storage</div>
{n.storages.length > 0 ? (
<table className="table table-sm table-vcenter mb-0">
<tbody>
{n.storages.map((s) => (
<tr key={s.id}>
<td>
{s.id}
{!s.active && <span className="badge bg-secondary-lt text-secondary ms-1">Inactive</span>}
</td>
<td className="text-secondary">{s.type}</td>
<td>
{formatBytes(s.usedBytes)} / {formatBytes(s.totalBytes)}
{usageBar(s.usedBytes, s.totalBytes)}
</td>
</tr>
))}
</tbody>
</table>
) : (
!n.error && (
<div className="text-secondary small">
No storage visible to this API token. Proxmox filters the storage list
per-token — grant it <code>Datastore.Audit</code> (e.g. on{" "}
<code>/storage</code>) to see disk usage here.
</div>
)
)}
</div>
</div>
</div>
</div>
</div>
))}
{nodeStats?.length === 0 && (
<div className="col-12">
<div className="card">
<div className="card-body text-secondary">No online Proxmox nodes found.</div>
</div>
</div>
)}
</div>
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">Backups</h3>
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadBackups(selected.id)}
disabled={loadingBackups}
>
{loadingBackups ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="card-body">
<ErrorNotice error={backupsError} className="mb-3" />
{backupTasks && backupTasks.length > 0 && !backupTasks[0].ok && backupTasks[0].status !== "running" && (
<div className="alert alert-danger">
Most recent backup run on <strong>{backupTasks[0].node}</strong>
{backupTasks[0].guestId ? ` (guest ${backupTasks[0].guestId})` : ""} did not succeed:{" "}
{backupTasks[0].status}
</div>
)}
{uncoveredGuests && uncoveredGuests.length > 0 && (
<div className="alert alert-warning">
{uncoveredGuests.length} guest{uncoveredGuests.length !== 1 ? "s are" : " is"} not covered by
any enabled backup job: {uncoveredGuests.map((g) => `${g.name} (#${g.vmid})`).join(", ")}
</div>
)}
<div className="text-secondary small mb-1 d-flex align-items-center justify-content-between">
Scheduled jobs
<ExportTableButton of="next" filename="proxmox-backup-jobs" className="btn btn-sm btn-ghost-secondary" />
</div>
{backupJobs && backupJobs.length > 0 ? (
<table className="table table-sm table-vcenter mb-4">
<thead>
<tr>
<th>Schedule</th>
<th>Storage</th>
<th>Guests</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{backupJobs.map((j) => (
<tr key={j.id}>
<td>{j.schedule || "—"}</td>
<td className="text-secondary">{j.storage}</td>
<td className="text-secondary">{describeGuests(j)}</td>
<td>
{j.enabled ? (
<span className="badge bg-green-lt text-green">Enabled</span>
) : (
<span className="badge bg-secondary-lt text-secondary">Disabled</span>
)}
</td>
</tr>
))}
</tbody>
</table>
) : (
!backupsError && <div className="text-secondary small mb-4">No backup jobs configured in Proxmox.</div>
)}
<div className="text-secondary small mb-1 d-flex align-items-center justify-content-between">
Guests without backup coverage
<ExportTableButton of="next" filename="proxmox-uncovered-guests" className="btn btn-sm btn-ghost-secondary" />
</div>
{uncoveredGuests && uncoveredGuests.length > 0 ? (
<table className="table table-sm table-vcenter mb-4">
<thead>
<tr>
<th>Name</th>
<th>Node</th>
<th>Type</th>
<th>Status</th>
</tr>
</thead>
<tbody>
{uncoveredGuests.map((g) => (
<tr key={`${g.node}:${g.type}:${g.vmid}`}>
<td>
{g.name} <span className="text-secondary">#{g.vmid}</span>
</td>
<td className="text-secondary">{g.node}</td>
<td>
<span className="badge bg-blue-lt">{g.type === "qemu" ? "VM" : "LXC"}</span>
</td>
<td>{proxmoxStatusBadge(g.status)}</td>
</tr>
))}
</tbody>
</table>
) : (
!backupsError &&
uncoveredGuests && <div className="text-secondary small mb-4">Every VM/LXC is covered by at least one enabled backup job.</div>
)}
<div className="text-secondary small mb-1 d-flex align-items-center justify-content-between">
Recent runs
<ExportTableButton of="next" filename="proxmox-backup-runs" className="btn btn-sm btn-ghost-secondary" />
</div>
{backupTasks && backupTasks.length > 0 ? (
<table className="table table-sm table-vcenter mb-0">
<thead>
<tr>
<th>Node</th>
<th>Guest</th>
<th>Status</th>
<th>Started</th>
<th>Duration</th>
</tr>
</thead>
<tbody>
{backupTasks.slice(0, 20).map((t) => (
<tr key={t.upid}>
<td className="text-secondary">{t.node}</td>
<td>{t.guestId ?? "—"}</td>
<td>{backupStatusBadge(t)}</td>
<td className="text-secondary"><TimeAgo value={t.startTime} /></td>
<td className="text-secondary">{formatDuration(t.startTime, t.endTime)}</td>
</tr>
))}
</tbody>
</table>
) : (
!backupsError && <div className="text-secondary small mb-0">No recent backup runs found.</div>
)}
</div>
</div>
<div className="card">
<div className="card-header">
<h3 className="card-title">
VMs &amp; Containers
{data && (
<span className="text-secondary fw-normal ms-2">
{data.summary.running}/{data.summary.total} running
</span>
)}
</h3>
<SearchBox value={tableSearch.query} onChange={tableSearch.setQuery} className="ms-3" />
<div className="card-actions">
<button
className="btn btn-sm btn-outline-secondary"
onClick={exportGuestsCsv}
disabled={!sortedGuests || sortedGuests.length === 0}
>
Export CSV
</button>
<button
className="btn btn-sm btn-outline-secondary"
onClick={() => selected && loadGuests(selected.id)}
disabled={loading}
>
{loading ? "Refreshing…" : "Refresh"}
</button>
</div>
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<SortableTh<ProxmoxGuest> label="Name" sortKeyName="name" activeKey={guestSortKey} direction={guestSortDir} onSort={requestGuestSort} />
<SortableTh<ProxmoxGuest> label="Node" sortKeyName="node" activeKey={guestSortKey} direction={guestSortDir} onSort={requestGuestSort} />
<SortableTh<ProxmoxGuest> label="Type" sortKeyName="type" activeKey={guestSortKey} direction={guestSortDir} onSort={requestGuestSort} />
<SortableTh<ProxmoxGuest>
label="Uptime"
sortKeyName="uptime"
activeKey={guestSortKey}
direction={guestSortDir}
onSort={requestGuestSort}
/>
<SortableTh<ProxmoxGuest>
label="Status"
sortKeyName="status"
activeKey={guestSortKey}
direction={guestSortDir}
onSort={requestGuestSort}
/>
{canEdit && <th className="w-1">Actions</th>}
</tr>
</thead>
<tbody>
{guestPageItems?.map((g) => (
<tr key={`${g.node}:${g.type}:${g.vmid}`} {...detail.rowProps(g)}>
<td>
{g.name} <span className="text-secondary">#{g.vmid}</span>
</td>
<td className="text-secondary">{g.node}</td>
<td>
<span className="badge bg-blue-lt">{g.type === "qemu" ? "VM" : "LXC"}</span>
</td>
<td className="text-secondary">{formatUptime(g.uptime)}</td>
<td>{proxmoxStatusBadge(g.status)}</td>
{canEdit && (
<td>
<div className="btn-list flex-nowrap">
{g.status === "running" ? (
<>
<button
className="btn btn-sm"
onClick={() => guestAction(g, "restart")}
disabled={actingOnGuest === g.vmid}
>
Restart
</button>
<button
className="btn btn-sm"
onClick={() => guestAction(g, "shutdown")}
disabled={actingOnGuest === g.vmid}
>
Shutdown
</button>
<button
className="btn btn-sm btn-outline-danger"
onClick={() => guestAction(g, "stop")}
disabled={actingOnGuest === g.vmid}
>
Stop
</button>
</>
) : (
<button
className="btn btn-sm btn-primary"
onClick={() => guestAction(g, "start")}
disabled={actingOnGuest === g.vmid}
>
Start
</button>
)}
</div>
</td>
)}
</tr>
))}
{sortedGuests?.length === 0 && (
<EmptyRow colSpan={canEdit ? 6 : 5} title="No guests found" hint="The cluster answered with no virtual machines or containers. Check that the API token can see them." action={{ label: "Check the integration", to: "/integrations" }} filtered={tableSearch.active ? () => tableSearch.setQuery("") : undefined} />
)}
</tbody>
</table>
</div>
<Pagination page={guestPage} pageCount={guestPageCount} totalCount={guestTotalCount} onPageChange={setGuestPage} />
</div>
</>
)}
</>
)}
{detail.selected && (
<DetailDrawer title={((g) => g.name)(detail.selected)} subtitle={((g) => `${g.type === "qemu" ? "Virtual machine" : "Container"} ${g.vmid} on ${g.node}`)(detail.selected)} onClose={detail.close}>
<ObjectDetails data={detail.selected} />
</DetailDrawer>
)}
</>
);
}