Files
Homelab-manager/web/src/pages/Hetzner.tsx
T
bobbanandClaude Sonnet 5.5 9937ab2202 Fold long page introductions to two lines with Show more
One component, PageIntro, for the text under a page's title: shown as it is
when it fits in two lines, otherwise folded with a Show more, remembered per
page in this browser, opened by tabbing to a link in it, unfolded in print.
Used on 41 pages.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 19:42:34 +01:00

373 lines
19 KiB
TypeScript

import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import ReadNowButton from "../components/ReadNowButton";
import { api, type CurrentUser, type HetznerProject, type HetznerTrafficForecast } from "../api/client";
import EmptyState from "../components/EmptyState";
import TimeAgo from "../components/TimeAgo";
import { BlockSkeleton } from "../components/Skeleton";
import { ErrorNotice } from "../components/Notice";
import { formatBytes } from "./settings/StorageSettings";
import { readableError } from "../utils/errors";
import PageIntro from "../components/PageIntro";
function Badge({ p }: { p: HetznerProject }) {
if (!p.enabled) return <span className="badge bg-secondary-lt text-secondary">Off</span>;
if (!p.state) return <span className="badge bg-secondary-lt text-secondary">Not read yet</span>;
if (!p.fresh) return <span className="badge bg-yellow-lt text-yellow">Can&rsquo;t be read</span>;
if (p.problems.some((x) => x.severity === "critical")) return <span className="badge bg-red-lt text-red">Needs a look</span>;
if (p.problems.length > 0) return <span className="badge bg-yellow-lt text-yellow">Needs a look</span>;
return <span className="badge bg-green-lt text-green">In order</span>;
}
export function StatusBadge({ status }: { status: string }) {
if (status === "running") return <span className="badge bg-green-lt text-green">Running</span>;
if (status === "off") return <span className="badge bg-secondary-lt text-secondary">Off</span>;
return <span className="badge bg-yellow-lt text-yellow">{status}</span>;
}
const DAY_NAMES = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
const dayText = (iso: string) => {
const d = new Date(iso);
return `${d.getUTCDate()} ${DAY_NAMES[d.getUTCMonth()]}`;
};
/** What the month's traffic is forecast to come to, and when the quota goes if it is before the month ends. */
export function ForecastText({ forecast, included }: { forecast: HetznerTrafficForecast | null | undefined; included: number | null }) {
if (!forecast || included === null || included <= 0) return null;
return (
<div className={`small ${forecast.exhaustedAt ? "text-yellow" : "text-secondary"}`}>
{forecast.exhaustedAt ? <>at this rate the quota is passed on {dayText(forecast.exhaustedAt)}</> : <>on course for {formatBytes(forecast.projectedMonth)} by the month&rsquo;s end</>} · {formatBytes(forecast.perDay)} a day ({forecast.basis === "recent" ? "this week" : "the month"})
</div>
);
}
/** This month's outgoing traffic against what the server includes, as a bar that turns yellow at 80% and red at 100%. */
export function TrafficBar({ used, included }: { used: number | null; included: number | null }) {
if (used === null || included === null || included <= 0) return <span className="text-secondary">{used === null ? "—" : formatBytes(used)}</span>;
const share = used / included;
return (
<div style={{ minWidth: 150 }}>
<div className="progress progress-sm">
<div className={`progress-bar ${share >= 1 ? "bg-red" : share >= 0.8 ? "bg-yellow" : "bg-green"}`} style={{ width: `${Math.min(100, share * 100)}%` }} />
</div>
<div className="small text-secondary">
{formatBytes(used)} of {formatBytes(included)} ({Math.floor(share * 100)}%)
</div>
</div>
);
}
const money = (n: number, currency: string) => {
try {
return new Intl.NumberFormat(undefined, { style: "currency", currency }).format(n);
} catch {
return `${n.toFixed(2)} ${currency}`;
}
};
function ServerRow({ s }: { s: NonNullable<HetznerProject["state"]>["servers"][number] }) {
return (
<tr>
<td className="text-break">
{s.linked ? <Link to={`/servers/${s.linked.id}`}>{s.name}</Link> : <strong>{s.name}</strong>}
{!s.linked && <div className="text-secondary small">no agent here — not in the app&rsquo;s servers</div>}
{s.os && <div className="text-secondary small">{s.os}</div>}
</td>
<td>
<StatusBadge status={s.status} />
{s.rescueEnabled && <span className="badge bg-yellow-lt text-yellow ms-1">rescue on</span>}
{s.locked && <span className="badge bg-secondary-lt text-secondary ms-1">locked</span>}
{s.status !== "running" && (
<div className="text-secondary small">
since <TimeAgo value={s.statusSince} />
</div>
)}
</td>
<td className="text-secondary">
{s.type ?? "—"}
<div className="small">{[s.cores !== null ? `${s.cores} cores` : null, s.memoryGb !== null ? `${s.memoryGb} GB RAM` : null, s.diskGb !== null ? `${s.diskGb} GB disk` : null].filter(Boolean).join(" · ")}</div>
</td>
<td className="text-secondary">{[s.city, s.location].filter(Boolean).join(" · ") || "—"}</td>
<td className="text-secondary text-break">
{s.ipv4 ?? "—"}
{s.privateIps.length > 0 && <div className="small">{s.privateIps.join(", ")}</div>}
</td>
<td>
<TrafficBar used={s.outgoingTraffic} included={s.includedTraffic} />
<ForecastText forecast={s.forecast} included={s.includedTraffic} />
</td>
<td className="text-secondary">{s.backupWindow ? `on (${s.backupWindow})` : "off"}</td>
<td className="text-secondary">{s.monthlyPrice === null ? "—" : s.monthlyPrice.toFixed(2)}</td>
</tr>
);
}
function Card({ p, canRead, onRead }: { p: HetznerProject; canRead: boolean; onRead: () => void }) {
const s = p.state;
const cost = s?.cost ?? null;
const gb = (s?.volumes ?? []).reduce((sum, v) => sum + v.size, 0);
const snapshots = (s?.images ?? []).filter((i) => i.type === "snapshot").sort((a, b) => (b.created ?? "").localeCompare(a.created ?? ""));
const backups = (s?.images ?? []).filter((i) => i.type === "backup");
return (
<div className="card mb-3">
<div className="card-header">
<h3 className="card-title">
{p.name} <Badge p={p} />
</h3>
<div className="card-actions d-flex align-items-center gap-2 text-secondary small">
{p.status ? <>read <TimeAgo value={p.status.at} /></> : "not read yet"}
{canRead && p.enabled && <ReadNowButton integrationId={p.id} name={p.name} onDone={onRead} />}
</div>
</div>
<div className="card-body">
{p.status && !p.status.ok && <div className="text-yellow mb-2">The last attempt to read it failed: {p.status.error ?? "no answer"}.</div>}
{p.problems.length > 0 && (
<ul className="mb-3">
{p.problems.map((x) => (
<li key={x.key} className={x.severity === "critical" ? "text-red" : ""}>
{x.message}
</li>
))}
</ul>
)}
{s && (
<>
<div className="row g-3 mb-3">
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">Servers</div>
<div className="h2 mb-0">{s.servers.length}</div>
<div className="text-secondary small">{s.servers.filter((x) => x.status === "running").length} running</div>
</div>
</div>
</div>
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">Estimated per month</div>
<div className="h2 mb-0">{cost ? money(cost.total, cost.currency) : "—"}</div>
<div className="text-secondary small">{cost ? "at list prices, with VAT" : "the price list could not be read"}</div>
</div>
</div>
</div>
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">Volumes</div>
<div className="h2 mb-0">{s.volumes === null ? "—" : s.volumes.length}</div>
<div className="text-secondary small">{s.volumes === null ? "could not be read" : `${gb} GB${s.volumes.some((v) => v.serverId === null) ? `, ${s.volumes.filter((v) => v.serverId === null).length} not attached` : ""}`}</div>
</div>
</div>
</div>
<div className="col-6 col-lg-3">
<div className="card card-sm h-100">
<div className="card-body">
<div className="text-secondary small">Snapshots and backups</div>
<div className="h2 mb-0">{s.images === null ? "—" : `${snapshots.length} + ${backups.length}`}</div>
<div className="text-secondary small">{s.images === null ? "could not be read" : "snapshots + backups"}</div>
</div>
</div>
</div>
</div>
{cost && (
<div className="text-secondary small mb-3">
Servers {money(cost.servers, cost.currency)} · backups {money(cost.backups, cost.currency)} · volumes {money(cost.volumes, cost.currency)} · snapshots {money(cost.snapshots, cost.currency)} · primary IPs {money(cost.ips, cost.currency)} · load balancers {money(cost.loadBalancers ?? 0, cost.currency)} · floating IPs {money(cost.floatingIps ?? 0, cost.currency)}
{cost.unassignedIps > 0 ? ` (${cost.unassignedIps} not attached to a server)` : ""}. An estimate from Hetzner&rsquo;s price list: it leaves out traffic over the quota{cost.unpriced > 0 ? `, and ${cost.unpriced} server(s) whose price was not given` : ""}.
</div>
)}
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<th>Server</th>
<th>Status</th>
<th>Type</th>
<th>Location</th>
<th>Address</th>
<th>Traffic this month</th>
<th>Backups</th>
<th>Price/mo</th>
</tr>
</thead>
<tbody>
{s.servers.map((x) => (
<ServerRow key={x.id} s={x} />
))}
{s.servers.length === 0 && (
<tr>
<td colSpan={8} className="text-secondary">
The project has no servers.
</td>
</tr>
)}
</tbody>
</table>
</div>
{s.loadBalancers && s.loadBalancers.length > 0 && (
<>
<h4 className="mt-3">Load balancers</h4>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Address</th>
<th>Targets</th>
<th>Traffic this month</th>
<th>Price/mo</th>
</tr>
</thead>
<tbody>
{s.loadBalancers.map((l) => {
const bad = l.targets.filter((t) => t.health === "unhealthy");
return (
<tr key={l.id}>
<td className="text-break">
<strong>{l.name}</strong>
<div className="text-secondary small">
{l.services} service{l.services === 1 ? "" : "s"}
{l.algorithm ? ` · ${l.algorithm.replace("_", " ")}` : ""}
</div>
</td>
<td className="text-secondary">{[l.type, l.location].filter(Boolean).join(" · ") || "—"}</td>
<td className="text-secondary text-break">{l.ipv4 ?? "—"}</td>
<td>
{l.targets.length === 0 ? (
<span className="text-secondary">none</span>
) : bad.length === 0 ? (
<span className="badge bg-green-lt text-green">{l.targets.every((t) => t.health === "healthy") ? `${l.targets.length} healthy` : `${l.targets.length} · not judged yet`}</span>
) : (
<span className="badge bg-red-lt text-red">{bad.length} of {l.targets.length} unhealthy</span>
)}
<div className="text-secondary small text-break">{l.targets.map((t) => `${t.serverName ?? t.label ?? "target"}${t.health === "unhealthy" ? " ✗" : ""}`).join(", ")}</div>
</td>
<td>
<TrafficBar used={l.outgoingTraffic} included={l.includedTraffic} />
</td>
<td className="text-secondary">{l.monthlyPrice === null ? "—" : l.monthlyPrice.toFixed(2)}</td>
</tr>
);
})}
</tbody>
</table>
</div>
</>
)}
{s.floatingIps && s.floatingIps.length > 0 && (
<>
<h4 className="mt-3">Floating IPs</h4>
<ul className="mb-0">
{s.floatingIps.map((f) => (
<li key={f.id}>
<code>{f.ip}</code>
{f.name ? ` (${f.name})` : ""} — {f.serverId === null ? <span className="text-yellow">points at no server (still billed)</span> : f.serverName ? `points at ${f.serverName}` : `points at a server (#${f.serverId})`}
{f.location ? `, ${f.location}` : ""}
</li>
))}
</ul>
</>
)}
{s.certificates && s.certificates.length > 0 && (
<>
<h4 className="mt-3">Certificates</h4>
<ul className="mb-0">
{s.certificates.map((c) => {
const left = c.notValidAfter === null ? null : (Date.parse(c.notValidAfter) - Date.now()) / 86_400_000;
return (
<li key={c.id}>
<strong>{c.name}</strong> ({c.type}
{c.domains.length > 0 ? `, ${c.domains.slice(0, 3).join(", ")}${c.domains.length > 3 ? ", …" : ""}` : ""}) —{" "}
{c.notValidAfter === null ? (
<span className="text-secondary">{c.issuance === "failed" ? "could not be issued" : "being issued"}</span>
) : left !== null && left <= 0 ? (
<span className="text-red">ended <TimeAgo value={c.notValidAfter} /></span>
) : (
<span className={left !== null && left <= 3 ? "text-red" : left !== null && left <= 14 ? "text-yellow" : ""}>ends in {Math.ceil(left ?? 0)} days</span>
)}
{c.usedBy === 0 && <span className="text-secondary small"> · used by nothing</span>}
{(c.issuance === "failed" || c.renewal === "failed") && <span className="text-red"> · {c.issuance === "failed" ? "issuing" : "renewing"} failed{c.error ? `: ${c.error}` : ""}</span>}
</li>
);
})}
</ul>
</>
)}
{s.volumes && s.volumes.length > 0 && (
<>
<h4 className="mt-3">Volumes</h4>
<ul className="mb-0">
{s.volumes.map((v) => (
<li key={v.id}>
<strong>{v.name}</strong> — {v.size} GB, {v.location ?? "?"}, {v.serverName ? `on ${v.serverName}` : v.serverId === null ? <span className="text-yellow">not attached to a server (still billed)</span> : `on a server (#${v.serverId})`}
</li>
))}
</ul>
</>
)}
{snapshots.length > 0 && (
<>
<h4 className="mt-3">Snapshots</h4>
<ul className="mb-0">
{snapshots.map((i) => (
<li key={i.id}>
<strong>{i.description ?? `#${i.id}`}</strong> — {i.sizeGb === null ? "being made" : `${i.sizeGb.toFixed(1)} GB`}, {i.serverName ? `of ${i.serverName}` : "of a server that is gone"}
{i.created && (
<>
, taken <TimeAgo value={i.created} />
</>
)}
</li>
))}
</ul>
<div className="text-secondary small mt-1">Snapshots are billed per GB and month until they are deleted.</div>
</>
)}
</>
)}
</div>
</div>
);
}
/** Hetzner Cloud: each project's servers, what is close to its traffic quota, which have backups, and roughly what it all costs. */
export default function Hetzner({ user }: { user: CurrentUser }) {
const canRead = user.role === "admin" || user.role === "operator";
const [tick, setTick] = useState(0);
const [data, setData] = useState<HetznerProject[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const load = () =>
api.hetzner
.list()
.then((r) => {
setData(r.projects);
setError(null);
})
.catch((err) => setError(readableError(err)));
void load();
const t = setInterval(load, 60_000);
return () => clearInterval(t);
}, [tick]);
return (
<>
<h2 className="page-title">Hetzner Cloud</h2>
<PageIntro>
One project per integration, read every few minutes (see <Link to="/integrations">Integrations</Link>) — nothing is started, stopped or changed. <strong>A server that was running and is now off</strong>, <strong>traffic close to the month&rsquo;s quota</strong>,{" "}
<strong>rescue mode left on</strong>, <strong>backups that are late</strong>, <strong>a traffic quota the month is on course to pass</strong>, <strong>unhealthy load balancer targets</strong>, <strong>certificates about to end</strong> and <strong>floating IPs that point at nothing</strong> are alerts — see <Link to="/alerts">Alerts</Link>.
</PageIntro>
<ErrorNotice error={error} />
{!data && !error && <BlockSkeleton lines={4} />}
{data && data.length === 0 && (
<div className="card">
<div className="card-body">
<EmptyState title="No Hetzner project connected" hint="Add one under Integrations with a project's API token (Hetzner Console → the project → Security → API tokens; Read is enough)." />
</div>
</div>
)}
{data?.map((p) => <Card key={p.id} p={p} canRead={canRead} onRead={() => setTick((n) => n + 1)} />)}
</>
);
}