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 persistence

rcourtman8c3c1e417c09
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index e980dacd57..e25e272607 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -68,6 +68,8 @@ operator-facing alert routing behavior for live runtime alerts.
46. `internal/alerts/health_assessment.go`
47. `internal/alerts/guest.go`
48. `internal/alerts/config_runtime.go`
+49. `internal/alerts/active_persistence.go`
+50. `internal/alerts/tracking_cleanup.go`
## Shared Boundaries
@@ -230,6 +232,16 @@ global disable cleanup, active alert reevaluation after threshold changes,
threshold override cloning and merge behavior, and hysteresis defaults; future
config-driven runtime behavior should extend that owner rather than expanding
the central Manager file.
+Active-alert persistence now lives in `internal/alerts/active_persistence.go`.
+That file owns active-alert save/load, secure active-alert storage leaves,
+startup restoration and legacy active-alert ID migration, and periodic active
+alert persistence; persistence changes should extend that owner rather than
+adding save/load logic back to the central Manager file.
+Tracking-map cleanup now lives in `internal/alerts/tracking_cleanup.go`. That
+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.
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_persistence.go b/internal/alerts/active_persistence.go
new file mode 100644
index 0000000000..d046904896
--- /dev/null
+++ b/internal/alerts/active_persistence.go
@@ -0,0 +1,299 @@
+package alerts
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "os"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"
+ "github.com/rs/zerolog/log"
+)
+
+func asyncSaveActiveAlerts(reason string, save func() error) {
+ go func() {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().Interface("panic", r).Str("reason", reason).Msg("panic in SaveActiveAlerts goroutine")
+ }
+ }()
+ if err := save(); err != nil {
+ log.Error().Err(err).Str("reason", reason).Msg("failed to save active alerts")
+ }
+ }()
+}
+
+// SaveActiveAlerts persists active alerts to disk.
+func (m *Manager) SaveActiveAlerts() error {
+ // Serialize snapshots and writes so concurrent async saves cannot
+ // overwrite newer state with an older snapshot.
+ m.saveMu.Lock()
+ defer m.saveMu.Unlock()
+
+ m.mu.RLock()
+ alerts := make([]*Alert, 0, len(m.activeAlerts))
+ for _, alert := range m.activeAlerts {
+ if alert == nil {
+ continue
+ }
+ clone := alert.Clone()
+ backfillCanonicalIdentity(clone)
+ alerts = append(alerts, clone)
+ }
+ m.mu.RUnlock()
+
+ alertsDir := m.getAlertsDir()
+ if err := os.MkdirAll(alertsDir, alertsDirPerm); err != nil {
+ return fmt.Errorf("failed to create alerts directory: %w", err)
+ }
+ if err := os.Chmod(alertsDir, alertsDirPerm); err != nil {
+ return fmt.Errorf("failed to set alerts directory permissions: %w", err)
+ }
+
+ data, err := json.Marshal(alerts)
+ if err != nil {
+ return fmt.Errorf("failed to marshal active alerts: %w", err)
+ }
+
+ // Write to temporary file first, then rename. Use a unique temp file so
+ // periodic saves, explicit saves, and shutdown saves cannot race on a name.
+ tmpFile, err := os.CreateTemp(alertsDir, "active-alerts-*.json.tmp")
+ if err != nil {
+ return fmt.Errorf("failed to create temp file: %w", err)
+ }
+ tmpName := tmpFile.Name()
+ cleanupTemp := true
+
+ defer func() {
+ if !cleanupTemp {
+ return
+ }
+ if err := os.Remove(tmpName); err != nil && !os.IsNotExist(err) {
+ log.Warn().Err(err).Str("file", tmpName).Msg("Failed to remove temp active alerts file")
+ }
+ }()
+
+ if _, err := tmpFile.Write(data); err != nil {
+ writeErr := fmt.Errorf("failed to write active alerts temp file %s: %w", tmpName, err)
+ if closeErr := tmpFile.Close(); closeErr != nil {
+ closeErr = fmt.Errorf("failed to close temp file %s after write failure: %w", tmpName, closeErr)
+ return fmt.Errorf("failed to persist active alerts: %w", errors.Join(writeErr, closeErr))
+ }
+ return writeErr
+ }
+ if err := tmpFile.Chmod(alertsFilePerm); err != nil {
+ if closeErr := tmpFile.Close(); closeErr != nil {
+ log.Warn().Err(closeErr).Str("file", tmpName).Msg("Failed to close temp file after chmod error")
+ }
+ return fmt.Errorf("failed to set active alerts temp file permissions: %w", err)
+ }
+ if err := tmpFile.Close(); err != nil {
+ return fmt.Errorf("failed to close active alerts temp file %s: %w", tmpName, err)
+ }
+
+ finalFile := filepath.Join(alertsDir, "active-alerts.json")
+ if err := os.Rename(tmpName, finalFile); err != nil {
+ return fmt.Errorf("failed to rename active alerts file from %s to %s: %w", tmpName, finalFile, err)
+ }
+ if err := os.Chmod(finalFile, alertsFilePerm); err != nil {
+ return fmt.Errorf("failed to set active alerts file permissions: %w", err)
+ }
+
+ log.Debug().Int("count", len(alerts)).Msg("saved active alerts to disk")
+ return nil
+}
+
+func (m *Manager) saveActiveAlertsAsync(context string) {
+ go func() {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().
+ Interface("panic", r).
+ Str("context", context).
+ Msg("Panic in SaveActiveAlerts goroutine")
+ }
+ }()
+ if err := m.SaveActiveAlerts(); err != nil {
+ log.Error().
+ Err(err).
+ Str("context", context).
+ Msg("Failed to save active alerts")
+ }
+ }()
+}
+
+// LoadActiveAlerts restores active alerts from disk.
+func (m *Manager) LoadActiveAlerts() error {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ alertsFile := filepath.Join(m.getAlertsDir(), "active-alerts.json")
+ data, err := readLimitedRegularFile(alertsFile, maxActiveAlertsFileSizeBytes)
+ if err != nil {
+ if errors.Is(err, os.ErrNotExist) {
+ log.Info().Msg("No active alerts file found, starting fresh")
+ return nil
+ }
+ return fmt.Errorf("failed to read active alerts: %w", err)
+ }
+
+ var alerts []*Alert
+ if err := json.Unmarshal(data, &alerts); err != nil {
+ return fmt.Errorf("failed to unmarshal active alerts: %w", err)
+ }
+ if err := os.Chmod(alertsFile, alertsFilePerm); err != nil && !os.IsNotExist(err) {
+ log.Warn().Err(err).Str("file", alertsFile).Msg("Failed to harden active alerts file permissions")
+ }
+
+ now := time.Now()
+ restoredCount := 0
+ duplicateCount := 0
+ seen := make(map[string]bool)
+
+ for _, alert := range alerts {
+ backfillCanonicalIdentity(alert)
+
+ // Migrate legacy guest alert IDs (instance-node-VMID -> instance-VMID).
+ isGuestAlert := strings.Contains(alert.Type, "cpu") || strings.Contains(alert.Type, "memory") ||
+ strings.Contains(alert.Type, "disk") || strings.Contains(alert.Type, "network") ||
+ alert.Type == "guest-offline"
+ if isGuestAlert {
+ parts := strings.Split(alert.ResourceID, "-")
+
+ if alert.Node != "" && len(parts) >= 2 {
+ var newResourceID string
+
+ vmidStr := parts[len(parts)-1]
+ if _, err := strconv.Atoi(vmidStr); err == nil {
+ if len(parts) == 3 && alert.Instance != "" && alert.Instance != alert.Node {
+ newResourceID = fmt.Sprintf("%s-%s", alert.Instance, vmidStr)
+ } else if len(parts) == 2 && alert.Instance == alert.Node {
+ newResourceID = fmt.Sprintf("%s-%s", alert.Instance, vmidStr)
+ }
+
+ if newResourceID != "" && newResourceID != alert.ResourceID {
+ log.Info().
+ Str("oldID", alert.ResourceID).
+ Str("newID", newResourceID).
+ Str("alertType", alert.Type).
+ Msg("Migrating active alert from legacy guest ID format")
+
+ oldResourceID := alert.ResourceID
+ alert.ResourceID = newResourceID
+ alert.ID = strings.Replace(alert.ID, oldResourceID, newResourceID, 1)
+ }
+ }
+ }
+ }
+
+ if seen[alert.ID] {
+ duplicateCount++
+ log.Warn().Str("alertID", alert.ID).Msg("skipping duplicate alert during restore")
+ continue
+ }
+ seen[alert.ID] = true
+
+ if now.Sub(alert.StartTime) > 24*time.Hour {
+ log.Debug().Str("alertID", alert.ID).Msg("skipping old alert during restore")
+ continue
+ }
+
+ if alert.Acknowledged && alert.AckTime != nil && now.Sub(*alert.AckTime) > time.Hour {
+ log.Debug().Str("alertID", alert.ID).Msg("skipping old acknowledged alert from activeAlerts but preserving ackState")
+ ackTime := alert.StartTime
+ if alert.AckTime != nil {
+ ackTime = *alert.AckTime
+ }
+ m.setAckRecordNoLock(alert, alert.ID, ackRecord{
+ acknowledged: true,
+ user: alert.AckUser,
+ time: ackTime,
+ })
+ continue
+ }
+
+ m.setActiveAlertNoLock(alert.ID, alert)
+ if alert.Acknowledged {
+ ackTime := alert.StartTime
+ if alert.AckTime != nil {
+ ackTime = *alert.AckTime
+ }
+ m.setAckRecordNoLock(alert, alert.ID, ackRecord{
+ acknowledged: true,
+ user: alert.AckUser,
+ time: ackTime,
+ })
+ }
+ restoredCount++
+
+ // Critical alerts restored shortly after restart are redispatched after a
+ // small delay so notification policy still controls delivery.
+ if alert.Level == AlertLevelCritical && now.Sub(alert.StartTime) < 2*time.Hour {
+ alertCopy := alert.Clone()
+ go func(a *Alert) {
+ delay := time.NewTimer(10 * time.Second)
+ defer func() {
+ if !delay.Stop() {
+ select {
+ case <-delay.C:
+ default:
+ }
+ }
+ }()
+
+ select {
+ case <-delay.C:
+ log.Info().
+ Str("alertID", a.ID).
+ Str("resource", a.ResourceName).
+ Msg("Attempting to send notification for restored critical alert")
+
+ m.mu.Lock()
+ m.dispatchAlert(a, false)
+ m.mu.Unlock()
+ case <-m.escalationStop:
+ log.Debug().
+ Str("alertID", a.ID).
+ Msg("Cancelled startup notification due to shutdown")
+ return
+ }
+ }(alertCopy)
+ }
+ }
+
+ log.Info().
+ Int("restored", restoredCount).
+ Int("total", len(alerts)).
+ Int("duplicates", duplicateCount).
+ Msg("Restored active alerts from disk")
+ return nil
+}
+
+func (m *Manager) getAlertsDir() string {
+ if strings.TrimSpace(m.alertsDir) != "" {
+ return m.alertsDir
+ }
+
+ return filepath.Join(utils.GetDataDir(), "alerts")
+}
+
+// periodicSaveAlerts saves active alerts to disk periodically.
+func (m *Manager) periodicSaveAlerts() {
+ ticker := time.NewTicker(1 * time.Minute)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ if err := m.SaveActiveAlerts(); err != nil {
+ log.Error().Err(err).Msg("failed to save active alerts during periodic save")
+ }
+ case <-m.escalationStop:
+ return
+ }
+ }
+}
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.go
index 7b460329ff..0ed963d1da 100644
--- a/internal/alerts/alerts.go
+++ b/internal/alerts/alerts.go
@@ -1,12 +1,9 @@
package alerts
import (
- "encoding/json"
"errors"
"fmt"
- "os"
"path/filepath"
- "strconv"
"strings"
"sync"
"time"
@@ -537,19 +534,6 @@ func (m *Manager) addRecentlyResolvedWithPrimaryLock(resolved *ResolvedAlert) {
m.mu.Lock()
}
-func asyncSaveActiveAlerts(reason string, save func() error) {
- go func() {
- defer func() {
- if r := recover(); r != nil {
- log.Error().Interface("panic", r).Str("reason", reason).Msg("panic in SaveActiveAlerts goroutine")
- }
- }()
- if err := save(); err != nil {
- log.Error().Err(err).Str("reason", reason).Msg("failed to save active alerts")
- }
- }()
-}
-
// clearAlert removes an alert if it exists
func (m *Manager) clearAlert(alertID string) {
m.mu.Lock()
@@ -1178,286 +1162,6 @@ func closeSignalChannel(ch chan struct{}) {
close(ch)
}
-// SaveActiveAlerts persists active alerts to disk
-func (m *Manager) SaveActiveAlerts() error {
- // Serialize snapshots and writes so concurrent async saves cannot
- // overwrite newer state with an older snapshot.
- m.saveMu.Lock()
- defer m.saveMu.Unlock()
-
- m.mu.RLock()
- alerts := make([]*Alert, 0, len(m.activeAlerts))
- for _, alert := range m.activeAlerts {
- if alert == nil {
- continue
- }
- clone := alert.Clone()
- backfillCanonicalIdentity(clone)
- alerts = append(alerts, clone)
- }
- m.mu.RUnlock()
-
- // Create directory if it doesn't exist
- alertsDir := m.getAlertsDir()
- if err := os.MkdirAll(alertsDir, alertsDirPerm); err != nil {
- return fmt.Errorf("failed to create alerts directory: %w", err)
- }
- if err := os.Chmod(alertsDir, alertsDirPerm); err != nil {
- return fmt.Errorf("failed to set alerts directory permissions: %w", err)
- }
-
- data, err := json.Marshal(alerts)
- if err != nil {
- return fmt.Errorf("failed to marshal active alerts: %w", err)
- }
-
- // Write to temporary file first, then rename (atomic operation)
- // Use a unique temp file to avoid race conditions between concurrent saves (e.g., periodic vs shutdown)
- tmpFile, err := os.CreateTemp(alertsDir, "active-alerts-*.json.tmp")
- if err != nil {
- return fmt.Errorf("failed to create temp file: %w", err)
- }
- tmpName := tmpFile.Name()
- cleanupTemp := true
-
- // Ensure cleanup of temp file in case of failure
- defer func() {
- if !cleanupTemp {
- return
- }
- if err := os.Remove(tmpName); err != nil && !os.IsNotExist(err) {
- log.Warn().Err(err).Str("file", tmpName).Msg("Failed to remove temp active alerts file")
- }
- }()
-
- if _, err := tmpFile.Write(data); err != nil {
- writeErr := fmt.Errorf("failed to write active alerts temp file %s: %w", tmpName, err)
- if closeErr := tmpFile.Close(); closeErr != nil {
- closeErr = fmt.Errorf("failed to close temp file %s after write failure: %w", tmpName, closeErr)
- return fmt.Errorf("failed to persist active alerts: %w", errors.Join(writeErr, closeErr))
- }
- return writeErr
- }
- if err := tmpFile.Chmod(alertsFilePerm); err != nil {
- if closeErr := tmpFile.Close(); closeErr != nil {
- log.Warn().Err(closeErr).Str("file", tmpName).Msg("Failed to close temp file after chmod error")
- }
- return fmt.Errorf("failed to set active alerts temp file permissions: %w", err)
- }
- if err := tmpFile.Close(); err != nil {
- return fmt.Errorf("failed to close active alerts temp file %s: %w", tmpName, err)
- }
-
- finalFile := filepath.Join(alertsDir, "active-alerts.json")
- if err := os.Rename(tmpName, finalFile); err != nil {
- return fmt.Errorf("failed to rename active alerts file from %s to %s: %w", tmpName, finalFile, err)
- }
- if err := os.Chmod(finalFile, alertsFilePerm); err != nil {
- return fmt.Errorf("failed to set active alerts file permissions: %w", err)
- }
-
- log.Debug().Int("count", len(alerts)).Msg("saved active alerts to disk")
- return nil
-}
-
-func (m *Manager) saveActiveAlertsAsync(context string) {
- go func() {
- defer func() {
- if r := recover(); r != nil {
- log.Error().
- Interface("panic", r).
- Str("context", context).
- Msg("Panic in SaveActiveAlerts goroutine")
- }
- }()
- if err := m.SaveActiveAlerts(); err != nil {
- log.Error().
- Err(err).
- Str("context", context).
- Msg("Failed to save active alerts")
- }
- }()
-}
-
-// LoadActiveAlerts restores active alerts from disk
-func (m *Manager) LoadActiveAlerts() error {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- alertsFile := filepath.Join(m.getAlertsDir(), "active-alerts.json")
- data, err := readLimitedRegularFile(alertsFile, maxActiveAlertsFileSizeBytes)
- if err != nil {
- if errors.Is(err, os.ErrNotExist) {
- log.Info().Msg("No active alerts file found, starting fresh")
- return nil
- }
- return fmt.Errorf("failed to read active alerts: %w", err)
- }
-
- var alerts []*Alert
- if err := json.Unmarshal(data, &alerts); err != nil {
- return fmt.Errorf("failed to unmarshal active alerts: %w", err)
- }
- if err := os.Chmod(alertsFile, alertsFilePerm); err != nil && !os.IsNotExist(err) {
- log.Warn().Err(err).Str("file", alertsFile).Msg("Failed to harden active alerts file permissions")
- }
-
- // Restore alerts to the map with deduplication
- now := time.Now()
- restoredCount := 0
- duplicateCount := 0
- seen := make(map[string]bool)
-
- for _, alert := range alerts {
- backfillCanonicalIdentity(alert)
-
- // Migrate legacy guest alert IDs (instance-node-VMID -> instance-VMID)
- // Check if this is a guest-related alert by looking at common alert types
- isGuestAlert := strings.Contains(alert.Type, "cpu") || strings.Contains(alert.Type, "memory") ||
- strings.Contains(alert.Type, "disk") || strings.Contains(alert.Type, "network") ||
- alert.Type == "guest-offline"
- if isGuestAlert {
- // Try to extract instance, node, and VMID from resource ID
- // Legacy format: instance-node-VMID or node-VMID (standalone)
- parts := strings.Split(alert.ResourceID, "-")
-
- // Check if this looks like a legacy format (has node in the ID)
- // We can detect this if we have Node field and it appears in the ResourceID
- if alert.Node != "" && len(parts) >= 2 {
- var newResourceID string
-
- // Try to extract VMID (should be last part)
- vmidStr := parts[len(parts)-1]
- if _, err := strconv.Atoi(vmidStr); err == nil {
- // VMID is valid, now check if we need to migrate
- if len(parts) == 3 && alert.Instance != "" && alert.Instance != alert.Node {
- // Format: instance-node-VMID -> instance-VMID
- newResourceID = fmt.Sprintf("%s-%s", alert.Instance, vmidStr)
- } else if len(parts) == 2 && alert.Instance == alert.Node {
- // Format: node-VMID -> instance-VMID (standalone)
- newResourceID = fmt.Sprintf("%s-%s", alert.Instance, vmidStr)
- }
-
- if newResourceID != "" && newResourceID != alert.ResourceID {
- log.Info().
- Str("oldID", alert.ResourceID).
- Str("newID", newResourceID).
- Str("alertType", alert.Type).
- Msg("Migrating active alert from legacy guest ID format")
-
- oldResourceID := alert.ResourceID
-
- // Update resource ID
- alert.ResourceID = newResourceID
-
- // Update alert ID (usually contains resource ID)
- alert.ID = strings.Replace(alert.ID, oldResourceID, newResourceID, 1)
- }
- }
- }
- }
-
- // Skip duplicates
- if seen[alert.ID] {
- duplicateCount++
- log.Warn().Str("alertID", alert.ID).Msg("skipping duplicate alert during restore")
- continue
- }
- seen[alert.ID] = true
-
- // Skip very old alerts (older than 24 hours)
- if now.Sub(alert.StartTime) > 24*time.Hour {
- log.Debug().Str("alertID", alert.ID).Msg("skipping old alert during restore")
- continue
- }
-
- // Skip acknowledged alerts older than 1 hour from activeAlerts,
- // but still preserve the ackState so if the same alert reappears
- // (e.g., backup-age alerts) it won't retrigger notifications.
- if alert.Acknowledged && alert.AckTime != nil && now.Sub(*alert.AckTime) > time.Hour {
- log.Debug().Str("alertID", alert.ID).Msg("skipping old acknowledged alert from activeAlerts but preserving ackState")
- ackTime := alert.StartTime
- if alert.AckTime != nil {
- ackTime = *alert.AckTime
- }
- m.setAckRecordNoLock(alert, alert.ID, ackRecord{
- acknowledged: true,
- user: alert.AckUser,
- time: ackTime,
- })
- continue
- }
-
- m.setActiveAlertNoLock(alert.ID, alert)
- if alert.Acknowledged {
- ackTime := alert.StartTime
- if alert.AckTime != nil {
- ackTime = *alert.AckTime
- }
- m.setAckRecordNoLock(alert, alert.ID, ackRecord{
- acknowledged: true,
- user: alert.AckUser,
- time: ackTime,
- })
- }
- restoredCount++
-
- // For critical alerts that are still active after restart, send notifications
- // This ensures users are notified about ongoing critical issues even after service restarts
- // Only notify for alerts that started recently (within last 2 hours) to avoid spam
- if alert.Level == AlertLevelCritical && now.Sub(alert.StartTime) < 2*time.Hour {
- // Use a goroutine and add a small delay to avoid notification spam on startup
- alertCopy := alert.Clone()
- go func(a *Alert) {
- delay := time.NewTimer(10 * time.Second)
- defer func() {
- if !delay.Stop() {
- select {
- case <-delay.C:
- default:
- }
- }
- }()
-
- // Wait for system to stabilize or cancellation
- select {
- case <-delay.C:
- log.Info().
- Str("alertID", a.ID).
- Str("resource", a.ResourceName).
- Msg("Attempting to send notification for restored critical alert")
-
- // Acquire lock before calling dispatchAlert (it accesses maps)
- m.mu.Lock()
- m.dispatchAlert(a, false) // Use dispatchAlert to respect activation state and quiet hours
- m.mu.Unlock()
- case <-m.escalationStop:
- log.Debug().
- Str("alertID", a.ID).
- Msg("Cancelled startup notification due to shutdown")
- return
- }
- }(alertCopy)
- }
- }
-
- log.Info().
- Int("restored", restoredCount).
- Int("total", len(alerts)).
- Int("duplicates", duplicateCount).
- Msg("Restored active alerts from disk")
- return nil
-}
-
-func (m *Manager) getAlertsDir() string {
- if strings.TrimSpace(m.alertsDir) != "" {
- return m.alertsDir
- }
-
- // Fallback for tests that construct Manager directly.
- return filepath.Join(utils.GetDataDir(), "alerts")
-}
-
// CleanupAlertsForNodes removes alerts for nodes that no longer exist
func (m *Manager) CleanupAlertsForNodes(existingNodes map[string]bool) {
m.mu.Lock()
@@ -1567,280 +1271,6 @@ func (m *Manager) ClearActiveAlerts() {
}()
}
-// periodicSaveAlerts saves active alerts to disk periodically
-func (m *Manager) periodicSaveAlerts() {
- ticker := time.NewTicker(1 * time.Minute)
- defer ticker.Stop()
-
- for {
- select {
- case <-ticker.C:
- if err := m.SaveActiveAlerts(); err != nil {
- log.Error().Err(err).Msg("failed to save active alerts during periodic save")
- }
- case <-m.escalationStop:
- return
- }
- }
-}
-
-// trackingMapCleanup periodically cleans up stale entries from tracking maps
-// to prevent unbounded memory growth from deleted/decommissioned resources.
-func (m *Manager) trackingMapCleanup() {
- // Run cleanup every hour
- ticker := time.NewTicker(1 * time.Hour)
- defer ticker.Stop()
-
- for {
- select {
- case <-ticker.C:
- m.cleanupStaleMaps()
- case <-m.cleanupStop:
- return
- }
- }
-}
-
-// cleanupStaleMaps removes stale entries from tracking maps.
-// Entries are considered stale if they haven't been updated in 24 hours
-// and don't correspond to any active alert.
-func (m *Manager) cleanupStaleMaps() {
- m.mu.Lock()
- defer m.mu.Unlock()
-
- now := time.Now()
- staleThreshold := StaleTrackingThreshold
- cleaned := 0
-
- // Clean up flapping history for resources without active alerts
- for alertID, history := range m.flappingHistory {
- if !m.hasActiveAlertNoLock(alertID) {
- // Check if history is stale (last entry older than threshold)
- if len(history) == 0 || now.Sub(history[len(history)-1]) > staleThreshold {
- delete(m.flappingHistory, alertID)
- delete(m.flappingActive, alertID)
- cleaned++
- }
- }
- }
-
- // Clean up suppressedUntil entries that have expired
- for alertID, suppressUntil := range m.suppressedUntil {
- if now.After(suppressUntil) {
- delete(m.suppressedUntil, alertID)
- cleaned++
- }
- }
-
- // Clean up pending alerts older than threshold without active alerts
- for alertID, pendingTime := range m.pendingAlerts {
- if !m.hasActiveAlertNoLock(alertID) {
- if now.Sub(pendingTime) > staleThreshold {
- delete(m.pendingAlerts, alertID)
- cleaned++
- }
- }
- }
-
- // Clean up offline confirmation counts for resources without active alerts
- for resourceID := range m.offlineConfirmations {
- hasRelatedAlert := false
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if strings.Contains(alertID, resourceID) {
- hasRelatedAlert = true
- break
- }
- }
- if !hasRelatedAlert {
- delete(m.offlineConfirmations, resourceID)
- cleaned++
- }
- }
-
- for alertID := range m.offlineRecoveryConfirmations {
- if !m.hasActiveAlertNoLock(alertID) {
- delete(m.offlineRecoveryConfirmations, alertID)
- cleaned++
- }
- }
-
- // Clean up node offline counts (legacy)
- for nodeID := range m.nodeOfflineCount {
- hasRelatedAlert := false
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if strings.Contains(alertID, nodeID) {
- hasRelatedAlert = true
- break
- }
- }
- if !hasRelatedAlert {
- delete(m.nodeOfflineCount, nodeID)
- cleaned++
- }
- }
-
- // Clean up Docker tracking maps
- for containerID := range m.dockerStateConfirm {
- hasRelatedAlert := false
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if strings.Contains(alertID, containerID) {
- hasRelatedAlert = true
- break
- }
- }
- if !hasRelatedAlert {
- delete(m.dockerStateConfirm, containerID)
- cleaned++
- }
- }
-
- for hostID := range m.dockerOfflineCount {
- hasRelatedAlert := false
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if strings.Contains(alertID, hostID) {
- hasRelatedAlert = true
- break
- }
- }
- if !hasRelatedAlert {
- delete(m.dockerOfflineCount, hostID)
- cleaned++
- }
- }
-
- // Clean up Docker restart tracking for stale containers
- for containerID, record := range m.dockerRestartTracking {
- if record != nil && now.Sub(record.lastChecked) > staleThreshold {
- delete(m.dockerRestartTracking, containerID)
- delete(m.dockerLastExitCode, containerID)
- cleaned++
- }
- }
-
- // Clean up Docker update tracking for stale entries
- for containerID, firstSeen := range m.dockerUpdateFirstSeen {
- if now.Sub(firstSeen) > staleThreshold {
- delete(m.dockerUpdateFirstSeen, containerID)
- cleaned++
- }
- }
- for containerID, firstSeen := range m.dockerUpdateFirstSeenByIdentity {
- if now.Sub(firstSeen) > staleThreshold {
- delete(m.dockerUpdateFirstSeenByIdentity, containerID)
- cleaned++
- }
- }
-
- // Clean up rate limit entries older than 1 hour
- rateLimitThreshold := RateLimitCleanupWindow
- for resourceID, times := range m.alertRateLimit {
- // Filter to keep only recent entries
- var recent []time.Time
- for _, t := range times {
- if now.Sub(t) < rateLimitThreshold {
- recent = append(recent, t)
- }
- }
- if len(recent) == 0 {
- delete(m.alertRateLimit, resourceID)
- cleaned++
- } else if len(recent) < len(times) {
- m.alertRateLimit[resourceID] = recent
- }
- }
-
- // Clean up recent alerts older than suppression window
- suppressWindow := time.Duration(m.config.SuppressionWindow) * time.Minute
- if suppressWindow <= 0 {
- suppressWindow = 5 * time.Minute
- }
- for alertID, alert := range m.recentAlerts {
- if now.Sub(alert.LastSeen) > suppressWindow {
- delete(m.recentAlerts, alertID)
- cleaned++
- }
- }
-
- // Clean up ackState for alerts that no longer exist and are older than threshold
- for alertID, record := range m.ackState {
- if !m.hasActiveAlertNoLock(alertID) {
- // Use inactiveAt (when alert was removed) for TTL, not ack time
- checkTime := record.inactiveAt
- if checkTime.IsZero() {
- checkTime = record.time
- }
- if now.Sub(checkTime) > staleThreshold {
- delete(m.ackState, alertID)
- cleaned++
- }
- }
- }
- for canonicalID, record := range m.ackStateByCanonical {
- checkTime := record.inactiveAt
- if checkTime.IsZero() {
- checkTime = record.time
- }
- if now.Sub(checkTime) > staleThreshold {
- delete(m.ackStateByCanonical, canonicalID)
- cleaned++
- }
- }
-
- // Auto-resolve stale alerts - alerts where the resource hasn't been polled in 24 hours.
- // This handles cases where a resource (e.g., Docker container, storage) stops being
- // monitored but its alert remains active. Without this, alerts would persist indefinitely.
- staleAlerts := make([]string, 0)
- for storageKey, alert := range m.activeAlerts {
- alertID := effectiveAlertID(alert, storageKey)
- if alert != nil && now.Sub(alert.LastSeen) > staleThreshold {
- staleAlerts = append(staleAlerts, alertID)
- }
- }
- staleResolved := 0
- for _, alertID := range staleAlerts {
- alert, exists := m.getActiveAlertNoLock(alertID)
- if !exists || alert == nil {
- continue
- }
- log.Info().
- Str("alertID", alertID).
- Str("resourceName", alert.ResourceName).
- Time("lastSeen", alert.LastSeen).
- Dur("staleFor", now.Sub(alert.LastSeen)).
- Msg("Auto-resolving stale alert - resource no longer being monitored")
- m.clearAlertNoLock(alertID)
- cleaned++
- staleResolved++
- }
-
- // Persist changes if we resolved any stale alerts
- if staleResolved > 0 {
- go func() {
- defer func() {
- if r := recover(); r != nil {
- log.Error().Interface("panic", r).Msg("panic in SaveActiveAlerts goroutine (stale cleanup)")
- }
- }()
- if err := m.SaveActiveAlerts(); err != nil {
- log.Error().Err(err).Msg("failed to save active alerts after stale cleanup")
- }
- }()
- log.Info().
- Int("count", staleResolved).
- Msg("Auto-resolved stale alerts")
- }
-
- if cleaned > 0 {
- log.Debug().
- Int("entriesCleaned", cleaned).
- Msg("Cleaned stale entries from alert tracking maps")
- }
-}
-
// clearAlertNoLock clears an alert without locking (must be called with lock held)
func (m *Manager) clearAlertNoLock(alertID string) {
alert, exists := m.getActiveAlertNoLock(alertID)
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index c775df28c6..0d37caecca 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -18048,6 +18048,66 @@ func TestSaveAndLoadActiveAlerts_UsesManagerDataDirAndSecurePermissions(t *testi
}
}
+func TestLoadActiveAlertsHardensExistingFilePermissions(t *testing.T) {
+ alertsDir := filepath.Join(t.TempDir(), "alerts")
+ if err := os.MkdirAll(alertsDir, 0o755); err != nil {
+ t.Fatalf("failed to create alerts dir: %v", err)
+ }
+
+ now := time.Now()
+ payload, err := json.Marshal([]*Alert{
+ {
+ ID: "loose-permission-alert",
+ Type: "cpu",
+ Level: AlertLevelWarning,
+ ResourceID: "guest-100",
+ ResourceName: "guest-100",
+ StartTime: now.Add(-1 * time.Minute),
+ LastSeen: now,
+ },
+ })
+ if err != nil {
+ t.Fatalf("failed to marshal active alerts: %v", err)
+ }
+
+ alertsFile := filepath.Join(alertsDir, "active-alerts.json")
+ if err := os.WriteFile(alertsFile, payload, 0o644); err != nil {
+ t.Fatalf("failed to write active alerts file: %v", err)
+ }
+
+ m := &Manager{
+ alertsDir: alertsDir,
+ activeAlerts: make(map[string]*Alert),
+ activeAlertAlias: make(map[string]string),
+ ackState: make(map[string]ackRecord),
+ ackStateByCanonical: make(map[string]ackRecord),
+ escalationStop: make(chan struct{}),
+ recentlyResolved: make(map[string]*ResolvedAlert),
+ resolvedAlias: make(map[string]string),
+ pendingAlerts: make(map[string]time.Time),
+ offlineConfirmations: make(map[string]int),
+ }
+
+ if err := m.LoadActiveAlerts(); err != nil {
+ t.Fatalf("LoadActiveAlerts failed: %v", err)
+ }
+
+ info, err := os.Stat(alertsFile)
+ if err != nil {
+ t.Fatalf("failed to stat active alerts file: %v", err)
+ }
+ if info.Mode().Perm() != alertsFilePerm {
+ t.Fatalf("active alerts file permissions = %o, want %o", info.Mode().Perm(), alertsFilePerm)
+ }
+
+ m.mu.RLock()
+ _, loaded := testLookupActiveAlert(t, m, "loose-permission-alert")
+ m.mu.RUnlock()
+ if !loaded {
+ t.Fatal("expected alert to load from existing active alerts file")
+ }
+}
+
func TestNamespaceMatchesInstance(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/alerts/tracking_cleanup.go b/internal/alerts/tracking_cleanup.go
new file mode 100644
index 0000000000..b07b914589
--- /dev/null
+++ b/internal/alerts/tracking_cleanup.go
@@ -0,0 +1,246 @@
+package alerts
+
+import (
+ "strings"
+ "time"
+
+ "github.com/rs/zerolog/log"
+)
+
+// trackingMapCleanup periodically cleans up stale entries from tracking maps
+// to prevent unbounded memory growth from deleted/decommissioned resources.
+func (m *Manager) trackingMapCleanup() {
+ ticker := time.NewTicker(1 * time.Hour)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ m.cleanupStaleMaps()
+ case <-m.cleanupStop:
+ return
+ }
+ }
+}
+
+// cleanupStaleMaps removes stale entries from tracking maps.
+// Entries are considered stale if they haven't been updated in 24 hours
+// and don't correspond to any active alert.
+func (m *Manager) cleanupStaleMaps() {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ now := time.Now()
+ staleThreshold := StaleTrackingThreshold
+ cleaned := 0
+
+ for alertID, history := range m.flappingHistory {
+ if !m.hasActiveAlertNoLock(alertID) {
+ if len(history) == 0 || now.Sub(history[len(history)-1]) > staleThreshold {
+ delete(m.flappingHistory, alertID)
+ delete(m.flappingActive, alertID)
+ cleaned++
+ }
+ }
+ }
+
+ for alertID, suppressUntil := range m.suppressedUntil {
+ if now.After(suppressUntil) {
+ delete(m.suppressedUntil, alertID)
+ cleaned++
+ }
+ }
+
+ for alertID, pendingTime := range m.pendingAlerts {
+ if !m.hasActiveAlertNoLock(alertID) {
+ if now.Sub(pendingTime) > staleThreshold {
+ delete(m.pendingAlerts, alertID)
+ cleaned++
+ }
+ }
+ }
+
+ for resourceID := range m.offlineConfirmations {
+ hasRelatedAlert := false
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if strings.Contains(alertID, resourceID) {
+ hasRelatedAlert = true
+ break
+ }
+ }
+ if !hasRelatedAlert {
+ delete(m.offlineConfirmations, resourceID)
+ cleaned++
+ }
+ }
+
+ for alertID := range m.offlineRecoveryConfirmations {
+ if !m.hasActiveAlertNoLock(alertID) {
+ delete(m.offlineRecoveryConfirmations, alertID)
+ cleaned++
+ }
+ }
+
+ for nodeID := range m.nodeOfflineCount {
+ hasRelatedAlert := false
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if strings.Contains(alertID, nodeID) {
+ hasRelatedAlert = true
+ break
+ }
+ }
+ if !hasRelatedAlert {
+ delete(m.nodeOfflineCount, nodeID)
+ cleaned++
+ }
+ }
+
+ for containerID := range m.dockerStateConfirm {
+ hasRelatedAlert := false
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if strings.Contains(alertID, containerID) {
+ hasRelatedAlert = true
+ break
+ }
+ }
+ if !hasRelatedAlert {
+ delete(m.dockerStateConfirm, containerID)
+ cleaned++
+ }
+ }
+
+ for hostID := range m.dockerOfflineCount {
+ hasRelatedAlert := false
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if strings.Contains(alertID, hostID) {
+ hasRelatedAlert = true
+ break
+ }
+ }
+ if !hasRelatedAlert {
+ delete(m.dockerOfflineCount, hostID)
+ cleaned++
+ }
+ }
+
+ for containerID, record := range m.dockerRestartTracking {
+ if record != nil && now.Sub(record.lastChecked) > staleThreshold {
+ delete(m.dockerRestartTracking, containerID)
+ delete(m.dockerLastExitCode, containerID)
+ cleaned++
+ }
+ }
+
+ for containerID, firstSeen := range m.dockerUpdateFirstSeen {
+ if now.Sub(firstSeen) > staleThreshold {
+ delete(m.dockerUpdateFirstSeen, containerID)
+ cleaned++
+ }
+ }
+ for containerID, firstSeen := range m.dockerUpdateFirstSeenByIdentity {
+ if now.Sub(firstSeen) > staleThreshold {
+ delete(m.dockerUpdateFirstSeenByIdentity, containerID)
+ cleaned++
+ }
+ }
+
+ rateLimitThreshold := RateLimitCleanupWindow
+ for resourceID, times := range m.alertRateLimit {
+ var recent []time.Time
+ for _, t := range times {
+ if now.Sub(t) < rateLimitThreshold {
+ recent = append(recent, t)
+ }
+ }
+ if len(recent) == 0 {
+ delete(m.alertRateLimit, resourceID)
+ cleaned++
+ } else if len(recent) < len(times) {
+ m.alertRateLimit[resourceID] = recent
+ }
+ }
+
+ suppressWindow := time.Duration(m.config.SuppressionWindow) * time.Minute
+ if suppressWindow <= 0 {
+ suppressWindow = 5 * time.Minute
+ }
+ for alertID, alert := range m.recentAlerts {
+ if now.Sub(alert.LastSeen) > suppressWindow {
+ delete(m.recentAlerts, alertID)
+ cleaned++
+ }
+ }
+
+ for alertID, record := range m.ackState {
+ if !m.hasActiveAlertNoLock(alertID) {
+ checkTime := record.inactiveAt
+ if checkTime.IsZero() {
+ checkTime = record.time
+ }
+ if now.Sub(checkTime) > staleThreshold {
+ delete(m.ackState, alertID)
+ cleaned++
+ }
+ }
+ }
+ for canonicalID, record := range m.ackStateByCanonical {
+ checkTime := record.inactiveAt
+ if checkTime.IsZero() {
+ checkTime = record.time
+ }
+ if now.Sub(checkTime) > staleThreshold {
+ delete(m.ackStateByCanonical, canonicalID)
+ cleaned++
+ }
+ }
+
+ staleAlerts := make([]string, 0)
+ for storageKey, alert := range m.activeAlerts {
+ alertID := effectiveAlertID(alert, storageKey)
+ if alert != nil && now.Sub(alert.LastSeen) > staleThreshold {
+ staleAlerts = append(staleAlerts, alertID)
+ }
+ }
+ staleResolved := 0
+ for _, alertID := range staleAlerts {
+ alert, exists := m.getActiveAlertNoLock(alertID)
+ if !exists || alert == nil {
+ continue
+ }
+ log.Info().
+ Str("alertID", alertID).
+ Str("resourceName", alert.ResourceName).
+ Time("lastSeen", alert.LastSeen).
+ Dur("staleFor", now.Sub(alert.LastSeen)).
+ Msg("Auto-resolving stale alert - resource no longer being monitored")
+ m.clearAlertNoLock(alertID)
+ cleaned++
+ staleResolved++
+ }
+
+ if staleResolved > 0 {
+ go func() {
+ defer func() {
+ if r := recover(); r != nil {
+ log.Error().Interface("panic", r).Msg("panic in SaveActiveAlerts goroutine (stale cleanup)")
+ }
+ }()
+ if err := m.SaveActiveAlerts(); err != nil {
+ log.Error().Err(err).Msg("failed to save active alerts after stale cleanup")
+ }
+ }()
+ log.Info().
+ Int("count", staleResolved).
+ Msg("Auto-resolved stale alerts")
+ }
+
+ if cleaned > 0 {
+ log.Debug().
+ Int("entriesCleaned", cleaned).
+ Msg("Cleaned stale entries from alert tracking maps")
+ }
+}