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.

Dedupe monitoring pollers behind shared provider, lifecycle, and seeding helpers

rcourtmanb855b21c7fd0
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 9a7802d8b1..cc27c6a46a 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -73,6 +73,7 @@ truth for live infrastructure data.
49. `internal/models/ceph_cluster_identity.go`
50. `internal/truenas/types.go`
51. `internal/monitoring/monitor_alert_sync.go`
+52. `internal/monitoring/platform_poller_shared.go`
## Shared Boundaries
@@ -81,6 +82,25 @@ truth for live infrastructure data.
## Extension Points
1. Add pollers/providers and discovery-provider coordination through `internal/monitoring/poll_providers.go` and `internal/monitoring/monitor_discovery_helpers.go`
+ The PVE/PBS/PMG providers share one wiring layer inside
+ `internal/monitoring/poll_providers.go`: instance listing, instance
+ description, and connection-status publication go through the generic
+ `sortedClientNames` / `describeProviderInstances` /
+ `providerConnectionStatuses` helpers, and the prefixed PBS/PMG providers
+ are built by `newPrefixedPollProvider` from a `prefixedPollProviderSpec`.
+ New scheduler-backed platform providers extend those helpers instead of
+ re-rolling per-platform copies of the same loops.
+ Periodic out-of-scheduler platform pollers (TrueNAS, VMware) share their
+ lifecycle and config-resolution scaffold through
+ `internal/monitoring/platform_poller_shared.go`: `startPollerLoop` owns
+ the double-start guard, stopped-channel handshake, and sync+poll cadence,
+ and `loadActiveInstanceConfigs` owns the "enabled instances keyed by
+ trimmed connection ID with defaults applied" active-connection policy. A
+ new platform poller of this family must reuse both rather than copying
+ the TrueNAS/VMware loop, and traditional PVE guest polling records
+ per-guest series through the canonical `recordGuestMetric` helper in
+ `internal/monitoring/monitor_pve_guest_helpers.go` instead of inline
+ metric writes.
2. Add metrics capture or history-retention behavior through `internal/monitoring/metrics.go` and `internal/monitoring/metrics_history.go`
3. Add typed read access through `internal/unifiedresources/views.go`
4. Add unified supplemental ingest through `internal/monitoring/poll_providers.go`
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index a885291251..dcbea8d382 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -1728,14 +1728,14 @@ func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {
file: "monitor_polling_vm.go",
snippets: []string{
"if !shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsStore.Write("vm", vm.ID, "cpu", vm.CPU*100, now)`,
+ `m.recordGuestMetric("vm", vm.ID, vm.CPU*100, vm.Memory.Usage, vm.Disk.Usage, -1, -1, -1, -1, now)`,
},
},
{
file: "monitor_polling_containers.go",
snippets: []string{
"if !shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsStore.Write("container", ct.ID, "cpu", ct.CPU*100, now)`,
+ `m.recordGuestMetric("container", ct.ID, ct.CPU*100, ct.Memory.Usage, ct.Disk.Usage, -1, -1, -1, -1, now)`,
},
},
{
diff --git a/internal/monitoring/memory_source_catalog_test.go b/internal/monitoring/memory_source_catalog_test.go
index c41df929d0..d138d0db3d 100644
--- a/internal/monitoring/memory_source_catalog_test.go
+++ b/internal/monitoring/memory_source_catalog_test.go
@@ -138,8 +138,7 @@ func TestMockVMPollingDefersMemoryHistoryToCanonicalSampler(t *testing.T) {
requiredSnippets := []string{
"if !shouldSkipNativeMockStateMetricWrites() {",
- `m.metricsHistory.AddGuestMetric(vm.ID, "memory", vm.Memory.Usage, now)`,
- `m.metricsStore.Write("vm", vm.ID, "memory", vm.Memory.Usage, now)`,
+ `m.recordGuestMetric("vm", vm.ID, vm.CPU*100, vm.Memory.Usage, vm.Disk.Usage, -1, -1, -1, -1, now)`,
}
for _, snippet := range requiredSnippets {
if !strings.Contains(source, snippet) {
diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.go
index 836d86c0b7..117ef3e8d7 100644
--- a/internal/monitoring/mock_metrics_history.go
+++ b/internal/monitoring/mock_metrics_history.go
@@ -679,16 +679,10 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
recordStorageTimeline(storage.ID, total)
}
- log.Debug().Int("count", len(state.PhysicalDisks)).Msg("mock seeding: processing physical disks")
- for _, disk := range state.PhysicalDisks {
- if disk.Temperature <= 0 {
- continue
- }
- resourceID := diskMetricsResourceID(disk)
- if resourceID == "" {
- continue
- }
-
+ // seedDiskTelemetry seeds the canonical smart_temp/busy/read/write disk
+ // series for one physical disk, shared by the native and TrueNAS fixture
+ // disk loops below.
+ seedDiskTelemetry := func(resourceID string) {
tempSeries := canonicalMetricSeries("disk", resourceID, "smart_temp", seedTimestamps)
busySeries := canonicalMetricSeries("disk", resourceID, "disk", seedTimestamps)
diskReadSeries := canonicalMetricSeries("disk", resourceID, "diskread", seedTimestamps)
@@ -704,7 +698,18 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
queueMetric("disk", resourceID, "diskread", diskReadSeries[i], ts)
queueMetric("disk", resourceID, "diskwrite", diskWriteSeries[i], ts)
}
+ }
+ log.Debug().Int("count", len(state.PhysicalDisks)).Msg("mock seeding: processing physical disks")
+ for _, disk := range state.PhysicalDisks {
+ if disk.Temperature <= 0 {
+ continue
+ }
+ resourceID := diskMetricsResourceID(disk)
+ if resourceID == "" {
+ continue
+ }
+ seedDiskTelemetry(resourceID)
}
log.Debug().Int("count", len(state.CephClusters)).Msg("mock seeding: processing ceph clusters")
@@ -821,22 +826,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
if resourceID == "" {
continue
}
-
- tempSeries := canonicalMetricSeries("disk", resourceID, "smart_temp", seedTimestamps)
- busySeries := canonicalMetricSeries("disk", resourceID, "disk", seedTimestamps)
- diskReadSeries := canonicalMetricSeries("disk", resourceID, "diskread", seedTimestamps)
- diskWriteSeries := canonicalMetricSeries("disk", resourceID, "diskwrite", seedTimestamps)
- for i := 0; i < numPoints; i++ {
- ts := seedTimestamps[i]
- mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)
- mh.AddDiskMetric(resourceID, "disk", busySeries[i], ts)
- mh.AddDiskMetric(resourceID, "diskread", diskReadSeries[i], ts)
- mh.AddDiskMetric(resourceID, "diskwrite", diskWriteSeries[i], ts)
- queueMetric("disk", resourceID, "smart_temp", tempSeries[i], ts)
- queueMetric("disk", resourceID, "disk", busySeries[i], ts)
- queueMetric("disk", resourceID, "diskread", diskReadSeries[i], ts)
- queueMetric("disk", resourceID, "diskwrite", diskWriteSeries[i], ts)
- }
+ seedDiskTelemetry(resourceID)
}
for _, app := range trueNASFixtures.Apps {
diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.go
index 0bdb83cda7..052072277d 100644
--- a/internal/monitoring/mock_metrics_history_test.go
+++ b/internal/monitoring/mock_metrics_history_test.go
@@ -1754,3 +1754,44 @@ func TestRecordMockStateToMetricsHistory_UsesCanonicalMetricModelForPlatformFixt
t.Fatalf("expected VMware datastore usage live tick to use canonical metric model: got=%f want=%f", got, want)
}
}
+
+func TestSeedMockMetricsHistory_DiskTelemetryParityAcrossNativeAndTrueNAS(t *testing.T) {
+ now := time.Now()
+ seedDuration := boundedMockHistoryProofWindow
+
+ state := models.StateSnapshot{
+ PhysicalDisks: []models.PhysicalDisk{
+ {
+ ID: "disk-parity",
+ Instance: "pve1",
+ Node: "node1",
+ DevPath: "/dev/nvme0n1",
+ Serial: "SERIAL-PARITY",
+ Temperature: 41,
+ },
+ },
+ }
+ fixtures := truenas.DefaultFixtures()
+ if len(fixtures.Disks) == 0 {
+ t.Fatal("expected canonical truenas disk fixtures")
+ }
+
+ mh := NewMetricsHistory(1000, seedDuration)
+ seedMockMetricsHistory(mh, nil, mock.FixtureGraph{
+ State: state,
+ PlatformFixtures: mock.PlatformFixtures{
+ TrueNAS: fixtures,
+ },
+ }, now, seedDuration, time.Minute)
+
+ // Native physical disks and TrueNAS fixture disks share one seeding
+ // helper, so both must carry the same four telemetry series.
+ for _, metric := range []string{"smart_temp", "disk", "diskread", "diskwrite"} {
+ if len(mh.GetDiskMetrics("SERIAL-PARITY", metric, seedDuration)) == 0 {
+ t.Fatalf("expected native disk %q series to be seeded", metric)
+ }
+ if len(mh.GetDiskMetrics(fixtures.Disks[0].Serial, metric, seedDuration)) == 0 {
+ t.Fatalf("expected TrueNAS disk %q series to be seeded", metric)
+ }
+ }
+}
diff --git a/internal/monitoring/monitor_polling_containers.go b/internal/monitoring/monitor_polling_containers.go
index 9924a6349d..b2b2a9c0f6 100644
--- a/internal/monitoring/monitor_polling_containers.go
+++ b/internal/monitoring/monitor_polling_containers.go
@@ -333,19 +333,9 @@ func (m *Monitor) pollContainersWithNodes(ctx context.Context, instanceName stri
if ct.Status != "running" {
continue
}
- m.metricsHistory.AddGuestMetric(ct.ID, "cpu", ct.CPU*100, now)
- m.metricsHistory.AddGuestMetric(ct.ID, "memory", ct.Memory.Usage, now)
- if ct.Disk.Usage >= 0 {
- m.metricsHistory.AddGuestMetric(ct.ID, "disk", ct.Disk.Usage, now)
- }
- // Also write to persistent store
- if m.metricsStore != nil {
- m.metricsStore.Write("container", ct.ID, "cpu", ct.CPU*100, now)
- m.metricsStore.Write("container", ct.ID, "memory", ct.Memory.Usage, now)
- if ct.Disk.Usage >= 0 {
- m.metricsStore.Write("container", ct.ID, "disk", ct.Disk.Usage, now)
- }
- }
+ // IO/network series are not recorded on the traditional polling
+ // path (parity with the historical inline writes).
+ m.recordGuestMetric("container", ct.ID, ct.CPU*100, ct.Memory.Usage, ct.Disk.Usage, -1, -1, -1, -1, now)
}
}
diff --git a/internal/monitoring/monitor_polling_vm.go b/internal/monitoring/monitor_polling_vm.go
index a77d101199..98af66aa98 100644
--- a/internal/monitoring/monitor_polling_vm.go
+++ b/internal/monitoring/monitor_polling_vm.go
@@ -121,18 +121,9 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu
if vm.Status != "running" {
continue
}
- m.metricsHistory.AddGuestMetric(vm.ID, "cpu", vm.CPU*100, now)
- m.metricsHistory.AddGuestMetric(vm.ID, "memory", vm.Memory.Usage, now)
- if vm.Disk.Usage >= 0 {
- m.metricsHistory.AddGuestMetric(vm.ID, "disk", vm.Disk.Usage, now)
- }
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", vm.ID, "cpu", vm.CPU*100, now)
- m.metricsStore.Write("vm", vm.ID, "memory", vm.Memory.Usage, now)
- if vm.Disk.Usage >= 0 {
- m.metricsStore.Write("vm", vm.ID, "disk", vm.Disk.Usage, now)
- }
- }
+ // IO/network series are not recorded on the traditional polling
+ // path (parity with the historical inline writes).
+ m.recordGuestMetric("vm", vm.ID, vm.CPU*100, vm.Memory.Usage, vm.Disk.Usage, -1, -1, -1, -1, now)
}
}
diff --git a/internal/monitoring/platform_poller_shared.go b/internal/monitoring/platform_poller_shared.go
new file mode 100644
index 0000000000..21f757891f
--- /dev/null
+++ b/internal/monitoring/platform_poller_shared.go
@@ -0,0 +1,115 @@
+package monitoring
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// startPollerLoop runs the scheduling scaffold shared by the periodic
+// platform pollers (TrueNAS, VMware): guard against double-start under mu,
+// then sync + poll immediately and again on every nextWaitDuration tick until
+// the context is cancelled. cancelSlot and stoppedSlot point at the poller's
+// lifecycle fields so Stop keeps working against the same state.
+func startPollerLoop(
+ ctx context.Context,
+ mu *sync.Mutex,
+ cancelSlot *context.CancelFunc,
+ stoppedSlot *chan struct{},
+ syncConnections func(),
+ pollAll func(context.Context),
+ nextWaitDuration func(time.Time) time.Duration,
+) {
+ if ctx == nil {
+ ctx = context.Background()
+ }
+
+ mu.Lock()
+ if *cancelSlot != nil {
+ mu.Unlock()
+ return
+ }
+
+ runCtx, cancel := context.WithCancel(ctx)
+ *cancelSlot = cancel
+ *stoppedSlot = make(chan struct{})
+ stopped := *stoppedSlot
+ mu.Unlock()
+
+ go func() {
+ defer close(stopped)
+ defer func() {
+ mu.Lock()
+ if *stoppedSlot == stopped {
+ *cancelSlot = nil
+ }
+ mu.Unlock()
+ }()
+
+ syncConnections()
+ pollAll(runCtx)
+ for {
+ wait := nextWaitDuration(time.Now())
+ timer := time.NewTimer(wait)
+ select {
+ case <-runCtx.Done():
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+ return
+ case <-timer.C:
+ syncConnections()
+ pollAll(runCtx)
+ }
+ }
+ }()
+}
+
+// loadActiveInstanceConfigs resolves the active platform connection configs
+// for an org: prefer the poller's cached map, otherwise load from per-org
+// persistence and keep enabled instances keyed by trimmed connection ID with
+// defaults applied. Shared by the TrueNAS and VMware pollers so the "what
+// counts as an active connection" policy stays single-sourced.
+func loadActiveInstanceConfigs[T any](
+ cached map[string]T,
+ multiTenant *config.MultiTenantPersistence,
+ orgID string,
+ load func(*config.ConfigPersistence) ([]T, error),
+ applyDefaults func(*T),
+ enabled func(T) bool,
+ connID func(T) string,
+) map[string]T {
+ if len(cached) > 0 || multiTenant == nil {
+ return cached
+ }
+
+ persistence, err := multiTenant.GetPersistence(orgID)
+ if err != nil || persistence == nil {
+ return cached
+ }
+ instances, err := load(persistence)
+ if err != nil {
+ return cached
+ }
+
+ active := make(map[string]T)
+ for i := range instances {
+ instance := instances[i]
+ applyDefaults(&instance)
+ if !enabled(instance) {
+ continue
+ }
+ id := strings.TrimSpace(connID(instance))
+ if id == "" {
+ continue
+ }
+ active[id] = instance
+ }
+ return active
+}
diff --git a/internal/monitoring/poll_providers.go b/internal/monitoring/poll_providers.go
index 92c36fedfc..94ce1600f3 100644
--- a/internal/monitoring/poll_providers.go
+++ b/internal/monitoring/poll_providers.go
@@ -6,7 +6,10 @@ import (
"strings"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/pbs"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/pmg"
)
// PollProvider defines how a monitoring backend participates in scheduling and
@@ -123,111 +126,185 @@ func (p pollProviderAdapter) BuildPollTask(m *Monitor, instanceName string) (Pol
return p.buildPollTask(m, instanceName)
}
+// pollProviderInstanceConfig is one configured instance entry (name + host)
+// independent of the per-platform config struct type.
+type pollProviderInstanceConfig struct {
+ Name string
+ Host string
+}
+
+// sortedClientNames returns the sorted key set of a provider client map read
+// under the monitor lock.
+func sortedClientNames[C any](m *Monitor, clientsOf func(*Monitor) map[string]C) []string {
+ if m == nil {
+ return nil
+ }
+ m.mu.RLock()
+ clients := clientsOf(m)
+ names := make([]string, 0, len(clients))
+ for name := range clients {
+ names = append(names, name)
+ }
+ m.mu.RUnlock()
+ sort.Strings(names)
+ return names
+}
+
+// describeProviderInstances merges configured instances with live client map
+// entries into the sorted instance info list shared by the PVE/PBS/PMG
+// providers. configInstances and clientsOf are invoked under the monitor lock.
+func describeProviderInstances[C any](
+ m *Monitor,
+ fallbackName string,
+ configInstances func(*Monitor) []pollProviderInstanceConfig,
+ clientsOf func(*Monitor) map[string]C,
+) []PollProviderInstanceInfo {
+ if m == nil {
+ return nil
+ }
+
+ byName := make(map[string]PollProviderInstanceInfo)
+ m.mu.RLock()
+ for _, inst := range configInstances(m) {
+ name := strings.TrimSpace(inst.Name)
+ if name == "" {
+ name = strings.TrimSpace(inst.Host)
+ }
+ if name == "" {
+ name = fallbackName
+ }
+
+ display := strings.TrimSpace(inst.Name)
+ if display == "" {
+ display = name
+ }
+ connection := strings.TrimSpace(inst.Host)
+ byName[name] = PollProviderInstanceInfo{
+ Name: name,
+ DisplayName: display,
+ Connection: connection,
+ }
+ }
+ for name := range clientsOf(m) {
+ trimmed := strings.TrimSpace(name)
+ if trimmed == "" {
+ continue
+ }
+ if _, exists := byName[trimmed]; exists {
+ continue
+ }
+ byName[trimmed] = PollProviderInstanceInfo{Name: trimmed, DisplayName: trimmed}
+ }
+ m.mu.RUnlock()
+
+ if len(byName) == 0 {
+ return nil
+ }
+ names := make([]string, 0, len(byName))
+ for name := range byName {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ infos := make([]PollProviderInstanceInfo, 0, len(names))
+ for _, name := range names {
+ infos = append(infos, byName[name])
+ }
+ return infos
+}
+
+// providerConnectionStatuses publishes per-instance connection booleans keyed
+// by "<keyPrefix><name>" for configured instances, shared by the PVE/PBS/PMG
+// providers. configInstances and clientsOf are invoked under the monitor lock.
+func providerConnectionStatuses[C comparable](
+ m *Monitor,
+ instanceType InstanceType,
+ keyPrefix string,
+ configInstances func(*Monitor) []pollProviderInstanceConfig,
+ clientsOf func(*Monitor) map[string]C,
+) map[string]bool {
+ if m == nil {
+ return nil
+ }
+
+ var zero C
+ statuses := make(map[string]bool)
+ m.mu.RLock()
+ clients := clientsOf(m)
+ for _, inst := range configInstances(m) {
+ name := strings.TrimSpace(inst.Name)
+ if name == "" {
+ name = strings.TrimSpace(inst.Host)
+ }
+ if name == "" {
+ continue
+ }
+ key := keyPrefix + name
+ connected := false
+ if client, exists := clients[name]; exists && client != zero {
+ if m.state != nil && m.state.ConnectionHealth != nil {
+ stateKey := m.connectionHealthStateKey(instanceType, name)
+ connected = m.state.ConnectionHealth[stateKey]
+ } else {
+ connected = true
+ }
+ }
+ statuses[key] = connected
+ }
+ m.mu.RUnlock()
+ if len(statuses) == 0 {
+ return nil
+ }
+ return statuses
+}
+
+func pveInstanceConfigs(m *Monitor) []pollProviderInstanceConfig {
+ if m.config == nil {
+ return nil
+ }
+ out := make([]pollProviderInstanceConfig, 0, len(m.config.PVEInstances))
+ for _, inst := range m.config.PVEInstances {
+ out = append(out, pollProviderInstanceConfig{Name: inst.Name, Host: inst.Host})
+ }
+ return out
+}
+
+func pbsInstanceConfigs(m *Monitor) []pollProviderInstanceConfig {
+ if m.config == nil {
+ return nil
+ }
+ out := make([]pollProviderInstanceConfig, 0, len(m.config.PBSInstances))
+ for _, inst := range m.config.PBSInstances {
+ out = append(out, pollProviderInstanceConfig{Name: inst.Name, Host: inst.Host})
+ }
+ return out
+}
+
+func pmgInstanceConfigs(m *Monitor) []pollProviderInstanceConfig {
+ if m.config == nil {
+ return nil
+ }
+ out := make([]pollProviderInstanceConfig, 0, len(m.config.PMGInstances))
+ for _, inst := range m.config.PMGInstances {
+ out = append(out, pollProviderInstanceConfig{Name: inst.Name, Host: inst.Host})
+ }
+ return out
+}
+
+func pveClientMap(m *Monitor) map[string]PVEClientInterface { return m.pveClients }
+func pbsClientMap(m *Monitor) map[string]*pbs.Client { return m.pbsClients }
+func pmgClientMap(m *Monitor) map[string]*pmg.Client { return m.pmgClients }
+
func newPVEPollProvider() PollProvider {
return pollProviderAdapter{
instanceType: InstanceTypePVE,
listInstances: func(m *Monitor) []string {
- if m == nil {
- return nil
- }
- m.mu.RLock()
- names := make([]string, 0, len(m.pveClients))
- for name := range m.pveClients {
- names = append(names, name)
- }
- m.mu.RUnlock()
- sort.Strings(names)
- return names
+ return sortedClientNames(m, pveClientMap)
},
describeInstances: func(m *Monitor) []PollProviderInstanceInfo {
- if m == nil {
- return nil
- }
-
- byName := make(map[string]PollProviderInstanceInfo)
- m.mu.RLock()
- if m.config != nil {
- for _, inst := range m.config.PVEInstances {
- name := strings.TrimSpace(inst.Name)
- if name == "" {
- name = strings.TrimSpace(inst.Host)
- }
- if name == "" {
- name = "pve-instance"
- }
-
- display := strings.TrimSpace(inst.Name)
- if display == "" {
- display = name
- }
- connection := strings.TrimSpace(inst.Host)
- byName[name] = PollProviderInstanceInfo{
- Name: name,
- DisplayName: display,
- Connection: connection,
- }
- }
- }
- for name := range m.pveClients {
- trimmed := strings.TrimSpace(name)
- if trimmed == "" {
- continue
- }
- if _, exists := byName[trimmed]; exists {
- continue
- }
- byName[trimmed] = PollProviderInstanceInfo{Name: trimmed, DisplayName: trimmed}
- }
- m.mu.RUnlock()
-
- if len(byName) == 0 {
- return nil
- }
- names := make([]string, 0, len(byName))
- for name := range byName {
- names = append(names, name)
- }
- sort.Strings(names)
- infos := make([]PollProviderInstanceInfo, 0, len(names))
- for _, name := range names {
- infos = append(infos, byName[name])
- }
- return infos
+ return describeProviderInstances(m, "pve-instance", pveInstanceConfigs, pveClientMap)
},
connectionStatus: func(m *Monitor) map[string]bool {
- if m == nil {
- return nil
- }
-
- statuses := make(map[string]bool)
- m.mu.RLock()
- if m.config != nil {
- for _, inst := range m.config.PVEInstances {
- name := strings.TrimSpace(inst.Name)
- if name == "" {
- name = strings.TrimSpace(inst.Host)
- }
- if name == "" {
- continue
- }
- key := "pve-" + name
- connected := false
- if client, exists := m.pveClients[name]; exists && client != nil {
- if m.state != nil && m.state.ConnectionHealth != nil {
- stateKey := m.connectionHealthStateKey(InstanceTypePVE, name)
- connected = m.state.ConnectionHealth[stateKey]
- } else {
- connected = true
- }
- }
- statuses[key] = connected
- }
- }
- m.mu.RUnlock()
- if len(statuses) == 0 {
- return nil
- }
- return statuses
+ return providerConnectionStatuses(m, InstanceTypePVE, "pve-", pveInstanceConfigs, pveClientMap)
},
connectionKey: func(_ *Monitor, instanceName string) string {
return strings.TrimSpace(instanceName)
@@ -255,125 +332,55 @@ func newPVEPollProvider() PollProvider {
}
}
-func newPBSPollProvider() PollProvider {
+// prefixedPollProviderSpec captures the bits that differ between the PBS and
+// PMG providers, which otherwise share the full adapter wiring. prefix
+// ("pbs-", "pmg-") namespaces connection status keys and connection health
+// keys, and derives the "<prefix>instance" fallback display name.
+type prefixedPollProviderSpec[C comparable] struct {
+ instanceType InstanceType
+ prefix string
+ configInstances func(*Monitor) []pollProviderInstanceConfig
+ clients func(*Monitor) map[string]C
+ pollingInterval func(*config.Config) time.Duration
+ buildPollTask func(*Monitor, string) (PollTask, error)
+}
+
+func newPrefixedPollProvider[C comparable](spec prefixedPollProviderSpec[C]) PollProvider {
return pollProviderAdapter{
- instanceType: InstanceTypePBS,
+ instanceType: spec.instanceType,
listInstances: func(m *Monitor) []string {
- if m == nil {
- return nil
- }
- m.mu.RLock()
- names := make([]string, 0, len(m.pbsClients))
- for name := range m.pbsClients {
- names = append(names, name)
- }
- m.mu.RUnlock()
- sort.Strings(names)
- return names
+ return sortedClientNames(m, spec.clients)
},
describeInstances: func(m *Monitor) []PollProviderInstanceInfo {
- if m == nil {
- return nil
- }
-
- byName := make(map[string]PollProviderInstanceInfo)
- m.mu.RLock()
- if m.config != nil {
- for _, inst := range m.config.PBSInstances {
- name := strings.TrimSpace(inst.Name)
- if name == "" {
- name = strings.TrimSpace(inst.Host)
- }
- if name == "" {
- name = "pbs-instance"
- }
-
- display := strings.TrimSpace(inst.Name)
- if display == "" {
- display = name
- }
- connection := strings.TrimSpace(inst.Host)
- byName[name] = PollProviderInstanceInfo{
- Name: name,
- DisplayName: display,
- Connection: connection,
- }
- }
- }
- for name := range m.pbsClients {
- trimmed := strings.TrimSpace(name)
- if trimmed == "" {
- continue
- }
- if _, exists := byName[trimmed]; exists {
- continue
- }
- byName[trimmed] = PollProviderInstanceInfo{Name: trimmed, DisplayName: trimmed}
- }
- m.mu.RUnlock()
-
- if len(byName) == 0 {
- return nil
- }
- names := make([]string, 0, len(byName))
- for name := range byName {
- names = append(names, name)
- }
- sort.Strings(names)
- infos := make([]PollProviderInstanceInfo, 0, len(names))
- for _, name := range names {
- infos = append(infos, byName[name])
- }
- return infos
+ return describeProviderInstances(m, spec.prefix+"instance", spec.configInstances, spec.clients)
},
connectionStatus: func(m *Monitor) map[string]bool {
- if m == nil {
- return nil
- }
-
- statuses := make(map[string]bool)
- m.mu.RLock()
- if m.config != nil {
- for _, inst := range m.config.PBSInstances {
- name := strings.TrimSpace(inst.Name)
- if name == "" {
- name = strings.TrimSpace(inst.Host)
- }
- if name == "" {
- continue
- }
- key := "pbs-" + name
- connected := false
- if client, exists := m.pbsClients[name]; exists && client != nil {
- if m.state != nil && m.state.ConnectionHealth != nil {
- stateKey := m.connectionHealthStateKey(InstanceTypePBS, name)
- connected = m.state.ConnectionHealth[stateKey]
- } else {
- connected = true
- }
- }
- statuses[key] = connected
- }
- }
- m.mu.RUnlock()
- if len(statuses) == 0 {
- return nil
- }
- return statuses
+ return providerConnectionStatuses(m, spec.instanceType, spec.prefix, spec.configInstances, spec.clients)
},
connectionKey: func(_ *Monitor, instanceName string) string {
trimmed := strings.TrimSpace(instanceName)
if trimmed == "" {
return ""
}
- return "pbs-" + trimmed
+ return spec.prefix + trimmed
},
baseInterval: func(m *Monitor) time.Duration {
if m == nil || m.config == nil {
return 0
}
- return clampInterval(m.config.PBSPollingInterval, 10*time.Second, time.Hour)
+ return clampInterval(spec.pollingInterval(m.config), 10*time.Second, time.Hour)
},
+ buildPollTask: spec.buildPollTask,
+ }
+}
+
+func newPBSPollProvider() PollProvider {
+ return newPrefixedPollProvider(prefixedPollProviderSpec[*pbs.Client]{
+ instanceType: InstanceTypePBS,
+ prefix: "pbs-",
+ configInstances: pbsInstanceConfigs,
+ clients: pbsClientMap,
+ pollingInterval: func(cfg *config.Config) time.Duration { return cfg.PBSPollingInterval },
buildPollTask: func(m *Monitor, instanceName string) (PollTask, error) {
if m == nil {
return PollTask{}, fmt.Errorf("monitor is nil")
@@ -388,128 +395,16 @@ func newPBSPollProvider() PollProvider {
PBSClient: client,
}, nil
},
- }
+ })
}
func newPMGPollProvider() PollProvider {
- return pollProviderAdapter{
- instanceType: InstanceTypePMG,
- listInstances: func(m *Monitor) []string {
- if m == nil {
- return nil
- }
- m.mu.RLock()
- names := make([]string, 0, len(m.pmgClients))
- for name := range m.pmgClients {
- names = append(names, name)
- }
- m.mu.RUnlock()
- sort.Strings(names)
- return names
- },
- describeInstances: func(m *Monitor) []PollProviderInstanceInfo {
- if m == nil {
- return nil
- }
-
- byName := make(map[string]PollProviderInstanceInfo)
- m.mu.RLock()
- if m.config != nil {
- for _, inst := range m.config.PMGInstances {
- name := strings.TrimSpace(inst.Name)
- if name == "" {
- name = strings.TrimSpace(inst.Host)
- }
- if name == "" {
- name = "pmg-instance"
- }
-
- display := strings.TrimSpace(inst.Name)
- if display == "" {
- display = name
- }
- connection := strings.TrimSpace(inst.Host)
- byName[name] = PollProviderInstanceInfo{
- Name: name,
- DisplayName: display,
- Connection: connection,
- }
- }
- }
- for name := range m.pmgClients {
- trimmed := strings.TrimSpace(name)
- if trimmed == "" {
- continue
- }
- if _, exists := byName[trimmed]; exists {
- continue
- }
- byName[trimmed] = PollProviderInstanceInfo{Name: trimmed, DisplayName: trimmed}
- }
- m.mu.RUnlock()
-
- if len(byName) == 0 {
- return nil
- }
- names := make([]string, 0, len(byName))
- for name := range byName {
- names = append(names, name)
- }
- sort.Strings(names)
- infos := make([]PollProviderInstanceInfo, 0, len(names))
- for _, name := range names {
- infos = append(infos, byName[name])
- }
- return infos
- },
- connectionStatus: func(m *Monitor) map[string]bool {
- if m == nil {
- return nil
- }
-
- statuses := make(map[string]bool)
- m.mu.RLock()
- if m.config != nil {
- for _, inst := range m.config.PMGInstances {
- name := strings.TrimSpace(inst.Name)
- if name == "" {
- name = strings.TrimSpace(inst.Host)
- }
- if name == "" {
- continue
- }
- key := "pmg-" + name
- connected := false
- if client, exists := m.pmgClients[name]; exists && client != nil {
- if m.state != nil && m.state.ConnectionHealth != nil {
- stateKey := m.connectionHealthStateKey(InstanceTypePMG, name)
- connected = m.state.ConnectionHealth[stateKey]
- } else {
- connected = true
- }
- }
- statuses[key] = connected
- }
- }
- m.mu.RUnlock()
- if len(statuses) == 0 {
- return nil
- }
- return statuses
- },
- connectionKey: func(_ *Monitor, instanceName string) string {
- trimmed := strings.TrimSpace(instanceName)
- if trimmed == "" {
- return ""
- }
- return "pmg-" + trimmed
- },
- baseInterval: func(m *Monitor) time.Duration {
- if m == nil || m.config == nil {
- return 0
- }
- return clampInterval(m.config.PMGPollingInterval, 10*time.Second, time.Hour)
- },
+ return newPrefixedPollProvider(prefixedPollProviderSpec[*pmg.Client]{
+ instanceType: InstanceTypePMG,
+ prefix: "pmg-",
+ configInstances: pmgInstanceConfigs,
+ clients: pmgClientMap,
+ pollingInterval: func(cfg *config.Config) time.Duration { return cfg.PMGPollingInterval },
buildPollTask: func(m *Monitor, instanceName string) (PollTask, error) {
if m == nil {
return PollTask{}, fmt.Errorf("monitor is nil")
@@ -524,7 +419,7 @@ func newPMGPollProvider() PollProvider {
PMGClient: client,
}, nil
},
- }
+ })
}
// RegisterPollProvider registers or replaces a polling provider for an
diff --git a/internal/monitoring/truenas_poller.go b/internal/monitoring/truenas_poller.go
index e0bd2b5609..19d3c91733 100644
--- a/internal/monitoring/truenas_poller.go
+++ b/internal/monitoring/truenas_poller.go
@@ -127,52 +127,7 @@ func (p *TrueNASPoller) Start(ctx context.Context) {
if p == nil || !truenas.IsFeatureEnabled() {
return
}
- if ctx == nil {
- ctx = context.Background()
- }
-
- p.mu.Lock()
- if p.cancel != nil {
- p.mu.Unlock()
- return
- }
-
- runCtx, cancel := context.WithCancel(ctx)
- p.cancel = cancel
- p.stopped = make(chan struct{})
- stopped := p.stopped
- p.mu.Unlock()
-
- go func() {
- defer close(stopped)
- defer func() {
- p.mu.Lock()
- if p.stopped == stopped {
- p.cancel = nil
- }
- p.mu.Unlock()
- }()
-
- p.syncConnections()
- p.pollAll(runCtx)
- for {
- wait := p.nextWaitDuration(time.Now())
- timer := time.NewTimer(wait)
- select {
- case <-runCtx.Done():
- if !timer.Stop() {
- select {
- case <-timer.C:
- default:
- }
- }
- return
- case <-timer.C:
- p.syncConnections()
- p.pollAll(runCtx)
- }
- }
- }()
+ startPollerLoop(ctx, &p.mu, &p.cancel, &p.stopped, p.syncConnections, p.pollAll, p.nextWaitDuration)
}
// Stop requests poller shutdown and waits up to five seconds for exit.
@@ -1090,33 +1045,15 @@ func (p *TrueNASPoller) activeConnectionConfigsForOrg(orgID string) map[string]c
p.mu.Lock()
cached := cloneTrueNASConnectionConfigMap(p.configsByOrg[orgID])
p.mu.Unlock()
- if len(cached) > 0 || p.multiTenant == nil {
- return cached
- }
-
- persistence, err := p.multiTenant.GetPersistence(orgID)
- if err != nil || persistence == nil {
- return cached
- }
- instances, err := persistence.LoadTrueNASConfig()
- if err != nil {
- return cached
- }
-
- active := make(map[string]config.TrueNASInstance)
- for i := range instances {
- instance := instances[i]
- instance.ApplyDefaults()
- if !instance.Enabled {
- continue
- }
- connID := strings.TrimSpace(instance.ID)
- if connID == "" {
- continue
- }
- active[connID] = instance
- }
- return active
+ return loadActiveInstanceConfigs(
+ cached,
+ p.multiTenant,
+ orgID,
+ (*config.ConfigPersistence).LoadTrueNASConfig,
+ func(instance *config.TrueNASInstance) { instance.ApplyDefaults() },
+ func(instance config.TrueNASInstance) bool { return instance.Enabled },
+ func(instance config.TrueNASInstance) string { return instance.ID },
+ )
}
func cloneTrueNASConnectionConfigMap(
diff --git a/internal/monitoring/truenas_poller_test.go b/internal/monitoring/truenas_poller_test.go
index 087f230388..f3e508248f 100644
--- a/internal/monitoring/truenas_poller_test.go
+++ b/internal/monitoring/truenas_poller_test.go
@@ -1764,3 +1764,56 @@ type failingTrueNASFetcher struct {
func (f failingTrueNASFetcher) Fetch(context.Context) (*truenas.FixtureSnapshot, error) {
return nil, f.err
}
+
+func TestTrueNASPollerDoubleStartKeepsSingleLoop(t *testing.T) {
+ previous := truenas.IsFeatureEnabled()
+ truenas.SetFeatureEnabled(true)
+ t.Cleanup(func() { truenas.SetFeatureEnabled(previous) })
+
+ mock := newTrueNASMockServer(t, "nas-double-start")
+ t.Cleanup(mock.Close)
+
+ mtp, persistence := newTestTenantPersistence(t)
+ connection := trueNASInstanceForServer(t, "double-start-conn", mock.URL(), true)
+ if err := persistence.SaveTrueNASConfig([]config.TrueNASInstance{connection}); err != nil {
+ t.Fatalf("SaveTrueNASConfig() error = %v", err)
+ }
+
+ poller := NewTrueNASPoller(mtp, 50*time.Millisecond, nil)
+ poller.Start(context.Background())
+ t.Cleanup(poller.Stop)
+
+ poller.mu.Lock()
+ firstStopped := poller.stopped
+ poller.mu.Unlock()
+ if firstStopped == nil {
+ t.Fatal("expected Start() to install a poller loop")
+ }
+
+ // A second Start while the first loop is live must be a no-op: the
+ // lifecycle slots keep pointing at the original run.
+ poller.Start(context.Background())
+ poller.mu.Lock()
+ secondStopped := poller.stopped
+ poller.mu.Unlock()
+ if secondStopped != firstStopped {
+ t.Fatal("expected double Start() to keep the original poller loop")
+ }
+
+ // Stop must clear the cancel slot so a later Start can run a fresh loop.
+ poller.Stop()
+ poller.mu.Lock()
+ cancelAfterStop := poller.cancel
+ poller.mu.Unlock()
+ if cancelAfterStop != nil {
+ t.Fatal("expected Stop() to clear the lifecycle cancel slot")
+ }
+
+ poller.Start(context.Background())
+ poller.mu.Lock()
+ thirdStopped := poller.stopped
+ poller.mu.Unlock()
+ if thirdStopped == firstStopped {
+ t.Fatal("expected restart to install a fresh poller loop")
+ }
+}
diff --git a/internal/monitoring/vmware_poller.go b/internal/monitoring/vmware_poller.go
index 360b205aae..25dbf70e03 100644
--- a/internal/monitoring/vmware_poller.go
+++ b/internal/monitoring/vmware_poller.go
@@ -146,52 +146,7 @@ func (p *VMwarePoller) Start(ctx context.Context) {
if p == nil || !vmware.IsFeatureEnabled() {
return
}
- if ctx == nil {
- ctx = context.Background()
- }
-
- p.mu.Lock()
- if p.cancel != nil {
- p.mu.Unlock()
- return
- }
-
- runCtx, cancel := context.WithCancel(ctx)
- p.cancel = cancel
- p.stopped = make(chan struct{})
- stopped := p.stopped
- p.mu.Unlock()
-
- go func() {
- defer close(stopped)
- defer func() {
- p.mu.Lock()
- if p.stopped == stopped {
- p.cancel = nil
- }
- p.mu.Unlock()
- }()
-
- p.syncConnections()
- p.pollAll(runCtx)
- for {
- wait := p.nextWaitDuration(time.Now())
- timer := time.NewTimer(wait)
- select {
- case <-runCtx.Done():
- if !timer.Stop() {
- select {
- case <-timer.C:
- default:
- }
- }
- return
- case <-timer.C:
- p.syncConnections()
- p.pollAll(runCtx)
- }
- }
- }()
+ startPollerLoop(ctx, &p.mu, &p.cancel, &p.stopped, p.syncConnections, p.pollAll, p.nextWaitDuration)
}
// Stop requests poller shutdown and waits up to five seconds for exit.
@@ -666,33 +621,15 @@ func (p *VMwarePoller) activeConnectionConfigsForOrg(orgID string) map[string]co
p.mu.Lock()
cached := cloneVMwareConnectionConfigMap(p.configsByOrg[orgID])
p.mu.Unlock()
- if len(cached) > 0 || p.multiTenant == nil {
- return cached
- }
-
- persistence, err := p.multiTenant.GetPersistence(orgID)
- if err != nil || persistence == nil {
- return cached
- }
- instances, err := persistence.LoadVMwareConfig()
- if err != nil {
- return cached
- }
-
- active := make(map[string]config.VMwareVCenterInstance)
- for i := range instances {
- instance := instances[i]
- instance.ApplyDefaults()
- if !instance.Enabled {
- continue
- }
- connID := strings.TrimSpace(instance.ID)
- if connID == "" {
- continue
- }
- active[connID] = instance
- }
- return active
+ return loadActiveInstanceConfigs(
+ cached,
+ p.multiTenant,
+ orgID,
+ (*config.ConfigPersistence).LoadVMwareConfig,
+ func(instance *config.VMwareVCenterInstance) { instance.ApplyDefaults() },
+ func(instance config.VMwareVCenterInstance) bool { return instance.Enabled },
+ func(instance config.VMwareVCenterInstance) string { return instance.ID },
+ )
}
func cloneVMwareConnectionConfigMap(