Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

feat(truenas): add native host chart fallback

rcourtman65d386bbd9f0
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 1753a0b3e4..95c78a3cf4 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -260,6 +260,14 @@ 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.
+That same boundary now also owns native host-history fallback for API-backed
+TrueNAS systems. `internal/truenas/client.go`,
+`internal/truenas/provider.go`, `internal/monitoring/truenas_poller.go`, and
+`internal/monitoring/monitor_metrics.go` must route TrueNAS
+`reporting.get_data` system history through the shared `agent` guest-chart
+path, so canonical host charts can show real provider-backed CPU, memory,
+network, and disk throughput history when Pulse's own local history is still
+shallow.
That same monitoring boundary now also owns canonical TrueNAS app control
refresh semantics. `internal/truenas/provider.go` and
`internal/monitoring/truenas_poller.go` must execute native app start/stop
diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.go
index 037f905514..a0ada1c873 100644
--- a/internal/monitoring/monitor_metrics.go
+++ b/internal/monitoring/monitor_metrics.go
@@ -35,6 +35,13 @@ const (
shortRangeCoverageMaxSlack = 2 * time.Minute
)
+// MonitorGuestMetricHistoryProvider optionally exposes source-native guest
+// metric history through the canonical chart boundary when local Pulse history
+// is shallow.
+type MonitorGuestMetricHistoryProvider interface {
+ GuestMetricHistory(m *Monitor, orgID string, resourceType string, duration time.Duration) map[string]map[string][]MetricPoint
+}
+
// GetGuestMetrics returns historical metrics for a guest
func (m *Monitor) GetGuestMetrics(guestID string, duration time.Duration) map[string][]MetricPoint {
if m == nil || m.metricsHistory == nil {
@@ -71,21 +78,22 @@ func (m *Monitor) GetGuestMetrics(guestID string, duration time.Duration) map[st
// (e.g. "dockerContainer"/"abc123").
func (m *Monitor) GetGuestMetricsForChart(inMemoryKey, sqlResourceType, sqlResourceID string, duration time.Duration) map[string][]MetricPoint {
inMemoryResult := m.GetGuestMetrics(inMemoryKey, duration)
- if m.metricsStore == nil {
- return inMemoryResult
- }
if duration <= inMemoryChartThreshold && hasSufficientChartMapCoverage(inMemoryResult, duration) {
return inMemoryResult
}
- converted, ok := m.queryStoreMetricMapWithGapFillAliases(sqlResourceType, sqlResourceID, duration)
- if !ok {
- return inMemoryResult
+ best := cloneMetricPointMap(inMemoryResult)
+ if m.metricsStore != nil {
+ if converted, ok := m.queryStoreMetricMapWithGapFillAliases(sqlResourceType, sqlResourceID, duration); ok {
+ best = mergeGuestMetricHistory(best, converted, duration)
+ }
}
- if duration <= inMemoryChartThreshold && chartMapCoverageSpan(converted) <= chartMapCoverageSpan(inMemoryResult) {
- return inMemoryResult
+ if nativeHistory := m.nativeGuestMetricHistory(sqlResourceType, duration); len(nativeHistory) > 0 {
+ if nativeMetrics, ok := nativeHistory[sqlResourceID]; ok {
+ best = mergeGuestMetricHistory(best, nativeMetrics, duration)
+ }
}
- return converted
+ return best
}
// GetNodeMetrics returns historical metrics for a node
@@ -377,23 +385,19 @@ func (m *Monitor) GetGuestMetricsForChartBatch(
result := make(map[string]map[string][]MetricPoint, len(requests))
- // Phase 1: Check in-memory for all guests.
- var needStore []string
+ // Phase 1: Check in-memory for all guests and identify which need fallback.
+ var needFallback []string
for _, req := range requests {
inMemory := m.GetGuestMetrics(req.InMemoryKey, duration)
- if m.metricsStore == nil {
- result[req.SQLResourceID] = inMemory
- continue
- }
+ result[req.SQLResourceID] = inMemory
if duration <= inMemoryChartThreshold && hasSufficientChartMapCoverage(inMemory, duration) {
result[req.SQLResourceID] = inMemory
continue
}
- needStore = append(needStore, req.SQLResourceID)
- result[req.SQLResourceID] = inMemory // keep as fallback
+ needFallback = append(needFallback, req.SQLResourceID)
}
- if len(needStore) == 0 {
+ if len(needFallback) == 0 {
return result
}
@@ -401,31 +405,36 @@ func (m *Monitor) GetGuestMetricsForChartBatch(
// keeping the best coverage per ID. Ties on span are broken by total
// point count, matching the single-resource alias resolution logic.
storeResults := make(map[string]map[string][]MetricPoint)
- for _, candidate := range monitorStoreResourceTypeCandidates(sqlResourceType) {
- batch := m.queryStoreBatchMetricMapWithGapFill(candidate, needStore, duration)
- for id, metricMap := range batch {
- if existing, ok := storeResults[id]; ok {
- newSpan := chartMapCoverageSpan(metricMap)
- oldSpan := chartMapCoverageSpan(existing)
- if newSpan < oldSpan || (newSpan == oldSpan && monitorMetricMapPointCount(metricMap) <= monitorMetricMapPointCount(existing)) {
- continue
+ if m.metricsStore != nil {
+ for _, candidate := range monitorStoreResourceTypeCandidates(sqlResourceType) {
+ batch := m.queryStoreBatchMetricMapWithGapFill(candidate, needFallback, duration)
+ for id, metricMap := range batch {
+ if existing, ok := storeResults[id]; ok {
+ newSpan := chartMapCoverageSpan(metricMap)
+ oldSpan := chartMapCoverageSpan(existing)
+ if newSpan < oldSpan || (newSpan == oldSpan && monitorMetricMapPointCount(metricMap) <= monitorMetricMapPointCount(existing)) {
+ continue
+ }
}
+ storeResults[id] = metricMap
}
- storeResults[id] = metricMap
}
}
+ nativeResults := m.nativeGuestMetricHistory(sqlResourceType, duration)
- // Phase 3: Merge — use store data when it has better coverage.
- for _, id := range needStore {
+ // Phase 3: Merge fallback data per metric type.
+ for _, id := range needFallback {
+ best := cloneMetricPointMap(result[id])
storeData, ok := storeResults[id]
- if !ok {
- continue
+ if ok {
+ best = mergeGuestMetricHistory(best, storeData, duration)
}
- inMemory := result[id]
- if duration <= inMemoryChartThreshold && chartMapCoverageSpan(storeData) <= chartMapCoverageSpan(inMemory) {
+ nativeData, ok := nativeResults[id]
+ if !ok {
+ result[id] = best
continue
}
- result[id] = storeData
+ result[id] = mergeGuestMetricHistory(best, nativeData, duration)
}
return result
@@ -544,6 +553,40 @@ func (m *Monitor) GetStorageMetricsForChartBatch(
return result
}
+func (m *Monitor) nativeGuestMetricHistory(resourceType string, duration time.Duration) map[string]map[string][]MetricPoint {
+ providers := m.supplementalProviderSnapshot()
+ if len(providers) == 0 {
+ return nil
+ }
+
+ orgID := "default"
+ if m != nil {
+ if trimmed := strings.TrimSpace(m.GetOrgID()); trimmed != "" {
+ orgID = trimmed
+ }
+ }
+
+ history := make(map[string]map[string][]MetricPoint)
+ for _, provider := range providers {
+ historyProvider, ok := provider.(MonitorGuestMetricHistoryProvider)
+ if !ok {
+ continue
+ }
+ nativeHistory := historyProvider.GuestMetricHistory(m, orgID, resourceType, duration)
+ for resourceID, metricMap := range nativeHistory {
+ if strings.TrimSpace(resourceID) == "" || len(metricMap) == 0 {
+ continue
+ }
+ existing := history[resourceID]
+ history[resourceID] = mergeGuestMetricHistory(existing, metricMap, duration)
+ }
+ }
+ if len(history) == 0 {
+ return nil
+ }
+ return history
+}
+
func chartGapFillLookbackWindow(duration time.Duration) time.Duration {
lookback := duration * chartGapFillLookbackMultiplier
if lookback < chartGapFillLookbackMin {
@@ -650,6 +693,71 @@ func convertAndDownsample(sqlResult map[string][]metrics.MetricPoint, target int
return result
}
+func cloneMetricSeries(points []MetricPoint) []MetricPoint {
+ if len(points) == 0 {
+ return nil
+ }
+ cloned := make([]MetricPoint, len(points))
+ copy(cloned, points)
+ return cloned
+}
+
+func cloneMetricPointMap(metrics map[string][]MetricPoint) map[string][]MetricPoint {
+ if len(metrics) == 0 {
+ return map[string][]MetricPoint{}
+ }
+ cloned := make(map[string][]MetricPoint, len(metrics))
+ for metricType, points := range metrics {
+ cloned[metricType] = cloneMetricSeries(points)
+ }
+ return cloned
+}
+
+func mergeGuestMetricHistory(base, candidate map[string][]MetricPoint, duration time.Duration) map[string][]MetricPoint {
+ if len(candidate) == 0 {
+ return cloneMetricPointMap(base)
+ }
+
+ merged := cloneMetricPointMap(base)
+ for metricType, candidateSeries := range candidate {
+ if !shouldPreferGuestMetricSeries(merged[metricType], candidateSeries, duration) {
+ continue
+ }
+ merged[metricType] = cloneMetricSeries(candidateSeries)
+ }
+ return merged
+}
+
+func shouldPreferGuestMetricSeries(current, candidate []MetricPoint, duration time.Duration) bool {
+ if len(candidate) == 0 {
+ return false
+ }
+ if len(current) == 0 {
+ return true
+ }
+
+ candidateSpan := chartSeriesCoverageSpan(candidate)
+ currentSpan := chartSeriesCoverageSpan(current)
+ if duration <= inMemoryChartThreshold {
+ currentSufficient := hasSufficientChartSeriesCoverage(current, duration)
+ candidateSufficient := hasSufficientChartSeriesCoverage(candidate, duration)
+ switch {
+ case currentSufficient && !candidateSufficient:
+ return false
+ case !currentSufficient && candidateSufficient:
+ return true
+ }
+ }
+
+ if candidateSpan > currentSpan {
+ return true
+ }
+ if candidateSpan < currentSpan {
+ return false
+ }
+ return len(candidate) > len(current)
+}
+
func chartCoverageRequiredSpan(duration time.Duration) time.Duration {
if duration <= 0 {
return 0
diff --git a/internal/monitoring/monitor_metrics_chart_fallback_test.go b/internal/monitoring/monitor_metrics_chart_fallback_test.go
index 3a31198f7b..ced0fbb809 100644
--- a/internal/monitoring/monitor_metrics_chart_fallback_test.go
+++ b/internal/monitoring/monitor_metrics_chart_fallback_test.go
@@ -30,6 +30,31 @@ func (s *stubDiskTemperatureHistoryProvider) PhysicalDiskTemperatureHistory(*Mon
return result
}
+type stubGuestMetricHistoryProvider struct {
+ history map[string]map[string][]MetricPoint
+}
+
+func (s *stubGuestMetricHistoryProvider) SupplementalRecords(*Monitor, string) []unifiedresources.IngestRecord {
+ return nil
+}
+
+func (s *stubGuestMetricHistoryProvider) GuestMetricHistory(*Monitor, string, string, time.Duration) map[string]map[string][]MetricPoint {
+ if len(s.history) == 0 {
+ return nil
+ }
+ result := make(map[string]map[string][]MetricPoint, len(s.history))
+ for resourceID, metricMap := range s.history {
+ cloned := make(map[string][]MetricPoint, len(metricMap))
+ for metricType, points := range metricMap {
+ copied := make([]MetricPoint, len(points))
+ copy(copied, points)
+ cloned[metricType] = copied
+ }
+ result[resourceID] = cloned
+ }
+ return result
+}
+
func newChartFallbackTestMonitor(t *testing.T) *Monitor {
t.Helper()
@@ -284,6 +309,46 @@ func TestGetGuestMetricsForChart_UsesGapFillLookbackWhenRequestedRangeIsEmpty(t
}
}
+func TestGetGuestMetricsForChart_UsesNativeHistoryWhenStoreCoverageShallow(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 4 * time.Hour
+
+ writeRawMetricBatch(t, monitor.metricsStore, "agent", "truenas-main", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-5 * time.Minute), Value: 41},
+ })
+ monitor.supplementalProviders = map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{
+ unifiedresources.SourceTrueNAS: &stubGuestMetricHistoryProvider{
+ history: map[string]map[string][]MetricPoint{
+ "truenas-main": {
+ "cpu": {
+ {Timestamp: now.Add(-2 * time.Hour), Value: 20},
+ {Timestamp: now.Add(-1 * time.Hour), Value: 28},
+ {Timestamp: now, Value: 34},
+ },
+ "memory": {
+ {Timestamp: now.Add(-2 * time.Hour), Value: 45},
+ {Timestamp: now, Value: 62},
+ },
+ },
+ },
+ },
+ }
+
+ result := monitor.GetGuestMetricsForChart("agent:truenas-main", "agent", "truenas-main", duration)
+ if got := len(result["cpu"]); got != 3 {
+ t.Fatalf("expected native cpu history to win, got %+v", result["cpu"])
+ }
+ if got := result["cpu"][2].Value; got != 34 {
+ t.Fatalf("expected latest native cpu value 34, got %+v", result["cpu"])
+ }
+ if got := len(result["memory"]); got != 2 {
+ t.Fatalf("expected native memory history, got %+v", result["memory"])
+ }
+}
+
func TestGetNodeMetricsForChart_UsesGapFillLookbackWhenRequestedRangeIsEmpty(t *testing.T) {
t.Parallel()
@@ -382,6 +447,42 @@ func TestGetGuestMetricsForChartBatch_PrefersInMemoryForShortRanges(t *testing.T
}
}
+func TestGetGuestMetricsForChartBatch_UsesNativeAgentHistoryWhenStoreCoverageShallow(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 4 * time.Hour
+
+ writeRawMetricBatch(t, monitor.metricsStore, "agent", "truenas-main", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-5 * time.Minute), Value: 41},
+ })
+ monitor.supplementalProviders = map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{
+ unifiedresources.SourceTrueNAS: &stubGuestMetricHistoryProvider{
+ history: map[string]map[string][]MetricPoint{
+ "truenas-main": {
+ "cpu": {
+ {Timestamp: now.Add(-2 * time.Hour), Value: 20},
+ {Timestamp: now.Add(-1 * time.Hour), Value: 28},
+ {Timestamp: now, Value: 34},
+ },
+ },
+ },
+ },
+ }
+
+ requests := []GuestChartRequest{{InMemoryKey: "agent:truenas-main", SQLResourceID: "truenas-main"}}
+ result := monitor.GetGuestMetricsForChartBatch("agent", requests, duration)
+
+ cpuPoints := result["truenas-main"]["cpu"]
+ if len(cpuPoints) != 3 {
+ t.Fatalf("expected native batch cpu history to win, got %+v", cpuPoints)
+ }
+ if cpuPoints[2].Value != 34 {
+ t.Fatalf("expected latest batch cpu value 34, got %+v", cpuPoints)
+ }
+}
+
func TestGetGuestMetricsForChartBatch_EmptyRequests(t *testing.T) {
t.Parallel()
diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.go
index d93596680c..3824817cfe 100644
--- a/internal/monitoring/monitor_metrics_slo_test.go
+++ b/internal/monitoring/monitor_metrics_slo_test.go
@@ -31,6 +31,8 @@ const (
SLONodeChartBatchGitHubActionsP95 = 140 * time.Millisecond
SLOPhysicalDiskChartFallbackP95 = 30 * time.Millisecond
SLOPhysicalDiskChartFallbackGHA = 120 * time.Millisecond
+ SLOGuestChartFallbackP95 = 30 * time.Millisecond
+ SLOGuestChartFallbackGHA = 120 * time.Millisecond
monitoringSLOIterations = 120
)
@@ -298,3 +300,57 @@ func TestSLO_GetPhysicalDiskTemperatureCharts_WithNativeHistoryFallback(t *testi
t.Errorf("SLO VIOLATION: p95=%v exceeds target %v", p95, target)
}
}
+
+func TestSLO_GetGuestMetricsForChart_WithNativeHistoryFallback(t *testing.T) {
+ skipMonitoringSLOUnderRace(t)
+ suppressMonitoringTestLogs(t)
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 4 * time.Hour
+
+ writeRawMetricBatch(t, monitor.metricsStore, "agent", "truenas-main", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-5 * time.Minute), Value: 41},
+ })
+ monitor.supplementalProviders = map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{
+ unifiedresources.SourceTrueNAS: &stubGuestMetricHistoryProvider{
+ history: map[string]map[string][]MetricPoint{
+ "truenas-main": {
+ "cpu": {
+ {Timestamp: now.Add(-2 * time.Hour), Value: 20},
+ {Timestamp: now.Add(-1 * time.Hour), Value: 28},
+ {Timestamp: now, Value: 34},
+ },
+ "memory": {
+ {Timestamp: now.Add(-2 * time.Hour), Value: 45},
+ {Timestamp: now, Value: 62},
+ },
+ },
+ },
+ },
+ }
+
+ sanity := monitor.GetGuestMetricsForChart("agent:truenas-main", "agent", "truenas-main", duration)
+ if got := len(sanity["cpu"]); got != 3 {
+ t.Fatalf("sanity: expected native cpu history, got %+v", sanity["cpu"])
+ }
+
+ latencies := measureMonitoringLatencies(t, func() {
+ result := monitor.GetGuestMetricsForChart("agent:truenas-main", "agent", "truenas-main", duration)
+ if got := len(result["cpu"]); got != 3 {
+ t.Fatalf("expected native cpu history, got %+v", result["cpu"])
+ }
+ if got := len(result["memory"]); got != 2 {
+ t.Fatalf("expected native memory history, got %+v", result["memory"])
+ }
+ })
+
+ target := effectiveMonitoringSLOTarget(SLOGuestChartFallbackP95, SLOGuestChartFallbackGHA)
+ p95 := monitoringPercentile(latencies, 0.95)
+ t.Logf("GetGuestMetricsForChart(native-history fallback) p50=%v p95=%v p99=%v SLO=%v",
+ monitoringPercentile(latencies, 0.50), p95, monitoringPercentile(latencies, 0.99), target)
+
+ if p95 > target {
+ t.Errorf("SLO VIOLATION: p95=%v exceeds target %v", p95, target)
+ }
+}
diff --git a/internal/monitoring/truenas_poller.go b/internal/monitoring/truenas_poller.go
index 21d7e0cbd8..8423cc5cde 100644
--- a/internal/monitoring/truenas_poller.go
+++ b/internal/monitoring/truenas_poller.go
@@ -502,6 +502,70 @@ func (p *TrueNASPoller) PhysicalDiskTemperatureHistory(_ *Monitor, orgID string,
return history
}
+// GuestMetricHistory exposes native TrueNAS host history through the canonical
+// guest-chart boundary when local Pulse history is shallow.
+func (p *TrueNASPoller) GuestMetricHistory(_ *Monitor, orgID string, resourceType string, duration time.Duration) map[string]map[string][]MetricPoint {
+ if p == nil || !truenas.IsFeatureEnabled() || strings.TrimSpace(resourceType) != "agent" {
+ return nil
+ }
+
+ orgID = strings.TrimSpace(orgID)
+ if orgID == "" {
+ orgID = "default"
+ }
+
+ entries := p.providerEntriesForOrg(orgID)
+ if len(entries) == 0 {
+ return nil
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), defaultTrueNASHistoryReadTimeout)
+ defer cancel()
+
+ history := make(map[string]map[string][]MetricPoint)
+ for _, entry := range entries {
+ resourceID, nativeHistory, err := entry.provider.SystemMetricHistory(ctx, duration)
+ if err != nil {
+ log.Warn().
+ Str("component", "truenas_poller").
+ Str("action", "guest_metric_history").
+ Str("resource_type", resourceType).
+ Str("org_id", orgID).
+ Str("connection_id", strings.TrimSpace(entry.connectionID)).
+ Err(err).
+ Msg("TrueNAS poller failed to read native guest history")
+ continue
+ }
+ resourceID = strings.TrimSpace(resourceID)
+ if resourceID == "" || len(nativeHistory) == 0 {
+ continue
+ }
+
+ converted := make(map[string][]MetricPoint, len(nativeHistory))
+ for metricType, points := range nativeHistory {
+ if strings.TrimSpace(metricType) == "" || len(points) == 0 {
+ continue
+ }
+ series := make([]MetricPoint, len(points))
+ for i, point := range points {
+ series[i] = MetricPoint{
+ Timestamp: point.Timestamp,
+ Value: point.Value,
+ }
+ }
+ converted[metricType] = series
+ }
+ if len(converted) == 0 {
+ continue
+ }
+ history[resourceID] = converted
+ }
+ if len(history) == 0 {
+ return nil
+ }
+ return history
+}
+
// SnapshotOwnedSources declares source-native ingest ownership for legacy
// snapshot suppression (default/global call path).
func (p *TrueNASPoller) SnapshotOwnedSources() []unifiedresources.DataSource {
diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.go
index 2c4c57dc4c..90fa8e6744 100644
--- a/internal/monitoring/truenas_poller_test.go
+++ b/internal/monitoring/truenas_poller_test.go
@@ -286,9 +286,53 @@ func TestTrueNASPollerPhysicalDiskTemperatureHistoryUsesTenantScopedProvider(t *
}
}
+func TestTrueNASPollerGuestMetricHistoryUsesTenantScopedProvider(t *testing.T) {
+ previous := truenas.IsFeatureEnabled()
+ truenas.SetFeatureEnabled(true)
+ t.Cleanup(func() { truenas.SetFeatureEnabled(previous) })
+
+ fixtures := truenas.DefaultFixtures()
+ now := time.Date(2026, 3, 29, 20, 0, 0, 0, time.UTC)
+ fetcher := &controllableTrueNASHistoryFetcher{
+ snapshot: &fixtures,
+ systemHistory: &truenas.SystemMetricHistory{
+ CPUPercent: []truenas.TimeSeriesPoint{
+ {Timestamp: now.Add(-2 * time.Hour), Value: 20},
+ {Timestamp: now, Value: 34},
+ },
+ MemoryPercent: []truenas.TimeSeriesPoint{
+ {Timestamp: now.Add(-2 * time.Hour), Value: 45},
+ {Timestamp: now, Value: 62},
+ },
+ },
+ }
+ provider := truenas.NewLiveProvider(fetcher)
+ if err := provider.Refresh(context.Background()); err != nil {
+ t.Fatalf("Refresh() error = %v", err)
+ }
+
+ poller := NewTrueNASPoller(nil, time.Minute, nil)
+ poller.providersByOrg["default"] = map[string]*truenas.Provider{
+ "conn-1": provider,
+ }
+
+ history := poller.GuestMetricHistory(nil, "default", "agent", 4*time.Hour)
+ metricMap, ok := history["truenas-main"]
+ if !ok {
+ t.Fatalf("expected canonical agent metric id truenas-main, got %#v", history)
+ }
+ if len(metricMap["cpu"]) != 2 || metricMap["cpu"][1].Value != 34 {
+ t.Fatalf("unexpected cpu history: %+v", metricMap["cpu"])
+ }
+ if len(metricMap["memory"]) != 2 || metricMap["memory"][1].Value != 62 {
+ t.Fatalf("unexpected memory history: %+v", metricMap["memory"])
+ }
+}
+
type controllableTrueNASHistoryFetcher struct {
- snapshot *truenas.FixtureSnapshot
- history map[string][]truenas.TimeSeriesPoint
+ snapshot *truenas.FixtureSnapshot
+ history map[string][]truenas.TimeSeriesPoint
+ systemHistory *truenas.SystemMetricHistory
}
func (s *controllableTrueNASHistoryFetcher) Fetch(context.Context) (*truenas.FixtureSnapshot, error) {
@@ -323,6 +367,23 @@ func (s *controllableTrueNASHistoryFetcher) DiskTemperatureHistory(_ context.Con
return result, nil
}
+func (s *controllableTrueNASHistoryFetcher) SystemMetricHistory(context.Context, time.Duration) (*truenas.SystemMetricHistory, error) {
+ if s == nil || s.systemHistory == nil {
+ return nil, nil
+ }
+ copied := *s.systemHistory
+ copied.CPUPercent = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.CPUPercent...)
+ copied.MemoryPercent = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.MemoryPercent...)
+ copied.MemoryUsedBytes = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.MemoryUsedBytes...)
+ copied.MemoryAvailableBytes = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.MemoryAvailableBytes...)
+ copied.MemoryTotalBytes = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.MemoryTotalBytes...)
+ copied.NetInRate = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.NetInRate...)
+ copied.NetOutRate = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.NetOutRate...)
+ copied.DiskReadRate = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.DiskReadRate...)
+ copied.DiskWriteRate = append([]truenas.TimeSeriesPoint(nil), s.systemHistory.DiskWriteRate...)
+ return &copied, nil
+}
+
type pollerControlFetcher struct {
snapshot *truenas.FixtureSnapshot
startCalls []string
diff --git a/internal/truenas/client.go b/internal/truenas/client.go
index fb36b1c7c9..9af5d2f061 100644
--- a/internal/truenas/client.go
+++ b/internal/truenas/client.go
@@ -218,6 +218,26 @@ func (c *Client) GetSystemTelemetry(ctx context.Context) (*SystemInfo, error) {
return telemetry, 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) {
+ 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
+ }
+
+ return rpc.getSystemMetricHistory(ctx, duration)
+}
+
// GetPools returns storage pools.
func (c *Client) GetPools(ctx context.Context) ([]Pool, error) {
var response []poolResponse
@@ -1339,6 +1359,36 @@ func isTimeoutError(err error) bool {
return errors.As(err, &netErr) && netErr.Timeout()
}
+func (c *trueNASRPCClient) getSystemMetricHistory(ctx context.Context, duration time.Duration) (*SystemMetricHistory, error) {
+ if c == nil || c.conn == nil {
+ return nil, fmt.Errorf("truenas rpc connection is nil")
+ }
+ if duration <= 0 {
+ duration = 24 * time.Hour
+ }
+
+ end := time.Now().Unix()
+ start := end - int64(duration.Seconds())
+ if start <= 0 {
+ start = end
+ }
+
+ response, err := c.getReportingDataWithQuery(ctx, []map[string]any{
+ {"name": "cpu", "identifier": nil},
+ {"name": "memory", "identifier": nil},
+ {"name": "interface", "identifier": nil},
+ {"name": "disk", "identifier": nil},
+ }, map[string]any{
+ "aggregate": false,
+ "start": start,
+ "end": end,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return parseSystemMetricHistory(response), nil
+}
+
func (c *trueNASRPCClient) getSystemTemperatures(ctx context.Context) (map[string]float64, error) {
if c == nil || c.conn == nil {
return nil, fmt.Errorf("truenas rpc connection is nil")
@@ -1659,6 +1709,76 @@ func parseSystemTemperatures(responses []trueNASReportingGetDataResponse) map[st
return temperatures
}
+func parseSystemMetricHistory(responses []trueNASReportingGetDataResponse) *SystemMetricHistory {
+ if len(responses) == 0 {
+ return nil
+ }
+
+ history := &SystemMetricHistory{}
+ for _, response := range responses {
+ name := strings.TrimSpace(strings.ToLower(response.Name))
+ switch name {
+ case "cpu", "memory", "interface", "disk":
+ default:
+ continue
+ }
+
+ for _, raw := range response.Data {
+ timestamp, values, ok := parseReportingSeriesValues(raw, response.Legend)
+ if !ok || timestamp.IsZero() || len(values) == 0 {
+ continue
+ }
+
+ switch name {
+ case "cpu":
+ if value, ok := parseSystemCPUPercent(values); ok {
+ history.CPUPercent = appendTimeSeriesPoint(history.CPUPercent, timestamp, value)
+ }
+ case "memory":
+ if value, ok := parseSystemMemoryPercent(values); ok {
+ history.MemoryPercent = appendTimeSeriesPoint(history.MemoryPercent, timestamp, value)
+ }
+ if value, ok := pickReportingValue(values, "used", "memory_used", "used_bytes", "active", "memory"); ok {
+ history.MemoryUsedBytes = appendTimeSeriesPoint(history.MemoryUsedBytes, timestamp, value)
+ }
+ if value, ok := pickReportingValue(values, "available", "free", "available_bytes", "free_bytes"); ok {
+ history.MemoryAvailableBytes = appendTimeSeriesPoint(history.MemoryAvailableBytes, timestamp, value)
+ }
+ if value, ok := pickReportingValue(values, "total", "memory_total", "total_bytes", "physical_memory_total"); ok {
+ history.MemoryTotalBytes = appendTimeSeriesPoint(history.MemoryTotalBytes, timestamp, value)
+ }
+ case "interface":
+ if value, ok := pickReportingValue(values, "received", "received_bytes", "rx", "rx_bytes", "netin", "in"); ok {
+ history.NetInRate = appendTimeSeriesPoint(history.NetInRate, timestamp, value)
+ }
+ if value, ok := pickReportingValue(values, "sent", "sent_bytes", "tx", "tx_bytes", "netout", "out"); ok {
+ history.NetOutRate = appendTimeSeriesPoint(history.NetOutRate, timestamp, value)
+ }
+ case "disk":
+ if value, ok := pickReportingValue(values, "read", "read_bytes", "diskread", "bytes_read"); ok {
+ history.DiskReadRate = appendTimeSeriesPoint(history.DiskReadRate, timestamp, value)
+ }
+ if value, ok := pickReportingValue(values, "write", "write_bytes", "diskwrite", "bytes_written"); ok {
+ history.DiskWriteRate = appendTimeSeriesPoint(history.DiskWriteRate, timestamp, value)
+ }
+ }
+ }
+ }
+
+ if len(history.CPUPercent) == 0 &&
+ len(history.MemoryPercent) == 0 &&
+ len(history.MemoryUsedBytes) == 0 &&
+ len(history.MemoryAvailableBytes) == 0 &&
+ len(history.MemoryTotalBytes) == 0 &&
+ len(history.NetInRate) == 0 &&
+ len(history.NetOutRate) == 0 &&
+ len(history.DiskReadRate) == 0 &&
+ len(history.DiskWriteRate) == 0 {
+ return nil
+ }
+ return history
+}
+
func parseReportingDiskTemperatures(responses []trueNASReportingGetDataResponse) map[string]int {
if len(responses) == 0 {
return nil
@@ -1811,42 +1931,104 @@ func readFloatValueAny(record map[string]any, keys ...string) (float64, bool) {
}
func parseReportingSeriesPoint(raw any, legends []string) (time.Time, float64, bool) {
+ timestamp, values, ok := parseReportingSeriesValues(raw, legends)
+ if !ok || timestamp.IsZero() {
+ return time.Time{}, 0, false
+ }
+ for _, legend := range legends {
+ if value, ok := values[legend]; ok {
+ return timestamp, value, true
+ }
+ }
+ return time.Time{}, 0, false
+}
+
+func parseReportingSeriesValues(raw any, legends []string) (time.Time, map[string]float64, bool) {
switch typed := raw.(type) {
case []any:
if len(typed) < 2 {
- return time.Time{}, 0, false
+ return time.Time{}, nil, false
}
timestamp, ok := parseReportingTimestampAny(typed[0])
if !ok {
- return time.Time{}, 0, false
+ return time.Time{}, nil, false
}
- if parsed, ok := parseFloat64Any(typed[1]); ok {
- return timestamp, parsed, true
+ if parsed, ok := parseFloat64Any(typed[1]); ok && len(legends) == 1 {
+ return timestamp, map[string]float64{legends[0]: parsed}, true
}
values := extractReportingLegendFloatValues(typed[1:], legends)
- for _, legend := range legends {
- if value, ok := values[legend]; ok {
- return timestamp, value, true
- }
+ if len(values) == 0 {
+ return time.Time{}, nil, false
}
+ return timestamp, values, true
case map[string]any:
timestamp, ok := parseReportingTimestampAny(
firstNonNilMapValue(typed, "timestamp", "time", "ts", "x"),
)
if !ok {
- return time.Time{}, 0, false
+ return time.Time{}, nil, false
}
values := extractReportingLegendFloatValues(typed, legends)
- for _, legend := range legends {
- if value, ok := values[legend]; ok {
- return timestamp, value, true
+ if len(values) == 0 && len(legends) == 1 {
+ if value, ok := readFloatValueAny(typed, "value", "y", "temperature"); ok {
+ values = map[string]float64{legends[0]: value}
}
}
- if value, ok := readFloatValueAny(typed, "value", "y", "temperature"); ok {
- return timestamp, value, true
+ if len(values) == 0 {
+ return time.Time{}, nil, false
}
+ return timestamp, values, true
+ default:
+ return time.Time{}, nil, false
}
- return time.Time{}, 0, false
+}
+
+func appendTimeSeriesPoint(series []TimeSeriesPoint, timestamp time.Time, value float64) []TimeSeriesPoint {
+ return append(series, TimeSeriesPoint{Timestamp: timestamp, Value: value})
+}
+
+func parseSystemCPUPercent(values map[string]float64) (float64, bool) {
+ if value, ok := pickReportingValue(values, "usage", "percent", "cpu", "total", "system_cpu"); ok {
+ return value, true
+ }
+ if idle, ok := pickReportingValue(values, "idle"); ok {
+ return 100 - idle, true
+ }
+ return 0, false
+}
+
+func parseSystemMemoryPercent(values map[string]float64) (float64, bool) {
+ if value, ok := pickReportingValue(values, "usage", "percent", "used_percent", "memory_percent"); ok {
+ return value, true
+ }
+ used, hasUsed := pickReportingValue(values, "used", "memory_used", "used_bytes", "active", "memory")
+ total, hasTotal := pickReportingValue(values, "total", "memory_total", "total_bytes", "physical_memory_total")
+ if hasUsed && hasTotal && total > 0 {
+ return (used / total) * 100, true
+ }
+ available, hasAvailable := pickReportingValue(values, "available", "free", "available_bytes", "free_bytes")
+ if hasAvailable && hasTotal && total > 0 {
+ return ((total - available) / total) * 100, true
+ }
+ return 0, false
+}
+
+func pickReportingValue(values map[string]float64, candidates ...string) (float64, bool) {
+ if len(values) == 0 {
+ return 0, false
+ }
+
+ normalized := make(map[string]float64, len(values))
+ for key, value := range values {
+ normalized[normalizeTemperatureLegendLabel(key)] = value
+ }
+
+ for _, candidate := range candidates {
+ if value, ok := normalized[normalizeTemperatureLegendLabel(candidate)]; ok {
+ return value, true
+ }
+ }
+ return 0, false
}
func firstNonNilMapValue(record map[string]any, keys ...string) any {
diff --git a/internal/truenas/client_test.go b/internal/truenas/client_test.go
index 99e1c98b46..006c3127ab 100644
--- a/internal/truenas/client_test.go
+++ b/internal/truenas/client_test.go
@@ -469,6 +469,110 @@ func TestGetSystemTelemetryFromRPC(t *testing.T) {
}
}
+func TestGetSystemMetricHistoryUsesReportingRPC(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)
+
+ historyReq := readRPCRequest(t, conn)
+ if historyReq.Method != "reporting.get_data" {
+ t.Fatalf("expected reporting.get_data, got %q", historyReq.Method)
+ }
+ params, ok := historyReq.Params.([]any)
+ if !ok || len(params) != 2 {
+ t.Fatalf("unexpected history params: %#v", historyReq.Params)
+ }
+ graphs, ok := params[0].([]any)
+ if !ok || len(graphs) != 4 {
+ t.Fatalf("unexpected history graphs: %#v", params[0])
+ }
+ query, ok := params[1].(map[string]any)
+ if !ok || query["aggregate"] != false {
+ t.Fatalf("expected aggregate=false history query, got %#v", params[1])
+ }
+
+ now := time.Now().UTC().Truncate(time.Second)
+ writeRPCResult(t, conn, historyReq.ID, []map[string]any{
+ {
+ "name": "cpu",
+ "identifier": nil,
+ "legend": []string{"usage"},
+ "data": []any{
+ map[string]any{"timestamp": now.Add(-2 * time.Hour).Unix(), "usage": 21.0},
+ map[string]any{"timestamp": now.Unix(), "usage": 34.0},
+ },
+ "aggregations": map[string]any{},
+ "start": now.Add(-2 * time.Hour).Unix(),
+ "end": now.Unix(),
+ },
+ {
+ "name": "memory",
+ "identifier": nil,
+ "legend": []string{"used", "total"},
+ "data": []any{
+ map[string]any{"timestamp": now.Add(-2 * time.Hour).Unix(), "used": 8.0 * 1024 * 1024 * 1024, "total": 16.0 * 1024 * 1024 * 1024},
+ map[string]any{"timestamp": now.Unix(), "used": 10.0 * 1024 * 1024 * 1024, "total": 16.0 * 1024 * 1024 * 1024},
+ },
+ "aggregations": map[string]any{},
+ "start": now.Add(-2 * time.Hour).Unix(),
+ "end": now.Unix(),
+ },
+ {
+ "name": "interface",
+ "identifier": nil,
+ "legend": []string{"received", "sent"},
+ "data": []any{
+ map[string]any{"timestamp": now.Add(-2 * time.Hour).Unix(), "received": 1024.0, "sent": 512.0},
+ map[string]any{"timestamp": now.Unix(), "received": 4096.0, "sent": 2048.0},
+ },
+ "aggregations": map[string]any{},
+ "start": now.Add(-2 * time.Hour).Unix(),
+ "end": now.Unix(),
+ },
+ {
+ "name": "disk",
+ "identifier": nil,
+ "legend": []string{"read", "write"},
+ "data": []any{
+ map[string]any{"timestamp": now.Add(-2 * time.Hour).Unix(), "read": 2048.0, "write": 1024.0},
+ map[string]any{"timestamp": now.Unix(), "read": 8192.0, "write": 4096.0},
+ },
+ "aggregations": map[string]any{},
+ "start": now.Add(-2 * time.Hour).Unix(),
+ "end": now.Unix(),
+ },
+ })
+ })
+ t.Cleanup(server.Close)
+
+ client := mustClientForServer(t, server.URL, ClientConfig{APIKey: "api-key"})
+ history, err := client.GetSystemMetricHistory(context.Background(), 4*time.Hour)
+ if err != nil {
+ t.Fatalf("GetSystemMetricHistory() error = %v", err)
+ }
+ if history == nil {
+ t.Fatal("expected system metric history")
+ }
+ if got := len(history.CPUPercent); got != 2 {
+ t.Fatalf("expected cpu history, got %+v", history)
+ }
+ if got := len(history.MemoryPercent); got != 2 {
+ t.Fatalf("expected memory percent history, got %+v", history)
+ }
+ if got := history.MemoryPercent[1].Value; got <= 0 {
+ t.Fatalf("expected non-zero memory percent, got %+v", history.MemoryPercent)
+ }
+ if got := history.NetInRate[1].Value; got != 4096.0 {
+ t.Fatalf("expected network history, got %+v", history.NetInRate)
+ }
+ if got := history.DiskWriteRate[1].Value; got != 4096.0 {
+ t.Fatalf("expected disk history, got %+v", history.DiskWriteRate)
+ }
+}
+
func TestGetSystemTelemetryIgnoresUnavailableTemperatureRPC(t *testing.T) {
server := newMockServerWithRPC(t, defaultAPIResponses(), nil, func(t *testing.T, conn *websocket.Conn) {
authReq := readRPCRequest(t, conn)
diff --git a/internal/truenas/provider.go b/internal/truenas/provider.go
index bb8d45184c..a83965d568 100644
--- a/internal/truenas/provider.go
+++ b/internal/truenas/provider.go
@@ -60,6 +60,10 @@ type physicalDiskHistoryFetcher interface {
DiskTemperatureHistory(ctx context.Context, identifiers []string, duration time.Duration) (map[string][]TimeSeriesPoint, error)
}
+type systemMetricHistoryFetcher interface {
+ SystemMetricHistory(ctx context.Context, duration time.Duration) (*SystemMetricHistory, error)
+}
+
// APIFetcher loads snapshots from the live TrueNAS API client.
type APIFetcher struct {
Client *Client
@@ -109,6 +113,13 @@ func (f *APIFetcher) DiskTemperatureHistory(ctx context.Context, identifiers []s
return f.Client.GetDiskTemperatureHistory(ctx, identifiers, duration)
}
+func (f *APIFetcher) SystemMetricHistory(ctx context.Context, duration time.Duration) (*SystemMetricHistory, error) {
+ if f == nil || f.Client == nil {
+ return nil, fmt.Errorf("truenas api fetcher client is nil")
+ }
+ return f.Client.GetSystemMetricHistory(ctx, duration)
+}
+
// FixtureFetcher loads snapshots from static fixture data.
type FixtureFetcher struct {
Snapshot FixtureSnapshot
@@ -266,6 +277,59 @@ func (p *Provider) GetAppConfig(_ context.Context, appID string) (*AppConfigResu
return result, nil
}
+// SystemMetricHistory returns canonical host-chart metrics for the TrueNAS
+// appliance keyed by the shared agent metrics resource ID.
+func (p *Provider) SystemMetricHistory(ctx context.Context, duration time.Duration) (string, map[string][]TimeSeriesPoint, error) {
+ if p == nil {
+ return "", nil, fmt.Errorf("truenas provider is nil")
+ }
+ historyFetcher, ok := p.fetcher.(systemMetricHistoryFetcher)
+ if !ok {
+ return "", nil, fmt.Errorf("truenas provider fetcher does not support system metric history")
+ }
+
+ snapshot := p.Snapshot()
+ if snapshot == nil {
+ return "", nil, fmt.Errorf("truenas provider has no cached snapshot")
+ }
+ resourceID := trueNASSystemMetricResourceID(snapshot.System)
+ if resourceID == "" {
+ return "", nil, fmt.Errorf("truenas provider snapshot is missing system metric resource id")
+ }
+
+ nativeHistory, err := historyFetcher.SystemMetricHistory(ctx, duration)
+ if err != nil {
+ return "", nil, err
+ }
+ if nativeHistory == nil {
+ return resourceID, nil, nil
+ }
+
+ metricMap := make(map[string][]TimeSeriesPoint)
+ if len(nativeHistory.CPUPercent) > 0 {
+ metricMap["cpu"] = cloneTimeSeriesPoints(nativeHistory.CPUPercent)
+ }
+ if memoryPercent := systemMemoryPercentHistory(nativeHistory, snapshot.System.MemoryTotalBytes); len(memoryPercent) > 0 {
+ metricMap["memory"] = memoryPercent
+ }
+ if len(nativeHistory.NetInRate) > 0 {
+ metricMap["netin"] = cloneTimeSeriesPoints(nativeHistory.NetInRate)
+ }
+ if len(nativeHistory.NetOutRate) > 0 {
+ metricMap["netout"] = cloneTimeSeriesPoints(nativeHistory.NetOutRate)
+ }
+ if len(nativeHistory.DiskReadRate) > 0 {
+ metricMap["diskread"] = cloneTimeSeriesPoints(nativeHistory.DiskReadRate)
+ }
+ if len(nativeHistory.DiskWriteRate) > 0 {
+ metricMap["diskwrite"] = cloneTimeSeriesPoints(nativeHistory.DiskWriteRate)
+ }
+ if len(metricMap) == 0 {
+ return resourceID, nil, nil
+ }
+ return resourceID, metricMap, nil
+}
+
// PhysicalDiskTemperatureHistory returns canonical physical-disk temperature
// series keyed by the shared physical-disk metrics resource IDs.
func (p *Provider) PhysicalDiskTemperatureHistory(ctx context.Context, duration time.Duration) (map[string][]TimeSeriesPoint, error) {
@@ -1408,6 +1472,60 @@ func temperatureAggregateMetaFromTrueNASDisk(disk Disk) *unifiedresources.Temper
}
}
+func cloneTimeSeriesPoints(points []TimeSeriesPoint) []TimeSeriesPoint {
+ if len(points) == 0 {
+ return nil
+ }
+ cloned := make([]TimeSeriesPoint, len(points))
+ copy(cloned, points)
+ return cloned
+}
+
+func systemMemoryPercentHistory(history *SystemMetricHistory, fallbackTotalBytes int64) []TimeSeriesPoint {
+ if history == nil {
+ return nil
+ }
+ if len(history.MemoryPercent) > 0 {
+ return cloneTimeSeriesPoints(history.MemoryPercent)
+ }
+
+ totalBytes := float64(fallbackTotalBytes)
+ if totalBytes <= 0 {
+ if len(history.MemoryTotalBytes) > 0 {
+ totalBytes = history.MemoryTotalBytes[len(history.MemoryTotalBytes)-1].Value
+ }
+ }
+ if totalBytes <= 0 {
+ return nil
+ }
+
+ if len(history.MemoryUsedBytes) > 0 {
+ points := make([]TimeSeriesPoint, 0, len(history.MemoryUsedBytes))
+ for _, point := range history.MemoryUsedBytes {
+ points = append(points, TimeSeriesPoint{
+ Timestamp: point.Timestamp,
+ Value: (point.Value / totalBytes) * 100,
+ })
+ }
+ return points
+ }
+ if len(history.MemoryAvailableBytes) > 0 {
+ points := make([]TimeSeriesPoint, 0, len(history.MemoryAvailableBytes))
+ for _, point := range history.MemoryAvailableBytes {
+ points = append(points, TimeSeriesPoint{
+ Timestamp: point.Timestamp,
+ Value: ((totalBytes - point.Value) / totalBytes) * 100,
+ })
+ }
+ return points
+ }
+ return nil
+}
+
+func trueNASSystemMetricResourceID(system SystemInfo) string {
+ return strings.TrimSpace(system.Hostname)
+}
+
func trueNASDiskHistoryLookupKeys(disk Disk) []string {
return dedupeStrings([]string{
strings.TrimSpace(disk.Name),
diff --git a/internal/truenas/provider_test.go b/internal/truenas/provider_test.go
index 28301fea4c..710d6a10ab 100644
--- a/internal/truenas/provider_test.go
+++ b/internal/truenas/provider_test.go
@@ -38,11 +38,12 @@ func (s *closableStubFetcher) Close() {
}
type controllableStubFetcher struct {
- snapshot *FixtureSnapshot
- startCalls []string
- stopCalls []string
- logReads []appLogReadCall
- diskHistory map[string][]TimeSeriesPoint
+ snapshot *FixtureSnapshot
+ startCalls []string
+ stopCalls []string
+ logReads []appLogReadCall
+ diskHistory map[string][]TimeSeriesPoint
+ systemHistory *SystemMetricHistory
}
type appLogReadCall struct {
@@ -113,6 +114,23 @@ func (s *controllableStubFetcher) DiskTemperatureHistory(_ context.Context, iden
return result, nil
}
+func (s *controllableStubFetcher) SystemMetricHistory(context.Context, time.Duration) (*SystemMetricHistory, error) {
+ if s == nil || s.systemHistory == nil {
+ return nil, nil
+ }
+ copied := *s.systemHistory
+ copied.CPUPercent = cloneTimeSeriesPoints(s.systemHistory.CPUPercent)
+ copied.MemoryPercent = cloneTimeSeriesPoints(s.systemHistory.MemoryPercent)
+ copied.MemoryUsedBytes = cloneTimeSeriesPoints(s.systemHistory.MemoryUsedBytes)
+ copied.MemoryAvailableBytes = cloneTimeSeriesPoints(s.systemHistory.MemoryAvailableBytes)
+ copied.MemoryTotalBytes = cloneTimeSeriesPoints(s.systemHistory.MemoryTotalBytes)
+ copied.NetInRate = cloneTimeSeriesPoints(s.systemHistory.NetInRate)
+ copied.NetOutRate = cloneTimeSeriesPoints(s.systemHistory.NetOutRate)
+ copied.DiskReadRate = cloneTimeSeriesPoints(s.systemHistory.DiskReadRate)
+ copied.DiskWriteRate = cloneTimeSeriesPoints(s.systemHistory.DiskWriteRate)
+ return &copied, nil
+}
+
func TestFixtureFetcherReturnsSnapshotCopy(t *testing.T) {
fixtures := DefaultFixtures()
fetcher := &FixtureFetcher{Snapshot: fixtures}
@@ -813,3 +831,48 @@ func TestProviderPhysicalDiskTemperatureHistoryUsesCanonicalMetricIDs(t *testing
t.Fatalf("expected latest point value 34, got %+v", points)
}
}
+
+func TestProviderSystemMetricHistoryUsesCanonicalAgentMetricIDs(t *testing.T) {
+ fixtures := DefaultFixtures()
+ now := time.Date(2026, 3, 29, 20, 0, 0, 0, time.UTC)
+ fetcher := &controllableStubFetcher{
+ snapshot: &fixtures,
+ systemHistory: &SystemMetricHistory{
+ CPUPercent: []TimeSeriesPoint{
+ {Timestamp: now.Add(-2 * time.Hour), Value: 20},
+ {Timestamp: now, Value: 34},
+ },
+ MemoryUsedBytes: []TimeSeriesPoint{
+ {Timestamp: now.Add(-2 * time.Hour), Value: 8 * 1024 * 1024 * 1024},
+ {Timestamp: now, Value: 10 * 1024 * 1024 * 1024},
+ },
+ NetInRate: []TimeSeriesPoint{
+ {Timestamp: now, Value: 4096},
+ },
+ },
+ }
+ provider := NewLiveProvider(fetcher)
+ if err := provider.Refresh(context.Background()); err != nil {
+ t.Fatalf("Refresh() error = %v", err)
+ }
+
+ resourceID, history, err := provider.SystemMetricHistory(context.Background(), 4*time.Hour)
+ if err != nil {
+ t.Fatalf("SystemMetricHistory() error = %v", err)
+ }
+ if resourceID != "truenas-main" {
+ t.Fatalf("resourceID = %q, want truenas-main", resourceID)
+ }
+ if got := len(history["cpu"]); got != 2 {
+ t.Fatalf("expected cpu history points, got %+v", history)
+ }
+ if got := len(history["memory"]); got != 2 {
+ t.Fatalf("expected memory history points, got %+v", history)
+ }
+ if history["memory"][1].Value <= 0 {
+ t.Fatalf("expected memory percent history, got %+v", history["memory"])
+ }
+ if got := len(history["netin"]); got != 1 {
+ t.Fatalf("expected netin history points, got %+v", history)
+ }
+}
diff --git a/internal/truenas/types.go b/internal/truenas/types.go
index c91c289eb2..16dda380b2 100644
--- a/internal/truenas/types.go
+++ b/internal/truenas/types.go
@@ -88,6 +88,20 @@ type TimeSeriesPoint struct {
Value float64
}
+// SystemMetricHistory stores provider-native TrueNAS system history before it
+// is normalized onto the canonical monitoring guest-chart surface.
+type SystemMetricHistory struct {
+ CPUPercent []TimeSeriesPoint
+ MemoryPercent []TimeSeriesPoint
+ MemoryUsedBytes []TimeSeriesPoint
+ MemoryAvailableBytes []TimeSeriesPoint
+ MemoryTotalBytes []TimeSeriesPoint
+ NetInRate []TimeSeriesPoint
+ NetOutRate []TimeSeriesPoint
+ DiskReadRate []TimeSeriesPoint
+ DiskWriteRate []TimeSeriesPoint
+}
+
// Alert mirrors a TrueNAS alert listing entry.
type Alert struct {
ID string