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.

refactor: split active alert cleanup

rcourtman0a1df9568443
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index fd33f30eef..be87edfd44 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -71,6 +71,7 @@ operator-facing alert routing behavior for live runtime alerts.
49. `internal/alerts/active_persistence.go`
50. `internal/alerts/tracking_cleanup.go`
51. `internal/alerts/active_lifecycle.go`
+52. `internal/alerts/active_cleanup.go`
## Shared Boundaries
@@ -248,6 +249,10 @@ That file owns acknowledgement and unacknowledgement, manual active-alert
clearing, preserved alert state during rebuilds, poll-confirmed offline
recovery clears, resolved-alert registration, and no-lock active-alert removal
helpers; future active-alert lifecycle changes should extend that owner.
+Active-alert cleanup now lives in `internal/alerts/active_cleanup.go`. That
+file owns TTL cleanup, auto-acknowledgement cleanup, stale acknowledgement
+retention cleanup, node-retirement cleanup, and full active-alert state reset;
+future cleanup policy changes should extend that owner.
Alert notification policy now lives in `internal/alerts/notification_policy.go`.
That file owns dispatch suppression, flapping suppression, quiet-hours
suppression, monitor-only notification suppression, cooldown decisions, and
diff --git a/internal/alerts/active_cleanup.go b/internal/alerts/active_cleanup.go
new file mode 100644
index 0000000000..0c9d3b6ff7
--- /dev/null
+++ b/internal/alerts/active_cleanup.go
@@ -0,0 +1,324 @@
+package alerts
+
+import (
+ "strings"
+ "time"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+ "github.com/rs/zerolog/log"
+)
+
+// Cleanup removes old acknowledged alerts and cleans up tracking maps.
+func (m *Manager) Cleanup(maxAge time.Duration) {
+ m.mu.Lock()
+ now := time.Now()
+ var autoAcked []*Alert
+
+ lastSeenTooOld := func(alert *Alert, cutoff time.Duration) bool {
+ if alert == nil {
+ return true
+ }
+ lastSeen := alert.LastSeen
+ if lastSeen.IsZero() {
+ lastSeen = alert.StartTime
+ }
+ return now.Sub(lastSeen) > cutoff
+ }
+
+ if m.config.AutoAcknowledgeAfterHours > 0 {
+ autoAckThreshold := time.Duration(m.config.AutoAcknowledgeAfterHours) * time.Hour
+ for id, alert := range m.activeAlerts {
+ if !alert.Acknowledged && now.Sub(alert.StartTime) > autoAckThreshold {
+ log.Info().
+ Str("alertID", id).
+ Dur("age", now.Sub(alert.StartTime)).
+ Msg("Auto-acknowledging old alert")
+ alert.Acknowledged = true
+ ackTime := now
+ alert.AckTime = &ackTime
+ alert.AckUser = "system-auto"
+ autoAcked = append(autoAcked, alert.Clone())
+
+ if recordAlertAcknowledged != nil {
+ recordAlertAcknowledged()
+ }
+ }
+ }
+ }
+
+ if m.config.MaxAcknowledgedAgeDays > 0 {
+ acknowledgedTTL := time.Duration(m.config.MaxAcknowledgedAgeDays) * 24 * time.Hour
+ for id, alert := range m.activeAlerts {
+ if alert.Acknowledged && alert.AckTime != nil &&
+ now.Sub(*alert.AckTime) > acknowledgedTTL &&
+ lastSeenTooOld(alert, acknowledgedTTL) {
+ log.Info().
+ Str("alertID", id).
+ Dur("age", now.Sub(*alert.AckTime)).
+ Msg("Cleaning up old acknowledged alert (TTL)")
+ m.removeActiveAlertNoLock(id)
+ }
+ }
+ }
+
+ if m.config.MaxAlertAgeDays > 0 {
+ alertTTL := time.Duration(m.config.MaxAlertAgeDays) * 24 * time.Hour
+ for id, alert := range m.activeAlerts {
+ if !alert.Acknowledged && now.Sub(alert.StartTime) > alertTTL {
+ log.Info().
+ Str("alertID", id).
+ Dur("age", now.Sub(alert.StartTime)).
+ Msg("Cleaning up old unacknowledged alert (TTL)")
+ m.removeActiveAlertNoLock(id)
+ }
+ }
+ }
+
+ for id, alert := range m.activeAlerts {
+ if alert.Acknowledged && alert.AckTime != nil &&
+ now.Sub(*alert.AckTime) > maxAge &&
+ lastSeenTooOld(alert, maxAge) {
+ m.removeActiveAlertNoLock(id)
+ }
+ }
+
+ ackStateTTL := 1 * time.Hour
+ for id, record := range m.ackState {
+ if !m.hasActiveAlertNoLock(id) {
+ checkTime := record.inactiveAt
+ if checkTime.IsZero() {
+ checkTime = record.time
+ }
+ if now.Sub(checkTime) > ackStateTTL {
+ delete(m.ackState, id)
+ }
+ }
+ }
+ for canonicalID, record := range m.ackStateByCanonical {
+ if m.hasActiveAlertTrackingKeyNoLock(canonicalID) {
+ continue
+ }
+ checkTime := record.inactiveAt
+ if checkTime.IsZero() {
+ checkTime = record.time
+ }
+ if now.Sub(checkTime) > ackStateTTL {
+ delete(m.ackStateByCanonical, canonicalID)
+ }
+ }
+
+ suppressionWindow := time.Duration(m.config.SuppressionWindow) * time.Minute
+ if suppressionWindow == 0 {
+ suppressionWindow = 5 * time.Minute
+ }
+ for id, alert := range m.recentAlerts {
+ if now.Sub(alert.StartTime) > suppressionWindow {
+ delete(m.recentAlerts, id)
+ }
+ }
+
+ for id, suppressUntil := range m.suppressedUntil {
+ if now.After(suppressUntil) {
+ delete(m.suppressedUntil, id)
+ }
+ }
+
+ cutoff := now.Add(-1 * time.Hour)
+ for alertID, times := range m.alertRateLimit {
+ var recentTimes []time.Time
+ for _, t := range times {
+ if t.After(cutoff) {
+ recentTimes = append(recentTimes, t)
+ }
+ }
+ if len(recentTimes) == 0 {
+ delete(m.alertRateLimit, alertID)
+ } else {
+ m.alertRateLimit[alertID] = recentTimes
+ }
+ }
+
+ fiveMinutesAgo := now.Add(-5 * time.Minute)
+ m.resolvedMutex.Lock()
+ for alertID, resolved := range m.recentlyResolved {
+ if resolved.ResolvedTime.Before(fiveMinutesAgo) {
+ m.removeResolvedAlertUnlocked(alertID)
+ }
+ }
+ m.resolvedMutex.Unlock()
+
+ maxPendingAge := 10 * time.Minute
+ for id, pendingTime := range m.pendingAlerts {
+ if now.Sub(pendingTime) > maxPendingAge {
+ delete(m.pendingAlerts, id)
+ log.Debug().
+ Str("resourceID", id).
+ Dur("age", now.Sub(pendingTime)).
+ Msg("Cleaned up stale pending alert entry")
+ }
+ }
+
+ flappingCleanupAge := 1 * time.Hour
+ for alertID := range m.flappingHistory {
+ if !m.hasActiveAlertTrackingKeyNoLock(alertID) {
+ if suppressUntil, suppressed := m.suppressedUntil[alertID]; !suppressed || now.After(suppressUntil.Add(flappingCleanupAge)) {
+ delete(m.flappingHistory, alertID)
+ delete(m.flappingActive, alertID)
+ log.Debug().
+ Str("alertID", alertID).
+ Msg("Cleaned up flapping history for inactive alert")
+ }
+ }
+ }
+
+ for resourceID, record := range m.dockerRestartTracking {
+ if now.Sub(record.lastChecked) > 24*time.Hour {
+ delete(m.dockerRestartTracking, resourceID)
+ log.Debug().
+ Str("resourceID", resourceID).
+ Msg("Cleaned up stale Docker restart tracking entry")
+ }
+ }
+
+ staleTrackerAge := 24 * time.Hour
+ for pmgID, tracker := range m.pmgAnomalyTrackers {
+ if tracker != nil && !tracker.LastSampleTime.IsZero() {
+ if now.Sub(tracker.LastSampleTime) > staleTrackerAge {
+ delete(m.pmgAnomalyTrackers, pmgID)
+ log.Debug().
+ Str("pmgID", pmgID).
+ Time("lastSampleTime", tracker.LastSampleTime).
+ Msg("Cleaned up stale PMG anomaly tracker")
+ }
+ }
+ }
+
+ staleHistoryAge := 7 * 24 * time.Hour
+ for pmgID, snapshots := range m.pmgQuarantineHistory {
+ if len(snapshots) == 0 {
+ delete(m.pmgQuarantineHistory, pmgID)
+ log.Debug().
+ Str("pmgID", pmgID).
+ Msg("Cleaned up empty PMG quarantine history")
+ continue
+ }
+
+ lastSnapshot := snapshots[len(snapshots)-1]
+ if now.Sub(lastSnapshot.Timestamp) > staleHistoryAge {
+ delete(m.pmgQuarantineHistory, pmgID)
+ log.Debug().
+ Str("pmgID", pmgID).
+ Time("lastSnapshot", lastSnapshot.Timestamp).
+ Msg("Cleaned up stale PMG quarantine history")
+ }
+ }
+
+ m.mu.Unlock()
+
+ for _, alert := range autoAcked {
+ m.safeCallAcknowledgedCallback(alert, "system-auto")
+ }
+}
+
+// CleanupAlertsForNodes removes alerts for nodes that no longer exist.
+func (m *Manager) CleanupAlertsForNodes(existingNodes map[string]bool) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ log.Debug().
+ Int("totalAlerts", len(m.activeAlerts)).
+ Int("existingNodes", len(existingNodes)).
+ Interface("nodes", existingNodes).
+ Msg("Starting alert cleanup for non-existent nodes")
+
+ removedCount := 0
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if alert == nil {
+ continue
+ }
+
+ if strings.HasPrefix(alertID, "docker-") || strings.HasPrefix(alert.ResourceID, "docker:") {
+ continue
+ }
+ if strings.HasPrefix(alertID, "pbs-") || alert.Type == "pbs-offline" {
+ continue
+ }
+ if alert.Metadata != nil {
+ if resourceType, _ := alert.Metadata["resourceType"].(string); resourceType == "pbs" {
+ continue
+ }
+ }
+ if alert.CanonicalKind == string(alertspecs.AlertSpecKindConnectivity) && strings.HasPrefix(alert.ResourceID, "pbs") {
+ continue
+ }
+
+ node := alert.Node
+ if node == "" || !existingNodes[node] {
+ m.removeActiveAlertNoLock(alertID)
+ removedCount++
+ log.Debug().Str("alertID", alertID).Str("node", node).Msg("removed alert for non-existent node")
+ }
+ }
+
+ if removedCount > 0 {
+ log.Debug().Int("removed", removedCount).Int("remaining", len(m.activeAlerts)).Msg("cleaned up alerts for non-existent nodes")
+ go func() {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().Interface("panic", r).Msg("panic in SaveActiveAlerts goroutine (cleanup)")
+ }
+ }()
+ if err := m.SaveActiveAlerts(); err != nil {
+ log.Error().Err(err).Msg("failed to save alerts after cleanup")
+ }
+ }()
+ } else {
+ log.Info().Msg("no alerts needed cleanup")
+ }
+}
+
+// ClearActiveAlerts removes all active and pending alerts, resetting the manager state.
+func (m *Manager) ClearActiveAlerts() {
+ m.mu.Lock()
+ if len(m.activeAlerts) == 0 && len(m.pendingAlerts) == 0 {
+ m.mu.Unlock()
+ return
+ }
+ m.activeAlerts = make(map[string]*Alert)
+ m.activeAlertAlias = make(map[string]string)
+ m.pendingAlerts = make(map[string]time.Time)
+ m.recentAlerts = make(map[string]*Alert)
+ m.suppressedUntil = make(map[string]time.Time)
+ m.alertRateLimit = make(map[string][]time.Time)
+ m.nodeOfflineCount = make(map[string]int)
+ m.offlineConfirmations = make(map[string]int)
+ m.offlineRecoveryConfirmations = make(map[string]int)
+ m.dockerOfflineCount = make(map[string]int)
+ m.dockerStateConfirm = make(map[string]int)
+ m.dockerRestartTracking = make(map[string]*dockerRestartRecord)
+ m.dockerLastExitCode = make(map[string]int)
+ m.dockerUpdateFirstSeen = make(map[string]time.Time)
+ m.dockerUpdateFirstSeenByIdentity = make(map[string]time.Time)
+ m.ackState = make(map[string]ackRecord)
+ m.ackStateByCanonical = make(map[string]ackRecord)
+ m.mu.Unlock()
+
+ m.resolvedMutex.Lock()
+ m.recentlyResolved = make(map[string]*ResolvedAlert)
+ m.resolvedAlias = make(map[string]string)
+ m.resolvedMutex.Unlock()
+
+ log.Info().Msg("cleared all active and pending alerts")
+
+ go func() {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().Interface("panic", r).Msg("panic in SaveActiveAlerts goroutine (clear)")
+ }
+ }()
+ if err := m.SaveActiveAlerts(); err != nil {
+ log.Error().Err(err).Msg("failed to persist cleared alerts")
+ }
+ }()
+}
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.go
index 6173a25e91..58a10c0f25 100644
--- a/internal/alerts/alerts.go
+++ b/internal/alerts/alerts.go
@@ -8,7 +8,6 @@ import (
"time"
alertconfig "github.com/rcourtman/pulse-go-rewrite/internal/alerts/config"
- alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
"github.com/rcourtman/pulse-go-rewrite/internal/utils"
"github.com/rs/zerolog/log"
)
@@ -512,245 +511,6 @@ func (m *Manager) SetLicenseChecker(checker func(feature string) bool) {
m.hasProFeature = checker
}
-// Cleanup removes old acknowledged alerts and cleans up tracking maps
-func (m *Manager) Cleanup(maxAge time.Duration) {
- m.mu.Lock()
- now := time.Now()
- var autoAcked []*Alert
-
- lastSeenTooOld := func(alert *Alert, cutoff time.Duration) bool {
- if alert == nil {
- return true
- }
- lastSeen := alert.LastSeen
- if lastSeen.IsZero() {
- lastSeen = alert.StartTime
- }
- return now.Sub(lastSeen) > cutoff
- }
-
- // Auto-acknowledge old alerts if configured
- if m.config.AutoAcknowledgeAfterHours > 0 {
- autoAckThreshold := time.Duration(m.config.AutoAcknowledgeAfterHours) * time.Hour
- for id, alert := range m.activeAlerts {
- if !alert.Acknowledged && now.Sub(alert.StartTime) > autoAckThreshold {
- log.Info().
- Str("alertID", id).
- Dur("age", now.Sub(alert.StartTime)).
- Msg("Auto-acknowledging old alert")
- alert.Acknowledged = true
- ackTime := now
- alert.AckTime = &ackTime
- alert.AckUser = "system-auto"
- autoAcked = append(autoAcked, alert.Clone())
-
- if recordAlertAcknowledged != nil {
- recordAlertAcknowledged()
- }
- }
- }
- }
-
- // Clean up acknowledged alerts based on TTL
- if m.config.MaxAcknowledgedAgeDays > 0 {
- acknowledgedTTL := time.Duration(m.config.MaxAcknowledgedAgeDays) * 24 * time.Hour
- for id, alert := range m.activeAlerts {
- if alert.Acknowledged && alert.AckTime != nil &&
- now.Sub(*alert.AckTime) > acknowledgedTTL &&
- lastSeenTooOld(alert, acknowledgedTTL) {
- log.Info().
- Str("alertID", id).
- Dur("age", now.Sub(*alert.AckTime)).
- Msg("Cleaning up old acknowledged alert (TTL)")
- m.removeActiveAlertNoLock(id)
- }
- }
- }
-
- // Clean up old unacknowledged alerts based on TTL
- if m.config.MaxAlertAgeDays > 0 {
- alertTTL := time.Duration(m.config.MaxAlertAgeDays) * 24 * time.Hour
- for id, alert := range m.activeAlerts {
- if !alert.Acknowledged && now.Sub(alert.StartTime) > alertTTL {
- log.Info().
- Str("alertID", id).
- Dur("age", now.Sub(alert.StartTime)).
- Msg("Cleaning up old unacknowledged alert (TTL)")
- m.removeActiveAlertNoLock(id)
- }
- }
- }
-
- // Original cleanup for acknowledged alerts (fallback if TTL not configured)
- for id, alert := range m.activeAlerts {
- if alert.Acknowledged && alert.AckTime != nil &&
- now.Sub(*alert.AckTime) > maxAge &&
- lastSeenTooOld(alert, maxAge) {
- m.removeActiveAlertNoLock(id)
- }
- }
-
- // Clean up stale ackState entries for alerts that no longer exist
- // Keep ackState for 1 hour after the alert was removed (not from ack time)
- // to handle transient alert clears (e.g., backups of powered-off VMs)
- ackStateTTL := 1 * time.Hour
- for id, record := range m.ackState {
- if !m.hasActiveAlertNoLock(id) {
- // Use inactiveAt (when alert was removed) for TTL, not ack time
- checkTime := record.inactiveAt
- if checkTime.IsZero() {
- // Fallback for legacy entries without inactiveAt
- checkTime = record.time
- }
- if now.Sub(checkTime) > ackStateTTL {
- delete(m.ackState, id)
- }
- }
- }
- for canonicalID, record := range m.ackStateByCanonical {
- if m.hasActiveAlertTrackingKeyNoLock(canonicalID) {
- continue
- }
- checkTime := record.inactiveAt
- if checkTime.IsZero() {
- checkTime = record.time
- }
- if now.Sub(checkTime) > ackStateTTL {
- delete(m.ackStateByCanonical, canonicalID)
- }
- }
-
- // Clean up recent alerts older than suppression window
- suppressionWindow := time.Duration(m.config.SuppressionWindow) * time.Minute
- if suppressionWindow == 0 {
- suppressionWindow = 5 * time.Minute // Default
- }
-
- for id, alert := range m.recentAlerts {
- if now.Sub(alert.StartTime) > suppressionWindow {
- delete(m.recentAlerts, id)
- }
- }
-
- // Clean up expired suppressions
- for id, suppressUntil := range m.suppressedUntil {
- if now.After(suppressUntil) {
- delete(m.suppressedUntil, id)
- }
- }
-
- // Clean up old rate limit entries (older than 1 hour)
- cutoff := now.Add(-1 * time.Hour)
- for alertID, times := range m.alertRateLimit {
- var recentTimes []time.Time
- for _, t := range times {
- if t.After(cutoff) {
- recentTimes = append(recentTimes, t)
- }
- }
- if len(recentTimes) == 0 {
- // No recent alerts, remove the entry entirely
- delete(m.alertRateLimit, alertID)
- } else {
- // Update with only recent times
- m.alertRateLimit[alertID] = recentTimes
- }
- }
-
- // Clean up old recently resolved alerts (older than 5 minutes)
- fiveMinutesAgo := now.Add(-5 * time.Minute)
- m.resolvedMutex.Lock()
- for alertID, resolved := range m.recentlyResolved {
- if resolved.ResolvedTime.Before(fiveMinutesAgo) {
- m.removeResolvedAlertUnlocked(alertID)
- }
- }
- m.resolvedMutex.Unlock()
-
- // Clean up stale pending alerts (older than max time threshold window)
- // This prevents memory leak from deleted resources that never triggered alerts
- maxPendingAge := 10 * time.Minute // Longest time threshold + safety buffer
- for id, pendingTime := range m.pendingAlerts {
- if now.Sub(pendingTime) > maxPendingAge {
- delete(m.pendingAlerts, id)
- log.Debug().
- Str("resourceID", id).
- Dur("age", now.Sub(pendingTime)).
- Msg("Cleaned up stale pending alert entry")
- }
- }
-
- // Clean up flapping history for resolved/inactive alerts
- flappingCleanupAge := 1 * time.Hour
- for alertID := range m.flappingHistory {
- // If alert is no longer active and flapping cooldown has expired
- if !m.hasActiveAlertTrackingKeyNoLock(alertID) {
- if suppressUntil, suppressed := m.suppressedUntil[alertID]; !suppressed || now.After(suppressUntil.Add(flappingCleanupAge)) {
- delete(m.flappingHistory, alertID)
- delete(m.flappingActive, alertID)
- log.Debug().
- Str("alertID", alertID).
- Msg("Cleaned up flapping history for inactive alert")
- }
- }
- }
-
- // Clean up old Docker restart tracking (containers not seen in 24h)
- // Prevents memory leak from ephemeral containers in CI/CD environments
- for resourceID, record := range m.dockerRestartTracking {
- if now.Sub(record.lastChecked) > 24*time.Hour {
- delete(m.dockerRestartTracking, resourceID)
- log.Debug().
- Str("resourceID", resourceID).
- Msg("Cleaned up stale Docker restart tracking entry")
- }
- }
-
- // Clean up stale PMG anomaly trackers (no samples in 24h)
- // Prevents memory leak from decommissioned or transient PMG instances
- staleTrackerAge := 24 * time.Hour
- for pmgID, tracker := range m.pmgAnomalyTrackers {
- if tracker != nil && !tracker.LastSampleTime.IsZero() {
- if now.Sub(tracker.LastSampleTime) > staleTrackerAge {
- delete(m.pmgAnomalyTrackers, pmgID)
- log.Debug().
- Str("pmgID", pmgID).
- Time("lastSampleTime", tracker.LastSampleTime).
- Msg("Cleaned up stale PMG anomaly tracker")
- }
- }
- }
-
- // Clean up stale PMG quarantine history (no recent snapshots in 7 days)
- // Prevents memory leak from deleted PMG instances
- staleHistoryAge := 7 * 24 * time.Hour
- for pmgID, snapshots := range m.pmgQuarantineHistory {
- // If no snapshots remain or last snapshot is very old
- if len(snapshots) == 0 {
- delete(m.pmgQuarantineHistory, pmgID)
- log.Debug().
- Str("pmgID", pmgID).
- Msg("Cleaned up empty PMG quarantine history")
- continue
- }
-
- lastSnapshot := snapshots[len(snapshots)-1]
- if now.Sub(lastSnapshot.Timestamp) > staleHistoryAge {
- delete(m.pmgQuarantineHistory, pmgID)
- log.Debug().
- Str("pmgID", pmgID).
- Time("lastSnapshot", lastSnapshot.Timestamp).
- Msg("Cleaned up stale PMG quarantine history")
- }
- }
-
- m.mu.Unlock()
-
- for _, alert := range autoAcked {
- m.safeCallAcknowledgedCallback(alert, "system-auto")
- }
-}
-
// escalationChecker runs periodically to check for alerts that need escalation and cleanup
func (m *Manager) escalationChecker() {
ticker := time.NewTicker(1 * time.Minute)
@@ -850,112 +610,3 @@ func closeSignalChannel(ch chan struct{}) {
}()
close(ch)
}
-
-// CleanupAlertsForNodes removes alerts for nodes that no longer exist
-func (m *Manager) CleanupAlertsForNodes(existingNodes map[string]bool) {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- log.Debug().
- Int("totalAlerts", len(m.activeAlerts)).
- Int("existingNodes", len(existingNodes)).
- Interface("nodes", existingNodes).
- Msg("Starting alert cleanup for non-existent nodes")
-
- removedCount := 0
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if alert == nil {
- continue
- }
-
- // Skip alerts that are not tied to Proxmox nodes. Docker and PBS resources use
- // synthetic node identifiers that won't appear in the Proxmox node list, so we
- // must preserve their alerts here.
- if strings.HasPrefix(alertID, "docker-") || strings.HasPrefix(alert.ResourceID, "docker:") {
- continue
- }
- if strings.HasPrefix(alertID, "pbs-") || alert.Type == "pbs-offline" {
- continue
- }
- if alert.Metadata != nil {
- if resourceType, _ := alert.Metadata["resourceType"].(string); resourceType == "pbs" {
- continue
- }
- }
- if alert.CanonicalKind == string(alertspecs.AlertSpecKindConnectivity) && strings.HasPrefix(alert.ResourceID, "pbs") {
- continue
- }
- // Use the Node field from the alert itself, which is more reliable
- node := alert.Node
-
- // If we couldn't get a node or the node doesn't exist, remove the alert
- if node == "" || !existingNodes[node] {
- m.removeActiveAlertNoLock(alertID)
- removedCount++
- log.Debug().Str("alertID", alertID).Str("node", node).Msg("removed alert for non-existent node")
- }
- }
-
- if removedCount > 0 {
- log.Debug().Int("removed", removedCount).Int("remaining", len(m.activeAlerts)).Msg("cleaned up alerts for non-existent nodes")
- // Save the cleaned up state
- go func() {
- defer func() {
- if r := recover(); r != nil {
- log.Error().Interface("panic", r).Msg("panic in SaveActiveAlerts goroutine (cleanup)")
- }
- }()
- if err := m.SaveActiveAlerts(); err != nil {
- log.Error().Err(err).Msg("failed to save alerts after cleanup")
- }
- }()
- } else {
- log.Info().Msg("no alerts needed cleanup")
- }
-}
-
-// ClearActiveAlerts removes all active and pending alerts, resetting the manager state.
-func (m *Manager) ClearActiveAlerts() {
- m.mu.Lock()
- if len(m.activeAlerts) == 0 && len(m.pendingAlerts) == 0 {
- m.mu.Unlock()
- return
- }
- m.activeAlerts = make(map[string]*Alert)
- m.activeAlertAlias = make(map[string]string)
- m.pendingAlerts = make(map[string]time.Time)
- m.recentAlerts = make(map[string]*Alert)
- m.suppressedUntil = make(map[string]time.Time)
- m.alertRateLimit = make(map[string][]time.Time)
- m.nodeOfflineCount = make(map[string]int)
- m.offlineConfirmations = make(map[string]int)
- m.offlineRecoveryConfirmations = make(map[string]int)
- m.dockerOfflineCount = make(map[string]int)
- m.dockerStateConfirm = make(map[string]int)
- m.dockerRestartTracking = make(map[string]*dockerRestartRecord)
- m.dockerLastExitCode = make(map[string]int)
- m.dockerUpdateFirstSeen = make(map[string]time.Time)
- m.dockerUpdateFirstSeenByIdentity = make(map[string]time.Time)
- m.ackState = make(map[string]ackRecord)
- m.ackStateByCanonical = make(map[string]ackRecord)
- m.mu.Unlock()
-
- m.resolvedMutex.Lock()
- m.recentlyResolved = make(map[string]*ResolvedAlert)
- m.resolvedAlias = make(map[string]string)
- m.resolvedMutex.Unlock()
-
- log.Info().Msg("cleared all active and pending alerts")
-
- go func() {
- defer func() {
- if r := recover(); r != nil {
- log.Error().Interface("panic", r).Msg("panic in SaveActiveAlerts goroutine (clear)")
- }
- }()
- if err := m.SaveActiveAlerts(); err != nil {
- log.Error().Err(err).Msg("failed to persist cleared alerts")
- }
- }()
-}
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index 5c804558bc..32fcf3a8b6 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -6511,15 +6511,22 @@ func TestClearActiveAlertsWithExistingAlerts(t *testing.T) {
m.mu.Lock()
m.activeAlerts["test-alert-1"] = &Alert{ID: "test-alert-1", Type: "cpu-usage"}
m.activeAlerts["test-alert-2"] = &Alert{ID: "test-alert-2", Type: "memory-usage"}
+ m.activeAlertAlias["canonical-test-alert-1"] = "test-alert-1"
m.pendingAlerts["pending-1"] = time.Now()
m.recentAlerts["recent-1"] = &Alert{ID: "recent-1", Type: "disk-usage"}
m.suppressedUntil["suppressed-1"] = time.Now().Add(time.Hour)
m.alertRateLimit["rate-1"] = []time.Time{time.Now()}
m.nodeOfflineCount["node-1"] = 3
m.offlineConfirmations["node-1"] = 2
+ m.offlineRecoveryConfirmations["test-alert-1"] = 2
m.dockerOfflineCount["docker-1"] = 1
m.dockerStateConfirm["docker-1"] = 1
+ m.dockerRestartTracking["docker-1"] = &dockerRestartRecord{}
+ m.dockerLastExitCode["docker-1"] = 137
+ m.dockerUpdateFirstSeen["docker-1"] = time.Now()
+ m.dockerUpdateFirstSeenByIdentity["docker-1"] = time.Now()
m.ackState["test-alert-1"] = ackRecord{acknowledged: true, user: "testuser", time: time.Now()}
+ m.ackStateByCanonical["canonical-test-alert-1"] = ackRecord{acknowledged: true, user: "testuser", time: time.Now()}
m.mu.Unlock()
m.resolvedMutex.Lock()
@@ -6537,6 +6544,9 @@ func TestClearActiveAlertsWithExistingAlerts(t *testing.T) {
if len(m.activeAlerts) != 0 {
t.Errorf("expected activeAlerts to be empty, got %d", len(m.activeAlerts))
}
+ if len(m.activeAlertAlias) != 0 {
+ t.Errorf("expected activeAlertAlias to be empty, got %d", len(m.activeAlertAlias))
+ }
if len(m.pendingAlerts) != 0 {
t.Errorf("expected pendingAlerts to be empty, got %d", len(m.pendingAlerts))
}
@@ -6555,15 +6565,33 @@ func TestClearActiveAlertsWithExistingAlerts(t *testing.T) {
if len(m.offlineConfirmations) != 0 {
t.Errorf("expected offlineConfirmations to be empty, got %d", len(m.offlineConfirmations))
}
+ if len(m.offlineRecoveryConfirmations) != 0 {
+ t.Errorf("expected offlineRecoveryConfirmations to be empty, got %d", len(m.offlineRecoveryConfirmations))
+ }
if len(m.dockerOfflineCount) != 0 {
t.Errorf("expected dockerOfflineCount to be empty, got %d", len(m.dockerOfflineCount))
}
if len(m.dockerStateConfirm) != 0 {
t.Errorf("expected dockerStateConfirm to be empty, got %d", len(m.dockerStateConfirm))
}
+ if len(m.dockerRestartTracking) != 0 {
+ t.Errorf("expected dockerRestartTracking to be empty, got %d", len(m.dockerRestartTracking))
+ }
+ if len(m.dockerLastExitCode) != 0 {
+ t.Errorf("expected dockerLastExitCode to be empty, got %d", len(m.dockerLastExitCode))
+ }
+ if len(m.dockerUpdateFirstSeen) != 0 {
+ t.Errorf("expected dockerUpdateFirstSeen to be empty, got %d", len(m.dockerUpdateFirstSeen))
+ }
+ if len(m.dockerUpdateFirstSeenByIdentity) != 0 {
+ t.Errorf("expected dockerUpdateFirstSeenByIdentity to be empty, got %d", len(m.dockerUpdateFirstSeenByIdentity))
+ }
if len(m.ackState) != 0 {
t.Errorf("expected ackState to be empty, got %d", len(m.ackState))
}
+ if len(m.ackStateByCanonical) != 0 {
+ t.Errorf("expected ackStateByCanonical to be empty, got %d", len(m.ackStateByCanonical))
+ }
m.mu.RUnlock()
m.resolvedMutex.RLock()