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
Harden Proxmox guest snapshot polling
rcourtman35b2deebfb57
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 557cbe14ac..4dff9a9fee 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -260,6 +260,12 @@ reports stale or zero I/O totals. `internal/monitoring/monitor_pve.go`,path before LXC rate calculation and must reuse the same prefetched statussnapshot for metadata enrichment instead of paying disconnected metric andmetadata status reads that can diverge.+That same Proxmox backup/snapshot boundary owns bounded concurrent guest+snapshot enumeration. `internal/monitoring/monitor_backups.go` must query VM+and LXC snapshot endpoints through one capped worker pool and preserve+previously-known snapshots only for guests that were not successfully polled in+the current cycle, so large or slow clusters do not starve later guests while+transient misses still avoid destructive state churn.That same guest-monitoring boundary also owns linked host-agent precedence forProxmox VMs. When a VM has a live linked Pulse host agent, the canonical diskinventory and aggregate disk summary must prefer that linked host-agent diskdiff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 492ce01564..6a23796950 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -88,6 +88,26 @@ func TestPVEBackupPermissionWarningsPreserveTokenACLRepair(t *testing.T) {}}+func TestGuestSnapshotPollingStaysBoundedConcurrent(t *testing.T) {+ data, err := os.ReadFile("monitor_backups.go")+ if err != nil {+ t.Fatalf("failed to read monitor_backups.go: %v", err)+ }+ source := string(data)++ for _, snippet := range []string{+ "maxConcurrentGuestSnapshotPolls = 8",+ "targets := make([]guestSnapshotPollTarget, 0, activeGuests)",+ "results := make(chan guestSnapshotPollResult, len(targets))",+ "sem := make(chan struct{}, maxConcurrentGuestSnapshotPolls)",+ "polledGuestKeys[result.target.key] = struct{}{}",+ } {+ if !strings.Contains(source, snippet) {+ t.Fatalf("monitor_backups.go must contain %q", snippet)+ }+ }+}+func TestGetStateRefreshesLiveAlertSnapshots(t *testing.T) {data, err := os.ReadFile("monitor.go")if err != nil {diff --git a/internal/monitoring/monitor_backups.go b/internal/monitoring/monitor_backups.goindex 7484dac5ce..492fb440a5 100644--- a/internal/monitoring/monitor_backups.go+++ b/internal/monitoring/monitor_backups.go@@ -747,9 +747,10 @@ func (m *Monitor) pollGuestSnapshots(ctx context.Context, instanceName string, c}const (- minSnapshotTimeout = 60 * time.Second- maxSnapshotTimeout = 4 * time.Minute- snapshotTimeoutPerGuest = 2 * time.Second+ minSnapshotTimeout = 60 * time.Second+ maxSnapshotTimeout = 4 * time.Minute+ snapshotTimeoutPerGuest = 2 * time.Second+ maxConcurrentGuestSnapshotPolls = 8)timeout := minSnapshotTimeout@@ -789,111 +790,148 @@ func (m *Monitor) pollGuestSnapshots(ctx context.Context, instanceName string, cdeadlineExceeded := falsepolledGuestKeys := make(map[string]struct{})- // Poll VM snapshots+ type guestSnapshotPollTarget struct {+ key string+ node string+ guestType string+ vmid int+ vmState bool+ }++ targets := make([]guestSnapshotPollTarget, 0, activeGuests)+for _, vm := range vms {- // Skip templatesif vm.Template {continue}+ targets = append(targets, guestSnapshotPollTarget{+ key: guestKey(instanceName, vm.Node, vm.VMID),+ node: vm.Node,+ guestType: "qemu",+ vmid: vm.VMID,+ vmState: true,+ })+ }- snapshots, err := client.GetVMSnapshots(snapshotCtx, vm.Node, vm.VMID)- if err != nil {- if snapshotCtx.Err() != nil {- log.Warn().- Str("instance", instanceName).- Str("node", vm.Node).- Int("vmid", vm.VMID).- Err(snapshotCtx.Err()).- Msg("Aborting guest snapshot polling due to context cancellation while fetching VM snapshots")- deadlineExceeded = true- break- }- // This is common for VMs without snapshots, so use debug level- monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_vm_snapshots", instanceName, err).WithNode(vm.Node)- log.Debug().- Err(monErr).- Str("node", vm.Node).- Int("vmid", vm.VMID).- Msg("Failed to get VM snapshots")+ for _, ct := range containers {+ if ct.Template {continue}+ targets = append(targets, guestSnapshotPollTarget{+ key: guestKey(instanceName, ct.Node, ct.VMID),+ node: ct.Node,+ guestType: "lxc",+ vmid: ct.VMID,+ vmState: false,+ })+ }- polledGuestKeys[guestKey(instanceName, vm.Node, vm.VMID)] = struct{}{}- for _, snap := range snapshots {- snapshot := models.GuestSnapshot{- ID: fmt.Sprintf("%s-%s-%d-%s", instanceName, vm.Node, vm.VMID, snap.Name),- Name: snap.Name,- Node: vm.Node,- Instance: instanceName,- Type: "qemu",- VMID: vm.VMID,- Time: time.Unix(snap.SnapTime, 0),- Description: snap.Description,- Parent: snap.Parent,- VMState: true, // VM state support enabled- }+ type guestSnapshotPollResult struct {+ target guestSnapshotPollTarget+ snapshots []models.GuestSnapshot+ err error+ polled bool+ }- allSnapshots = append(allSnapshots, snapshot)+ buildSnapshot := func(target guestSnapshotPollTarget, snap proxmox.Snapshot) models.GuestSnapshot {+ return models.GuestSnapshot{+ ID: fmt.Sprintf("%s-%s-%d-%s", instanceName, target.node, target.vmid, snap.Name),+ Name: snap.Name,+ Node: target.node,+ Instance: instanceName,+ Type: target.guestType,+ VMID: target.vmid,+ Time: time.Unix(snap.SnapTime, 0),+ Description: snap.Description,+ Parent: snap.Parent,+ VMState: target.vmState,}}- // Poll container snapshots- for _, ct := range containers {- // Skip templates- if ct.Template {+ fetchSnapshots := func(target guestSnapshotPollTarget) ([]proxmox.Snapshot, error) {+ if target.guestType == "lxc" {+ return client.GetContainerSnapshots(snapshotCtx, target.node, target.vmid)+ }+ return client.GetVMSnapshots(snapshotCtx, target.node, target.vmid)+ }++ results := make(chan guestSnapshotPollResult, len(targets))+ var wg sync.WaitGroup+ sem := make(chan struct{}, maxConcurrentGuestSnapshotPolls)++ for _, target := range targets {+ target := target+ wg.Add(1)+ go func() {+ defer wg.Done()++ select {+ case sem <- struct{}{}:+ case <-snapshotCtx.Done():+ results <- guestSnapshotPollResult{target: target, err: snapshotCtx.Err()}+ return+ }+ defer func() { <-sem }()++ snapshots, err := fetchSnapshots(target)+ result := guestSnapshotPollResult{target: target, err: err}+ if err == nil {+ result.polled = true+ result.snapshots = make([]models.GuestSnapshot, 0, len(snapshots))+ for _, snap := range snapshots {+ result.snapshots = append(result.snapshots, buildSnapshot(target, snap))+ }+ } else if target.guestType == "lxc" {+ errStr := err.Error()+ if strings.Contains(errStr, "596") || strings.Contains(errStr, "not available") {+ result.polled = true+ }+ }++ results <- result+ }()+ }++ wg.Wait()+ close(results)++ for result := range results {+ if result.polled {+ polledGuestKeys[result.target.key] = struct{}{}+ allSnapshots = append(allSnapshots, result.snapshots...)continue}++ if result.err == nil {+ continue+ }+if snapshotCtx.Err() != nil {deadlineExceeded = true- break+ log.Warn().+ Str("instance", instanceName).+ Str("node", result.target.node).+ Str("type", result.target.guestType).+ Int("vmid", result.target.vmid).+ Err(snapshotCtx.Err()).+ Msg("Guest snapshot polling context expired before all guests completed")+ continue}- snapshots, err := client.GetContainerSnapshots(snapshotCtx, ct.Node, ct.VMID)- if err != nil {- if snapshotCtx.Err() != nil {- log.Warn().- Str("instance", instanceName).- Str("node", ct.Node).- Int("vmid", ct.VMID).- Err(snapshotCtx.Err()).- Msg("Aborting guest snapshot polling due to context cancellation while fetching container snapshots")- deadlineExceeded = true- break- }- // API error 596 means snapshots not supported/available - this is expected for many containers- errStr := err.Error()- if strings.Contains(errStr, "596") || strings.Contains(errStr, "not available") {- // Silently skip containers without snapshot support; treat- // them as polled so stale unsupported snapshots are not kept.- polledGuestKeys[guestKey(instanceName, ct.Node, ct.VMID)] = struct{}{}- continue- }- // Log other errors at debug level- monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_container_snapshots", instanceName, err).WithNode(ct.Node)+ if result.target.guestType == "lxc" {+ monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_container_snapshots", instanceName, result.err).WithNode(result.target.node)log.Debug().Err(monErr).- Str("node", ct.Node).- Int("vmid", ct.VMID).+ Str("node", result.target.node).+ Int("vmid", result.target.vmid).Msg("Failed to get container snapshots")- continue- }-- polledGuestKeys[guestKey(instanceName, ct.Node, ct.VMID)] = struct{}{}- for _, snap := range snapshots {- snapshot := models.GuestSnapshot{- ID: fmt.Sprintf("%s-%s-%d-%s", instanceName, ct.Node, ct.VMID, snap.Name),- Name: snap.Name,- Node: ct.Node,- Instance: instanceName,- Type: "lxc",- VMID: ct.VMID,- Time: time.Unix(snap.SnapTime, 0),- Description: snap.Description,- Parent: snap.Parent,- VMState: false,- }-- allSnapshots = append(allSnapshots, snapshot)+ } else {+ monErr := errors.NewMonitorError(errors.ErrorTypeAPI, "get_vm_snapshots", instanceName, result.err).WithNode(result.target.node)+ log.Debug().+ Err(monErr).+ Str("node", result.target.node).+ Int("vmid", result.target.vmid).+ Msg("Failed to get VM snapshots")}}diff --git a/internal/monitoring/monitor_snapshot_test.go b/internal/monitoring/monitor_snapshot_test.goindex fcdadefdad..7396f51aaa 100644--- a/internal/monitoring/monitor_snapshot_test.go+++ b/internal/monitoring/monitor_snapshot_test.go@@ -3,6 +3,7 @@ package monitoringimport ("context""fmt"+ "sync/atomic""testing""time"@@ -12,7 +13,11 @@ import (type mockPVEClientSnapshots struct {mockPVEClientExtra- snapshots []proxmox.Snapshot+ snapshots []proxmox.Snapshot+ vmSnapshots map[int][]proxmox.Snapshot+ snapshotGate <-chan struct{}+ inflight int64+ maxInflight int64}func (m *mockPVEClientSnapshots) GetVMSnapshots(ctx context.Context, node string, vmid int) ([]proxmox.Snapshot, error) {@@ -20,6 +25,10 @@ func (m *mockPVEClientSnapshots) GetVMSnapshots(ctx context.Context, node string// simulate timeout/errorreturn nil, fmt.Errorf("timeout")}+ m.trackSnapshotConcurrency(ctx)+ if m.vmSnapshots != nil {+ return m.vmSnapshots[vmid], nil+ }return m.snapshots, nil}@@ -27,6 +36,25 @@ func (m *mockPVEClientSnapshots) GetContainerSnapshots(ctx context.Context, nodereturn m.snapshots, nil}+func (m *mockPVEClientSnapshots) trackSnapshotConcurrency(ctx context.Context) {+ if m.snapshotGate == nil {+ return+ }+ current := atomic.AddInt64(&m.inflight, 1)+ for {+ max := atomic.LoadInt64(&m.maxInflight)+ if current <= max || atomic.CompareAndSwapInt64(&m.maxInflight, max, current) {+ break+ }+ }+ defer atomic.AddInt64(&m.inflight, -1)++ select {+ case <-m.snapshotGate:+ case <-ctx.Done():+ }+}+func TestMonitor_PollGuestSnapshots_Coverage(t *testing.T) {m := &Monitor{state: models.NewState(),@@ -130,6 +158,68 @@ func TestMonitor_PollGuestSnapshots_PreservesPreviousOnPerVMError(t *testing.T)}}+func TestMonitor_PollGuestSnapshots_PollsGuestsConcurrently(t *testing.T) {+ m := &Monitor{state: models.NewState()}++ const guestCount = 12+ vms := make([]models.VM, 0, guestCount)+ snapshotsByVMID := make(map[int][]proxmox.Snapshot, guestCount)+ for i := 0; i < guestCount; i++ {+ vmid := 100 + i+ vms = append(vms, models.VM{+ ID: fmt.Sprintf("qemu/%d", vmid),+ VMID: vmid,+ Node: "node1",+ Instance: "pve1",+ Name: fmt.Sprintf("vm%d", vmid),+ })+ snapshotsByVMID[vmid] = []proxmox.Snapshot{{+ Name: fmt.Sprintf("snap-%d", vmid),+ SnapTime: int64(3000 + i),+ Description: "fresh",+ }}+ }+ m.state.UpdateVMsForInstance("pve1", vms)++ gate := make(chan struct{})+ client := &mockPVEClientSnapshots{+ vmSnapshots: snapshotsByVMID,+ snapshotGate: gate,+ }++ done := make(chan struct{})+ go func() {+ m.pollGuestSnapshots(context.Background(), "pve1", client)+ close(done)+ }()++ deadline := time.After(2 * time.Second)+ for atomic.LoadInt64(&client.maxInflight) < 2 {+ select {+ case <-deadline:+ close(gate)+ <-done+ t.Fatalf("guest snapshot polling did not start concurrent guest fetches; max inflight=%d", atomic.LoadInt64(&client.maxInflight))+ case <-done:+ t.Fatalf("guest snapshot polling completed before the gated snapshot fetches were released")+ default:+ time.Sleep(10 * time.Millisecond)+ }+ }++ close(gate)+ select {+ case <-done:+ case <-time.After(2 * time.Second):+ t.Fatal("guest snapshot polling did not finish after releasing concurrent fetches")+ }++ got := m.state.GetSnapshot().PVEBackups.GuestSnapshots+ if len(got) != guestCount {+ t.Fatalf("guest snapshots = %d, want %d: %+v", len(got), guestCount, got)+ }+}+func keys[K comparable, V any](m map[K]V) []K {out := make([]K, 0, len(m))for k := range m {