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 large Proxmox cluster poll exhaustion

rcourtman44a3f1945435
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 366c37005d..f81cca453d 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -43,6 +43,15 @@ source-native `{instance}:{node}:{vmid}` IDs; a successful empty member
enumeration is authoritative and removes genuinely deleted guests. Collection
failure remains visible through source freshness/error state and must not be
converted into an authoritative empty inventory.
+Large Proxmox generations separate authoritative inventory from optional deep
+detail. The efficient poller must bound VM/LXC enrichment below the whole-cycle
+deadline, rotate the first enriched row across cycles, and still publish every
+non-template row returned by `cluster/resources` when that detail budget is
+exhausted. VM and LXC work share the bounded slots concurrently so one guest
+kind cannot permanently starve the other. Replication, storage, backup, and
+snapshot enrichment owns independent runtime-scoped budgets; exhaustion or
+cancellation of those optional tails must not turn a successfully enumerated
+PVE API connection into `unreachable`.
Running LXC filesystem detail may be supplemented by a node-local Unified
Agent report when the reporting host is securely linked to exactly one current
PVE node. Monitoring admits only bounded, normalized VMID/name/disk rows,
@@ -996,10 +1005,31 @@ only graft them onto fixture data.
response bodies containing permission-like text, recovery, caching, and
concurrent single-flight behavior under the race detector. Monitoring proof
must cover a healthy API-token poll without a `/nodes` request.
+16. Keep large-cluster Proxmox polling bounded without weakening inventory or
+ reachability truth. `cluster/resources` remains authoritative for the full
+ VM/LXC generation when optional detail runs out of budget, optional tail
+ collectors use runtime-scoped contexts, and only a failed core provider read
+ may make the PVE connection unreachable. Regression coverage lives in
+ `internal/monitoring/proxmox_large_cluster_poll_budget_test.go`,
+ `internal/monitoring/monitor_shutdown_additional_test.go`, and
+ `internal/monitoring/monitor_backups_dir_storage_test.go`.
## Current State
+### Large Proxmox generations preserve reachability under bounded enrichment
+
+The efficient PVE poll reserves a fixed tail of the scheduler deadline and
+spends at most sixty seconds on per-guest VM/LXC detail. Work begins at a
+rotating offset and both guest kinds share the worker pool concurrently. When
+the budget closes, builders retain the live `cluster/resources` rows under a
+canceled detail context, then publish one complete coherent generation.
+Replication runs asynchronously with its own ten-second runtime-scoped budget;
+storage and backup polls schedule against the monitor lifecycle rather than the
+completed cycle.
+The core poll therefore records success after an authoritative inventory even
+when those optional collectors time out independently.
+
### Local libvirt guests are bounded host-agent observations
Authenticated Linux host reports may carry a read-only libvirt inventory for
diff --git a/docs/release-control/v6/internal/subsystems/registry.json b/docs/release-control/v6/internal/subsystems/registry.json
index 18522232cc..e30454d8ba 100644
--- a/docs/release-control/v6/internal/subsystems/registry.json
+++ b/docs/release-control/v6/internal/subsystems/registry.json
@@ -5796,6 +5796,7 @@
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_pve_cluster_refresh_test.go",
"internal/monitoring/monitor_pve_guest_lxc_test.go",
+ "internal/monitoring/proxmox_large_cluster_poll_budget_test.go",
"internal/monitoring/pve_protection_observation_test.go",
"internal/monitoring/ratetracker_test.go",
"internal/monitoring/truenas_poller_test.go",
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 9831fb5daf..4fd44fdd3f 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -1116,7 +1116,7 @@ func TestProxmoxGuestDockerInventoryUsesCanonicalReportIngestPath(t *testing.T)
"ParseProxmoxGuestDockerInventoryVMIDs",
},
"monitor_pve_guest_poll.go": {
- "m.CollectProxmoxGuestDockerInventory(ctx, allContainers)",
+ "m.CollectProxmoxGuestDockerInventory(enrichmentCtx, allContainers)",
"m.state.UpdateGuestsForInstance(instanceName, allVMs, allContainers)",
},
"monitor_polling_containers.go": {
diff --git a/internal/monitoring/guest_agent_work.go b/internal/monitoring/guest_agent_work.go
index 35bdfd7fbb..e454d4c81e 100644
--- a/internal/monitoring/guest_agent_work.go
+++ b/internal/monitoring/guest_agent_work.go
@@ -21,7 +21,12 @@ func (m *Monitor) efficientQEMUWorkerCount(total int) int {
func (m *Monitor) acquireGuestAgentWorkSlot(ctx context.Context) bool {
if m == nil || m.guestAgentWorkSlots == nil {
- return true
+ select {
+ case <-ctx.Done():
+ return false
+ default:
+ return true
+ }
}
select {
case m.guestAgentWorkSlots <- struct{}{}:
diff --git a/internal/monitoring/monitor_backups.go b/internal/monitoring/monitor_backups.go
index 273e3c1201..3c9a1f9e05 100644
--- a/internal/monitoring/monitor_backups.go
+++ b/internal/monitoring/monitor_backups.go
@@ -2409,23 +2409,22 @@ func parseVzdumpJobLog(jobTask models.BackupTask, upid string, logLines []proxmo
}
func (m *Monitor) pollPVEBackupsAsync(
- ctx context.Context,
instanceName string,
instanceCfg *config.PVEInstance,
client PVEClientInterface,
nodes []proxmox.Node,
nodeEffectiveStatus map[string]string,
-) error {
+) {
// Poll backups if enabled - respect configured interval or cycle gating
if !instanceCfg.MonitorBackups {
- return nil
+ return
}
if !m.backupPollingEnabledSetting() {
log.Debug().
Str("instance", instanceName).
Msg("Skipping backup polling - globally disabled")
- return nil
+ return
}
now := time.Now()
@@ -2442,50 +2441,47 @@ func (m *Monitor) pollPVEBackupsAsync(
Str("reason", reason).
Msg("Skipping PVE backup polling this cycle")
}
- return nil
+ return
}
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- // Set initial timestamp before starting goroutine (prevents concurrent starts)
- m.mu.Lock()
- m.lastPVEBackupPoll[instanceName] = newLast
- m.mu.Unlock()
+ // Set initial timestamp before starting goroutine (prevents concurrent starts).
+ // This optional work owns a runtime-scoped timeout below; the completed core
+ // PVE generation must not be reclassified as unreachable merely because its
+ // per-cycle context expired before background scheduling.
+ m.mu.Lock()
+ m.lastPVEBackupPoll[instanceName] = newLast
+ m.mu.Unlock()
- // Run backup polling in a separate goroutine to avoid blocking real-time stats
- go func(startTime time.Time, inst string, pveClient PVEClientInterface) {
- defer recoverFromPanic(fmt.Sprintf("pollPVEBackups-%s", inst))
- timeout := m.calculateBackupOperationTimeout(inst)
- log.Info().
- Str("instance", inst).
- Dur("timeout", timeout).
- Msg("Starting background backup/snapshot polling")
-
- // The per-cycle ctx is canceled as soon as the main polling loop finishes,
- // so derive the backup poll context from the long-lived runtime context instead.
- parentCtx := m.getRuntimeContext()
- if parentCtx == nil {
- parentCtx = context.Background()
- }
+ // Run backup polling in a separate goroutine to avoid blocking real-time stats
+ go func(startTime time.Time, inst string, pveClient PVEClientInterface) {
+ defer recoverFromPanic(fmt.Sprintf("pollPVEBackups-%s", inst))
+ timeout := m.calculateBackupOperationTimeout(inst)
+ log.Info().
+ Str("instance", inst).
+ Dur("timeout", timeout).
+ Msg("Starting background backup/snapshot polling")
- m.pollPVEBackupsAndSnapshots(parentCtx, inst, pveClient, nodes, nodeEffectiveStatus, timeout)
+ // The per-cycle ctx is canceled as soon as the main polling loop finishes,
+ // so derive the backup poll context from the long-lived runtime context instead.
+ parentCtx := m.getRuntimeContext()
+ if parentCtx == nil {
+ parentCtx = context.Background()
+ }
- duration := time.Since(startTime)
- log.Info().
- Str("instance", inst).
- Dur("duration", duration).
- Msg("Completed background backup/snapshot polling")
+ m.pollPVEBackupsAndSnapshots(parentCtx, inst, pveClient, nodes, nodeEffectiveStatus, timeout)
- // Update timestamp after completion for accurate interval scheduling
- m.mu.Lock()
- m.lastPVEBackupPoll[inst] = time.Now()
- m.mu.Unlock()
- }(now, instanceName, client)
- }
+ duration := time.Since(startTime)
+ log.Info().
+ Str("instance", inst).
+ Dur("duration", duration).
+ Msg("Completed background backup/snapshot polling")
+
+ // Update timestamp after completion for accurate interval scheduling
+ m.mu.Lock()
+ m.lastPVEBackupPoll[inst] = time.Now()
+ m.mu.Unlock()
+ }(now, instanceName, client)
- return nil
}
// checkMockAlerts checks alerts for mock data
diff --git a/internal/monitoring/monitor_backups_dir_storage_test.go b/internal/monitoring/monitor_backups_dir_storage_test.go
index afe432cee5..89b2ecd213 100644
--- a/internal/monitoring/monitor_backups_dir_storage_test.go
+++ b/internal/monitoring/monitor_backups_dir_storage_test.go
@@ -221,3 +221,30 @@ func TestPollStorageBackups_Issue1639HarvestsPBSGuestConfirmations(t *testing.T)
}
}
}
+
+func TestPollPVEBackupsAsyncUsesRuntimeContextIndependentOfCycle(t *testing.T) {
+ runtimeCtx, cancelRuntime := context.WithCancel(context.Background())
+ cancelRuntime()
+ m := &Monitor{
+ state: models.NewState(),
+ runtimeCtx: runtimeCtx,
+ lastPVEBackupPoll: make(map[string]time.Time),
+ config: &config.Config{
+ EnableBackupPolling: true,
+ BackupPollingCycles: 1,
+ },
+ }
+ m.pollPVEBackupsAsync(
+ "cluster-a",
+ &config.PVEInstance{MonitorBackups: true},
+ &mockPVEClientExtra{},
+ nil,
+ map[string]string{},
+ )
+ m.mu.RLock()
+ scheduledAt := m.lastPVEBackupPoll["cluster-a"]
+ m.mu.RUnlock()
+ if scheduledAt.IsZero() {
+ t.Fatal("backup polling was not scheduled on the monitor runtime context")
+ }
+}
diff --git a/internal/monitoring/monitor_previous_state.go b/internal/monitoring/monitor_previous_state.go
index f7a03d6e4a..914198f941 100644
--- a/internal/monitoring/monitor_previous_state.go
+++ b/internal/monitoring/monitor_previous_state.go
@@ -11,6 +11,7 @@ type previousGuestContext struct {
vms []models.VM
vmsByID map[string]models.VM
containers []models.Container
+ containersByID map[string]models.Container
containerOCIByVMID map[int]bool
hostAgentsByVMID map[string]models.Host
}
@@ -20,6 +21,7 @@ func (m *Monitor) previousGuestContextForInstance(instanceName string) previousG
vms: make([]models.VM, 0),
vmsByID: make(map[string]models.VM),
containers: make([]models.Container, 0),
+ containersByID: make(map[string]models.Container),
containerOCIByVMID: make(map[int]bool),
hostAgentsByVMID: make(map[string]models.Host),
}
@@ -50,6 +52,13 @@ func (m *Monitor) previousGuestContextForInstance(instanceName string) previousG
}
container := previousContainerFromView(ct)
ctx.containers = append(ctx.containers, container)
+ if container.ID != "" {
+ ctx.containersByID[container.ID] = container
+ }
+ guestID := makeGuestID(container.Instance, container.Node, container.VMID)
+ if guestID != "" {
+ ctx.containersByID[guestID] = container
+ }
if container.VMID > 0 && (strings.EqualFold(strings.TrimSpace(container.Type), "oci") || container.IsOCI) {
ctx.containerOCIByVMID[container.VMID] = true
}
@@ -108,6 +117,7 @@ func previousVMFromView(vm *unifiedresources.VMView) models.VM {
OSName: vm.OSName(),
OSVersion: vm.OSVersion(),
AgentVersion: vm.AgentVersion(),
+ Lock: vm.Lock(),
Disk: models.Disk{
Used: vm.DiskUsed(),
Total: vm.DiskTotal(),
@@ -129,15 +139,23 @@ func previousContainerFromView(ct *unifiedresources.ContainerView) models.Contai
node := ct.Node()
vmid := ct.VMID()
return models.Container{
- ID: makeGuestID(instance, node, vmid),
- Instance: instance,
- Node: node,
- VMID: vmid,
- Name: ct.Name(),
- Status: ct.RuntimeStatus(),
- Type: ct.ContainerType(),
- IsOCI: ct.IsOCI(),
- LastSeen: ct.LastSeen(),
+ ID: makeGuestID(instance, node, vmid),
+ Instance: instance,
+ Node: node,
+ VMID: vmid,
+ Name: ct.Name(),
+ Status: ct.RuntimeStatus(),
+ Type: ct.ContainerType(),
+ IsOCI: ct.IsOCI(),
+ LastSeen: ct.LastSeen(),
+ IPAddresses: ct.IPAddresses(),
+ NetworkInterfaces: guestNetworkInterfacesFromReadStateView(ct.NetworkInterfaces()),
+ OSName: ct.OSName(),
+ OSTemplate: ct.OSTemplate(),
+ HasDocker: ct.HasDocker(),
+ DockerCheckedAt: ct.DockerCheckedAt(),
+ Disks: guestDisksFromReadStateView(ct.Disks()),
+ Lock: ct.Lock(),
Memory: models.Memory{
Used: ct.MemoryUsed(),
Total: ct.MemoryTotal(),
diff --git a/internal/monitoring/monitor_pve.go b/internal/monitoring/monitor_pve.go
index 24f447e1e3..4c0d90a8b8 100644
--- a/internal/monitoring/monitor_pve.go
+++ b/internal/monitoring/monitor_pve.go
@@ -1520,15 +1520,8 @@ func (m *Monitor) pollPVEInstance(ctx context.Context, instanceName string, clie
// Update cluster endpoint online status if this is a cluster
m.updateClusterEndpointStatus(instanceName, instanceCfg, client, modelNodes)
- if err := m.pollStorageAsync(ctx, instanceName, instanceCfg, client, nodes); err != nil {
- pollErr = err
- return
- }
-
- if err := m.pollPVEBackupsAsync(ctx, instanceName, instanceCfg, client, nodes, nodeEffectiveStatus); err != nil {
- pollErr = err
- return
- }
+ m.pollStorageAsync(instanceName, instanceCfg, client, nodes)
+ m.pollPVEBackupsAsync(instanceName, instanceCfg, client, nodes, nodeEffectiveStatus)
}
func copyFloatPointer(src *float64) *float64 {
diff --git a/internal/monitoring/monitor_pve_guest_poll.go b/internal/monitoring/monitor_pve_guest_poll.go
index fcc97e2cf1..879035d7cc 100644
--- a/internal/monitoring/monitor_pve_guest_poll.go
+++ b/internal/monitoring/monitor_pve_guest_poll.go
@@ -10,6 +10,31 @@ import (
"github.com/rs/zerolog/log"
)
+const (
+ // Deep guest detail is deliberately bounded below the whole PVE poll
+ // deadline. The authoritative cluster/resources generation can contain
+ // hundreds of guests; reserving the tail keeps connection-health
+ // publication from inheriting an exhausted context.
+ pveGuestEnrichmentMaxDuration = 60 * time.Second
+ pvePollTailReserve = 15 * time.Second
+)
+
+func pveGuestEnrichmentContext(ctx context.Context) (context.Context, context.CancelFunc) {
+ budget := pveGuestEnrichmentMaxDuration
+ if deadline, ok := ctx.Deadline(); ok {
+ available := time.Until(deadline) - pvePollTailReserve
+ if available <= 0 {
+ boundedCtx, cancel := context.WithCancel(ctx)
+ cancel()
+ return boundedCtx, func() {}
+ }
+ if available < budget {
+ budget = available
+ }
+ }
+ return context.WithTimeout(ctx, budget)
+}
+
// pollVMsAndContainersEfficient uses the cluster/resources endpoint to get all VMs and containers in one call
// This works on both clustered and standalone nodes for efficient polling
// When the instance is part of a cluster, the cluster name is used for guest IDs to prevent duplicates
@@ -29,17 +54,20 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
return false
}
m.updatePVEBackupTemplateSubjectsFromClusterResources(instanceName, resources)
+ enrichmentCtx, cancelEnrichment := pveGuestEnrichmentContext(ctx)
+ defer cancelEnrichment()
// Capture previous guest state once per poll cycle so fallback and grace-period
// behavior is based on a consistent pre-poll snapshot.
prevGuests := m.previousGuestContextForInstance(instanceName)
allVMs, allContainers := m.collectGuestsFromClusterResources(
- ctx,
+ enrichmentCtx,
instanceName,
resources,
client,
prevGuests.containerOCIByVMID,
+ prevGuests.containersByID,
prevGuests.vmsByID,
prevGuests.hostAgentsByVMID,
)
@@ -47,8 +75,8 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
allVMs, allContainers = m.preserveGuestsForGracePeriod(instanceName, resources, prevGuests.vms, prevGuests.containers, nodeEffectiveStatus, allVMs, allContainers)
// Check Docker presence for containers that need it (new, restarted, started)
- allContainers = m.CheckContainersForDocker(ctx, allContainers)
- m.CollectProxmoxGuestDockerInventory(ctx, allContainers)
+ allContainers = m.CheckContainersForDocker(enrichmentCtx, allContainers)
+ m.CollectProxmoxGuestDockerInventory(enrichmentCtx, allContainers)
// Publish the complete guest generation only after both VM and container
// collection/enrichment has finished. Empty authoritative results still
@@ -57,7 +85,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
m.recordGuestMetrics(allVMs, allContainers, cycleStart)
- m.pollReplicationStatus(ctx, instanceName, client, allVMs)
+ m.pollReplicationStatusAsync(instanceName, client, allVMs)
log.Debug().
Str("instance", instanceName).
@@ -74,12 +102,14 @@ func (m *Monitor) collectGuestsFromClusterResources(
resources []proxmox.ClusterResource,
client PVEClientInterface,
prevContainerIsOCI map[int]bool,
+ prevContainerByID map[string]models.Container,
prevVMByID map[string]models.VM,
vmIDToHostAgent map[string]models.Host,
) ([]models.VM, []models.Container) {
allVMs := make([]models.VM, 0, len(resources))
allContainers := make([]models.Container, 0, len(resources))
vmResources := make([]indexedClusterResource, 0, len(resources))
+ containerResources := make([]indexedClusterResource, 0, len(resources))
for _, res := range resources {
// Generate canonical guest ID: instance:node:vmid
@@ -101,17 +131,33 @@ func (m *Monitor) collectGuestsFromClusterResources(
guestID: guestID,
})
case "lxc":
- container, ok := m.handleClusterContainerResource(ctx, instanceName, res, guestID, client, prevContainerIsOCI)
- if !ok {
- continue
- }
- allContainers = append(allContainers, container)
+ containerResources = append(containerResources, indexedClusterResource{
+ order: len(containerResources),
+ resource: res,
+ guestID: guestID,
+ })
}
}
+ // Let VM and LXC detail compete fairly for the shared enrichment slots.
+ // Running one type to completion first can consume the entire bounded budget
+ // on a large mixed cluster and permanently starve the other type.
+ var collectionWG sync.WaitGroup
+ if len(containerResources) > 0 {
+ collectionWG.Add(1)
+ go func() {
+ defer collectionWG.Done()
+ allContainers = m.collectClusterContainerResources(ctx, instanceName, containerResources, client, prevContainerIsOCI, prevContainerByID)
+ }()
+ }
if len(vmResources) > 0 {
- allVMs = append(allVMs, m.collectClusterVMResources(ctx, instanceName, vmResources, client, prevVMByID, vmIDToHostAgent)...)
+ collectionWG.Add(1)
+ go func() {
+ defer collectionWG.Done()
+ allVMs = m.collectClusterVMResources(ctx, instanceName, vmResources, client, prevVMByID, vmIDToHostAgent)
+ }()
}
+ collectionWG.Wait()
return allVMs, allContainers
}
@@ -128,6 +174,122 @@ type clusterVMResourceResult struct {
ok bool
}
+func rotatingResourceOffset(total int) int {
+ if total <= 1 {
+ return 0
+ }
+ return int(uint64(time.Now().UnixNano()) % uint64(total))
+}
+
+func preserveVMOptionalEnrichment(current models.VM, previous *models.VM) models.VM {
+ if previous == nil {
+ return current
+ }
+ if len(current.IPAddresses) == 0 {
+ current.IPAddresses = cloneStringSlice(previous.IPAddresses)
+ }
+ if len(current.NetworkInterfaces) == 0 {
+ current.NetworkInterfaces = cloneGuestNetworkInterfaces(previous.NetworkInterfaces)
+ }
+ if current.OSName == "" {
+ current.OSName = previous.OSName
+ }
+ if current.OSVersion == "" {
+ current.OSVersion = previous.OSVersion
+ }
+ if current.AgentVersion == "" {
+ current.AgentVersion = previous.AgentVersion
+ }
+ if len(current.Disks) == 0 {
+ current.Disks = cloneGuestDisks(previous.Disks)
+ }
+ if current.OnBoot == nil && previous.OnBoot != nil {
+ onBoot := *previous.OnBoot
+ current.OnBoot = &onBoot
+ }
+ if current.Lock == "" {
+ current.Lock = previous.Lock
+ }
+ return current
+}
+
+func preserveContainerOptionalEnrichment(current models.Container, previous *models.Container) models.Container {
+ if previous == nil {
+ return current
+ }
+ if len(current.IPAddresses) == 0 {
+ current.IPAddresses = cloneStringSlice(previous.IPAddresses)
+ }
+ if len(current.NetworkInterfaces) == 0 {
+ current.NetworkInterfaces = cloneGuestNetworkInterfaces(previous.NetworkInterfaces)
+ }
+ if current.OSName == "" {
+ current.OSName = previous.OSName
+ }
+ if current.OSTemplate == "" {
+ current.OSTemplate = previous.OSTemplate
+ }
+ if len(current.Disks) == 0 {
+ current.Disks = cloneGuestDisks(previous.Disks)
+ }
+ if current.OnBoot == nil && previous.OnBoot != nil {
+ onBoot := *previous.OnBoot
+ current.OnBoot = &onBoot
+ }
+ if current.DockerCheckedAt.IsZero() {
+ current.HasDocker = previous.HasDocker
+ current.DockerCheckedAt = previous.DockerCheckedAt
+ }
+ if current.Lock == "" {
+ current.Lock = previous.Lock
+ }
+ return current
+}
+
+func (m *Monitor) collectClusterContainerResources(
+ ctx context.Context,
+ instanceName string,
+ resources []indexedClusterResource,
+ client PVEClientInterface,
+ prevContainerIsOCI map[int]bool,
+ prevContainerByID map[string]models.Container,
+) []models.Container {
+ orderedContainers := make([]models.Container, len(resources))
+ orderedOK := make([]bool, len(resources))
+ offset := rotatingResourceOffset(len(resources))
+
+ for i := range resources {
+ entry := resources[(offset+i)%len(resources)]
+ var container models.Container
+ var ok bool
+ ran := m.runGuestAgentVMWork(ctx, func(workCtx context.Context) {
+ container, ok = m.handleClusterContainerResource(workCtx, instanceName, entry.resource, entry.guestID, client, prevContainerIsOCI)
+ })
+ if !ran {
+ // The enrichment budget is exhausted, but cluster/resources is still
+ // authoritative inventory. A canceled context makes remote detail
+ // calls fail immediately while the builder retains the base row.
+ container, ok = m.handleClusterContainerResource(ctx, instanceName, entry.resource, entry.guestID, client, prevContainerIsOCI)
+ }
+ if ctx.Err() != nil {
+ previous := prevContainerByID[entry.guestID]
+ container = preserveContainerOptionalEnrichment(container, &previous)
+ }
+ if ok {
+ orderedContainers[entry.order] = container
+ orderedOK[entry.order] = true
+ }
+ }
+
+ containers := make([]models.Container, 0, len(resources))
+ for i, ok := range orderedOK {
+ if ok {
+ containers = append(containers, orderedContainers[i])
+ }
+ }
+ return containers
+}
+
func (m *Monitor) collectClusterVMResources(
ctx context.Context,
instanceName string,
@@ -160,15 +322,30 @@ func (m *Monitor) collectClusterVMResources(
}
})
if !ran {
- result = clusterVMResourceResult{order: entry.order, ok: false}
+ // Do not turn an exhausted detail budget into missing inventory.
+ // Re-run only the builder with the canceled context so it emits the
+ // current cluster/resources row without remote enrichment.
+ var prevVM *models.VM
+ if prev, ok := prevVMByID[entry.guestID]; ok {
+ prevVM = &prev
+ }
+ vm, ok := m.handleClusterVMResource(ctx, instanceName, entry.resource, entry.guestID, client, prevVM, vmIDToHostAgent)
+ result = clusterVMResourceResult{order: entry.order, vm: vm, ok: ok}
+ }
+ if ctx.Err() != nil && result.ok {
+ previous, exists := prevVMByID[entry.guestID]
+ if exists {
+ result.vm = preserveVMOptionalEnrichment(result.vm, &previous)
+ }
}
resultCh <- result
}
}()
}
- for _, entry := range resources {
- jobCh <- entry
+ offset := rotatingResourceOffset(len(resources))
+ for i := range resources {
+ jobCh <- resources[(offset+i)%len(resources)]
}
close(jobCh)
diff --git a/internal/monitoring/monitor_pve_replication.go b/internal/monitoring/monitor_pve_replication.go
index 947016981b..e5a3429f5b 100644
--- a/internal/monitoring/monitor_pve_replication.go
+++ b/internal/monitoring/monitor_pve_replication.go
@@ -12,6 +12,22 @@ import (
"github.com/rs/zerolog/log"
)
+const pveReplicationPollTimeout = 10 * time.Second
+
+func (m *Monitor) pollReplicationStatusAsync(instanceName string, client PVEClientInterface, vms []models.VM) {
+ parentCtx := m.getRuntimeContext()
+ if parentCtx == nil {
+ parentCtx = context.Background()
+ }
+ guestSnapshot := append([]models.VM(nil), vms...)
+ go func() {
+ defer recoverFromPanic(fmt.Sprintf("pollReplicationStatus-%s", instanceName))
+ ctx, cancel := context.WithTimeout(parentCtx, pveReplicationPollTimeout)
+ defer cancel()
+ m.pollReplicationStatus(ctx, instanceName, client, guestSnapshot)
+ }()
+}
+
// pollReplicationStatus polls storage replication jobs for a PVE instance.
func (m *Monitor) pollReplicationStatus(ctx context.Context, instanceName string, client PVEClientInterface, vms []models.VM) {
log.Debug().Str("instance", instanceName).Msg("polling replication status")
diff --git a/internal/monitoring/monitor_pve_storage.go b/internal/monitoring/monitor_pve_storage.go
index 0b49ad486a..a47c41c80c 100644
--- a/internal/monitoring/monitor_pve_storage.go
+++ b/internal/monitoring/monitor_pve_storage.go
@@ -253,42 +253,32 @@ func (m *Monitor) applyStorageFallbackAndRecordNodeMetrics(
}
func (m *Monitor) pollStorageAsync(
- ctx context.Context,
instanceName string,
instanceCfg *config.PVEInstance,
client PVEClientInterface,
nodes []proxmox.Node,
-) error {
+) {
// Poll storage in background if enabled - storage APIs can be slow (NFS mounts, etc.)
// so we run this asynchronously to prevent it from causing task timeouts.
// This is similar to how backup polling runs in the background.
if !instanceCfg.MonitorStorage {
- return nil
+ return
}
- select {
- case <-ctx.Done():
- return ctx.Err()
- default:
- go func(inst string, pveClient PVEClientInterface, nodeList []proxmox.Node) {
- defer recoverFromPanic(fmt.Sprintf("pollStorageWithNodes-%s", inst))
-
- // Use a generous timeout for storage polling - it's not blocking the main task
- storageTimeout := 60 * time.Second
- // Use monitor lifecycle context so shutdown can interrupt detached async polling.
- parentCtx := m.getRuntimeContext()
- if parentCtx == nil {
- parentCtx = ctx
- }
- if parentCtx == nil {
- parentCtx = context.Background()
- }
- storageCtx, storageCancel := context.WithTimeout(parentCtx, storageTimeout)
- defer storageCancel()
+ go func(inst string, pveClient PVEClientInterface, nodeList []proxmox.Node) {
+ defer recoverFromPanic(fmt.Sprintf("pollStorageWithNodes-%s", inst))
- m.pollStorageWithNodes(storageCtx, inst, pveClient, nodeList)
- }(instanceName, client, nodes)
- }
+ // Use a generous timeout for storage polling - it's not blocking the main task
+ storageTimeout := 60 * time.Second
+ // Use monitor lifecycle context so shutdown can interrupt detached async polling.
+ parentCtx := m.getRuntimeContext()
+ if parentCtx == nil {
+ parentCtx = context.Background()
+ }
+ storageCtx, storageCancel := context.WithTimeout(parentCtx, storageTimeout)
+ defer storageCancel()
+
+ m.pollStorageWithNodes(storageCtx, inst, pveClient, nodeList)
+ }(instanceName, client, nodes)
- return nil
}
diff --git a/internal/monitoring/monitor_shutdown_additional_test.go b/internal/monitoring/monitor_shutdown_additional_test.go
index 3a43ac5ddc..76c3f606e5 100644
--- a/internal/monitoring/monitor_shutdown_additional_test.go
+++ b/internal/monitoring/monitor_shutdown_additional_test.go
@@ -70,9 +70,7 @@ func TestPollStorageAsync_UsesRuntimeContextForShutdown(t *testing.T) {
MonitorStorage: true,
}
- if err := monitor.pollStorageAsync(context.Background(), "inst", instanceCfg, client, nil); err != nil {
- t.Fatalf("pollStorageAsync() error = %v", err)
- }
+ monitor.pollStorageAsync("inst", instanceCfg, client, nil)
waitForSignal(t, client.allStorageCalled, time.Second, "expected async storage polling goroutine to call GetAllStorage")
diff --git a/internal/monitoring/proxmox_large_cluster_poll_budget_test.go b/internal/monitoring/proxmox_large_cluster_poll_budget_test.go
new file mode 100644
index 0000000000..246030f7eb
--- /dev/null
+++ b/internal/monitoring/proxmox_large_cluster_poll_budget_test.go
@@ -0,0 +1,220 @@
+package monitoring
+
+import (
+ "context"
+ "fmt"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+type largeClusterBudgetClient struct {
+ *stubPVEClient
+ resources []proxmox.ClusterResource
+ vmStatusCalls atomic.Int64
+ containerStatusCalls atomic.Int64
+}
+
+const largeClusterGuestCount = 500
+
+func largeClusterResources() []proxmox.ClusterResource {
+ resources := make([]proxmox.ClusterResource, 0, largeClusterGuestCount)
+ for i := 0; i < largeClusterGuestCount; i++ {
+ guestType := "qemu"
+ if i%5 == 0 {
+ guestType = "lxc"
+ }
+ resources = append(resources, proxmox.ClusterResource{
+ Type: guestType,
+ Node: fmt.Sprintf("node-%d", i%7),
+ VMID: 1000 + i,
+ Name: fmt.Sprintf("vm-%d", i),
+ Status: "running",
+ MaxCPU: 2,
+ MaxMem: 2 * 1024 * 1024 * 1024,
+ MaxDisk: 32 * 1024 * 1024 * 1024,
+ })
+ }
+ return resources
+}
+
+func (c *largeClusterBudgetClient) GetClusterResources(context.Context, string) ([]proxmox.ClusterResource, error) {
+ return c.resources, nil
+}
+
+func (c *largeClusterBudgetClient) GetVMStatus(ctx context.Context, _ string, _ int) (*proxmox.VMStatus, error) {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ default:
+ c.vmStatusCalls.Add(1)
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+}
+
+func (c *largeClusterBudgetClient) GetContainerStatus(ctx context.Context, _ string, _ int) (*proxmox.Container, error) {
+ select {
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ default:
+ c.containerStatusCalls.Add(1)
+ <-ctx.Done()
+ return nil, ctx.Err()
+ }
+}
+
+func TestLargePVEClusterPublishesCompleteGenerationWhenEnrichmentBudgetExpires(t *testing.T) {
+ monitor := newTestPVEMonitor("large-cluster")
+ defer monitor.alertManager.Stop()
+ defer monitor.notificationMgr.Stop()
+ monitor.guestAgentWorkSlots = make(chan struct{}, defaultGuestAgentVMMaxConcurrent)
+ monitor.state.UpdateGuestsForInstance(
+ "large-cluster",
+ []models.VM{{
+ ID: "large-cluster:node-1:1001",
+ VMID: 1001,
+ Name: "vm-1",
+ Node: "node-1",
+ Instance: "large-cluster",
+ Status: "running",
+ IPAddresses: []string{"10.0.0.11"},
+ OSName: "Debian",
+ AgentVersion: "1.2.3",
+ }},
+ []models.Container{{
+ ID: "large-cluster:node-0:1000",
+ VMID: 1000,
+ Name: "vm-0",
+ Node: "node-0",
+ Instance: "large-cluster",
+ Status: "running",
+ IPAddresses: []string{"10.0.0.10"},
+ OSName: "Ubuntu",
+ HasDocker: true,
+ DockerCheckedAt: time.Now(),
+ }},
+ )
+
+ client := &largeClusterBudgetClient{
+ stubPVEClient: &stubPVEClient{},
+ resources: largeClusterResources(),
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 40*time.Millisecond)
+ defer cancel()
+
+ started := time.Now()
+ err := monitor.pollGuestsWithFallback(
+ ctx,
+ "large-cluster",
+ &config.PVEInstance{MonitorVMs: true, MonitorContainers: true},
+ client,
+ nil,
+ map[string]string{},
+ )
+ if err != nil {
+ t.Fatalf("pollGuestsWithFallback() error = %v", err)
+ }
+ if elapsed := time.Since(started); elapsed > time.Second {
+ t.Fatalf("bounded guest poll took %v, want under 1s", elapsed)
+ }
+
+ snapshot := monitor.GetState()
+ if got := len(snapshot.VMs); got != 400 {
+ t.Fatalf("published VM generation has %d guests, want 400", got)
+ }
+ if got := len(snapshot.Containers); got != 100 {
+ t.Fatalf("published container generation has %d guests, want 100", got)
+ }
+ if got := client.vmStatusCalls.Load(); got != 0 {
+ t.Fatalf("expired enrichment budget made %d VM detail calls, want 0", got)
+ }
+ if got := client.containerStatusCalls.Load(); got != 0 {
+ t.Fatalf("expired enrichment budget made %d container detail calls, want 0", got)
+ }
+ for i, vm := range snapshot.VMs {
+ if vm.ID == "" || vm.VMID == 0 || vm.Instance != "large-cluster" {
+ t.Fatalf("VM %d lost authoritative cluster identity: %+v", i, vm)
+ }
+ }
+ if vm := findVMByID(snapshot.VMs, 1001); vm == nil || len(vm.IPAddresses) != 1 || vm.OSName != "Debian" || vm.AgentVersion != "1.2.3" {
+ t.Fatalf("budgeted VM lost previous optional enrichment: %+v", vm)
+ }
+ if container := findContainerByID(snapshot.Containers, 1000); container == nil || len(container.IPAddresses) != 1 || container.OSName != "Ubuntu" || !container.HasDocker {
+ t.Fatalf("budgeted container lost previous optional enrichment: %+v", container)
+ }
+}
+
+func findVMByID(vms []models.VM, vmid int) *models.VM {
+ for i := range vms {
+ if vms[i].VMID == vmid {
+ return &vms[i]
+ }
+ }
+ return nil
+}
+
+func findContainerByID(containers []models.Container, vmid int) *models.Container {
+ for i := range containers {
+ if containers[i].VMID == vmid {
+ return &containers[i]
+ }
+ }
+ return nil
+}
+
+func TestLargePVEClusterCoreSuccessKeepsConnectionHealthy(t *testing.T) {
+ nodes := make([]proxmox.Node, 0, 7)
+ for i := 0; i < 7; i++ {
+ nodes = append(nodes, proxmox.Node{Node: fmt.Sprintf("node-%d", i), Status: "online"})
+ }
+ client := &largeClusterBudgetClient{
+ stubPVEClient: &stubPVEClient{nodes: nodes, nodeStatus: &proxmox.NodeStatus{}},
+ resources: largeClusterResources(),
+ }
+ monitor := newTestPVEMonitor("large-cluster")
+ defer monitor.alertManager.Stop()
+ defer monitor.notificationMgr.Stop()
+ monitor.guestAgentWorkSlots = make(chan struct{}, defaultGuestAgentVMMaxConcurrent)
+ monitor.config.PVEInstances[0].MonitorVMs = true
+ monitor.config.PVEInstances[0].MonitorContainers = true
+
+ ctx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond)
+ defer cancel()
+ monitor.pollPVEInstance(ctx, "large-cluster", client)
+
+ key := schedulerKey(InstanceTypePVE, "large-cluster")
+ monitor.mu.RLock()
+ status := monitor.pollStatusMap[key]
+ monitor.mu.RUnlock()
+ if status == nil {
+ t.Fatal("PVE poll did not record connection health")
+ }
+ if status.LastSuccess.IsZero() || !status.LastErrorAt.IsZero() || status.LastErrorMessage != "" {
+ t.Fatalf("core inventory was not recorded as healthy: %+v", *status)
+ }
+ snapshot := monitor.GetState()
+ if got := len(snapshot.VMs) + len(snapshot.Containers); got != largeClusterGuestCount {
+ t.Fatalf("published generation has %d guests, want %d", got, largeClusterGuestCount)
+ }
+}
+
+func TestPVEGuestEnrichmentBudgetReservesPollTail(t *testing.T) {
+ parent, cancelParent := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancelParent()
+
+ bounded, cancelBounded := pveGuestEnrichmentContext(parent)
+ defer cancelBounded()
+ deadline, ok := bounded.Deadline()
+ if !ok {
+ t.Fatal("enrichment context has no deadline")
+ }
+ remaining := time.Until(deadline)
+ if remaining < 59*time.Second || remaining > pveGuestEnrichmentMaxDuration {
+ t.Fatalf("enrichment budget = %v, want approximately %v", remaining, pveGuestEnrichmentMaxDuration)
+ }
+}
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index 0bebe97fc2..769c694a21 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -310,6 +310,7 @@ class CanonicalCompletionGuardTest(unittest.TestCase):
"internal/monitoring/monitor_host_agents_test.go",
"internal/monitoring/monitor_pve_cluster_refresh_test.go",
"internal/monitoring/monitor_pve_guest_lxc_test.go",
+ "internal/monitoring/proxmox_large_cluster_poll_budget_test.go",
"internal/monitoring/pve_protection_observation_test.go",
"internal/monitoring/ratetracker_test.go",
"internal/monitoring/truenas_poller_test.go",