Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix(truenas): read CORE memory from legacy REST reporting
pulse-triage[bot]a4c53b511de7
diff --git a/internal/truenas/client.go b/internal/truenas/client.goindex 36c685ea94..734c4216dc 100644--- a/internal/truenas/client.go+++ b/internal/truenas/client.go@@ -29,6 +29,11 @@ const maxResponseBodyBytes int64 = 4 * 1024 * 1024const defaultRealtimeIntervalSeconds = 2+// legacyRESTTelemetryWindowSeconds bounds the reporting.get_data window used+// to reconstruct live system telemetry on the legacy REST transport, where the+// reporting.realtime JSON-RPC subscription does not exist (#2077).+const legacyRESTTelemetryWindowSeconds = 300+const defaultAppStatsIntervalSeconds = defaultRealtimeIntervalSecondsconst defaultDiskTemperatureAggregateWindowDays = 7@@ -235,9 +240,17 @@ func systemInfoFromResponse(response systemInfoResponse) *SystemInfo {// transport or endpoint failure as "telemetry unavailable" rather than a// system identity failure.func (c *Client) GetSystemTelemetry(ctx context.Context) (*SystemInfo, error) {+ legacy, err := c.useLegacyREST(ctx)+ if err != nil {+ return nil, err+ }+ if legacy {+ return c.getSystemTelemetryREST(ctx)+ }+var telemetry *SystemInfovar temperatures map[string]float64- err := c.withRPC(ctx, func(rpc *trueNASRPCClient) error {+ err = c.withRPC(ctx, func(rpc *trueNASRPCClient) error {temperatures, _ = rpc.getSystemTemperatures(ctx)subscriptionName := fmt.Sprintf("reporting.realtime:{\"interval\":%d}", defaultRealtimeIntervalSeconds)subscriptionID, err := rpc.subscribe(ctx, subscriptionName)@@ -259,11 +272,122 @@ func (c *Client) GetSystemTelemetry(ctx context.Context) (*SystemInfo, error) {return telemetry, nil}+// getSystemTelemetryREST reconstructs live system telemetry from the legacy+// REST reporting API. TrueNAS CORE 13 has no reporting.realtime JSON-RPC+// subscription, so reporting.get_data is the only live memory and ARC source+// there; without it the total-available derivation reports every CORE install+// as 100% used (#2077).+func (c *Client) getSystemTelemetryREST(ctx context.Context) (*SystemInfo, error) {+ end := time.Now().Unix()+ start := end - int64(legacyRESTTelemetryWindowSeconds)+ if start <= 0 {+ start = end+ }+ response, err := c.getReportingDataREST(ctx, legacyRESTReportingGraphs(), map[string]any{+ "aggregate": false,+ "start": start,+ "end": end,+ })+ if err != nil {+ return nil, err+ }+ history := parseSystemMetricHistory(response)+ if history == nil {+ return nil, fmt.Errorf("truenas legacy REST reporting returned no system telemetry")+ }+ return systemInfoFromMetricHistory(history), nil+}++// systemInfoFromMetricHistory maps the latest reporting sample onto live system+// telemetry. Series that the appliance did not report stay zero so callers can+// distinguish "absent" from a genuine zero.+func systemInfoFromMetricHistory(history *SystemMetricHistory) *SystemInfo {+ if history == nil {+ return nil+ }+ system := &SystemInfo{CollectedAt: time.Now().UTC()}+ if value, ok := latestTimeSeriesValue(history.CPUPercent); ok {+ system.CPUPercent = value+ }+ if value, ok := latestTimeSeriesValue(history.MemoryTotalBytes); ok {+ system.MemoryTotalBytes = int64(value)+ }+ if value, ok := latestTimeSeriesValue(history.MemoryAvailableBytes); ok {+ system.MemoryAvailableBytes = int64(value)+ }+ if value, ok := latestTimeSeriesValue(history.ARCSizeBytes); ok {+ system.ARCSizeBytes = int64(value)+ }+ if value, ok := latestTimeSeriesValue(history.NetInRate); ok {+ system.NetInRate = value+ }+ if value, ok := latestTimeSeriesValue(history.NetOutRate); ok {+ system.NetOutRate = value+ }+ if value, ok := latestTimeSeriesValue(history.DiskReadRate); ok {+ system.DiskReadRate = value+ }+ if value, ok := latestTimeSeriesValue(history.DiskWriteRate); ok {+ system.DiskWriteRate = value+ }+ return system+}++// latestTimeSeriesValue returns the most recent sample in a series by+// timestamp, so an unordered reporting payload cannot select a stale point.+func latestTimeSeriesValue(series []TimeSeriesPoint) (float64, bool) {+ if len(series) == 0 {+ return 0, false+ }+ latest := series[0]+ for _, point := range series[1:] {+ if point.Timestamp.After(latest.Timestamp) {+ latest = point+ }+ }+ return latest.Value, true+}++// legacyRESTReportingGraphs is the reporting.get_data graph set used to+// reconstruct live telemetry and history over the legacy REST transport.+func legacyRESTReportingGraphs() []map[string]any {+ return []map[string]any{+ {"name": "cpu", "identifier": nil},+ {"name": "memory", "identifier": nil},+ {"name": "arcsize", "identifier": nil},+ {"name": "interface", "identifier": nil},+ {"name": "disk", "identifier": nil},+ }+}++// getReportingDataREST issues reporting.get_data over the REST v2.0 transport.+// The middleware method takes positional parameters (graphs, query); REST+// serves it as a POST body keyed by parameter name.+func (c *Client) getReportingDataREST(ctx context.Context, graphs []map[string]any, query map[string]any) ([]trueNASReportingGetDataResponse, error) {+ var response []trueNASReportingGetDataResponse+ err := c.postJSON(ctx, "/reporting/get_data", map[string]any{+ "graphs": graphs,+ "query": query,+ }, &response)+ if err != nil {+ return nil, err+ }+ return response, nil+}+// GetSystemMetricHistory retrieves historical system metrics from the native// TrueNAS reporting API for the canonical host-chart fallback path.func (c *Client) GetSystemMetricHistory(ctx context.Context, duration time.Duration) (*SystemMetricHistory, error) {+ legacy, err := c.useLegacyREST(ctx)+ if err != nil {+ return nil, err+ }+ if legacy {+ return c.getSystemMetricHistoryREST(ctx, duration)+ }+var history *SystemMetricHistory- err := c.withRPC(ctx, func(rpc *trueNASRPCClient) error {+ err = c.withRPC(ctx, func(rpc *trueNASRPCClient) error {var err errorhistory, err = rpc.getSystemMetricHistory(ctx, duration)return err@@ -271,6 +395,28 @@ func (c *Client) GetSystemMetricHistory(ctx context.Context, duration time.Duratreturn history, err}+// getSystemMetricHistoryREST serves the host-chart history from the legacy REST+// reporting API, mirroring the JSON-RPC query for CORE appliances.+func (c *Client) getSystemMetricHistoryREST(ctx context.Context, duration time.Duration) (*SystemMetricHistory, error) {+ if duration <= 0 {+ duration = 24 * time.Hour+ }+ end := time.Now().Unix()+ start := end - int64(duration.Seconds())+ if start <= 0 {+ start = end+ }+ response, err := c.getReportingDataREST(ctx, legacyRESTReportingGraphs(), map[string]any{+ "aggregate": false,+ "start": start,+ "end": end,+ })+ if err != nil {+ return nil, err+ }+ return parseSystemMetricHistory(response), nil+}+// GetPools returns storage pools.func (c *Client) GetPools(ctx context.Context) ([]Pool, error) {legacy, err := c.useLegacyREST(ctx)diff --git a/internal/truenas/issue2077_core_memory_test.go b/internal/truenas/issue2077_core_memory_test.gonew file mode 100644index 0000000000..99451d3352--- /dev/null+++ b/internal/truenas/issue2077_core_memory_test.go@@ -0,0 +1,134 @@+package truenas++import (+ "context"+ "testing"+ "time"+)++// #2077: on the legacy REST transport (TrueNAS CORE 13) there is no+// reporting.realtime JSON-RPC subscription, so the available-memory reading is+// never populated and the ARC-aware used figure collapses to total (100% used).+// These tests pin the REST reporting fallback and the "usage unavailable"+// guard that replaced the fabricated reading.++func legacyRESTReportingMemoryBody() string {+ return `[+ {+ "name": "memory",+ "identifier": null,+ "legend": ["used", "free", "available", "total"],+ "data": [+ {"timestamp": 1789000000, "used": 12000000000, "free": 2000000000, "available": 20000000000, "total": 34359738368},+ {"timestamp": 1789000060, "used": 13000000000, "free": 3000000000, "available": 21000000000, "total": 34359738368}+ ],+ "start": 1789000000,+ "end": 1789000060+ },+ {+ "name": "arcsize",+ "identifier": null,+ "legend": ["arc_size"],+ "data": [+ {"timestamp": 1789000060, "arc_size": 8000000000}+ ],+ "start": 1789000000,+ "end": 1789000060+ }+ ]`+}++func newLegacyRESTReportingClient(t *testing.T, routes alertArgsTransport) *Client {+ t.Helper()+ client, err := NewClient(ClientConfig{Host: "http://truenas.invalid", APIKey: "synthetic"})+ if err != nil {+ t.Fatal(err)+ }+ client.httpClient.Transport = routes+ client.mode = TransportLegacyREST+ return client+}++func TestRESTSystemTelemetryReadsReportingMemory(t *testing.T) {+ routes := alertArgsTransport(defaultAPIResponses())+ routes["/api/v2.0/system/info"] = apiResponse{body: `{"hostname":"core","version":"TrueNAS-13.0-U6.1","physmem":34359738368}`}+ routes["/api/v2.0/reporting/get_data"] = apiResponse{body: legacyRESTReportingMemoryBody()}++ client := newLegacyRESTReportingClient(t, routes)+ telemetry, err := client.GetSystemTelemetry(context.Background())+ if err != nil {+ t.Fatalf("GetSystemTelemetry() error = %v", err)+ }+ if telemetry == nil {+ t.Fatal("expected telemetry")+ }+ if telemetry.MemoryTotalBytes != 34359738368 {+ t.Fatalf("MemoryTotalBytes = %d, want 34359738368", telemetry.MemoryTotalBytes)+ }+ if telemetry.MemoryAvailableBytes != 21000000000 {+ t.Fatalf("MemoryAvailableBytes = %d, want latest sample 21000000000", telemetry.MemoryAvailableBytes)+ }+ if telemetry.ARCSizeBytes != 8000000000 {+ t.Fatalf("ARCSizeBytes = %d, want 8000000000", telemetry.ARCSizeBytes)+ }++ metrics := metricsFromTrueNASSystem(*telemetry, 0, 0)+ if metrics.Memory == nil || metrics.Memory.Used == nil {+ t.Fatalf("expected derived memory usage, got %+v", metrics.Memory)+ }+ wantUsed := int64(34359738368 - 21000000000 - 8000000000)+ if *metrics.Memory.Used != wantUsed {+ t.Fatalf("used = %d, want %d", *metrics.Memory.Used, wantUsed)+ }+ if metrics.Memory.Percent >= 99 {+ t.Fatalf("memory percent = %v, want a real reading below 99", metrics.Memory.Percent)+ }++ agent := agentDataFromTrueNASSystem("conn-core", *telemetry, nil, nil, false, "", false, "")+ if agent.Memory == nil || agent.Memory.UsageUnavailable {+ t.Fatalf("expected known agent memory, got %+v", agent.Memory)+ }+ if agent.Memory.Used != wantUsed || agent.Memory.Cache != 8000000000 {+ t.Fatalf("unexpected agent memory: %+v", agent.Memory)+ }+}++func TestRESTSystemMetricHistoryUsesReporting(t *testing.T) {+ routes := alertArgsTransport(defaultAPIResponses())+ routes["/api/v2.0/reporting/get_data"] = apiResponse{body: legacyRESTReportingMemoryBody()}++ client := newLegacyRESTReportingClient(t, routes)+ history, err := client.GetSystemMetricHistory(context.Background(), time.Hour)+ if err != nil {+ t.Fatalf("GetSystemMetricHistory() error = %v", err)+ }+ if history == nil {+ t.Fatal("expected history")+ }+ if len(history.MemoryAvailableBytes) != 2 {+ t.Fatalf("MemoryAvailableBytes points = %d, want 2", len(history.MemoryAvailableBytes))+ }+ if len(history.ARCSizeBytes) != 1 {+ t.Fatalf("ARCSizeBytes points = %d, want 1", len(history.ARCSizeBytes))+ }+}++func TestTrueNASMemoryWithoutAvailableIsNotReportedAsUsed(t *testing.T) {+ system := SystemInfo{Hostname: "core", MemoryTotalBytes: 34359738368}++ metrics := metricsFromTrueNASSystem(system, 0, 0)+ if metrics.Memory != nil {+ t.Fatalf("fabricated memory metric without an available reading: %+v", metrics.Memory)+ }++ agent := agentDataFromTrueNASSystem("conn-core", system, nil, nil, false, "", false, "")+ if agent.Memory == nil {+ t.Fatal("expected agent memory capacity")+ }+ if !agent.Memory.UsageUnavailable {+ t.Fatalf("UsageUnavailable = false, want true: %+v", agent.Memory)+ }+ if agent.Memory.Total != 34359738368 || agent.Memory.Used != 0 {+ t.Fatalf("unexpected agent memory: %+v", agent.Memory)+ }+}diff --git a/internal/truenas/provider.go b/internal/truenas/provider.goindex 686391c7d9..e81c5ef029 100644--- a/internal/truenas/provider.go+++ b/internal/truenas/provider.go@@ -916,6 +916,14 @@ func trueNASReclaimableARC(system SystemInfo) int64 {return arc}+// trueNASMemoryUsageKnown reports whether the appliance supplied an available+// memory reading. Without it the ARC-aware used figure cannot be derived, and+// treating the zero value as a measurement reports total capacity as 100% used+// (#2077, legacy REST transport on TrueNAS CORE).+func trueNASMemoryUsageKnown(system SystemInfo) bool {+ return system.MemoryAvailableBytes > 0+}+// trueNASEffectiveMemoryUsed treats the ZFS ARC as reclaimable cache, the// same way node memory accounting treats buffers and page cache: the// kernel's MemAvailable does not count ARC even though it shrinks under@@ -944,7 +952,7 @@ func metricsFromTrueNASSystem(system SystemInfo, totalCapacity, totalUsed int64)}}- if system.MemoryTotalBytes > 0 {+ if system.MemoryTotalBytes > 0 && trueNASMemoryUsageKnown(system) {used := trueNASEffectiveMemoryUsed(system)memory := &unifiedresources.MetricValue{Used: &used,@@ -952,10 +960,8 @@ func metricsFromTrueNASSystem(system SystemInfo, totalCapacity, totalUsed int64)Unit: "bytes",Source: unifiedresources.SourceTrueNAS,}- if system.MemoryTotalBytes > 0 {- memory.Percent = (float64(used) / float64(system.MemoryTotalBytes)) * 100- memory.Value = memory.Percent- }+ memory.Percent = (float64(used) / float64(system.MemoryTotalBytes)) * 100+ memory.Value = memory.Percentmetrics.Memory = memory}@@ -1010,16 +1016,26 @@ func agentDataFromTrueNASSystem(connectionID string, system SystemInfo, disks []}if system.MemoryTotalBytes > 0 {- used := trueNASEffectiveMemoryUsed(system)- free := system.MemoryAvailableBytes- if free < 0 {- free = 0- }- agent.Memory = &unifiedresources.AgentMemoryMeta{- Total: system.MemoryTotalBytes,- Used: used,- Free: free,- Cache: trueNASReclaimableARC(system),+ if trueNASMemoryUsageKnown(system) {+ used := trueNASEffectiveMemoryUsed(system)+ free := system.MemoryAvailableBytes+ if free < 0 {+ free = 0+ }+ agent.Memory = &unifiedresources.AgentMemoryMeta{+ Total: system.MemoryTotalBytes,+ Used: used,+ Free: free,+ Cache: trueNASReclaimableARC(system),+ }+ } else {+ // Total capacity is known but the appliance did not report an+ // available reading; preserve the capacity without inventing usage+ // from total-0 (#2077).+ agent.Memory = &unifiedresources.AgentMemoryMeta{+ Total: system.MemoryTotalBytes,+ UsageUnavailable: true,+ }}}if temperature := maxTrueNASSystemTemperature(system); temperature != nil {