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 app stats through canonical workload history
rcourtmane14ddcf3485e
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 64510b0852..daf07c0b3b 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -231,3 +231,11 @@ That same monitoring boundary now also owns live TrueNAS disk temperatures.`disk.temperatures` from the TrueNAS API and project those readings into thecanonical physical-disk model and risk path instead of leaving temperaturetelemetry agent-only or adding a TrueNAS-local presentation shim.+That same monitoring boundary now also owns modern TrueNAS app workload+telemetry. `internal/truenas/client.go`, `internal/truenas/provider.go`, and+`internal/monitoring/monitor.go` must ingest `app.stats` through the official+`/api/current` JSON-RPC websocket transport, project those readings onto the+canonical `app-container` metrics contract, and sync them into the existing+guest metrics-history/store path. Pulse must not add a TrueNAS-only charts+path or treat API-backed app workloads as second-class compared with native+Docker reports.diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.jsonindex c6239eec4c..3f29e838f2 100644--- a/docs/release-control/v6/internal/subsystems/registry.json+++ b/docs/release-control/v6/internal/subsystems/registry.json@@ -2860,7 +2860,8 @@"lane": "L13","contract": "docs/release-control/v6/internal/subsystems/monitoring.md","owned_prefixes": [- "internal/monitoring/"+ "internal/monitoring/",+ "internal/truenas/"],"owned_files": ["docker-entrypoint.sh"@@ -2895,6 +2896,26 @@"internal/monitoring/truenas_poller_test.go"]},+ {+ "id": "truenas-runtime",+ "label": "monitoring truenas runtime proof",+ "match_prefixes": [],+ "match_files": [+ "internal/truenas/client.go",+ "internal/truenas/fixtures.go",+ "internal/truenas/provider.go",+ "internal/truenas/types.go"+ ],+ "allow_same_subsystem_tests": false,+ "test_prefixes": [],+ "exact_files": [+ "internal/api/resources_test.go",+ "internal/monitoring/monitor_polling_test.go",+ "internal/truenas/client_test.go",+ "internal/truenas/contract_test.go",+ "internal/truenas/provider_test.go"+ ]+ },{"id": "metrics-hot-path","label": "monitoring metrics hot-path proof",diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.mdindex f091f3b3ca..ab2a360265 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -168,9 +168,10 @@ TrueNAS-managed applications now follow the same canonical workload rule. OneTrueNAS app instance from `app.query` must project as one canonical`app-container` resource under `SourceTrueNAS`, reusing the shared workload andDocker payload contracts instead of inventing a `truenas-app` resource type or-lane-local workload UI. Until Pulse ingests a real TrueNAS app stats/history-path, those resources must keep metrics-history targets unset rather than-pretending Docker memory-store history exists for them.+lane-local workload UI. API-backed `app.stats` telemetry must now project onto+that same canonical `app-container` contract as live metrics and metrics+targets, using the shared `docker:<id>` in-memory key and `dockerContainer`+history store path instead of adding a TrueNAS-local workload 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 7d916a2590..39bffd8897 100644--- a/internal/api/resources_test.go+++ b/internal/api/resources_test.go@@ -2995,8 +2995,8 @@ func TestResourceListIncludesTrueNASAppsAsAppContainers(t *testing.T) {if nextcloud.Docker.Runtime != "docker" {t.Fatalf("expected runtime docker, got %q", nextcloud.Docker.Runtime)}- if nextcloud.MetricsTarget != nil {- t.Fatalf("expected metrics target to remain unset until TrueNAS app stats are ingested, got %+v", nextcloud.MetricsTarget)+ if nextcloud.MetricsTarget == nil || nextcloud.MetricsTarget.ResourceType != "app-container" || nextcloud.MetricsTarget.ResourceID != "nextcloud" {+ t.Fatalf("expected canonical TrueNAS app metrics target nextcloud, got %+v", nextcloud.MetricsTarget)}}diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 0f7a8ca1c6..d58b2d6cad 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -148,6 +148,26 @@ func TestProxmoxGuestPollersCarryPoolIntoCanonicalModels(t *testing.T) {}}+func TestUnifiedAppContainerMetricsUseCanonicalGuestHistoryPath(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.syncUnifiedAppContainerMetrics(store)",+ `if target == nil || target.ResourceType != "app-container" || strings.TrimSpace(target.ResourceID) == "" {`,+ `metricKey := fmt.Sprintf("docker:%s", targetID)`,+ `m.metricsStore.Write("dockerContainer", targetID, "cpu", value, now)`,+ `m.metricsStore.Write("dockerContainer", 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 939469334f..a50c88dbaa 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -4137,6 +4137,7 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {if atomicStore, ok := store.(AtomicSnapshotResourceStore); ok {atomicStore.PopulateSnapshotAndSupplemental(snapshotForStore, recordsBySource)m.syncUnifiedStorageMetrics(store)+ m.syncUnifiedAppContainerMetrics(store)for source, records := range recordsBySource {if len(records) == 0 {continue@@ -4151,25 +4152,23 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {}store.PopulateFromSnapshot(snapshotForStore)- m.syncUnifiedStorageMetrics(store)supplementalStore, ok := store.(SupplementalRecordStore)- if !ok {- m.syncUnifiedResourceAlertsToState(store.GetAll())- return- }-- for source, records := range recordsBySource {- if len(records) == 0 {- continue+ if ok {+ for source, records := range recordsBySource {+ if len(records) == 0 {+ continue+ }+ supplementalStore.PopulateSupplementalRecords(source, records)+ log.Debug().+ Str("source", string(source)).+ Int("records", len(records)).+ Msg("[Resources] Ingested supplemental records")}- supplementalStore.PopulateSupplementalRecords(source, records)- log.Debug().- Str("source", string(source)).- Int("records", len(records)).- Msg("[Resources] Ingested supplemental records")}+ m.syncUnifiedStorageMetrics(store)+ m.syncUnifiedAppContainerMetrics(store)m.syncUnifiedResourceAlertsToState(store.GetAll())}@@ -4251,6 +4250,115 @@ func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {}}+func (m *Monitor) syncUnifiedAppContainerMetrics(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.ResourceTypeAppContainer || resource.Metrics == nil {+ continue+ }+ hasDockerSource := false+ for _, source := range resource.Sources {+ if source == unifiedresources.SourceDocker {+ hasDockerSource = true+ break+ }+ }+ if hasDockerSource {+ continue+ }++ target := resolver.MetricsTargetForResource(resource.ID)+ if target == nil || target.ResourceType != "app-container" || strings.TrimSpace(target.ResourceID) == "" {+ continue+ }+ targetID := strings.TrimSpace(target.ResourceID)+ if _, ok := seenTargets[targetID]; ok {+ continue+ }+ seenTargets[targetID] = struct{}{}+ metricKey := fmt.Sprintf("docker:%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("dockerContainer", targetID, "cpu", value, now)+ }+ }++ if metric := resource.Metrics.Memory; metric != nil && (metric.Total != nil || metric.Percent > 0) {+ value := metric.Percent+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "memory", value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("dockerContainer", targetID, "memory", value, now)+ }+ }++ if metric := resource.Metrics.Disk; metric != nil && (metric.Total != nil || metric.Percent > 0) {+ value := metric.Percent+ if m.metricsHistory != nil {+ m.metricsHistory.AddGuestMetric(metricKey, "disk", value, now)+ }+ if m.metricsStore != nil {+ m.metricsStore.Write("dockerContainer", 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("dockerContainer", 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("dockerContainer", 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("dockerContainer", 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("dockerContainer", targetID, "diskwrite", metric.Value, now)+ }+ }+ }+}+// getUnifiedResourcesForBroadcast retrieves all resources from the store.// Returns nil if no resource store is configured.func (m *Monitor) getUnifiedResourcesForBroadcast() []unifiedresources.Resource {diff --git a/internal/monitoring/monitor_polling_test.go b/internal/monitoring/monitor_polling_test.goindex 6f86fcadc2..82a6f143f4 100644--- a/internal/monitoring/monitor_polling_test.go+++ b/internal/monitoring/monitor_polling_test.go@@ -12,6 +12,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"+ "github.com/rcourtman/pulse-go-rewrite/internal/truenas""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources""github.com/rcourtman/pulse-go-rewrite/pkg/metrics""github.com/rcourtman/pulse-go-rewrite/pkg/pbs"@@ -481,6 +482,64 @@ func TestBuildBroadcastFrontendStateIncludesUnifiedIncidentAlerts(t *testing.T)}}+func TestSyncUnifiedAppContainerMetricsRecordsTrueNASHistory(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.syncUnifiedAppContainerMetrics(resourceStore)++ var appResourceID string+ for _, resource := range resourceStore.GetAll() {+ if resource.Type == unifiedresources.ResourceTypeAppContainer && resource.Name == "Nextcloud" {+ appResourceID = resource.ID+ break+ }+ }+ if appResourceID == "" {+ t.Fatal("expected Nextcloud app-container resource in unified store")+ }++ target := resourceStore.MetricsTargetForResource(appResourceID)+ if target == nil || target.ResourceType != "app-container" || target.ResourceID != "nextcloud" {+ t.Fatalf("unexpected app-container metrics target %+v", target)+ }++ inMemory := monitor.GetGuestMetrics("docker:nextcloud", time.Hour)+ if got := len(inMemory["cpu"]); got == 0 {+ t.Fatalf("expected in-memory cpu history for nextcloud")+ }+ if got := len(inMemory["netin"]); got == 0 {+ t.Fatalf("expected in-memory network history for nextcloud")+ }++ storeBacked := monitor.GetGuestMetricsForChart("docker:nextcloud", "dockerContainer", "nextcloud", 7*24*time.Hour)+ if got := len(storeBacked["cpu"]); got == 0 {+ t.Fatalf("expected persisted cpu history for nextcloud")+ }+}+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 3667bcfcf6..97e15a9fa0 100644--- a/internal/truenas/client.go+++ b/internal/truenas/client.go@@ -16,12 +16,16 @@ import ("strconv""strings""time"++ "github.com/gorilla/websocket")const defaultHTTPTimeout = 30 * time.Secondconst maxResponseBodyBytes int64 = 4 * 1024 * 1024+const defaultAppStatsIntervalSeconds = 2+// ClientConfig configures the TrueNAS REST API client.type ClientConfig struct {Host string@@ -40,6 +44,7 @@ type Client struct {config ClientConfighttpClient *http.ClientbaseURL string+ rpcURL string}// APIError represents an HTTP-level error from the TrueNAS REST API.@@ -96,6 +101,10 @@ func NewClient(config ClientConfig) (*Client, error) {if useHTTPS {scheme = "https"}+ wsScheme := "ws"+ if useHTTPS {+ wsScheme = "wss"+ }return &Client{config: config,@@ -104,6 +113,7 @@ func NewClient(config ClientConfig) (*Client, error) {Transport: transport,},baseURL: fmt.Sprintf("%s://%s/api/v2.0", scheme, hostPort),+ rpcURL: fmt.Sprintf("%s://%s/api/current", wsScheme, hostPort),}, nil}@@ -320,6 +330,10 @@ func (c *Client) GetApps(ctx context.Context) ([]App, error) {if err := c.getJSON(ctx, http.MethodGet, "/app", &response); err != nil {return nil, err}+ statsByApp, err := c.GetAppStats(ctx)+ if err != nil {+ statsByApp = nil+ }apps := make([]App, 0, len(response))for _, item := range response {@@ -356,6 +370,15 @@ func (c *Client) GetApps(ctx context.Context) ([]App, error) {if len(app.Volumes) == 0 {app.Volumes = dedupeAppVolumes(appVolumesFromContainers(app.Containers))}+ if len(statsByApp) > 0 {+ if stats, ok := statsByApp[normalizeAppStatsKey(app.ID)]; ok {+ statsCopy := stats+ app.Stats = &statsCopy+ } else if stats, ok := statsByApp[normalizeAppStatsKey(app.Name)]; ok {+ statsCopy := stats+ app.Stats = &statsCopy+ }+ }apps = append(apps, app)}@@ -363,6 +386,33 @@ func (c *Client) GetApps(ctx context.Context) ([]App, error) {return apps, nil}+// GetAppStats retrieves live TrueNAS app workload telemetry from the modern+// JSON-RPC websocket API. This path is best-effort; callers should treat any+// transport or endpoint failure as "stats unavailable" rather than inventory+// failure.+func (c *Client) GetAppStats(ctx context.Context) (map[string]AppStats, 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("app.stats:{\"interval\":%d}", defaultAppStatsIntervalSeconds)+ if err := rpc.call(ctx, "core.subscribe", []any{subscriptionName}, nil); err != nil {+ return nil, err+ }++ return rpc.readAppStatsEvent(ctx, defaultAppStatsIntervalSeconds)+}+// GetZFSSnapshots returns a best-effort list of ZFS snapshots.//// NOTE: TrueNAS exposes multiple snapshot APIs across versions. We intentionally parse the@@ -614,6 +664,216 @@ func appendDiskTemperature(out map[string]int, diskName string, value any) {out[diskName] = int(temperature)}+type trueNASRPCClient struct {+ conn *websocket.Conn+ nextID int64+}++type trueNASRPCRequest struct {+ JSONRPC string `json:"jsonrpc"`+ ID int64 `json:"id"`+ Method string `json:"method"`+ Params any `json:"params,omitempty"`+}++type trueNASRPCResponse struct {+ JSONRPC string `json:"jsonrpc"`+ ID int64 `json:"id,omitempty"`+ Method string `json:"method,omitempty"`+ Result json.RawMessage `json:"result,omitempty"`+ Params json.RawMessage `json:"params,omitempty"`+ Error *trueNASRPCError `json:"error,omitempty"`+}++type trueNASRPCError struct {+ Code int `json:"code"`+ Message string `json:"message"`+}++type trueNASCollectionUpdate struct {+ Collection string `json:"collection"`+ Fields []trueNASAppStatsEvent `json:"fields"`+}++type trueNASAppStatsEvent struct {+ AppName string `json:"app_name"`+ CPUUsage int64 `json:"cpu_usage"`+ Memory int64 `json:"memory"`+ Networks []trueNASAppNetworkStats `json:"networks"`+ BlkIO trueNASAppBlkIOStats `json:"blkio"`+}++type trueNASAppNetworkStats struct {+ InterfaceName string `json:"interface_name"`+ RXBytes int64 `json:"rx_bytes"`+ TXBytes int64 `json:"tx_bytes"`+}++type trueNASAppBlkIOStats struct {+ Read int64 `json:"read"`+ Write int64 `json:"write"`+}++func (c *Client) dialRPC(ctx context.Context) (*websocket.Conn, error) {+ if c == nil {+ return nil, fmt.Errorf("truenas client is nil")+ }++ dialer := websocket.Dialer{+ Proxy: http.ProxyFromEnvironment,+ }+ if c.config.UseHTTPS {+ tlsConfig, err := buildTLSConfig(c.config.InsecureSkipVerify, c.config.Fingerprint)+ if err != nil {+ return nil, err+ }+ dialer.TLSClientConfig = tlsConfig+ }+ if deadline, ok := ctx.Deadline(); ok {+ timeout := time.Until(deadline)+ if timeout > 0 {+ dialer.HandshakeTimeout = timeout+ }+ }++ conn, response, err := dialer.DialContext(ctx, c.rpcURL, nil)+ if err != nil {+ if response != nil {+ return nil, fmt.Errorf("dial truenas rpc websocket: status=%d: %w", response.StatusCode, err)+ }+ return nil, fmt.Errorf("dial truenas rpc websocket: %w", err)+ }+ return conn, nil+}++func (c *trueNASRPCClient) authenticate(ctx context.Context, config ClientConfig) error {+ if apiKey := strings.TrimSpace(config.APIKey); apiKey != "" {+ return c.call(ctx, "auth.login_with_api_key", []any{apiKey}, nil)+ }+ if config.Username != "" || config.Password != "" {+ return c.call(ctx, "auth.login", []any{config.Username, config.Password}, nil)+ }+ return fmt.Errorf("truenas rpc authentication requires api key or username/password")+}++func (c *trueNASRPCClient) call(ctx context.Context, method string, params any, result any) error {+ if c == nil || c.conn == nil {+ return fmt.Errorf("truenas rpc connection is nil")+ }++ request := trueNASRPCRequest{+ JSONRPC: "2.0",+ ID: c.nextID,+ Method: method,+ Params: params,+ }+ c.nextID++++ if deadline, ok := ctx.Deadline(); ok {+ _ = c.conn.SetWriteDeadline(deadline)+ }+ if err := c.conn.WriteJSON(request); err != nil {+ return fmt.Errorf("write truenas rpc %s request: %w", method, err)+ }++ for {+ if deadline, ok := ctx.Deadline(); ok {+ _ = c.conn.SetReadDeadline(deadline)+ }++ var message trueNASRPCResponse+ if err := c.conn.ReadJSON(&message); err != nil {+ return fmt.Errorf("read truenas rpc %s response: %w", method, err)+ }+ if message.Method != "" {+ continue+ }+ if message.ID != request.ID {+ continue+ }+ if message.Error != nil {+ return fmt.Errorf("truenas rpc %s failed: code=%d message=%q", method, message.Error.Code, strings.TrimSpace(message.Error.Message))+ }+ if result == nil || len(message.Result) == 0 || string(message.Result) == "null" {+ return nil+ }+ if err := json.Unmarshal(message.Result, result); err != nil {+ return fmt.Errorf("decode truenas rpc %s response: %w", method, err)+ }+ return nil+ }+}++func (c *trueNASRPCClient) readAppStatsEvent(ctx context.Context, intervalSeconds int) (map[string]AppStats, 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 app.stats notification: %w", err)+ }+ if message.Method == "" {+ if message.Error != nil {+ return nil, fmt.Errorf("truenas rpc app.stats failed: code=%d message=%q", message.Error.Code, strings.TrimSpace(message.Error.Message))+ }+ continue+ }+ if message.Method != "collection_update" || len(message.Params) == 0 {+ continue+ }++ var update trueNASCollectionUpdate+ if err := json.Unmarshal(message.Params, &update); err != nil {+ return nil, fmt.Errorf("decode truenas app.stats notification: %w", err)+ }+ if !strings.HasPrefix(strings.TrimSpace(update.Collection), "app.stats") {+ continue+ }++ collectedAt := time.Now().UTC()+ stats := make(map[string]AppStats, len(update.Fields))+ for _, field := range update.Fields {+ key := normalizeAppStatsKey(field.AppName)+ if key == "" {+ continue+ }++ appStats := AppStats{+ CPUPercent: float64(field.CPUUsage),+ MemoryBytes: field.Memory,+ BlockReadBytes: field.BlkIO.Read,+ BlockWriteBytes: field.BlkIO.Write,+ IntervalSeconds: intervalSeconds,+ CollectedAt: collectedAt,+ }+ if len(field.Networks) > 0 {+ appStats.Interfaces = make([]AppInterfaceStats, 0, len(field.Networks))+ }+ for _, network := range field.Networks {+ appStats.NetInRate += float64(network.RXBytes)+ appStats.NetOutRate += float64(network.TXBytes)+ appStats.Interfaces = append(appStats.Interfaces, AppInterfaceStats{+ Name: strings.TrimSpace(network.InterfaceName),+ RxBytesPS: float64(network.RXBytes),+ TxBytesPS: float64(network.TXBytes),+ })+ }+ stats[key] = appStats+ }+ return stats, nil+ }+}++func normalizeAppStatsKey(value string) string {+ return strings.ToLower(strings.TrimSpace(value))+}+func firstAny(record map[string]any, keys ...string) (any, bool) {if record == nil {return nil, falsediff --git a/internal/truenas/client_test.go b/internal/truenas/client_test.goindex e4a3c883d9..5e4a9a195b 100644--- a/internal/truenas/client_test.go+++ b/internal/truenas/client_test.go@@ -4,6 +4,7 @@ import ("context""crypto/sha256""encoding/hex"+ "encoding/json""fmt""net/http""net/http/httptest"@@ -12,6 +13,8 @@ import ("strings""testing""time"++ "github.com/gorilla/websocket")type apiResponse struct {@@ -218,6 +221,62 @@ func TestFetchSnapshot(t *testing.T) {}}+func TestGetAppsEnrichesStatsFromRPC(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": "app.stats:{\"interval\":2}",+ "fields": []map[string]any{+ {+ "app_name": "nextcloud",+ "cpu_usage": 17,+ "memory": 268435456,+ "networks": []map[string]any{+ {"interface_name": "eth0", "rx_bytes": 2048, "tx_bytes": 1024},+ {"interface_name": "eth1", "rx_bytes": 512, "tx_bytes": 256},+ },+ "blkio": map[string]any{+ "read": 4096,+ "write": 2048,+ },+ },+ },+ })+ })+ t.Cleanup(server.Close)++ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})+ apps, err := client.GetApps(context.Background())+ if err != nil {+ t.Fatalf("GetApps() error = %v", err)+ }+ if len(apps) != 1 || apps[0].Stats == nil {+ t.Fatalf("expected one app with stats, got %+v", apps)+ }+ if apps[0].Stats.CPUPercent != 17 || apps[0].Stats.MemoryBytes != 268435456 {+ t.Fatalf("unexpected app stats core fields: %+v", apps[0].Stats)+ }+ if apps[0].Stats.NetInRate != 2560 || apps[0].Stats.NetOutRate != 1280 {+ t.Fatalf("unexpected aggregated app network rates: %+v", apps[0].Stats)+ }+ if apps[0].Stats.BlockReadBytes != 4096 || apps[0].Stats.BlockWriteBytes != 2048 {+ t.Fatalf("unexpected app blkio stats: %+v", apps[0].Stats)+ }+ if len(apps[0].Stats.Interfaces) != 2 {+ t.Fatalf("expected two interface stats, got %+v", apps[0].Stats.Interfaces)+ }+}+func TestGetDiskTemperaturesSupportsArrayShape(t *testing.T) {server := newMockServer(t, map[string]apiResponse{"/api/v2.0/disk/temperatures": {@@ -495,6 +554,88 @@ func newMockServer(t *testing.T, responses map[string]apiResponse, assertRequest}))}+func newMockServerWithRPC(t *testing.T, responses map[string]apiResponse, assertRequest func(*testing.T, *http.Request), handleRPC func(*testing.T, *websocket.Conn)) *httptest.Server {+ t.Helper()++ upgrader := websocket.Upgrader{}+ return httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {+ if request.URL.Path == "/api/current" && websocket.IsWebSocketUpgrade(request) {+ conn, err := upgrader.Upgrade(writer, request, nil)+ if err != nil {+ t.Fatalf("upgrade websocket: %v", err)+ }+ defer func() { _ = conn.Close() }()+ handleRPC(t, conn)+ return+ }++ if assertRequest != nil {+ assertRequest(t, request)+ }++ response, ok := responses[request.URL.Path]+ if !ok {+ http.NotFound(writer, request)+ return+ }++ status := response.status+ if status == 0 {+ status = http.StatusOK+ }+ contentType := response.contentType+ if contentType == "" {+ contentType = "application/json"+ }++ writer.Header().Set("Content-Type", contentType)+ writer.WriteHeader(status)+ _, _ = writer.Write([]byte(response.body))+ }))+}++func readRPCRequest(t *testing.T, conn *websocket.Conn) trueNASRPCRequest {+ t.Helper()++ var request trueNASRPCRequest+ if err := conn.ReadJSON(&request); err != nil {+ t.Fatalf("ReadJSON() rpc request error = %v", err)+ }+ return request+}++func writeRPCResult(t *testing.T, conn *websocket.Conn, id int64, result any) {+ t.Helper()++ raw, err := json.Marshal(result)+ if err != nil {+ t.Fatalf("Marshal() rpc result error = %v", err)+ }+ if err := conn.WriteJSON(trueNASRPCResponse{+ JSONRPC: "2.0",+ ID: id,+ Result: raw,+ }); err != nil {+ t.Fatalf("WriteJSON() rpc result error = %v", err)+ }+}++func writeRPCNotification(t *testing.T, conn *websocket.Conn, method string, params any) {+ t.Helper()++ raw, err := json.Marshal(params)+ if err != nil {+ t.Fatalf("Marshal() rpc notification params error = %v", err)+ }+ if err := conn.WriteJSON(trueNASRPCResponse{+ JSONRPC: "2.0",+ Method: method,+ Params: raw,+ }); err != nil {+ t.Fatalf("WriteJSON() rpc notification error = %v", err)+ }+}+func mustClientForServer(t *testing.T, serverURL string, config ClientConfig) *Client {t.Helper()diff --git a/internal/truenas/contract_test.go b/internal/truenas/contract_test.goindex c086d7035d..890fb55ab9 100644--- a/internal/truenas/contract_test.go+++ b/internal/truenas/contract_test.go@@ -132,6 +132,16 @@ func TestRegistryIngestRecordsTreatsTrueNASAsGenericDataSource(t *testing.T) {if app.Status != unifiedresources.StatusOnline {t.Fatalf("expected Nextcloud status online, got %q", app.Status)}+ if app.Metrics == nil || app.Metrics.CPU == nil || app.Metrics.CPU.Percent != 18 {+ t.Fatalf("expected Nextcloud CPU metrics, got %+v", app.Metrics)+ }+ appTarget := registry.MetricsTarget(app.ID)+ if appTarget == nil || appTarget.ResourceType != "app-container" || appTarget.ResourceID != "nextcloud" {+ t.Fatalf("expected canonical Nextcloud metrics target, got %+v", appTarget)+ }+ if app.Docker.NetInRate != 2_100_000 || app.Docker.NetOutRate != 1_250_000 {+ t.Fatalf("expected Nextcloud network rates, got in=%v out=%v", app.Docker.NetInRate, app.Docker.NetOutRate)+ }disk := requireResource(t, resources, unifiedresources.ResourceTypePhysicalDisk, "sda")assertSourceTracking(t, *disk, unifiedresources.SourceTrueNAS)diff --git a/internal/truenas/fixtures.go b/internal/truenas/fixtures.goindex 6d8ff77524..2937e2e47f 100644--- a/internal/truenas/fixtures.go+++ b/internal/truenas/fixtures.go@@ -244,6 +244,21 @@ func DefaultFixtures() FixtureSnapshot {},},},+ Stats: &AppStats{+ CPUPercent: 18,+ MemoryBytes: 768 * 1024 * 1024,+ NetInRate: 2_100_000,+ NetOutRate: 1_250_000,+ BlockReadBytes: 15_000_000,+ BlockWriteBytes: 9_000_000,+ DiskReadRate: 320_000,+ DiskWriteRate: 180_000,+ IntervalSeconds: 2,+ CollectedAt: time.Date(2026, 2, 8, 12, 0, 0, 0, time.UTC),+ Interfaces: []AppInterfaceStats{+ {Name: "eth0", RxBytesPS: 2_100_000, TxBytesPS: 1_250_000},+ },+ },},{ID: "adguard-home",@@ -252,6 +267,18 @@ func DefaultFixtures() FixtureSnapshot {Version: "0.1.2",HumanVersion: "0.107.64",CustomApp: true,+ Stats: &AppStats{+ CPUPercent: 0,+ MemoryBytes: 96 * 1024 * 1024,+ NetInRate: 0,+ NetOutRate: 0,+ BlockReadBytes: 1_000_000,+ BlockWriteBytes: 500_000,+ DiskReadRate: 0,+ DiskWriteRate: 0,+ IntervalSeconds: 2,+ CollectedAt: time.Date(2026, 2, 8, 12, 0, 0, 0, time.UTC),+ },Containers: []AppContainer{{ID: "adguard-home-1",diff --git a/internal/truenas/provider.go b/internal/truenas/provider.goindex 8134108f38..6f1e9dff4d 100644--- a/internal/truenas/provider.go+++ b/internal/truenas/provider.go@@ -132,6 +132,7 @@ func (p *Provider) Refresh(ctx context.Context) error {}p.mu.Lock()+ enrichAppStatsFromPreviousSnapshot(snapshot, p.lastSnapshot)p.lastSnapshot = copyFixtureSnapshot(snapshot)p.mu.Unlock()return nil@@ -302,6 +303,7 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {}for _, app := range snapshot.Apps {+ metrics := metricsFromTrueNASApp(app)dockerMeta := &unifiedresources.DockerData{ContainerID: appCanonicalID(app),Hostname: strings.TrimSpace(snapshot.System.Hostname),@@ -316,6 +318,12 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {"truenas.app_id": strings.TrimSpace(app.ID),},}+ if app.Stats != nil {+ dockerMeta.NetInRate = app.Stats.NetInRate+ dockerMeta.NetOutRate = app.Stats.NetOutRate+ dockerMeta.DiskReadRate = app.Stats.DiskReadRate+ dockerMeta.DiskWriteRate = app.Stats.DiskWriteRate+ }if strings.TrimSpace(app.Version) != "" {dockerMeta.Labels["truenas.version"] = strings.TrimSpace(app.Version)}@@ -336,6 +344,7 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {Status: statusFromApp(app),LastSeen: collectedAt,UpdatedAt: collectedAt,+ Metrics: metrics,Docker: dockerMeta,Tags: appTags(app),},@@ -385,6 +394,99 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {return records}+func metricsFromTrueNASApp(app App) *unifiedresources.ResourceMetrics {+ if app.Stats == nil {+ return nil+ }++ stats := app.Stats+ metrics := &unifiedresources.ResourceMetrics{+ CPU: &unifiedresources.MetricValue{+ Value: stats.CPUPercent,+ Percent: stats.CPUPercent,+ Unit: "percent",+ Source: unifiedresources.SourceTrueNAS,+ },+ NetIn: &unifiedresources.MetricValue{+ Value: stats.NetInRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ },+ NetOut: &unifiedresources.MetricValue{+ Value: stats.NetOutRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ },+ DiskRead: &unifiedresources.MetricValue{+ Value: stats.DiskReadRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ },+ DiskWrite: &unifiedresources.MetricValue{+ Value: stats.DiskWriteRate,+ Unit: "bytes/s",+ Source: unifiedresources.SourceTrueNAS,+ },+ }++ memoryUsed := stats.MemoryBytes+ metrics.Memory = &unifiedresources.MetricValue{+ Used: &memoryUsed,+ Unit: "bytes",+ Source: unifiedresources.SourceTrueNAS,+ }+ return metrics+}++func enrichAppStatsFromPreviousSnapshot(current *FixtureSnapshot, previous *FixtureSnapshot) {+ if current == nil || previous == nil || len(current.Apps) == 0 || len(previous.Apps) == 0 {+ return+ }++ previousByApp := make(map[string]*AppStats, len(previous.Apps))+ for i := range previous.Apps {+ if previous.Apps[i].Stats == nil {+ continue+ }+ key := normalizeAppStatsKey(previous.Apps[i].ID)+ if key == "" {+ key = normalizeAppStatsKey(previous.Apps[i].Name)+ }+ if key == "" {+ continue+ }+ previousByApp[key] = previous.Apps[i].Stats+ }++ for i := range current.Apps {+ stats := current.Apps[i].Stats+ if stats == nil {+ continue+ }+ key := normalizeAppStatsKey(current.Apps[i].ID)+ if key == "" {+ key = normalizeAppStatsKey(current.Apps[i].Name)+ }+ if key == "" {+ continue+ }+ previousStats, ok := previousByApp[key]+ if !ok || previousStats == nil {+ continue+ }+ deltaSeconds := stats.CollectedAt.Sub(previousStats.CollectedAt).Seconds()+ if deltaSeconds <= 0 {+ continue+ }+ if stats.BlockReadBytes >= previousStats.BlockReadBytes {+ stats.DiskReadRate = float64(stats.BlockReadBytes-previousStats.BlockReadBytes) / deltaSeconds+ }+ if stats.BlockWriteBytes >= previousStats.BlockWriteBytes {+ stats.DiskWriteRate = float64(stats.BlockWriteBytes-previousStats.BlockWriteBytes) / deltaSeconds+ }+ }+}+func buildIncidentAssignments(snapshot *FixtureSnapshot) ([]unifiedresources.ResourceIncident, map[string][]unifiedresources.ResourceIncident, map[string][]unifiedresources.ResourceIncident) {systemIncidents := make([]unifiedresources.ResourceIncident, 0)poolIncidents := make(map[string][]unifiedresources.ResourceIncident)@@ -880,6 +982,11 @@ func cloneApps(apps []App) []App {out[i].Volumes = append([]AppVolume(nil), apps[i].Volumes...)out[i].Images = append([]string(nil), apps[i].Images...)out[i].Networks = cloneAppNetworks(apps[i].Networks)+ if apps[i].Stats != nil {+ stats := *apps[i].Stats+ stats.Interfaces = append([]AppInterfaceStats(nil), apps[i].Stats.Interfaces...)+ out[i].Stats = &stats+ }}return out}diff --git a/internal/truenas/provider_test.go b/internal/truenas/provider_test.goindex c9760b30ef..6b4d91a201 100644--- a/internal/truenas/provider_test.go+++ b/internal/truenas/provider_test.go@@ -5,6 +5,7 @@ import ("errors""net/http""testing"+ "time""github.com/rcourtman/pulse-go-rewrite/internal/storagehealth""github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"@@ -216,6 +217,73 @@ func TestSystemRecordPopulatesTrueNASMetadata(t *testing.T) {}}+func TestRecordsProjectTrueNASAppStatsIntoCanonicalMetrics(t *testing.T) {+ previous := IsFeatureEnabled()+ SetFeatureEnabled(true)+ t.Cleanup(func() {+ SetFeatureEnabled(previous)+ })++ provider := NewProvider(DefaultFixtures())+ records := provider.Records()+ if len(records) == 0 {+ t.Fatal("expected fixture records from provider")+ }++ for _, record := range records {+ if record.Resource.Type != unifiedresources.ResourceTypeAppContainer || record.Resource.Name != "Nextcloud" {+ continue+ }+ if record.Resource.Metrics == nil || record.Resource.Metrics.CPU == nil || record.Resource.Metrics.CPU.Percent != 18 {+ t.Fatalf("expected canonical CPU metrics on Nextcloud, got %+v", record.Resource.Metrics)+ }+ if record.Resource.Docker == nil || record.Resource.Docker.NetInRate != 2_100_000 || record.Resource.Docker.DiskReadRate != 320_000 {+ t.Fatalf("expected projected TrueNAS app rates, got %+v", record.Resource.Docker)+ }+ return+ }++ t.Fatal("expected Nextcloud app record")+}++func TestProviderRefreshDerivesTrueNASAppDiskRatesFromPreviousSnapshot(t *testing.T) {+ previous := IsFeatureEnabled()+ SetFeatureEnabled(true)+ t.Cleanup(func() {+ SetFeatureEnabled(previous)+ })++ initial := DefaultFixtures()+ initial.CollectedAt = time.Date(2026, 2, 8, 12, 0, 0, 0, time.UTC)+ initial.Apps[0].Stats.BlockReadBytes = 100+ initial.Apps[0].Stats.BlockWriteBytes = 50+ initial.Apps[0].Stats.CollectedAt = initial.CollectedAt++ updated := DefaultFixtures()+ updated.CollectedAt = initial.CollectedAt.Add(4 * time.Second)+ updated.Apps[0].Stats.BlockReadBytes = 500+ updated.Apps[0].Stats.BlockWriteBytes = 250+ updated.Apps[0].Stats.CollectedAt = updated.CollectedAt++ provider := NewProvider(initial)+ provider.fetcher = &stubFetcher{snapshot: &updated}++ if err := provider.Refresh(context.Background()); err != nil {+ t.Fatalf("Refresh() error = %v", err)+ }++ snapshot := provider.Snapshot()+ if snapshot == nil || snapshot.Apps[0].Stats == nil {+ t.Fatal("expected refreshed app stats")+ }+ if snapshot.Apps[0].Stats.DiskReadRate != 100 {+ t.Fatalf("expected disk read rate 100, got %v", snapshot.Apps[0].Stats.DiskReadRate)+ }+ if snapshot.Apps[0].Stats.DiskWriteRate != 50 {+ t.Fatalf("expected disk write rate 50, got %v", snapshot.Apps[0].Stats.DiskWriteRate)+ }+}+func TestAPIFetcherCloseDelegatesToClient(t *testing.T) {transport := &closeTrackingTransport{}client := &Client{diff --git a/internal/truenas/types.go b/internal/truenas/types.goindex 0404f0b8b4..ef754aa779 100644--- a/internal/truenas/types.go+++ b/internal/truenas/types.go@@ -89,6 +89,29 @@ type App struct {Volumes []AppVolumeImages []stringNetworks []AppNetwork+ Stats *AppStats+}++// AppStats contains live API-backed workload telemetry for one TrueNAS app.+type AppStats struct {+ CPUPercent float64+ MemoryBytes int64+ NetInRate float64+ NetOutRate float64+ BlockReadBytes int64+ BlockWriteBytes int64+ DiskReadRate float64+ DiskWriteRate float64+ IntervalSeconds int+ CollectedAt time.Time+ Interfaces []AppInterfaceStats+}++// AppInterfaceStats stores per-interface throughput from TrueNAS app.stats.+type AppInterfaceStats struct {+ Name string+ RxBytesPS float64+ TxBytesPS float64}// AppPort describes an app-level published port mapping.diff --git a/internal/unifiedresources/metrics_targets.go b/internal/unifiedresources/metrics_targets.goindex 53769b9e5d..cf79955ebc 100644--- a/internal/unifiedresources/metrics_targets.go+++ b/internal/unifiedresources/metrics_targets.go@@ -41,6 +41,11 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metricif st, ok := bySource[SourceDocker]; ok {return &MetricsTarget{ResourceType: "app-container", ResourceID: st.SourceID}}+ if st, ok := bySource[SourceTrueNAS]; ok {+ if resourceID := canonicalAppContainerMetricID(st.SourceID); resourceID != "" {+ return &MetricsTarget{ResourceType: "app-container", ResourceID: resourceID}+ }+ }case ResourceTypeStorage, ResourceTypeCeph:if st, ok := bySource[SourceProxmox]; ok {return &MetricsTarget{ResourceType: "storage", ResourceID: st.SourceID}@@ -98,3 +103,9 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metricreturn nil}++func canonicalAppContainerMetricID(sourceID string) string {+ trimmed := strings.TrimSpace(sourceID)+ trimmed = strings.TrimPrefix(trimmed, "app:")+ return strings.TrimSpace(trimmed)+}diff --git a/internal/unifiedresources/metrics_targets_test.go b/internal/unifiedresources/metrics_targets_test.goindex 4f0baf2ec4..c5db4f1682 100644--- a/internal/unifiedresources/metrics_targets_test.go+++ b/internal/unifiedresources/metrics_targets_test.go@@ -183,3 +183,24 @@ func TestBuildMetricsTarget_UsesCanonicalPhysicalDiskMetricIDForTrueNAS(t *testit.Fatalf("ResourceID = %q, want SER-TRUE-1", target.ResourceID)}}++func TestBuildMetricsTarget_UsesCanonicalAppMetricIDForTrueNAS(t *testing.T) {+ target := BuildMetricsTarget(+ Resource{+ Type: ResourceTypeAppContainer,+ },+ []SourceTarget{{+ Source: SourceTrueNAS,+ SourceID: " app:nextcloud ",+ }},+ )+ if target == nil {+ t.Fatal("BuildMetricsTarget() returned nil")+ }+ if target.ResourceType != "app-container" {+ t.Fatalf("ResourceType = %q, want app-container", target.ResourceType)+ }+ if target.ResourceID != "nextcloud" {+ t.Fatalf("ResourceID = %q, want nextcloud", target.ResourceID)+ }+}diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.pyindex b32afa5a26..c84b2a8107 100644--- a/scripts/release_control/canonical_completion_guard_test.py+++ b/scripts/release_control/canonical_completion_guard_test.py@@ -180,6 +180,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):policy_ids,["discovery-provider-runtime",+ "truenas-runtime","metrics-hot-path","metrics-history-runtime","memory-source-runtime",