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 lifecycle

rcourtmanfeb2eb2f1baa
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index e25e272607..fd33f30eef 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -70,6 +70,7 @@ operator-facing alert routing behavior for live runtime alerts.
48. `internal/alerts/config_runtime.go`
49. `internal/alerts/active_persistence.go`
50. `internal/alerts/tracking_cleanup.go`
+51. `internal/alerts/active_lifecycle.go`
## Shared Boundaries
@@ -242,6 +243,11 @@ file owns stale flapping, suppression, pending-alert, offline-confirmation,
Docker tracking, rate-limit, recent-alert, acknowledgement, and stale active
alert cleanup; future cleanup rules should extend that owner rather than
mixing cleanup into resource evaluators.
+Active-alert lifecycle now lives in `internal/alerts/active_lifecycle.go`.
+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.
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_lifecycle.go b/internal/alerts/active_lifecycle.go
new file mode 100644
index 0000000000..9e78910f22
--- /dev/null
+++ b/internal/alerts/active_lifecycle.go
@@ -0,0 +1,342 @@
+package alerts
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// addRecentlyResolvedUnlocked records a resolved alert assuming the caller does not hold m.mu.
+func (m *Manager) addRecentlyResolvedUnlocked(resolved *ResolvedAlert) {
+ m.resolvedMutex.Lock()
+ if resolved == nil || resolved.Alert == nil {
+ m.resolvedMutex.Unlock()
+ return
+ }
+ storageKey := activeAlertStorageKey(resolved.Alert, resolved.Alert.ID)
+ m.recentlyResolved[storageKey] = resolved
+ m.registerResolvedAliasUnlocked(storageKey, resolved)
+ m.resolvedMutex.Unlock()
+}
+
+// addRecentlyResolvedWithPrimaryLock records a resolved alert while preserving the caller's
+// ownership of m.mu. Callers must hold m.mu before invoking this helper.
+func (m *Manager) addRecentlyResolvedWithPrimaryLock(resolved *ResolvedAlert) {
+ m.mu.Unlock()
+ m.addRecentlyResolvedUnlocked(resolved)
+ m.mu.Lock()
+}
+
+// clearAlert removes an alert if it exists.
+func (m *Manager) clearAlert(alertID string) {
+ m.mu.Lock()
+ alert, exists := m.getActiveAlertNoLock(alertID)
+ if exists {
+ m.removeActiveAlertNoLock(alertID)
+ }
+ m.mu.Unlock()
+
+ if !exists {
+ return
+ }
+
+ publicID := effectiveAlertID(alert, alertID)
+ resolvedAlert := &ResolvedAlert{
+ Alert: alert,
+ ResolvedTime: time.Now(),
+ }
+
+ m.addRecentlyResolvedUnlocked(resolvedAlert)
+
+ m.safeCallResolvedAlertCallback(alert, publicID, false)
+
+ log.Info().
+ Str("alertID", publicID).
+ Msg("Alert cleared")
+}
+
+// AcknowledgeAlert acknowledges an alert.
+func (m *Manager) AcknowledgeAlert(alertID, user string) error {
+ m.mu.Lock()
+
+ key, exists := m.resolveActiveAlertKeyNoLock(alertID)
+ if !exists {
+ m.mu.Unlock()
+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
+ }
+ alert, ok := m.getActiveAlertNoLock(key)
+ if !ok || alert == nil {
+ m.mu.Unlock()
+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
+ }
+
+ alert.Acknowledged = true
+ now := time.Now()
+ alert.AckTime = &now
+ alert.AckUser = user
+
+ m.setActiveAlertNoLock(key, alert)
+ m.setAckRecordNoLock(alert, alertID, ackRecord{
+ acknowledged: true,
+ user: user,
+ time: now,
+ })
+
+ alertCopy := alert.Clone()
+ m.mu.Unlock()
+
+ log.Debug().
+ Str("alertID", alertID).
+ Str("user", user).
+ Time("ackTime", now).
+ Msg("Alert acknowledgment recorded")
+
+ m.safeCallAcknowledgedCallback(alertCopy, user)
+ return nil
+}
+
+// UnacknowledgeAlert removes the acknowledged status from an alert.
+func (m *Manager) UnacknowledgeAlert(alertID string) error {
+ m.mu.Lock()
+
+ key, exists := m.resolveActiveAlertKeyNoLock(alertID)
+ if !exists {
+ m.mu.Unlock()
+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
+ }
+ alert, ok := m.getActiveAlertNoLock(key)
+ if !ok || alert == nil {
+ m.mu.Unlock()
+ return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
+ }
+
+ alert.Acknowledged = false
+ alert.AckTime = nil
+ alert.AckUser = ""
+
+ m.setActiveAlertNoLock(key, alert)
+ m.deleteAckRecordNoLock(alert, alertID)
+
+ alertCopy := alert.Clone()
+ m.mu.Unlock()
+
+ log.Info().
+ Str("alertID", alertID).
+ Msg("Alert unacknowledged")
+
+ m.safeCallUnacknowledgedCallback(alertCopy, "")
+ return nil
+}
+
+// preserveAlertState copies acknowledgement and escalation metadata from an existing alert
+// into a freshly constructed alert before it replaces the existing entry in the map. This
+// prevents UI state from regressing when alerts are rebuilt during polling.
+func (m *Manager) preserveAlertState(alertID string, updated *Alert) {
+ if updated == nil {
+ return
+ }
+ backfillCanonicalIdentity(updated)
+
+ if updated.NodeDisplayName == "" && updated.Node != "" {
+ updated.NodeDisplayName = m.resolveNodeDisplayName(updated.Instance, updated.Node)
+ }
+
+ existing, exists := m.getActiveAlertNoLock(alertID)
+ if exists && existing != nil {
+ updated.StartTime = existing.StartTime
+ if existing.LastNotified != nil {
+ t := *existing.LastNotified
+ updated.LastNotified = &t
+ } else {
+ updated.LastNotified = nil
+ }
+ updated.Acknowledged = existing.Acknowledged
+ updated.AckUser = existing.AckUser
+ if existing.AckTime != nil {
+ t := *existing.AckTime
+ updated.AckTime = &t
+ } else {
+ updated.AckTime = nil
+ }
+ updated.LastEscalation = existing.LastEscalation
+ if len(existing.EscalationTimes) > 0 {
+ updated.EscalationTimes = append([]time.Time(nil), existing.EscalationTimes...)
+ } else {
+ updated.EscalationTimes = nil
+ }
+
+ log.Debug().
+ Str("alertID", alertID).
+ Time("originalStartTime", existing.StartTime).
+ Dur("currentDuration", time.Since(existing.StartTime)).
+ Msg("Preserving alert state including StartTime")
+ return
+ }
+
+ if record, ok := m.getAckRecordNoLock(updated, alertID); ok && record.acknowledged {
+ updated.Acknowledged = true
+ updated.AckUser = record.user
+ t := record.time
+ updated.AckTime = &t
+ }
+}
+
+func (m *Manager) removeActiveAlertNoLock(alertID string) {
+ publicID := alertID
+ var currentAlert *Alert
+ key, exists := m.resolveActiveAlertKeyNoLock(alertID)
+ if !exists {
+ key, exists = m.resolveActiveAlertKeyByCanonicalStateNoLock(alertID)
+ }
+ if alert, ok := m.getActiveAlertNoLock(alertID); exists && ok && alert != nil {
+ currentAlert = alert
+ backfillCanonicalIdentity(alert)
+ publicID = effectiveAlertID(alert, alertID)
+ m.historyManager.UpdateAlertLastSeenForAlert(alert, alert.LastSeen)
+ m.unregisterActiveAlertAliasNoLock(key, alert)
+ }
+ if exists {
+ delete(m.offlineRecoveryConfirmations, key)
+ delete(m.activeAlerts, key)
+ }
+ delete(m.offlineRecoveryConfirmations, alertID)
+
+ // Preserve acknowledgement state so quick alert rebuilds keep user intent.
+ if exists {
+ m.markAckInactiveNoLock(currentAlert, publicID, time.Now())
+ }
+}
+
+func (m *Manager) confirmOfflineRecoveryNoLock(alertID string, required int) (int, bool) {
+ alertID = strings.TrimSpace(alertID)
+ if alertID == "" {
+ return 0, false
+ }
+
+ if required <= 1 {
+ delete(m.offlineRecoveryConfirmations, alertID)
+ return required, true
+ }
+
+ m.offlineRecoveryConfirmations[alertID]++
+ confirmations := m.offlineRecoveryConfirmations[alertID]
+ if confirmations < required {
+ return confirmations, false
+ }
+
+ delete(m.offlineRecoveryConfirmations, alertID)
+ return confirmations, true
+}
+
+// clearResourceOfflineAlert removes an offline alert when a poll-driven resource
+// stays healthy for enough consecutive polls to confirm recovery.
+func (m *Manager) clearResourceOfflineAlert(resourceID, resourceName, host, resourceKind string, requiredRecoveryCount int) {
+ alertID := canonicalConnectivityStateID(resourceID)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if count, exists := m.offlineConfirmations[resourceID]; exists && count > 0 {
+ log.Debug().
+ Str(strings.ToLower(resourceKind), resourceName).
+ Int("previousCount", count).
+ Msg(resourceKind + " is online, resetting offline confirmation count")
+ delete(m.offlineConfirmations, resourceID)
+ }
+
+ alert, exists := m.getActiveAlertNoLock(alertID)
+ if !exists {
+ delete(m.offlineRecoveryConfirmations, alertID)
+ return
+ }
+
+ recoveryCount, confirmed := m.confirmOfflineRecoveryNoLock(alertID, requiredRecoveryCount)
+ if !confirmed {
+ log.Debug().
+ Str(strings.ToLower(resourceKind), resourceName).
+ Int("confirmations", recoveryCount).
+ Int("required", requiredRecoveryCount).
+ Msg(resourceKind + " appears back online, waiting for recovery confirmation")
+ return
+ }
+
+ m.removeActiveAlertNoLock(alertID)
+
+ resolvedAlert := &ResolvedAlert{
+ Alert: alert,
+ ResolvedTime: time.Now(),
+ }
+ m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
+
+ m.safeCallResolvedAlertCallback(alert, alertID, true)
+
+ log.Info().
+ Str(strings.ToLower(resourceKind), resourceName).
+ Str("host", host).
+ Dur("downtime", time.Since(alert.StartTime)).
+ Msg(resourceKind + " instance is back online")
+}
+
+// ClearAlert removes an alert from active alerts while keeping it in history.
+func (m *Manager) ClearAlert(alertID string) bool {
+ m.mu.Lock()
+ alert, exists := m.getActiveAlertNoLock(alertID)
+ if !exists || alert == nil {
+ m.mu.Unlock()
+ return false
+ }
+ trackingKey := canonicalTrackingKeyForAlert(alert)
+
+ m.clearAlertNoLock(alertID)
+ delete(m.recentAlerts, alertID)
+ delete(m.pendingAlerts, alertID)
+ delete(m.suppressedUntil, alertID)
+ delete(m.alertRateLimit, alertID)
+ if trackingKey != "" && trackingKey != alertID {
+ delete(m.recentAlerts, trackingKey)
+ delete(m.pendingAlerts, trackingKey)
+ delete(m.suppressedUntil, trackingKey)
+ delete(m.alertRateLimit, trackingKey)
+ }
+ m.mu.Unlock()
+
+ m.saveActiveAlertsAsync("manual-clear")
+ return true
+}
+
+// clearAlertNoLock clears an alert without locking. Caller must hold m.mu.
+func (m *Manager) clearAlertNoLock(alertID string) {
+ alert, exists := m.getActiveAlertNoLock(alertID)
+ if !exists {
+ return
+ }
+ publicID := effectiveAlertID(alert, alertID)
+
+ if recordAlertResolved != nil {
+ recordAlertResolved(alert)
+ }
+
+ m.removeActiveAlertNoLock(alertID)
+ resolvedAlert := &ResolvedAlert{
+ Alert: alert,
+ ResolvedTime: time.Now(),
+ }
+
+ m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
+
+ m.safeCallResolvedAlertCallback(alert, publicID, true)
+
+ log.Info().
+ Str("alertID", publicID).
+ Msg("Alert cleared")
+}
+
+func (m *Manager) clearActiveAlertIfPresentNoLock(alertID string) bool {
+ if _, exists := m.getActiveAlertNoLock(alertID); !exists {
+ return false
+ }
+ m.clearAlertNoLock(alertID)
+ return true
+}
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.go
index 0ed963d1da..6173a25e91 100644
--- a/internal/alerts/alerts.go
+++ b/internal/alerts/alerts.go
@@ -2,7 +2,6 @@ package alerts
import (
"errors"
- "fmt"
"path/filepath"
"strings"
"sync"
@@ -513,316 +512,6 @@ func (m *Manager) SetLicenseChecker(checker func(feature string) bool) {
m.hasProFeature = checker
}
-// addRecentlyResolvedUnlocked records a resolved alert assuming the caller does not hold m.mu.
-func (m *Manager) addRecentlyResolvedUnlocked(resolved *ResolvedAlert) {
- m.resolvedMutex.Lock()
- if resolved == nil || resolved.Alert == nil {
- m.resolvedMutex.Unlock()
- return
- }
- storageKey := activeAlertStorageKey(resolved.Alert, resolved.Alert.ID)
- m.recentlyResolved[storageKey] = resolved
- m.registerResolvedAliasUnlocked(storageKey, resolved)
- m.resolvedMutex.Unlock()
-}
-
-// addRecentlyResolvedWithPrimaryLock records a resolved alert while preserving the caller's
-// ownership of m.mu. Callers must hold m.mu before invoking this helper.
-func (m *Manager) addRecentlyResolvedWithPrimaryLock(resolved *ResolvedAlert) {
- m.mu.Unlock()
- m.addRecentlyResolvedUnlocked(resolved)
- m.mu.Lock()
-}
-
-// clearAlert removes an alert if it exists
-func (m *Manager) clearAlert(alertID string) {
- m.mu.Lock()
- alert, exists := m.getActiveAlertNoLock(alertID)
- if exists {
- m.removeActiveAlertNoLock(alertID)
- }
- m.mu.Unlock()
-
- if !exists {
- return
- }
-
- publicID := effectiveAlertID(alert, alertID)
- resolvedAlert := &ResolvedAlert{
- Alert: alert,
- ResolvedTime: time.Now(),
- }
-
- m.addRecentlyResolvedUnlocked(resolvedAlert)
-
- m.safeCallResolvedAlertCallback(alert, publicID, false)
-
- log.Info().
- Str("alertID", publicID).
- Msg("Alert cleared")
-}
-
-// AcknowledgeAlert acknowledges an alert
-func (m *Manager) AcknowledgeAlert(alertID, user string) error {
- m.mu.Lock()
-
- key, exists := m.resolveActiveAlertKeyNoLock(alertID)
- if !exists {
- m.mu.Unlock()
- return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
- }
- alert, ok := m.getActiveAlertNoLock(key)
- if !ok || alert == nil {
- m.mu.Unlock()
- return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
- }
-
- alert.Acknowledged = true
- now := time.Now()
- alert.AckTime = &now
- alert.AckUser = user
-
- m.setActiveAlertNoLock(key, alert)
- m.setAckRecordNoLock(alert, alertID, ackRecord{
- acknowledged: true,
- user: user,
- time: now,
- })
-
- alertCopy := alert.Clone()
- m.mu.Unlock()
-
- log.Debug().
- Str("alertID", alertID).
- Str("user", user).
- Time("ackTime", now).
- Msg("Alert acknowledgment recorded")
-
- m.safeCallAcknowledgedCallback(alertCopy, user)
- return nil
-}
-
-// UnacknowledgeAlert removes the acknowledged status from an alert
-func (m *Manager) UnacknowledgeAlert(alertID string) error {
- m.mu.Lock()
-
- key, exists := m.resolveActiveAlertKeyNoLock(alertID)
- if !exists {
- m.mu.Unlock()
- return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
- }
- alert, ok := m.getActiveAlertNoLock(key)
- if !ok || alert == nil {
- m.mu.Unlock()
- return fmt.Errorf("%w: %s", ErrAlertNotFound, alertID)
- }
-
- alert.Acknowledged = false
- alert.AckTime = nil
- alert.AckUser = ""
-
- m.setActiveAlertNoLock(key, alert)
- m.deleteAckRecordNoLock(alert, alertID)
-
- alertCopy := alert.Clone()
- m.mu.Unlock()
-
- log.Info().
- Str("alertID", alertID).
- Msg("Alert unacknowledged")
-
- m.safeCallUnacknowledgedCallback(alertCopy, "")
- return nil
-}
-
-// preserveAlertState copies acknowledgement and escalation metadata from an existing alert
-// into a freshly constructed alert before it replaces the existing entry in the map. This
-// prevents UI state from regressing when alerts are rebuilt during polling.
-func (m *Manager) preserveAlertState(alertID string, updated *Alert) {
- if updated == nil {
- return
- }
- backfillCanonicalIdentity(updated)
-
- // Auto-resolve node display name if not already set.
- if updated.NodeDisplayName == "" && updated.Node != "" {
- updated.NodeDisplayName = m.resolveNodeDisplayName(updated.Instance, updated.Node)
- }
-
- existing, exists := m.getActiveAlertNoLock(alertID)
- if exists && existing != nil {
- // Preserve the original start time so duration calculations are correct
- updated.StartTime = existing.StartTime
- if existing.LastNotified != nil {
- t := *existing.LastNotified
- updated.LastNotified = &t
- } else {
- updated.LastNotified = nil
- }
- updated.Acknowledged = existing.Acknowledged
- updated.AckUser = existing.AckUser
- if existing.AckTime != nil {
- t := *existing.AckTime
- updated.AckTime = &t
- } else {
- updated.AckTime = nil
- }
- updated.LastEscalation = existing.LastEscalation
- if len(existing.EscalationTimes) > 0 {
- updated.EscalationTimes = append([]time.Time(nil), existing.EscalationTimes...)
- } else {
- updated.EscalationTimes = nil
- }
-
- log.Debug().
- Str("alertID", alertID).
- Time("originalStartTime", existing.StartTime).
- Dur("currentDuration", time.Since(existing.StartTime)).
- Msg("Preserving alert state including StartTime")
- return
- }
-
- if record, ok := m.getAckRecordNoLock(updated, alertID); ok && record.acknowledged {
- updated.Acknowledged = true
- updated.AckUser = record.user
- t := record.time
- updated.AckTime = &t
- }
-}
-
-func (m *Manager) removeActiveAlertNoLock(alertID string) {
- // Before deleting, update the history entry with the alert's final LastSeen
- // timestamp so the stored duration reflects how long the alert was actually active.
- publicID := alertID
- var currentAlert *Alert
- key, exists := m.resolveActiveAlertKeyNoLock(alertID)
- if !exists {
- key, exists = m.resolveActiveAlertKeyByCanonicalStateNoLock(alertID)
- }
- if alert, ok := m.getActiveAlertNoLock(alertID); exists && ok && alert != nil {
- currentAlert = alert
- backfillCanonicalIdentity(alert)
- publicID = effectiveAlertID(alert, alertID)
- m.historyManager.UpdateAlertLastSeenForAlert(alert, alert.LastSeen)
- m.unregisterActiveAlertAliasNoLock(key, alert)
- }
- if exists {
- delete(m.offlineRecoveryConfirmations, key)
- delete(m.activeAlerts, key)
- }
- delete(m.offlineRecoveryConfirmations, alertID)
- // NOTE: Don't delete ackState here - preserve it so if the same alert
- // reappears (e.g., powered-off VM during backup), the acknowledgement
- // is restored via preserveAlertState. ackState is cleaned up in Cleanup().
- // Update inactiveAt so the cleanup TTL is measured from removal time, not ack time.
- if exists {
- m.markAckInactiveNoLock(currentAlert, publicID, time.Now())
- }
-}
-
-func (m *Manager) confirmOfflineRecoveryNoLock(alertID string, required int) (int, bool) {
- alertID = strings.TrimSpace(alertID)
- if alertID == "" {
- return 0, false
- }
-
- if required <= 1 {
- delete(m.offlineRecoveryConfirmations, alertID)
- return required, true
- }
-
- m.offlineRecoveryConfirmations[alertID]++
- confirmations := m.offlineRecoveryConfirmations[alertID]
- if confirmations < required {
- return confirmations, false
- }
-
- delete(m.offlineRecoveryConfirmations, alertID)
- return confirmations, true
-}
-
-// clearResourceOfflineAlert removes an offline alert when a poll-driven resource
-// stays healthy for enough consecutive polls to confirm recovery.
-func (m *Manager) clearResourceOfflineAlert(resourceID, resourceName, host, resourceKind string, requiredRecoveryCount int) {
- alertID := canonicalConnectivityStateID(resourceID)
-
- m.mu.Lock()
- defer m.mu.Unlock()
-
- // Reset offline confirmation count
- if count, exists := m.offlineConfirmations[resourceID]; exists && count > 0 {
- log.Debug().
- Str(strings.ToLower(resourceKind), resourceName).
- Int("previousCount", count).
- Msg(resourceKind + " is online, resetting offline confirmation count")
- delete(m.offlineConfirmations, resourceID)
- }
-
- // Check if offline alert exists
- alert, exists := m.getActiveAlertNoLock(alertID)
- if !exists {
- delete(m.offlineRecoveryConfirmations, alertID)
- return
- }
-
- recoveryCount, confirmed := m.confirmOfflineRecoveryNoLock(alertID, requiredRecoveryCount)
- if !confirmed {
- log.Debug().
- Str(strings.ToLower(resourceKind), resourceName).
- Int("confirmations", recoveryCount).
- Int("required", requiredRecoveryCount).
- Msg(resourceKind + " appears back online, waiting for recovery confirmation")
- return
- }
-
- // Remove from active alerts
- m.removeActiveAlertNoLock(alertID)
-
- resolvedAlert := &ResolvedAlert{
- Alert: alert,
- ResolvedTime: time.Now(),
- }
- m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
-
- // Send recovery notification (async to avoid deadlock — callback acquires m.mu.RLock
- // via ShouldSuppressResolvedNotification, and we currently hold m.mu.Lock)
- m.safeCallResolvedAlertCallback(alert, alertID, true)
-
- // Log recovery
- log.Info().
- Str(strings.ToLower(resourceKind), resourceName).
- Str("host", host).
- Dur("downtime", time.Since(alert.StartTime)).
- Msg(resourceKind + " instance is back online")
-}
-
-// ClearAlert removes an alert from active alerts (but keeps in history)
-func (m *Manager) ClearAlert(alertID string) bool {
- m.mu.Lock()
- alert, exists := m.getActiveAlertNoLock(alertID)
- if !exists || alert == nil {
- m.mu.Unlock()
- return false
- }
- trackingKey := canonicalTrackingKeyForAlert(alert)
-
- m.clearAlertNoLock(alertID)
- delete(m.recentAlerts, alertID)
- delete(m.pendingAlerts, alertID)
- delete(m.suppressedUntil, alertID)
- delete(m.alertRateLimit, alertID)
- if trackingKey != "" && trackingKey != alertID {
- delete(m.recentAlerts, trackingKey)
- delete(m.pendingAlerts, trackingKey)
- delete(m.suppressedUntil, trackingKey)
- delete(m.alertRateLimit, trackingKey)
- }
- m.mu.Unlock()
-
- m.saveActiveAlertsAsync("manual-clear")
- return true
-}
-
// Cleanup removes old acknowledged alerts and cleans up tracking maps
func (m *Manager) Cleanup(maxAge time.Duration) {
m.mu.Lock()
@@ -1270,39 +959,3 @@ func (m *Manager) ClearActiveAlerts() {
}
}()
}
-
-// clearAlertNoLock clears an alert without locking (must be called with lock held)
-func (m *Manager) clearAlertNoLock(alertID string) {
- alert, exists := m.getActiveAlertNoLock(alertID)
- if !exists {
- return
- }
- publicID := effectiveAlertID(alert, alertID)
-
- // Record metric for resolved alert
- if recordAlertResolved != nil {
- recordAlertResolved(alert)
- }
-
- m.removeActiveAlertNoLock(alertID)
- resolvedAlert := &ResolvedAlert{
- Alert: alert,
- ResolvedTime: time.Now(),
- }
-
- m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
-
- m.safeCallResolvedAlertCallback(alert, publicID, true) // Make async to prevent deadlock
-
- log.Info().
- Str("alertID", publicID).
- Msg("Alert cleared")
-}
-
-func (m *Manager) clearActiveAlertIfPresentNoLock(alertID string) bool {
- if _, exists := m.getActiveAlertNoLock(alertID); !exists {
- return false
- }
- m.clearAlertNoLock(alertID)
- return true
-}
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index 0d37caecca..5c804558bc 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -698,6 +698,50 @@ func TestClearAlertMarksResolutionAndReturnsStatus(t *testing.T) {
}
}
+func TestClearAlertByCanonicalAliasRemovesActiveState(t *testing.T) {
+ m := newTestManager(t)
+ resourceID := "guest-200"
+ canonicalState := buildCanonicalStateID(resourceID, "metric-threshold:cpu")
+ now := time.Now()
+ alert := &Alert{
+ ID: "legacy-guest-200-cpu",
+ Type: "cpu",
+ Level: AlertLevelWarning,
+ ResourceID: resourceID,
+ CanonicalSpecID: "metric-threshold:cpu",
+ CanonicalKind: "metric_threshold",
+ CanonicalState: canonicalState,
+ ResourceName: "guest-200",
+ StartTime: now.Add(-time.Minute),
+ LastSeen: now,
+ }
+
+ m.mu.Lock()
+ m.setActiveAlertNoLock(alert.ID, alert)
+ m.pendingAlerts[canonicalState] = now
+ m.suppressedUntil[canonicalState] = now.Add(time.Minute)
+ m.alertRateLimit[canonicalState] = []time.Time{now}
+ m.mu.Unlock()
+
+ if ok := m.ClearAlert(canonicalState); !ok {
+ t.Fatalf("expected manual clear by canonical alias to succeed")
+ }
+
+ m.mu.RLock()
+ _, active := m.getActiveAlertNoLock(canonicalState)
+ _, pending := m.pendingAlerts[canonicalState]
+ _, suppressed := m.suppressedUntil[canonicalState]
+ _, rateLimited := m.alertRateLimit[canonicalState]
+ m.mu.RUnlock()
+
+ if active {
+ t.Fatal("expected canonical alias clear to remove active alert")
+ }
+ if pending || suppressed || rateLimited {
+ t.Fatalf("expected canonical alias clear to remove tracking state: pending=%v suppressed=%v rateLimited=%v", pending, suppressed, rateLimited)
+ }
+}
+
func TestAddRecentlyResolvedUsesCanonicalStorageKey(t *testing.T) {
m := newTestManager(t)