Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Fix alert escalation notification scheduling
rcourtmand8f154addd1a
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 57f318a1d5..6310b3bcc9 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -342,7 +342,11 @@ alerts delivery layer. Monitor-owned escalation handling may still publishcanonical escalation state to websocket consumers, but notification fan-outmust defer quiet-hours and resolved-notification suppression policy to thealerts manager instead of bypassing that shared routing contract when monitor-plumbs escalations outward.+plumbs escalations outward. Scheduled escalation delivery must use the+notification manager's explicit escalation path, not normal alert re-send+delivery, so delivery cooldown cannot suppress an escalation level that the+alert manager has already deemed due and the escalation channel target remains+the configured email/webhook/all target for that level.That same monitoring owner now also governs monitored-system grouping readinessfor settings and support boundaries. A non-nil unified read-state is notsufficient when provider-owned supplemental inventories such as TrueNAS ordiff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.mdindex d7d48c28ad..08aebfe200 100644--- a/docs/release-control/v6/internal/subsystems/notifications.md+++ b/docs/release-control/v6/internal/subsystems/notifications.md@@ -158,13 +158,22 @@ That same queue owner also governs alert-resolution cancellation policy.Cancelling queued work by alert identifier must remove outstanding firingdeliveries for that alert, but it must preserve already-queued resolvednotifications so recovery deliveries cannot be dropped just because the alert-was resolved before the queue drained.+was resolved before the queue drained. Cancellation must run even when there is+no in-memory grouped notification pending, because the persistent queue and the+delivery cooldown map are also notification-owned state for the alert+occurrence.That same queue boundary also owns processor attachment semantics. Thecanonical queue may persist pending notifications before a delivery processor isconfigured, but it must not mark those entries sending, failed, or sent until aprocessor exists. When a processor is attached, the queue owner must wake thepending backlog through the same canonical batch path instead of relying on aseparate direct-send shortcut or waiting for an unrelated timer tick.+Alert delivery cooldown is also owned at this boundary. Normal alert delivery+must suppress duplicate sends for the same active alert occurrence when+cooldown is disabled or still active; scheduled escalation delivery is the+explicit exception and must route through the dedicated escalation send path so+the alert schedule, not transport cooldown, controls escalation cadence and+channel targeting.`internal/api/notifications.go` and`frontend-modern/src/api/notifications.ts` are shared boundaries withdiff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 7fb6b4d330..4af73b6985 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -431,6 +431,7 @@ func TestEscalationDeliveryDefersToCanonicalAlertSuppression(t *testing.T) {"monitor_alerts.go": {"func (m *Monitor) handleAlertEscalated(hub *websocket.Hub, alert *alerts.Alert, level int) {","if m.alertManager.ShouldSuppressNotification(alert) {",+ "m.notificationMgr.SendEscalatedAlert(alert, escalationLevel.Notify)","m.broadcastEscalatedAlert(hub, alert)",},}diff --git a/internal/monitoring/monitor_alert_handling_test.go b/internal/monitoring/monitor_alert_handling_test.goindex a4733b63e1..9f0cccb027 100644--- a/internal/monitoring/monitor_alert_handling_test.go+++ b/internal/monitoring/monitor_alert_handling_test.go@@ -493,3 +493,66 @@ func TestMonitor_HandleAlertEscalated_SendsNotificationWhenNotSuppressed(t *testt.Fatal("expected escalated notification delivery")}}++func TestMonitor_HandleAlertEscalated_BypassesDeliveryCooldown(t *testing.T) {+ t.Setenv("PULSE_DATA_DIR", t.TempDir())++ requests := make(chan struct{}, 2)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requests <- struct{}{}+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ notifMgr := notifications.NewNotificationManager("https://pulse.local")+ defer notifMgr.Stop()+ notifMgr.SetGroupingWindow(0)+ notifMgr.SetCooldown(30)+ if err := notifMgr.UpdateAllowedPrivateCIDRs("127.0.0.1/32"); err != nil {+ t.Fatalf("UpdateAllowedPrivateCIDRs: %v", err)+ }+ notifMgr.AddWebhook(notifications.WebhookConfig{+ ID: "cooldown-hook",+ Name: "cooldown",+ URL: server.URL,+ Enabled: true,+ })++ mgr := alerts.NewManager()+ cfg := mgr.GetConfig()+ cfg.Schedule.Escalation.Levels = []alerts.EscalationLevel{{After: 1, Notify: "webhook"}}+ cfg.Schedule.QuietHours.Enabled = false+ mgr.UpdateConfig(cfg)++ m := &Monitor{+ notificationMgr: notifMgr,+ alertManager: mgr,+ }++ alert := &alerts.Alert{+ ID: "escalated-with-cooldown",+ Type: "memory",+ Level: alerts.AlertLevelWarning,+ ResourceID: "vm/100",+ ResourceName: "vm-100",+ Node: "pve-1",+ Instance: "pve",+ Message: "Memory threshold crossed",+ StartTime: time.Now().Add(-10 * time.Minute),+ }++ notifMgr.SendAlert(alert)+ select {+ case <-requests:+ case <-time.After(2 * time.Second):+ t.Fatal("expected initial notification delivery")+ }++ m.handleAlertEscalated(nil, alert, 1)++ select {+ case <-requests:+ case <-time.After(2 * time.Second):+ t.Fatal("expected escalated notification delivery despite active cooldown")+ }+}diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.goindex 9bb7081166..d7f95b6936 100644--- a/internal/monitoring/monitor_alerts.go+++ b/internal/monitoring/monitor_alerts.go@@ -2,6 +2,7 @@ package monitoringimport ("context"+ "strings""time""github.com/rcourtman/pulse-go-rewrite/internal/ai/memory"@@ -196,20 +197,15 @@ func (m *Monitor) handleAlertEscalated(hub *websocket.Hub, alert *alerts.Alert,if m.notificationMgr != nil {escalationLevel := config.Schedule.Escalation.Levels[level-1]- switch escalationLevel.Notify {- case "email":- if emailConfig := m.notificationMgr.GetEmailConfig(); emailConfig.Enabled {- m.notificationMgr.SendAlert(alert)- }- case "webhook":- for _, webhook := range m.notificationMgr.GetWebhooks() {- if webhook.Enabled {- m.notificationMgr.SendAlert(alert)- break- }- }- case "all":- m.notificationMgr.SendAlert(alert)+ switch strings.ToLower(strings.TrimSpace(escalationLevel.Notify)) {+ case "", "all", "email", "webhook", "webhooks":+ m.notificationMgr.SendEscalatedAlert(alert, escalationLevel.Notify)+ default:+ log.Warn().+ Str("alertID", alert.ID).+ Int("level", level).+ Str("notify", escalationLevel.Notify).+ Msg("Skipping alert escalation with unknown notification target")}}diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.goindex 485f42f59e..952ddbff0b 100644--- a/internal/notifications/notifications.go+++ b/internal/notifications/notifications.go@@ -78,6 +78,21 @@ type notificationQueueBucket struct {nextRetryAt *time.Time}+type notificationDeliveryTarget string++const (+ notificationDeliveryTargetAll notificationDeliveryTarget = "all"+ notificationDeliveryTargetEmail notificationDeliveryTarget = "email"+ notificationDeliveryTargetWebhook notificationDeliveryTarget = "webhook"+ notificationDeliveryTargetApprise notificationDeliveryTarget = "apprise"+)++type alertSendOptions struct {+ bypassCooldown bool+ immediate bool+ target notificationDeliveryTarget+}+// createSecureWebhookClient creates an HTTP client with security controlsfunc (n *NotificationManager) createSecureWebhookClient(timeout time.Duration) *http.Client {return n.createSecureWebhookClientWithTLS(timeout, false)@@ -934,8 +949,23 @@ func (n *NotificationManager) IsEnabled() bool {return n.enabled}-// SendAlert sends notifications for an alert+// SendAlert sends notifications for a newly fired or explicitly re-notified alert.func (n *NotificationManager) SendAlert(alert *alerts.Alert) {+ n.sendAlert(alert, alertSendOptions{target: notificationDeliveryTargetAll})+}++// SendEscalatedAlert sends a scheduled escalation notification. Escalation+// cadence is owned by the alert schedule, so delivery cooldown must not suppress+// a level that the alert manager has already decided is due.+func (n *NotificationManager) SendEscalatedAlert(alert *alerts.Alert, notifyTarget string) {+ n.sendAlert(alert, alertSendOptions{+ bypassCooldown: true,+ immediate: true,+ target: normalizeNotificationDeliveryTarget(notifyTarget),+ })+}++func (n *NotificationManager) sendAlert(alert *alerts.Alert, options alertSendOptions) {if alert == nil {return}@@ -943,9 +973,11 @@ func (n *NotificationManager) SendAlert(alert *alerts.Alert) {if alert == nil {return}+ if options.target == "" {+ options.target = notificationDeliveryTargetAll+ }n.mu.Lock()- defer n.mu.Unlock()log.Info().Str("alertID", alert.ID).@@ -956,20 +988,57 @@ func (n *NotificationManager) SendAlert(alert *alerts.Alert) {if !n.enabled {log.Debug().Msg("notifications disabled, skipping")+ n.mu.Unlock()return}- // Check cooldown+ // Check cooldown. A disabled cooldown means "do not send repeat+ // notifications for the same active alert occurrence"; escalation uses an+ // explicit bypass because its cadence is owned by the alert schedule.record, exists := n.lastNotified[alert.ID]- if exists && record.alertStart.Equal(alert.StartTime) && time.Since(record.lastSent) < n.cooldown {+ if !options.bypassCooldown && exists && record.alertStart.Equal(alert.StartTime) && (n.cooldown <= 0 || time.Since(record.lastSent) < n.cooldown) {+ elapsed := time.Since(record.lastSent)+ remainingCooldown := time.Duration(0)+ if n.cooldown > elapsed {+ remainingCooldown = n.cooldown - elapsed+ }log.Info().Str("alertID", alert.ID).Str("resourceName", alert.ResourceName).Str("type", alert.Type).- Dur("timeSince", time.Since(record.lastSent)).+ Dur("timeSince", elapsed).Dur("cooldown", n.cooldown).- Dur("remainingCooldown", n.cooldown-time.Since(record.lastSent)).+ Dur("remainingCooldown", remainingCooldown).Msg("alert notification in cooldown for active alert - notification suppressed")+ n.mu.Unlock()+ return+ }++ if options.immediate {+ emailConfig := copyEmailConfig(n.emailConfig)+ webhooks := copyWebhookConfigs(n.webhooks)+ appriseConfig := copyAppriseConfig(n.appriseConfig)+ queue := n.queue+ n.mu.Unlock()++ alertsToSend := []*alerts.Alert{alert}+ jobs := buildNotificationDeliveryJobsForTarget(+ emailConfig,+ webhooks,+ appriseConfig,+ alertsToSend,+ eventAlert,+ time.Time{},+ options.target,+ )+ if queue != nil {+ if anyFailed := n.enqueueNotificationJobs(queue, jobs); anyFailed {+ n.markAlertsNotified(alertsToSend, time.Now())+ }+ } else {+ n.dispatchNotificationJobsAsync(jobs)+ n.markAlertsNotified(alertsToSend, time.Now())+ }return}@@ -995,6 +1064,7 @@ func (n *NotificationManager) SendAlert(alert *alerts.Alert) {Dur("groupWindow", n.groupWindow).Msg("started alert grouping timer")}+ n.mu.Unlock()}func (n *NotificationManager) markAlertsNotified(alertsToSend []*alerts.Alert, sentAt time.Time) {@@ -1060,48 +1130,43 @@ func (n *NotificationManager) SendResolvedAlert(resolved *alerts.ResolvedAlert)// CancelAlert removes pending notifications for a resolved alertfunc (n *NotificationManager) CancelAlert(alertID string) {n.mu.Lock()- defer n.mu.Unlock()-- if len(n.pendingAlerts) == 0 {- return- }+ queue := n.queue- filtered := n.pendingAlerts[:0]removed := 0- for _, pending := range n.pendingAlerts {- if pending == nil {- continue- }- if pending.ID == alertID {- removed++- continue+ if len(n.pendingAlerts) > 0 {+ filtered := n.pendingAlerts[:0]+ for _, pending := range n.pendingAlerts {+ if pending == nil {+ continue+ }+ if pending.ID == alertID {+ removed+++ continue+ }+ filtered = append(filtered, pending)}- filtered = append(filtered, pending)- }-- if removed == 0 {- return- }- for i := len(filtered); i < len(n.pendingAlerts); i++ {- n.pendingAlerts[i] = nil- }+ for i := len(filtered); i < len(n.pendingAlerts); i++ {+ n.pendingAlerts[i] = nil+ }- n.pendingAlerts = filtered+ n.pendingAlerts = filtered- if len(n.pendingAlerts) == 0 && n.groupTimer != nil {- if n.groupTimer.Stop() {- log.Debug().Str("alertID", alertID).Msg("stopped grouping timer after alert cancellation")+ if len(n.pendingAlerts) == 0 && n.groupTimer != nil {+ if n.groupTimer.Stop() {+ log.Debug().Str("alertID", alertID).Msg("stopped grouping timer after alert cancellation")+ }+ n.groupTimer = nil}- n.groupTimer = nil}// Clean up cooldown record for resolved alertdelete(n.lastNotified, alertID)+ n.mu.Unlock()// Cancel any queued notifications containing this alert- if n.queue != nil {- if err := n.queue.CancelByAlertIdentifiers([]string{alertID}); err != nil {+ if queue != nil {+ if err := queue.CancelByAlertIdentifiers([]string{alertID}); err != nil {log.Error().Err(err).Str("alertID", alertID).Msg("failed to cancel queued notifications")}}@@ -1158,8 +1223,32 @@ func (n *NotificationManager) sendGroupedAlerts() {}func buildNotificationDeliveryJobs(emailConfig EmailConfig, webhooks []WebhookConfig, appriseConfig AppriseConfig, alertsToSend []*alerts.Alert, event notificationEvent, resolvedAt time.Time) []notificationDeliveryJob {+ return buildNotificationDeliveryJobsForTarget(+ emailConfig,+ webhooks,+ appriseConfig,+ alertsToSend,+ event,+ resolvedAt,+ notificationDeliveryTargetAll,+ )+}++func buildNotificationDeliveryJobsForTarget(+ emailConfig EmailConfig,+ webhooks []WebhookConfig,+ appriseConfig AppriseConfig,+ alertsToSend []*alerts.Alert,+ event notificationEvent,+ resolvedAt time.Time,+ target notificationDeliveryTarget,+) []notificationDeliveryJob {+ if target == "" {+ target = notificationDeliveryTargetAll+ }+jobs := make([]notificationDeliveryJob, 0, 2+len(webhooks))- if emailConfig.Enabled {+ if emailConfig.Enabled && (target == notificationDeliveryTargetAll || target == notificationDeliveryTargetEmail) {emailCopy := emailConfigjobs = append(jobs, notificationDeliveryJob{Type: "email",@@ -1169,20 +1258,22 @@ func buildNotificationDeliveryJobs(emailConfig EmailConfig, webhooks []WebhookCoEmailConfig: &emailCopy,})}- for _, webhook := range webhooks {- if !webhook.Enabled {- continue+ if target == notificationDeliveryTargetAll || target == notificationDeliveryTargetWebhook {+ for _, webhook := range webhooks {+ if !webhook.Enabled {+ continue+ }+ webhookCopy := webhook+ jobs = append(jobs, notificationDeliveryJob{+ Type: "webhook",+ Event: event,+ Alerts: alertsToSend,+ ResolvedAt: resolvedAt,+ WebhookConfig: &webhookCopy,+ })}- webhookCopy := webhook- jobs = append(jobs, notificationDeliveryJob{- Type: "webhook",- Event: event,- Alerts: alertsToSend,- ResolvedAt: resolvedAt,- WebhookConfig: &webhookCopy,- })}- if appriseConfig.Enabled {+ if appriseConfig.Enabled && (target == notificationDeliveryTargetAll || target == notificationDeliveryTargetApprise) {appriseCopy := appriseConfigjobs = append(jobs, notificationDeliveryJob{Type: "apprise",@@ -1203,6 +1294,21 @@ func queueTypeForNotificationDeliveryJob(job notificationDeliveryJob) string {return queueType}+func normalizeNotificationDeliveryTarget(raw string) notificationDeliveryTarget {+ switch strings.ToLower(strings.TrimSpace(raw)) {+ case "", string(notificationDeliveryTargetAll):+ return notificationDeliveryTargetAll+ case string(notificationDeliveryTargetEmail):+ return notificationDeliveryTargetEmail+ case string(notificationDeliveryTargetWebhook), "webhooks":+ return notificationDeliveryTargetWebhook+ case string(notificationDeliveryTargetApprise):+ return notificationDeliveryTargetApprise+ default:+ return notificationDeliveryTargetAll+ }+}+func configJSONForNotificationDeliveryJob(job notificationDeliveryJob) ([]byte, error) {switch job.Type {case "email":diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.goindex 5beffd925c..c2c643de5b 100644--- a/internal/notifications/notifications_test.go+++ b/internal/notifications/notifications_test.go@@ -418,6 +418,165 @@ func TestNotificationCooldownAllowsNewAlertInstance(t *testing.T) {}}+func TestNotificationCooldownDisabledSuppressesDuplicateActiveAlert(t *testing.T) {+ t.Setenv("PULSE_DATA_DIR", t.TempDir())+ nm := NewNotificationManager("")+ defer nm.Stop()+ nm.SetCooldown(0)+ nm.SetGroupingWindow(3600) // keep timer from firing during assertions++ alert := &alerts.Alert{+ ID: "vm-100-cpu",+ Type: "cpu",+ Level: alerts.AlertLevelWarning,+ StartTime: time.Now().Add(-time.Minute),+ }++ nm.SendAlert(alert)+ flushPending(nm)++ nm.SendAlert(alert)++ nm.mu.RLock()+ pendingAfterDuplicate := len(nm.pendingAlerts)+ nm.mu.RUnlock()++ if pendingAfterDuplicate != 0 {+ t.Fatalf("cooldown-disabled duplicate should not be queued, found %d pending", pendingAfterDuplicate)+ }+}++func TestSendEscalatedAlertBypassesCooldownAndTargetsWebhook(t *testing.T) {+ queue, err := NewNotificationQueue(t.TempDir())+ if err != nil {+ t.Fatalf("failed to create queue: %v", err)+ }+ defer func() { _ = queue.Stop() }()++ alertStart := time.Now().Add(-10 * time.Minute)+ alert := &alerts.Alert{+ ID: "vm-100-memory",+ Type: "memory",+ Level: alerts.AlertLevelWarning,+ ResourceName: "vm-100",+ Message: "memory threshold crossed",+ StartTime: alertStart,+ }+ nm := &NotificationManager{+ enabled: true,+ cooldown: 30 * time.Minute,+ emailConfig: EmailConfig{+ Enabled: true,+ SMTPHost: "smtp.example.test",+ SMTPPort: 587,+ From: "[email protected]",+ To: []string{"[email protected]"},+ },+ webhooks: []WebhookConfig{{+ ID: "hook-1",+ Name: "Webhook",+ URL: "https://hooks.example.test/pulse",+ Enabled: true,+ }},+ appriseConfig: AppriseConfig{+ Enabled: true,+ Mode: AppriseModeCLI,+ Targets: []string{"mailto://[email protected]"},+ },+ lastNotified: map[string]notificationRecord{+ alert.ID: {+ lastSent: time.Now(),+ alertStart: alertStart,+ },+ },+ queue: queue,+ }++ nm.SendAlert(alert)+ nm.mu.RLock()+ pendingAfterNormalSend := len(nm.pendingAlerts)+ nm.mu.RUnlock()+ if pendingAfterNormalSend != 0 {+ t.Fatalf("normal send should be suppressed by cooldown, found %d pending", pendingAfterNormalSend)+ }++ nm.SendEscalatedAlert(alert, "webhook")++ rows, err := queue.db.Query(`SELECT type FROM notification_queue ORDER BY created_at`)+ if err != nil {+ t.Fatalf("failed to read queued notifications: %v", err)+ }+ defer rows.Close()++ var queuedTypes []string+ for rows.Next() {+ var queuedType string+ if err := rows.Scan(&queuedType); err != nil {+ t.Fatalf("failed to scan queued notification: %v", err)+ }+ queuedTypes = append(queuedTypes, queuedType)+ }+ if err := rows.Err(); err != nil {+ t.Fatalf("failed to iterate queued notifications: %v", err)+ }++ if len(queuedTypes) != 1 || queuedTypes[0] != "webhook" {+ t.Fatalf("expected only one webhook escalation notification, got %#v", queuedTypes)+ }+}++func TestCancelAlertClearsCooldownAndQueueWithoutPendingGroup(t *testing.T) {+ queue, err := NewNotificationQueue(t.TempDir())+ if err != nil {+ t.Fatalf("failed to create queue: %v", err)+ }+ defer func() { _ = queue.Stop() }()++ alert := &alerts.Alert{+ ID: "alert-without-pending-group",+ Type: "cpu",+ Level: alerts.AlertLevelWarning,+ StartTime: time.Now().Add(-time.Minute),+ }+ if err := queue.Enqueue(&QueuedNotification{+ Type: "webhook",+ Status: QueueStatusPending,+ Alerts: []*alerts.Alert{alert},+ Config: json.RawMessage(`{"enabled":true,"url":"https://hooks.example.test/pulse"}`),+ MaxAttempts: 3,+ }); err != nil {+ t.Fatalf("failed to enqueue notification: %v", err)+ }++ nm := &NotificationManager{+ lastNotified: map[string]notificationRecord{+ alert.ID: {+ lastSent: time.Now(),+ alertStart: alert.StartTime,+ },+ },+ pendingAlerts: []*alerts.Alert{},+ queue: queue,+ }++ nm.CancelAlert(alert.ID)++ nm.mu.RLock()+ _, hasCooldownRecord := nm.lastNotified[alert.ID]+ nm.mu.RUnlock()+ if hasCooldownRecord {+ t.Fatal("expected resolved alert cooldown record to be cleared")+ }++ var status string+ if err := queue.db.QueryRow(`SELECT status FROM notification_queue WHERE type = ?`, "webhook").Scan(&status); err != nil {+ t.Fatalf("failed to read queued notification status: %v", err)+ }+ if status != string(QueueStatusCancelled) {+ t.Fatalf("expected queued firing notification to be cancelled, got %q", status)+ }+}+func TestCancelAlertRemovesPending(t *testing.T) {t.Setenv("PULSE_DATA_DIR", t.TempDir())nm := NewNotificationManager("")