Skip to content

armgit / Pulse

Public Imported from GitHub
0

Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.

Reconcile recovery points against source enumerations

rcourtman5867d439a34a
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index c6814c5fbb..0f4b980701 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -25,7 +25,6 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring/errors"
"github.com/rcourtman/pulse-go-rewrite/internal/notifications"
- "github.com/rcourtman/pulse-go-rewrite/internal/recovery"
recoverymanager "github.com/rcourtman/pulse-go-rewrite/internal/recovery/manager"
"github.com/rcourtman/pulse-go-rewrite/internal/system"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
@@ -1052,7 +1051,7 @@ type Monitor struct {
recoveryManager *recoverymanager.Manager // Optional recovery store manager for backup rollups
recoveryIngestMu sync.Mutex
recoveryIngestRunning bool
- recoveryIngestPending []recovery.RecoveryPoint
+ recoveryIngestPending []recoveryIngestBatch
mockMetricsCancel context.CancelFunc
mockMetricsWg sync.WaitGroup
dockerChecker DockerChecker // Optional Docker checker for LXC containers
diff --git a/internal/monitoring/monitor_backups.go b/internal/monitoring/monitor_backups.go
index 37739973b1..b8ebb10a7b 100644
--- a/internal/monitoring/monitor_backups.go
+++ b/internal/monitoring/monitor_backups.go
@@ -13,6 +13,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring/errors"
+ "github.com/rcourtman/pulse-go-rewrite/internal/recovery"
proxmoxrecoverymapper "github.com/rcourtman/pulse-go-rewrite/internal/recovery/mapper/proxmox"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/pbs"
@@ -381,7 +382,14 @@ func (m *Monitor) pollStorageBackupsWithNodes(ctx context.Context, instanceName
// Best-effort ingestion into recovery store (for rollups / unified backups UX).
guestInfo := buildProxmoxGuestInfoIndex(readState)
- m.ingestRecoveryPointsAsync(proxmoxrecoverymapper.FromPVEStorageBackups(allBackups, guestInfo))
+ m.ingestAndReconcileRecoveryPointsAsync(
+ proxmoxrecoverymapper.FromPVEStorageBackups(allBackups, guestInfo),
+ recoveryReconcileScope{
+ provider: string(recovery.ProviderProxmoxPVE),
+ idPrefix: "pve-backup:",
+ instance: instanceName,
+ },
+ )
// Sync backup times to VMs/Containers and republish them to canonical resources.
m.syncGuestBackupTimesAndResourceStore()
@@ -1095,7 +1103,14 @@ func (m *Monitor) pollGuestSnapshots(ctx context.Context, instanceName string, c
// Best-effort ingestion into recovery store (for rollups / unified backups UX).
guestInfo := buildProxmoxGuestInfoIndex(readState)
- m.ingestRecoveryPointsAsync(proxmoxrecoverymapper.FromPVEGuestSnapshots(allSnapshots, guestInfo))
+ m.ingestAndReconcileRecoveryPointsAsync(
+ proxmoxrecoverymapper.FromPVEGuestSnapshots(allSnapshots, guestInfo),
+ recoveryReconcileScope{
+ provider: string(recovery.ProviderProxmoxPVE),
+ idPrefix: "pve-snapshot:",
+ instance: instanceName,
+ },
+ )
if m.alertManager != nil {
m.alertManager.CheckSnapshotsForInstance(instanceName, allSnapshots, guestLookups)
@@ -1581,7 +1596,14 @@ func (m *Monitor) pollPBSBackups(ctx context.Context, instanceName string, clien
// Best-effort ingestion into recovery store (for rollups / unified backups UX).
candidates := buildPBSGuestCandidates(m.GetUnifiedReadStateOrSnapshot())
- m.ingestRecoveryPointsAsync(proxmoxrecoverymapper.FromPBSBackups(allBackups, candidates))
+ m.ingestAndReconcileRecoveryPointsAsync(
+ proxmoxrecoverymapper.FromPBSBackups(allBackups, candidates),
+ recoveryReconcileScope{
+ provider: string(recovery.ProviderProxmoxPBS),
+ idPrefix: "pbs-backup:",
+ instance: instanceName,
+ },
+ )
// Sync backup times to VMs/Containers and republish them to canonical resources.
m.syncGuestBackupTimesAndResourceStore()
diff --git a/internal/monitoring/recovery_ingest.go b/internal/monitoring/recovery_ingest.go
index 75e2432f44..5bfd2f3864 100644
--- a/internal/monitoring/recovery_ingest.go
+++ b/internal/monitoring/recovery_ingest.go
@@ -12,32 +12,64 @@ import (
"github.com/rs/zerolog/log"
)
+// recoveryReconcileScope identifies one class of points for one polled
+// connection whose latest enumeration is authoritative: after the batch is
+// upserted, points in scope that were not part of the batch are deleted.
+type recoveryReconcileScope struct {
+ provider string
+ idPrefix string
+ instance string
+}
+
+// recoveryIngestBatch is one poll cycle's worth of recovery points, plus an
+// optional reconcile scope when the points are a complete enumeration.
+type recoveryIngestBatch struct {
+ points []recovery.RecoveryPoint
+ reconcile *recoveryReconcileScope
+}
+
func (m *Monitor) ingestRecoveryPointsAsync(points []recovery.RecoveryPoint) {
- if m == nil || len(points) == 0 {
+ m.enqueueRecoveryIngest(recoveryIngestBatch{points: points})
+}
+
+// ingestAndReconcileRecoveryPointsAsync upserts a complete enumeration and
+// removes points in scope that the source no longer reports. An empty points
+// slice is meaningful here: it clears the scope entirely (#1580).
+func (m *Monitor) ingestAndReconcileRecoveryPointsAsync(points []recovery.RecoveryPoint, scope recoveryReconcileScope) {
+ m.enqueueRecoveryIngest(recoveryIngestBatch{points: points, reconcile: &scope})
+}
+
+func (m *Monitor) enqueueRecoveryIngest(batch recoveryIngestBatch) {
+ if m == nil || (len(batch.points) == 0 && batch.reconcile == nil) {
return
}
m.recoveryIngestMu.Lock()
if m.recoveryIngestRunning {
- m.recoveryIngestPending = points
+ // Queue rather than replace: batches come from different sources (PVE
+ // storage, PBS, snapshots), and dropping one loses a full poll cycle
+ // for that source.
+ m.recoveryIngestPending = append(m.recoveryIngestPending, batch)
m.recoveryIngestMu.Unlock()
log.Debug().
- Int("points", len(points)).
- Msg("Coalesced recovery point ingest behind active batch")
+ Int("points", len(batch.points)).
+ Msg("Queued recovery point ingest behind active batch")
return
}
m.recoveryIngestRunning = true
m.recoveryIngestMu.Unlock()
- go m.runRecoveryPointIngestLoop(points)
+ go m.runRecoveryPointIngestLoop([]recoveryIngestBatch{batch})
}
-func (m *Monitor) runRecoveryPointIngestLoop(points []recovery.RecoveryPoint) {
- for len(points) > 0 {
- // SQLite upserts are usually quick, but allow a bit of time for large batches.
- ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
- m.ingestRecoveryPointsBestEffort(ctx, points)
- cancel()
+func (m *Monitor) runRecoveryPointIngestLoop(batches []recoveryIngestBatch) {
+ for len(batches) > 0 {
+ for _, batch := range batches {
+ // SQLite upserts are usually quick, but allow a bit of time for large batches.
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
+ m.ingestRecoveryPointsBestEffort(ctx, batch)
+ cancel()
+ }
m.recoveryIngestMu.Lock()
if len(m.recoveryIngestPending) == 0 {
@@ -45,7 +77,7 @@ func (m *Monitor) runRecoveryPointIngestLoop(points []recovery.RecoveryPoint) {
m.recoveryIngestMu.Unlock()
return
}
- points = m.recoveryIngestPending
+ batches = m.recoveryIngestPending
m.recoveryIngestPending = nil
m.recoveryIngestMu.Unlock()
}
@@ -55,8 +87,8 @@ func (m *Monitor) runRecoveryPointIngestLoop(points []recovery.RecoveryPoint) {
m.recoveryIngestMu.Unlock()
}
-func (m *Monitor) ingestRecoveryPointsBestEffort(ctx context.Context, points []recovery.RecoveryPoint) {
- if m == nil || len(points) == 0 {
+func (m *Monitor) ingestRecoveryPointsBestEffort(ctx context.Context, batch recoveryIngestBatch) {
+ if m == nil || (len(batch.points) == 0 && batch.reconcile == nil) {
return
}
@@ -78,8 +110,27 @@ func (m *Monitor) ingestRecoveryPointsBestEffort(ctx context.Context, points []r
return
}
- if err := store.UpsertPoints(ctx, points); err != nil {
- log.Warn().Err(err).Str("org_id", orgID).Int("points", len(points)).Msg("Failed to upsert recovery points from backup polling")
+ if err := store.UpsertPoints(ctx, batch.points); err != nil {
+ log.Warn().Err(err).Str("org_id", orgID).Int("points", len(batch.points)).Msg("Failed to upsert recovery points from backup polling")
+ // Do not reconcile against a batch that failed to land; deleting on
+ // top of a failed upsert could drop points the source still reports.
+ return
+ }
+
+ if batch.reconcile == nil {
+ return
+ }
+ keepIDs := make([]string, 0, len(batch.points))
+ for _, p := range batch.points {
+ keepIDs = append(keepIDs, p.ID)
+ }
+ if _, err := store.ReconcileInstancePoints(ctx, batch.reconcile.provider, batch.reconcile.idPrefix, batch.reconcile.instance, keepIDs); err != nil {
+ log.Warn().
+ Err(err).
+ Str("org_id", orgID).
+ Str("instance", batch.reconcile.instance).
+ Str("idPrefix", batch.reconcile.idPrefix).
+ Msg("Failed to reconcile recovery points against source enumeration")
}
}
diff --git a/internal/recovery/store/store.go b/internal/recovery/store/store.go
index 5196ff1437..6af4b29c7c 100644
--- a/internal/recovery/store/store.go
+++ b/internal/recovery/store/store.go
@@ -416,6 +416,115 @@ func (s *Store) PurgeStalePVEPBSBackups(ctx context.Context) error {
return nil
}
+// ReconcileInstancePoints removes recovery points of one class (idPrefix) for
+// one polled connection (instance) that are absent from the latest complete
+// enumeration (keepIDs). Ingest is otherwise upsert-only, so points for
+// backups or snapshots deleted at the source lingered until the retention
+// prune and kept re-raising age alerts (#1580). Callers must only pass
+// enumerations that fully succeeded (or carried forward unpolled entries).
+func (s *Store) ReconcileInstancePoints(ctx context.Context, provider, idPrefix, instance string, keepIDs []string) (int64, error) {
+ if err := s.ensureInitialized(); err != nil {
+ return 0, err
+ }
+ provider = strings.TrimSpace(provider)
+ idPrefix = strings.TrimSpace(idPrefix)
+ instance = strings.TrimSpace(instance)
+ if provider == "" || idPrefix == "" || instance == "" {
+ return 0, fmt.Errorf("reconcile requires provider, id prefix, and instance")
+ }
+ if ctx == nil {
+ ctx = context.Background()
+ }
+
+ keep := make(map[string]struct{}, len(keepIDs))
+ for _, id := range keepIDs {
+ if id = strings.TrimSpace(id); id != "" {
+ keep[id] = struct{}{}
+ }
+ }
+
+ // PVE points carry the connection in details_json.instance; PBS points in
+ // repository_ref_json.namespace. The id prefix keeps the classes apart, so
+ // matching either field never crosses providers.
+ rows, err := s.db.QueryContext(ctx, `
+ SELECT id FROM recovery_points
+ WHERE provider = ?
+ AND id LIKE ? || '%'
+ AND (
+ json_extract(details_json, '$.instance') = ?
+ OR json_extract(repository_ref_json, '$.namespace') = ?
+ )
+ `, provider, idPrefix, instance, instance)
+ if err != nil {
+ return 0, err
+ }
+ defer rows.Close()
+
+ var stale []string
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ return 0, err
+ }
+ if _, ok := keep[id]; !ok {
+ stale = append(stale, id)
+ }
+ }
+ if err := rows.Err(); err != nil {
+ return 0, err
+ }
+ if len(stale) == 0 {
+ return 0, nil
+ }
+
+ tx, err := s.db.BeginTx(ctx, nil)
+ if err != nil {
+ return 0, err
+ }
+ defer func() {
+ if err != nil {
+ _ = tx.Rollback()
+ }
+ }()
+
+ const chunkSize = 200
+ var deleted int64
+ for start := 0; start < len(stale); start += chunkSize {
+ end := start + chunkSize
+ if end > len(stale) {
+ end = len(stale)
+ }
+ chunk := stale[start:end]
+ placeholders := strings.TrimSuffix(strings.Repeat("?,", len(chunk)), ",")
+ args := make([]any, len(chunk))
+ for i, id := range chunk {
+ args[i] = id
+ }
+ res, execErr := tx.ExecContext(ctx, "DELETE FROM recovery_points WHERE id IN ("+placeholders+")", args...)
+ if execErr != nil {
+ err = execErr
+ return 0, err
+ }
+ if n, raErr := res.RowsAffected(); raErr == nil {
+ deleted += n
+ }
+ }
+ if err = tx.Commit(); err != nil {
+ return 0, err
+ }
+
+ if deleted > 0 {
+ log.Info().
+ Str("provider", provider).
+ Str("idPrefix", idPrefix).
+ Str("instance", instance).
+ Int64("deleted", deleted).
+ Msg("Reconciled recovery points against latest source enumeration")
+ }
+
+ return deleted, nil
+}
+
func (s *Store) initSchema() error {
if err := s.ensureInitialized(); err != nil {
return err
diff --git a/internal/recovery/store/store_test.go b/internal/recovery/store/store_test.go
index 7f3bfc0ecb..977f667e2d 100644
--- a/internal/recovery/store/store_test.go
+++ b/internal/recovery/store/store_test.go
@@ -69,6 +69,134 @@ func TestStore_UpsertAndList(t *testing.T) {
}
}
+// TestStore_ReconcileInstancePoints pins the deleted-at-source cleanup (#1580):
+// points in the reconciled scope that are missing from the enumeration are
+// removed, while other instances, other point classes, and other providers
+// survive, and an empty enumeration clears the scope entirely.
+func TestStore_ReconcileInstancePoints(t *testing.T) {
+ t.Parallel()
+
+ dir := t.TempDir()
+ dbPath := filepath.Join(dir, "recovery.db")
+
+ store, err := Open(dbPath)
+ if err != nil {
+ t.Fatalf("Open() error = %v", err)
+ }
+ t.Cleanup(func() { _ = store.Close() })
+
+ now := time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC)
+ pvePoint := func(id, instance string) recovery.RecoveryPoint {
+ return recovery.RecoveryPoint{
+ ID: id,
+ Provider: recovery.ProviderProxmoxPVE,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeLocal,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &now,
+ CompletedAt: &now,
+ Details: map[string]any{"instance": instance},
+ }
+ }
+ pbsPoint := func(id, instance string) recovery.RecoveryPoint {
+ return recovery.RecoveryPoint{
+ ID: id,
+ Provider: recovery.ProviderProxmoxPBS,
+ Kind: recovery.KindBackup,
+ Mode: recovery.ModeRemote,
+ Outcome: recovery.OutcomeSuccess,
+ StartedAt: &now,
+ CompletedAt: &now,
+ RepositoryRef: &recovery.ExternalRef{
+ Type: "proxmox-pbs-datastore",
+ Namespace: instance,
+ Name: "main",
+ },
+ }
+ }
+
+ seed := []recovery.RecoveryPoint{
+ pvePoint("pve-backup:pve1-vzdump-100", "pve1"),
+ pvePoint("pve-backup:pve1-vzdump-101", "pve1"),
+ pvePoint("pve-backup:pve2-vzdump-100", "pve2"),
+ pvePoint("pve-snapshot:pve1-snap-100", "pve1"),
+ pbsPoint("pbs-backup:pbs-pbs1-main-vm-100-1", "pbs1"),
+ }
+ if err := store.UpsertPoints(context.Background(), seed); err != nil {
+ t.Fatalf("UpsertPoints() error = %v", err)
+ }
+
+ // vzdump-101 was deleted at the source; the enumeration keeps only vzdump-100.
+ deleted, err := store.ReconcileInstancePoints(
+ context.Background(),
+ string(recovery.ProviderProxmoxPVE), "pve-backup:", "pve1",
+ []string{"pve-backup:pve1-vzdump-100"},
+ )
+ if err != nil {
+ t.Fatalf("ReconcileInstancePoints() error = %v", err)
+ }
+ if deleted != 1 {
+ t.Fatalf("deleted = %d, want 1", deleted)
+ }
+
+ remaining := map[string]bool{}
+ rows, err := store.db.Query(`SELECT id FROM recovery_points`)
+ if err != nil {
+ t.Fatalf("query ids: %v", err)
+ }
+ defer rows.Close()
+ for rows.Next() {
+ var id string
+ if err := rows.Scan(&id); err != nil {
+ t.Fatalf("scan id: %v", err)
+ }
+ remaining[id] = true
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatalf("rows err: %v", err)
+ }
+
+ if remaining["pve-backup:pve1-vzdump-101"] {
+ t.Fatal("stale point pve-backup:pve1-vzdump-101 should have been removed")
+ }
+ for _, want := range []string{
+ "pve-backup:pve1-vzdump-100", // still enumerated
+ "pve-backup:pve2-vzdump-100", // other instance
+ "pve-snapshot:pve1-snap-100", // other point class
+ "pbs-backup:pbs-pbs1-main-vm-100-1", // other provider
+ } {
+ if !remaining[want] {
+ t.Fatalf("point %q should have survived reconciliation", want)
+ }
+ }
+
+ // The source now reports zero backups (user deleted them all): the scope empties.
+ deleted, err = store.ReconcileInstancePoints(
+ context.Background(),
+ string(recovery.ProviderProxmoxPVE), "pve-backup:", "pve1",
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("ReconcileInstancePoints(empty) error = %v", err)
+ }
+ if deleted != 1 {
+ t.Fatalf("deleted = %d, want 1 (the last pve1 backup point)", deleted)
+ }
+
+ // PBS scope reconciles via repository_ref_json namespace.
+ deleted, err = store.ReconcileInstancePoints(
+ context.Background(),
+ string(recovery.ProviderProxmoxPBS), "pbs-backup:", "pbs1",
+ nil,
+ )
+ if err != nil {
+ t.Fatalf("ReconcileInstancePoints(pbs) error = %v", err)
+ }
+ if deleted != 1 {
+ t.Fatalf("pbs deleted = %d, want 1", deleted)
+ }
+}
+
func TestStore_ListPoints_IgnoresMalformedJSONFields(t *testing.T) {
t.Parallel()