feat(widgets): add GPU metrics to Beszel system stats (#6645)

Co-authored-by: ajnart <thomas@ajnart.dev>
This commit is contained in:
SmilingJoeandajnart authored and GitHub committed 2026-10-05 14:53:23 +02:00
1 parent 177fa97b76
commit df6410d56c
12 files changed
+443 -9

No files matched your search

@@ -271,6 +271,9 @@ export default function BeszelSystemStatsWidget({
disk: options.showDisk,
diskIO: options.showDiskIO,
network: options.showNetwork,
gpuUsage: options.showGpuUsage,
gpuMemory: options.showGpuMemory,
gpuPower: options.showGpuPower,
dockerCpu: options.showDockerCpu,
dockerMemory: options.showDockerMemory,
dockerNetwork: options.showDockerNetwork,
@@ -66,6 +66,9 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
showDisk: factory.switch({ defaultValue: true }),
showDiskIO: factory.switch({ defaultValue: true }),
showNetwork: factory.switch({ defaultValue: true }),
showGpuUsage: factory.switch({ defaultValue: true }),
showGpuMemory: factory.switch({ defaultValue: true }),
showGpuPower: factory.switch({ defaultValue: true }),
showDockerCpu: factory.switch({ defaultValue: true }),
showDockerMemory: factory.switch({ defaultValue: true }),
showDockerNetwork: factory.switch({ defaultValue: true }),
@@ -2,7 +2,14 @@ import { describe, expect, test } from "vitest";
import type { BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { buildDiskChartData, normalizeBeszelByteRate, padLiveTimeGrid } from "./chart";
import {
buildDiskChartData,
buildGpuChartData,
buildGpuDevices,
hasGpuMetric,
normalizeBeszelByteRate,
padLiveTimeGrid,
} from "./chart";
const GIBIBYTE = 1024 ** 3;
@@ -103,3 +110,74 @@ describe("padLiveTimeGrid", () => {
expect(data.slice(-3).map((point) => point.CPU)).toEqual([10, undefined, 20]);
});
});
describe("buildGpuChartData", () => {
test("uses stable GPU ID and model labels across samples", () => {
const first = record("2026-07-11T13:46:00.000Z", 0, undefined);
first.stats.g = {
"0": { n: "RTX 3090", u: 10, mu: 1024, p: 150 },
"1": { n: "RTX 3090", u: 20, mu: 2048, p: 175 },
};
const second = record("2026-07-11T13:47:00.000Z", 0, undefined);
second.stats.g = { "0": { n: "RTX 3090", u: 30, mu: 4096, p: 200 } };
const devices = [
{ id: "0", seriesName: "RTX 3090 (0)" },
{ id: "1", seriesName: "RTX 3090 (1)" },
];
const data = buildGpuChartData([second, first], devices, "usage", "1h");
expect(data.map((point) => ({ zero: point["RTX 3090 (0)"], one: point["RTX 3090 (1)"] }))).toEqual([
{ zero: 10, one: 20 },
{ zero: 30, one: 0 },
]);
expect(buildGpuChartData([second, first], devices, "memory", "1h").map((point) => point["RTX 3090 (0)"])).toEqual([
1024 * 1024 * 1024,
4096 * 1024 * 1024,
]);
expect(buildGpuChartData([second, first], devices, "power", "1h").map((point) => point["RTX 3090 (0)"])).toEqual([
150, 200,
]);
});
test("returns no data when no GPU stats are available", () => {
expect(buildGpuDevices(undefined)).toEqual([]);
expect(buildGpuChartData(undefined, [], "usage")).toEqual([]);
});
test("keeps same-model GPUs distinct and orders them by device ID", () => {
const sample = record("2026-07-11T13:46:00.000Z", 0, undefined);
sample.stats.g = {
"1": { n: "RTX 3090", u: 20 },
"0": { n: "RTX 3090", u: 10 },
};
expect(buildGpuDevices([sample])).toEqual([
{ id: "0", seriesName: "RTX 3090 (0)" },
{ id: "1", seriesName: "RTX 3090 (1)" },
]);
});
test("uses zero for unavailable optional metrics and preserves the live window", () => {
const sample = record("2026-07-11T13:51:30.000Z", 0, undefined);
sample.stats.g = { "0": { n: "RTX 3090", u: 10 } };
const devices = [{ id: "0", seriesName: "RTX 3090 (0)" }];
expect(buildGpuChartData([sample], devices, "memory", "1m").at(-1)?.["RTX 3090 (0)"]).toBe(0);
expect(buildGpuChartData([sample], devices, "power", "1m").at(-1)?.["RTX 3090 (0)"]).toBe(0);
expect(buildGpuChartData([sample], devices, "usage", "1m")).toHaveLength(60);
});
test("distinguishes missing optional GPU metrics from reported zero values", () => {
const sample = record("2026-07-11T13:51:30.000Z", 0, undefined);
sample.stats.g = { "0": { n: "RTX 3090", u: 0 } };
expect(hasGpuMetric([sample], "memory")).toBe(false);
expect(hasGpuMetric([sample], "power")).toBe(false);
sample.stats.g = { "0": { n: "RTX 3090", u: 0, mu: 0, p: 0 } };
expect(hasGpuMetric([sample], "memory")).toBe(true);
expect(hasGpuMetric([sample], "power")).toBe(true);
});
});
+67 -1
View File
@@ -6,7 +6,7 @@ import type { AreaChartProps } from "@mantine/charts";
import { AreaChart } from "@mantine/charts";
import dayjs from "dayjs";
import type { BeszelContainerStatsRecord, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import type { BeszelContainerStatsRecord, BeszelGPUData, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { formatLocalizedDate } from "../../common/locale";
@@ -324,3 +324,69 @@ export const useDockerChartData = (
});
return padTimeGrid(mapped, timePeriod, locale);
}, [containerStats, containerNames, metric, timePeriod, locale]);
export interface BeszelGpuDevice {
id: string;
seriesName: string;
}
export type BeszelGpuMetric = "usage" | "memory" | "power";
export const buildGpuDevices = (systemStats: BeszelSystemStatsRecord[] | undefined) => {
const devices = new Map<string, BeszelGpuDevice>();
for (const record of systemStats ?? []) {
for (const [id, gpu] of Object.entries(record.stats.g ?? {})) {
if (!devices.has(id)) devices.set(id, { id, seriesName: `${gpu.n} (${id})` });
}
}
return [...devices.values()].toSorted((a, b) => a.id.localeCompare(b.id));
};
export const useGpuDevices = (systemStats: BeszelSystemStatsRecord[] | undefined) =>
useMemo(() => buildGpuDevices(systemStats), [systemStats]);
export const hasGpuMetric = (systemStats: BeszelSystemStatsRecord[] | undefined, metric: BeszelGpuMetric) => {
if (metric === "usage") return (systemStats ?? []).some((record) => Object.keys(record.stats.g ?? {}).length > 0);
return (systemStats ?? []).some((record) =>
Object.values(record.stats.g ?? {}).some((device) => (metric === "memory" ? device.mu : device.p) !== undefined),
);
};
const gpuExtractors: Record<BeszelGpuMetric, (device: BeszelGPUData | undefined) => number> = {
usage: (device) => device?.u ?? 0,
memory: (device) => (device?.mu ?? 0) * 1024 * 1024,
power: (device) => device?.p ?? 0,
};
export const useGpuChartData = (
systemStats: BeszelSystemStatsRecord[] | undefined,
devices: BeszelGpuDevice[],
metric: BeszelGpuMetric,
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) =>
useMemo(
() => buildGpuChartData(systemStats, devices, metric, timePeriod, locale),
[systemStats, devices, metric, timePeriod, locale],
);
export const buildGpuChartData = (
systemStats: BeszelSystemStatsRecord[] | undefined,
devices: BeszelGpuDevice[],
metric: BeszelGpuMetric,
timePeriod: BeszelTimePeriod = "1h",
locale = "en-US",
) => {
if (!systemStats?.length) return [];
const extract = gpuExtractors[metric];
const { fmt, ordered } = prepareRecords(systemStats, timePeriod, locale);
const mapped = ordered.map((record) => {
const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created };
for (const device of devices) {
point[device.seriesName] = extract(record.stats.g?.[device.id]);
}
return point;
});
return padTimeGrid(mapped, timePeriod, locale);
};
@@ -20,6 +20,8 @@ export const createByteChartAxisFormatters = (
export const formatPercent = (value: number): string => `${value.toFixed(1)}%`;
export const formatWatts = (value: number): string => `${value.toFixed(1)} W`;
export const getProgressTrackSize = (size: "xs" | "sm"): number => (size === "xs" ? 6 : 9);
export const formatUptime = (seconds: number): string => dayjs.duration(seconds, "seconds").humanize();
@@ -0,0 +1,148 @@
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { MantineProvider } from "@mantine/core";
import { afterEach, describe, expect, test, vi } from "vitest";
import type { BeszelSystemStatsRecord } from "@homarr/integrations/types";
import type * as ChartModule from "./chart";
import { BeszelStatsView } from "./stats-view";
import type { BeszelStatsVisibility } from "./stats-view";
const systemStats: BeszelSystemStatsRecord[] = [
{
id: "gpu-sample",
system: "llama01",
type: "1m",
created: "2026-07-11T13:51:30.000Z",
updated: "2026-07-11T13:51:30.000Z",
stats: {
cpu: 0,
m: 0,
mu: 0,
mp: 0,
mb: 0,
s: 0,
su: 0,
d: 0,
du: 0,
dp: 0,
g: { "0": { n: "RTX 3090", u: 10, mu: 1024, p: 150 } },
},
},
];
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
Object.defineProperty(window, "matchMedia", {
writable: true,
value: vi.fn().mockImplementation(() => ({
matches: false,
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
})),
});
vi.mock("@homarr/api/client", () => ({
clientApi: {
widget: {
beszel: {
getSystemStats: { useQuery: () => ({ data: { systemStats, containerStats: [] } }) },
},
},
},
}));
vi.mock("@homarr/translation/client", () => ({
useI18n: () => (key: string) => key,
useCurrentIntlLocale: () => "en-US",
}));
vi.mock("@homarr/settings", () => ({
useByteFormatter: () => ({ formatBytes: String, formatByteRate: String }),
}));
vi.mock("./use-live-stats", () => ({ useLiveStats: () => ({ data: undefined }) }));
vi.mock("./chart", async (importOriginal) => {
const actual = await importOriginal<typeof ChartModule>();
return {
...actual,
BeszelChartPanel: ({ title }: { title: string }) => createElement("div", { "data-chart": title }),
};
});
const hiddenCharts: BeszelStatsVisibility = {
cpu: false,
memory: false,
disk: false,
diskIO: false,
network: false,
gpuUsage: false,
gpuMemory: false,
gpuPower: false,
dockerCpu: false,
dockerMemory: false,
dockerNetwork: false,
};
const roots: ReturnType<typeof createRoot>[] = [];
const setGpuStats = (gpu: BeszelSystemStatsRecord["stats"]["g"]) => {
const sample = systemStats[0];
if (!sample) throw new Error("Expected a GPU test sample");
sample.stats.g = gpu;
};
afterEach(() => {
for (const root of roots.splice(0)) root.unmount();
document.body.replaceChildren();
setGpuStats({ "0": { n: "RTX 3090", u: 10, mu: 1024, p: 150 } });
});
const renderStatsView = async (visibility: BeszelStatsVisibility) => {
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
roots.push(root);
await act(async () => {
root.render(
createElement(
MantineProvider,
null,
createElement(BeszelStatsView, {
integrationIds: ["beszel"],
systemId: "llama01",
timePeriod: "1h",
visibility,
columns: 1,
}),
),
);
});
return container;
};
describe("BeszelStatsView GPU charts", () => {
test("renders only the GPU charts enabled by widget options", async () => {
const container = await renderStatsView({ ...hiddenCharts, gpuUsage: true, gpuPower: true });
expect(container.querySelector('[data-chart="chart.gpuUsage.title"]')).not.toBeNull();
expect(container.querySelector('[data-chart="chart.gpuPower.title"]')).not.toBeNull();
expect(container.querySelector('[data-chart="chart.gpuMemory.title"]')).toBeNull();
});
test("does not render GPU charts for a non-GPU system", async () => {
setGpuStats(undefined);
const container = await renderStatsView({ ...hiddenCharts, gpuUsage: true, gpuMemory: true, gpuPower: true });
expect(container.querySelectorAll("[data-chart]")).toHaveLength(0);
});
test("does not render optional GPU charts when Beszel does not report their metrics", async () => {
setGpuStats({ "0": { n: "RTX 3090", u: 10 } });
const container = await renderStatsView({ ...hiddenCharts, gpuMemory: true, gpuPower: true });
expect(container.querySelector('[data-chart="chart.gpuMemory.title"]')).toBeNull();
expect(container.querySelector('[data-chart="chart.gpuPower.title"]')).toBeNull();
});
});
@@ -18,14 +18,17 @@ import type { BeszelTimePeriod } from "./chart";
import {
BeszelChartPanel,
CPU_Y_AXIS_DOMAIN,
hasGpuMetric,
normalizeBeszelByteRate,
useContainerNames,
useDiskChartData,
useDiskIOChartData,
useDockerChartData,
useGpuChartData,
useGpuDevices,
useSystemChartData,
} from "./chart";
import { createByteChartAxisFormatters, formatPercent } from "./format";
import { createByteChartAxisFormatters, formatPercent, formatWatts } from "./format";
import { makeTooltipProps } from "./tooltip";
import { useLiveStats } from "./use-live-stats";
import { useDemoReadOnly } from "../../demo-read-only";
@@ -40,6 +43,9 @@ export interface BeszelStatsVisibility {
disk: boolean;
diskIO: boolean;
network: boolean;
gpuUsage: boolean;
gpuMemory: boolean;
gpuPower: boolean;
dockerCpu: boolean;
dockerMemory: boolean;
dockerNetwork: boolean;
@@ -93,6 +99,7 @@ export function BeszelStatsView({
rate: makeTooltipProps(formatByteRate, true),
percentTotal: makeTooltipProps(formatPercent, true),
bytesTotal: makeTooltipProps(formatBytes, true),
watts: makeTooltipProps(formatWatts),
}),
[formatByteRate, formatBytes],
);
@@ -157,6 +164,41 @@ export function BeszelStatsView({
locale,
);
const gpuDevices = useGpuDevices(
whenVisible(visibility.gpuUsage || visibility.gpuMemory || visibility.gpuPower, systemStats),
);
const gpuSeries = useMemo(
() =>
gpuDevices.map((device, index) => ({
name: device.seriesName,
color: containerColors[index % containerColors.length] as string,
})),
[gpuDevices],
);
const gpuUsageData = useGpuChartData(
whenVisible(visibility.gpuUsage, systemStats),
gpuDevices,
"usage",
timePeriod,
locale,
);
const gpuMemoryData = useGpuChartData(
whenVisible(visibility.gpuMemory, systemStats),
gpuDevices,
"memory",
timePeriod,
locale,
);
const gpuPowerData = useGpuChartData(
whenVisible(visibility.gpuPower, systemStats),
gpuDevices,
"power",
timePeriod,
locale,
);
const hasGpuMemory = hasGpuMetric(systemStats, "memory");
const hasGpuPower = hasGpuMetric(systemStats, "power");
const efsPaths = useMemo(() => {
const paths = new Set<string>();
for (const record of systemStats ?? []) {
@@ -283,6 +325,9 @@ export function BeszelStatsView({
(visibility.disk && diskData.length > 0 ? 1 : 0) +
(visibility.diskIO && diskIOData.length > 0 ? 1 : 0) +
(visibility.network && networkData.length > 0 ? 1 : 0) +
(visibility.gpuUsage && gpuSeries.length > 0 && gpuUsageData.length > 0 ? 1 : 0) +
(visibility.gpuMemory && hasGpuMemory && gpuMemoryData.length > 0 ? 1 : 0) +
(visibility.gpuPower && hasGpuPower && gpuPowerData.length > 0 ? 1 : 0) +
(showDocker && containerSeries.length > 0
? (visibility.dockerCpu && dockerCpuData.length > 0 ? 1 : 0) +
(visibility.dockerMemory && dockerMemoryData.length > 0 ? 1 : 0) +
@@ -367,6 +412,53 @@ export function BeszelStatsView({
}}
/>
)}
{gpuSeries.length > 0 && (
<>
{visibility.gpuUsage && gpuUsageData.length > 0 && (
<BeszelChartPanel
title={t("chart.gpuUsage.title")}
subtitle={t("chart.gpuUsage.subtitle")}
chartProps={{
h: chartHeight,
withXAxis: showXAxis,
data: gpuUsageData,
series: gpuSeries,
yAxisFormatter: formatPercent,
yAxisDomain: CPU_Y_AXIS_DOMAIN,
tooltipProps: tooltips.percent,
}}
/>
)}
{visibility.gpuMemory && hasGpuMemory && gpuMemoryData.length > 0 && (
<BeszelChartPanel
title={t("chart.gpuMemory.title")}
subtitle={t("chart.gpuMemory.subtitle")}
chartProps={{
h: chartHeight,
withXAxis: showXAxis,
data: gpuMemoryData,
series: gpuSeries,
yAxisFormatter: byteAxisFormatters.bytes,
tooltipProps: tooltips.bytesTotal,
}}
/>
)}
{visibility.gpuPower && hasGpuPower && gpuPowerData.length > 0 && (
<BeszelChartPanel
title={t("chart.gpuPower.title")}
subtitle={t("chart.gpuPower.subtitle")}
chartProps={{
h: chartHeight,
withXAxis: showXAxis,
data: gpuPowerData,
series: gpuSeries,
yAxisFormatter: formatWatts,
tooltipProps: tooltips.watts,
}}
/>
)}
</>
)}
{showDocker && containerSeries.length > 0 && (
<>
{visibility.dockerCpu && dockerCpuData.length > 0 && (
@@ -23,6 +23,9 @@ const allCharts = {
disk: true,
diskIO: true,
network: true,
gpuUsage: true,
gpuMemory: true,
gpuPower: true,
dockerCpu: true,
dockerMemory: true,
dockerNetwork: true,