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 stale queued notification delivery
rcourtman464d3f84864d
diff --git a/internal/notifications/notifications.go b/internal/notifications/notifications.goindex 1d28ebdb1a..dcd4fc0c7b 100644--- a/internal/notifications/notifications.go+++ b/internal/notifications/notifications.go@@ -5,6 +5,7 @@ import ("context""crypto/tls""encoding/json"+ "errors""fmt""html""io"@@ -57,6 +58,8 @@ const (eventEscalation notificationEvent = "escalation")+var ErrNotificationCancelled = errors.New("notification cancelled")+// createSecureWebhookClient creates an HTTP client with security controlsfunc (n *NotificationManager) createSecureWebhookClient(timeout time.Duration) *http.Client {// dedicated transport that pins DNS resolution to prevent rebinding@@ -473,7 +476,6 @@ func (n *NotificationManager) GetPublicURL() string {// SetEmailConfig updates email configurationfunc (n *NotificationManager) SetEmailConfig(config EmailConfig) {n.mu.Lock()- defer n.mu.Unlock()n.emailConfig = config// Recreate email manager with new config to preserve rate limiting state@@ -492,13 +494,29 @@ func (n *NotificationManager) SetEmailConfig(config EmailConfig) {AuthRequired: config.Username != "" && config.Password != "",}n.emailManager = NewEnhancedEmailManager(providerConfig)+ queue := n.queue+ n.mu.Unlock()++ if !config.Enabled && queue != nil {+ if err := queue.CancelByTypes([]string{"email", "email_resolved", "email_escalation"}); err != nil {+ log.Error().Err(err).Msg("Failed to cancel queued email notifications after disable")+ }+ }}// SetAppriseConfig updates Apprise configuration.func (n *NotificationManager) SetAppriseConfig(config AppriseConfig) {n.mu.Lock()- defer n.mu.Unlock()n.appriseConfig = NormalizeAppriseConfig(config)+ queue := n.queue+ enabled := n.appriseConfig.Enabled+ n.mu.Unlock()++ if !enabled && queue != nil {+ if err := queue.CancelByTypes([]string{"apprise", "apprise_resolved", "apprise_escalation"}); err != nil {+ log.Error().Err(err).Msg("Failed to cancel queued Apprise notifications after disable")+ }+ }}// GetAppriseConfig returns a copy of the Apprise configuration.@@ -568,28 +586,40 @@ func (n *NotificationManager) AddWebhook(webhook WebhookConfig) {// UpdateWebhook updates an existing webhookfunc (n *NotificationManager) UpdateWebhook(id string, webhook WebhookConfig) error {n.mu.Lock()- defer n.mu.Unlock()-+ queue := n.queuefor i, w := range n.webhooks {if w.ID == id {n.webhooks[i] = webhook+ n.mu.Unlock()+ if !webhook.Enabled && queue != nil {+ if err := queue.CancelWebhooksByIDs([]string{id}); err != nil {+ log.Error().Err(err).Str("webhookID", id).Msg("Failed to cancel queued webhook notifications after disable")+ }+ }return nil}}+ n.mu.Unlock()return fmt.Errorf("webhook not found: %s", id)}// DeleteWebhook removes a webhookfunc (n *NotificationManager) DeleteWebhook(id string) error {n.mu.Lock()- defer n.mu.Unlock()-+ queue := n.queuefor i, w := range n.webhooks {if w.ID == id {n.webhooks = append(n.webhooks[:i], n.webhooks[i+1:]...)+ n.mu.Unlock()+ if queue != nil {+ if err := queue.CancelWebhooksByIDs([]string{id}); err != nil {+ log.Error().Err(err).Str("webhookID", id).Msg("Failed to cancel queued webhook notifications after delete")+ }+ }return nil}}+ n.mu.Unlock()return fmt.Errorf("webhook not found: %s", id)}@@ -3279,9 +3309,9 @@ func (n *NotificationManager) ProcessQueuedNotification(notif *QueuedNotificatiovar err errorswitch baseType {case "email":- var emailConfig EmailConfig- if err = json.Unmarshal(notif.Config, &emailConfig); err != nil {- return fmt.Errorf("failed to unmarshal email config: %w", err)+ emailConfig, resolveErr := n.resolveQueuedEmailConfig()+ if resolveErr != nil {+ return resolveErr}if event == eventResolved {err = n.sendResolvedEmail(emailConfig, notif.Alerts, resolvedTimeFromAlerts(notif.Alerts))@@ -3290,10 +3320,14 @@ func (n *NotificationManager) ProcessQueuedNotification(notif *QueuedNotificatio}case "webhook":- var webhookConfig WebhookConfig- if err = json.Unmarshal(notif.Config, &webhookConfig); err != nil {+ var queuedWebhookConfig WebhookConfig+ if err = json.Unmarshal(notif.Config, &queuedWebhookConfig); err != nil {return fmt.Errorf("failed to unmarshal webhook config: %w", err)}+ webhookConfig, resolveErr := n.resolveQueuedWebhookConfig(queuedWebhookConfig)+ if resolveErr != nil {+ return resolveErr+ }if event == eventResolved {err = n.sendResolvedWebhook(webhookConfig, notif.Alerts, resolvedTimeFromAlerts(notif.Alerts))} else {@@ -3301,9 +3335,9 @@ func (n *NotificationManager) ProcessQueuedNotification(notif *QueuedNotificatio}case "apprise":- var appriseConfig AppriseConfig- if err = json.Unmarshal(notif.Config, &appriseConfig); err != nil {- return fmt.Errorf("failed to unmarshal apprise config: %w", err)+ appriseConfig, resolveErr := n.resolveQueuedAppriseConfig()+ if resolveErr != nil {+ return resolveErr}if event == eventResolved {err = n.sendResolvedApprise(appriseConfig, notif.Alerts, resolvedTimeFromAlerts(notif.Alerts))@@ -3331,6 +3365,60 @@ func (n *NotificationManager) ProcessQueuedNotification(notif *QueuedNotificatioreturn err}+func (n *NotificationManager) resolveQueuedEmailConfig() (EmailConfig, error) {+ n.mu.RLock()+ config := copyEmailConfig(n.emailConfig)+ n.mu.RUnlock()++ if !config.Enabled {+ return EmailConfig{}, fmt.Errorf("%w: email notifications are disabled", ErrNotificationCancelled)+ }++ return config, nil+}++func (n *NotificationManager) resolveQueuedAppriseConfig() (AppriseConfig, error) {+ n.mu.RLock()+ config := copyAppriseConfig(n.appriseConfig)+ n.mu.RUnlock()++ if !config.Enabled {+ return AppriseConfig{}, fmt.Errorf("%w: Apprise notifications are disabled", ErrNotificationCancelled)+ }++ return config, nil+}++func (n *NotificationManager) resolveQueuedWebhookConfig(queued WebhookConfig) (WebhookConfig, error) {+ n.mu.RLock()+ webhooks := copyWebhookConfigs(n.webhooks)+ n.mu.RUnlock()++ if queued.ID != "" {+ for _, webhook := range webhooks {+ if webhook.ID != queued.ID {+ continue+ }+ if !webhook.Enabled {+ return WebhookConfig{}, fmt.Errorf("%w: webhook %s is disabled", ErrNotificationCancelled, queued.ID)+ }+ return webhook, nil+ }+ return WebhookConfig{}, fmt.Errorf("%w: webhook %s no longer exists", ErrNotificationCancelled, queued.ID)+ }++ for _, webhook := range webhooks {+ if webhook.Name == queued.Name && webhook.URL == queued.URL {+ if !webhook.Enabled {+ return WebhookConfig{}, fmt.Errorf("%w: webhook %q is disabled", ErrNotificationCancelled, queued.Name)+ }+ return webhook, nil+ }+ }++ return WebhookConfig{}, fmt.Errorf("%w: webhook %q no longer exists", ErrNotificationCancelled, queued.Name)+}+// cleanupOldNotificationRecords periodically cleans up old entries from lastNotified mapfunc (n *NotificationManager) cleanupOldNotificationRecords() {ticker := time.NewTicker(1 * time.Hour)diff --git a/internal/notifications/notifications_test.go b/internal/notifications/notifications_test.goindex a0621441ea..5c9a147d0d 100644--- a/internal/notifications/notifications_test.go+++ b/internal/notifications/notifications_test.go@@ -3,6 +3,7 @@ package notificationsimport ("context""encoding/json"+ "errors""io""net/http""net/http/httptest"@@ -29,6 +30,57 @@ func flushPending(n *NotificationManager) {n.sendGroupedAlerts()}+func testQueuedAlert() *alerts.Alert {+ return &alerts.Alert{+ ID: "queued-alert",+ Type: "cpu",+ Level: alerts.AlertLevelWarning,+ ResourceID: "vm-100",+ ResourceName: "vm-100",+ Message: "CPU usage high",+ Value: 95,+ Threshold: 90,+ StartTime: time.Now().Add(-time.Minute),+ LastSeen: time.Now(),+ }+}++func queuedNotificationStatus(t *testing.T, queue *NotificationQueue, id string) NotificationQueueStatus {+ t.Helper()++ var status string+ if err := queue.db.QueryRow(`SELECT status FROM notification_queue WHERE id = ?`, id).Scan(&status); err != nil {+ t.Fatalf("failed to read notification status: %v", err)+ }++ return NotificationQueueStatus(status)+}++func insertPendingQueuedNotification(t *testing.T, queue *NotificationQueue, notif *QueuedNotification) {+ t.Helper()++ alertsJSON, err := json.Marshal(notif.Alerts)+ if err != nil {+ t.Fatalf("marshal alerts: %v", err)+ }++ if notif.CreatedAt.IsZero() {+ notif.CreatedAt = time.Now()+ }+ if notif.MaxAttempts == 0 {+ notif.MaxAttempts = 3+ }++ _, err = queue.db.Exec(`+ INSERT INTO notification_queue+ (id, type, method, status, alerts, config, attempts, max_attempts, created_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)+ `, notif.ID, notif.Type, notif.Method, QueueStatusPending, string(alertsJSON), string(notif.Config), notif.Attempts, notif.MaxAttempts, notif.CreatedAt.Unix())+ if err != nil {+ t.Fatalf("insert queued notification: %v", err)+ }+}+func TestNormalizeAppriseConfig(t *testing.T) {original := AppriseConfig{Enabled: true,@@ -2794,20 +2846,21 @@ func TestSendNotificationsDirect_AppriseEnabled(t *testing.T) {}func TestProcessQueuedNotification_InvalidEmailConfig(t *testing.T) {- nm := &NotificationManager{}+ t.Setenv("PULSE_DATA_DIR", t.TempDir())++ nm := NewNotificationManager("")+ defer nm.Stop()+notif := &QueuedNotification{ID: "test-1",Type: "email",Config: json.RawMessage(`{invalid json`),- Alerts: []*alerts.Alert{},+ Alerts: []*alerts.Alert{testQueuedAlert()},}err := nm.ProcessQueuedNotification(notif)- if err == nil {- t.Error("expected error for invalid email config JSON")- }- if !strings.Contains(err.Error(), "failed to unmarshal email config") {- t.Errorf("expected 'failed to unmarshal email config' error, got: %v", err)+ if !errors.Is(err, ErrNotificationCancelled) {+ t.Fatalf("expected queued email to be cancelled when live config is disabled, got: %v", err)}}@@ -2830,20 +2883,146 @@ func TestProcessQueuedNotification_InvalidWebhookConfig(t *testing.T) {}func TestProcessQueuedNotification_InvalidAppriseConfig(t *testing.T) {- nm := &NotificationManager{}+ t.Setenv("PULSE_DATA_DIR", t.TempDir())++ nm := NewNotificationManager("")+ defer nm.Stop()+notif := &QueuedNotification{ID: "test-3",Type: "apprise",Config: json.RawMessage(`broken json`),- Alerts: []*alerts.Alert{},+ Alerts: []*alerts.Alert{testQueuedAlert()},}err := nm.ProcessQueuedNotification(notif)- if err == nil {- t.Error("expected error for invalid apprise config JSON")+ if !errors.Is(err, ErrNotificationCancelled) {+ t.Fatalf("expected queued Apprise notification to be cancelled when live config is disabled, got: %v", err)+ }+}++func TestProcessQueuedNotification_WebhookUsesCurrentConfig(t *testing.T) {+ t.Setenv("PULSE_DATA_DIR", t.TempDir())++ hits := make(chan struct{}, 1)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ select {+ case hits <- struct{}{}:+ default:+ }+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ nm := NewNotificationManager("https://pulse.local")+ defer nm.Stop()+ if err := nm.UpdateAllowedPrivateCIDRs("127.0.0.1/32"); err != nil {+ t.Fatalf("failed to allowlist localhost: %v", err)+ }++ currentWebhook := WebhookConfig{+ ID: "wh-live",+ Name: "live",+ URL: server.URL,+ Method: http.MethodPost,+ Enabled: true,+ }+ nm.AddWebhook(currentWebhook)++ queuedWebhook := currentWebhook+ queuedWebhook.URL = "https://example.invalid/should-not-be-used"++ configJSON, err := json.Marshal(queuedWebhook)+ if err != nil {+ t.Fatalf("marshal queued webhook: %v", err)+ }++ err = nm.ProcessQueuedNotification(&QueuedNotification{+ ID: "test-webhook-live",+ Type: "webhook",+ Config: configJSON,+ Alerts: []*alerts.Alert{testQueuedAlert()},+ })+ if err != nil {+ t.Fatalf("expected queued webhook to use live config, got: %v", err)+ }++ select {+ case <-hits:+ case <-time.After(2 * time.Second):+ t.Fatal("expected webhook request to hit the live webhook URL")}- if !strings.Contains(err.Error(), "failed to unmarshal apprise config") {- t.Errorf("expected 'failed to unmarshal apprise config' error, got: %v", err)+}++func TestSetEmailConfig_DisableCancelsQueuedEmailNotifications(t *testing.T) {+ t.Setenv("PULSE_DATA_DIR", t.TempDir())++ nm := NewNotificationManager("")+ defer nm.Stop()+ nm.queue.processorTicker.Stop()++ emailConfigJSON, err := json.Marshal(EmailConfig{+ Enabled: true,+ SMTPHost: "smtp.example.com",+ SMTPPort: 587,+ From: "[email protected]",+ To: []string{"[email protected]"},+ })+ if err != nil {+ t.Fatalf("marshal email config: %v", err)+ }++ notif := &QueuedNotification{+ ID: "queued-email-disable",+ Type: "email",+ Config: emailConfigJSON,+ Alerts: []*alerts.Alert{testQueuedAlert()},+ }+ insertPendingQueuedNotification(t, nm.queue, notif)++ nm.SetEmailConfig(EmailConfig{Enabled: false})++ if got := queuedNotificationStatus(t, nm.queue, notif.ID); got != QueueStatusCancelled {+ t.Fatalf("expected queued email to be cancelled, got %s", got)+ }+}++func TestUpdateWebhook_DisableCancelsQueuedWebhookNotifications(t *testing.T) {+ t.Setenv("PULSE_DATA_DIR", t.TempDir())++ nm := NewNotificationManager("")+ defer nm.Stop()+ nm.queue.processorTicker.Stop()++ webhook := WebhookConfig{+ ID: "queued-webhook",+ Name: "queued",+ URL: "https://example.com/webhook",+ Method: http.MethodPost,+ Enabled: true,+ }+ nm.AddWebhook(webhook)++ configJSON, err := json.Marshal(webhook)+ if err != nil {+ t.Fatalf("marshal webhook config: %v", err)+ }++ notif := &QueuedNotification{+ ID: "queued-webhook-disable",+ Type: "webhook",+ Config: configJSON,+ Alerts: []*alerts.Alert{testQueuedAlert()},+ }+ insertPendingQueuedNotification(t, nm.queue, notif)++ webhook.Enabled = false+ if err := nm.UpdateWebhook(webhook.ID, webhook); err != nil {+ t.Fatalf("disable webhook: %v", err)+ }++ if got := queuedNotificationStatus(t, nm.queue, notif.ID); got != QueueStatusCancelled {+ t.Fatalf("expected queued webhook to be cancelled, got %s", got)}}diff --git a/internal/notifications/queue.go b/internal/notifications/queue.goindex a76dec1a20..5cea40e503 100644--- a/internal/notifications/queue.go+++ b/internal/notifications/queue.go@@ -3,10 +3,12 @@ package notificationsimport ("database/sql""encoding/json"+ "errors""fmt""net/url""os""path/filepath"+ "strings""sync""time"@@ -294,12 +296,16 @@ func (nq *NotificationQueue) IncrementAttemptAndSetStatus(id string, status NotiSET attempts = attempts + 1,status = ?,last_attempt = ?- WHERE id = ?+ WHERE id = ? AND status = 'pending'`- _, err := nq.db.Exec(query, status, time.Now().Unix(), id)+ result, err := nq.db.Exec(query, status, time.Now().Unix(), id)if err != nil {return fmt.Errorf("failed to increment attempt and set status: %w", err)}+ rows, _ := result.RowsAffected()+ if rows == 0 {+ return fmt.Errorf("notification not pending: %s", id)+ }return nil}@@ -588,7 +594,11 @@ func (nq *NotificationQueue) processNotification(notif *QueuedNotification) {// Atomically increment attempt counter and set status to sendingif err := nq.IncrementAttemptAndSetStatus(notif.ID, QueueStatusSending); err != nil {- log.Error().Err(err).Str("id", notif.ID).Msg("Failed to increment attempt and set status")+ if strings.Contains(err.Error(), "notification not pending") {+ log.Debug().Str("id", notif.ID).Msg("Skipping notification that is no longer pending")+ } else {+ log.Error().Err(err).Str("id", notif.ID).Msg("Failed to increment attempt and set status")+ }return}@@ -604,8 +614,10 @@ func (nq *NotificationQueue) processNotification(notif *QueuedNotification) {err = fmt.Errorf("no processor configured")}+ cancelled := errors.Is(err, ErrNotificationCancelled)+// Record audit- success := err == nil+ success := err == nil || cancellederrorMsg := ""if err != nil {errorMsg = err.Error()@@ -615,7 +627,17 @@ func (nq *NotificationQueue) processNotification(notif *QueuedNotification) {log.Error().Err(auditErr).Str("id", notif.ID).Msg("Failed to record audit")}- if success {+ if cancelled {+ if err := nq.UpdateStatus(notif.ID, QueueStatusCancelled, errorMsg); err != nil {+ log.Error().Err(err).Str("id", notif.ID).Msg("Failed to update notification status to cancelled")+ } else {+ log.Info().+ Str("id", notif.ID).+ Str("type", notif.Type).+ Str("reason", errorMsg).+ Msg("Notification cancelled before delivery")+ }+ } else if success {// Mark as sentif err := nq.UpdateStatus(notif.ID, QueueStatusSent, ""); err != nil {log.Error().Err(err).Str("id", notif.ID).Msg("Failed to update notification status to sent")@@ -725,6 +747,120 @@ func (nq *NotificationQueue) Stop() error {return nil}+func sqlPlaceholders(count int) string {+ if count <= 0 {+ return ""+ }+ return strings.TrimRight(strings.Repeat("?,", count), ",")+}++func (nq *NotificationQueue) cancelByIDsLocked(ids []string, reason string) error {+ if len(ids) == 0 {+ return nil+ }++ now := time.Now().Unix()+ args := make([]interface{}, 0, len(ids)+3)+ args = append(args, QueueStatusCancelled, now, reason)+ for _, id := range ids {+ args = append(args, id)+ }++ query := fmt.Sprintf(`+ UPDATE notification_queue+ SET status = ?, completed_at = ?, last_error = ?+ WHERE id IN (%s) AND status IN ('pending', 'sending')+ `, sqlPlaceholders(len(ids)))++ _, err := nq.db.Exec(query, args...)+ if err != nil {+ return fmt.Errorf("failed to cancel notifications: %w", err)+ }++ return nil+}++// CancelByTypes marks queued notifications of the given types as cancelled.+func (nq *NotificationQueue) CancelByTypes(types []string) error {+ if len(types) == 0 {+ return nil+ }++ nq.mu.Lock()+ defer nq.mu.Unlock()++ now := time.Now().Unix()+ args := make([]interface{}, 0, len(types)+3)+ args = append(args, QueueStatusCancelled, now, "cancelled due to notification configuration change")+ for _, typ := range types {+ args = append(args, typ)+ }++ query := fmt.Sprintf(`+ UPDATE notification_queue+ SET status = ?, completed_at = ?, last_error = ?+ WHERE status IN ('pending', 'sending') AND type IN (%s)+ `, sqlPlaceholders(len(types)))++ _, err := nq.db.Exec(query, args...)+ if err != nil {+ return fmt.Errorf("failed to cancel notifications by type: %w", err)+ }++ return nil+}++// CancelWebhooksByIDs marks queued webhook notifications for the given webhook IDs as cancelled.+func (nq *NotificationQueue) CancelWebhooksByIDs(webhookIDs []string) error {+ if len(webhookIDs) == 0 {+ return nil+ }++ nq.mu.Lock()+ defer nq.mu.Unlock()++ rows, err := nq.db.Query(`+ SELECT id, config+ FROM notification_queue+ WHERE status IN ('pending', 'sending')+ AND type IN ('webhook', 'webhook_resolved', 'webhook_escalation')+ `)+ if err != nil {+ return fmt.Errorf("failed to query queued webhooks for cancellation: %w", err)+ }+ defer rows.Close()++ webhookIDSet := make(map[string]struct{}, len(webhookIDs))+ for _, id := range webhookIDs {+ webhookIDSet[id] = struct{}{}+ }++ var queueIDs []string+ for rows.Next() {+ var queueID string+ var configJSON []byte+ if err := rows.Scan(&queueID, &configJSON); err != nil {+ return fmt.Errorf("failed to scan queued webhook notification: %w", err)+ }++ var webhook WebhookConfig+ if err := json.Unmarshal(configJSON, &webhook); err != nil {+ log.Error().Err(err).Str("notificationID", queueID).Msg("Failed to parse queued webhook config for cancellation")+ continue+ }++ if _, exists := webhookIDSet[webhook.ID]; exists {+ queueIDs = append(queueIDs, queueID)+ }+ }++ if err := rows.Err(); err != nil {+ return fmt.Errorf("failed while reading queued webhook notifications: %w", err)+ }++ return nq.cancelByIDsLocked(queueIDs, "cancelled due to webhook configuration change")+}+// calculateBackoff calculates exponential backoff durationfunc calculateBackoff(attempt int) time.Duration {// 1s, 2s, 4s, 8s, 16s, 32s, 60s (capped)