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
Guard per-VM guest agent calls with timeout and panic recovery (#1319)
rcourtmanff1bbe2fb8af
diff --git a/internal/monitoring/guest_metadata.go b/internal/monitoring/guest_metadata.goindex f326b7aada..c5aa6912f4 100644--- a/internal/monitoring/guest_metadata.go+++ b/internal/monitoring/guest_metadata.go@@ -26,6 +26,7 @@ const (defaultGuestAgentNetworkTimeout = 10 * time.Second // GUEST_AGENT_NETWORK_TIMEOUTdefaultGuestAgentOSInfoTimeout = 10 * time.Second // GUEST_AGENT_OSINFO_TIMEOUTdefaultGuestAgentVersionTimeout = 10 * time.Second // GUEST_AGENT_VERSION_TIMEOUT+ defaultGuestAgentVMBudget = 10 * time.Second // Hard cap per VM so one bad agent cannot starve later VMIDs (refs #1319)defaultGuestAgentRetries = 1 // GUEST_AGENT_RETRIES (0 = no retry, 1 = one retry)defaultGuestAgentRetryDelay = 500 * time.Millisecond@@ -115,6 +116,48 @@ func (m *Monitor) releaseGuestMetadataSlot() {}}+func (m *Monitor) guestAgentVMContext(parent context.Context) (context.Context, context.CancelFunc) {+ if parent == nil {+ return context.WithTimeout(context.Background(), defaultGuestAgentVMBudget)+ }++ budget := defaultGuestAgentVMBudget+ if deadline, ok := parent.Deadline(); ok {+ remaining := time.Until(deadline)+ if remaining <= 0 {+ return context.WithCancel(parent)+ }+ if remaining < budget {+ budget = remaining+ }+ }++ return context.WithTimeout(parent, budget)+}++func (m *Monitor) runGuestAgentVMWork(parent context.Context, instanceName, nodeName, vmName string, vmid int, fn func(context.Context)) {+ if fn == nil {+ return+ }++ ctx, cancel := m.guestAgentVMContext(parent)+ defer cancel()++ defer func() {+ if recovered := recover(); recovered != nil {+ log.Warn().+ Str("instance", instanceName).+ Str("node", nodeName).+ Str("vm", vmName).+ Int("vmid", vmid).+ Interface("panic", recovered).+ Msg("Recovered from guest agent processing failure; continuing with remaining VMs")+ }+ }()++ fn(ctx)+}+// retryGuestAgentCall executes a guest agent API call with timeout and retry logic (refs #592)func (m *Monitor) retryGuestAgentCall(ctx context.Context, timeout time.Duration, maxRetries int, fn func(context.Context) (interface{}, error)) (interface{}, error) {var lastErr errordiff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex e5277a5847..ee8d8e65d2 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -7069,7 +7069,9 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam// We should prefer guest agent data when available for accurate metricsif res.Status == "running" && res.Type == "qemu" {// First check if agent is enabled by getting VM status- status, err := client.GetVMStatus(ctx, res.Node, res.VMID)+ statusCtx, cancel := context.WithTimeout(ctx, 2*time.Second)+ status, err := client.GetVMStatus(statusCtx, res.Node, res.VMID)+ cancel()if err != nil {log.Debug().Err(err).@@ -7119,28 +7121,84 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNamif detailedStatus.MaxMem > 0 {memTotal = detailedStatus.MaxMem}+ } else {+ // No vmStatus available - keep cluster/resources data+ log.Debug().+ Str("instance", instanceName).+ Str("vm", res.Name).+ Int("vmid", res.VMID).+ Msg("Could not get VM status, using cluster/resources disk data")+ }+ }- // Gather guest metadata from the agent when available- guestIPs, guestIfaces, guestOSName, guestOSVersion, guestAgentVersion := m.fetchGuestAgentMetadata(ctx, client, instanceName, res.Node, res.Name, res.VMID, detailedStatus)- if len(guestIPs) > 0 {- ipAddresses = guestIPs- }- if len(guestIfaces) > 0 {- networkInterfaces = guestIfaces- }- if guestOSName != "" {- osName = guestOSName+ // Fallback for Linux VMs when the guest agent doesn't provide MemInfo.Available:+ // try Proxmox RRD memory first, even if detailed status was unavailable.+ if res.Status == "running" && memAvailable == 0 {+ if rrdEntry, rrdErr := m.getVMRRDMetrics(ctx, client, instanceName, res.Node, res.VMID); rrdErr == nil {+ if rrdEntry.total > 0 {+ memTotal = rrdEntry.total}- if guestOSVersion != "" {- osVersion = guestOSVersion+ if rrdEntry.available > 0 {+ memAvailable = rrdEntry.available+ memorySource = "rrd-memavailable"+ guestRaw.RRDAvailable = rrdEntry.available+ guestRaw.MemInfoAvailable = rrdEntry.available+ log.Debug().+ Str("vm", res.Name).+ Str("node", res.Node).+ Int("vmid", res.VMID).+ Uint64("total", memTotal).+ Uint64("available", memAvailable).+ Msg("QEMU memory: using RRD memavailable fallback (excludes reclaimable cache)")+ } else if rrdEntry.used > 0 {+ rrdUsed = rrdEntry.used+ memorySource = "rrd-memused"+ guestRaw.RRDUsed = rrdEntry.used+ log.Debug().+ Str("vm", res.Name).+ Str("node", res.Node).+ Int("vmid", res.VMID).+ Uint64("total", memTotal).+ Uint64("used", rrdUsed).+ Msg("QEMU memory: using RRD memused fallback")}- if guestAgentVersion != "" {- agentVersion = guestAgentVersion+ } else {+ log.Debug().+ Err(rrdErr).+ Str("instance", instanceName).+ Str("vm", res.Name).+ Int("vmid", res.VMID).+ Msg("RRD memory data unavailable for VM, using status/cluster resources values")+ }+ }++ // Fallback: use linked Pulse host agent's memory data.+ // gopsutil's Used = Total - Available (excludes page cache),+ // so we can derive accurate available memory. Refs: #1270+ if res.Status == "running" && memAvailable == 0 {+ if agentHost, ok := vmIDToHostAgent[guestID]; ok {+ agentAvailable := agentHost.Memory.Total - agentHost.Memory.Used+ if agentAvailable > 0 {+ memAvailable = uint64(agentAvailable)+ memorySource = "host-agent"+ guestRaw.HostAgentTotal = uint64(agentHost.Memory.Total)+ guestRaw.HostAgentUsed = uint64(agentHost.Memory.Used)+ log.Debug().+ Str("vm", res.Name).+ Str("node", res.Node).+ Int("vmid", res.VMID).+ Uint64("total", memTotal).+ Uint64("available", memAvailable).+ Int64("agentTotal", agentHost.Memory.Total).+ Int64("agentUsed", agentHost.Memory.Used).+ Msg("QEMU memory: using linked Pulse host agent memory (excludes page cache)")}+ }+ }- // Always try to get filesystem info if agent is enabled- // Prefer guest agent data over cluster/resources data for accuracy- if detailedStatus.Agent.Value > 0 {+ if res.Status == "running" && agentEnabled {+ m.runGuestAgentVMWork(ctx, instanceName, res.Node, res.Name, res.VMID, func(agentCtx context.Context) {+ if detailedStatus != nil && detailedStatus.Agent.Value > 0 {log.Debug().Str("instance", instanceName).Str("vm", res.Name).@@ -7151,7 +7209,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNamMsg("Guest agent enabled, querying filesystem info for accurate disk usage")// Use retry logic for guest agent calls to handle transient timeouts (refs #630)- fsInfoRaw, err := m.retryGuestAgentCall(ctx, m.guestAgentFSInfoTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {+ fsInfoRaw, err := m.retryGuestAgentCall(agentCtx, m.guestAgentFSInfoTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {return client.GetVMFSInfo(ctx, res.Node, res.VMID)})var fsInfo []proxmox.VMFileSystem@@ -7173,7 +7231,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNamStr("instance", instanceName).Str("vm", res.Name).Msg("To verify: ssh into VM and run 'systemctl status qemu-guest-agent' or 'ps aux | grep qemu-ga'")- } else if strings.Contains(errMsg, "timeout") {+ } else if strings.Contains(errMsg, "timeout") || strings.Contains(errMsg, "deadline exceeded") {log.Info().Str("instance", instanceName).Str("vm", res.Name).@@ -7427,110 +7485,44 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNamMsg("Guest agent provided filesystem info but no usable filesystems found (all were special mounts)")}}- } else {- // Agent disabled - show allocated disk size- if diskTotal > 0 {- diskUsage = -1 // Show as allocated size+ }++ // Last-resort fallback before status-mem: read /proc/meminfo via the+ // QEMU guest agent's file-read endpoint. This works for Linux VMs with+ // the guest agent running even when the balloon driver doesn't populate+ // the meminfo fields. Results are cached with negative backoff. Refs: #1270+ if memAvailable == 0 {+ if agentAvail, agentErr := m.getVMAgentMemAvailable(agentCtx, client, instanceName, res.Node, res.VMID); agentErr == nil && agentAvail > 0 {+ memAvailable = agentAvail+ memorySource = "guest-agent-meminfo"+ guestRaw.MemInfoAvailable = memAvailable+ log.Debug().+ Str("vm", res.Name).+ Str("node", res.Node).+ Int("vmid", res.VMID).+ Uint64("total", memTotal).+ Uint64("available", memAvailable).+ Msg("QEMU memory: using guest agent /proc/meminfo fallback (excludes reclaimable cache)")}- log.Debug().- Str("instance", instanceName).- Str("vm", res.Name).- Int("vmid", res.VMID).- Int("agent", detailedStatus.Agent.Value).- Msg("VM does not have guest agent enabled in config")}- } else {- // No vmStatus available - keep cluster/resources data- log.Debug().- Str("instance", instanceName).- Str("vm", res.Name).- Int("vmid", res.VMID).- Msg("Could not get VM status, using cluster/resources disk data")- }- }- // Fallback for Linux VMs when the guest agent doesn't provide MemInfo.Available:- // try Proxmox RRD memory first, even if detailed status was unavailable.- if res.Status == "running" && memAvailable == 0 {- if rrdEntry, rrdErr := m.getVMRRDMetrics(ctx, client, instanceName, res.Node, res.VMID); rrdErr == nil {- if rrdEntry.total > 0 {- memTotal = rrdEntry.total+ guestIPs, guestIfaces, guestOSName, guestOSVersion, guestAgentVersion := m.fetchGuestAgentMetadata(agentCtx, client, instanceName, res.Node, res.Name, res.VMID, detailedStatus)+ if len(guestIPs) > 0 {+ ipAddresses = guestIPs}- if rrdEntry.available > 0 {- memAvailable = rrdEntry.available- memorySource = "rrd-memavailable"- guestRaw.RRDAvailable = rrdEntry.available- guestRaw.MemInfoAvailable = rrdEntry.available- log.Debug().- Str("vm", res.Name).- Str("node", res.Node).- Int("vmid", res.VMID).- Uint64("total", memTotal).- Uint64("available", memAvailable).- Msg("QEMU memory: using RRD memavailable fallback (excludes reclaimable cache)")- } else if rrdEntry.used > 0 {- rrdUsed = rrdEntry.used- memorySource = "rrd-memused"- guestRaw.RRDUsed = rrdEntry.used- log.Debug().- Str("vm", res.Name).- Str("node", res.Node).- Int("vmid", res.VMID).- Uint64("total", memTotal).- Uint64("used", rrdUsed).- Msg("QEMU memory: using RRD memused fallback")+ if len(guestIfaces) > 0 {+ networkInterfaces = guestIfaces}- } else {- log.Debug().- Err(rrdErr).- Str("instance", instanceName).- Str("vm", res.Name).- Int("vmid", res.VMID).- Msg("RRD memory data unavailable for VM, using status/cluster resources values")- }- }-- // Fallback: use linked Pulse host agent's memory data.- // gopsutil's Used = Total - Available (excludes page cache),- // so we can derive accurate available memory. Refs: #1270- if res.Status == "running" && memAvailable == 0 {- if agentHost, ok := vmIDToHostAgent[guestID]; ok {- agentAvailable := agentHost.Memory.Total - agentHost.Memory.Used- if agentAvailable > 0 {- memAvailable = uint64(agentAvailable)- memorySource = "host-agent"- guestRaw.HostAgentTotal = uint64(agentHost.Memory.Total)- guestRaw.HostAgentUsed = uint64(agentHost.Memory.Used)- log.Debug().- Str("vm", res.Name).- Str("node", res.Node).- Int("vmid", res.VMID).- Uint64("total", memTotal).- Uint64("available", memAvailable).- Int64("agentTotal", agentHost.Memory.Total).- Int64("agentUsed", agentHost.Memory.Used).- Msg("QEMU memory: using linked Pulse host agent memory (excludes page cache)")+ if guestOSName != "" {+ osName = guestOSName}- }- }-- // Last-resort fallback before status-mem: read /proc/meminfo via the- // QEMU guest agent's file-read endpoint. This works for Linux VMs with- // the guest agent running even when the balloon driver doesn't populate- // the meminfo fields. Results are cached with negative backoff. Refs: #1270- if res.Status == "running" && memAvailable == 0 && agentEnabled {- if agentAvail, agentErr := m.getVMAgentMemAvailable(ctx, client, instanceName, res.Node, res.VMID); agentErr == nil && agentAvail > 0 {- memAvailable = agentAvail- memorySource = "guest-agent-meminfo"- guestRaw.MemInfoAvailable = memAvailable- log.Debug().- Str("vm", res.Name).- Str("node", res.Node).- Int("vmid", res.VMID).- Uint64("total", memTotal).- Uint64("available", memAvailable).- Msg("QEMU memory: using guest agent /proc/meminfo fallback (excludes reclaimable cache)")- }+ if guestOSVersion != "" {+ osVersion = guestOSVersion+ }+ if guestAgentVersion != "" {+ agentVersion = guestAgentVersion+ }+ })}// Last-chance MemInfo fallback: use Total-Used only after RRD/agentdiff --git a/internal/monitoring/monitor_polling.go b/internal/monitoring/monitor_polling.goindex 42a2aeebc7..65b770b99c 100644--- a/internal/monitoring/monitor_polling.go+++ b/internal/monitoring/monitor_polling.go@@ -394,18 +394,20 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu}if vm.Status == "running" && memAvailable == 0 && agentEnabled {- if agentAvail, agentErr := m.getVMAgentMemAvailable(ctx, client, instanceName, n.Node, vm.VMID); agentErr == nil && agentAvail > 0 {- memAvailable = agentAvail- memorySource = "guest-agent-meminfo"- guestRaw.MemInfoAvailable = memAvailable- log.Debug().- Str("vm", vm.Name).- Str("node", n.Node).- Int("vmid", vm.VMID).- Uint64("total", memTotal).- Uint64("available", memAvailable).- Msg("QEMU memory: using guest agent /proc/meminfo fallback (excludes reclaimable cache)")- }+ m.runGuestAgentVMWork(ctx, instanceName, n.Node, vm.Name, vm.VMID, func(agentCtx context.Context) {+ if agentAvail, agentErr := m.getVMAgentMemAvailable(agentCtx, client, instanceName, n.Node, vm.VMID); agentErr == nil && agentAvail > 0 {+ memAvailable = agentAvail+ memorySource = "guest-agent-meminfo"+ guestRaw.MemInfoAvailable = memAvailable+ log.Debug().+ Str("vm", vm.Name).+ Str("node", n.Node).+ Int("vmid", vm.VMID).+ Uint64("total", memTotal).+ Uint64("available", memAvailable).+ Msg("QEMU memory: using guest agent /proc/meminfo fallback (excludes reclaimable cache)")+ }+ })}if vm.Status == "running" && memAvailable == 0 && memInfoTotalMinusUsed > 0 {@@ -441,22 +443,24 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu}if vm.Status == "running" && vmStatus != nil {- guestIPs, guestIfaces, guestOSName, guestOSVersion, agentVersion := m.fetchGuestAgentMetadata(ctx, client, instanceName, n.Node, vm.Name, vm.VMID, vmStatus)- if len(guestIPs) > 0 {- ipAddresses = guestIPs- }- if len(guestIfaces) > 0 {- networkInterfaces = guestIfaces- }- if guestOSName != "" {- osName = guestOSName- }- if guestOSVersion != "" {- osVersion = guestOSVersion- }- if agentVersion != "" {- guestAgentVersion = agentVersion- }+ m.runGuestAgentVMWork(ctx, instanceName, n.Node, vm.Name, vm.VMID, func(agentCtx context.Context) {+ guestIPs, guestIfaces, guestOSName, guestOSVersion, agentVersion := m.fetchGuestAgentMetadata(agentCtx, client, instanceName, n.Node, vm.Name, vm.VMID, vmStatus)+ if len(guestIPs) > 0 {+ ipAddresses = guestIPs+ }+ if len(guestIfaces) > 0 {+ networkInterfaces = guestIfaces+ }+ if guestOSName != "" {+ osName = guestOSName+ }+ if guestOSVersion != "" {+ osVersion = guestOSVersion+ }+ if agentVersion != "" {+ guestAgentVersion = agentVersion+ }+ })}// Calculate I/O rates after we have the actual values@@ -532,214 +536,216 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, cluMsg("Guest agent disabled in VM config")}} else if vmStatus.Agent.Value > 0 || diskUsed == 0 {- if logging.IsLevelEnabled(zerolog.DebugLevel) {- log.Debug().- Str("instance", instanceName).- Str("vm", vm.Name).- Int("vmid", vm.VMID).- Msg("Guest agent enabled, fetching filesystem info")- }-- // Filesystem info with configurable timeout and retry (refs #592)- fsInfoRaw, err := m.retryGuestAgentCall(ctx, m.guestAgentFSInfoTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {- return client.GetVMFSInfo(ctx, n.Node, vm.VMID)- })- var fsInfo []proxmox.VMFileSystem- if err == nil {- if fs, ok := fsInfoRaw.([]proxmox.VMFileSystem); ok {- fsInfo = fs- }- }- if err != nil {- // Handle errors- errStr := err.Error()- errStrLower := strings.ToLower(errStr)- log.Warn().- Str("instance", instanceName).- Str("vm", vm.Name).- Int("vmid", vm.VMID).- Str("error", errStr).- Msg("Failed to get VM filesystem info from guest agent")-- // Classify the error type for better user messaging- // Order matters: check most specific patterns first- if strings.Contains(errStr, "QEMU guest agent is not running") {- diskStatusReason = "agent-not-running"- log.Info().+ m.runGuestAgentVMWork(ctx, instanceName, n.Node, vm.Name, vm.VMID, func(agentCtx context.Context) {+ if logging.IsLevelEnabled(zerolog.DebugLevel) {+ log.Debug().Str("instance", instanceName).Str("vm", vm.Name).Int("vmid", vm.VMID).- Msg("Guest agent enabled in VM config but not running inside guest OS. Install and start qemu-guest-agent in the VM")- } else if strings.Contains(errStr, "timeout") {- diskStatusReason = "agent-timeout"- } else if strings.Contains(errStr, "500") && (strings.Contains(errStr, "not running") || strings.Contains(errStr, "not available")) {- // Proxmox API error 500 with "not running"/"not available" indicates guest agent issue, not permissions- // This commonly happens when guest agent is not installed or not running- diskStatusReason = "agent-not-running"- log.Info().+ Msg("Guest agent enabled, fetching filesystem info")+ }++ // Filesystem info with configurable timeout and retry (refs #592)+ fsInfoRaw, err := m.retryGuestAgentCall(agentCtx, m.guestAgentFSInfoTimeout, m.guestAgentRetries, func(ctx context.Context) (interface{}, error) {+ return client.GetVMFSInfo(ctx, n.Node, vm.VMID)+ })+ var fsInfo []proxmox.VMFileSystem+ if err == nil {+ if fs, ok := fsInfoRaw.([]proxmox.VMFileSystem); ok {+ fsInfo = fs+ }+ }+ if err != nil {+ // Handle errors+ errStr := err.Error()+ errStrLower := strings.ToLower(errStr)+ log.Warn().Str("instance", instanceName).Str("vm", vm.Name).Int("vmid", vm.VMID).- Msg("Guest agent communication failed (API error 500). Install and start qemu-guest-agent in the VM")- } else if (strings.Contains(errStr, "403") || strings.Contains(errStr, "401")) &&- (strings.Contains(errStrLower, "permission") || strings.Contains(errStrLower, "forbidden") || strings.Contains(errStrLower, "not allowed")) {- // Only treat as permission-denied if we get explicit auth/permission error codes (401/403)- // This distinguishes actual permission issues from guest agent unavailability- diskStatusReason = "permission-denied"+ Str("error", errStr).+ Msg("Failed to get VM filesystem info from guest agent")++ // Classify the error type for better user messaging+ // Order matters: check most specific patterns first+ if strings.Contains(errStr, "QEMU guest agent is not running") {+ diskStatusReason = "agent-not-running"+ log.Info().+ Str("instance", instanceName).+ Str("vm", vm.Name).+ Int("vmid", vm.VMID).+ Msg("Guest agent enabled in VM config but not running inside guest OS. Install and start qemu-guest-agent in the VM")+ } else if strings.Contains(errStr, "timeout") || strings.Contains(errStr, "deadline exceeded") {+ diskStatusReason = "agent-timeout"+ } else if strings.Contains(errStr, "500") && (strings.Contains(errStr, "not running") || strings.Contains(errStr, "not available")) {+ // Proxmox API error 500 with "not running"/"not available" indicates guest agent issue, not permissions+ // This commonly happens when guest agent is not installed or not running+ diskStatusReason = "agent-not-running"+ log.Info().+ Str("instance", instanceName).+ Str("vm", vm.Name).+ Int("vmid", vm.VMID).+ Msg("Guest agent communication failed (API error 500). Install and start qemu-guest-agent in the VM")+ } else if (strings.Contains(errStr, "403") || strings.Contains(errStr, "401")) &&+ (strings.Contains(errStrLower, "permission") || strings.Contains(errStrLower, "forbidden") || strings.Contains(errStrLower, "not allowed")) {+ // Only treat as permission-denied if we get explicit auth/permission error codes (401/403)+ // This distinguishes actual permission issues from guest agent unavailability+ diskStatusReason = "permission-denied"+ log.Warn().+ Str("instance", instanceName).+ Str("vm", vm.Name).+ Int("vmid", vm.VMID).+ Msg("Permission denied accessing guest agent. Verify Pulse user has VM.Monitor (PVE 8) or VM.Audit+VM.GuestAgent.Audit (PVE 9) permissions")+ } else if strings.Contains(errStr, "500") {+ // Generic 500 error without clear indicators - likely agent unavailable+ // Refs #596: Proxmox returns 500 errors when guest agent isn't installed/running+ diskStatusReason = "agent-not-running"+ log.Info().+ Str("instance", instanceName).+ Str("vm", vm.Name).+ Int("vmid", vm.VMID).+ Msg("Failed to communicate with guest agent (API error 500). This usually means qemu-guest-agent is not installed or not running in the VM")+ } else {+ diskStatusReason = "agent-error"+ }+ } else if len(fsInfo) == 0 {+ diskStatusReason = "no-filesystems"log.Warn().Str("instance", instanceName).Str("vm", vm.Name).Int("vmid", vm.VMID).- Msg("Permission denied accessing guest agent. Verify Pulse user has VM.Monitor (PVE 8) or VM.Audit+VM.GuestAgent.Audit (PVE 9) permissions")- } else if strings.Contains(errStr, "500") {- // Generic 500 error without clear indicators - likely agent unavailable- // Refs #596: Proxmox returns 500 errors when guest agent isn't installed/running- diskStatusReason = "agent-not-running"+ Msg("Guest agent returned empty filesystem list")+ } else {log.Info().Str("instance", instanceName).Str("vm", vm.Name).Int("vmid", vm.VMID).- Msg("Failed to communicate with guest agent (API error 500). This usually means qemu-guest-agent is not installed or not running in the VM")- } else {- diskStatusReason = "agent-error"- }- } else if len(fsInfo) == 0 {- diskStatusReason = "no-filesystems"- log.Warn().- Str("instance", instanceName).- Str("vm", vm.Name).- Int("vmid", vm.VMID).- Msg("Guest agent returned empty filesystem list")- } else {- log.Info().- Str("instance", instanceName).- Str("vm", vm.Name).- Int("vmid", vm.VMID).- Int("filesystems", len(fsInfo)).- Msg("Got filesystem info from guest agent")- // Aggregate disk usage from all filesystems- // Fix for #425: Track seen devices to avoid counting duplicates- var totalBytes, usedBytes uint64- seenDevices := make(map[string]bool)-- for _, fs := range fsInfo {- // Log each filesystem for debugging- log.Debug().- Str("vm", vm.Name).- Str("mountpoint", fs.Mountpoint).- Str("type", fs.Type).- Str("disk", fs.Disk).- Uint64("total", fs.TotalBytes).- Uint64("used", fs.UsedBytes).- Msg("Processing filesystem from guest agent")-- // Skip special filesystems and Windows System Reserved- // For Windows, mountpoints are like "C:\\" or "D:\\" - don't skip those- isWindowsDrive := len(fs.Mountpoint) >= 2 && fs.Mountpoint[1] == ':' && strings.Contains(fs.Mountpoint, "\\")-- if !isWindowsDrive {- if reason, skip := readOnlyFilesystemReason(fs.Type, fs.TotalBytes, fs.UsedBytes); skip {+ Int("filesystems", len(fsInfo)).+ Msg("Got filesystem info from guest agent")+ // Aggregate disk usage from all filesystems+ // Fix for #425: Track seen devices to avoid counting duplicates+ var totalBytes, usedBytes uint64+ seenDevices := make(map[string]bool)++ for _, fs := range fsInfo {+ // Log each filesystem for debugging+ log.Debug().+ Str("vm", vm.Name).+ Str("mountpoint", fs.Mountpoint).+ Str("type", fs.Type).+ Str("disk", fs.Disk).+ Uint64("total", fs.TotalBytes).+ Uint64("used", fs.UsedBytes).+ Msg("Processing filesystem from guest agent")++ // Skip special filesystems and Windows System Reserved+ // For Windows, mountpoints are like "C:\\" or "D:\\" - don't skip those+ isWindowsDrive := len(fs.Mountpoint) >= 2 && fs.Mountpoint[1] == ':' && strings.Contains(fs.Mountpoint, "\\")++ if !isWindowsDrive {+ if reason, skip := readOnlyFilesystemReason(fs.Type, fs.TotalBytes, fs.UsedBytes); skip {+ log.Debug().+ Str("vm", vm.Name).+ Str("mountpoint", fs.Mountpoint).+ Str("type", fs.Type).+ Str("skipReason", reason).+ Uint64("total", fs.TotalBytes).+ Uint64("used", fs.UsedBytes).+ Msg("Skipping read-only filesystem from guest agent")+ continue+ }++ if fs.Type == "tmpfs" || fs.Type == "devtmpfs" ||+ strings.HasPrefix(fs.Mountpoint, "/dev") ||+ strings.HasPrefix(fs.Mountpoint, "/proc") ||+ strings.HasPrefix(fs.Mountpoint, "/sys") ||+ strings.HasPrefix(fs.Mountpoint, "/run") ||+ fs.Mountpoint == "/boot/efi" ||+ fs.Mountpoint == "System Reserved" ||+ strings.Contains(fs.Mountpoint, "System Reserved") ||+ strings.HasPrefix(fs.Mountpoint, "/snap") { // Skip snap mounts+ log.Debug().+ Str("vm", vm.Name).+ Str("mountpoint", fs.Mountpoint).+ Str("type", fs.Type).+ Msg("Skipping special filesystem")+ continue+ }+ }++ // Skip if we've already seen this device (duplicate mount point)+ if fs.Disk != "" && seenDevices[fs.Disk] {log.Debug().Str("vm", vm.Name).Str("mountpoint", fs.Mountpoint).- Str("type", fs.Type).- Str("skipReason", reason).- Uint64("total", fs.TotalBytes).- Uint64("used", fs.UsedBytes).- Msg("Skipping read-only filesystem from guest agent")+ Str("disk", fs.Disk).+ Msg("Skipping duplicate mount of same device")continue}- if fs.Type == "tmpfs" || fs.Type == "devtmpfs" ||- strings.HasPrefix(fs.Mountpoint, "/dev") ||- strings.HasPrefix(fs.Mountpoint, "/proc") ||- strings.HasPrefix(fs.Mountpoint, "/sys") ||- strings.HasPrefix(fs.Mountpoint, "/run") ||- fs.Mountpoint == "/boot/efi" ||- fs.Mountpoint == "System Reserved" ||- strings.Contains(fs.Mountpoint, "System Reserved") ||- strings.HasPrefix(fs.Mountpoint, "/snap") { // Skip snap mounts+ // Only count real filesystems with valid data+ if fs.TotalBytes > 0 {+ // Mark this device as seen+ if fs.Disk != "" {+ seenDevices[fs.Disk] = true+ }++ totalBytes += fs.TotalBytes+ usedBytes += fs.UsedBytes+ individualDisks = append(individualDisks, models.Disk{+ Total: int64(fs.TotalBytes),+ Used: int64(fs.UsedBytes),+ Free: int64(fs.TotalBytes - fs.UsedBytes),+ Usage: safePercentage(float64(fs.UsedBytes), float64(fs.TotalBytes)),+ Mountpoint: fs.Mountpoint,+ Type: fs.Type,+ Device: fs.Disk,+ })log.Debug().Str("vm", vm.Name).Str("mountpoint", fs.Mountpoint).- Str("type", fs.Type).- Msg("Skipping special filesystem")- continue+ Str("disk", fs.Disk).+ Uint64("added_total", fs.TotalBytes).+ Uint64("added_used", fs.UsedBytes).+ Msg("Adding filesystem to total")+ } else {+ log.Debug().+ Str("vm", vm.Name).+ Str("mountpoint", fs.Mountpoint).+ Msg("Skipping filesystem with 0 total bytes")}}- // Skip if we've already seen this device (duplicate mount point)- if fs.Disk != "" && seenDevices[fs.Disk] {- log.Debug().- Str("vm", vm.Name).- Str("mountpoint", fs.Mountpoint).- Str("disk", fs.Disk).- Msg("Skipping duplicate mount of same device")- continue- }-- // Only count real filesystems with valid data- if fs.TotalBytes > 0 {- // Mark this device as seen- if fs.Disk != "" {- seenDevices[fs.Disk] = true- }+ // If we got valid data from guest agent, use it+ if totalBytes > 0 {+ diskTotal = totalBytes+ diskUsed = usedBytes+ diskFree = totalBytes - usedBytes+ diskUsage = safePercentage(float64(usedBytes), float64(totalBytes))+ diskStatusReason = "" // Clear reason on success- totalBytes += fs.TotalBytes- usedBytes += fs.UsedBytes- individualDisks = append(individualDisks, models.Disk{- Total: int64(fs.TotalBytes),- Used: int64(fs.UsedBytes),- Free: int64(fs.TotalBytes - fs.UsedBytes),- Usage: safePercentage(float64(fs.UsedBytes), float64(fs.TotalBytes)),- Mountpoint: fs.Mountpoint,- Type: fs.Type,- Device: fs.Disk,- })- log.Debug().+ log.Info().+ Str("instance", instanceName).Str("vm", vm.Name).- Str("mountpoint", fs.Mountpoint).- Str("disk", fs.Disk).- Uint64("added_total", fs.TotalBytes).- Uint64("added_used", fs.UsedBytes).- Msg("Adding filesystem to total")+ Int("vmid", vm.VMID).+ Uint64("totalBytes", totalBytes).+ Uint64("usedBytes", usedBytes).+ Float64("usage", diskUsage).+ Msg("✓ Successfully retrieved disk usage from guest agent")} else {- log.Debug().+ // Only special filesystems found - show allocated disk size instead+ diskStatusReason = "special-filesystems-only"+ if diskTotal > 0 {+ diskUsage = -1 // Show as allocated size+ }+ log.Info().+ Str("instance", instanceName).Str("vm", vm.Name).- Str("mountpoint", fs.Mountpoint).- Msg("Skipping filesystem with 0 total bytes")- }- }-- // If we got valid data from guest agent, use it- if totalBytes > 0 {- diskTotal = totalBytes- diskUsed = usedBytes- diskFree = totalBytes - usedBytes- diskUsage = safePercentage(float64(usedBytes), float64(totalBytes))- diskStatusReason = "" // Clear reason on success-- log.Info().- Str("instance", instanceName).- Str("vm", vm.Name).- Int("vmid", vm.VMID).- Uint64("totalBytes", totalBytes).- Uint64("usedBytes", usedBytes).- Float64("usage", diskUsage).- Msg("✓ Successfully retrieved disk usage from guest agent")- } else {- // Only special filesystems found - show allocated disk size instead- diskStatusReason = "special-filesystems-only"- if diskTotal > 0 {- diskUsage = -1 // Show as allocated size+ Int("filesystems_found", len(fsInfo)).+ Msg("Guest agent provided filesystem info but no usable filesystems found (all were special mounts)")}- log.Info().- Str("instance", instanceName).- Str("vm", vm.Name).- Int("filesystems_found", len(fsInfo)).- Msg("Guest agent provided filesystem info but no usable filesystems found (all were special mounts)")}- }+ })} else {// No vmStatus available or agent disabled - show allocated diskif diskTotal > 0 {diff --git a/internal/monitoring/proxmox_vm_guest_agent_regression_test.go b/internal/monitoring/proxmox_vm_guest_agent_regression_test.gonew file mode 100644index 0000000000..0daa1bd95a--- /dev/null+++ b/internal/monitoring/proxmox_vm_guest_agent_regression_test.go@@ -0,0 +1,130 @@+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"+)++type guestAgentPanicPVEClient struct {+ mockPVEClient+}++func (guestAgentPanicPVEClient) GetClusterResources(ctx context.Context, resourceType string) ([]proxmox.ClusterResource, error) {+ return []proxmox.ClusterResource{+ {+ Type: "qemu",+ Node: "node1",+ VMID: 100,+ Name: "broken-agent",+ Status: "running",+ MaxMem: 4 * 1024,+ Mem: 2 * 1024,+ MaxDisk: 100 * 1024,+ MaxCPU: 2,+ },+ {+ Type: "qemu",+ Node: "node1",+ VMID: 101,+ Name: "healthy-after-broken",+ Status: "running",+ MaxMem: 4 * 1024,+ Mem: 2 * 1024,+ MaxDisk: 100 * 1024,+ MaxCPU: 2,+ },+ }, nil+}++func (guestAgentPanicPVEClient) GetVMStatus(ctx context.Context, node string, vmid int) (*proxmox.VMStatus, error) {+ return &proxmox.VMStatus{+ MaxMem: 4 * 1024,+ Mem: 2 * 1024,+ Agent: proxmox.VMAgentField{Value: 1},+ }, nil+}++func (guestAgentPanicPVEClient) GetVMRRDData(ctx context.Context, node string, vmid int, timeframe string, cf string, ds []string) ([]proxmox.GuestRRDPoint, error) {+ return nil, nil+}++func (guestAgentPanicPVEClient) GetVMFSInfo(ctx context.Context, node string, vmid int) ([]proxmox.VMFileSystem, error) {+ if vmid == 100 {+ panic("simulated guest agent parser failure")+ }++ return []proxmox.VMFileSystem{+ {+ Mountpoint: "/",+ Type: "ext4",+ TotalBytes: 100 * 1024,+ UsedBytes: 50 * 1024,+ Disk: "/dev/vda",+ },+ }, nil+}++func (guestAgentPanicPVEClient) GetVMNetworkInterfaces(ctx context.Context, node string, vmid int) ([]proxmox.VMNetworkInterface, error) {+ return nil, nil+}++func (guestAgentPanicPVEClient) GetVMAgentInfo(ctx context.Context, node string, vmid int) (map[string]interface{}, error) {+ return map[string]interface{}{}, nil+}++func (guestAgentPanicPVEClient) GetVMAgentVersion(ctx context.Context, node string, vmid int) (string, error) {+ return "", nil+}++func (guestAgentPanicPVEClient) GetReplicationStatus(ctx context.Context) ([]proxmox.ReplicationJob, error) {+ return nil, nil+}++func TestPollVMsAndContainersEfficient_GuestAgentFailureDoesNotSkipLaterVMs(t *testing.T) {+ t.Parallel()++ monitor := &Monitor{+ state: models.NewState(),+ alertManager: alerts.NewManager(),+ metricsHistory: NewMetricsHistory(16, time.Minute),+ rateTracker: NewRateTracker(),+ vmRRDMemCache: make(map[string]rrdMemCacheEntry),+ vmAgentMemCache: make(map[string]agentMemCacheEntry),+ guestMetadataCache: make(map[string]guestMetadataCacheEntry),+ guestMetadataLimiter: make(map[string]time.Time),+ }++ ok := monitor.pollVMsAndContainersEfficient(+ context.Background(),+ "pve-test",+ "",+ false,+ &guestAgentPanicPVEClient{},+ map[string]string{"node1": "online"},+ )+ if !ok {+ t.Fatalf("pollVMsAndContainersEfficient() returned false, want true")+ }++ vms := monitor.state.VMs+ if len(vms) != 2 {+ t.Fatalf("expected 2 VMs after polling, got %d", len(vms))+ }++ found := make(map[int]bool, len(vms))+ for _, vm := range vms {+ found[vm.VMID] = true+ }++ if !found[100] {+ t.Fatalf("broken guest-agent VM 100 was dropped from state")+ }+ if !found[101] {+ t.Fatalf("VM 101 was skipped after VM 100 guest-agent failure")+ }+}