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
Withdraw earlier TrueNAS history when batch ownership changes
pulse-triage[bot]964e47cfcf59
diff --git a/internal/api/truenas_history_batch_http_test.go b/internal/api/truenas_history_batch_http_test.gonew file mode 100644index 0000000000..ed5edbc509--- /dev/null+++ b/internal/api/truenas_history_batch_http_test.go@@ -0,0 +1,195 @@+package api++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "sync/atomic"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ "github.com/rcourtman/pulse-go-rewrite/internal/truenas"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++type batchHTTPHistoryFetcher struct {+ truenas.FixtureFetcher+ onRead func()+ points []truenas.TimeSeriesPoint+ reads atomic.Int32+}++func (f *batchHTTPHistoryFetcher) SystemMetricHistory(context.Context, time.Duration) (*truenas.SystemMetricHistory, error) {+ f.reads.Add(1)+ if f.onRead != nil {+ f.onRead()+ }+ return &truenas.SystemMetricHistory{CPUPercent: f.points}, nil+}++// Exercise the actual chart producer consumed by Machines. Inventory remains+// the last snapshot during the synthetic connection change; only the obsolete+// native history must withdraw. This is not installed removal or #2077 proof.+func TestTrueNASHistoryBatchHTTPWithdrawal(t *testing.T) {+ old := truenas.IsFeatureEnabled()+ truenas.SetFeatureEnabled(true)+ t.Cleanup(func() { truenas.SetFeatureEnabled(old) })+ oldMulti := IsMultiTenantEnabled()+ SetMultiTenantEnabled(true)+ t.Cleanup(func() { SetMultiTenantEnabled(oldMulti) })+ t.Setenv("PULSE_DEV", "true")+ now := time.Now().UTC().Truncate(time.Second)+ fetchers := map[string]*batchHTTPHistoryFetcher{}+ providers := map[string]*truenas.Provider{}+ records := map[string][]unifiedresources.IngestRecord{}+ for _, id := range []string{"batch-a", "batch-b"} {+ fixture := truenas.DefaultFixtures()+ fixture.System.Hostname = id+ fixture.CollectedAt = now+ fixture.Pools = nil+ fixture.Datasets = nil+ fixture.Disks = nil+ fixture.Alerts = nil+ fixture.Apps = nil+ fixture.VMs = nil+ fixture.Shares = nil+ fixture.Services = nil+ fixture.ZFSSnapshots = nil+ fixture.ReplicationTasks = nil+ points := []truenas.TimeSeriesPoint{{Timestamp: now.Add(-50 * time.Minute), Value: 11}, {Timestamp: now.Add(-25 * time.Minute), Value: 23}, {Timestamp: now.Add(-time.Minute), Value: 0}}+ if id == "batch-b" {+ points[0].Value = 37+ points[1].Value = 51+ points[2].Value = 19+ }+ f := &batchHTTPHistoryFetcher{FixtureFetcher: truenas.FixtureFetcher{Snapshot: fixture}, points: points}+ p := truenas.NewLiveProviderForConnection(f, id)+ if err := p.Refresh(context.Background()); err != nil {+ t.Fatal(err)+ }+ fetchers[id], providers[id], records[id] = f, p, p.Records()+ }+ poller := monitoring.NewTrueNASPoller(nil, time.Minute, nil)+ setUnexportedField(t, poller, "providersByOrg", map[string]map[string]*truenas.Provider{"org-batch": providers})+ setUnexportedField(t, poller, "cachedRecordsByOrg", map[string]map[string][]unifiedresources.IngestRecord{"org-batch": records})+ monitor := &monitoring.Monitor{}+ monitor.SetOrgID("org-batch")+ setUnexportedField(t, monitor, "state", models.NewState())+ setUnexportedField(t, monitor, "metricsHistory", monitoring.NewMetricsHistory(128, time.Hour))+ monitor.SetResourceStoreAndProviders(unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)), map[unifiedresources.DataSource]monitoring.MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: poller})+ // No local long-range history: the batch must exercise its native fallback.+ setUnexportedField(t, monitor, "metricsHistory", monitoring.NewMetricsHistory(128, time.Hour))+ const raw = "batch-reader.1234567890123456789"+ token := newTokenRecord(t, raw, []string{config.ScopeMonitoringRead}, nil)+ token.OrgID = "org-batch"+ cfg := newTestConfigWithTokens(t, token)+ cfg.AuthUser, cfg.AuthPass = "fixture-admin", "synthetic-unused-hash"+ if err := os.MkdirAll(filepath.Join(cfg.DataPath, "orgs", "org-batch"), 0700); err != nil {+ t.Fatal(err)+ }+ router := NewRouter(cfg, monitor, nil, nil, nil, "test")+ t.Cleanup(router.ShutdownBackgroundWorkers)+ t.Cleanup(router.ShutdownResourceStores)+ t.Cleanup(router.ShutdownRBAC)+ mtm := monitoring.NewMultiTenantMonitor(cfg, nil, nil)+ setUnexportedField(t, mtm, "monitors", map[string]*monitoring.Monitor{"org-batch": monitor})+ router.mtMonitor = mtm+ router.resourceHandlers.SetTenantStateProvider(NewMultiTenantStateProvider(mtm, monitor))+ router.setMonitorSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, poller)+ request := func(path, credential string) *httptest.ResponseRecorder {+ r := httptest.NewRequest(http.MethodGet, path, nil)+ r.Header.Set("X-Pulse-Org-ID", "org-batch")+ if credential != "" {+ r.Header.Set("X-API-Token", credential)+ }+ w := httptest.NewRecorder()+ router.Handler().ServeHTTP(w, r)+ return w+ }+ for _, path := range []string{"/api/charts?range=1h", "/api/charts/infrastructure?range=1h"} {+ if got := request(path, ""); got.Code != 401 {+ t.Fatalf("anonymous chart %d", got.Code)+ }+ }+ if fetchers["batch-a"].reads.Load() != 0 || fetchers["batch-b"].reads.Load() != 0 {+ t.Fatal("anonymous chart reached native history")+ }+ resources := request("/api/resources?type=agent&source=truenas&limit=100", raw)+ if resources.Code != 200 {+ t.Fatal(resources.Body.String())+ }+ t.Logf("BATCH_RESOURCES %s", resources.Body.String())+ type chartReply struct {+ AgentData map[string]map[string][]struct {+ Timestamp int64 `json:"timestamp"`+ Value float64 `json:"value"`+ } `json:"agentData"`+ }+ decode := func(w *httptest.ResponseRecorder) chartReply {+ var reply chartReply+ if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &reply) != nil {+ t.Fatalf("charts %d %s", w.Code, w.Body.String())+ }+ return reply+ }+ before := request("/api/charts?range=1h", raw)+ for id, series := range decode(before).AgentData {+ if len(series["cpu"]) != 3 {+ t.Fatalf("baseline native host %s: %+v", id, series)+ }+ }+ t.Logf("BATCH_BEFORE %s", before.Body.String())+ var calls int+ first := ""+ for _, id := range []string{"batch-a", "batch-b"} {+ id := id+ fetchers[id].onRead = func() {+ calls+++ if calls == 1 {+ first = id+ }+ if calls == 2 {+ delete(providers, first)+ }+ }+ }+ during := request("/api/charts/infrastructure?range=1h", raw)+ reply := decode(during)+ if calls != 2 || first == "" {+ t.Fatalf("batch did not read both native hosts: calls %d first %q", calls, first)+ }+ // Provider removal is synchronous inside the later read: no concurrent map+ // access or pointer mutation is needed to model the temporal ownership loss.+ for _, point := range reply.AgentData[first]["cpu"] {+ if point.Timestamp < now.Add(-2*time.Minute).UnixMilli() {+ t.Fatalf("withdrawn earlier native history escaped HTTP: %s", during.Body.String())+ }+ }+ survivor := "batch-a"+ if first == survivor {+ survivor = "batch-b"+ }+ if len(reply.AgentData[survivor]["cpu"]) != 3 {+ t.Fatalf("surviving native host lost history: %s", during.Body.String())+ }+ t.Logf("BATCH_WITHDRAWAL %s", during.Body.String())+ for _, f := range fetchers {+ f.onRead = nil+ }+ providers[first] = truenas.NewLiveProviderForConnection(fetchers[first], first)+ if err := providers[first].Refresh(context.Background()); err != nil {+ t.Fatal(err)+ }+ after := request("/api/charts?range=1h", raw)+ if len(decode(after).AgentData[first]["cpu"]) != 3 {+ t.Fatal("fresh replacement read did not recover native history")+ }+ t.Logf("BATCH_AFTER %s", after.Body.String())+ t.Logf("BATCH_IDENTITIES withdrawn=%s survivor=%s", first, survivor)+}diff --git a/internal/monitoring/truenas_history_batch_lifetime_test.go b/internal/monitoring/truenas_history_batch_lifetime_test.gonew file mode 100644index 0000000000..24921315fd--- /dev/null+++ b/internal/monitoring/truenas_history_batch_lifetime_test.go@@ -0,0 +1,145 @@+package monitoring++import (+ "context"+ "sync/atomic"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/truenas"+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++type batchLifetimeHistoryFetcher struct {+ truenas.FixtureFetcher+ onRead func(context.Context)+ value float64+}++func (f *batchLifetimeHistoryFetcher) SystemMetricHistory(ctx context.Context, _ time.Duration) (*truenas.SystemMetricHistory, error) {+ if f.onRead != nil {+ f.onRead(ctx)+ }+ return &truenas.SystemMetricHistory{CPUPercent: []truenas.TimeSeriesPoint{{Timestamp: time.Now().UTC().Add(-time.Minute), Value: f.value}}}, nil+}++// The provider map is deliberately unordered. Whichever connection is read+// first loses ownership while the second native read is outstanding. Checking+// each provider only when its own read finishes cannot fence the whole result.+func TestTrueNASHostHistoryBatchRechecksEarlierOwners(t *testing.T) {+ previous := truenas.IsFeatureEnabled()+ truenas.SetFeatureEnabled(true)+ t.Cleanup(func() { truenas.SetFeatureEnabled(previous) })+ for _, surface := range []string{"native", "chart-batch"} {+ for _, action := range []string{"remove", "replace", "disable"} {+ t.Run(surface+"/"+action, func(t *testing.T) {+ truenas.SetFeatureEnabled(true)+ poller := NewTrueNASPoller(nil, time.Minute, nil)+ fetchers := map[string]*batchLifetimeHistoryFetcher{}+ makeProvider := func(id string, value float64) *truenas.Provider {+ fixture := truenas.DefaultFixtures()+ fixture.System.Hostname = "namesake"+ f := &batchLifetimeHistoryFetcher{FixtureFetcher: truenas.FixtureFetcher{Snapshot: fixture}, value: value}+ p := truenas.NewLiveProviderForConnection(f, id)+ if err := p.Refresh(context.Background()); err != nil {+ t.Fatal(err)+ }+ fetchers[id] = f+ return p+ }+ poller.providersByOrg["org-current"] = map[string]*truenas.Provider{"a": makeProvider("a", 12), "b": makeProvider("b", 34)}+ replacement := makeProvider("replacement", 99)+ // A peer tenant with the same connection keys must never be selected or+ // removed as a side effect of withdrawing this tenant's result.+ other := makeProvider("other", 78)+ poller.providersByOrg["org-other"] = map[string]*truenas.Provider{"a": other}+ var calls atomic.Int32+ first := make(chan string, 1)+ entered := make(chan struct{})+ release := make(chan struct{})+ for _, id := range []string{"a", "b"} {+ id := id+ fetchers[id].onRead = func(ctx context.Context) {+ switch calls.Add(1) {+ case 1:+ first <- id+ case 2:+ close(entered)+ select {+ case <-release:+ case <-ctx.Done():+ }+ }+ }+ }+ monitor := &Monitor{metricsHistory: NewMetricsHistory(32, time.Hour), supplementalProviders: map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{unifiedresources.SourceTrueNAS: poller}}+ monitor.SetOrgID("org-current")+ read := func() map[string]map[string][]MetricPoint {+ if surface == "native" {+ return poller.GuestMetricHistory(nil, "org-current", "agent", time.Hour)+ }+ return monitor.GetGuestMetricsForChartBatch("agent", []GuestChartRequest{{InMemoryKey: "agent:a", SQLResourceID: "a"}, {InMemoryKey: "agent:b", SQLResourceID: "b"}}, time.Hour, "cpu")+ }+ done := make(chan map[string]map[string][]MetricPoint, 1)+ go func() { done <- read() }()+ select {+ case <-entered:+ case <-time.After(5 * time.Second):+ close(release)+ t.Fatal("second native read did not begin")+ }+ revoked := <-first+ survivor := "a"+ if revoked == survivor {+ survivor = "b"+ }+ poller.mu.Lock()+ switch action {+ case "remove":+ delete(poller.providersByOrg["org-current"], revoked)+ case "replace":+ poller.providersByOrg["org-current"][revoked] = replacement+ case "disable":+ truenas.SetFeatureEnabled(false)+ }+ poller.mu.Unlock()+ close(release)+ result := <-done+ if len(result[revoked]["cpu"]) != 0 {+ t.Fatalf("%s earlier connection retained native history after %s: %+v", revoked, action, result)+ }+ if action == "disable" {+ if len(result[survivor]["cpu"]) != 0 {+ t.Fatalf("disabled source retained later history: %+v", result)+ }+ } else if got := result[survivor]["cpu"]; len(got) != 1 || got[0].Value == 99 {+ t.Fatalf("surviving connection lost or borrowed history: %+v", result)+ }+ poller.mu.Lock()+ if poller.providersByOrg["org-other"]["a"] != other {+ t.Fatal("withdrawal changed peer tenant")+ }+ for _, id := range []string{"a", "b"} {+ fetchers[id].onRead = nil+ }+ if action == "remove" {+ poller.providersByOrg["org-current"][revoked] = replacement+ }+ poller.mu.Unlock()+ truenas.SetFeatureEnabled(true)+ fresh := read()+ // The replacement's own host identity is different: it is visible to a+ // native fleet read, never attached to the old chart target.+ if surface == "native" && action != "disable" {+ got := fresh["replacement"]["cpu"]+ if len(got) != 1 || got[0].Value != 99 {+ t.Fatalf("fresh native read did not recover replacement: %+v", fresh)+ }+ }+ if action == "disable" && len(fresh[survivor]["cpu"]) != 1 {+ t.Fatalf("fresh read after enable did not recover: %+v", fresh)+ }+ })+ }+ }+}diff --git a/internal/monitoring/truenas_poller.go b/internal/monitoring/truenas_poller.goindex 8ad2b55f40..f4e110d77e 100644--- a/internal/monitoring/truenas_poller.go+++ b/internal/monitoring/truenas_poller.go@@ -1107,6 +1107,7 @@ func (p *TrueNASPoller) guestMetricHistory(orgID, resourceType, selectedID strindefer cancel()history := make(map[string]map[string][]MetricPoint)+ owners := make(map[string]trueNASPollerProviderEntry)for _, entry := range entries {if selectedID != "" && entry.provider.SystemMetricResourceID() != selectedID {continue@@ -1153,7 +1154,17 @@ func (p *TrueNASPoller) guestMetricHistory(orgID, resourceType, selectedID strincontinue}history[resourceID] = converted+ owners[resourceID] = entry+ }+ // An earlier provider can lose ownership while a later native read is+ // outstanding. Fence the complete result, not just each individual read.+ p.mu.Lock()+ for resourceID, owner := range owners {+ if !truenas.IsFeatureEnabled() || p.providersByOrg[orgID][owner.connectionID] != owner.provider {+ delete(history, resourceID)+ }}+ p.mu.Unlock()if len(history) == 0 {return nil}