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.

Replay quiet-hours alert notifications

rcourtman6112fcd5ae8e
diff --git a/internal/alerts/notification_policy.go b/internal/alerts/notification_policy.go
index 3f4ad3fb21..0c503d1984 100644
--- a/internal/alerts/notification_policy.go
+++ b/internal/alerts/notification_policy.go
@@ -8,6 +8,18 @@ import (
"github.com/rs/zerolog/log"
)
+const (
+ // MetadataQuietHoursSuppressed marks notifications that were held by alert
+ // quiet-hours policy and must be replayed by the notification queue.
+ MetadataQuietHoursSuppressed = "quietHoursSuppressed"
+ // MetadataQuietHoursSuppressionReason records the quiet-hours rule that
+ // deferred notification delivery.
+ MetadataQuietHoursSuppressionReason = "quietHoursSuppressionReason"
+ // MetadataQuietHoursReplayAt stores the earliest RFC3339 UTC time that the
+ // notification queue may retry delivery.
+ MetadataQuietHoursReplayAt = "quietHoursReplayAt"
+)
+
// checkFlappingLocked detects alert flapping and returns whether the alert
// should be suppressed and whether this call is the first transition into
// the flapping state for the current cooldown window. justTransitioned is
@@ -134,13 +146,17 @@ func (m *Manager) dispatchAlert(alert *Alert, async bool) bool {
}
if suppressed, reason := m.shouldSuppressNotification(alert); suppressed {
+ replayAt := m.quietHoursReplayAt()
+ markQuietHoursNotificationReplay(alert, reason, replayAt)
log.Debug().
Str("alertID", alert.ID).
Str("type", alert.Type).
Str("level", string(alert.Level)).
Str("quietHoursRule", reason).
- Msg("Alert notification suppressed during quiet hours")
- return false
+ Time("replayAt", replayAt).
+ Msg("Alert notification deferred during quiet hours")
+ } else {
+ clearQuietHoursNotificationReplay(alert)
}
if isMonitorOnlyAlert(alert) {
@@ -340,8 +356,82 @@ func (m *Manager) shouldSuppressNotification(alert *Alert) (bool, string) {
return false, ""
}
-// ShouldSuppressNotification checks if a notification should be suppressed
-// during quiet hours. This is used by paths that bypass dispatchAlert, such as escalation.
+func (m *Manager) quietHoursReplayAt() time.Time {
+ nowFn := m.now
+ if nowFn == nil {
+ nowFn = time.Now
+ }
+ now := nowFn()
+
+ loc := m.quietHoursLoc
+ if loc == nil {
+ var err error
+ loc, err = time.LoadLocation(m.config.Schedule.QuietHours.Timezone)
+ if err != nil {
+ log.Warn().Err(err).Str("timezone", m.config.Schedule.QuietHours.Timezone).Msg("failed to load timezone for quiet-hours replay, using local time")
+ loc = time.Local
+ }
+ m.quietHoursLoc = loc
+ }
+
+ localNow := now.In(loc).Truncate(time.Minute)
+ startTime, startErr := time.ParseInLocation("15:04", m.config.Schedule.QuietHours.Start, loc)
+ endTime, endErr := time.ParseInLocation("15:04", m.config.Schedule.QuietHours.End, loc)
+ if startErr != nil || endErr != nil {
+ return now.Add(time.Minute).UTC()
+ }
+
+ startTime = time.Date(localNow.Year(), localNow.Month(), localNow.Day(), startTime.Hour(), startTime.Minute(), 0, 0, loc)
+ endTime = time.Date(localNow.Year(), localNow.Month(), localNow.Day(), endTime.Hour(), endTime.Minute(), 0, 0, loc)
+ endExclusive := endTime.Add(time.Minute)
+ if endTime.Before(startTime) && !localNow.Before(startTime) {
+ endExclusive = endExclusive.AddDate(0, 0, 1)
+ }
+
+ if !endExclusive.After(localNow) {
+ return now.Add(time.Minute).UTC()
+ }
+ return endExclusive.UTC()
+}
+
+func markQuietHoursNotificationReplay(alert *Alert, reason string, replayAt time.Time) {
+ if alert == nil {
+ return
+ }
+ if alert.Metadata == nil {
+ alert.Metadata = make(map[string]interface{}, 3)
+ }
+ alert.Metadata[MetadataQuietHoursSuppressed] = true
+ alert.Metadata[MetadataQuietHoursSuppressionReason] = reason
+ alert.Metadata[MetadataQuietHoursReplayAt] = replayAt.UTC().Format(time.RFC3339)
+}
+
+func clearQuietHoursNotificationReplay(alert *Alert) {
+ if alert == nil || alert.Metadata == nil {
+ return
+ }
+ delete(alert.Metadata, MetadataQuietHoursSuppressed)
+ delete(alert.Metadata, MetadataQuietHoursSuppressionReason)
+ delete(alert.Metadata, MetadataQuietHoursReplayAt)
+}
+
+func hasQuietHoursNotificationReplay(alert *Alert) bool {
+ if alert == nil || alert.Metadata == nil {
+ return false
+ }
+ if replayAt, ok := alert.Metadata[MetadataQuietHoursReplayAt].(string); ok && strings.TrimSpace(replayAt) != "" {
+ return true
+ }
+ if suppressed, ok := alert.Metadata[MetadataQuietHoursSuppressed].(bool); ok {
+ return suppressed
+ }
+ return false
+}
+
+// ShouldSuppressNotification checks whether a notification must be dropped at
+// the alert-policy layer. Quiet-hours matches are replayable, so this helper
+// annotates the alert for notification-queue retry and returns false to let
+// bypass callers hand the alert to the delivery owner.
func (m *Manager) ShouldSuppressNotification(alert *Alert) bool {
if alert == nil {
return false
@@ -352,19 +442,26 @@ func (m *Manager) ShouldSuppressNotification(alert *Alert) bool {
suppressed, reason := m.shouldSuppressNotification(alert)
if suppressed {
+ replayAt := m.quietHoursReplayAt()
+ markQuietHoursNotificationReplay(alert, reason, replayAt)
log.Debug().
Str("alertID", alert.ID).
Str("type", alert.Type).
Str("level", string(alert.Level)).
Str("quietHoursRule", reason).
- Msg("Notification suppressed during quiet hours")
+ Time("replayAt", replayAt).
+ Msg("Notification deferred during quiet hours")
+ return false
}
- return suppressed
+ clearQuietHoursNotificationReplay(alert)
+ return false
}
-// ShouldSuppressResolvedNotification checks if a recovery notification should be suppressed
-// during quiet hours. Recovery notifications follow the same quiet hours rules as their
-// corresponding alerts - if the original alert would have been suppressed, so is the recovery.
+// ShouldSuppressResolvedNotification checks if a recovery notification should be suppressed.
+// Recovery notifications keep the existing quiet-hours rule unless the firing
+// notification was already deferred into the owned queue replay path; in that
+// case the resolved notification is also allowed to enter the queue so the
+// close-the-loop delivery is not lost.
func (m *Manager) ShouldSuppressResolvedNotification(alert *Alert) bool {
if alert == nil {
return false
@@ -381,7 +478,8 @@ func (m *Manager) ShouldSuppressResolvedNotification(alert *Alert) bool {
return true
}
- if alert.LastNotified == nil {
+ quietHoursReplay := hasQuietHoursNotificationReplay(alert)
+ if alert.LastNotified == nil && !quietHoursReplay {
log.Debug().
Str("alertID", alert.ID).
Str("type", alert.Type).
@@ -391,6 +489,15 @@ func (m *Manager) ShouldSuppressResolvedNotification(alert *Alert) bool {
suppressed, reason := m.shouldSuppressNotification(alert)
if suppressed {
+ if quietHoursReplay {
+ log.Debug().
+ Str("alertID", alert.ID).
+ Str("type", alert.Type).
+ Str("level", string(alert.Level)).
+ Str("quietHoursRule", reason).
+ Msg("Recovery notification allowed into quiet-hours replay queue")
+ return false
+ }
log.Debug().
Str("alertID", alert.ID).
Str("type", alert.Type).
diff --git a/internal/alerts/quiet_hours_test.go b/internal/alerts/quiet_hours_test.go
index 0fd5a3f660..0d36326323 100644
--- a/internal/alerts/quiet_hours_test.go
+++ b/internal/alerts/quiet_hours_test.go
@@ -80,11 +80,51 @@ func TestShouldSuppressNotificationQuietHours(t *testing.T) {
}
})
- t.Run("public suppression helper mirrors quiet hours policy", func(t *testing.T) {
+ t.Run("public suppression helper defers quiet hours through queue metadata", func(t *testing.T) {
m := newManagerWithQuietHoursSuppress(QuietHoursSuppression{Offline: true})
alert := &Alert{ID: "offline-public", Type: "connectivity", Level: AlertLevelCritical}
- if !m.ShouldSuppressNotification(alert) {
- t.Fatal("expected public quiet-hours suppression helper to return true")
+ if m.ShouldSuppressNotification(alert) {
+ t.Fatal("expected public quiet-hours helper to defer rather than drop")
+ }
+ if alert.Metadata[MetadataQuietHoursSuppressed] != true {
+ t.Fatalf("expected quiet-hours replay metadata, got %#v", alert.Metadata)
+ }
+ if alert.Metadata[MetadataQuietHoursSuppressionReason] != "offline" {
+ t.Fatalf("expected offline suppression reason, got %#v", alert.Metadata[MetadataQuietHoursSuppressionReason])
+ }
+ })
+
+ t.Run("dispatch annotates quiet-hours replay instead of dropping callback", func(t *testing.T) {
+ m := newManagerWithQuietHoursSuppress(QuietHoursSuppression{})
+ m.config.ActivationState = ActivationActive
+ var dispatched *Alert
+ m.SetAlertCallback(func(alert *Alert) {
+ dispatched = alert
+ })
+
+ alert := &Alert{ID: "warn-deferred", Type: "cpu", Level: AlertLevelWarning}
+ if !m.dispatchAlert(alert, false) {
+ t.Fatal("expected quiet-hours suppressed alert to dispatch for queued replay")
+ }
+ if dispatched == nil {
+ t.Fatal("expected alert callback to receive quiet-hours deferred alert")
+ }
+ if dispatched.Metadata[MetadataQuietHoursSuppressed] != true {
+ t.Fatalf("expected quiet-hours suppression metadata on dispatched alert, got %#v", dispatched.Metadata)
+ }
+ if dispatched.Metadata[MetadataQuietHoursSuppressionReason] != "non-critical" {
+ t.Fatalf("expected non-critical suppression reason, got %#v", dispatched.Metadata[MetadataQuietHoursSuppressionReason])
+ }
+ rawReplayAt, ok := dispatched.Metadata[MetadataQuietHoursReplayAt].(string)
+ if !ok || rawReplayAt == "" {
+ t.Fatalf("expected replay timestamp metadata, got %#v", dispatched.Metadata[MetadataQuietHoursReplayAt])
+ }
+ replayAt, err := time.Parse(time.RFC3339, rawReplayAt)
+ if err != nil {
+ t.Fatalf("expected RFC3339 replay timestamp, got %q: %v", rawReplayAt, err)
+ }
+ if !replayAt.After(m.now()) {
+ t.Fatalf("expected replay timestamp after quiet-hours suppression time, got %s", replayAt)
}
})
@@ -113,6 +153,23 @@ func TestShouldSuppressNotificationQuietHours(t *testing.T) {
t.Fatal("expected recovery notification to be suppressed when LastNotified is nil")
}
})
+
+ t.Run("resolved notifications are not dropped when firing alert was deferred for quiet hours", func(t *testing.T) {
+ m := newManagerWithQuietHoursSuppress(QuietHoursSuppression{})
+ alert := &Alert{
+ ID: "resolved-deferred",
+ Type: "cpu",
+ Level: AlertLevelWarning,
+ Metadata: map[string]interface{}{
+ MetadataQuietHoursSuppressed: true,
+ MetadataQuietHoursSuppressionReason: "non-critical",
+ MetadataQuietHoursReplayAt: m.now().Add(time.Hour).UTC().Format(time.RFC3339),
+ },
+ }
+ if m.ShouldSuppressResolvedNotification(alert) {
+ t.Fatal("expected recovery notification to enter quiet-hours replay queue")
+ }
+ })
}
func TestIsInQuietHours(t *testing.T) {
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.go
index 4aedc3b7b5..a0ea9874da 100644
--- a/internal/notifications/notifications.go
+++ b/internal/notifications/notifications.go
@@ -342,6 +342,45 @@ func annotateResolvedMetadata(alert *alerts.Alert, resolvedAt time.Time) {
alert.Metadata[metadataResolvedAt] = resolvedAt.Format(time.RFC3339)
}
+func quietHoursReplayAtForAlerts(alertList []*alerts.Alert, now time.Time) *time.Time {
+ var replayAt time.Time
+ for _, alert := range alertList {
+ if alert == nil || alert.Metadata == nil {
+ continue
+ }
+ raw, ok := alert.Metadata[alerts.MetadataQuietHoursReplayAt]
+ if !ok {
+ continue
+ }
+
+ var parsed time.Time
+ switch value := raw.(type) {
+ case string:
+ ts, err := time.Parse(time.RFC3339, strings.TrimSpace(value))
+ if err != nil {
+ continue
+ }
+ parsed = ts
+ case time.Time:
+ parsed = value
+ case float64:
+ if value <= 0 {
+ continue
+ }
+ parsed = time.Unix(int64(value), 0)
+ }
+ if parsed.After(now) && (replayAt.IsZero() || parsed.After(replayAt)) {
+ replayAt = parsed
+ }
+ }
+
+ if replayAt.IsZero() {
+ return nil
+ }
+ replayAt = replayAt.UTC()
+ return &replayAt
+}
+
// NormalizeAppriseConfig cleans and normalizes Apprise configuration values.
func NormalizeAppriseConfig(cfg AppriseConfig) AppriseConfig {
normalized := cfg
@@ -1148,6 +1187,7 @@ func (n *NotificationManager) enqueueNotificationJobs(queue *NotificationQueue,
Alerts: job.Alerts,
Config: configJSON,
MaxAttempts: 3,
+ NextRetryAt: quietHoursReplayAtForAlerts(job.Alerts, time.Now()),
}
if err := queue.Enqueue(notif); err != nil {
anyFailed = true
@@ -1160,6 +1200,9 @@ func (n *NotificationManager) enqueueNotificationJobs(queue *NotificationQueue,
Str("type", job.Type).
Str("event", string(job.Event)).
Int("alertCount", len(job.Alerts))
+ if notif.NextRetryAt != nil {
+ logger = logger.Time("nextRetryAt", *notif.NextRetryAt)
+ }
if job.WebhookConfig != nil {
logger = logger.Str("webhookName", job.WebhookConfig.Name)
}
diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.go
index 32e8a2b2e0..57eb130dbc 100644
--- a/internal/notifications/notifications_test.go
+++ b/internal/notifications/notifications_test.go
@@ -3022,6 +3022,71 @@ func TestProcessQueuedNotification_UnknownType(t *testing.T) {
}
}
+func TestProcessQueuedNotification_QuietHoursReplayUsesQueueRetryTime(t *testing.T) {
+ queue, err := NewNotificationQueue(t.TempDir())
+ if err != nil {
+ t.Fatalf("failed to create queue: %v", err)
+ }
+ defer func() { _ = queue.Stop() }()
+
+ replayAt := time.Now().Add(time.Hour).UTC()
+ alert := &alerts.Alert{
+ ID: "quiet-hours-alert",
+ Type: "cpu",
+ Level: alerts.AlertLevelWarning,
+ Metadata: map[string]interface{}{
+ alerts.MetadataQuietHoursSuppressed: true,
+ alerts.MetadataQuietHoursSuppressionReason: "non-critical",
+ alerts.MetadataQuietHoursReplayAt: replayAt.Format(time.RFC3339),
+ },
+ }
+ jobs := buildNotificationDeliveryJobs(
+ EmailConfig{Enabled: true, SMTPHost: "smtp.example.com", SMTPPort: 587, From: "[email protected]", To: []string{"[email protected]"}},
+ nil,
+ AppriseConfig{},
+ []*alerts.Alert{alert},
+ eventAlert,
+ time.Time{},
+ )
+
+ nm := &NotificationManager{}
+ if failed := nm.enqueueNotificationJobs(queue, jobs); failed {
+ t.Fatal("did not expect quiet-hours replay enqueue to fall back")
+ }
+
+ pending, err := queue.GetPending(10)
+ if err != nil {
+ t.Fatalf("GetPending failed: %v", err)
+ }
+ if len(pending) != 0 {
+ t.Fatalf("expected quiet-hours replay notification to wait for retry time, got %d pending", len(pending))
+ }
+
+ var queuedType string
+ var nextRetryAt int64
+ if err := queue.db.QueryRow(`SELECT type, next_retry_at FROM notification_queue WHERE type = ?`, "email").Scan(&queuedType, &nextRetryAt); err != nil {
+ t.Fatalf("failed to read queued quiet-hours notification: %v", err)
+ }
+ if queuedType != "email" {
+ t.Fatalf("queued type = %q, want email", queuedType)
+ }
+ if nextRetryAt != replayAt.Unix() {
+ t.Fatalf("next_retry_at = %d, want %d", nextRetryAt, replayAt.Unix())
+ }
+
+ readyAt := time.Now().Add(-time.Second).Unix()
+ if _, err := queue.db.Exec(`UPDATE notification_queue SET next_retry_at = ? WHERE type = ?`, readyAt, "email"); err != nil {
+ t.Fatalf("failed to move quiet-hours replay notification into retry window: %v", err)
+ }
+ pending, err = queue.GetPending(10)
+ if err != nil {
+ t.Fatalf("GetPending after replay window failed: %v", err)
+ }
+ if len(pending) != 1 || pending[0].ID == "" {
+ t.Fatalf("expected quiet-hours replay notification to become pending, got %#v", pending)
+ }
+}
+
func TestGetQueue_NilQueue(t *testing.T) {
nm := &NotificationManager{}