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
Add guest agent meminfo VM memory fallback
rcourtman2fb76b90afda
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 4374e22ce2..cde05f36bb 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -130,12 +130,37 @@ That same demo-owned mock boundary also owns chart continuity. Seeded mockhistory and runtime mock sampling must be projections of the same canonicalmetric timeline, so changing chart ranges feels like zooming one historywindow instead of stitching a second live tail onto the end of seeded-sparklines. Monitoring must not let provider-owned mock resources receive a+sparklines. Monitoring must not let any mock-owned resource receive aduplicate generic unified-resource writer that appends a divergent recent tailafter the canonical mock sampler has already seeded and extended that series.The seed path must therefore include the canonical terminal `now` sample on-its tiered timeline instead of generating history only up to before `now` and-then appending a separately anchored current-value tail afterward.+its tiered timeline and anchor seeded series to the canonical metric model at+that timestamp instead of to mutable state fields, so historical charts match+the exact runtime history that would have been recorded live.+That means seeded history must sample the shared canonical mock runtime metric+function at every historical timestamp for every mock-owned resource class.+Monitoring must not approximate the past from snapshot/current values and then+switch to the canonical sampler only for recent live ticks, because that still+creates a visible seam even when the identities and timestamps are correct.+Seeded history and subsequent live mock writes must also record on the same+canonical chart-time grid. Monitoring must not seed on one wall-clock phase+and append live ticks on another `time.Now()` phase, because the canonical+sampler is dynamic enough that off-grid recent points still look like a+different tail.+Runtime mock tick writers must also sample the canonical metric model at the+recorded chart timestamp instead of copying mutable state fields directly,+because graph refresh cadence and state rounding can otherwise append a recent+tail that looks like a different generator even when the underlying mock+resource identity has not changed. Provider-backed fixture refresh paths must+derive their live host, workload, storage, and disk-history writes from that+same canonical sampler instead of replaying snapshot values. Native polling+lanes and unified sync must not append duplicate mock history once the+canonical mock sampler owns that resource class.+That same ownership rule applies by default whenever mock mode is enabled.+Real client initialization, native pollers, and async agent-origin metric+writers are support-only opt-ins, not the normal demo path, and they must not+append chart-history or persistent metric-store points onto mock-owned+timelines while the canonical mock sampler is active.That same chart boundary also owns role-shaped realism. Seeded history,synthetic summary fallbacks, and runtime mock writes must derive their boundsand curve shape from the same canonical resource-role registry, so database,@@ -385,6 +410,14 @@ selector. When cache-aware availability is unavailable, the shared selector inagainst the effective balloon total and prefer that fallback over `status-mem`when Proxmox reports a saturated or materially inconsistent used figure, soWindows and ballooned guests do not get pinned to false 100% usage samples.+That same guest-memory boundary also owns fallback order and cache scoping for+Proxmox VMs when `MemInfo` is absent. Monitoring must try instance-scoped RRD+`memavailable`, then guest-agent `/proc/meminfo` via the shared Proxmox+client, and only then linked host-agent memory as the final fallback. Both RRD+and guest-agent fallback caches must key on `(instance, node, vmid)` instead+of raw `node/vmid`, so separate Proxmox instances cannot leak stale or foreign+memory evidence into each other just because they reuse the same node name and+VMID.That compatibility boundary also applies to historical snapshot labels that maystill exist in tests, live in-memory state, or pre-canonical diagnostic paths:legacy aliases such as `rrd-available`, `rrd-data`, `node-status-available`,diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 1849ae4724..ec9eb45adc 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -110,6 +110,47 @@ func TestGuestMemoryFallbackUsesCanonicalLowTrustSelector(t *testing.T) {}}+func TestProxmoxGuestMemoryFallbackUsesInstanceScopedCachesAndAgentMeminfo(t *testing.T) {+ requiredSnippets := map[string][]string{+ "guest_memory_agent.go": {+ "func guestMemoryCacheKey(instanceName, node string, vmid int) string {",+ "return fmt.Sprintf(\"%s/%s/%d\", instanceName, node, vmid)",+ "func (m *Monitor) getVMAgentMemAvailable(ctx context.Context, client PVEClientInterface, instanceName, node string, vmid int) (uint64, error) {",+ "requestCtx, cancel := context.WithTimeout(ctx, vmAgentMemRequestTTL)",+ "ttl := vmAgentMemCacheTTL",+ "ttl = vmAgentMemNegativeTTL",+ },+ "guest_memory_sources.go": {+ "if rrdAvailable, rrdErr := m.getVMRRDMetrics(ctx, client, instanceName, node, vmid); rrdErr == nil && rrdAvailable > 0 {",+ "if agentAvailable, agentErr := m.getVMAgentMemAvailable(ctx, client, instanceName, node, vmid); agentErr == nil && agentAvailable > 0 {",+ `memorySource = "guest-agent-meminfo"`,+ "guestRaw.GuestAgentMemAvailable = memAvailable",+ },+ "monitor.go": {+ "func (m *Monitor) getVMRRDMetrics(ctx context.Context, client PVEClientInterface, instanceName, node string, vmid int) (uint64, error) {",+ "cacheKey := guestMemoryCacheKey(instanceName, node, vmid)",+ "vmAgentMemCache map[string]agentMemCacheEntry",+ },+ "monitor_agents.go": {+ "for key, entry := range m.vmAgentMemCache {",+ "if now.Sub(entry.fetchedAt) > vmAgentMemCleanupMaxAge {",+ },+ }++ for file, snippets := range requiredSnippets {+ data, err := os.ReadFile(file)+ if err != nil {+ t.Fatalf("failed to read %s: %v", file, err)+ }+ source := string(data)+ for _, snippet := range snippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("%s must contain %q", file, snippet)+ }+ }+ }+}+func TestMonitoringRuntimeAvoidsLegacyMockPartialHelpers(t *testing.T) {forbiddenSnippets := []string{"mock.GetMockState(",@@ -126,7 +167,7 @@ func TestMonitoringRuntimeAvoidsLegacyMockPartialHelpers(t *testing.T) {}}-func TestMockOwnedUnifiedMetricSyncSkipsProviderWriters(t *testing.T) {+func TestMockOwnedUnifiedMetricSyncDefersToCanonicalSamplerInMockMode(t *testing.T) {previous := mock.IsMockEnabled()mock.SetEnabled(true)t.Cleanup(func() { mock.SetEnabled(previous) })@@ -141,10 +182,17 @@ func TestMockOwnedUnifiedMetricSyncSkipsProviderWriters(t *testing.T) {}) {t.Fatal("expected VMware mock-owned resources to skip generic unified metric sync")}+ if !shouldSkipMockOwnedUnifiedMetricSync(unifiedresources.Resource{+ Sources: []unifiedresources.DataSource{unifiedresources.SourceDocker},+ }) {+ t.Fatal("expected all mock-owned resources to defer to the canonical mock sampler")+ }++ mock.SetEnabled(false)if shouldSkipMockOwnedUnifiedMetricSync(unifiedresources.Resource{Sources: []unifiedresources.DataSource{unifiedresources.SourceDocker},}) {- t.Fatal("expected non-provider mock resources to keep generic unified metric sync")+ t.Fatal("expected unified metric sync to remain available outside mock mode")}}@@ -256,6 +304,7 @@ func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {}{{source: "avail-field", canonical: "available-field"},{source: "meminfo-available", canonical: "available-field"},+ {source: "guest-agent-meminfo", canonical: "guest-agent-meminfo"},{source: "node-status-available", canonical: "available-field"},{source: "meminfo-derived", canonical: "derived-free-buffers-cached"},{source: "calculated", canonical: "derived-free-buffers-cached"},@@ -507,6 +556,118 @@ func TestUnifiedVMMetricsUseCanonicalVMHistoryPath(t *testing.T) {}}+func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {+ cases := []struct {+ file string+ snippets []string+ }{+ {+ file: "monitor.go",+ snippets: []string{+ "func shouldSkipNativeMockStateMetricWrites() bool {",+ "return mock.IsMockEnabled()",+ },+ },+ {+ file: "monitor.go",+ snippets: []string{+ "func keepRealPollingInMockMode() bool {",+ "case \"\", \"0\", \"false\", \"no\", \"off\":",+ "return false",+ },+ },+ {+ file: "monitor.go",+ snippets: []string{+ "func shouldSkipMockOwnedUnifiedMetricSync(resource unifiedresources.Resource) bool {",+ "if !mock.IsMockEnabled() {",+ "return true",+ },+ },+ {+ file: "monitor_polling_vm.go",+ snippets: []string{+ "if !shouldSkipNativeMockStateMetricWrites() {",+ `m.metricsStore.Write("vm", vm.ID, "cpu", vm.CPU*100, now)`,+ },+ },+ {+ file: "monitor_polling_containers.go",+ snippets: []string{+ "if !shouldSkipNativeMockStateMetricWrites() {",+ `m.metricsStore.Write("container", ct.ID, "cpu", ct.CPU*100, now)`,+ },+ },+ {+ file: "monitor_pve_guest_helpers.go",+ snippets: []string{+ "func (m *Monitor) recordGuestMetric(",+ "if m == nil || shouldSkipNativeMockStateMetricWrites() {",+ `m.metricsStore.Write(resourceType, resourceID, "memory", memory, now)`,+ },+ },+ {+ file: "kubernetes_agents.go",+ snippets: []string{+ "if shouldSkipNativeMockStateMetricWrites() {",+ `m.metricsStore.Write("k8s", metricID, "cpu", pod.UsageCPUPercent, timestamp)`,+ },+ },+ {+ file: "monitor_polling_storage.go",+ snippets: []string{+ "if m.metricsHistory != nil && !shouldSkipNativeMockStateMetricWrites() {",+ `m.metricsStore.Write("storage", storage.ID, "usage", storage.Usage, timestamp)`,+ },+ },+ {+ file: "monitor_metrics.go",+ snippets: []string{+ "func (m *Monitor) nativePhysicalDiskTemperatureHistory(duration time.Duration) map[string][]MetricPoint {",+ "if mock.IsMockEnabled() {",+ "return nil",+ },+ },+ {+ file: "mock_metrics_history.go",+ snippets: []string{+ `cpu := mock.SampleMetric("k8s", metricID, "cpu", ts)`,+ `memory := mock.SampleMetric("k8s", metricID, "memory", ts)`,+ `ms.Write("k8s", metricID, "memory", memory, ts)`,+ },+ },+ {+ file: "monitor_agents.go",+ snippets: []string{+ "if !shouldSkipNativeMockStateMetricWrites() {",+ `m.metricsStore.Write("dockerHost", host.ID, "cpu", host.CPUUsage, now)`,+ `m.metricsStore.Write("agent", host.ID, "cpu", host.CPUUsage, now)`,+ },+ },+ {+ file: "monitor.go",+ snippets: []string{+ "func (m *Monitor) writeSMARTMetrics(disk models.PhysicalDisk, now time.Time) {",+ "if shouldSkipNativeMockStateMetricWrites() {",+ "return",+ },+ },+ }++ for _, tc := range cases {+ data, err := os.ReadFile(tc.file)+ if err != nil {+ t.Fatalf("failed to read %s: %v", tc.file, err)+ }+ source := string(data)+ for _, snippet := range tc.snippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("%s must contain %q", tc.file, snippet)+ }+ }+ }+}+func TestUnifiedPhysicalDiskMetricsUseCanonicalDiskHistoryPath(t *testing.T) {data, err := os.ReadFile("monitor.go")if err != nil {diff --git a/internal/monitoring/diagnostic_snapshots.go b/internal/monitoring/diagnostic_snapshots.goindex 32e3e82841..d0c4d81585 100644--- a/internal/monitoring/diagnostic_snapshots.go+++ b/internal/monitoring/diagnostic_snapshots.go@@ -45,25 +45,26 @@ type NodeMemorySnapshot struct {// VMMemoryRaw captures both the listing and detailed status memory fields for a VM/CT.type VMMemoryRaw struct {- ListingMem uint64 `json:"listingMem"`- ListingMaxMem uint64 `json:"listingMaxmem"`- StatusMem uint64 `json:"statusMem,omitempty"`- StatusFreeMem uint64 `json:"statusFreemem,omitempty"`- StatusMaxMem uint64 `json:"statusMaxmem,omitempty"`- Balloon uint64 `json:"balloon,omitempty"`- BalloonMin uint64 `json:"balloonMin,omitempty"`- MemInfoUsed uint64 `json:"meminfoUsed,omitempty"`- MemInfoFree uint64 `json:"meminfoFree,omitempty"`- MemInfoTotal uint64 `json:"meminfoTotal,omitempty"`- MemInfoAvailable uint64 `json:"meminfoAvailable,omitempty"`- MemInfoBuffers uint64 `json:"meminfoBuffers,omitempty"`- MemInfoCached uint64 `json:"meminfoCached,omitempty"`- MemInfoShared uint64 `json:"meminfoShared,omitempty"`- MemInfoTotalMinusUsed uint64 `json:"meminfoTotalMinusUsed,omitempty"`- HostAgentTotal uint64 `json:"hostAgentTotal,omitempty"`- HostAgentUsed uint64 `json:"hostAgentUsed,omitempty"`- Agent int `json:"agent,omitempty"`- DerivedFromBall bool `json:"derivedFromBalloon,omitempty"`+ ListingMem uint64 `json:"listingMem"`+ ListingMaxMem uint64 `json:"listingMaxmem"`+ StatusMem uint64 `json:"statusMem,omitempty"`+ StatusFreeMem uint64 `json:"statusFreemem,omitempty"`+ StatusMaxMem uint64 `json:"statusMaxmem,omitempty"`+ Balloon uint64 `json:"balloon,omitempty"`+ BalloonMin uint64 `json:"balloonMin,omitempty"`+ MemInfoUsed uint64 `json:"meminfoUsed,omitempty"`+ MemInfoFree uint64 `json:"meminfoFree,omitempty"`+ MemInfoTotal uint64 `json:"meminfoTotal,omitempty"`+ MemInfoAvailable uint64 `json:"meminfoAvailable,omitempty"`+ MemInfoBuffers uint64 `json:"meminfoBuffers,omitempty"`+ MemInfoCached uint64 `json:"meminfoCached,omitempty"`+ MemInfoShared uint64 `json:"meminfoShared,omitempty"`+ MemInfoTotalMinusUsed uint64 `json:"meminfoTotalMinusUsed,omitempty"`+ GuestAgentMemAvailable uint64 `json:"guestAgentMemAvailable,omitempty"`+ HostAgentTotal uint64 `json:"hostAgentTotal,omitempty"`+ HostAgentUsed uint64 `json:"hostAgentUsed,omitempty"`+ Agent int `json:"agent,omitempty"`+ DerivedFromBall bool `json:"derivedFromBalloon,omitempty"`}// GuestMemorySnapshot records the memory calculation for a guest (VM/LXC).@@ -243,6 +244,9 @@ func (m *Monitor) logGuestMemorySource(instance, guestType, node string, vmid inif snapshot.Raw.MemInfoAvailable > 0 {evt = evt.Uint64("memInfoAvailable", snapshot.Raw.MemInfoAvailable)}+ if snapshot.Raw.GuestAgentMemAvailable > 0 {+ evt = evt.Uint64("guestAgentMemAvailable", snapshot.Raw.GuestAgentMemAvailable)+ }if snapshot.Raw.MemInfoBuffers > 0 {evt = evt.Uint64("memInfoBuffers", snapshot.Raw.MemInfoBuffers)}diff --git a/internal/monitoring/diagnostic_snapshots_test.go b/internal/monitoring/diagnostic_snapshots_test.goindex 832c8dc1eb..af8049528b 100644--- a/internal/monitoring/diagnostic_snapshots_test.go+++ b/internal/monitoring/diagnostic_snapshots_test.go@@ -304,13 +304,14 @@ func TestNodeMemoryRaw_Fields(t *testing.T) {func TestVMMemoryRaw_Fields(t *testing.T) {raw := VMMemoryRaw{- ListingMem: 2000000000,- ListingMaxMem: 4000000000,- StatusMem: 2100000000,- StatusMaxMem: 4000000000,- Balloon: 3000000000,- BalloonMin: 1000000000,- Agent: 1,+ ListingMem: 2000000000,+ ListingMaxMem: 4000000000,+ StatusMem: 2100000000,+ StatusMaxMem: 4000000000,+ Balloon: 3000000000,+ BalloonMin: 1000000000,+ GuestAgentMemAvailable: 1500000000,+ Agent: 1,}if raw.ListingMem != 2000000000 {@@ -331,6 +332,9 @@ func TestVMMemoryRaw_Fields(t *testing.T) {if raw.BalloonMin != 1000000000 {t.Errorf("BalloonMin = %d, want 1000000000", raw.BalloonMin)}+ if raw.GuestAgentMemAvailable != 1500000000 {+ t.Errorf("GuestAgentMemAvailable = %d, want 1500000000", raw.GuestAgentMemAvailable)+ }if raw.Agent != 1 {t.Errorf("Agent = %d, want 1", raw.Agent)}@@ -1119,10 +1123,10 @@ func TestGetDiagnosticSnapshots(t *testing.T) {}m.guestSnapshots[makeGuestSnapshotKey("pve1", "qemu", "node1", 100)] = GuestMemorySnapshot{- Instance: "pve1",- Node: "node1",- GuestType:"qemu",- VMID: 100,+ Instance: "pve1",+ Node: "node1",+ GuestType: "qemu",+ VMID: 100,}result := m.GetDiagnosticSnapshots()diff --git a/internal/monitoring/guest_memory_agent.go b/internal/monitoring/guest_memory_agent.gonew file mode 100644index 0000000000..a754b425ee--- /dev/null+++ b/internal/monitoring/guest_memory_agent.go@@ -0,0 +1,77 @@+package monitoring++import (+ "context"+ "fmt"+ "time"+)++const (+ vmAgentMemCacheTTL = 60 * time.Second // Cache guest-agent /proc/meminfo reads.+ vmAgentMemRequestTTL = 3 * time.Second // Bound guest-agent file-read latency.+ vmAgentMemNegativeTTL = 5 * time.Minute // Back off on unsupported or failing guests.+ vmAgentMemCleanupMaxAge = 2 * vmAgentMemNegativeTTL+)++type agentMemCacheEntry struct {+ available uint64+ negative bool+ fetchedAt time.Time+}++type guestAgentMemAvailableClient interface {+ GetVMMemAvailableFromAgent(ctx context.Context, node string, vmid int) (uint64, error)+}++func guestMemoryCacheKey(instanceName, node string, vmid int) string {+ return fmt.Sprintf("%s/%s/%d", instanceName, node, vmid)+}++func (m *Monitor) getVMAgentMemAvailable(ctx context.Context, client PVEClientInterface, instanceName, node string, vmid int) (uint64, error) {+ memClient, ok := client.(guestAgentMemAvailableClient)+ if !ok {+ return 0, fmt.Errorf("guest agent meminfo fallback unsupported")+ }+ if node == "" || vmid <= 0 {+ return 0, fmt.Errorf("invalid arguments for guest agent meminfo lookup")+ }++ cacheKey := guestMemoryCacheKey(instanceName, node, vmid)+ now := time.Now()++ m.rrdCacheMu.RLock()+ if entry, ok := m.vmAgentMemCache[cacheKey]; ok {+ ttl := vmAgentMemCacheTTL+ if entry.negative {+ ttl = vmAgentMemNegativeTTL+ }+ if now.Sub(entry.fetchedAt) < ttl {+ m.rrdCacheMu.RUnlock()+ if entry.negative {+ return 0, fmt.Errorf("guest agent meminfo fallback unavailable")+ }+ return entry.available, nil+ }+ }+ m.rrdCacheMu.RUnlock()++ requestCtx, cancel := context.WithTimeout(ctx, vmAgentMemRequestTTL)+ defer cancel()++ available, err := memClient.GetVMMemAvailableFromAgent(requestCtx, node, vmid)+ m.rrdCacheMu.Lock()+ defer m.rrdCacheMu.Unlock()+ if m.vmAgentMemCache == nil {+ m.vmAgentMemCache = make(map[string]agentMemCacheEntry)+ }+ if err != nil || available == 0 {+ m.vmAgentMemCache[cacheKey] = agentMemCacheEntry{negative: true, fetchedAt: now}+ if err == nil {+ err = fmt.Errorf("guest agent meminfo fallback unavailable")+ }+ return 0, err+ }++ m.vmAgentMemCache[cacheKey] = agentMemCacheEntry{available: available, fetchedAt: now}+ return available, nil+}diff --git a/internal/monitoring/guest_memory_agent_test.go b/internal/monitoring/guest_memory_agent_test.gonew file mode 100644index 0000000000..72047e6d01--- /dev/null+++ b/internal/monitoring/guest_memory_agent_test.go@@ -0,0 +1,161 @@+package monitoring++import (+ "context"+ "errors"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/pkg/proxmox"+)++type guestMemoryAgentTestClient struct {+ *stubPVEClient+ vmRRDPoints []proxmox.GuestRRDPoint+ memAvailable uint64+ memErr error+ rrdCalls int+ memCalls int+}++func (c *guestMemoryAgentTestClient) GetVMRRDData(ctx context.Context, node string, vmid int, timeframe, cf string, ds []string) ([]proxmox.GuestRRDPoint, error) {+ c.rrdCalls+++ return c.vmRRDPoints, nil+}++func (c *guestMemoryAgentTestClient) GetVMMemAvailableFromAgent(ctx context.Context, node string, vmid int) (uint64, error) {+ c.memCalls+++ if c.memErr != nil {+ return 0, c.memErr+ }+ return c.memAvailable, nil+}++func TestGetVMRRDMetricsCacheKeyIncludesInstance(t *testing.T) {+ t.Parallel()++ giB := float64(1024 * 1024 * 1024)+ mon := &Monitor{vmRRDMemCache: make(map[string]rrdMemCacheEntry)}+ clientA := &guestMemoryAgentTestClient{+ stubPVEClient: &stubPVEClient{},+ vmRRDPoints: []proxmox.GuestRRDPoint{{MemAvailable: floatPtr(3 * giB)}},+ }+ clientB := &guestMemoryAgentTestClient{+ stubPVEClient: &stubPVEClient{},+ vmRRDPoints: []proxmox.GuestRRDPoint{{MemAvailable: floatPtr(5 * giB)}},+ }++ gotA, err := mon.getVMRRDMetrics(context.Background(), clientA, "pve-a", "node1", 100)+ if err != nil {+ t.Fatalf("getVMRRDMetrics(pve-a) error = %v", err)+ }+ gotB, err := mon.getVMRRDMetrics(context.Background(), clientB, "pve-b", "node1", 100)+ if err != nil {+ t.Fatalf("getVMRRDMetrics(pve-b) error = %v", err)+ }++ if gotA != 3*1024*1024*1024 {+ t.Fatalf("getVMRRDMetrics(pve-a) = %d, want %d", gotA, uint64(3*1024*1024*1024))+ }+ if gotB != 5*1024*1024*1024 {+ t.Fatalf("getVMRRDMetrics(pve-b) = %d, want %d", gotB, uint64(5*1024*1024*1024))+ }+ if clientA.rrdCalls != 1 || clientB.rrdCalls != 1 {+ t.Fatalf("expected isolated cache fetches, got clientA=%d clientB=%d", clientA.rrdCalls, clientB.rrdCalls)+ }+}++func TestGetVMAgentMemAvailableCachesResults(t *testing.T) {+ t.Parallel()++ t.Run("positive cache", func(t *testing.T) {+ mon := &Monitor{vmAgentMemCache: make(map[string]agentMemCacheEntry)}+ client := &guestMemoryAgentTestClient{+ stubPVEClient: &stubPVEClient{},+ memAvailable: 5 * 1024 * 1024 * 1024,+ }++ first, err := mon.getVMAgentMemAvailable(context.Background(), client, "pve-a", "node1", 100)+ if err != nil {+ t.Fatalf("first getVMAgentMemAvailable error = %v", err)+ }+ second, err := mon.getVMAgentMemAvailable(context.Background(), client, "pve-a", "node1", 100)+ if err != nil {+ t.Fatalf("second getVMAgentMemAvailable error = %v", err)+ }++ if first != client.memAvailable || second != client.memAvailable {+ t.Fatalf("cached guest agent memavailable = (%d, %d), want %d", first, second, client.memAvailable)+ }+ if client.memCalls != 1 {+ t.Fatalf("expected positive result to be cached, got %d calls", client.memCalls)+ }+ })++ t.Run("negative cache", func(t *testing.T) {+ mon := &Monitor{vmAgentMemCache: make(map[string]agentMemCacheEntry)}+ client := &guestMemoryAgentTestClient{+ stubPVEClient: &stubPVEClient{},+ memErr: errors.New("boom"),+ }++ if _, err := mon.getVMAgentMemAvailable(context.Background(), client, "pve-a", "node1", 100); err == nil {+ t.Fatal("expected first guest agent memavailable lookup to fail")+ }+ if _, err := mon.getVMAgentMemAvailable(context.Background(), client, "pve-a", "node1", 100); err == nil {+ t.Fatal("expected cached negative guest agent memavailable lookup to fail")+ }+ if client.memCalls != 1 {+ t.Fatalf("expected negative result to back off, got %d calls", client.memCalls)+ }+ })+}++func TestResolveGuestStatusMemoryUsesGuestAgentMeminfoFallback(t *testing.T) {+ t.Parallel()++ const giB = uint64(1024 * 1024 * 1024)++ mon := &Monitor{+ vmRRDMemCache: make(map[string]rrdMemCacheEntry),+ vmAgentMemCache: make(map[string]agentMemCacheEntry),+ }+ client := &guestMemoryAgentTestClient{+ stubPVEClient: &stubPVEClient{},+ memAvailable: 5 * giB,+ }+ raw := &VMMemoryRaw{}++ memTotal, memUsed, source := mon.resolveGuestStatusMemory(+ context.Background(),+ client,+ "pve-a",+ "vm-100",+ "node1",+ 100,+ "pve-a:node1:100",+ &proxmox.VMStatus{+ Agent: proxmox.VMAgentField{Value: 1},+ MaxMem: 8 * giB,+ },+ nil,+ 8*giB,+ "",+ raw,+ )++ if memTotal != 8*giB {+ t.Fatalf("memTotal = %d, want %d", memTotal, uint64(8*giB))+ }+ if memUsed != 3*giB {+ t.Fatalf("memUsed = %d, want %d", memUsed, uint64(3*giB))+ }+ if source != "guest-agent-meminfo" {+ t.Fatalf("source = %q, want guest-agent-meminfo", source)+ }+ if raw.GuestAgentMemAvailable != 5*giB {+ t.Fatalf("raw.GuestAgentMemAvailable = %d, want %d", raw.GuestAgentMemAvailable, uint64(5*giB))+ }+ if client.memCalls != 1 {+ t.Fatalf("expected guest agent meminfo fallback to be queried once, got %d calls", client.memCalls)+ }+}diff --git a/internal/monitoring/guest_memory_sources.go b/internal/monitoring/guest_memory_sources.goindex 01d7e65b11..96059f1884 100644--- a/internal/monitoring/guest_memory_sources.go+++ b/internal/monitoring/guest_memory_sources.go@@ -184,7 +184,7 @@ func (m *Monitor) resolveGuestStatusMemory(}if memAvailable == 0 {- if rrdAvailable, rrdErr := m.getVMRRDMetrics(ctx, client, node, vmid); rrdErr == nil && rrdAvailable > 0 {+ if rrdAvailable, rrdErr := m.getVMRRDMetrics(ctx, client, instanceName, node, vmid); rrdErr == nil && rrdAvailable > 0 {memAvailable = rrdAvailablememorySource = "rrd-memavailable"if guestRaw != nil {@@ -207,6 +207,23 @@ func (m *Monitor) resolveGuestStatusMemory(}}+ if memAvailable == 0 && status.Agent.Value > 0 {+ if agentAvailable, agentErr := m.getVMAgentMemAvailable(ctx, client, instanceName, node, vmid); agentErr == nil && agentAvailable > 0 {+ memAvailable = agentAvailable+ memorySource = "guest-agent-meminfo"+ if guestRaw != nil {+ guestRaw.GuestAgentMemAvailable = memAvailable+ }+ log.Debug().+ Str("vm", guestName).+ Str("node", node).+ Int("vmid", vmid).+ Uint64("total", memTotal).+ Uint64("available", memAvailable).+ Msg("QEMU memory: using guest agent /proc/meminfo fallback (excludes reclaimable cache)")+ }+ }+if memAvailable == 0 {if agentHost, ok := vmIDToHostAgent[guestID]; ok &&agentHost.Memory.Total > 0 &&diff --git a/internal/monitoring/memory_source_catalog.go b/internal/monitoring/memory_source_catalog.goindex 7258454cb7..6ea1d473f8 100644--- a/internal/monitoring/memory_source_catalog.go+++ b/internal/monitoring/memory_source_catalog.go@@ -24,6 +24,7 @@ var memorySourceCatalog = map[string]MemorySourceDescriptor{"calculated": {Canonical: "derived-free-buffers-cached", Trust: "derived"},"derived-total-minus-used": {Canonical: "derived-total-minus-used", Trust: "derived", Fallback: true, DefaultFallbackReason: "derived-total-minus-used"},"meminfo-total-minus-used": {Canonical: "derived-total-minus-used", Trust: "derived", Fallback: true, DefaultFallbackReason: "derived-total-minus-used"},+ "guest-agent-meminfo": {Canonical: "guest-agent-meminfo", Trust: "fallback", Fallback: true, DefaultFallbackReason: "guest-agent-meminfo"},"rrd-memavailable": {Canonical: "rrd-memavailable", Trust: "fallback", Fallback: true, DefaultFallbackReason: "rrd-memavailable"},"rrd-available": {Canonical: "rrd-memavailable", Trust: "fallback", Fallback: true, DefaultFallbackReason: "rrd-memavailable"},"rrd-memused": {Canonical: "rrd-memused", Trust: "fallback", Fallback: true, DefaultFallbackReason: "rrd-memused"},diff --git a/internal/monitoring/memory_source_catalog_test.go b/internal/monitoring/memory_source_catalog_test.goindex 14b7cde3b7..dada002573 100644--- a/internal/monitoring/memory_source_catalog_test.go+++ b/internal/monitoring/memory_source_catalog_test.go@@ -47,6 +47,14 @@ func TestDescribeMemorySourceCanonicalizesAliases(t *testing.T) {wantFallback: true,wantDefaultFallback: "rrd-memavailable",},+ {+ name: "guest agent meminfo fallback",+ source: "guest-agent-meminfo",+ wantCanonical: "guest-agent-meminfo",+ wantTrust: "fallback",+ wantFallback: true,+ wantDefaultFallback: "guest-agent-meminfo",+ },{name: "legacy rrd data alias",source: "rrd-data",diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex be227126a1..ebcf39c55f 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -934,9 +934,10 @@ type Monitor struct {diagMu sync.RWMutex // Protects diagnostic snapshot mapsnodeSnapshots map[string]NodeMemorySnapshotguestSnapshots map[string]GuestMemorySnapshot- rrdCacheMu sync.RWMutex // Protects RRD memavailable cache+ rrdCacheMu sync.RWMutex // Protects short-lived guest memory caches.nodeRRDMemCache map[string]rrdMemCacheEntryvmRRDMemCache map[string]rrdMemCacheEntry+ vmAgentMemCache map[string]agentMemCacheEntryremovedDockerHosts map[string]time.Time // Track deliberately removed Docker hosts (ID -> removal time)dockerTokenBindings map[string]string // Track token ID -> agent ID bindings to enforce uniquenessremovedKubernetesClusters map[string]time.Time // Track deliberately removed Kubernetes clusters (ID -> removal time)@@ -1167,12 +1168,12 @@ func (m *Monitor) getNodeRRDMetrics(ctx context.Context, client PVEClientInterfa// getVMRRDMetrics fetches Proxmox RRD memavailable for a single VM with a// short-lived cache to avoid a live API call on every poll for VMs that// consistently lack guest-agent memory data (e.g. Windows VMs).-func (m *Monitor) getVMRRDMetrics(ctx context.Context, client PVEClientInterface, node string, vmid int) (uint64, error) {+func (m *Monitor) getVMRRDMetrics(ctx context.Context, client PVEClientInterface, instanceName, node string, vmid int) (uint64, error) {if client == nil || node == "" || vmid <= 0 {return 0, fmt.Errorf("invalid arguments for VM RRD lookup")}- cacheKey := fmt.Sprintf("%s/%d", node, vmid)+ cacheKey := guestMemoryCacheKey(instanceName, node, vmid)now := time.Now()m.rrdCacheMu.RLock()@@ -1461,6 +1462,7 @@ func New(cfg *config.Config) (*Monitor, error) {guestSnapshots: make(map[string]GuestMemorySnapshot),nodeRRDMemCache: make(map[string]rrdMemCacheEntry),vmRRDMemCache: make(map[string]rrdMemCacheEntry),+ vmAgentMemCache: make(map[string]agentMemCacheEntry),removedDockerHosts: make(map[string]time.Time),dockerTokenBindings: make(map[string]string),removedKubernetesClusters: make(map[string]time.Time),diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex 5a058935a4..3169477fa3 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -2372,8 +2372,8 @@ func (m *Monitor) cleanupDiagnosticSnapshots(now time.Time) {}// cleanupRRDCache removes stale RRD memory cache entries.-// Entries older than 2x the cache TTL (1 minute) are removed to prevent unbounded growth-// when nodes are removed from the cluster.+// Entries older than their short-lived TTL windows are removed to prevent+// unbounded growth when nodes or guests disappear from the poll set.func (m *Monitor) cleanupRRDCache(now time.Time) {const maxAge = 2 * nodeRRDCacheTTL // 1 minute@@ -2395,6 +2395,12 @@ func (m *Monitor) cleanupRRDCache(now time.Time) {delete(m.vmRRDMemCache, key)}}++ for key, entry := range m.vmAgentMemCache {+ if now.Sub(entry.fetchedAt) > vmAgentMemCleanupMaxAge {+ delete(m.vmAgentMemCache, key)+ }+ }}// cleanupMetricsHistory removes stale entries from the metrics history.diff --git a/internal/monitoring/monitor_extra_coverage_test.go b/internal/monitoring/monitor_extra_coverage_test.goindex 8174d3ed75..ad3c805e2b 100644--- a/internal/monitoring/monitor_extra_coverage_test.go+++ b/internal/monitoring/monitor_extra_coverage_test.go@@ -88,6 +88,7 @@ func TestMonitor_Cleanup_Extra(t *testing.T) {nodeSnapshots: make(map[string]NodeMemorySnapshot),guestSnapshots: make(map[string]GuestMemorySnapshot),nodeRRDMemCache: make(map[string]rrdMemCacheEntry),+ vmAgentMemCache: make(map[string]agentMemCacheEntry),}now := time.Now()@@ -118,6 +119,8 @@ func TestMonitor_Cleanup_Extra(t *testing.T) {m.rrdCacheMu.Lock()m.nodeRRDMemCache["stale"] = rrdMemCacheEntry{fetchedAt: stale}m.nodeRRDMemCache["fresh"] = rrdMemCacheEntry{fetchedAt: fresh}+ m.vmAgentMemCache["stale"] = agentMemCacheEntry{negative: true, fetchedAt: stale.Add(-vmAgentMemNegativeTTL)}+ m.vmAgentMemCache["fresh"] = agentMemCacheEntry{available: 42, fetchedAt: fresh}m.rrdCacheMu.Unlock()m.cleanupRRDCache(now)@@ -128,6 +131,12 @@ func TestMonitor_Cleanup_Extra(t *testing.T) {if _, ok := m.nodeRRDMemCache["fresh"]; !ok {t.Error("Fresh RRD cache entry removed")}+ if _, ok := m.vmAgentMemCache["stale"]; ok {+ t.Error("Stale guest agent memory cache entry not removed")+ }+ if _, ok := m.vmAgentMemCache["fresh"]; !ok {+ t.Error("Fresh guest agent memory cache entry removed")+ }}func TestMonitor_SetMockMode_Advanced_Extra(t *testing.T) {diff --git a/pkg/proxmox/client.go b/pkg/proxmox/client.goindex f8801ac4c0..673af0bfc0 100644--- a/pkg/proxmox/client.go+++ b/pkg/proxmox/client.go@@ -2144,6 +2144,48 @@ func vmNetworkInterfaceHasUsefulData(iface VMNetworkInterface) bool {iface.HasIp6Gateway}+// GetVMMemAvailableFromAgent reads /proc/meminfo via the QEMU guest agent's+// file-read endpoint and returns MemAvailable in bytes.+func (c *Client) GetVMMemAvailableFromAgent(ctx context.Context, node string, vmid int) (uint64, error) {+ fileParam := url.QueryEscape("/proc/meminfo")+ resp, err := c.get(ctx, fmt.Sprintf("/nodes/%s/qemu/%d/agent/file-read?file=%s", node, vmid, fileParam))+ if err != nil {+ return 0, fmt.Errorf("guest agent file-read /proc/meminfo: %w", err)+ }+ defer resp.Body.Close()++ var result struct {+ Data struct {+ Content string `json:"content"`+ Truncated *bool `json:"truncated,omitempty"`+ } `json:"data"`+ }+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {+ return 0, fmt.Errorf("decode file-read response: %w", err)+ }++ for _, line := range strings.Split(result.Data.Content, "\n") {+ line = strings.TrimSpace(line)+ if !strings.HasPrefix(line, "MemAvailable:") {+ continue+ }+ fields := strings.Fields(line)+ if len(fields) < 2 {+ continue+ }+ kB, err := strconv.ParseUint(fields[1], 10, 64)+ if err != nil {+ return 0, fmt.Errorf("parse MemAvailable value %q: %w", fields[1], err)+ }+ if kB > math.MaxUint64/1024 {+ return 0, fmt.Errorf("MemAvailable value %d kB overflows uint64", kB)+ }+ return kB * 1024, nil+ }++ return 0, fmt.Errorf("MemAvailable not found in /proc/meminfo")+}+// GetVMStatus returns detailed VM status including balloon infofunc (c *Client) GetVMStatus(ctx context.Context, node string, vmid int) (*VMStatus, error) {// Note: Proxmox 9.x removed support for the "full" parameterdiff --git a/pkg/proxmox/client_api_more_test.go b/pkg/proxmox/client_api_more_test.goindex 06270e05b0..095d6cc9a3 100644--- a/pkg/proxmox/client_api_more_test.go+++ b/pkg/proxmox/client_api_more_test.go@@ -337,3 +337,30 @@ func TestClientStatusAndResources(t *testing.T) {t.Fatalf("unexpected container interfaces: %+v", ifaces)}}++func TestClientGetVMMemAvailableFromAgent(t *testing.T) {+ client := newTestClient(t, func(w http.ResponseWriter, r *http.Request) {+ switch r.URL.Path {+ case "/api2/json/nodes/node1/qemu/100/agent/file-read":+ if got := r.URL.Query().Get("file"); got != "/proc/meminfo" {+ t.Fatalf("unexpected file query = %q", got)+ }+ writeJSON(t, w, map[string]interface{}{+ "data": map[string]interface{}{+ "content": "MemTotal: 8163488 kB\nMemAvailable: 5242880 kB\n",+ },+ })+ default:+ http.NotFound(w, r)+ }+ })++ ctx := context.Background()+ available, err := client.GetVMMemAvailableFromAgent(ctx, "node1", 100)+ if err != nil {+ t.Fatalf("GetVMMemAvailableFromAgent error: %v", err)+ }+ if available != 5242880*1024 {+ t.Fatalf("available = %d, want %d", available, uint64(5242880*1024))+ }+}diff --git a/pkg/proxmox/cluster_client.go b/pkg/proxmox/cluster_client.goindex 94851ffe23..b9039f1644 100644--- a/pkg/proxmox/cluster_client.go+++ b/pkg/proxmox/cluster_client.go@@ -1321,6 +1321,20 @@ func (cc *ClusterClient) GetVMNetworkInterfaces(ctx context.Context, node stringreturn result, err}+// GetVMMemAvailableFromAgent reads /proc/meminfo via the QEMU guest agent to get MemAvailable.+func (cc *ClusterClient) GetVMMemAvailableFromAgent(ctx context.Context, node string, vmid int) (uint64, error) {+ var result uint64+ err := cc.executeWithFailover(ctx, func(client *Client) error {+ available, err := client.GetVMMemAvailableFromAgent(ctx, node, vmid)+ if err != nil {+ return err+ }+ result = available+ return nil+ })+ return result, err+}+// GetClusterResources returns all resources (VMs, containers) across the cluster in a single callfunc (cc *ClusterClient) GetClusterResources(ctx context.Context, resourceType string) ([]ClusterResource, error) {var result []ClusterResource