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
feat(alerts): raise a system alert when notification delivery is failing
rcourtman1a142127857a
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 5d52a937dd..f4f045e2ee 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -497,6 +497,7 @@ cleanup so readers cannot retain orphaned runtime or alert projections.62. `internal/monitoring/kubernetes_metadata_migration.go`62a. `internal/monitoring/monitor_xcpng.go`63. `internal/monitoring/metadata_stores.go`+64. `internal/monitoring/system_alerts.go`63a. `internal/config/docker_metadata.go`63b. `internal/config/guest_metadata.go`@@ -921,6 +922,21 @@ cleanup so readers cannot retain orphaned runtime or alert projections.cancellation, timeout, and network failures remain transient and retry onthe next polling call. Concurrent callers must share one in-flight `/nodes`request so immediate retry does not create a request storm.+21. Add or change system-alert evaluation through+ `internal/monitoring/system_alerts.go`. Monitoring holds both the+ notification manager and the alert manager, so it is where a condition+ about Pulse itself becomes an alert. The founding case is notification+ delivery: a destination that has stopped delivering cannot announce itself+ through a notification, so the alert list and navigation badge are the only+ escalation path left. The verdict must come from+ `notifications.ClassifyQueueHealth` rather than a local rule, and the+ result must be raised through `alerts.RaiseSystemAlert` so identity and+ idempotence stay owned by the alerts subsystem. Evaluation runs on the poll+ ticker and must stay throttled well below the polling cadence, because+ reading queue health costs a database query. New Monitor struct fields+ added for this must fit the existing field alignment column: a longer name+ makes gofmt re-pad the whole block and breaks the canonical guardrail tests+ that pin those declarations verbatim.## Forbidden Pathsdiff --git a/docs/release-control/v6/internal/subsystems/notifications.md b/docs/release-control/v6/internal/subsystems/notifications.mdindex bf9cc0e2b7..0bf04c6e9c 100644--- a/docs/release-control/v6/internal/subsystems/notifications.md+++ b/docs/release-control/v6/internal/subsystems/notifications.md@@ -44,6 +44,7 @@ group headings, and HTML-escape every resource, message, and category field.7. `internal/operationaltrust/contracts.go`8. `internal/api/notification_queue.go`9. `internal/notifications/tag_routing.go`+10. `internal/notifications/delivery_health.go`## Shared Boundaries@@ -57,6 +58,16 @@ group headings, and HTML-escape every resource, message, and category field.1. Add or change provider delivery, queue processing, or retry behavior through `internal/notifications/`2. Add or change notification-management request or response handling through `internal/api/notifications.go`3. Add or change notification-management frontend transport through `frontend-modern/src/api/notifications.ts`+4. Add or change the delivery-health verdict through+ `internal/notifications/delivery_health.go`. `ClassifyQueueHealth` is the+ single rule for whether configured destinations are reaching anyone, and it+ lives beside the queue that produces the counts so consumers cannot each+ carry their own copy. Only terminal failed or dead-letter outcomes count as+ unhealthy; recoverable retry attempts do not. A queue that cannot be read+ reports `unavailable` and never `healthy`, because an unreadable queue must+ not be mistaken for successful delivery. `internal/api/notifications.go`+ delegates to this rule rather than reimplementing it, and `monitoring`+ consumes it to raise the notification-delivery system alert.## Forbidden Pathsdiff --git a/internal/api/notifications.go b/internal/api/notifications.goindex e525e4a0a2..b77f75a009 100644--- a/internal/api/notifications.go+++ b/internal/api/notifications.go@@ -903,18 +903,12 @@ func (h *NotificationHandlers) GetNotificationHealth(w http.ResponseWriter, r *hjson.NewEncoder(w).Encode(health)}+// classifyNotificationQueueHealth delegates to the canonical rule in+// internal/notifications so this endpoint and the monitoring loop that raises+// the notification-delivery system alert cannot drift apart.func classifyNotificationQueueHealth(stats map[string]int) (bool, int, []string) {- failed := stats[string(notifications.QueueStatusFailed)]- deadLetter := stats[string(notifications.QueueStatusDLQ)]- reasonCodes := make([]string, 0, 2)- if failed > 0 {- reasonCodes = append(reasonCodes, "retained_failed_deliveries")- }- if deadLetter > 0 {- reasonCodes = append(reasonCodes, "retained_dead_letter_deliveries")- }- attentionRequired := failed + deadLetter- return attentionRequired == 0, attentionRequired, reasonCodes+ health := notifications.ClassifyQueueHealth(stats)+ return health.Healthy, health.AttentionRequired, health.ReasonCodes}func countEnabledWebhooks(webhooks []notifications.WebhookConfig) int {diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex aed225a92c..4fb71dc1de 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1107,6 +1107,7 @@ type Monitor struct {connectionsSnapshotLister func() []alerts.ConnectionSnapshot // returns platform connection snapshots for the connection-degraded checkincidentStore *memory.IncidentStorenotificationMgr *notifications.NotificationManager+ lastDeliveryHealthCheck time.Time // throttles the notification-delivery system alert evaluation; guarded by muconfigPersist *config.ConfigPersistencediscoveryService *discovery.Service // Background discovery serviceactivePollCount int32 // Number of active polling operations@@ -2027,6 +2028,7 @@ func (m *Monitor) Start(ctx context.Context, wsHub *websocket.Hub) {m.cleanupTrackingMaps(now)m.cleanupMetricsHistory()m.cleanupRateTracker(now)+ m.evaluateNotificationDelivery(now)if mock.IsMockEnabled() {// In mock mode, keep synthetic alerts freshgo m.checkMockAlerts()diff --git a/internal/monitoring/system_alerts.go b/internal/monitoring/system_alerts.gonew file mode 100644index 0000000000..d2b079c876--- /dev/null+++ b/internal/monitoring/system_alerts.go@@ -0,0 +1,100 @@+package monitoring++import (+ "fmt"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"+ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"+)++// notificationDeliveryCheckInterval throttles the delivery-health evaluation.+// The poll ticker runs on the configured polling cadence, which can be a few+// seconds, and reading queue health costs a SQLite query, so the check runs on+// its own slower schedule rather than on every poll.+const notificationDeliveryCheckInterval = 5 * time.Minute++// evaluateNotificationDelivery raises or clears the notification-delivery+// system alert. A destination that has stopped delivering cannot announce+// itself through a notification, so this is the path that puts it in the alert+// list and the navigation badge instead.+//+// RaiseSystemAlert is idempotent for an unchanged condition, so repeating this+// on a timer neither re-notifies nor accumulates alerts.+func (m *Monitor) evaluateNotificationDelivery(now time.Time) {+ if m == nil {+ return+ }+ if now.IsZero() {+ now = time.Now()+ }++ m.mu.Lock()+ if !m.lastDeliveryHealthCheck.IsZero() &&+ now.Sub(m.lastDeliveryHealthCheck) < notificationDeliveryCheckInterval {+ m.mu.Unlock()+ return+ }+ m.lastDeliveryHealthCheck = now+ notificationMgr := m.notificationMgr+ m.mu.Unlock()++ alertManager := m.GetAlertManager()+ if alertManager == nil || notificationMgr == nil {+ return+ }++ health := notificationMgr.DeliveryHealth()+ if health.Healthy {+ alertManager.ClearSystemAlert(alerts.NotificationDeliveryAlertType)+ return+ }++ alertManager.RaiseSystemAlert(alerts.SystemAlertInput{+ Type: alerts.NotificationDeliveryAlertType,+ Level: alerts.AlertLevelWarning,+ Message: notificationDeliveryAlertMessage(health),+ Metadata: map[string]interface{}{+ "deliveryStatus": string(health.Status),+ "failedDeliveries": health.Failed,+ "deadLetterCount": health.DeadLetter,+ "attentionRequired": health.AttentionRequired,+ "reasonCodes": health.ReasonCodes,+ },+ })+}++// notificationDeliveryAlertMessage says what failed and where to fix it. The+// operator reading this has, by definition, not received a notification about+// it, so the message has to stand on its own.+func notificationDeliveryAlertMessage(health notifications.DeliveryHealth) string {+ if health.Status == notifications.DeliveryUnavailable {+ return "Pulse cannot read the notification queue, so alert delivery cannot be confirmed. Check the Pulse logs and the notification settings."+ }++ switch {+ case health.Failed > 0 && health.DeadLetter > 0:+ return fmt.Sprintf(+ "Alert notifications are not reaching their destinations. %s and %s were not delivered. Check destination credentials and settings under Alerts, Notifications.",+ pluralDeliveries(health.Failed, "failed delivery", "failed deliveries"),+ pluralDeliveries(health.DeadLetter, "dead-lettered delivery", "dead-lettered deliveries"),+ )+ case health.DeadLetter > 0:+ return fmt.Sprintf(+ "Alert notifications are not reaching their destinations. %s gave up after repeated failures. Check destination credentials and settings under Alerts, Notifications.",+ pluralDeliveries(health.DeadLetter, "dead-lettered delivery", "dead-lettered deliveries"),+ )+ default:+ return fmt.Sprintf(+ "Alert notifications are not reaching their destinations. %s were not delivered. Check destination credentials and settings under Alerts, Notifications.",+ pluralDeliveries(health.Failed, "failed delivery", "failed deliveries"),+ )+ }+}++func pluralDeliveries(count int, singular, plural string) string {+ if count == 1 {+ return fmt.Sprintf("%d %s", count, singular)+ }+ return fmt.Sprintf("%d %s", count, plural)+}diff --git a/internal/monitoring/system_alerts_test.go b/internal/monitoring/system_alerts_test.gonew file mode 100644index 0000000000..b6266da329--- /dev/null+++ b/internal/monitoring/system_alerts_test.go@@ -0,0 +1,107 @@+package monitoring++import (+ "strings"+ "testing"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/notifications"+)++func TestNotificationDeliveryAlertMessageNamesTheOutcome(t *testing.T) {+ cases := []struct {+ name string+ health notifications.DeliveryHealth+ want []string+ }{+ {+ name: "failed only",+ health: notifications.DeliveryHealth{+ Status: notifications.DeliveryDegraded,+ Failed: 4,+ },+ want: []string{"4 failed deliveries", "not reaching their destinations"},+ },+ {+ name: "dead lettered only",+ health: notifications.DeliveryHealth{+ Status: notifications.DeliveryDegraded,+ DeadLetter: 1,+ },+ want: []string{"1 dead-lettered delivery", "gave up after repeated failures"},+ },+ {+ name: "both",+ health: notifications.DeliveryHealth{+ Status: notifications.DeliveryDegraded,+ Failed: 2,+ DeadLetter: 3,+ },+ want: []string{"2 failed deliveries", "3 dead-lettered deliveries"},+ },+ {+ name: "unavailable",+ health: notifications.DeliveryHealth{Status: notifications.DeliveryUnavailable},+ want: []string{"cannot read the notification queue"},+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ message := notificationDeliveryAlertMessage(tc.health)+ for _, want := range tc.want {+ if !strings.Contains(message, want) {+ t.Errorf("message %q does not contain %q", message, want)+ }+ }+ // The operator reading this has not received a notification about+ // it, so the message must say where to go.+ if tc.health.Status == notifications.DeliveryDegraded &&+ !strings.Contains(message, "Alerts, Notifications") {+ t.Errorf("message %q does not point at the destinations surface", message)+ }+ })+ }+}++func TestNotificationDeliveryAlertMessageSingularises(t *testing.T) {+ message := notificationDeliveryAlertMessage(notifications.DeliveryHealth{+ Status: notifications.DeliveryDegraded,+ Failed: 1,+ })++ if !strings.Contains(message, "1 failed delivery ") {+ t.Errorf("expected a singular delivery in %q", message)+ }+}++func TestEvaluateNotificationDeliveryThrottles(t *testing.T) {+ // The poll ticker runs on the polling cadence, which can be seconds, and+ // reading queue health costs a SQLite query. A nil notification manager+ // means the evaluation returns early, but the throttle stamp must still be+ // taken so the interval is honoured.+ m := &Monitor{}++ start := time.Now()+ m.evaluateNotificationDelivery(start)+ firstStamp := m.lastDeliveryHealthCheck+ if firstStamp.IsZero() {+ t.Fatal("expected the first evaluation to record a check time")+ }++ m.evaluateNotificationDelivery(start.Add(notificationDeliveryCheckInterval / 2))+ if !m.lastDeliveryHealthCheck.Equal(firstStamp) {+ t.Error("expected an evaluation inside the interval to be skipped")+ }++ due := start.Add(notificationDeliveryCheckInterval + time.Second)+ m.evaluateNotificationDelivery(due)+ if !m.lastDeliveryHealthCheck.Equal(due) {+ t.Error("expected an evaluation past the interval to run")+ }+}++func TestEvaluateNotificationDeliveryIsSafeWithoutAMonitor(t *testing.T) {+ var m *Monitor+ m.evaluateNotificationDelivery(time.Now())+}diff --git a/internal/notifications/delivery_health.go b/internal/notifications/delivery_health.gonew file mode 100644index 0000000000..4718bd0402--- /dev/null+++ b/internal/notifications/delivery_health.go@@ -0,0 +1,92 @@+package notifications++// Delivery health is the queue's own verdict on whether configured+// destinations are reaching anyone. It lives here, next to the queue that+// produces the counts, so the API surface and the monitoring loop that raises+// the notification-delivery system alert share one rule instead of each+// carrying their own copy of it.++// DeliveryHealthStatus is the coarse verdict callers act on.+type DeliveryHealthStatus string++const (+ // DeliveryHealthy means no terminal delivery failure is retained.+ DeliveryHealthy DeliveryHealthStatus = "healthy"+ // DeliveryDegraded means retained failed or dead-lettered deliveries exist.+ DeliveryDegraded DeliveryHealthStatus = "degraded"+ // DeliveryUnavailable means the queue could not report, so delivery cannot+ // be vouched for either way.+ DeliveryUnavailable DeliveryHealthStatus = "unavailable"+)++const (+ reasonRetainedFailedDeliveries = "retained_failed_deliveries"+ reasonRetainedDeadLetterDeliveries = "retained_dead_letter_deliveries"+ reasonQueueStatsUnavailable = "queue_stats_unavailable"+)++// DeliveryHealth is a content-free view of delivery outcomes. It carries no+// destination, alert, or recipient identity.+type DeliveryHealth struct {+ Status DeliveryHealthStatus+ Healthy bool+ AttentionRequired int+ ReasonCodes []string+ Failed int+ DeadLetter int+}++// ClassifyQueueHealth turns raw queue counts into the delivery verdict.+// Recoverable retry attempts deliberately do not count: only outcomes that+// have reached a terminal failed or dead-letter state mean something was not+// delivered.+func ClassifyQueueHealth(stats map[string]int) DeliveryHealth {+ failed := stats[string(QueueStatusFailed)]+ deadLetter := stats[string(QueueStatusDLQ)]++ reasonCodes := make([]string, 0, 2)+ if failed > 0 {+ reasonCodes = append(reasonCodes, reasonRetainedFailedDeliveries)+ }+ if deadLetter > 0 {+ reasonCodes = append(reasonCodes, reasonRetainedDeadLetterDeliveries)+ }++ attentionRequired := failed + deadLetter+ health := DeliveryHealth{+ Healthy: attentionRequired == 0,+ AttentionRequired: attentionRequired,+ ReasonCodes: reasonCodes,+ Failed: failed,+ DeadLetter: deadLetter,+ }+ if health.Healthy {+ health.Status = DeliveryHealthy+ } else {+ health.Status = DeliveryDegraded+ }+ return health+}++// UnavailableDeliveryHealth is the verdict when the queue cannot be read.+func UnavailableDeliveryHealth() DeliveryHealth {+ return DeliveryHealth{+ Status: DeliveryUnavailable,+ Healthy: false,+ ReasonCodes: []string{reasonQueueStatsUnavailable},+ }+}++// DeliveryHealth reports the queue's current delivery verdict. A queue that+// cannot be read is reported as unavailable rather than healthy, because the+// whole point of this signal is that silence must not read as success.+func (n *NotificationManager) DeliveryHealth() DeliveryHealth {+ if n == nil {+ return UnavailableDeliveryHealth()+ }+ stats, err := n.GetQueueStats()+ if err != nil || stats == nil {+ return UnavailableDeliveryHealth()+ }+ return ClassifyQueueHealth(stats)+}diff --git a/internal/notifications/delivery_health_test.go b/internal/notifications/delivery_health_test.gonew file mode 100644index 0000000000..ea74ab7fa7--- /dev/null+++ b/internal/notifications/delivery_health_test.go@@ -0,0 +1,74 @@+package notifications++import "testing"++func TestClassifyQueueHealthCountsOnlyTerminalOutcomes(t *testing.T) {+ // Pending and sending entries are work in progress, and retries are+ // expected. Treating them as unhealthy would fire on every transient blip.+ health := ClassifyQueueHealth(map[string]int{+ string(QueueStatusPending): 12,+ string(QueueStatusSending): 3,+ string(QueueStatusSent): 100,+ })++ if !health.Healthy {+ t.Error("expected in-flight work alone to stay healthy")+ }+ if health.Status != DeliveryHealthy {+ t.Errorf("Status = %q, want %q", health.Status, DeliveryHealthy)+ }+ if health.AttentionRequired != 0 {+ t.Errorf("AttentionRequired = %d, want 0", health.AttentionRequired)+ }+ if len(health.ReasonCodes) != 0 {+ t.Errorf("ReasonCodes = %v, want none", health.ReasonCodes)+ }+}++func TestClassifyQueueHealthFlagsRetainedFailures(t *testing.T) {+ health := ClassifyQueueHealth(map[string]int{+ string(QueueStatusFailed): 7,+ string(QueueStatusDLQ): 2,+ string(QueueStatusSent): 1,+ })++ if health.Healthy {+ t.Error("expected retained terminal failures to be unhealthy")+ }+ if health.Status != DeliveryDegraded {+ t.Errorf("Status = %q, want %q", health.Status, DeliveryDegraded)+ }+ if health.AttentionRequired != 9 {+ t.Errorf("AttentionRequired = %d, want 9", health.AttentionRequired)+ }+ if health.Failed != 7 || health.DeadLetter != 2 {+ t.Errorf("Failed/DeadLetter = %d/%d, want 7/2", health.Failed, health.DeadLetter)+ }+ if len(health.ReasonCodes) != 2 {+ t.Errorf("ReasonCodes = %v, want both retained-failure reasons", health.ReasonCodes)+ }+}++func TestUnavailableDeliveryHealthIsNotHealthy(t *testing.T) {+ // A queue that cannot be read must not read as success. The entire point of+ // this signal is that silence is the failure mode being guarded against.+ health := UnavailableDeliveryHealth()++ if health.Healthy {+ t.Error("expected an unreadable queue to be treated as not healthy")+ }+ if health.Status != DeliveryUnavailable {+ t.Errorf("Status = %q, want %q", health.Status, DeliveryUnavailable)+ }+ if len(health.ReasonCodes) != 1 || health.ReasonCodes[0] != reasonQueueStatsUnavailable {+ t.Errorf("ReasonCodes = %v, want %q", health.ReasonCodes, reasonQueueStatsUnavailable)+ }+}++func TestDeliveryHealthOnNilManagerIsUnavailable(t *testing.T) {+ var manager *NotificationManager++ if health := manager.DeliveryHealth(); health.Status != DeliveryUnavailable {+ t.Errorf("Status = %q, want %q", health.Status, DeliveryUnavailable)+ }+}