Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
fix: add retention pruning for unified_resources.db (issue #1496)
rcourtman3202b4ab5634
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.goindex deec107cd4..cf444c594a 100644--- a/internal/unifiedresources/store.go+++ b/internal/unifiedresources/store.go@@ -6,6 +6,7 @@ import ("errors""fmt""io"+ "log""net/url""os""path/filepath"@@ -105,6 +106,8 @@ type SQLiteResourceStore struct {identityPinMu sync.MutexidentityPinCache []ResourceIdentityPinidentityPinFresh bool++ retentionStop chan struct{}}const (@@ -169,6 +172,7 @@ func NewSQLiteResourceStore(dataDir, orgID string) (*SQLiteResourceStore, error)}return nil, wrappedInitErr}+ store.retentionStop = store.startRetentionLoop()return store, nil}@@ -877,7 +881,70 @@ func (s *SQLiteResourceStore) GetExclusions() (exclusions []ResourceExclusion, ereturn exclusions, nil}+const (+ resourceChangesRetention = 30 * 24 * time.Hour+ actionAuditsRetention = 90 * 24 * time.Hour+ retentionInterval = 6 * time.Hour+)++// startRetentionLoop launches a background goroutine that periodically+// prunes old rows from resource_changes and action_audits. Without this,+// these append-only tables grow without bound (GitHub issue #1496).+// Returns a stop channel; closing it signals the goroutine to exit.+func (s *SQLiteResourceStore) startRetentionLoop() chan struct{} {+ stop := make(chan struct{})+ go func() {+ ticker := time.NewTicker(retentionInterval)+ defer ticker.Stop()+ for {+ select {+ case <-stop:+ return+ case <-ticker.C:+ s.pruneOldRecords()+ }+ }+ }()+ return stop+}++func (s *SQLiteResourceStore) pruneOldRecords() {+ now := time.Now()+ changesCutoff := now.Add(-resourceChangesRetention)+ auditsCutoff := now.Add(-actionAuditsRetention)++ var totalDeleted int64++ res, err := s.db.Exec(+ `DELETE FROM resource_changes WHERE observed_at < ? OR observed_at IS NULL`,+ changesCutoff.UTC().Format("2006-01-02T15:04:05Z"),+ )+ if err != nil {+ log.Printf("unifiedresources: failed to prune resource_changes: %v", err)+ } else if affected, _ := res.RowsAffected(); affected > 0 {+ totalDeleted += affected+ }++ res, err = s.db.Exec(+ `DELETE FROM action_audits WHERE created_at < ?`,+ auditsCutoff.UTC().Format("2006-01-02T15:04:05Z"),+ )+ if err != nil {+ log.Printf("unifiedresources: failed to prune action_audits: %v", err)+ } else if affected, _ := res.RowsAffected(); affected > 0 {+ totalDeleted += affected+ }++ if totalDeleted > 0 {+ log.Printf("unifiedresources: pruned %d old records (changes<%s, audits<%s)",+ totalDeleted, changesCutoff.Format("2006-01-02"), auditsCutoff.Format("2006-01-02"))+ }+}+func (s *SQLiteResourceStore) Close() error {+ if s.retentionStop != nil {+ close(s.retentionStop)+ }if s.db != nil {if err := s.db.Close(); err != nil {return fmt.Errorf("close resources db %q: %w", s.dbPath, err)diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.goindex e103d39ce2..ada7ce26e6 100644--- a/internal/unifiedresources/store_test.go+++ b/internal/unifiedresources/store_test.go@@ -2391,3 +2391,84 @@ func TestResourceChangeReadsMergeCanonicalIDEras(t *testing.T) {})}}++func TestPruneOldRecords_DeletesExpiredChangesAndAudits(t *testing.T) {+ store := newTestStore(t)++ old := time.Now().Add(-120 * 24 * time.Hour)+ recent := time.Now().Add(-1 * time.Hour)++ changes := []ResourceChange{+ {+ ID: "change-old",+ ObservedAt: old,+ ResourceID: "vm:100",+ Kind: ChangeStateTransition,+ SourceType: SourcePulseDiff,+ Confidence: ConfidenceHigh,+ },+ {+ ID: "change-recent",+ ObservedAt: recent,+ ResourceID: "vm:100",+ Kind: ChangeStateTransition,+ SourceType: SourcePulseDiff,+ Confidence: ConfidenceHigh,+ },+ }+ for _, ch := range changes {+ if err := store.RecordChange(ch); err != nil {+ t.Fatalf("RecordChange(%s): %v", ch.ID, err)+ }+ }++ audits := []ActionAuditRecord{+ {+ ID: "audit-old",+ CreatedAt: old,+ UpdatedAt: old,+ State: ActionStateCompleted,+ Request: ActionRequest{+ RequestID: "req-old",+ ResourceID: "vm:100",+ CapabilityName: "restart",+ RequestedBy: "agent:test",+ },+ },+ {+ ID: "audit-recent",+ CreatedAt: recent,+ UpdatedAt: recent,+ State: ActionStateCompleted,+ Request: ActionRequest{+ RequestID: "req-recent",+ ResourceID: "vm:100",+ CapabilityName: "restart",+ RequestedBy: "agent:test",+ },+ },+ }+ for _, a := range audits {+ if err := store.RecordActionAudit(a); err != nil {+ t.Fatalf("RecordActionAudit(%s): %v", a.ID, err)+ }+ }++ store.pruneOldRecords()++ remaining, err := store.GetRecentChanges("vm:100", time.Time{}, 0)+ if err != nil {+ t.Fatalf("GetRecentChanges after prune: %v", err)+ }+ if len(remaining) != 1 || remaining[0].ID != "change-recent" {+ t.Fatalf("expected only change-recent to survive, got %d: %+v", len(remaining), remaining)+ }++ auditResults, err := store.GetActionAudits("", time.Time{}, 10)+ if err != nil {+ t.Fatalf("GetActionAudits after prune: %v", err)+ }+ if len(auditResults) != 1 || auditResults[0].ID != "audit-recent" {+ t.Fatalf("expected only audit-recent to survive, got %d: %+v", len(auditResults), auditResults)+ }+}