A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.
fix(truenas): normalize legacy memory and reporting columns (#7298)
Thomase3a026e08184
diff --git a/packages/integrations/src/truenas/test/truenas-integration.spec.ts b/packages/integrations/src/truenas/test/truenas-integration.spec.tsindex c0e71fdf5..cc2acd110 100644--- a/packages/integrations/src/truenas/test/truenas-integration.spec.ts+++ b/packages/integrations/src/truenas/test/truenas-integration.spec.ts@@ -138,7 +138,7 @@ const happyResponder = (method: string) => {aggregations: emptyAggregations(),start: 0,end: 1,- legend: [],+ legend: ["time", "cpu"],data: [[1000, 12]],},{@@ -147,7 +147,6 @@ const happyResponder = (method: string) => {aggregations: emptyAggregations(),start: 0,end: 1,- // The "memory" graph reports available (free) memory: legend is ["time", "available"].legend: ["time", "available"],data: [[1000, 6_000_000_000]],},@@ -157,7 +156,7 @@ const happyResponder = (method: string) => {aggregations: emptyAggregations(),start: 0,end: 1,- legend: [],+ legend: ["time", "cpu0"],data: [[1000, 45]],},];@@ -174,7 +173,9 @@ const happyResponder = (method: string) => {case "interface.query":return [{ id: "eth0", name: "eth0" }];case "reporting.netdata_get_data":- return [{ name: "interface", identifier: "eth0", data: [[1000, 100, 200]] }];+ return [+ { name: "interface", identifier: "eth0", legend: ["time", "received", "sent"], data: [[1000, 100, 200]] },+ ];default:return null;}@@ -182,6 +183,15 @@ const happyResponder = (method: string) => {const emptyAggregations = () => ({ min: {}, mean: {}, max: {} });+const reportingResponder = (identifier: string, legend: string[], data: number[][]) => (method: string) => {+ const response = happyResponder(method);+ if (method !== "reporting.get_data" || !Array.isArray(response)) return response;+ return response.map((report) => {+ if ("identifier" in report && report.identifier === identifier) return { ...report, legend, data };+ return report;+ });+};+// `pool.query` reports 500 allocated of a 1000 byte pool, leaving 500 free.const physicalFallbackFileSystem = [{ deviceName: "tank", available: "500", used: "500", percentage: 50 }];@@ -244,7 +254,7 @@ describe("TrueNasIntegration", () => {availablePkgUpdates: 0,loadAverage: null,gpu: [],- network: { up: 20_000, down: 10_000 },+ network: { up: 25_000, down: 12_500 },// `available` and `used` come from the root dataset, not the physical pool.fileSystem: [{ deviceName: "tank", available: "300", used: "200", percentage: 40 }],smart: [{ deviceName: "tank", healthy: true, overallStatus: "ONLINE", temperature: null }],@@ -262,6 +272,136 @@ describe("TrueNasIntegration", () => {expect(result.smart).toMatchObject([{ deviceName: "tank", healthy: true, overallStatus: "ONLINE" }]);});+ test.each([+ {+ version: "TrueNAS-SCALE-24.10.2.2",+ physmem: 168_946_339_840,+ legend: ["time", "free", "used", "cached", "buffers"],+ data: [[1792834434, 54525.64, 65164.29, 41429.86, 0]],+ used: 65164.29 * 1024 * 1024,+ },+ {+ version: "25.10.7",+ physmem: 541_011_288_064,+ legend: ["time", "available"],+ data: [[1792834431, 492_588_100_000]],+ used: 541_011_288_064 - 492_588_100_000,+ },+ ])("normalizes the $version memory reporting format", async ({ version, physmem, legend, data, used }) => {+ ws.setResponder((method) => {+ if (method === "system.info") return { version, physmem, hostname: "nas", model: "Xeon", uptime_seconds: 3600 };+ const response = happyResponder(method);+ if (method === "reporting.get_data" && Array.isArray(response)) {+ return response.map((report) => {+ if ("name" in report && report.name === "memory") return { ...report, legend, data };+ return report;+ });+ }+ return response;+ });++ const result = await createIntegration(credentials).getSystemInfoAsync();++ expect(result.memUsedInBytes).toBe(used);+ expect(result.memAvailableInBytes).toBe(physmem - used);+ });++ test.each([+ {+ legend: ["cached", "used", "time", "buffers", "free"],+ data: [+ [4000, 1, 999, 0, 1000],+ [4000, 6000, 1000, 0, 1000],+ ],+ used: 6000 * 1024 * 1024,+ },+ {+ legend: ["available", "time"],+ data: [+ [1, 999],+ [6_000_000_000, 1000],+ ],+ used: 10_000_000_000,+ },+ { legend: ["time", "available"], data: [[1000, 0]], used: 16_000_000_000 },+ { legend: ["time", "available"], data: [[1000, 17_000_000_000]], used: 0 },+ {+ legend: ["time", "free", "used", "cached", "buffers"],+ data: [[1000, 0, 20_000, 0, 0]],+ used: 16_000_000_000,+ },+ ])("uses the latest named memory columns and bounds usage: $legend $used", async ({ legend, data, used }) => {+ ws.setResponder(reportingResponder("memory", legend, data));++ const result = await createIntegration(credentials).getSystemInfoAsync();++ expect(result.memUsedInBytes).toBe(used);+ expect(result.memAvailableInBytes).toBe(16_000_000_000 - used);+ });++ test.each([+ { legend: ["time", "other"], data: [[1000, 123]] },+ { legend: ["time", "used"], data: [[1000, 123]] },+ { legend: ["time", "available"], data: [] },+ { legend: ["time", "available"], data: [[1000]] },+ { legend: ["time", "available", "available"], data: [[1000, 123, 456]] },+ { legend: ["time", "available"], data: [[1000, Number.NaN]] },+ { legend: ["time", "available"], data: [[1000, -1]] },+ { legend: ["time", "free", "used", "cached", "buffers"], data: [[1000, 0, -1, 0, 0]] },+ ])("reports an integration error instead of inventing memory usage: $legend $data", async ({ legend, data }) => {+ ws.setResponder(reportingResponder("memory", legend, data));++ await expect(createIntegration(credentials).getSystemInfoAsync()).rejects.toThrow(+ "Failed to parse integration data",+ );+ });++ test.each([+ { legend: ["time", "system", "user", "idle", "softirq", "nice", "iowait"], data: [[1000, 4, 8, 87, 0, 0, 1]] },+ { legend: ["cpu1", "cpu", "time", "cpu0"], data: [[100, 12, 1000, 0]] },+ ])(+ "reads CPU utilization without averaging timestamps, idle time or duplicate core totals: $legend",+ async ({ legend, data }) => {+ ws.setResponder(reportingResponder("cpu", legend, data));++ const result = await createIntegration(credentials).getSystemInfoAsync();++ expect(result.cpuUtilization).toBe(12);+ },+ );++ test("excludes the named timestamp from CPU temperatures even when reordered", async () => {+ ws.setResponder(reportingResponder("cputemp", ["cpu0", "time", "cpu1"], [[45, 1000, 46]]));++ const result = await createIntegration(credentials).getSystemInfoAsync();++ expect(result.cpuTemp).toBe(46);+ });++ test("sums the latest named network columns across interfaces in bytes per second", async () => {+ ws.setResponder((method) => {+ if (method === "reporting.netdata_get_data") {+ return [+ {+ name: "interface",+ identifier: "eth0",+ legend: ["sent", "time", "received"],+ data: [+ [1, 999, 2],+ [200, 1000, 100],+ ],+ },+ { name: "interface", identifier: "eth1", legend: ["time", "received", "sent"], data: [[1000, 300, 400]] },+ ];+ }+ return happyResponder(method);+ });++ const result = await createIntegration(credentials).getSystemInfoAsync();++ expect(result.network).toEqual({ up: 75_000, down: 50_000 });+ });+test("falls back to physical pool space when the root dataset reports no usable values", async () => {ws.setResponder((method) =>method === "pool.dataset.query"@@ -398,7 +538,7 @@ describe("TrueNasIntegration", () => {await expect(resultPromise).resolves.toMatchObject({version: "TrueNAS-SCALE-24.10",- network: { up: 20_000, down: 10_000 },+ network: { up: 25_000, down: 12_500 },});});diff --git a/packages/integrations/src/truenas/truenas-integration.ts b/packages/integrations/src/truenas/truenas-integration.tsindex 068659c6a..7e79aeafc 100644--- a/packages/integrations/src/truenas/truenas-integration.ts+++ b/packages/integrations/src/truenas/truenas-integration.ts@@ -1,6 +1,7 @@import dayjs from "dayjs";import z from "zod";+import { ParseError } from "@homarr/common/server";import { createLogger } from "@homarr/core/infrastructure/logs";import type { IntegrationTestingInput } from "../base/integration";@@ -14,7 +15,8 @@ import { TrueNasClient } from "./truenas-client";const logger = createLogger({ module: "trueNasIntegration" });-const NETWORK_MULTIPLIER = 100;+const NETWORK_MULTIPLIER = 1000 / 8;+const MEBIBYTE = 1024 * 1024;const ERROR_MESSAGE_LIMIT = 200;@@ -55,18 +57,36 @@ export class TrueNasIntegration extends Integration implements ISystemHealthMoniconst cpuData = this.extractLatestReportingData(reporting, "cpu");const cpuTempData = this.extractLatestReportingData(reporting, "cputemp");const memoryData = this.extractLatestReportingData(reporting, "memory");+ if (Object.values(memoryData).some((value) => value < 0)) {+ throw new ParseError("TrueNAS returned negative memory reporting values");+ }- const upload = this.extractNetworkTrafficData(netdata, 2); // Index 2 is "sent"- const download = this.extractNetworkTrafficData(netdata, 1); // Index 1 is "received"-- // The "memory" reporting graph reports available (free) memory, its legend is ["time", "available"].- // Used memory is therefore the physical total minus what is still available (clamped against timing skew).- const memAvailableInBytes = memoryData[1] ?? 0; // Index 0 is the UNIX timestamp, Index 1 is available bytes- const memUsedInBytes = Math.max(systemInformation.physmem - memAvailableInBytes, 0);+ const upload = this.extractNetworkTrafficData(netdata, "sent");+ const download = this.extractNetworkTrafficData(netdata, "received");++ let memoryUsed: number;+ if (memoryData.available !== undefined) {+ memoryUsed = systemInformation.physmem - memoryData.available;+ } else if (+ memoryData.used !== undefined &&+ ["free", "cached", "buffers"].every((column) => memoryData[column] !== undefined)+ ) {+ memoryUsed = memoryData.used * MEBIBYTE;+ } else {+ throw new ParseError("TrueNAS returned an unsupported memory reporting format");+ }+ const memUsedInBytes = Math.min(systemInformation.physmem, Math.max(memoryUsed, 0));+ const memAvailableInBytes = systemInformation.physmem - memUsedInBytes;+ const cpuUtilization =+ cpuData.cpu ??+ Object.entries(cpuData).reduce((total, [column, value]) => {+ if (column === "idle" || column === "iowait") return total;+ return total + value;+ }, 0);return {- cpuUtilization: cpuData.reduce((acc, item) => acc + (item > 100 ? 0 : item), 0) / cpuData.length,- cpuTemp: Math.max(...cpuTempData.filter((_item, index) => index > 0)),+ cpuUtilization: Math.min(100, Math.max(0, cpuUtilization)),+ cpuTemp: Math.max(...Object.values(cpuTempData)),memAvailableInBytes,memUsedInBytes,fileSystem: datasets.map((dataset) => {@@ -313,16 +333,29 @@ export class TrueNasIntegration extends Integration implements ISystemHealthMonireturn result;}- private extractNetworkTrafficData = (data: z.infer<typeof reportingNetDataSchema>, index: 1 | 2) => {- return data.reduce((acc, current) => acc + (current.data.at(-1)?.at(index) ?? 0), 0);+ private extractNetworkTrafficData = (data: z.infer<typeof reportingNetDataSchema>, column: "sent" | "received") => {+ return data.reduce((total, report) => {+ const value = report.data.at(-1)?.[report.legend.indexOf(column)] ?? 0;+ return total + value;+ }, 0);};private extractLatestReportingData(data: ReportingItem[], identifier: ReportingItem["identifier"]) {const item = data.find((reportingItem) => reportingItem.identifier === identifier);- // Reporting rows are [timestamp, ...values] in ascending time order, so the last row is the most recent reading.const latest = item?.data.at(-1);- if (!latest) throw new Error(`TrueNAS returned no "${identifier}" reporting data`);- return latest;+ if (!item || !latest?.length) throw new ParseError(`TrueNAS returned no "${identifier}" reporting data`);+ if (new Set(item.legend).size !== item.legend.length) {+ throw new ParseError(`TrueNAS returned duplicate "${identifier}" reporting columns`);+ }+ const values: Record<string, number> = {};+ for (const [index, column] of item.legend.entries()) {+ if (column === "time") continue;+ const value = latest[index];+ if (value === undefined) throw new ParseError(`TrueNAS returned no "${identifier}.${column}" reporting value`);+ values[column] = value;+ }+ if (Object.keys(values).length === 0) throw new ParseError(`TrueNAS returned no "${identifier}" reporting values`);+ return values;}}@@ -372,6 +405,7 @@ const reportingNetDataSchema = z.array(z.object({name: z.string(),identifier: z.string(),+ legend: z.array(z.string()),data: z.array(z.array(z.number())),}),);@@ -379,7 +413,7 @@ const reportingNetDataSchema = z.array(const systemInfoSchema = z.object({version: z.string(),hostname: z.string(),- physmem: z.number().min(0), // pysical memory+ physmem: z.number().positive(),model: z.string(), // cpu modeluptime_seconds: z.number().min(0),});