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
feat(truenas): project system telemetry through canonical host history
rcourtman16f976537fe9
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex daf07c0b3b..7aae46b6b5 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -239,3 +239,12 @@ canonical `app-container` metrics contract, and sync them into the existingguest metrics-history/store path. Pulse must not add a TrueNAS-only chartspath or treat API-backed app workloads as second-class compared with nativeDocker reports.+That same monitoring boundary now also owns API-backed TrueNAS system+telemetry for the top-level NAS host. `internal/truenas/client.go` must ingest+`reporting.realtime` through the official `/api/current` JSON-RPC websocket+transport, `internal/truenas/provider.go` must project those readings onto the+canonical host `AgentData` and shared `ResourceMetrics` contract, and+`internal/monitoring/monitor.go` must sync them into the existing `agent`+metrics-history/store path. Pulse must not add a TrueNAS-only top-level+system charts path or leave TrueNAS host telemetry outside the canonical host+history contract.diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex ab2a360265..374ecd9f25 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -172,6 +172,14 @@ lane-local workload UI. API-backed `app.stats` telemetry must now project ontothat same canonical `app-container` contract as live metrics and metricstargets, using the shared `docker:<id>` in-memory key and `dockerContainer`history store path instead of adding a TrueNAS-local workload history lane.+TrueNAS top-level systems now follow the same canonical host rule. One+TrueNAS appliance must project as one canonical `agent` resource under+`SourceTrueNAS`, carrying host-facing `AgentData` plus provider-specific+`TrueNASData` instead of inventing a `truenas-system` resource type or a+provider-local host surface. API-backed `reporting.realtime` telemetry must+project onto that same canonical `agent` contract as live metrics and metrics+targets, using the shared `agent:<id>` in-memory key and `agent` history store+path instead of adding a TrueNAS-only host history lane.The canonical resource timeline now also owns durable incident-response factsthat materially changed resource investigation state. `ResourceChange` kindssuch as `alert_fired`, `alert_acknowledged`, `alert_unacknowledged`,diff --git a/internal/api/resources_test.go b/internal/api/resources_test.goindex 39bffd8897..9dcf170de4 100644--- a/internal/api/resources_test.go+++ b/internal/api/resources_test.go@@ -3000,6 +3000,58 @@ func TestResourceListIncludesTrueNASAppsAsAppContainers(t *testing.T) {}}+func TestResourceListIncludesTrueNASSystemAsCanonicalHost(t *testing.T) {+ previous := truenas.IsFeatureEnabled()+ truenas.SetFeatureEnabled(true)+ t.Cleanup(func() {+ truenas.SetFeatureEnabled(previous)+ })++ cfg := &config.Config{DataPath: t.TempDir()}+ h := NewResourceHandlers(cfg)+ h.SetStateProvider(resourceStateProvider{snapshot: models.StateSnapshot{LastUpdate: time.Now().UTC()}})+ h.SetSupplementalRecordsProvider(unified.SourceTrueNAS, mockSupplementalRecordsProvider{+ records: truenas.NewProvider(truenas.DefaultFixtures()).Records(),+ ownedSources: []unified.DataSource{unified.SourceTrueNAS},+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/resources?type=agent&source=truenas", nil)+ h.HandleListResources(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())+ }++ var resp ResourcesResponse+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(resp.Data) == 0 {+ t.Fatal("expected TrueNAS system resources")+ }++ var system *unified.Resource+ for i := range resp.Data {+ if resp.Data[i].Name == "truenas-main" {+ system = &resp.Data[i]+ break+ }+ }+ if system == nil {+ t.Fatalf("expected truenas-main in response, got %+v", resp.Data)+ }+ if system.Agent == nil || system.Agent.Platform != "truenas" {+ t.Fatalf("expected canonical host payload on TrueNAS system resource, got %+v", system)+ }+ if system.Metrics == nil || system.Metrics.CPU == nil || system.Metrics.Memory == nil {+ t.Fatalf("expected canonical host metrics on TrueNAS system resource, got %+v", system)+ }+ if system.MetricsTarget == nil || system.MetricsTarget.ResourceType != "agent" || system.MetricsTarget.ResourceID != "truenas-main" {+ t.Fatalf("expected canonical TrueNAS host metrics target truenas-main, got %+v", system.MetricsTarget)+ }+}+func TestResourceStorageIncidentsGroupsCanonicalSections(t *testing.T) {now := time.Now().UTC()cfg := &config.Config{DataPath: t.TempDir()}diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex d58b2d6cad..e4d75db13b 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -168,6 +168,26 @@ func TestUnifiedAppContainerMetricsUseCanonicalGuestHistoryPath(t *testing.T) {}}+func TestUnifiedAgentMetricsUseCanonicalHostHistoryPath(t *testing.T) {+ data, err := os.ReadFile("monitor.go")+ if err != nil {+ t.Fatalf("failed to read monitor.go: %v", err)+ }+ source := string(data)+ requiredSnippets := []string{+ "m.syncUnifiedAgentMetrics(store)",+ `if target == nil || target.ResourceType != "agent" || strings.TrimSpace(target.ResourceID) == "" {`,+ `metricKey := fmt.Sprintf("agent:%s", targetID)`,+ `m.metricsStore.Write("agent", targetID, "cpu", value, now)`,+ `m.metricsStore.Write("agent", targetID, "diskwrite", metric.Value, now)`,+ }+ for _, snippet := range requiredSnippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("monitor.go must contain %q", snippet)+ }+ }+}+func TestHostAgentRemovalGuardUsesResolvedIdentifier(t *testing.T) {data, err := os.ReadFile("monitor_agents.go")if err != nil {diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex a50c88dbaa..951ccaa0d7 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -4136,6 +4136,7 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {recordsBySource := m.collectSupplementalRecordsBySource()if atomicStore, ok := store.(AtomicSnapshotResourceStore); ok {atomicStore.PopulateSnapshotAndSupplemental(snapshotForStore, recordsBySource)+ m.syncUnifiedAgentMetrics(store)m.syncUnifiedStorageMetrics(store)m.syncUnifiedAppContainerMetrics(store)for source, records := range recordsBySource {@@ -4167,11 +4168,116 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {}}+ m.syncUnifiedAgentMetrics(store)m.syncUnifiedStorageMetrics(store)m.syncUnifiedAppContainerMetrics(store)m.syncUnifiedResourceAlertsToState(store.GetAll())}+func (m *Monitor) syncUnifiedAgentMetrics(store ResourceStoreInterface) {+ if store == nil || (m.metricsHistory == nil && m.metricsStore == nil) {+ return+ }++ resolver, ok := store.(MetricsTargetResourceStore)+ if !ok {+ return+ }++ now := time.Now()+ seenTargets := make(map[string]struct{})+ for _, resource := range store.GetAll() {+ if resource.Type != unifiedresources.ResourceTypeAgent || resource.Metrics == nil {+ continue+ }+ if monitorHasSource(resource.Sources, unifiedresources.SourceAgent) ||+ monitorHasSource(resource.Sources, unifiedresources.SourceProxmox) ||+ monitorHasSource(resource.Sources, unifiedresources.SourceDocker) {+ continue+ }++ target := resolver.MetricsTargetForResource(resource.ID)+ if target == nil || target.ResourceType != "agent" || strings.TrimSpace(target.ResourceID) == "" {+ continue+ }+ targetID := strings.TrimSpace(target.ResourceID)+ if _, ok := seenTargets[targetID]; ok {+ continue+ }+ seenTargets[targetID] = struct{}{}+ metricKey := fmt.Sprintf("agent:%s", targetID)++ if metric := resource.Metrics.CPU; metric != nil {+ value := metric.Percent+ if value == 0 {+ value = metric.Value+ }+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "cpu", value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "cpu", value, now)+ }+ }++ if metric := resource.Metrics.Memory; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {+ value := metric.Percent+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "memory", value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "memory", value, now)+ }+ }++ if metric := resource.Metrics.Disk; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {+ value := metric.Percent+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "disk", value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "disk", value, now)+ }+ }++ if metric := resource.Metrics.NetIn; metric != nil {+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "netin", metric.Value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "netin", metric.Value, now)+ }+ }++ if metric := resource.Metrics.NetOut; metric != nil {+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "netout", metric.Value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "netout", metric.Value, now)+ }+ }++ if metric := resource.Metrics.DiskRead; metric != nil {+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "diskread", metric.Value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "diskread", metric.Value, now)+ }+ }++ if metric := resource.Metrics.DiskWrite; metric != nil {+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "diskwrite", metric.Value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("agent", targetID, "diskwrite", metric.Value, now)+ }+ }+ }+}+func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {if store == nil || (m.metricsHistory == nil && m.metricsStore == nil) {returndiff --git a/internal/monitoring/monitor_polling_test.go b/internal/monitoring/monitor_polling_test.goindex 82a6f143f4..89e1e69730 100644--- a/internal/monitoring/monitor_polling_test.go+++ b/internal/monitoring/monitor_polling_test.go@@ -540,6 +540,64 @@ func TestSyncUnifiedAppContainerMetricsRecordsTrueNASHistory(t *testing.T) {}}+func TestSyncUnifiedAgentMetricsRecordsTrueNASHostHistory(t *testing.T) {+ previous := truenas.IsFeatureEnabled()+ truenas.SetFeatureEnabled(true)+ t.Cleanup(func() {+ truenas.SetFeatureEnabled(previous)+ })++ cfg := metrics.DefaultConfig(t.TempDir())+ store, err := metrics.NewStore(cfg)+ if err != nil {+ t.Fatalf("metrics.NewStore() error = %v", err)+ }+ defer func() { _ = store.Close() }()++ resourceStore := unifiedresources.NewMonitorAdapter(nil)+ records := truenas.NewProvider(truenas.DefaultFixtures()).Records()+ resourceStore.PopulateSnapshotAndSupplemental(models.StateSnapshot{}, map[unifiedresources.DataSource][]unifiedresources.IngestRecord{+ unifiedresources.SourceTrueNAS: records,+ })++ monitor := &Monitor{+ resourceStore: resourceStore,+ metricsHistory: NewMetricsHistory(1024, 24*time.Hour),+ metricsStore: store,+ }++ monitor.syncUnifiedAgentMetrics(resourceStore)++ var systemResourceID string+ for _, resource := range resourceStore.GetAll() {+ if resource.Type == unifiedresources.ResourceTypeAgent && resource.Name == "truenas-main" {+ systemResourceID = resource.ID+ break+ }+ }+ if systemResourceID == "" {+ t.Fatal("expected TrueNAS system resource in unified store")+ }++ target := resourceStore.MetricsTargetForResource(systemResourceID)+ if target == nil || target.ResourceType != "agent" || target.ResourceID != "truenas-main" {+ t.Fatalf("unexpected agent metrics target %+v", target)+ }++ inMemory := monitor.GetGuestMetrics("agent:truenas-main", time.Hour)+ if got := len(inMemory["cpu"]); got == 0 {+ t.Fatalf("expected in-memory cpu history for truenas-main")+ }+ if got := len(inMemory["netin"]); got == 0 {+ t.Fatalf("expected in-memory network history for truenas-main")+ }++ storeBacked := monitor.GetGuestMetricsForChart("agent:truenas-main", "agent", "truenas-main", 7*24*time.Hour)+ if got := len(storeBacked["cpu"]); got == 0 {+ t.Fatalf("expected persisted cpu history for truenas-main")+ }+}+func TestBuildBroadcastFrontendStatePrefersLiveAlertManagerOverSnapshotAlerts(t *testing.T) {alertManager := alerts.NewManagerWithDataDir(t.TempDir())defer alertManager.Stop()diff --git a/internal/truenas/client.go b/internal/truenas/client.goindex 97e15a9fa0..0af47bda48 100644--- a/internal/truenas/client.go+++ b/internal/truenas/client.go@@ -24,7 +24,9 @@ const defaultHTTPTimeout = 30 * time.Secondconst maxResponseBodyBytes int64 = 4 * 1024 * 1024-const defaultAppStatsIntervalSeconds = 2+const defaultRealtimeIntervalSeconds = 2++const defaultAppStatsIntervalSeconds = defaultRealtimeIntervalSeconds// ClientConfig configures the TrueNAS REST API client.type ClientConfig struct {@@ -151,17 +153,50 @@ func (c *Client) GetSystemInfo(ctx context.Context) (*SystemInfo, error) {if build == "" {build = strings.TrimSpace(response.Version)}+ cpuCount := response.PhysicalCores+ if cpuCount <= 0 {+ cpuCount = response.Cores+ }return &SystemInfo{- Hostname: strings.TrimSpace(response.Hostname),- Version: strings.TrimSpace(response.Version),- Build: build,- UptimeSeconds: response.UptimeSeconds,- Healthy: true,- MachineID: machineID,+ Hostname: strings.TrimSpace(response.Hostname),+ Version: strings.TrimSpace(response.Version),+ Build: build,+ UptimeSeconds: response.UptimeSeconds,+ Healthy: true,+ MachineID: machineID,+ CPUCount: cpuCount,+ MemoryTotalBytes: response.Physmem,}, nil}+// GetSystemTelemetry retrieves live system telemetry from the modern TrueNAS+// JSON-RPC websocket API. This path is best-effort; callers should treat any+// transport or endpoint failure as "telemetry unavailable" rather than a+// system identity failure.+func (c *Client) GetSystemTelemetry(ctx context.Context) (*SystemInfo, error) {+ conn, err := c.dialRPC(ctx)+ if err != nil {+ return nil, err+ }+ defer func() { _ = conn.Close() }()++ rpc := trueNASRPCClient{+ conn: conn,+ nextID: 1,+ }+ if err := rpc.authenticate(ctx, c.config); err != nil {+ return nil, err+ }++ subscriptionName := fmt.Sprintf("reporting.realtime:{\"interval\":%d}", defaultRealtimeIntervalSeconds)+ if err := rpc.call(ctx, "core.subscribe", []any{subscriptionName}, nil); err != nil {+ return nil, err+ }++ return rpc.readSystemTelemetryEvent(ctx, defaultRealtimeIntervalSeconds)+}+// GetPools returns storage pools.func (c *Client) GetPools(ctx context.Context) ([]Pool, error) {var response []poolResponse@@ -538,6 +573,9 @@ func (c *Client) FetchSnapshot(ctx context.Context) (*FixtureSnapshot, error) {if err != nil {return nil, fmt.Errorf("fetch truenas system info: %w", err)}+ if telemetry, err := c.GetSystemTelemetry(ctx); err == nil && telemetry != nil {+ mergeSystemTelemetry(system, telemetry)+ }pools, err := c.GetPools(ctx)if err != nil {@@ -577,6 +615,32 @@ func (c *Client) FetchSnapshot(ctx context.Context) (*FixtureSnapshot, error) {}, nil}+func mergeSystemTelemetry(system *SystemInfo, telemetry *SystemInfo) {+ if system == nil || telemetry == nil {+ return+ }+ if telemetry.CPUCount > 0 {+ system.CPUCount = telemetry.CPUCount+ }+ if telemetry.MemoryTotalBytes > 0 {+ system.MemoryTotalBytes = telemetry.MemoryTotalBytes+ }+ if telemetry.MemoryAvailableBytes > 0 {+ system.MemoryAvailableBytes = telemetry.MemoryAvailableBytes+ }+ system.CPUPercent = telemetry.CPUPercent+ system.NetInRate = telemetry.NetInRate+ system.NetOutRate = telemetry.NetOutRate+ system.DiskReadRate = telemetry.DiskReadRate+ system.DiskWriteRate = telemetry.DiskWriteRate+ if telemetry.IntervalSeconds > 0 {+ system.IntervalSeconds = telemetry.IntervalSeconds+ }+ if !telemetry.CollectedAt.IsZero() {+ system.CollectedAt = telemetry.CollectedAt+ }+}+func temperatureForTrueNASDisk(temperatures map[string]int, item diskResponse) int {if len(temperatures) == 0 {return 0@@ -714,6 +778,11 @@ type trueNASAppBlkIOStats struct {Write int64 `json:"write"`}+type trueNASRealtimeNotification struct {+ Collection string `json:"collection"`+ Fields map[string]any `json:"fields"`+}+func (c *Client) dialRPC(ctx context.Context) (*websocket.Conn, error) {if c == nil {return nil, fmt.Errorf("truenas client is nil")@@ -870,10 +939,149 @@ func (c *trueNASRPCClient) readAppStatsEvent(ctx context.Context, intervalSecond}}+func (c *trueNASRPCClient) readSystemTelemetryEvent(ctx context.Context, intervalSeconds int) (*SystemInfo, error) {+ if c == nil || c.conn == nil {+ return nil, fmt.Errorf("truenas rpc connection is nil")+ }++ for {+ if deadline, ok := ctx.Deadline(); ok {+ _ = c.conn.SetReadDeadline(deadline)+ }++ var message trueNASRPCResponse+ if err := c.conn.ReadJSON(&message); err != nil {+ return nil, fmt.Errorf("read truenas rpc reporting.realtime notification: %w", err)+ }+ if message.Method == "" {+ if message.Error != nil {+ return nil, fmt.Errorf("truenas rpc reporting.realtime failed: code=%d message=%q", message.Error.Code, strings.TrimSpace(message.Error.Message))+ }+ continue+ }++ fields, ok, err := parseRealtimeFields(message, "reporting.realtime")+ if err != nil {+ return nil, err+ }+ if !ok {+ continue+ }++ return parseSystemTelemetry(fields, intervalSeconds, time.Now().UTC()), nil+ }+}+func normalizeAppStatsKey(value string) string {return strings.ToLower(strings.TrimSpace(value))}+func parseRealtimeFields(message trueNASRPCResponse, collectionPrefix string) (map[string]any, bool, error) {+ method := strings.TrimSpace(message.Method)+ switch method {+ case "collection_update":+ var notification trueNASRealtimeNotification+ if err := json.Unmarshal(message.Params, ¬ification); err != nil {+ return nil, false, fmt.Errorf("decode truenas %s notification: %w", collectionPrefix, err)+ }+ if !strings.HasPrefix(strings.TrimSpace(notification.Collection), collectionPrefix) {+ return nil, false, nil+ }+ if len(notification.Fields) == 0 {+ return nil, false, nil+ }+ return notification.Fields, true, nil+ default:+ if !strings.HasPrefix(method, collectionPrefix) {+ return nil, false, nil+ }+ var payload map[string]any+ if len(message.Params) == 0 {+ return nil, false, nil+ }+ if err := json.Unmarshal(message.Params, &payload); err != nil {+ return nil, false, fmt.Errorf("decode truenas %s notification: %w", collectionPrefix, err)+ }+ if fields := readMapAny(payload, "fields"); len(fields) > 0 {+ return fields, true, nil+ }+ return payload, true, nil+ }+}++func parseSystemTelemetry(fields map[string]any, intervalSeconds int, collectedAt time.Time) *SystemInfo {+ if len(fields) == 0 {+ return &SystemInfo{+ IntervalSeconds: intervalSeconds,+ CollectedAt: collectedAt,+ }+ }++ telemetry := &SystemInfo{+ IntervalSeconds: intervalSeconds,+ CollectedAt: collectedAt,+ }++ cpu := readMapAny(fields, "cpu")+ cpuPercent := readFloatAny(cpu,+ "usage",+ "percent",+ "usage_percent",+ "cpu_usage",+ "cpu_percent",+ "total",+ "overall",+ )+ if cpuPercent == 0 {+ if usage := readMapAny(cpu, "usage", "total"); len(usage) > 0 {+ cpuPercent = readFloatAny(usage, "percent", "value", "usage")+ }+ }+ telemetry.CPUPercent = cpuPercent++ memory := readMapAny(fields, "memory")+ total := readInt64Any(memory, "physical_memory_total", "total", "memory_total", "total_bytes")+ available := readInt64Any(memory, "physical_memory_available", "available", "free", "available_bytes", "free_bytes")+ telemetry.MemoryTotalBytes = total+ telemetry.MemoryAvailableBytes = available++ interfaces := readMapAny(fields, "interfaces")+ for _, raw := range interfaces {+ record, ok := raw.(map[string]any)+ if !ok {+ continue+ }+ telemetry.NetInRate += readFloatAny(record,+ "rx_bytes",+ "received_bytes",+ "received_bytes_rate",+ "rx_bytes_rate",+ "bytes_recv",+ "bytes_received",+ )+ telemetry.NetOutRate += readFloatAny(record,+ "tx_bytes",+ "sent_bytes",+ "sent_bytes_rate",+ "tx_bytes_rate",+ "bytes_sent",+ "bytes_transmitted",+ )+ }++ disks := readMapAny(fields, "disks", "disls")+ for _, raw := range disks {+ record, ok := raw.(map[string]any)+ if !ok {+ continue+ }+ telemetry.DiskReadRate += readFloatAny(record, "read_bytes", "read_bytes_rate", "bytes_read")+ telemetry.DiskWriteRate += readFloatAny(record, "write_bytes", "write_bytes_rate", "bytes_written")+ }++ return telemetry+}+func firstAny(record map[string]any, keys ...string) (any, bool) {if record == nil {return nil, false@@ -975,6 +1183,38 @@ func readIntAny(record map[string]any, keys ...string) int {return 0}+func readInt64Any(record map[string]any, keys ...string) int64 {+ if record == nil {+ return 0+ }+ for _, key := range keys {+ value, ok := record[key]+ if !ok || value == nil {+ continue+ }+ if parsed, ok := parseInt64Any(value); ok {+ return parsed+ }+ }+ return 0+}++func readFloatAny(record map[string]any, keys ...string) float64 {+ if record == nil {+ return 0+ }+ for _, key := range keys {+ value, ok := record[key]+ if !ok || value == nil {+ continue+ }+ if parsed, ok := parseFloat64Any(value); ok {+ return parsed+ }+ }+ return 0+}+func parseAppPorts(entries []any) []AppPort {if len(entries) == 0 {return nil@@ -1438,6 +1678,9 @@ type systemInfoResponse struct {UptimeSeconds int64 `json:"uptime_seconds"`SystemSerial string `json:"system_serial"`SystemVendor string `json:"system_manufacturer"`+ Cores int `json:"cores"`+ PhysicalCores int `json:"physical_cores"`+ Physmem int64 `json:"physmem"`}type poolResponse struct {@@ -1729,6 +1972,36 @@ func parseInt64Any(value any) (int64, bool) {return 0, false}+func parseFloat64Any(value any) (float64, bool) {+ switch typed := value.(type) {+ case float64:+ return typed, true+ case float32:+ return float64(typed), true+ case int64:+ return float64(typed), true+ case int:+ return float64(typed), true+ case json.Number:+ if v, err := typed.Float64(); err == nil {+ return v, true+ }+ case string:+ s := strings.TrimSpace(typed)+ if s == "" {+ return 0, false+ }+ if v, err := strconv.ParseFloat(s, 64); err == nil {+ return v, true+ }+ case map[string]any:+ if parsed, ok := firstAny(typed, "parsed", "value", "rawvalue"); ok {+ return parseFloat64Any(parsed)+ }+ }+ return 0, false+}+func readTimeAny(record map[string]any, keys ...string) *time.Time {if record == nil {return nildiff --git a/internal/truenas/client_test.go b/internal/truenas/client_test.goindex 5e4a9a195b..e015edd52a 100644--- a/internal/truenas/client_test.go+++ b/internal/truenas/client_test.go@@ -55,6 +55,9 @@ func TestClientGetters(t *testing.T) {if !system.Healthy || system.MachineID != "SER123" {t.Fatalf("unexpected system health/identity: %+v", system)}+ if system.CPUCount != 16 || system.MemoryTotalBytes != 68719476736 {+ t.Fatalf("unexpected system capacity mapping: %+v", system)+ }pools, err := client.GetPools(ctx)if err != nil {@@ -277,6 +280,67 @@ func TestGetAppsEnrichesStatsFromRPC(t *testing.T) {}}+func TestGetSystemTelemetryFromRPC(t *testing.T) {+ server := newMockServerWithRPC(t, defaultAPIResponses(), nil, func(t *testing.T, conn *websocket.Conn) {+ authReq := readRPCRequest(t, conn)+ if authReq.Method != "auth.login_with_api_key" {+ t.Fatalf("expected api-key auth method, got %q", authReq.Method)+ }+ writeRPCResult(t, conn, authReq.ID, true)++ subscribeReq := readRPCRequest(t, conn)+ if subscribeReq.Method != "core.subscribe" {+ t.Fatalf("expected core.subscribe, got %q", subscribeReq.Method)+ }+ writeRPCResult(t, conn, subscribeReq.ID, "sub-1")+ writeRPCNotification(t, conn, "collection_update", map[string]any{+ "collection": "reporting.realtime:{\"interval\":2}",+ "fields": map[string]any{+ "cpu": map[string]any{+ "usage": 41,+ },+ "memory": map[string]any{+ "physical_memory_total": 68719476736,+ "physical_memory_available": 21474836480,+ },+ "interfaces": map[string]any{+ "enp1s0": map[string]any{"rx_bytes": 4096, "tx_bytes": 2048},+ "enp2s0": map[string]any{"received_bytes": 1024, "sent_bytes": 512},+ },+ "disks": map[string]any{+ "sda": map[string]any{"read_bytes": 2048, "write_bytes": 1024},+ "nvme0n1": map[string]any{"read_bytes": 4096, "write_bytes": 3072},+ },+ },+ })+ })+ t.Cleanup(server.Close)++ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})+ system, err := client.GetSystemTelemetry(context.Background())+ if err != nil {+ t.Fatalf("GetSystemTelemetry() error = %v", err)+ }+ if system == nil {+ t.Fatal("expected system telemetry")+ }+ if system.CPUPercent != 41 {+ t.Fatalf("expected cpu percent 41, got %+v", system)+ }+ if system.MemoryTotalBytes != 68719476736 || system.MemoryAvailableBytes != 21474836480 {+ t.Fatalf("unexpected memory telemetry: %+v", system)+ }+ if system.NetInRate != 5120 || system.NetOutRate != 2560 {+ t.Fatalf("unexpected network telemetry: %+v", system)+ }+ if system.DiskReadRate != 6144 || system.DiskWriteRate != 4096 {+ t.Fatalf("unexpected disk telemetry: %+v", system)+ }+ if system.IntervalSeconds != 2 || system.CollectedAt.IsZero() {+ t.Fatalf("expected interval/collectedAt metadata, got %+v", system)+ }+}+func TestGetDiskTemperaturesSupportsArrayShape(t *testing.T) {server := newMockServer(t, map[string]apiResponse{"/api/v2.0/disk/temperatures": {@@ -502,7 +566,7 @@ func TestClientCloseNilSafe(t *testing.T) {func defaultAPIResponses() map[string]apiResponse {return map[string]apiResponse{"/api/v2.0/system/info": {- body: `{"hostname":"truenas-main","version":"TrueNAS-SCALE-24.10.2","buildtime":"24.10.2.1","uptime_seconds":86400,"system_serial":"SER123","system_manufacturer":"iXsystems"}`,+ body: `{"hostname":"truenas-main","version":"TrueNAS-SCALE-24.10.2","buildtime":"24.10.2.1","uptime_seconds":86400,"system_serial":"SER123","system_manufacturer":"iXsystems","physical_cores":16,"physmem":68719476736}`,},"/api/v2.0/pool": {body: `[{"id":1,"name":"tank","status":"ONLINE","size":1000,"allocated":400,"free":600}]`,diff --git a/internal/truenas/fixtures.go b/internal/truenas/fixtures.goindex 2937e2e47f..e5a0f1823e 100644--- a/internal/truenas/fixtures.go+++ b/internal/truenas/fixtures.go@@ -7,12 +7,22 @@ func DefaultFixtures() FixtureSnapshot {return FixtureSnapshot{CollectedAt: time.Date(2026, 2, 8, 12, 0, 0, 0, time.UTC),System: SystemInfo{- Hostname: "truenas-main",- Version: "TrueNAS-SCALE-24.10.2",- Build: "24.10.2.1",- UptimeSeconds: 42 * 24 * 60 * 60,- Healthy: true,- MachineID: "truenas-1-machine-id",+ Hostname: "truenas-main",+ Version: "TrueNAS-SCALE-24.10.2",+ Build: "24.10.2.1",+ UptimeSeconds: 42 * 24 * 60 * 60,+ Healthy: true,+ MachineID: "truenas-1-machine-id",+ CPUCount: 16,+ MemoryTotalBytes: 64 * 1024 * 1024 * 1024,+ MemoryAvailableBytes: 22 * 1024 * 1024 * 1024,+ CPUPercent: 38,+ NetInRate: 48_000_000,+ NetOutRate: 19_500_000,+ DiskReadRate: 7_200_000,+ DiskWriteRate: 3_400_000,+ IntervalSeconds: 2,+ CollectedAt: time.Date(2026, 2, 8, 12, 0, 0, 0, time.UTC),},Pools: []Pool{{diff --git a/internal/truenas/provider.go b/internal/truenas/provider.goindex 6f1e9dff4d..ba17da9a4e 100644--- a/internal/truenas/provider.go+++ b/internal/truenas/provider.go@@ -191,9 +191,8 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {Status: systemStatus(snapshot.System, systemRisk, systemIncidents),LastSeen: collectedAt,UpdatedAt: collectedAt,- Metrics: &unifiedresources.ResourceMetrics{- Disk: diskMetric(totalCapacity, totalUsed),- },+ Metrics: metricsFromTrueNASSystem(snapshot.System, totalCapacity, totalUsed),+ Agent: agentDataFromTrueNASSystem(snapshot.System, systemRisk, protectionReduced, protectionSummary, rebuildInProgress, rebuildSummary),TrueNAS: &unifiedresources.TrueNASData{Hostname: strings.TrimSpace(snapshot.System.Hostname),Version: snapshot.System.Version,@@ -438,6 +437,107 @@ func metricsFromTrueNASApp(app App) *unifiedresources.ResourceMetrics {return metrics}+func metricsFromTrueNASSystem(system SystemInfo, totalCapacity, totalUsed int64) *unifiedresources.ResourceMetrics {+ hasRealtimeTelemetry := !system.CollectedAt.IsZero() || system.IntervalSeconds > 0+ metrics := &unifiedresources.ResourceMetrics{+ Disk: diskMetric(totalCapacity, totalUsed),+ }++ if hasRealtimeTelemetry {+ metrics.CPU = &unifiedresources.MetricValue{+ Value: system.CPUPercent,+ Percent: system.CPUPercent,+ Unit: "percent",+ Source: unifiedresources.SourceTrueNAS,+ }+ }++ if system.MemoryTotalBytes > 0 {+ used := system.MemoryTotalBytes - system.MemoryAvailableBytes+ if used < 0 {+ used = 0+ }+ memory := &unifiedresources.MetricValue{+ Used: &used,+ Total: &system.MemoryTotalBytes,+ Unit: "bytes",+ Source: unifiedresources.SourceTrueNAS,+ }+ if system.MemoryTotalBytes > 0 {+ memory.Percent = (float64(used) / float64(system.MemoryTotalBytes)) * 100+ memory.Value = memory.Percent+ }+ metrics.Memory = memory+ }++ if hasRealtimeTelemetry {+ metrics.NetIn = &unifiedresources.MetricValue{+ Value: system.NetInRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ }+ metrics.NetOut = &unifiedresources.MetricValue{+ Value: system.NetOutRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ }+ metrics.DiskRead = &unifiedresources.MetricValue{+ Value: system.DiskReadRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ }+ metrics.DiskWrite = &unifiedresources.MetricValue{+ Value: system.DiskWriteRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ }+ }++ return metrics+}++func agentDataFromTrueNASSystem(system SystemInfo, storageRisk *unifiedresources.StorageRisk, protectionReduced bool, protectionSummary string, rebuildInProgress bool, rebuildSummary string) *unifiedresources.AgentData {+ agent := &unifiedresources.AgentData{+ Hostname: strings.TrimSpace(system.Hostname),+ MachineID: strings.TrimSpace(system.MachineID),+ Platform: "truenas",+ OSName: "TrueNAS",+ OSVersion: strings.TrimSpace(system.Version),+ CPUCount: system.CPUCount,+ UptimeSeconds: system.UptimeSeconds,+ IntervalSeconds: system.IntervalSeconds,+ StorageRisk: storageRisk,+ StorageRiskSummary: unifiedresources.StorageRiskSummary(storageRisk),+ StoragePostureSummary: unifiedresources.StorageRiskSummary(storageRisk),+ ProtectionReduced: protectionReduced,+ ProtectionSummary: protectionSummary,+ RebuildInProgress: rebuildInProgress,+ RebuildSummary: rebuildSummary,+ NetInRate: system.NetInRate,+ NetOutRate: system.NetOutRate,+ DiskReadRate: system.DiskReadRate,+ DiskWriteRate: system.DiskWriteRate,+ }++ if system.MemoryTotalBytes > 0 {+ used := system.MemoryTotalBytes - system.MemoryAvailableBytes+ if used < 0 {+ used = 0+ }+ free := system.MemoryAvailableBytes+ if free < 0 {+ free = 0+ }+ agent.Memory = &unifiedresources.AgentMemoryMeta{+ Total: system.MemoryTotalBytes,+ Used: used,+ Free: free,+ }+ }++ return agent+}+func enrichAppStatsFromPreviousSnapshot(current *FixtureSnapshot, previous *FixtureSnapshot) {if current == nil || previous == nil || len(current.Apps) == 0 || len(previous.Apps) == 0 {returndiff --git a/internal/truenas/provider_test.go b/internal/truenas/provider_test.goindex 6b4d91a201..9c06ebac1f 100644--- a/internal/truenas/provider_test.go+++ b/internal/truenas/provider_test.go@@ -215,6 +215,24 @@ func TestSystemRecordPopulatesTrueNASMetadata(t *testing.T) {if system.Resource.TrueNAS.Hostname != "truenas-main" {t.Fatalf("expected hostname %q, got %q", "truenas-main", system.Resource.TrueNAS.Hostname)}+ if system.Resource.Agent == nil {+ t.Fatal("expected canonical agent payload on TrueNAS system record")+ }+ if system.Resource.Agent.Platform != "truenas" || system.Resource.Agent.OSName != "TrueNAS" {+ t.Fatalf("expected canonical TrueNAS agent metadata, got %+v", system.Resource.Agent)+ }+ if system.Resource.Agent.CPUCount != 16 || system.Resource.Agent.UptimeSeconds != int64(42*24*60*60) {+ t.Fatalf("expected canonical host telemetry metadata, got %+v", system.Resource.Agent)+ }+ if system.Resource.Metrics == nil || system.Resource.Metrics.CPU == nil || system.Resource.Metrics.Memory == nil {+ t.Fatalf("expected canonical system metrics on TrueNAS host record, got %+v", system.Resource.Metrics)+ }+ if system.Resource.Metrics.CPU.Percent != 38 {+ t.Fatalf("expected cpu percent 38, got %+v", system.Resource.Metrics.CPU)+ }+ if system.Resource.Metrics.NetIn == nil || system.Resource.Metrics.NetIn.Value != 48_000_000 {+ t.Fatalf("expected network telemetry metrics, got %+v", system.Resource.Metrics)+ }}func TestRecordsProjectTrueNASAppStatsIntoCanonicalMetrics(t *testing.T) {diff --git a/internal/truenas/types.go b/internal/truenas/types.goindex ef754aa779..f4a3ae6345 100644--- a/internal/truenas/types.go+++ b/internal/truenas/types.go@@ -17,12 +17,22 @@ type FixtureSnapshot struct {// SystemInfo mirrors high-level TrueNAS system identity/status data.type SystemInfo struct {- Hostname string- Version string- Build string- UptimeSeconds int64- Healthy bool- MachineID string+ Hostname string+ Version string+ Build string+ UptimeSeconds int64+ Healthy bool+ MachineID string+ CPUCount int+ MemoryTotalBytes int64+ MemoryAvailableBytes int64+ CPUPercent float64+ NetInRate float64+ NetOutRate float64+ DiskReadRate float64+ DiskWriteRate float64+ IntervalSeconds int+ CollectedAt time.Time}// Pool mirrors the subset of TrueNAS pool fields needed for unified mapping.diff --git a/internal/unifiedresources/metrics_targets.go b/internal/unifiedresources/metrics_targets.goindex cf79955ebc..b99a764238 100644--- a/internal/unifiedresources/metrics_targets.go+++ b/internal/unifiedresources/metrics_targets.go@@ -26,6 +26,11 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metricif st, ok := bySource[SourceAgent]; ok {return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}}+ if st, ok := bySource[SourceTrueNAS]; ok {+ if resourceID := canonicalAgentMetricID(st.SourceID); resourceID != "" {+ return &MetricsTarget{ResourceType: "agent", ResourceID: resourceID}+ }+ }if st, ok := bySource[SourceDocker]; ok {return &MetricsTarget{ResourceType: "docker-host", ResourceID: st.SourceID}}@@ -109,3 +114,10 @@ func canonicalAppContainerMetricID(sourceID string) string {trimmed = strings.TrimPrefix(trimmed, "app:")return strings.TrimSpace(trimmed)}++func canonicalAgentMetricID(sourceID string) string {+ trimmed := strings.TrimSpace(sourceID)+ trimmed = strings.TrimPrefix(trimmed, "system:")+ trimmed = strings.TrimPrefix(trimmed, "agent:")+ return strings.TrimSpace(trimmed)+}diff --git a/internal/unifiedresources/metrics_targets_test.go b/internal/unifiedresources/metrics_targets_test.goindex c5db4f1682..9444914ea1 100644--- a/internal/unifiedresources/metrics_targets_test.go+++ b/internal/unifiedresources/metrics_targets_test.go@@ -204,3 +204,24 @@ func TestBuildMetricsTarget_UsesCanonicalAppMetricIDForTrueNAS(t *testing.T) {t.Fatalf("ResourceID = %q, want nextcloud", target.ResourceID)}}++func TestBuildMetricsTarget_UsesCanonicalAgentMetricIDForTrueNAS(t *testing.T) {+ target := BuildMetricsTarget(+ Resource{+ Type: ResourceTypeAgent,+ },+ []SourceTarget{{+ Source: SourceTrueNAS,+ SourceID: " system:truenas-main ",+ }},+ )+ if target == nil {+ t.Fatal("BuildMetricsTarget() returned nil")+ }+ if target.ResourceType != "agent" {+ t.Fatalf("ResourceType = %q, want agent", target.ResourceType)+ }+ if target.ResourceID != "truenas-main" {+ t.Fatalf("ResourceID = %q, want truenas-main", target.ResourceID)+ }+}