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(monitoring): smooth transient VM memory fallback spikes

rcourtmand05a00b9318f
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 86f88185e0..cf190cf218 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -7231,7 +7231,9 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
// guest agent call fails (prevents disk usage flickering 57% → 0% → 57%).
// Refs: #1319
prevDiskByGuestID := make(map[string]models.Disk, len(prevInstanceVMs))
+ prevVMByGuestID := make(map[string]models.VM, len(prevInstanceVMs))
for _, pvm := range prevInstanceVMs {
+ prevVMByGuestID[pvm.ID] = pvm
if pvm.Disk.Usage > 0 {
prevDiskByGuestID[pvm.ID] = pvm.Disk
}
@@ -7832,12 +7834,59 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
memUsed = memTotal
}
- memFree := uint64(0)
- if memTotal >= memUsed {
- memFree = memTotal - memUsed
+ sampleTime := time.Now()
+ var memory models.Memory
+ snapshotNotes := []string(nil)
+ if prev, ok := prevVMByGuestID[guestID]; ok &&
+ shouldCarryForwardPreviousVMMemory(prev, res.Status, memorySource, memTotal, memUsed, sampleTime) {
+ fallbackSource := memorySource
+ memory = prev.Memory
+ if detailedStatus != nil && detailedStatus.Balloon > 0 {
+ memory.Balloon = int64(detailedStatus.Balloon)
+ }
+ memorySource = "previous-snapshot"
+ snapshotNotes = append(snapshotNotes, "preserved-previous-memory-after-low-trust-fallback")
+ log.Debug().
+ Str("instance", instanceName).
+ Str("vm", res.Name).
+ Int("vmid", res.VMID).
+ Str("previousSource", prev.MemorySource).
+ Str("fallbackSource", fallbackSource).
+ Float64("previousUsage", prev.Memory.Usage).
+ Float64("fallbackUsage", safePercentage(float64(memUsed), float64(memTotal))).
+ Msg("Preserving previous VM memory metrics after low-trust fallback")
+ } else {
+ memFree := uint64(0)
+ if memTotal >= memUsed {
+ memFree = memTotal - memUsed
+ }
+
+ memoryUsage := safePercentage(float64(memUsed), float64(memTotal))
+ memory = models.Memory{
+ Total: int64(memTotal),
+ Used: int64(memUsed),
+ Free: int64(memFree),
+ Usage: memoryUsage,
+ }
+ if memory.Free < 0 {
+ memory.Free = 0
+ }
+ if memory.Used > memory.Total {
+ memory.Used = memory.Total
+ }
+ // Derive reclaimable cache: the difference between "available" memory
+ // (what the OS can reclaim) and "truly free" memory (unused pages).
+ // This lets the frontend show a split bar: used | cache | free.
+ if memRawFree > 0 && memFree > memRawFree {
+ memory.Cache = int64(memFree - memRawFree)
+ // Adjust Free to reflect truly free pages, not available
+ memory.Free = int64(memRawFree)
+ }
+ if detailedStatus != nil && detailedStatus.Balloon > 0 {
+ memory.Balloon = int64(detailedStatus.Balloon)
+ }
}
- sampleTime := time.Now()
currentMetrics := IOMetrics{
DiskRead: diskReadBytes,
DiskWrite: diskWriteBytes,
@@ -7847,31 +7896,6 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
}
diskReadRate, diskWriteRate, netInRate, netOutRate := m.rateTracker.CalculateRates(guestID, currentMetrics)
- memoryUsage := safePercentage(float64(memUsed), float64(memTotal))
- memory := models.Memory{
- Total: int64(memTotal),
- Used: int64(memUsed),
- Free: int64(memFree),
- Usage: memoryUsage,
- }
- if memory.Free < 0 {
- memory.Free = 0
- }
- if memory.Used > memory.Total {
- memory.Used = memory.Total
- }
- // Derive reclaimable cache: the difference between "available" memory
- // (what the OS can reclaim) and "truly free" memory (unused pages).
- // This lets the frontend show a split bar: used | cache | free.
- if memRawFree > 0 && memFree > memRawFree {
- memory.Cache = int64(memFree - memRawFree)
- // Adjust Free to reflect truly free pages, not available
- memory.Free = int64(memRawFree)
- }
- if detailedStatus != nil && detailedStatus.Balloon > 0 {
- memory.Balloon = int64(detailedStatus.Balloon)
- }
-
vm := models.VM{
ID: guestID,
VMID: res.VMID,
@@ -7936,6 +7960,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
MemorySource: memorySource,
Memory: vm.Memory,
Raw: guestRaw,
+ Notes: snapshotNotes,
})
// For non-running VMs, zero out resource usage metrics to prevent false alerts
diff --git a/internal/monitoring/vm_memory_carry_forward.go b/internal/monitoring/vm_memory_carry_forward.go
new file mode 100644
index 0000000000..04663a26b2
--- /dev/null
+++ b/internal/monitoring/vm_memory_carry_forward.go
@@ -0,0 +1,63 @@
+package monitoring
+
+import (
+ "math"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+const (
+ vmMemoryCarryForwardMaxAge = 2 * time.Minute
+ vmMemoryCarryForwardMinUsageDelta = 5.0
+ vmMemorySourceReliabilityLow = 0
+ vmMemorySourceReliabilityFallback = 1
+ vmMemorySourceReliabilityTrusted = 2
+)
+
+func vmMemorySourceReliability(source string) int {
+ switch strings.TrimSpace(source) {
+ case "meminfo-available", "meminfo-derived", "guest-agent-meminfo",
+ "rrd-memavailable", "rrd-memused", "host-agent", "meminfo-total-minus-used":
+ return vmMemorySourceReliabilityTrusted
+ case "previous-snapshot":
+ return vmMemorySourceReliabilityFallback
+ case "", "cluster-resources", "listing-mem", "status-mem", "status-freemem", "status-unavailable":
+ return vmMemorySourceReliabilityLow
+ default:
+ return vmMemorySourceReliabilityFallback
+ }
+}
+
+func shouldCarryForwardPreviousVMMemory(prev models.VM, currentStatus, currentSource string, currentTotal, currentUsed uint64, now time.Time) bool {
+ if currentStatus != "running" || prev.Type != "qemu" || prev.Status != "running" {
+ return false
+ }
+ if prev.Memory.Total <= 0 || prev.Memory.Used < 0 {
+ return false
+ }
+ if prev.LastSeen.IsZero() || now.Sub(prev.LastSeen) > vmMemoryCarryForwardMaxAge {
+ return false
+ }
+
+ prevReliability := vmMemorySourceReliability(prev.MemorySource)
+ currentReliability := vmMemorySourceReliability(currentSource)
+ if prevReliability < vmMemorySourceReliabilityTrusted || currentReliability > vmMemorySourceReliabilityFallback {
+ return false
+ }
+ if prevReliability <= currentReliability {
+ return false
+ }
+
+ if currentTotal > 0 && prev.Memory.Total > 0 && prev.Memory.Total != int64(currentTotal) {
+ return false
+ }
+
+ currentUsage := safePercentage(float64(currentUsed), float64(currentTotal))
+ if prev.Memory.Usage > 0 && math.Abs(prev.Memory.Usage-currentUsage) < vmMemoryCarryForwardMinUsageDelta {
+ return false
+ }
+
+ return true
+}
diff --git a/internal/monitoring/vm_memory_carry_forward_test.go b/internal/monitoring/vm_memory_carry_forward_test.go
new file mode 100644
index 0000000000..dacd3c9315
--- /dev/null
+++ b/internal/monitoring/vm_memory_carry_forward_test.go
@@ -0,0 +1,110 @@
+package monitoring
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"
+)
+
+func TestPollVMsAndContainersEfficient_PreservesPreviousTrustedVMMemoryForOneCycle(t *testing.T) {
+ const total = uint64(8 << 30)
+ const trustedUsed = uint64(2 << 30)
+ const fallbackUsed = total
+
+ m := &Monitor{
+ state: models.NewState(),
+ guestAgentFSInfoTimeout: time.Second,
+ guestAgentRetries: 1,
+ guestAgentNetworkTimeout: time.Second,
+ guestAgentOSInfoTimeout: time.Second,
+ guestAgentVersionTimeout: time.Second,
+ guestMetadataCache: make(map[string]guestMetadataCacheEntry),
+ guestMetadataLimiter: make(map[string]time.Time),
+ rateTracker: NewRateTracker(),
+ metricsHistory: NewMetricsHistory(100, time.Hour),
+ alertManager: alerts.NewManager(),
+ stalenessTracker: NewStalenessTracker(nil),
+ nodeRRDMemCache: make(map[string]rrdMemCacheEntry),
+ vmRRDMemCache: make(map[string]rrdMemCacheEntry),
+ vmAgentMemCache: make(map[string]agentMemCacheEntry),
+ }
+ defer m.alertManager.Stop()
+
+ m.state.UpdateVMsForInstance("pve1", []models.VM{
+ {
+ ID: "pve1:node1:100",
+ Instance: "pve1",
+ Node: "node1",
+ VMID: 100,
+ Name: "vm100",
+ Type: "qemu",
+ Status: "running",
+ MemorySource: "rrd-memavailable",
+ Memory: models.Memory{
+ Total: int64(total),
+ Used: int64(trustedUsed),
+ Free: int64(total - trustedUsed),
+ Usage: safePercentage(float64(trustedUsed), float64(total)),
+ },
+ LastSeen: time.Now(),
+ },
+ })
+
+ client := &mockPVEClientExtra{
+ resources: []proxmox.ClusterResource{
+ {Type: "qemu", VMID: 100, Name: "vm100", Node: "node1", Status: "running", MaxMem: total, Mem: fallbackUsed},
+ },
+ vmStatus: &proxmox.VMStatus{
+ Status: "running",
+ Agent: proxmox.VMAgentField{Value: 0},
+ MaxMem: total,
+ Mem: fallbackUsed,
+ },
+ }
+
+ success := m.pollVMsAndContainersEfficient(context.Background(), "pve1", "", false, client, map[string]string{"node1": "online"})
+ if !success {
+ t.Fatal("pollVMsAndContainersEfficient failed")
+ }
+
+ state := m.GetState()
+ if len(state.VMs) != 1 {
+ t.Fatalf("expected 1 VM, got %d", len(state.VMs))
+ }
+ vm := state.VMs[0]
+ if vm.MemorySource != "previous-snapshot" {
+ t.Fatalf("memory source = %q, want previous-snapshot", vm.MemorySource)
+ }
+ if vm.Memory.Used != int64(trustedUsed) {
+ t.Fatalf("memory used = %d, want preserved %d", vm.Memory.Used, trustedUsed)
+ }
+
+ snapshotKey := makeGuestSnapshotKey("pve1", "qemu", "node1", 100)
+ m.diagMu.RLock()
+ snapshot, ok := m.guestSnapshots[snapshotKey]
+ m.diagMu.RUnlock()
+ if !ok {
+ t.Fatal("expected guest snapshot entry")
+ }
+ if len(snapshot.Notes) == 0 || snapshot.Notes[0] != "preserved-previous-memory-after-low-trust-fallback" {
+ t.Fatalf("expected preservation note, got %#v", snapshot.Notes)
+ }
+
+ success = m.pollVMsAndContainersEfficient(context.Background(), "pve1", "", false, client, map[string]string{"node1": "online"})
+ if !success {
+ t.Fatal("second pollVMsAndContainersEfficient failed")
+ }
+
+ state = m.GetState()
+ vm = state.VMs[0]
+ if vm.MemorySource != "status-mem" {
+ t.Fatalf("second poll memory source = %q, want status-mem", vm.MemorySource)
+ }
+ if vm.Memory.Used != int64(fallbackUsed) {
+ t.Fatalf("second poll memory used = %d, want fallback %d", vm.Memory.Used, fallbackUsed)
+ }
+}