History: server load, memory and disks are also kept as hourly (four months) and daily (over two years) averages with lowest and highest; endpoint answers as hourly (four months) beside the daily figures. Charts ask for 24 hours to a year and are drawn from whichever is fine enough. A disk that two weeks call flat is looked at again over ninety days for the forecast. Built once from what is kept. One chart: TimeChart replaces the sparkline and the multi-line chart: hover and arrow-key readout, a lowest/highest band, gaps shown as gaps, the same ranges everywhere and the choice remembered. Used for server trends, comparing servers, a check's availability and answer times (Endpoints > History) and a server's availability. Read API: /api/v1 (servers, metrics, alerts, incidents, inventory, network, endpoints and their history, maintenance) with personal read-only tokens made under the user menu: shown once, hashed, 30/90/365 days or none, ten at most, removed with their owner. GET only. Documented in API.md. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
184 lines
7.4 KiB
TypeScript
184 lines
7.4 KiB
TypeScript
import { useEffect, useMemo, useState } from "react";
|
|
import { Link, useSearchParams } from "react-router-dom";
|
|
import { api, type ServerMetricSeries, type ServerRecord } from "../api/client";
|
|
import TimeChart, { type ChartSeries } from "../components/TimeChart";
|
|
import RangeSelect from "../components/RangeSelect";
|
|
import { CHART_RANGES, useChartRange } from "../utils/chartRanges";
|
|
import { BlockSkeleton } from "../components/Skeleton";
|
|
import ExportTableButton from "../components/ExportTableButton";
|
|
|
|
const MAX_SERVERS = 4;
|
|
// A colour and a dash pattern for each line, so they can be told apart by either.
|
|
const LOOKS = [
|
|
{ color: "#4299e1", dash: "" },
|
|
{ color: "#f59f00", dash: "7 4" },
|
|
{ color: "#2fb344", dash: "2 4" },
|
|
{ color: "#ae3ec9", dash: "9 3 2 3" },
|
|
];
|
|
|
|
interface Loaded {
|
|
server: ServerRecord;
|
|
series: ServerMetricSeries[] | null;
|
|
}
|
|
|
|
function percent(v: number | null | undefined): string {
|
|
return v === null || v === undefined ? "—" : `${Math.round(v)}%`;
|
|
}
|
|
|
|
/**
|
|
* Two to four servers' load, memory or a disk on one chart, so "which of them is the busy one" and "did they spike together" are
|
|
* answered at a glance. Uses the same history as each server's own Trends card; servers without an agent have none to draw.
|
|
*/
|
|
export default function ServerCompare() {
|
|
const [params] = useSearchParams();
|
|
const ids = useMemo(() => {
|
|
const seen = new Set<number>();
|
|
for (const part of (params.get("ids") ?? "").split(",")) {
|
|
const n = Number(part);
|
|
if (Number.isInteger(n) && n > 0) seen.add(n);
|
|
}
|
|
return [...seen].slice(0, MAX_SERVERS);
|
|
}, [params]);
|
|
|
|
const [days, setDays] = useChartRange(7);
|
|
const [metric, setMetric] = useState("cpu");
|
|
const [loaded, setLoaded] = useState<Loaded[] | null>(null);
|
|
const [failed, setFailed] = useState(false);
|
|
const [to, setTo] = useState(() => Date.now());
|
|
|
|
useEffect(() => {
|
|
if (ids.length < 2) return;
|
|
let alive = true;
|
|
setFailed(false);
|
|
setLoaded(null);
|
|
Promise.all([api.servers.list(), ...ids.map((id) => api.servers.metrics(id, days).catch(() => null))])
|
|
.then(([list, ...metrics]) => {
|
|
if (!alive) return;
|
|
const byId = new Map((list as { servers: ServerRecord[] }).servers.map((s) => [s.id, s]));
|
|
setTo(Date.now());
|
|
setLoaded(
|
|
ids.flatMap((id, i) => {
|
|
const server = byId.get(id);
|
|
const m = metrics[i] as { series: ServerMetricSeries[] } | null;
|
|
return server ? [{ server, series: m ? m.series : null }] : [];
|
|
}),
|
|
);
|
|
})
|
|
.catch(() => alive && setFailed(true));
|
|
return () => {
|
|
alive = false;
|
|
};
|
|
}, [ids, days]);
|
|
|
|
// Every measure at least one of them has: load, memory, and each disk by its mount.
|
|
const metrics = useMemo(() => {
|
|
const found = new Map<string, string>([
|
|
["cpu", "CPU load"],
|
|
["mem", "Memory"],
|
|
]);
|
|
for (const l of loaded ?? []) for (const s of l.series ?? []) if (s.kind === "disk") found.set(s.metric, s.label);
|
|
return [...found.entries()];
|
|
}, [loaded]);
|
|
const metricName = metrics.find(([key]) => key === metric)?.[1] ?? "CPU load";
|
|
|
|
const rows = (loaded ?? []).map((l, i) => {
|
|
const s = l.series?.find((x) => x.metric === metric) ?? null;
|
|
const values = s?.points.map((p) => p.v) ?? [];
|
|
return {
|
|
server: l.server,
|
|
look: LOOKS[i % LOOKS.length],
|
|
series: s,
|
|
now: s?.latest ?? null,
|
|
average: values.length ? values.reduce((a, b) => a + b, 0) / values.length : null,
|
|
peak: values.length ? Math.max(...values) : null,
|
|
hasAgent: l.series !== null,
|
|
};
|
|
});
|
|
const chart: ChartSeries[] = rows.filter((r) => r.series).map((r) => ({ name: r.server.name, color: r.look.color, dash: r.look.dash, points: r.series!.points }));
|
|
const summary = `${metricName} over the last ${CHART_RANGES.find((r) => r.days === days)?.label}: ${rows.map((r) => `${r.server.name} ${percent(r.now)} now`).join(", ")}`;
|
|
|
|
return (
|
|
<>
|
|
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
|
<h2 className="page-title mb-0">Compare servers</h2>
|
|
<Link to="/servers" className="btn btn-sm btn-outline-secondary ms-auto">
|
|
Pick different servers
|
|
</Link>
|
|
</div>
|
|
|
|
{ids.length < 2 ? (
|
|
<div className="card">
|
|
<div className="card-body text-secondary">
|
|
Pick two to {MAX_SERVERS} servers to compare. On the <Link to="/servers">Servers</Link> page, press Compare and choose them.
|
|
</div>
|
|
</div>
|
|
) : (
|
|
<div className="card mb-3">
|
|
<div className="card-header d-flex flex-wrap gap-2">
|
|
<h3 className="card-title me-auto">{metricName}</h3>
|
|
<select className="form-select form-select-sm w-auto" aria-label="What to compare" value={metric} onChange={(e) => setMetric(e.target.value)}>
|
|
{metrics.map(([key, name]) => (
|
|
<option key={key} value={key}>
|
|
{name}
|
|
</option>
|
|
))}
|
|
</select>
|
|
<RangeSelect value={days} onChange={setDays} />
|
|
<ExportTableButton filename={`compare-${metric}`} />
|
|
</div>
|
|
<div className="card-body">
|
|
{failed ? (
|
|
<div className="text-secondary">Couldn't load the history.</div>
|
|
) : loaded === null ? (
|
|
<BlockSkeleton lines={5} />
|
|
) : (
|
|
<>
|
|
{chart.length === 0 ? (
|
|
<div className="text-secondary mb-3">None of these servers has a history for this yet. A sample is kept about every ten minutes once an agent has reported.</div>
|
|
) : (
|
|
<TimeChart series={chart} from={to - days * 86_400_000} to={to} label={summary} />
|
|
)}
|
|
<div className="table-responsive mt-3">
|
|
<table className="table table-vcenter">
|
|
<thead>
|
|
<tr>
|
|
<th>Server</th>
|
|
<th>Now</th>
|
|
<th>Average</th>
|
|
<th>Peak</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{rows.map((r) => (
|
|
<tr key={r.server.id}>
|
|
<td>
|
|
<svg width="34" height="10" aria-hidden="true" className="me-2">
|
|
<line x1="1" x2="33" y1="5" y2="5" stroke={r.look.color} strokeWidth="3" strokeDasharray={r.look.dash || undefined} strokeLinecap="round" />
|
|
</svg>
|
|
<Link to={`/servers/${r.server.id}`}>{r.server.name}</Link>
|
|
</td>
|
|
{r.series ? (
|
|
<>
|
|
<td>{percent(r.now)}</td>
|
|
<td>{percent(r.average)}</td>
|
|
<td>{percent(r.peak)}</td>
|
|
</>
|
|
) : (
|
|
<td colSpan={3} className="text-secondary">
|
|
{r.hasAgent ? "No history for this" : "No agent history (not reported by an agent)"}
|
|
</td>
|
|
)}
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
</>
|
|
)}
|
|
</div>
|
|
</div>
|
|
)}
|
|
</>
|
|
);
|
|
}
|