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): bulk delivery diagnosis for all active alerts
rcourtman515aa319e8c6
diff --git a/docs/API.md b/docs/API.mdindex ca8aa29cab..8d8784e20b 100644--- a/docs/API.md+++ b/docs/API.md@@ -617,7 +617,7 @@ Alert configuration and history (requires `monitoring:read`/`monitoring:write`).- `PUT /api/alerts/config`- `POST /api/alerts/activate`- `GET /api/alerts/active`-- `GET /api/alerts/delivery-diagnosis?alertIdentifier=<alert-id>`+- `GET /api/alerts/delivery-diagnosis?alertIdentifier=<alert-id>` (omit `alertIdentifier` to get the diagnosis array for every active alert)- `GET /api/alerts/history`- `DELETE /api/alerts/history`- `GET /api/alerts/incidents`diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.goindex 7dc94d012b..46a6bfa27d 100644--- a/internal/alerts/alerts_test.go+++ b/internal/alerts/alerts_test.go@@ -19713,6 +19713,54 @@ func TestDiagnoseAlertDeliverySuppressesCooldown(t *testing.T) {}}+func TestDiagnoseActiveAlertDeliveriesCoversEveryActiveAlert(t *testing.T) {+ manager, now := newDeliveryDiagnosisManager(t)+ ready := addDeliveryDiagnosisAlert(manager, &Alert{+ ID: "alert-bulk-ready",+ Type: "cpu",+ Level: AlertLevelWarning,+ ResourceID: "node-1",+ ResourceName: "node-1",+ StartTime: now.Add(-10 * time.Minute),+ })+ acked := addDeliveryDiagnosisAlert(manager, &Alert{+ ID: "alert-bulk-acked",+ Type: "memory",+ Level: AlertLevelCritical,+ ResourceID: "node-2",+ ResourceName: "node-2",+ StartTime: now.Add(-10 * time.Minute),+ Acknowledged: true,+ })++ diagnoses := manager.DiagnoseActiveAlertDeliveries()+ if len(diagnoses) != 2 {+ t.Fatalf("len(diagnoses) = %d, want 2", len(diagnoses))+ }++ byID := make(map[string]AlertDeliveryDiagnosis, len(diagnoses))+ for _, diagnosis := range diagnoses {+ if diagnosis.AlertIdentifier != diagnosis.AlertID {+ t.Fatalf("AlertIdentifier = %q, want canonical alert ID %q", diagnosis.AlertIdentifier, diagnosis.AlertID)+ }+ byID[diagnosis.AlertID] = diagnosis+ }+ if got := byID[ready.ID]; got.Status != AlertDeliveryStatusWouldSend || got.Reason != AlertDeliveryReasonReady {+ t.Fatalf("ready alert diagnosis = %q/%q, want %q/%q", got.Status, got.Reason, AlertDeliveryStatusWouldSend, AlertDeliveryReasonReady)+ }+ if got := byID[acked.ID]; got.Status != AlertDeliveryStatusSuppressed || got.Reason != AlertDeliveryReasonAcknowledged {+ t.Fatalf("acked alert diagnosis = %q/%q, want %q/%q", got.Status, got.Reason, AlertDeliveryStatusSuppressed, AlertDeliveryReasonAcknowledged)+ }++ single, ok := manager.DiagnoseAlertDelivery(ready.ID)+ if !ok {+ t.Fatal("expected single-alert diagnosis to keep working")+ }+ if single.Status != byID[ready.ID].Status || single.Reason != byID[ready.ID].Reason {+ t.Fatalf("single diagnosis %q/%q diverged from bulk %q/%q", single.Status, single.Reason, byID[ready.ID].Status, byID[ready.ID].Reason)+ }+}+func TestDiagnoseAlertDeliverySuppressesRateLimitWithoutMutating(t *testing.T) {manager, now := newDeliveryDiagnosisManager(t)cfg := manager.GetConfig()diff --git a/internal/alerts/notification_policy.go b/internal/alerts/notification_policy.goindex 831d0dd722..a0f962f8fc 100644--- a/internal/alerts/notification_policy.go+++ b/internal/alerts/notification_policy.go@@ -1,6 +1,7 @@package alertsimport (+ "sort""strings""time"@@ -679,6 +680,42 @@ func (m *Manager) DiagnoseAlertDelivery(alertIdentifier string) (AlertDeliveryDireturn diagnosis, false}+ resolved := m.diagnoseActiveAlertLocked(alert)+ resolved.AlertIdentifier = diagnosis.AlertIdentifier+ return resolved, true+}++// DiagnoseActiveAlertDeliveries reports the delivery policy outcome for every+// active alert in one pass, with AlertIdentifier set to the canonical alert+// ID. Like DiagnoseAlertDelivery it is read-only: it sends nothing and+// advances no delivery tracking state.+func (m *Manager) DiagnoseActiveAlertDeliveries() []AlertDeliveryDiagnosis {+ if m == nil {+ return nil+ }++ m.mu.Lock()+ defer m.mu.Unlock()++ diagnoses := make([]AlertDeliveryDiagnosis, 0, len(m.activeAlerts))+ for _, alert := range m.activeAlerts {+ if alert == nil {+ continue+ }+ diagnosis := m.diagnoseActiveAlertLocked(alert)+ diagnosis.AlertIdentifier = alert.ID+ diagnoses = append(diagnoses, diagnosis)+ }+ sort.Slice(diagnoses, func(i, j int) bool {+ return diagnoses[i].AlertID < diagnoses[j].AlertID+ })+ return diagnoses+}++// diagnoseActiveAlertLocked computes the delivery diagnosis for one active+// alert. Caller MUST hold m.mu.+func (m *Manager) diagnoseActiveAlertLocked(alert *Alert) AlertDeliveryDiagnosis {+ var diagnosis AlertDeliveryDiagnosisnow := m.policyNow()trackingKey := canonicalTrackingKeyForAlert(alert)diagnosis.AlertID = alert.ID@@ -748,7 +785,7 @@ func (m *Manager) DiagnoseAlertDelivery(alertIdentifier string) (AlertDeliveryDidiagnosis.Message = "Alert delivery is currently eligible for notification delivery."}- return diagnosis, true+ return diagnosis}func (d *AlertDeliveryDiagnosis) setSuppressed(reason, message string) {diff --git a/internal/api/alerting/alerts.go b/internal/api/alerting/alerts.goindex 57b6143488..af4f113a37 100644--- a/internal/api/alerting/alerts.go+++ b/internal/api/alerting/alerts.go@@ -32,6 +32,7 @@ type AlertManager interface {UpdateConfig(alerts.AlertConfig)GetActiveAlerts() []alerts.AlertDiagnoseAlertDelivery(alertIdentifier string) (alerts.AlertDeliveryDiagnosis, bool)+ DiagnoseActiveAlertDeliveries() []alerts.AlertDeliveryDiagnosisNotifyExistingAlert(id string)ClearAlertHistory() errorUnacknowledgeAlert(id string) error@@ -420,8 +421,11 @@ func (h *AlertHandlers) PreviewAlertIntentPolicy(w http.ResponseWriter, r *http.}}-// GetAlertDeliveryDiagnosis explains current notification delivery policy for-// one active alert without sending a notification or mutating delivery state.+// GetAlertDeliveryDiagnosis explains current notification delivery policy+// without sending a notification or mutating delivery state. With an+// alertIdentifier query parameter it returns one diagnosis object; without+// one it returns the diagnosis array for every active alert in a single+// pass so list surfaces do not need a request per alert.func (h *AlertHandlers) GetAlertDeliveryDiagnosis(w http.ResponseWriter, r *http.Request) {if r.Method != http.MethodGet {http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)@@ -432,11 +436,7 @@ func (h *AlertHandlers) GetAlertDeliveryDiagnosis(w http.ResponseWriter, r *httpif alertIdentifier == "" {alertIdentifier = strings.TrimSpace(r.URL.Query().Get("id"))}- if alertIdentifier == "" {- http.Error(w, "alertIdentifier is required", http.StatusBadRequest)- return- }- if !validateAlertIdentifier(alertIdentifier) {+ if alertIdentifier != "" && !validateAlertIdentifier(alertIdentifier) {http.Error(w, "Invalid alert identifier", http.StatusBadRequest)return}@@ -453,6 +453,17 @@ func (h *AlertHandlers) GetAlertDeliveryDiagnosis(w http.ResponseWriter, r *httpreturn}+ if alertIdentifier == "" {+ diagnoses := manager.DiagnoseActiveAlertDeliveries()+ if diagnoses == nil {+ diagnoses = []alerts.AlertDeliveryDiagnosis{}+ }+ if err := utils.WriteJSONResponse(w, diagnoses); err != nil {+ log.Error().Err(err).Msg("Failed to write alert delivery diagnoses response")+ }+ return+ }+diagnosis, exists := manager.DiagnoseAlertDelivery(alertIdentifier)if !exists {http.Error(w, "alert not found", http.StatusNotFound)diff --git a/internal/api/alerting/alerts_test.go b/internal/api/alerting/alerts_test.goindex cf47405e9f..0e2ae5bb5f 100644--- a/internal/api/alerting/alerts_test.go+++ b/internal/api/alerting/alerts_test.go@@ -80,6 +80,11 @@ func (m *MockAlertManager) DiagnoseAlertDelivery(alertIdentifier string) (alertsreturn args.Get(0).(alerts.AlertDeliveryDiagnosis), args.Bool(1)}+func (m *MockAlertManager) DiagnoseActiveAlertDeliveries() []alerts.AlertDeliveryDiagnosis {+ args := m.Called()+ return args.Get(0).([]alerts.AlertDeliveryDiagnosis)+}+func (m *MockAlertManager) NotifyExistingAlert(id string) {m.Called(id)}@@ -337,16 +342,59 @@ func TestGetAlertDeliveryDiagnosis(t *testing.T) {assert.Equal(t, expected.TrackingKey, resp.TrackingKey)}-func TestGetAlertDeliveryDiagnosisRejectsMissingIdentifier(t *testing.T) {- h := NewAlertHandlers(nil, new(MockAlertMonitor), nil)+func TestGetAlertDeliveryDiagnosisWithoutIdentifierReturnsAllActive(t *testing.T) {+ mockMonitor := new(MockAlertMonitor)+ mockManager := new(MockAlertManager)+ mockMonitor.On("GetAlertManager").Return(mockManager)++ expected := []alerts.AlertDeliveryDiagnosis{+ {+ AlertIdentifier: "a1",+ AlertID: "a1",+ Status: alerts.AlertDeliveryStatusWouldSend,+ Reason: alerts.AlertDeliveryReasonReady,+ },+ {+ AlertIdentifier: "a2",+ AlertID: "a2",+ Status: alerts.AlertDeliveryStatusSuppressed,+ Reason: alerts.AlertDeliveryReasonCooldown,+ },+ }+ mockManager.On("DiagnoseActiveAlertDeliveries").Return(expected)++ h := NewAlertHandlers(nil, mockMonitor, nil)++ req := httptest.NewRequest(http.MethodGet, "/api/alerts/delivery-diagnosis", nil)+ w := httptest.NewRecorder()++ h.GetAlertDeliveryDiagnosis(w, req)++ assert.Equal(t, http.StatusOK, w.Code)+ var resp []alerts.AlertDeliveryDiagnosis+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ assert.Len(t, resp, 2)+ assert.Equal(t, expected[0].AlertIdentifier, resp[0].AlertIdentifier)+ assert.Equal(t, expected[1].Reason, resp[1].Reason)+}++func TestGetAlertDeliveryDiagnosisWithoutIdentifierWritesEmptyArray(t *testing.T) {+ mockMonitor := new(MockAlertMonitor)+ mockManager := new(MockAlertManager)+ mockMonitor.On("GetAlertManager").Return(mockManager)+ mockManager.On("DiagnoseActiveAlertDeliveries").Return([]alerts.AlertDeliveryDiagnosis(nil))++ h := NewAlertHandlers(nil, mockMonitor, nil)req := httptest.NewRequest(http.MethodGet, "/api/alerts/delivery-diagnosis", nil)w := httptest.NewRecorder()h.GetAlertDeliveryDiagnosis(w, req)- assert.Equal(t, http.StatusBadRequest, w.Code)- assert.Contains(t, w.Body.String(), "alertIdentifier is required")+ assert.Equal(t, http.StatusOK, w.Code)+ assert.Equal(t, "[]", strings.TrimSpace(w.Body.String()))}func TestGetAlertDeliveryDiagnosisNotFound(t *testing.T) {