diff --git a/internal/models/metadata_snapshot.go b/internal/models/metadata_snapshot.go index 554ebb4bea..dbce721cb0 100644 --- a/internal/models/metadata_snapshot.go +++ b/internal/models/metadata_snapshot.go @@ -163,3 +163,12 @@ func (s *State) GetConnectionHealth() map[string]bool { } return health } + +// ConnectionHealthForClient reads the health of an existing connection client. +// Before the health map is initialized, client presence is the health signal. +// Once initialized, a missing entry is not evidence of a healthy connection. +func (s *State) ConnectionHealthForClient(instanceID string) bool { + s.mu.RLock() + defer s.mu.RUnlock() + return s.ConnectionHealth == nil || s.ConnectionHealth[instanceID] +} diff --git a/internal/monitoring/monitor_polling_test.go b/internal/monitoring/monitor_polling_test.go index ed3ac9e0fe..9b629cf8ee 100644 --- a/internal/monitoring/monitor_polling_test.go +++ b/internal/monitoring/monitor_polling_test.go @@ -6,11 +6,14 @@ import ( "encoding/json" "errors" "fmt" + "maps" "math" "net/http" "net/http/httptest" + "runtime" "strconv" "strings" + "sync" "sync/atomic" "testing" "time" @@ -2898,6 +2901,143 @@ func TestGetConnectionStatuses_BuiltInPMGSupport(t *testing.T) { } } +func TestGetConnectionStatuses_AllowsQueuedPollOutcome(t *testing.T) { + monitor := &Monitor{ + config: &config.Config{PVEInstances: []config.PVEInstance{{Name: "cluster"}}}, + state: models.NewState(), + pveClients: map[string]PVEClientInterface{"cluster": &mockPVEClient{}}, + pollStatusMap: make(map[string]*pollStatus), + } + monitor.state.SetConnectionHealth("custom/cluster", true) + + readerLocked, resumeReader := make(chan struct{}), make(chan struct{}) + resume := sync.OnceFunc(func() { close(resumeReader) }) + defer resume() + provider := newPVEPollProvider().(pollProviderAdapter) + provider.connectionStatus = func(m *Monitor) map[string]bool { + return providerConnectionStatuses(m, InstanceTypePVE, "pve-", func(m *Monitor) []pollProviderInstanceConfig { + close(readerLocked) + <-resumeReader + return pveInstanceConfigs(m) + }, pveClientMap) + } + // Registered providers can override the health key and consult the monitor. + provider.connectionKey = func(m *Monitor, name string) string { + if _, ok := m.getPVEClient(name); ok { + return "custom/" + name + } + return "" + } + monitor.pollProviders = map[InstanceType]PollProvider{InstanceTypePVE: provider} + + statuses := make(chan map[string]bool, 1) + go func() { statuses <- monitor.GetConnectionStatuses() }() + select { + case <-readerLocked: + case <-time.After(2 * time.Second): + t.Fatal("connection-status reader did not enter the monitor read lock") + } + + pollDone := make(chan struct{}) + go func() { + monitor.recordTaskOutcome(InstanceTypePVE, "cluster", nil, nil) + close(pollDone) + }() + // The reader still holds m.mu. Since there can be no active writer yet, + // TryRLock failing proves that the poll writer is queued, not just started. + deadline := time.Now().Add(2 * time.Second) + for monitor.mu.TryRLock() { + monitor.mu.RUnlock() + if time.Now().After(deadline) { + t.Fatal("poll writer did not queue behind the connection-status reader") + } + runtime.Gosched() + } + resume() + + select { + case got := <-statuses: + want := map[string]bool{"pve-cluster": true} + if !maps.Equal(got, want) { + t.Fatalf("connection statuses = %v, want %v", got, want) + } + case <-time.After(2 * time.Second): + t.Fatal("connection-status read did not complete with a queued poll writer") + } + select { + case <-pollDone: + if status := monitor.pollStatusMap[schedulerKey(InstanceTypePVE, "cluster")]; status == nil || status.LastSuccess.IsZero() { + t.Fatalf("poll success was not recorded: %+v", status) + } + case <-time.After(2 * time.Second): + t.Fatal("poll outcome did not complete") + } +} + +func TestGetConnectionStatuses_ConfiguredClientHealth(t *testing.T) { + monitor := &Monitor{ + config: &config.Config{ + PVEInstances: []config.PVEInstance{{Name: " cluster "}, {Name: "not-loaded"}}, + PBSInstances: []config.PBSInstance{{Host: " backup.example "}}, + PMGInstances: []config.PMGInstance{{Name: "mail"}}, + }, + pveClients: map[string]PVEClientInterface{"cluster": &mockPVEClient{}}, + pbsClients: map[string]*pbs.Client{"backup.example": {}}, + pmgClients: map[string]*pmg.Client{"mail": {}}, + } + want := map[string]bool{ + "pve-cluster": true, "pve-not-loaded": false, "pbs-backup.example": true, "pmg-mail": true, + } + for _, state := range []*models.State{nil, {}} { + monitor.state = state + if got := monitor.GetConnectionStatuses(); !maps.Equal(got, want) { + t.Fatalf("without initialized health: statuses = %v, want %v", got, want) + } + } + + monitor.state = models.NewState() + monitor.state.SetConnectionHealth("cluster", true) + monitor.state.SetConnectionHealth("not-loaded", true) // A stale entry cannot stand in for a missing client. + monitor.state.SetConnectionHealth("pmg-mail", false) + want["pbs-backup.example"] = false // Initialized health with no PBS entry yet. + want["pmg-mail"] = false + if got := monitor.GetConnectionStatuses(); !maps.Equal(got, want) { + t.Fatalf("with initialized health: statuses = %v, want %v", got, want) + } +} + +func TestGetConnectionStatuses_ReadsConcurrentHealthChanges(t *testing.T) { + monitor := &Monitor{ + config: &config.Config{PVEInstances: []config.PVEInstance{{Name: "cluster"}}}, + state: models.NewState(), + pveClients: map[string]PVEClientInterface{"cluster": &mockPVEClient{}}, + pollProviders: map[InstanceType]PollProvider{ + "xcp": testPollProvider{ + providerType: "xcp", instances: []string{"one"}, connectionKey: "xcp/one", + }, + }, + } + done := make(chan struct{}) + go func() { + defer close(done) + for range 256 { + monitor.state.SetConnectionHealth("cluster", true) + monitor.state.SetConnectionHealth("xcp/one", false) + monitor.state.RemoveConnectionHealth("cluster") + monitor.state.RemoveConnectionHealth("xcp/one") + } + }() + defer func() { <-done }() + for range 256 { + got := monitor.GetConnectionStatuses() + for _, key := range []string{"pve-cluster", "xcp-one"} { + if _, ok := got[key]; !ok { + t.Fatalf("configured status %q disappeared: %v", key, got) + } + } + } +} + func TestSetProviderConnectionHealth_UsesProviderConnectionKey(t *testing.T) { const customType InstanceType = "xcp" const instanceName = "xcp-a" diff --git a/internal/monitoring/poll_providers.go b/internal/monitoring/poll_providers.go index 7768277c14..a963c86743 100644 --- a/internal/monitoring/poll_providers.go +++ b/internal/monitoring/poll_providers.go @@ -234,10 +234,13 @@ func providerConnectionStatuses[C comparable]( } var zero C - statuses := make(map[string]bool) m.mu.RLock() + state := m.state + provider := m.pollProviders[instanceType] clients := clientsOf(m) - for _, inst := range configInstances(m) { + instances := configInstances(m) + statuses := make(map[string]bool, len(instances)) + for _, inst := range instances { name := strings.TrimSpace(inst.Name) if name == "" { name = strings.TrimSpace(inst.Host) @@ -245,22 +248,28 @@ func providerConnectionStatuses[C comparable]( 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 + statuses[keyPrefix+name] = clients[name] != zero } m.mu.RUnlock() if len(statuses) == 0 { return nil } + + // Only configuration and client presence belong to m.mu. Neither provider + // key callbacks nor State health reads run inside it: a queued poll writer + // prevents recursive read-locking, and State has its own lock. + if state != nil { + if provider == nil { + provider = builtinPollProvider(instanceType) + } + for key, hasClient := range statuses { + if hasClient { + name := strings.TrimPrefix(key, keyPrefix) + stateKey := connectionHealthStateKeyFor(m, provider, instanceType, name) + statuses[key] = state.ConnectionHealthForClient(stateKey) + } + } + } return statuses } @@ -574,6 +583,10 @@ func (m *Monitor) getPollProvider(instanceType InstanceType) PollProvider { return provider } + return builtinPollProvider(instanceType) +} + +func builtinPollProvider(instanceType InstanceType) PollProvider { switch instanceType { case InstanceTypePVE: return newPVEPollProvider() @@ -711,24 +724,27 @@ func (m *Monitor) refreshInstanceInfoCacheFromProviders() { } func (m *Monitor) connectionHealthStateKey(instanceType InstanceType, instanceName string) string { - trimmedName := strings.TrimSpace(instanceName) - if trimmedName == "" { + name := strings.TrimSpace(instanceName) + if name == "" { return "" } + return connectionHealthStateKeyFor(m, m.getPollProvider(instanceType), instanceType, name) +} - if provider := m.getPollProvider(instanceType); provider != nil { - if keyProvider, ok := provider.(ConnectionHealthKeyPollProvider); ok { - if key := strings.TrimSpace(keyProvider.ConnectionHealthKey(m, trimmedName)); key != "" { - return key - } +// name is already normalized by the caller. The provider callback may consult +// the monitor, so no caller may hold m.mu. +func connectionHealthStateKeyFor(m *Monitor, provider PollProvider, instanceType InstanceType, name string) string { + if keyProvider, ok := provider.(ConnectionHealthKeyPollProvider); ok { + if key := strings.TrimSpace(keyProvider.ConnectionHealthKey(m, name)); key != "" { + return key } } trimmedType := strings.TrimSpace(string(instanceType)) if trimmedType == "" { - return trimmedName + return name } - return trimmedType + "-" + trimmedName + return trimmedType + "-" + name } func (m *Monitor) setProviderConnectionHealth(instanceType InstanceType, instanceName string, healthy bool) { @@ -783,15 +799,13 @@ func (m *Monitor) providerConnectionStatuses(provider PollProvider) map[string]b return nil } - connectionHealth := make(map[string]bool) m.mu.RLock() - if m.state != nil && m.state.ConnectionHealth != nil { - connectionHealth = make(map[string]bool, len(m.state.ConnectionHealth)) - for key, healthy := range m.state.ConnectionHealth { - connectionHealth[key] = healthy - } - } + state := m.state m.mu.RUnlock() + var connectionHealth map[string]bool + if state != nil { + connectionHealth = state.GetConnectionHealth() + } statuses := make(map[string]bool, len(names)) for _, name := range names { @@ -801,7 +815,7 @@ func (m *Monitor) providerConnectionStatuses(provider PollProvider) map[string]b } key := instanceType + "-" + trimmedName - stateKey := m.connectionHealthStateKey(InstanceType(instanceType), trimmedName) + stateKey := connectionHealthStateKeyFor(m, provider, InstanceType(instanceType), trimmedName) if stateKey == "" { stateKey = trimmedName }