Files
Pulse/internal/monitoring/monitor_polling_vm.go
rcourtman 91ceaa0ece Keep unread VM disks out of fallback History
When cluster/resources is unavailable, the per-node VM collector wrote
vm.Disk.Usage straight to History. A retained prev- reading looked like a
new sample, and a guest whose status read failed got its cluster allocation
recorded as filesystem usage. The efficient route already refused both.

The collector now calls recordGuestMetrics, so both routes share one rule
instead of two loops. Memory had no matching gap: the builder annotates
every VM's memory, so the only check the fallback lacked, for unannotated
memory, cannot fire on a guest it just polled.

The mock-mode source pin needed that loop to stay in this file. A test now
runs both real collectors in mock mode instead.
2026-11-04 21:27:36 +00:00

140 lines
4.2 KiB
Go

package monitoring
import (
"context"
"sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring/errors"
"github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
"github.com/rs/zerolog/log"
)
func (m *Monitor) collectVMsWithNodes(ctx context.Context, instanceName string, clusterName string, isCluster bool, client PVEClientInterface, nodes []proxmox.Node, nodeEffectiveStatus map[string]string) []models.VM {
startTime := time.Now()
type nodeResult struct {
node string
vms []models.VM
templateSubjects map[string]struct{}
err error
}
resultChan := make(chan nodeResult, len(nodes))
var wg sync.WaitGroup
onlineNodes := 0
for _, node := range nodes {
if nodeEffectiveStatus[node.Node] == "online" {
onlineNodes++
}
}
prevGuests := m.previousGuestContextForInstance(instanceName)
prevVMByID := prevGuests.vmsByID
vmIDToHostAgent := prevGuests.hostAgentsByVMID
log.Debug().
Str("instance", instanceName).
Int("totalNodes", len(nodes)).
Int("onlineNodes", onlineNodes).
Msg("Starting parallel VM polling")
for _, node := range nodes {
if nodeEffectiveStatus[node.Node] != "online" {
log.Debug().
Str("node", node.Node).
Str("status", node.Status).
Msg("Skipping offline node for VM polling")
continue
}
wg.Add(1)
go func(n proxmox.Node) {
defer wg.Done()
nodeStart := time.Now()
vms, err := client.GetVMs(ctx, n.Node)
if err != nil {
monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_vms", instanceName, err).WithNode(n.Node)
log.Error().Err(monErr).Str("node", n.Node).Msg("failed to get VMs; deferring node poll until next cycle")
resultChan <- nodeResult{node: n.Node, err: err}
return
}
nodeVMs, nodeTemplateSubjects := m.pollNodeVMsWithClusterResourceBuilder(ctx, instanceName, n.Node, vms, client, prevVMByID, vmIDToHostAgent)
nodeDuration := time.Since(nodeStart)
log.Debug().
Str("node", n.Node).
Int("vms", len(nodeVMs)).
Dur("duration", nodeDuration).
Msg("Node VM polling completed")
resultChan <- nodeResult{node: n.Node, vms: nodeVMs, templateSubjects: nodeTemplateSubjects}
}(node)
}
go func() {
wg.Wait()
close(resultChan)
}()
var allVMs []models.VM
qemuTemplateSubjects := make(map[string]struct{})
successfulNodes := 0
failedNodes := 0
failedNodeNames := make(map[string]struct{})
for result := range resultChan {
if result.err != nil {
failedNodes++
failedNodeNames[result.node] = struct{}{}
continue
}
successfulNodes++
allVMs = append(allVMs, result.vms...)
for key := range result.templateSubjects {
qemuTemplateSubjects[key] = struct{}{}
}
}
if failedNodes == 0 && successfulNodes > 0 {
stagePVEGuestEffect(ctx, func() { m.updatePVEBackupTemplateSubjectsForType(instanceName, "qemu", qemuTemplateSubjects) })
}
preservedVMs := 0
if len(failedNodeNames) > 0 {
retained, _ := m.retainedGuestsForFailedNodes(instanceName, failedNodeNames, prevGuests)
allVMs = append(allVMs, retained...)
preservedVMs = len(retained)
}
if preservedVMs > 0 {
log.Warn().
Str("instance", instanceName).
Int("preservedVMs", preservedVMs).
Int("failedNodes", failedNodes).
Msg("Preserved prior VMs for nodes whose enumeration failed")
}
stagePVEGuestEffect(ctx, func() { m.recordGuestMetrics(allVMs, nil, startTime) })
duration := time.Since(startTime)
log.Debug().
Str("instance", instanceName).
Int("totalVMs", len(allVMs)).
Int("successfulNodes", successfulNodes).
Int("failedNodes", failedNodes).
Dur("duration", duration).
Msg("Parallel VM polling completed")
return allVMs
}
// pollVMsWithNodes retains the focused single-kind polling entry point used by
// tests and maintenance callers. The production guest cycle uses
// collectVMsWithNodes and publishes both guest kinds atomically.
func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clusterName string, isCluster bool, client PVEClientInterface, nodes []proxmox.Node, nodeEffectiveStatus map[string]string) {
vms := m.collectVMsWithNodes(ctx, instanceName, clusterName, isCluster, client, nodes, nodeEffectiveStatus)
m.state.UpdateVMsForInstance(instanceName, vms)
}