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
Reuse mock history seeds across tenants
rcourtman6eb559905d36
diff --git a/internal/mock/fixture_graph.go b/internal/mock/fixture_graph.goindex 161a12e13f..16ee8be3fb 100644--- a/internal/mock/fixture_graph.go+++ b/internal/mock/fixture_graph.go@@ -101,14 +101,21 @@ func (g *FixtureGraph) UpdateAlertSnapshots(active []alerts.Alert, resolved []mo}func CurrentFixtureGraph() FixtureGraph {- if !IsMockEnabled() {- return emptyFixtureGraph()- }+ graph, _ := CurrentFixtureGraphWithRevision()+ return graph+}+// CurrentFixtureGraphWithRevision returns one coherent fixture snapshot and+// its structural revision so downstream caches cannot pair an old graph with+// a newer invalidation token.+func CurrentFixtureGraphWithRevision() (FixtureGraph, uint64) {dataMu.RLock()defer dataMu.RUnlock()- return cloneFixtureGraph(mockGraph)+ if !enabled.Load() {+ return emptyFixtureGraph(), fixtureRevision.Load()+ }+ return cloneFixtureGraph(mockGraph), fixtureRevision.Load()}func currentOrDefaultPlatformFixtures() PlatformFixtures {diff --git a/internal/mock/integration.go b/internal/mock/integration.goindex 456b0f4e66..7b092bbc1d 100644--- a/internal/mock/integration.go+++ b/internal/mock/integration.go@@ -16,16 +16,17 @@ import ()var (- dataMu sync.RWMutex- setEnabledMu sync.Mutex- updateLoopMu sync.Mutex- mockGraph = emptyFixtureGraph()- mockConfig = DefaultConfig- enabled atomic.Bool- updateEveryNS atomic.Int64- updateTicker *time.Ticker- stopUpdatesCh chan struct{}- updateLoopWg sync.WaitGroup+ dataMu sync.RWMutex+ setEnabledMu sync.Mutex+ updateLoopMu sync.Mutex+ mockGraph = emptyFixtureGraph()+ mockConfig = DefaultConfig+ enabled atomic.Bool+ fixtureRevision atomic.Uint64+ updateEveryNS atomic.Int64+ updateTicker *time.Ticker+ stopUpdatesCh chan struct{}+ updateLoopWg sync.WaitGroup)func init() {@@ -168,6 +169,7 @@ func enableMockMode(config MockConfig, fromInit bool) {dataMu.Lock()mockConfig = configmockGraph = buildFixtureGraph(config, now)+ fixtureRevision.Add(1)enabled.Store(true)dataMu.Unlock()startUpdateLoop()@@ -202,6 +204,7 @@ func disableMockMode() {dataMu.Lock()mockGraph = emptyFixtureGraph()+ fixtureRevision.Add(1)dataMu.Unlock()log.Info().Msg("mock mode disabled")@@ -474,6 +477,7 @@ func SetMockConfig(cfg MockConfig) {setMockUpdateInterval(normalized.UpdateInterval)if configChanged && enabled.Load() {mockGraph = buildFixtureGraph(normalized, time.Now())+ fixtureRevision.Add(1)}dataMu.Unlock()diff --git a/internal/monitoring/metrics_history.go b/internal/monitoring/metrics_history.goindex ae6e1bb0c2..fe23616e92 100644--- a/internal/monitoring/metrics_history.go+++ b/internal/monitoring/metrics_history.go@@ -63,6 +63,64 @@ func NewMetricsHistory(maxDataPoints int, retentionTime time.Duration) *MetricsH}}+func (mh *MetricsHistory) clone() *MetricsHistory {+ if mh == nil {+ return nil+ }++ mh.mu.RLock()+ defer mh.mu.RUnlock()++ cloned := NewMetricsHistory(mh.maxDataPoints, mh.retentionTime)+ for id, metrics := range mh.guestMetrics {+ cloned.guestMetrics[id] = cloneGuestMetrics(metrics)+ }+ for id, metrics := range mh.nodeMetrics {+ cloned.nodeMetrics[id] = cloneGuestMetrics(metrics)+ }+ for id, metrics := range mh.storageMetrics {+ if metrics == nil {+ cloned.storageMetrics[id] = nil+ continue+ }+ cloned.storageMetrics[id] = &StorageMetrics{+ Usage: append([]MetricPoint(nil), metrics.Usage...),+ Used: append([]MetricPoint(nil), metrics.Used...),+ Total: append([]MetricPoint(nil), metrics.Total...),+ Avail: append([]MetricPoint(nil), metrics.Avail...),+ }+ }+ for id, metrics := range mh.diskMetrics {+ if metrics == nil {+ cloned.diskMetrics[id] = nil+ continue+ }+ cloned.diskMetrics[id] = &DiskMetrics{+ Temperature: append([]MetricPoint(nil), metrics.Temperature...),+ Utilization: append([]MetricPoint(nil), metrics.Utilization...),+ DiskRead: append([]MetricPoint(nil), metrics.DiskRead...),+ DiskWrite: append([]MetricPoint(nil), metrics.DiskWrite...),+ }+ }+ return cloned+}++func cloneGuestMetrics(metrics *GuestMetrics) *GuestMetrics {+ if metrics == nil {+ return nil+ }+ return &GuestMetrics{+ CPU: append([]MetricPoint(nil), metrics.CPU...),+ Memory: append([]MetricPoint(nil), metrics.Memory...),+ Disk: append([]MetricPoint(nil), metrics.Disk...),+ DiskRead: append([]MetricPoint(nil), metrics.DiskRead...),+ DiskWrite: append([]MetricPoint(nil), metrics.DiskWrite...),+ NetworkIn: append([]MetricPoint(nil), metrics.NetworkIn...),+ NetworkOut: append([]MetricPoint(nil), metrics.NetworkOut...),+ Temperature: append([]MetricPoint(nil), metrics.Temperature...),+ }+}+// Reset clears all historical metrics data.func (mh *MetricsHistory) Reset() {mh.mu.Lock()diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.goindex 0b05020b08..1c8a4d3e99 100644--- a/internal/monitoring/mock_metrics_history.go+++ b/internal/monitoring/mock_metrics_history.go@@ -8,6 +8,7 @@ import ("math/rand""sort""strings"+ "sync""time""github.com/rcourtman/pulse-go-rewrite/internal/mock"@@ -35,6 +36,20 @@ type mockMetricsSamplerConfig struct {SeedStore bool}+type mockMetricsSeedCacheKey struct {+ fixtureRevision uint64+ seedAtUnixNano int64+ seedDuration time.Duration+ sampleInterval time.Duration+ maxDataPoints int+}++var mockMetricsSeedCache = struct {+ sync.Mutex+ key mockMetricsSeedCacheKey+ history *MetricsHistory+}{}+func mockMetricsSamplerConfigFromEnv() mockMetricsSamplerConfig {seedDuration := parseDurationEnv("PULSE_MOCK_TRENDS_SEED_DURATION", defaultMockSeedDuration)sampleInterval := parseDurationEnv("PULSE_MOCK_TRENDS_SAMPLE_INTERVAL", defaultMockSampleInterval)@@ -1003,6 +1018,43 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Filog.Debug().Msg("mock seeding: completed")}+func prepareMockMetricsHistory(+ graph mock.FixtureGraph,+ fixtureRevision uint64,+ now time.Time,+ seedDuration time.Duration,+ interval time.Duration,+ maxDataPoints int,+ storeSink *metrics.Store,+) (*MetricsHistory, bool) {+ seedAt := normalizeMockMetricTimestamp(now, interval)+ if storeSink != nil {+ history := NewMetricsHistory(maxDataPoints, seedDuration)+ seedMockMetricsHistory(history, storeSink, graph, seedAt, seedDuration, interval)+ return history, false+ }++ key := mockMetricsSeedCacheKey{+ fixtureRevision: fixtureRevision,+ seedAtUnixNano: seedAt.UnixNano(),+ seedDuration: seedDuration,+ sampleInterval: interval,+ maxDataPoints: maxDataPoints,+ }++ mockMetricsSeedCache.Lock()+ defer mockMetricsSeedCache.Unlock()+ if mockMetricsSeedCache.history != nil && mockMetricsSeedCache.key == key {+ return mockMetricsSeedCache.history.clone(), true+ }++ template := NewMetricsHistory(maxDataPoints, seedDuration)+ seedMockMetricsHistory(template, nil, graph, seedAt, seedDuration, interval)+ mockMetricsSeedCache.key = key+ mockMetricsSeedCache.history = template+ return template.clone(), false+}+// recordTrueNASFixturesMetrics records live fixture ticks for TrueNAS host,// storage, and app-container metrics.func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixtures mock.PlatformFixtures, ts time.Time) {@@ -1630,7 +1682,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {m.metricsHistory = NewMetricsHistory(maxPoints, seedDuration)m.mu.Unlock()- graph := mock.CurrentFixtureGraph()+ graph, fixtureRevision := mock.CurrentFixtureGraphWithRevision()state := graph.Statelog.Info().Int("nodes", len(state.Nodes)).@@ -1653,7 +1705,21 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {log.Warn().Msg("PULSE_MOCK_SEED_METRICS_STORE is set but the metrics store is unavailable; mock report history will stay empty")}}- seedMockMetricsHistory(m.metricsHistory, storeSink, graph, normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval), seedDuration, cfg.SampleInterval)+ history, cacheHit := prepareMockMetricsHistory(+ graph,+ fixtureRevision,+ time.Now(),+ seedDuration,+ cfg.SampleInterval,+ maxPoints,+ storeSink,+ )+ m.mu.Lock()+ m.metricsHistory = history+ m.mu.Unlock()+ if cacheHit {+ log.Info().Msg("Mock metrics sampler: reused cached historical seed")+ }m.invalidateMockChartCaches()m.prewarmMockDashboardChartCaches()diff --git a/internal/monitoring/mock_metrics_seed_cache_test.go b/internal/monitoring/mock_metrics_seed_cache_test.gonew file mode 100644index 0000000000..b5cb40a4b2--- /dev/null+++ b/internal/monitoring/mock_metrics_seed_cache_test.go@@ -0,0 +1,99 @@+package monitoring++import (+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func resetMockMetricsSeedCacheForTest(t *testing.T) {+ t.Helper()+ mockMetricsSeedCache.Lock()+ previousKey := mockMetricsSeedCache.key+ previousHistory := mockMetricsSeedCache.history+ mockMetricsSeedCache.key = mockMetricsSeedCacheKey{}+ mockMetricsSeedCache.history = nil+ mockMetricsSeedCache.Unlock()+ t.Cleanup(func() {+ mockMetricsSeedCache.Lock()+ mockMetricsSeedCache.key = previousKey+ mockMetricsSeedCache.history = previousHistory+ mockMetricsSeedCache.Unlock()+ })+}++func TestPrepareMockMetricsHistoryReusesRevisionSeedWithIndependentHistories(t *testing.T) {+ resetMockMetricsSeedCacheForTest(t)++ now := time.Now().UTC().Truncate(time.Minute)+ const (+ fixtureRevision = uint64(41)+ seedDuration = time.Hour+ sampleInterval = time.Minute+ maxDataPoints = 3500+ )+ graph := fixtureGraphWithState(models.StateSnapshot{+ VMs: []models.VM{+ {+ ID: "vm-cache",+ Status: "running",+ CPU: 0.42,+ Memory: models.Memory{Usage: 55, Total: 1024},+ Disk: models.Disk{Usage: 61, Total: 1024, Used: 625},+ },+ },+ })++ first, firstCacheHit := prepareMockMetricsHistory(+ graph,+ fixtureRevision,+ now,+ seedDuration,+ sampleInterval,+ maxDataPoints,+ nil,+ )+ if firstCacheHit {+ t.Fatal("first seed unexpectedly reported a cache hit")+ }+ second, secondCacheHit := prepareMockMetricsHistory(+ graph,+ fixtureRevision,+ now,+ seedDuration,+ sampleInterval,+ maxDataPoints,+ nil,+ )+ if !secondCacheHit {+ t.Fatal("second seed did not reuse the matching fixture revision")+ }+ if first == second {+ t.Fatal("cached seed returned shared mutable MetricsHistory pointers")+ }++ firstCPU := first.GetGuestMetrics("vm-cache", "cpu", seedDuration)+ secondCPU := second.GetGuestMetrics("vm-cache", "cpu", seedDuration)+ if len(firstCPU) == 0 || len(firstCPU) != len(secondCPU) {+ t.Fatalf("cached seed coverage mismatch: first=%d second=%d", len(firstCPU), len(secondCPU))+ }++ first.AddGuestMetric("vm-cache", "cpu", 99, now.Add(sampleInterval))+ if got := len(second.GetGuestMetrics("vm-cache", "cpu", seedDuration)); got != len(secondCPU) {+ t.Fatalf("mutating one tenant history changed cached sibling coverage: got=%d want=%d", got, len(secondCPU))+ }++ _, revisionCacheHit := prepareMockMetricsHistory(+ graph,+ fixtureRevision+1,+ now,+ seedDuration,+ sampleInterval,+ maxDataPoints,+ nil,+ )+ if revisionCacheHit {+ t.Fatal("new fixture revision reused a stale seed")+ }+}