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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix(monitoring): harden VM memory selection and flag repeated VM usage
rcourtmana4571f580b52
diff --git a/frontend-modern/src/types/api.ts b/frontend-modern/src/types/api.tsindex 6b04ef60a9..6815a4bae0 100644--- a/frontend-modern/src/types/api.ts+++ b/frontend-modern/src/types/api.ts@@ -191,6 +191,7 @@ export interface VM {uptime: number;template: boolean;lastBackup: number;+ memorySource?: string;tags: string[] | string | null;lock: string;lastSeen: string;diff --git a/internal/models/converters.go b/internal/models/converters.goindex 974d3c26a2..74b5ad80ac 100644--- a/internal/models/converters.go+++ b/internal/models/converters.go@@ -76,6 +76,7 @@ func (v VM) ToFrontend() VMFrontend {CPUs: v.CPUs,Mem: v.Memory.Used,MaxMem: v.Memory.Total,+ MemorySource: v.MemorySource,NetIn: zeroIfNegative(v.NetworkIn),NetOut: zeroIfNegative(v.NetworkOut),DiskRead: zeroIfNegative(v.DiskRead),diff --git a/internal/models/converters_test.go b/internal/models/converters_test.goindex a4c7a9e6d7..d4ab407783 100644--- a/internal/models/converters_test.go+++ b/internal/models/converters_test.go@@ -185,28 +185,29 @@ func TestVMToFrontend(t *testing.T) {lastBackup := now.Add(-24 * time.Hour)vm := VM{- ID: "vm-100",- VMID: 100,- Name: "test-vm",- Node: "pve1",- Instance: "default",- Status: "running",- Type: "qemu",- CPU: 0.15,- CPUs: 4,- Memory: Memory{Total: 8000000000, Used: 4000000000},- Disk: Disk{Total: 100000000000, Used: 50000000000},- NetworkIn: 1000000,- NetworkOut: 500000,- DiskRead: 100000,- DiskWrite: 50000,- Uptime: 3600,- Tags: []string{"production", "web"},- LastSeen: now,- LastBackup: lastBackup,- IPAddresses: []string{"192.168.1.50", "10.0.0.50"},- OSName: "Ubuntu",- OSVersion: "22.04",+ ID: "vm-100",+ VMID: 100,+ Name: "test-vm",+ Node: "pve1",+ Instance: "default",+ Status: "running",+ Type: "qemu",+ CPU: 0.15,+ CPUs: 4,+ Memory: Memory{Total: 8000000000, Used: 4000000000},+ Disk: Disk{Total: 100000000000, Used: 50000000000},+ NetworkIn: 1000000,+ NetworkOut: 500000,+ DiskRead: 100000,+ DiskWrite: 50000,+ Uptime: 3600,+ Tags: []string{"production", "web"},+ MemorySource: "rrd-memavailable",+ LastSeen: now,+ LastBackup: lastBackup,+ IPAddresses: []string{"192.168.1.50", "10.0.0.50"},+ OSName: "Ubuntu",+ OSVersion: "22.04",}frontend := vm.ToFrontend()@@ -238,6 +239,9 @@ func TestVMToFrontend(t *testing.T) {if frontend.OSName != "Ubuntu" {t.Errorf("OSName = %q, want Ubuntu", frontend.OSName)}+ if frontend.MemorySource != "rrd-memavailable" {+ t.Errorf("MemorySource = %q, want %q", frontend.MemorySource, "rrd-memavailable")+ }if frontend.Memory == nil {t.Error("Memory should not be nil when Total > 0")}diff --git a/internal/models/models.go b/internal/models/models.goindex abef2e0198..d28b7a5127 100644--- a/internal/models/models.go+++ b/internal/models/models.go@@ -125,6 +125,7 @@ type VM struct {Uptime int64 `json:"uptime"`Template bool `json:"template"`LastBackup time.Time `json:"lastBackup,omitempty"`+ MemorySource string `json:"memorySource,omitempty"` // Source used to calculate memory (diagnostics/support)Tags []string `json:"tags,omitempty"`Lock string `json:"lock,omitempty"`LastSeen time.Time `json:"lastSeen"`diff --git a/internal/models/models_frontend.go b/internal/models/models_frontend.goindex 87536eb069..5b390c2ef8 100644--- a/internal/models/models_frontend.go+++ b/internal/models/models_frontend.go@@ -65,7 +65,8 @@ type VMFrontend struct {Uptime int64 `json:"uptime"`Template bool `json:"template"`LastBackup int64 `json:"lastBackup,omitempty"` // Unix timestamp- Tags string `json:"tags,omitempty"` // Joined string+ MemorySource string `json:"memorySource,omitempty"`+ Tags string `json:"tags,omitempty"` // Joined stringLock string `json:"lock,omitempty"`LastSeen int64 `json:"lastSeen"` // Unix timestamp}diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex df328a6105..8ea89505f0 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -6980,6 +6980,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam// Seed OCI classification from previous state so we never "downgrade" to LXC// if container config fetching intermittently fails (permissions or transient API errors).prevState := m.GetState()+ prevInstanceVMs := filterVMsByInstance(prevState.VMs, instanceName)prevContainerIsOCI := make(map[int]bool)for _, ct := range prevState.Containers {if ct.Instance != instanceName {@@ -7579,16 +7580,17 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam}vm := models.VM{- ID: guestID,- VMID: res.VMID,- Name: res.Name,- Node: res.Node,- Instance: instanceName,- Status: res.Status,- Type: "qemu",- CPU: safeFloat(res.CPU),- CPUs: res.MaxCPU,- Memory: memory,+ ID: guestID,+ VMID: res.VMID,+ Name: res.Name,+ Node: res.Node,+ Instance: instanceName,+ Status: res.Status,+ Type: "qemu",+ CPU: safeFloat(res.CPU),+ CPUs: res.MaxCPU,+ Memory: memory,+ MemorySource: memorySource,Disk: models.Disk{Total: int64(diskTotal),Used: int64(diskUsed),@@ -7966,6 +7968,8 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNamMsg("Grace period preservation complete")}+ m.logSuspiciousRepeatedVMMemoryUsage(instanceName, allVMs, prevInstanceVMs)+// Always update state when using efficient polling path// Even if arrays are empty, we need to update to clear out VMs from genuinely offline nodesm.state.UpdateVMsForInstance(instanceName, allVMs)diff --git a/internal/monitoring/monitor_polling.go b/internal/monitoring/monitor_polling.goindex cb0d0e7a58..f8d470d9d2 100644--- a/internal/monitoring/monitor_polling.go+++ b/internal/monitoring/monitor_polling.go@@ -219,6 +219,7 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu// and gets accurate MemAvailable (excluding page cache). We use this as// a memory fallback before the inflated status.Mem value. Refs: #1270prevState := m.GetState()+ prevInstanceVMs := filterVMsByInstance(prevState.VMs, instanceName)vmIDToHostAgent := make(map[string]models.Host)for _, h := range prevState.Hosts {if h.LinkedVMID != "" && h.Status == "online" && h.Memory.Total > 0 {@@ -303,6 +304,7 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, cluguestRaw.BalloonMin = status.BalloonMinguestRaw.Agent = status.Agent.ValuememAvailable := uint64(0)+ memInfoTotalMinusUsed := uint64(0)if status.MemInfo != nil {guestRaw.MemInfoUsed = status.MemInfo.UsedguestRaw.MemInfoFree = status.MemInfo.Free@@ -312,28 +314,12 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, cluguestRaw.MemInfoCached = status.MemInfo.CachedguestRaw.MemInfoShared = status.MemInfo.Shared- // Derive memAvailable from balloon MemInfo. Prefer Available (most- // accurate), then Free+Buffers+Cached when cache metrics are present.- // When Buffers=0 AND Cached=0, the balloon isn't reporting cache- // breakdown — using Free alone gives wildly inflated usage because- // reclaimable page cache is counted as used. In that case, skip and- // fall through to RRD/guest-agent fallbacks. Refs: #1302, #1270- switch {- case status.MemInfo.Available > 0:- memAvailable = status.MemInfo.Available- memorySource = "meminfo-available"- case status.MemInfo.Buffers > 0 || status.MemInfo.Cached > 0:- memAvailable = status.MemInfo.Free +- status.MemInfo.Buffers +- status.MemInfo.Cached- memorySource = "meminfo-derived"- }-- // Record Total-Used for diagnostics even when not used as the source- if status.MemInfo.Total > 0 &&- status.MemInfo.Used > 0 &&- status.MemInfo.Total >= status.MemInfo.Used {- guestRaw.MemInfoTotalMinusUsed = status.MemInfo.Total - status.MemInfo.Used+ selection := selectVMAvailableFromMemInfo(status.MemInfo)+ memInfoTotalMinusUsed = selection.TotalMinusUsed+ guestRaw.MemInfoTotalMinusUsed = memInfoTotalMinusUsed+ if selection.Available > 0 {+ memAvailable = selection.Available+ memorySource = selection.Source}}// Note: We intentionally do NOT override memTotal with balloon.@@ -400,16 +386,10 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu}}- // Last-chance MemInfo fallback: when balloon reports Used/Total but no- // cache breakdown (Buffers=Cached=0), use Total-Used. This may equal- // Free (if Used=Total-Free) but is still better than status-mem which- // can be even more inflated. Placed after RRD/agent so those get- // priority. Refs: #1302, #1270- if memAvailable == 0 && status.MemInfo != nil &&- status.MemInfo.Total > 0 &&- status.MemInfo.Used > 0 &&- status.MemInfo.Total >= status.MemInfo.Used {- memAvailable = status.MemInfo.Total - status.MemInfo.Used+ // Last-chance MemInfo fallback: use Total-Used only after RRD/agent+ // attempts, so those more reliable cache-aware sources get priority.+ if memAvailable == 0 && memInfoTotalMinusUsed > 0 {+ memAvailable = memInfoTotalMinusUsedmemorySource = "meminfo-total-minus-used"}@@ -788,16 +768,17 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu// Create VM modelmodelVM := models.VM{- ID: guestID,- VMID: vm.VMID,- Name: vm.Name,- Node: n.Node,- Instance: instanceName,- Status: vm.Status,- Type: "qemu",- CPU: cpuUsage,- CPUs: vm.CPUs,- Memory: memory,+ ID: guestID,+ VMID: vm.VMID,+ Name: vm.Name,+ Node: n.Node,+ Instance: instanceName,+ Status: vm.Status,+ Type: "qemu",+ CPU: cpuUsage,+ CPUs: vm.CPUs,+ Memory: memory,+ MemorySource: memorySource,Disk: models.Disk{Total: int64(diskTotal),Used: int64(diskUsed),@@ -886,14 +867,10 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu// If we got ZERO VMs but had VMs before (likely cluster health issue),// preserve previous VMs instead of clearing themif len(allVMs) == 0 && len(nodes) > 0 {- prevState := m.GetState()- prevVMCount := 0- for _, vm := range prevState.VMs {- if vm.Instance == instanceName {- allVMs = append(allVMs, vm)- prevVMCount++- }+ for _, vm := range prevInstanceVMs {+ allVMs = append(allVMs, vm)}+ prevVMCount := len(prevInstanceVMs)if prevVMCount > 0 {log.Warn().Str("instance", instanceName).@@ -904,6 +881,8 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu}}+ m.logSuspiciousRepeatedVMMemoryUsage(instanceName, allVMs, prevInstanceVMs)+// Update state with all VMsm.state.UpdateVMsForInstance(instanceName, allVMs)diff --git a/internal/monitoring/vm_memory_selection.go b/internal/monitoring/vm_memory_selection.gonew file mode 100644index 0000000000..635c850a8a--- /dev/null+++ b/internal/monitoring/vm_memory_selection.go@@ -0,0 +1,78 @@+package monitoring++import (+ "math"++ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++const vmMemInfoGapTolerance uint64 = 16 * 1024 * 1024 // 16 MiB++type vmMemAvailableSelection struct {+ Available uint64+ Source string+ TotalMinusUsed uint64+}++// selectVMAvailableFromMemInfo evaluates VM meminfo data from the QEMU guest+// agent and returns:+// - a primary cache-aware memAvailable value when meminfo is trustworthy+// - total-minus-used as a secondary fallback candidate+//+// We intentionally defer to downstream fallbacks (RRD/guest-agent file-read)+// when meminfo appears incomplete (e.g. tiny buffers/cached with a large gap+// to total-used), because those paths are more reliable for affected guests.+func selectVMAvailableFromMemInfo(memInfo *proxmox.VMMemInfo) vmMemAvailableSelection {+ if memInfo == nil {+ return vmMemAvailableSelection{}+ }++ selection := vmMemAvailableSelection{}+ if memInfo.Total > 0 && memInfo.Used > 0 && memInfo.Total >= memInfo.Used {+ selection.TotalMinusUsed = memInfo.Total - memInfo.Used+ }++ if memInfo.Available > 0 {+ selection.Available = memInfo.Available+ if memInfo.Total > 0 && selection.Available > memInfo.Total {+ selection.Available = memInfo.Total+ }+ selection.Source = "meminfo-available"+ return selection+ }++ // If the balloon doesn't report cache breakdown, avoid using Free alone.+ if memInfo.Buffers == 0 && memInfo.Cached == 0 {+ return selection+ }++ componentAvailable := saturatingAddUint64(memInfo.Free, memInfo.Buffers)+ componentAvailable = saturatingAddUint64(componentAvailable, memInfo.Cached)+ if memInfo.Total > 0 && componentAvailable > memInfo.Total {+ componentAvailable = memInfo.Total+ }+ if componentAvailable == 0 {+ return selection+ }++ // If total-used is materially larger than free+buffers+cached, the cache+ // breakdown appears incomplete. Defer to downstream fallbacks before using+ // total-used.+ if selection.TotalMinusUsed > componentAvailable {+ gap := selection.TotalMinusUsed - componentAvailable+ if gap >= vmMemInfoGapTolerance {+ return selection+ }+ }++ selection.Available = componentAvailable+ selection.Source = "meminfo-derived"+ return selection+}++func saturatingAddUint64(lhs, rhs uint64) uint64 {+ if math.MaxUint64-lhs < rhs {+ return math.MaxUint64+ }+ return lhs + rhs+}diff --git a/internal/monitoring/vm_memory_selection_test.go b/internal/monitoring/vm_memory_selection_test.gonew file mode 100644index 0000000000..24d1287d37--- /dev/null+++ b/internal/monitoring/vm_memory_selection_test.go@@ -0,0 +1,103 @@+package monitoring++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++func TestSelectVMAvailableFromMemInfo(t *testing.T) {+ giB := uint64(1024 * 1024 * 1024)+ miB := uint64(1024 * 1024)++ tests := []struct {+ name string+ memInfo *proxmox.VMMemInfo+ wantAvailable uint64+ wantSource string+ wantTotalMinusUsed uint64+ }{+ {+ name: "prefers explicit available",+ memInfo: &proxmox.VMMemInfo{+ Total: 16 * giB,+ Used: 10 * giB,+ Free: 2 * giB,+ Available: 6 * giB,+ Buffers: 512 * miB,+ Cached: 2 * giB,+ },+ wantAvailable: 6 * giB,+ wantSource: "meminfo-available",+ wantTotalMinusUsed: 6 * giB,+ },+ {+ name: "uses derived free buffers cached when consistent",+ memInfo: &proxmox.VMMemInfo{+ Total: 8 * giB,+ Used: 4 * giB,+ Free: 1536 * miB,+ Buffers: 512 * miB,+ Cached: 2 * giB,+ },+ wantAvailable: 4 * giB,+ wantSource: "meminfo-derived",+ wantTotalMinusUsed: 4 * giB,+ },+ {+ name: "defers derived when total-used gap is materially larger",+ memInfo: &proxmox.VMMemInfo{+ Total: 64 * giB,+ Used: 16 * giB,+ Free: 6 * giB,+ Buffers: 64 * miB,+ Cached: 128 * miB,+ },+ wantAvailable: 0,+ wantSource: "",+ wantTotalMinusUsed: 48 * giB,+ },+ {+ name: "skips free-only meminfo and keeps total-used fallback",+ memInfo: &proxmox.VMMemInfo{+ Total: 32 * giB,+ Used: 22 * giB,+ Free: 10 * giB,+ },+ wantAvailable: 0,+ wantSource: "",+ wantTotalMinusUsed: 10 * giB,+ },+ {+ name: "nil meminfo",+ memInfo: nil,+ },+ {+ name: "keeps derived when gap is below tolerance",+ memInfo: &proxmox.VMMemInfo{+ Total: 1024 * miB,+ Used: 256 * miB,+ Free: 760 * miB,+ Buffers: 4 * miB,+ },+ wantAvailable: 764 * miB,+ wantSource: "meminfo-derived",+ wantTotalMinusUsed: 768 * miB,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := selectVMAvailableFromMemInfo(tt.memInfo)+ if got.Available != tt.wantAvailable {+ t.Fatalf("available = %d, want %d", got.Available, tt.wantAvailable)+ }+ if got.Source != tt.wantSource {+ t.Fatalf("source = %q, want %q", got.Source, tt.wantSource)+ }+ if got.TotalMinusUsed != tt.wantTotalMinusUsed {+ t.Fatalf("totalMinusUsed = %d, want %d", got.TotalMinusUsed, tt.wantTotalMinusUsed)+ }+ })+ }+}diff --git a/internal/monitoring/vm_memory_telemetry_guard.go b/internal/monitoring/vm_memory_telemetry_guard.gonew file mode 100644index 0000000000..cc440a5c6b--- /dev/null+++ b/internal/monitoring/vm_memory_telemetry_guard.go@@ -0,0 +1,155 @@+package monitoring++import (+ "fmt"+ "sort"+ "strings"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+ "github.com/rs/zerolog/log"+)++const (+ minRunningVMsForRepeatedMemoryCheck = 4+ minRepeatedVMsForSuspicion = 3+ minRepeatedMemoryShare = 0.60+ maxRepeatedMemorySampleNames = 5+)++type repeatedVMMemoryUsage struct {+ suspicious bool+ signature string+ runningCount int+ repeatedCount int+ repeatedMemUsed int64+ sourceBreakdown []string+ sampleVMNames []string+}++type repeatedMemoryGroup struct {+ count int+ sources map[string]int+ names []string+}++func filterVMsByInstance(vms []models.VM, instanceName string) []models.VM {+ filtered := make([]models.VM, 0, len(vms))+ for _, vm := range vms {+ if vm.Instance == instanceName {+ filtered = append(filtered, vm)+ }+ }+ return filtered+}++func detectRepeatedVMMemoryUsage(vms []models.VM) repeatedVMMemoryUsage {+ groups := make(map[int64]*repeatedMemoryGroup)+ runningCount := 0++ for _, vm := range vms {+ if vm.Type != "qemu" || vm.Status != "running" || vm.Memory.Total <= 0 || vm.Memory.Used <= 0 {+ continue+ }+ runningCount++++ group, ok := groups[vm.Memory.Used]+ if !ok {+ group = &repeatedMemoryGroup{+ sources: make(map[string]int),+ }+ groups[vm.Memory.Used] = group+ }+ group.count+++ source := strings.TrimSpace(vm.MemorySource)+ if source == "" {+ source = "unknown"+ }+ group.sources[source]+++ if len(group.names) < maxRepeatedMemorySampleNames {+ name := strings.TrimSpace(vm.Name)+ if name == "" {+ name = vm.ID+ }+ group.names = append(group.names, name)+ }+ }++ if runningCount < minRunningVMsForRepeatedMemoryCheck {+ return repeatedVMMemoryUsage{runningCount: runningCount}+ }++ var topUsed int64+ var topGroup *repeatedMemoryGroup+ for used, group := range groups {+ if topGroup == nil || group.count > topGroup.count {+ topUsed = used+ topGroup = group+ }+ }+ if topGroup == nil {+ return repeatedVMMemoryUsage{runningCount: runningCount}+ }++ share := float64(topGroup.count) / float64(runningCount)+ if topGroup.count < minRepeatedVMsForSuspicion || share < minRepeatedMemoryShare {+ return repeatedVMMemoryUsage{runningCount: runningCount}+ }++ breakdown := formatMemorySourceBreakdown(topGroup.sources)+ sampleNames := append([]string(nil), topGroup.names...)+ sort.Strings(sampleNames)++ return repeatedVMMemoryUsage{+ suspicious: true,+ signature: fmt.Sprintf("%d:%d:%s", topUsed, topGroup.count, strings.Join(breakdown, ",")),+ runningCount: runningCount,+ repeatedCount: topGroup.count,+ repeatedMemUsed: topUsed,+ sourceBreakdown: breakdown,+ sampleVMNames: sampleNames,+ }+}++func formatMemorySourceBreakdown(counts map[string]int) []string {+ type sourceCount struct {+ source string+ count int+ }+ entries := make([]sourceCount, 0, len(counts))+ for source, count := range counts {+ entries = append(entries, sourceCount{source: source, count: count})+ }+ sort.Slice(entries, func(i, j int) bool {+ if entries[i].count == entries[j].count {+ return entries[i].source < entries[j].source+ }+ return entries[i].count > entries[j].count+ })++ breakdown := make([]string, 0, len(entries))+ for _, entry := range entries {+ breakdown = append(breakdown, fmt.Sprintf("%s:%d", entry.source, entry.count))+ }+ return breakdown+}++func (m *Monitor) logSuspiciousRepeatedVMMemoryUsage(instanceName string, currentVMs []models.VM, previousVMs []models.VM) {+ current := detectRepeatedVMMemoryUsage(currentVMs)+ if !current.suspicious {+ return+ }++ previous := detectRepeatedVMMemoryUsage(previousVMs)+ if previous.suspicious && previous.signature == current.signature {+ return+ }++ log.Warn().+ Str("instance", instanceName).+ Int("runningVMs", current.runningCount).+ Int("repeatedVMs", current.repeatedCount).+ Int64("repeatedMemoryUsedBytes", current.repeatedMemUsed).+ Strs("memorySources", current.sourceBreakdown).+ Strs("sampleVMs", current.sampleVMNames).+ Msg("Suspicious repeated VM memory-used pattern detected")+}diff --git a/internal/monitoring/vm_memory_telemetry_guard_test.go b/internal/monitoring/vm_memory_telemetry_guard_test.gonew file mode 100644index 0000000000..9a29e570e5--- /dev/null+++ b/internal/monitoring/vm_memory_telemetry_guard_test.go@@ -0,0 +1,90 @@+package monitoring++import (+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/models"+)++func TestDetectRepeatedVMMemoryUsage(t *testing.T) {+ tests := []struct {+ name string+ vms []models.VM+ wantSuspicious bool+ wantRepeated int+ wantRunning int+ wantRepeatedMem int64+ }{+ {+ name: "detects suspicious repeated memory used values",+ vms: []models.VM{+ {Name: "vm1", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm2", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm3", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm4", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm5", Type: "qemu", Status: "running", MemorySource: "rrd-memavailable", Memory: models.Memory{Total: 8 << 30, Used: 2 << 30}},+ },+ wantSuspicious: true,+ wantRepeated: 4,+ wantRunning: 5,+ wantRepeatedMem: 3 << 30,+ },+ {+ name: "ignores patterns under share threshold",+ vms: []models.VM{+ {Name: "vm1", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm2", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm3", Type: "qemu", Status: "running", MemorySource: "rrd-memavailable", Memory: models.Memory{Total: 8 << 30, Used: 2 << 30}},+ {Name: "vm4", Type: "qemu", Status: "running", MemorySource: "rrd-memavailable", Memory: models.Memory{Total: 8 << 30, Used: 1 << 30}},+ },+ wantSuspicious: false,+ wantRepeated: 0,+ wantRunning: 4,+ },+ {+ name: "ignores when not enough running qemu guests",+ vms: []models.VM{+ {Name: "vm1", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm2", Type: "qemu", Status: "running", MemorySource: "status-mem", Memory: models.Memory{Total: 8 << 30, Used: 3 << 30}},+ {Name: "vm3", Type: "qemu", Status: "stopped", MemorySource: "powered-off", Memory: models.Memory{Total: 8 << 30, Used: 0}},+ },+ wantSuspicious: false,+ wantRepeated: 0,+ wantRunning: 2,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ got := detectRepeatedVMMemoryUsage(tt.vms)+ if got.suspicious != tt.wantSuspicious {+ t.Fatalf("suspicious = %v, want %v", got.suspicious, tt.wantSuspicious)+ }+ if got.repeatedCount != tt.wantRepeated {+ t.Fatalf("repeatedCount = %d, want %d", got.repeatedCount, tt.wantRepeated)+ }+ if got.runningCount != tt.wantRunning {+ t.Fatalf("runningCount = %d, want %d", got.runningCount, tt.wantRunning)+ }+ if got.repeatedMemUsed != tt.wantRepeatedMem {+ t.Fatalf("repeatedMemUsed = %d, want %d", got.repeatedMemUsed, tt.wantRepeatedMem)+ }+ })+ }+}++func TestFilterVMsByInstance(t *testing.T) {+ vms := []models.VM{+ {ID: "a", Instance: "pve1"},+ {ID: "b", Instance: "pve2"},+ {ID: "c", Instance: "pve1"},+ }++ filtered := filterVMsByInstance(vms, "pve1")+ if len(filtered) != 2 {+ t.Fatalf("len(filtered) = %d, want 2", len(filtered))+ }+ if filtered[0].ID != "a" || filtered[1].ID != "c" {+ t.Fatalf("unexpected filtered result: %#v", filtered)+ }+}