Keep Proxmox connection reads from blocking the polling scheduler

A queued poll writer can deadlock PVE, PBS and PMG connection status
lookups when the same reader reacquires Monitor.mu to resolve a health
key. Snapshot configured client presence under the monitor lock, then
resolve provider keys outside it and read health under the state lock.

Exercise a queued poll outcome alongside the connection read and
preserve built-in and provider-specific status keys and defaults.

Contract-Neutral: Removes recursive monitor locking and synchronizes health reads without changing endpoints, status keys, health defaults, polling cadence, or registration authority.
Change-source: pulse-maintainer
This commit is contained in:
pulse-triage[bot]
2026-11-24 16:46:49 +00:00
parent 9f71173b7a
commit af323da28b
3 changed files with 193 additions and 30 deletions

View File

@@ -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]
}

View File

@@ -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"

View File

@@ -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
}