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.

Fix Proxmox cluster connection authority

rcourtman3c6d933e9d84
diff --git a/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-address-authority-2026-07-23.md b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-address-authority-2026-07-23.md
new file mode 100644
index 0000000000..06e7161647
--- /dev/null
+++ b/docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-address-authority-2026-07-23.md
@@ -0,0 +1,64 @@
+# Known RC Issue Closure For GA Proxmox Cluster Address Authority Record
+
+- Date: `2026-07-23`
+- Gate: `known-rc-issue-closure-for-ga`
+- Issues: `#1437`, `#1493`
+- Result: `fixed-main-proof`
+
+## Context
+
+Issue `#1437` supplied a support bundle from a cluster configured through one
+reachable management URL. Proxmox discovery also returned member/corosync
+addresses that the Pulse container could not route. Snapshot and replication
+polls repeatedly waited on those addresses until their task context expired,
+while independent Unified Agent data remained visible. The earlier v6
+snapshot-read-state correction ensured clustered guests reached the snapshot
+poller, but it did not govern which cluster address served the resulting API
+requests.
+
+Issue `#1493` reported the presentation side of the same address model after a
+cluster network move: Settings retained old member IP reachability errors and
+historically repeated the connection-level API badge on every member. The
+periodic member refresh and single parent API badge shipped in
+`v6.0.0-rc.7`, but the cluster client still treated the saved URL as a final
+fallback inside a random endpoint pool.
+
+## Disposition
+
+The operator-saved Proxmox URL is now the ordered cluster API authority. It and
+one credential set serve ordinary polling; auto-discovered member addresses
+remain ordered failover candidates and direct reachability evidence rather
+than becoming per-node credentials or randomly selected peers.
+
+When the configured authority is healthy, member recovery runs as one bounded
+background sweep. Snapshot, storage-content, replication, and other API-only
+requests therefore do not wait on cluster-private member addresses. If no
+endpoint is healthy, recovery remains synchronous so a newly reachable member
+can restore service. Recovery is rate-limited and retains member health/error
+evidence for Settings and diagnostics.
+
+Periodic cluster discovery still replaces changed member addresses and rebuilds
+the failover client. Reachability evidence is carried forward only when the
+effective dial URL is unchanged; a re-IP resets the old success/error until the
+new target is checked. Settings keeps one API badge on the cluster connection
+while member addresses and node-local Agent evidence remain visible.
+
+## Proof
+
+- `go test ./pkg/proxmox -count=1`
+- `go test -race ./pkg/proxmox -run 'TestClusterClient_ConfiguredAuthorityDoesNotWaitForMemberRecovery|TestExecuteWithFailoverMovesToAnotherEndpoint|TestClusterClient_RecoverUnhealthyNodes' -count=1`
+- `go test ./internal/monitoring -count=1`
+- `go test ./internal/monitoring -run 'TestBuildClusterEndpointsForInit_RespectsDiscoveryPolicy|TestDetectClusterMembership_RefreshesStaleClusterEndpoints|TestMergeRefreshedClusterEndpoints|TestBuildClusterEndpoints_PreservesConfiguredAuthority' -count=1`
+- `vitest run src/components/Settings/__tests__/InfrastructureSourceManager.test.tsx src/components/Settings/__tests__/useConnectionsLedger.test.ts src/components/Settings/ConnectionEditor/CredentialSlots/__tests__/NodeCredentialSlot.test.tsx`
+- subsystem registry, contract, status, control-plane, staged-shape, and
+ canonical-completion audits
+
+## Outcome
+
+The stale-address refresh and single cluster API presentation from `#1493`
+remain available from `v6.0.0-rc.7` onward, including `v6.1.1`. The configured
+authority and non-blocking member-recovery hardening in this record is on
+`main` for a future v6 release; it is not retroactively part of `v6.1.1`, no v5
+backport is claimed, and no publication date is promised by this proof. Both
+issues remain open for reporter confirmation after a release containing the
+change.
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index f4d812c921..a1c6625bac 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -5742,6 +5742,12 @@
"kind": "file",
"evidence_tier": "managed-runtime-exercise"
},
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-address-authority-2026-07-23.md",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-snapshots-2026-06-16.md",
@@ -7813,6 +7819,12 @@
"kind": "file",
"evidence_tier": "managed-runtime-exercise"
},
+ {
+ "repo": "pulse",
+ "path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-address-authority-2026-07-23.md",
+ "kind": "file",
+ "evidence_tier": "test-proof"
+ },
{
"repo": "pulse",
"path": "docs/release-control/v6/internal/records/known-rc-issue-closure-for-ga-proxmox-cluster-snapshots-2026-06-16.md",
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index b1c6ac9c7e..e760601bba 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -154,6 +154,21 @@ neutral rather than borrowing telemetry from another disk.
Negative percentage-used counters remain unknown; values above 100 clamp to
exhausted before deriving remaining life, so invalid or over-limit controller
data cannot wrap into a fabricated healthy value.
+Proxmox cluster API polling has one configured connection authority: the
+operator-saved `PVEInstance.Host` and its single credential set. Auto-discovered
+member/corosync addresses remain ordered failover candidates and direct
+reachability evidence; they are not per-node API connections or credentials and
+must not randomly displace a healthy configured authority. When the authority
+is healthy, recovery checks for unreachable members run bounded and
+asynchronously so snapshots, storage content, replication, and other API-only
+data do not wait on cluster-private addresses. When no endpoint is healthy,
+recovery remains synchronous so a reachable member can restore service.
+Periodic cluster discovery refreshes changed member addresses and rebuilds the
+failover client. Pulse reachability evidence survives that reconciliation only
+when the member's effective dial URL is unchanged; a network move resets the
+old result until the new target is checked. Infrastructure Settings presents
+one cluster-level API source while retaining member addresses and their
+node-local Agent evidence.
## Canonical Files
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index e1d224ab19..dab2160c47 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -5427,6 +5427,7 @@
"allow_same_subsystem_tests": false,
"test_prefixes": [],
"exact_files": [
+ "internal/monitoring/monitor_pve_cluster_refresh_test.go",
"internal/monitoring/monitor_pve_disk_fallback_test.go",
"pkg/proxmox/cluster_client_additional_api4_test.go",
"pkg/proxmox/cluster_client_api_test.go"
@@ -5571,12 +5572,14 @@
"internal/monitoring/canonical_guardrails_test.go",
"internal/monitoring/issue1485_unraid_lifecycle_test.go",
"internal/monitoring/issue1595_collection_trust_test.go",
+ "internal/monitoring/monitor_additional_test.go",
"internal/monitoring/monitor_alert_intent_test.go",
"internal/monitoring/monitor_alert_override_migration_test.go",
"internal/monitoring/monitor_backups_readstate_test.go",
"internal/monitoring/monitor_docker_test.go",
"internal/monitoring/monitor_host_agent_removal_lifecycle_test.go",
"internal/monitoring/monitor_host_agents_test.go",
+ "internal/monitoring/monitor_pve_cluster_refresh_test.go",
"internal/unifiedresources/code_standards_test.go"
]
}
diff --git a/frontend-modern/src/components/Settings/__tests__/InfrastructureSourceManager.test.tsx b/frontend-modern/src/components/Settings/__tests__/InfrastructureSourceManager.test.tsx
index 20f198bd02..09db8bb064 100644
--- a/frontend-modern/src/components/Settings/__tests__/InfrastructureSourceManager.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/InfrastructureSourceManager.test.tsx
@@ -401,6 +401,63 @@ describe('InfrastructureSourceManager setup summary', () => {
);
});
+ it('shows one cluster API connection while retaining member reachability addresses', () => {
+ render(() => (
+ <InfrastructureSourceManager
+ rows={() => [
+ row({
+ id: 'pve:remote-cluster',
+ ownerType: 'pve',
+ name: 'Remote cluster',
+ subtitle: 'Proxmox VE cluster',
+ source: 'api',
+ host: 'https://management.example.test:8006',
+ isCluster: true,
+ coverageLabels: ['Nodes', 'Guests', 'Storage'],
+ connection: connectionFixture({
+ id: 'pve:remote-cluster',
+ type: 'pve',
+ name: 'Remote cluster',
+ address: 'https://management.example.test:8006',
+ source: 'manual',
+ surfaces: ['nodes', 'guests', 'storage'],
+ scope: { nodes: true, guests: true, storage: true },
+ capabilities: { supportsPause: true, supportsScope: true, supportsTest: true },
+ }),
+ members: [
+ member({
+ id: 'pve-a',
+ name: 'pve-a',
+ source: 'api',
+ host: 'https://10.15.5.11:8006',
+ coverageLabels: ['Cluster API'],
+ }),
+ member({
+ id: 'pve-b',
+ name: 'pve-b',
+ source: 'api',
+ host: 'https://10.15.5.12:8006',
+ coverageLabels: ['Cluster API'],
+ }),
+ ],
+ }),
+ ]}
+ discoveredNodes={() => []}
+ discoveryEnabled={false}
+ discoveryScanStatus={() => ({ scanning: false })}
+ readOnly
+ />
+ ));
+
+ expect(screen.getAllByText('API')).toHaveLength(1);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show 2 nodes for Remote cluster' }));
+
+ expect(screen.getAllByText('API')).toHaveLength(1);
+ expect(screen.getByText('https://10.15.5.11:8006')).toBeInTheDocument();
+ expect(screen.getByText('https://10.15.5.12:8006')).toBeInTheDocument();
+ });
+
it('labels vSphere member composition as hosts, not cluster nodes', () => {
render(() => (
<InfrastructureSourceManager
diff --git a/internal/monitoring/monitor_additional_test.go b/internal/monitoring/monitor_additional_test.go
index 79824b2f83..2f1459b10f 100644
--- a/internal/monitoring/monitor_additional_test.go
+++ b/internal/monitoring/monitor_additional_test.go
@@ -327,12 +327,12 @@ func TestBuildClusterEndpointsForInit_RespectsDiscoveryPolicy(t *testing.T) {
})
if len(endpoints) != 2 {
- t.Fatalf("expected allowed endpoint plus main host fallback, got %#v", endpoints)
+ t.Fatalf("expected configured authority plus allowed member failover, got %#v", endpoints)
}
- if endpoints[0] != "https://allowed.local:8006" {
- t.Fatalf("expected discovery-allowed endpoint first, got %#v", endpoints)
+ if endpoints[0] != "https://main.local:8006" {
+ t.Fatalf("expected configured authority first, got %#v", endpoints)
}
- if endpoints[1] != "https://main.local:8006" {
- t.Fatalf("expected main host fallback retained, got %#v", endpoints)
+ if endpoints[1] != "https://allowed.local:8006" {
+ t.Fatalf("expected only the discovery-allowed member as failover, got %#v", endpoints)
}
}
diff --git a/internal/monitoring/monitor_pve_client_endpoints.go b/internal/monitoring/monitor_pve_client_endpoints.go
index 38d239ec48..6e9394dab3 100644
--- a/internal/monitoring/monitor_pve_client_endpoints.go
+++ b/internal/monitoring/monitor_pve_client_endpoints.go
@@ -1,142 +1,74 @@
package monitoring
import (
- "net"
- "net/url"
- "strings"
-
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rs/zerolog/log"
)
func (m *Monitor) buildClusterEndpointsForInit(pve config.PVEInstance) ([]string, map[string]string) {
- // For clusters, check if endpoints have IPs/resolvable hosts
- // If not, use the main host for all connections (Proxmox will route cluster API calls)
- hasValidEndpoints := false
- endpoints := make([]string, 0, len(pve.ClusterEndpoints))
+ return m.buildClusterClientEndpoints(pve)
+}
+
+func (m *Monitor) buildClusterEndpointsForReconnect(pve config.PVEInstance) ([]string, map[string]string) {
+ return m.buildClusterClientEndpoints(pve)
+}
+
+// buildClusterClientEndpoints preserves the configured connection as the
+// cluster API authority. Proxmox can advertise corosync/member addresses that
+// are valid inside the cluster but unreachable from the Pulse container; those
+// addresses remain useful failover and reachability evidence, but they must
+// never displace the URL the operator proved reachable when adding the cluster.
+func (m *Monitor) buildClusterClientEndpoints(pve config.PVEInstance) ([]string, map[string]string) {
+ endpoints := make([]string, 0, len(pve.ClusterEndpoints)+1)
endpointFingerprints := make(map[string]string)
discoveryCfg := monitorDiscoveryConfig(m)
-
hasFingerprint := pve.Fingerprint != ""
- for _, ep := range pve.ClusterEndpoints {
- effectiveURL := clusterEndpointRuntimeURL(ep, pve.VerifySSL, hasFingerprint, discoveryCfg)
- if effectiveURL == "" {
- log.Warn().
- Str("node", ep.NodeName).
- Msg("Skipping cluster endpoint with no allowed host/IP")
- continue
- }
+ seen := make(map[string]struct{}, len(pve.ClusterEndpoints)+1)
- if parsed, err := url.Parse(effectiveURL); err == nil {
- hostname := parsed.Hostname()
- if hostname != "" && (strings.Contains(hostname, ".") || net.ParseIP(hostname) != nil) {
- hasValidEndpoints = true
- }
- } else {
- hostname := normalizeEndpointHost(effectiveURL)
- if hostname != "" && (strings.Contains(hostname, ".") || net.ParseIP(hostname) != nil) {
- hasValidEndpoints = true
- }
+ addEndpoint := func(endpoint string) bool {
+ if endpoint == "" {
+ return false
}
-
- endpoints = append(endpoints, effectiveURL)
- // Store per-endpoint fingerprint for TOFU (Trust On First Use)
- if ep.Fingerprint != "" {
- endpointFingerprints[effectiveURL] = ep.Fingerprint
+ if _, exists := seen[endpoint]; exists {
+ return false
}
+ seen[endpoint] = struct{}{}
+ endpoints = append(endpoints, endpoint)
+ return true
}
- // If endpoints are just node names (not FQDNs or IPs), use main host only
- // This is common when cluster nodes are discovered but not directly reachable
- if !hasValidEndpoints || len(endpoints) == 0 {
- log.Info().
- Str("instance", pve.Name).
- Str("mainHost", pve.Host).
- Msg("Cluster endpoints are not resolvable, using main host for all cluster operations")
- fallback := ensureClusterEndpointURL(pve.Host)
- if fallback == "" {
- fallback = ensureClusterEndpointURL(pve.Host)
- }
- endpoints = []string{fallback}
- } else {
- // Always include the main host URL as a fallback endpoint.
- // This handles remote cluster scenarios where Proxmox reports internal IPs
- // that aren't reachable from Pulse's network. The user-provided URL is
- // reachable, so include it as a fallback for cluster API routing.
- mainHostURL := ensureClusterEndpointURL(pve.Host)
- mainHostAlreadyIncluded := false
- for _, ep := range endpoints {
- if ep == mainHostURL {
- mainHostAlreadyIncluded = true
- break
- }
- }
- if !mainHostAlreadyIncluded && mainHostURL != "" {
- log.Info().
- Str("instance", pve.Name).
- Str("mainHost", mainHostURL).
- Int("clusterEndpoints", len(endpoints)).
- Msg("Adding main host as fallback for remote cluster access")
- endpoints = append(endpoints, mainHostURL)
- }
- }
-
- return endpoints, endpointFingerprints
-}
-
-func (m *Monitor) buildClusterEndpointsForReconnect(pve config.PVEInstance) ([]string, map[string]string) {
- hasValidEndpoints := false
- endpoints := make([]string, 0, len(pve.ClusterEndpoints))
- endpointFingerprints := make(map[string]string)
- discoveryCfg := monitorDiscoveryConfig(m)
- hasFingerprint := pve.Fingerprint != ""
+ configuredAuthority := ensureClusterEndpointURL(pve.Host)
+ addEndpoint(configuredAuthority)
+ failoverCount := 0
for _, ep := range pve.ClusterEndpoints {
host := clusterEndpointRuntimeURL(ep, pve.VerifySSL, hasFingerprint, discoveryCfg)
if host == "" {
+ log.Warn().
+ Str("node", ep.NodeName).
+ Msg("Skipping cluster member endpoint with no allowed host/IP")
continue
}
-
- if parsed, err := url.Parse(host); err == nil {
- hostname := parsed.Hostname()
- if hostname != "" && (strings.Contains(hostname, ".") || net.ParseIP(hostname) != nil) {
- hasValidEndpoints = true
- }
- } else {
- hostname := normalizeEndpointHost(host)
- if hostname != "" && (strings.Contains(hostname, ".") || net.ParseIP(hostname) != nil) {
- hasValidEndpoints = true
- }
- }
-
- if !strings.HasPrefix(host, "http") {
- host = ensureClusterEndpointURL(host)
+ if addEndpoint(host) {
+ failoverCount++
}
- endpoints = append(endpoints, host)
if ep.Fingerprint != "" {
endpointFingerprints[host] = ep.Fingerprint
}
}
- if !hasValidEndpoints || len(endpoints) == 0 {
- fallback := ensureClusterEndpointURL(pve.Host)
- if fallback == "" {
- fallback = ensureClusterEndpointURL(pve.Host)
- }
- endpoints = []string{fallback}
- return endpoints, endpointFingerprints
- }
-
- mainHostURL := ensureClusterEndpointURL(pve.Host)
- mainHostAlreadyIncluded := false
- for _, ep := range endpoints {
- if ep == mainHostURL {
- mainHostAlreadyIncluded = true
- break
- }
- }
- if !mainHostAlreadyIncluded && mainHostURL != "" {
- endpoints = append(endpoints, mainHostURL)
+ if configuredAuthority != "" {
+ log.Info().
+ Str("instance", pve.Name).
+ Str("authority", configuredAuthority).
+ Int("memberFailovers", failoverCount).
+ Msg("Using configured Proxmox cluster connection as API authority")
+ } else if len(endpoints) > 0 {
+ log.Warn().
+ Str("instance", pve.Name).
+ Str("authority", endpoints[0]).
+ Int("memberFailovers", len(endpoints)-1).
+ Msg("Configured Proxmox cluster URL is empty; using first discovered member as API authority")
}
return endpoints, endpointFingerprints
diff --git a/internal/monitoring/monitor_pve_cluster.go b/internal/monitoring/monitor_pve_cluster.go
index 72e064d984..771e20a0c4 100644
--- a/internal/monitoring/monitor_pve_cluster.go
+++ b/internal/monitoring/monitor_pve_cluster.go
@@ -78,7 +78,7 @@ func (m *Monitor) detectClusterMembership(ctx context.Context, instanceName stri
// node addresses changed, the config is persisted and the failover client is
// rebuilt so polling stops dialing the dead addresses.
func (m *Monitor) refreshClusterEndpoints(instanceName string, instanceCfg *config.PVEInstance, clusterName string, discovered []config.ClusterEndpoint) {
- refreshed := mergeRefreshedClusterEndpoints(instanceCfg.ClusterEndpoints, discovered)
+ refreshed := mergeRefreshedClusterEndpoints(instanceCfg.ClusterEndpoints, discovered, instanceCfg.VerifySSL)
if !clusterEndpointIdentityChanged(instanceCfg.ClusterEndpoints, refreshed) {
return
}
@@ -120,15 +120,17 @@ func (m *Monitor) refreshClusterEndpoints(instanceName string, instanceCfg *conf
// mergeRefreshedClusterEndpoints folds freshly discovered endpoints over the
// stored set. The cluster status API can omit per-node fields, so discovery
// never erases information Pulse already had; Pulse-side reachability
-// bookkeeping is carried over because it is recomputed each poll and dropping
-// it would flap the UI to "unknown" after every refresh.
-func mergeRefreshedClusterEndpoints(existing, discovered []config.ClusterEndpoint) []config.ClusterEndpoint {
+// bookkeeping is carried over only while the effective dial target is
+// unchanged. Reusing a success/error from an address that was just replaced
+// would present stale reachability evidence after a cluster network move.
+func mergeRefreshedClusterEndpoints(existing, discovered []config.ClusterEndpoint, verifySSL bool) []config.ClusterEndpoint {
merged := make([]config.ClusterEndpoint, 0, len(discovered))
for _, ep := range discovered {
for _, old := range existing {
if !strings.EqualFold(strings.TrimSpace(old.NodeName), strings.TrimSpace(ep.NodeName)) {
continue
}
+ oldEffectiveURL := clusterEndpointEffectiveURL(old, verifySSL, false)
if strings.TrimSpace(ep.IP) == "" {
ep.IP = old.IP
}
@@ -138,9 +140,11 @@ func mergeRefreshedClusterEndpoints(existing, discovered []config.ClusterEndpoin
if strings.TrimSpace(ep.NodeID) == "" {
ep.NodeID = old.NodeID
}
- ep.PulseReachable = old.PulseReachable
- ep.LastPulseCheck = old.LastPulseCheck
- ep.PulseError = old.PulseError
+ if clusterEndpointEffectiveURL(ep, verifySSL, false) == oldEffectiveURL {
+ ep.PulseReachable = old.PulseReachable
+ ep.LastPulseCheck = old.LastPulseCheck
+ ep.PulseError = old.PulseError
+ }
break
}
merged = append(merged, ep)
diff --git a/internal/monitoring/monitor_pve_cluster_refresh_test.go b/internal/monitoring/monitor_pve_cluster_refresh_test.go
index bd4748381c..649cff8fb8 100644
--- a/internal/monitoring/monitor_pve_cluster_refresh_test.go
+++ b/internal/monitoring/monitor_pve_cluster_refresh_test.go
@@ -137,7 +137,7 @@ func TestMergeRefreshedClusterEndpoints_InheritsMissingFields(t *testing.T) {
{NodeID: "node/proxmox1", NodeName: "proxmox1", Host: "https://proxmox1:8006", IP: "10.32.20.22"},
}
- merged := mergeRefreshedClusterEndpoints(existing, discovered)
+ merged := mergeRefreshedClusterEndpoints(existing, discovered, false)
if len(merged) != 2 {
t.Fatalf("expected 2 merged endpoints, got %d", len(merged))
}
@@ -152,6 +152,100 @@ func TestMergeRefreshedClusterEndpoints_InheritsMissingFields(t *testing.T) {
}
}
+func TestMergeRefreshedClusterEndpoints_ReachabilityFollowsEffectiveTarget(t *testing.T) {
+ reachable := true
+ checked := time.Now().Add(-time.Minute)
+ existing := []config.ClusterEndpoint{
+ {
+ NodeID: "node/proxmox0",
+ NodeName: "proxmox0",
+ Host: "https://proxmox0:8006",
+ IP: "10.32.21.21",
+ PulseReachable: &reachable,
+ LastPulseCheck: &checked,
+ PulseError: "old address timed out",
+ },
+ }
+
+ t.Run("network move resets stale evidence", func(t *testing.T) {
+ discovered := []config.ClusterEndpoint{
+ {NodeID: "node/proxmox0", NodeName: "proxmox0", Host: "https://proxmox0:8006", IP: "10.32.20.21"},
+ }
+
+ merged := mergeRefreshedClusterEndpoints(existing, discovered, false)
+ if merged[0].PulseReachable != nil || merged[0].LastPulseCheck != nil || merged[0].PulseError != "" {
+ t.Fatalf("expected reachability evidence to reset with the dial target, got %+v", merged[0])
+ }
+ })
+
+ t.Run("stable override preserves useful evidence", func(t *testing.T) {
+ withOverride := append([]config.ClusterEndpoint(nil), existing...)
+ withOverride[0].IPOverride = "pulse-route.example.test"
+ discovered := []config.ClusterEndpoint{
+ {
+ NodeID: "node/proxmox0",
+ NodeName: "proxmox0",
+ Host: "https://proxmox0:8006",
+ IP: "10.32.20.21",
+ IPOverride: "pulse-route.example.test",
+ Fingerprint: withOverride[0].Fingerprint,
+ },
+ }
+
+ merged := mergeRefreshedClusterEndpoints(withOverride, discovered, false)
+ if merged[0].PulseReachable != &reachable || merged[0].LastPulseCheck != &checked || merged[0].PulseError != "old address timed out" {
+ t.Fatalf("expected evidence for the unchanged override target, got %+v", merged[0])
+ }
+ })
+}
+
+func TestBuildClusterEndpoints_PreservesConfiguredAuthority(t *testing.T) {
+ monitor := &Monitor{config: &config.Config{}}
+ instance := config.PVEInstance{
+ Name: "remote-cluster",
+ Host: "https://management.example.test:8006",
+ VerifySSL: false,
+ ClusterEndpoints: []config.ClusterEndpoint{
+ {NodeName: "pve-a", IP: "10.15.5.11", Fingerprint: "AA:11"},
+ {NodeName: "pve-b", IP: "10.15.5.12", Fingerprint: "BB:22"},
+ // Discovery may report the configured route as a member too; it
+ // remains one endpoint and keeps its member certificate evidence.
+ {NodeName: "pve-c", Host: "https://management.example.test:8006", Fingerprint: "CC:33"},
+ },
+ }
+
+ want := []string{
+ "https://management.example.test:8006",
+ "https://10.15.5.11:8006",
+ "https://10.15.5.12:8006",
+ }
+
+ for _, build := range []struct {
+ name string
+ fn func(config.PVEInstance) ([]string, map[string]string)
+ }{
+ {name: "initialization", fn: monitor.buildClusterEndpointsForInit},
+ {name: "reconnect", fn: monitor.buildClusterEndpointsForReconnect},
+ } {
+ t.Run(build.name, func(t *testing.T) {
+ endpoints, fingerprints := build.fn(instance)
+ if len(endpoints) != len(want) {
+ t.Fatalf("expected %d ordered endpoints, got %v", len(want), endpoints)
+ }
+ for i := range want {
+ if endpoints[i] != want[i] {
+ t.Fatalf("endpoint %d: expected %q, got %q (all: %v)", i, want[i], endpoints[i], endpoints)
+ }
+ }
+ if fingerprints["https://10.15.5.11:8006"] != "AA:11" ||
+ fingerprints["https://10.15.5.12:8006"] != "BB:22" ||
+ fingerprints["https://management.example.test:8006"] != "CC:33" {
+ t.Fatalf("expected per-member fingerprints to survive deduplication, got %+v", fingerprints)
+ }
+ })
+ }
+}
+
func TestClusterEndpointIdentityChanged(t *testing.T) {
base := []config.ClusterEndpoint{
{NodeID: "node/a", NodeName: "a", Host: "https://a:8006", IP: "10.0.0.1"},
diff --git a/pkg/proxmox/cluster_client.go b/pkg/proxmox/cluster_client.go
index d189f9f3f1..08585569f8 100644
--- a/pkg/proxmox/cluster_client.go
+++ b/pkg/proxmox/cluster_client.go
@@ -26,12 +26,15 @@ type ClusterClient struct {
lastError map[string]string // Track last error per endpoint
config ClientConfig // Base config (auth info)
rateLimitUntil map[string]time.Time // Cooldown window for rate-limited endpoints
+ recoveryInProgress bool // Prevent overlapping background recovery sweeps
}
const (
- rateLimitBaseDelay = 150 * time.Millisecond
- rateLimitMaxJitter = 200 * time.Millisecond
- rateLimitRetryBudget = 2
+ rateLimitBaseDelay = 150 * time.Millisecond
+ rateLimitMaxJitter = 200 * time.Millisecond
+ rateLimitRetryBudget = 2
+ backgroundRecoveryTimeout = 6 * time.Second
+ unhealthyRecoveryInterval = 10 * time.Second
)
var statusCodePattern = regexp.MustCompile(`(?i)(?:api error|status)\s+(\d{3})`)
@@ -382,27 +385,65 @@ func (cc *ClusterClient) initialHealthCheck() {
Msg("Initial cluster health check completed")
}
-// getHealthyClient returns a healthy client using round-robin selection
+func (cc *ClusterClient) availableEndpointsLocked(now time.Time) (healthyEndpoints, coolingEndpoints []string) {
+ for _, endpoint := range cc.endpoints {
+ if !cc.nodeHealth[endpoint] {
+ continue
+ }
+ if cooldown, exists := cc.rateLimitUntil[endpoint]; exists {
+ if now.Before(cooldown) {
+ coolingEndpoints = append(coolingEndpoints, endpoint)
+ continue
+ }
+ delete(cc.rateLimitUntil, endpoint)
+ }
+ healthyEndpoints = append(healthyEndpoints, endpoint)
+ }
+ return healthyEndpoints, coolingEndpoints
+}
+
+func (cc *ClusterClient) startBackgroundRecoveryLocked() {
+ if cc.recoveryInProgress {
+ return
+ }
+ cc.recoveryInProgress = true
+
+ go func() {
+ defer func() {
+ cc.mu.Lock()
+ cc.recoveryInProgress = false
+ cc.mu.Unlock()
+ }()
+
+ recoveryCtx, cancel := context.WithTimeout(context.Background(), backgroundRecoveryTimeout)
+ defer cancel()
+ cc.recoverUnhealthyNodes(recoveryCtx)
+ }()
+}
+
+func (cc *ClusterClient) hasRecoverableUnhealthyEndpointLocked(now time.Time) bool {
+ for _, endpoint := range cc.endpoints {
+ if cc.nodeHealth[endpoint] {
+ continue
+ }
+ lastCheck, checked := cc.lastHealthCheck[endpoint]
+ if !checked || now.Sub(lastCheck) >= unhealthyRecoveryInterval {
+ return true
+ }
+ }
+ return false
+}
+
+// getHealthyClient returns the first available endpoint in configured priority
+// order. The first endpoint is the operator-configured cluster URL; discovered
+// member addresses are failover candidates rather than a random load-balancing
+// pool.
func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error) {
cc.mu.Lock()
defer cc.mu.Unlock()
- // Get list of healthy endpoints
- var healthyEndpoints []string
- var coolingEndpoints []string
now := time.Now()
- for endpoint, healthy := range cc.nodeHealth {
- if healthy {
- if cooldown, exists := cc.rateLimitUntil[endpoint]; exists {
- if now.Before(cooldown) {
- coolingEndpoints = append(coolingEndpoints, endpoint)
- continue
- }
- delete(cc.rateLimitUntil, endpoint)
- }
- healthyEndpoints = append(healthyEndpoints, endpoint)
- }
- }
+ healthyEndpoints, coolingEndpoints := cc.availableEndpointsLocked(now)
if len(healthyEndpoints) == 0 && len(coolingEndpoints) > 0 {
// Nothing is immediately available, fall back to endpoints that are in cooldown
@@ -435,36 +476,27 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
Msg("Checking for healthy endpoints")
}
- // Trigger recovery if we have any unhealthy endpoints
- // This ensures degraded clusters recover individual nodes over time,
- // not just when all nodes are down
+ // Keep failover evidence fresh, but do not make a healthy API request wait
+ // for member addresses that may only be reachable on the cluster network.
if unhealthyCount > 0 {
- // Use an anonymous function to ensure the lock is re-acquired even if
- // recoverUnhealthyNodes panics, preventing double-unlock from defer
- func() {
- cc.mu.Unlock()
- defer cc.mu.Lock()
- cc.recoverUnhealthyNodes(ctx)
- }()
-
- // Refresh the healthy/cooling endpoints lists after recovery attempt
- // since cluster state may have changed while lock was released
- healthyEndpoints = nil
- coolingEndpoints = nil
- now = time.Now() // Refresh time for accurate cooldown checks
- for endpoint, healthy := range cc.nodeHealth {
- if healthy {
- if cooldown, exists := cc.rateLimitUntil[endpoint]; exists && now.Before(cooldown) {
- coolingEndpoints = append(coolingEndpoints, endpoint)
- continue
- }
- healthyEndpoints = append(healthyEndpoints, endpoint)
+ if len(healthyEndpoints) > 0 {
+ if cc.hasRecoverableUnhealthyEndpointLocked(now) {
+ cc.startBackgroundRecoveryLocked()
+ }
+ } else {
+ // With no usable authority, recovery remains synchronous so this
+ // request can fail over to a member that has just become reachable.
+ func() {
+ cc.mu.Unlock()
+ defer cc.mu.Lock()
+ cc.recoverUnhealthyNodes(ctx)
+ }()
+
+ now = time.Now()
+ healthyEndpoints, coolingEndpoints = cc.availableEndpointsLocked(now)
+ if len(healthyEndpoints) == 0 && len(coolingEndpoints) > 0 {
+ healthyEndpoints = append(healthyEndpoints, coolingEndpoints...)
}
- }
-
- // Re-apply cooldown fallback if no healthy endpoints but some cooling
- if len(healthyEndpoints) == 0 && len(coolingEndpoints) > 0 {
- healthyEndpoints = append(healthyEndpoints, coolingEndpoints...)
}
}
@@ -507,8 +539,7 @@ func (cc *ClusterClient) getHealthyClient(ctx context.Context) (*Client, error)
}
}
- // Use random selection for better load distribution
- selectedEndpoint := healthyEndpoints[rand.Intn(len(healthyEndpoints))]
+ selectedEndpoint := healthyEndpoints[0]
// Get or create client for this endpoint
client, exists := cc.clients[selectedEndpoint]
@@ -638,10 +669,10 @@ func (cc *ClusterClient) recoverUnhealthyNodes(ctx context.Context) {
now := time.Now()
for endpoint, healthy := range cc.nodeHealth {
if !healthy {
- // Skip if we checked this endpoint recently (within 10 seconds)
+ // Skip if we checked this endpoint recently.
// Balance between recovery speed and avoiding excessive checks
if lastCheck, exists := cc.lastHealthCheck[endpoint]; exists {
- if now.Sub(lastCheck) < 10*time.Second {
+ if now.Sub(lastCheck) < unhealthyRecoveryInterval {
throttledEndpoints = append(throttledEndpoints, endpoint)
continue
}
diff --git a/pkg/proxmox/cluster_client_api_test.go b/pkg/proxmox/cluster_client_api_test.go
index a9dd6dc651..8c124fedbd 100644
--- a/pkg/proxmox/cluster_client_api_test.go
+++ b/pkg/proxmox/cluster_client_api_test.go
@@ -82,6 +82,147 @@ func TestClusterClient_GetStorageContent(t *testing.T) {
}
}
+func TestClusterClient_ConfiguredAuthorityDoesNotWaitForMemberRecovery(t *testing.T) {
+ var authorityDataCalls atomic.Int32
+ authority := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch r.URL.Path {
+ case "/api2/json/nodes/node1/qemu/100/snapshot":
+ authorityDataCalls.Add(1)
+ fmt.Fprint(w, `{"data":[{"name":"snap-authority","description":"cluster snapshot"}]}`)
+ case "/api2/json/nodes/node1/storage/local/content":
+ authorityDataCalls.Add(1)
+ fmt.Fprint(w, `{"data":[{"volid":"local:backup/vzdump-qemu-100.vma.zst","format":"vma.zst","size":1000,"content":"backup"}]}`)
+ default:
+ fmt.Fprint(w, `{"data":[{"node":"node1","status":"online"}]}`)
+ }
+ }))
+ defer authority.Close()
+
+ recoveryStarted := make(chan struct{}, 2)
+ releaseRecovery := make(chan struct{})
+ recoveryReleased := false
+
+ var memberDataCalls atomic.Int32
+ newMember := func() *httptest.Server {
+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if r.URL.Path == "/api2/json/nodes" {
+ recoveryStarted <- struct{}{}
+ <-releaseRecovery
+ fmt.Fprint(w, `{"data":[{"node":"node1","status":"online"}]}`)
+ return
+ }
+ memberDataCalls.Add(1)
+ fmt.Fprint(w, `{"data":[]}`)
+ }))
+ }
+ memberA := newMember()
+ defer memberA.Close()
+ memberB := newMember()
+ defer memberB.Close()
+ defer func() {
+ if !recoveryReleased {
+ close(releaseRecovery)
+ }
+ }()
+
+ cfg := ClientConfig{
+ Host: authority.URL,
+ TokenName: "u@p!t",
+ TokenValue: "v",
+ Timeout: 2 * time.Second,
+ }
+ authorityClient, err := NewClient(cfg)
+ if err != nil {
+ t.Fatalf("create configured authority client: %v", err)
+ }
+
+ endpoints := []string{authority.URL, memberA.URL, memberB.URL}
+ cc := &ClusterClient{
+ name: "remote-cluster",
+ clients: map[string]*Client{authority.URL: authorityClient},
+ endpoints: endpoints,
+ endpointFingerprints: make(map[string]string),
+ nodeHealth: map[string]bool{
+ authority.URL: true,
+ memberA.URL: false,
+ memberB.URL: false,
+ },
+ lastHealthCheck: make(map[string]time.Time),
+ lastError: map[string]string{
+ memberA.URL: "Network unreachable - check network connectivity to Proxmox host",
+ memberB.URL: "Network unreachable - check network connectivity to Proxmox host",
+ },
+ config: cfg,
+ rateLimitUntil: make(map[string]time.Time),
+ }
+
+ snapshotResult := make(chan error, 1)
+ go func() {
+ snapshots, snapshotErr := cc.GetVMSnapshots(context.Background(), "node1", 100)
+ if snapshotErr == nil && (len(snapshots) != 1 || snapshots[0].Name != "snap-authority") {
+ snapshotErr = fmt.Errorf("unexpected authority snapshots: %+v", snapshots)
+ }
+ snapshotResult <- snapshotErr
+ }()
+
+ select {
+ case <-recoveryStarted:
+ // Recovery is actively blocked on a member-only address.
+ case <-time.After(2 * time.Second):
+ t.Fatal("member recovery did not start")
+ }
+
+ select {
+ case err := <-snapshotResult:
+ if err != nil {
+ t.Fatalf("snapshot polling through configured authority failed: %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("snapshot polling waited for unreachable member recovery")
+ }
+
+ health := cc.GetHealthStatus()
+ if !health[authority.URL] || health[memberA.URL] || health[memberB.URL] {
+ t.Fatalf("expected healthy authority with degraded member evidence, got %+v", health)
+ }
+
+ close(releaseRecovery)
+ recoveryReleased = true
+
+ deadline := time.Now().Add(2 * time.Second)
+ for {
+ health = cc.GetHealthStatus()
+ cc.mu.RLock()
+ recoveryDone := !cc.recoveryInProgress
+ cc.mu.RUnlock()
+ if health[memberA.URL] && health[memberB.URL] && recoveryDone {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("expected member refresh to recover both failovers, got %+v", health)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+
+ for i := 0; i < 20; i++ {
+ content, err := cc.GetStorageContent(context.Background(), "node1", "local")
+ if err != nil {
+ t.Fatalf("storage content poll %d failed: %v", i+1, err)
+ }
+ if len(content) != 1 {
+ t.Fatalf("storage content poll %d returned %+v", i+1, content)
+ }
+ }
+ if got := memberDataCalls.Load(); got != 0 {
+ t.Fatalf("expected recovered members to remain failovers, got %d member data calls", got)
+ }
+ if got := authorityDataCalls.Load(); got != 21 {
+ t.Fatalf("expected all API-only data from configured authority, got %d calls", got)
+ }
+}
+
func TestClusterClient_RecoverUnhealthyNodes(t *testing.T) {
var callCount int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {