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.

Add connection-degraded alert for wedged platform connections

rcourtman5fd05efa83ec
diff --git a/internal/alerts/connection.go b/internal/alerts/connection.go
new file mode 100644
index 0000000000..33a1411a13
--- /dev/null
+++ b/internal/alerts/connection.go
@@ -0,0 +1,254 @@
+package alerts
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+// ConnectionState mirrors api.ConnectionState as a free-standing string so the
+// alerts package can react to derived connection state without importing the
+// api package (which would create a cycle through api → monitoring → alerts).
+// Values stay in lockstep with api.ConnectionState by convention; the
+// connections_aggregator translator is the single producer.
+type ConnectionState string
+
+const (
+ ConnectionStateActive ConnectionState = "active"
+ ConnectionStateStale ConnectionState = "stale"
+ ConnectionStateUnreachable ConnectionState = "unreachable"
+ ConnectionStateUnauthorized ConnectionState = "unauthorized"
+ ConnectionStatePaused ConnectionState = "paused"
+ ConnectionStatePending ConnectionState = "pending"
+)
+
+// ConnectionType narrows the set of connections that participate in the
+// connection-degraded alert. Agent, availability, docker, and kubernetes
+// connections have their own dedicated alert lifecycles, so the aggregator
+// must omit them when handing snapshots to CheckConnection.
+type ConnectionType string
+
+const (
+ ConnectionTypePVE ConnectionType = "pve"
+ ConnectionTypePBS ConnectionType = "pbs"
+ ConnectionTypePMG ConnectionType = "pmg"
+ ConnectionTypeVMware ConnectionType = "vmware"
+ ConnectionTypeTrueNAS ConnectionType = "truenas"
+)
+
+// ConnectionErrorSnapshot mirrors the api.ConnectionError shape that the
+// aggregator computes per target. Only the fields used in alert metadata are
+// carried.
+type ConnectionErrorSnapshot struct {
+ At time.Time
+ Message string
+ Category string
+}
+
+// ConnectionSnapshot is the alerts-side view of one unified connection row.
+// The api package's aggregator translates each platform api.Connection into
+// this shape before invoking CheckConnection so alerts does not depend on
+// api.
+type ConnectionSnapshot struct {
+ ID string
+ Name string
+ Type ConnectionType
+ State ConnectionState
+ StateReason string
+ Enabled bool
+ LastSeen *time.Time
+ LastError *ConnectionErrorSnapshot
+}
+
+// connectionDegradedAlertType is the alert.Type emitted for connection-degraded
+// alerts. Surfacing this as a constant keeps notification routing and history
+// indexing in lockstep with the producer.
+const connectionDegradedAlertType = "connection-degraded"
+
+// connectionDegradedStateKey is the DiscreteState spec stateKey for the
+// connection-degraded canonical alert. The full state-ID derived by
+// canonicalDiscreteStateStateID becomes "<connectionID>-<connectionDegradedStateKey>".
+const connectionDegradedStateKey = "connection-degraded"
+
+func isPlatformConnectionType(t ConnectionType) bool {
+ switch t {
+ case ConnectionTypePVE, ConnectionTypePBS, ConnectionTypePMG, ConnectionTypeVMware, ConnectionTypeTrueNAS:
+ return true
+ default:
+ return false
+ }
+}
+
+// CheckConnection raises or clears the connection-degraded alert for one
+// platform connection. Severity scales with observed state: stale → warning,
+// unreachable / unauthorized → critical. State=active runs through the
+// recovery-confirmation gate before resolving. Paused, disabled, and
+// non-platform connections are skipped.
+func (m *Manager) CheckConnection(snap ConnectionSnapshot) {
+ if !isPlatformConnectionType(snap.Type) {
+ return
+ }
+ if strings.TrimSpace(snap.ID) == "" {
+ return
+ }
+ if !snap.Enabled || snap.State == ConnectionStatePaused {
+ m.clearConnectionDegradedAlert(snap)
+ return
+ }
+
+ switch snap.State {
+ case ConnectionStateActive:
+ m.clearConnectionDegradedAlert(snap)
+ return
+ case ConnectionStateStale, ConnectionStateUnreachable, ConnectionStateUnauthorized:
+ // fall through and fire
+ default:
+ // pending/unknown — no alert, but reset the consecutive count so a
+ // later degraded run starts from zero instead of accumulating across
+ // a transient pending blip.
+ m.mu.Lock()
+ delete(m.connectionDegradedCount, snap.ID)
+ m.mu.Unlock()
+ return
+ }
+
+ severity := AlertLevelWarning
+ if snap.State == ConnectionStateUnreachable || snap.State == ConnectionStateUnauthorized {
+ severity = AlertLevelCritical
+ }
+
+ // Another degraded observation invalidates any in-flight recovery
+ // confirmations — recovery must build back up from zero.
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+ m.mu.Lock()
+ delete(m.offlineRecoveryConfirmations, alertID)
+ m.mu.Unlock()
+
+ spec, err := buildCanonicalDiscreteStateSpec(
+ snap.ID,
+ snap.Name,
+ unifiedresources.ResourceType("connection"),
+ severity,
+ 3,
+ false,
+ connectionDegradedStateKey,
+ []string{
+ string(ConnectionStateStale),
+ string(ConnectionStateUnreachable),
+ string(ConnectionStateUnauthorized),
+ },
+ )
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("connection", snap.Name).
+ Str("connectionID", snap.ID).
+ Msg("Skipping invalid canonical connection-degraded spec")
+ return
+ }
+
+ reason := strings.TrimSpace(snap.StateReason)
+ message := fmt.Sprintf("Connection '%s' is %s", snap.Name, snap.State)
+ if reason != "" {
+ message = fmt.Sprintf("%s: %s", message, reason)
+ }
+
+ metadata := map[string]interface{}{
+ "resourceType": "connection",
+ "connectionType": string(snap.Type),
+ "state": string(snap.State),
+ }
+ if reason != "" {
+ metadata["stateReason"] = reason
+ }
+ if snap.LastSeen != nil {
+ metadata["lastSeen"] = snap.LastSeen.UTC()
+ }
+ if snap.LastError != nil && strings.TrimSpace(snap.LastError.Message) != "" {
+ metadata["lastError"] = snap.LastError.Message
+ if !snap.LastError.At.IsZero() {
+ metadata["lastErrorAt"] = snap.LastError.At.UTC()
+ }
+ if snap.LastError.Category != "" {
+ metadata["lastErrorCategory"] = snap.LastError.Category
+ }
+ }
+
+ _, _ = m.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
+ Spec: spec,
+ Evidence: alertspecs.AlertEvidence{
+ ObservedAt: time.Now(),
+ DiscreteState: &alertspecs.DiscreteStateEvidence{
+ StateKey: connectionDegradedStateKey,
+ Observed: string(snap.State),
+ },
+ },
+ Tracking: m.connectionDegradedCount,
+ TrackingKey: snap.ID,
+ AlertID: alertID,
+ AlertType: connectionDegradedAlertType,
+ ResourceID: snap.ID,
+ ResourceName: snap.Name,
+ Instance: snap.Name,
+ Message: message,
+ Metadata: metadata,
+ AddToRecent: true,
+ AddToHistory: true,
+ RateLimit: true,
+ DispatchAsync: false,
+ })
+}
+
+// clearConnectionDegradedAlert resolves an active connection-degraded alert
+// after enough consecutive healthy observations to confirm recovery. Mirrors
+// clearNodeOfflineAlert so a single flap back to active does not silently
+// resolve a real outage. Callers hold no manager locks.
+func (m *Manager) clearConnectionDegradedAlert(snap ConnectionSnapshot) {
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ if m.connectionDegradedCount[snap.ID] > 0 {
+ log.Debug().
+ Str("connection", snap.Name).
+ Int("previousCount", m.connectionDegradedCount[snap.ID]).
+ Msg("Connection healthy, resetting degraded count")
+ delete(m.connectionDegradedCount, snap.ID)
+ }
+
+ alert, exists := m.getActiveAlertNoLock(alertID)
+ if !exists {
+ delete(m.offlineRecoveryConfirmations, alertID)
+ return
+ }
+
+ recoveryCount, confirmed := m.confirmOfflineRecoveryNoLock(alertID, offlineRecoveryConfirmationsDefault)
+ if !confirmed {
+ log.Debug().
+ Str("connection", snap.Name).
+ Int("confirmations", recoveryCount).
+ Int("required", offlineRecoveryConfirmationsDefault).
+ Msg("Connection appears healthy, waiting for recovery confirmation")
+ return
+ }
+
+ m.removeActiveAlertNoLock(alertID)
+
+ resolvedAlert := &ResolvedAlert{
+ Alert: alert,
+ ResolvedTime: time.Now(),
+ }
+ m.addRecentlyResolvedWithPrimaryLock(resolvedAlert)
+ m.safeCallResolvedAlertCallback(alert, alertID, true)
+
+ log.Info().
+ Str("connection", snap.Name).
+ Str("connectionID", snap.ID).
+ Dur("downtime", time.Since(alert.StartTime)).
+ Msg("Connection back to active")
+}
diff --git a/internal/alerts/connection_test.go b/internal/alerts/connection_test.go
new file mode 100644
index 0000000000..7103aeb23f
--- /dev/null
+++ b/internal/alerts/connection_test.go
@@ -0,0 +1,286 @@
+package alerts
+
+import (
+ "testing"
+ "time"
+)
+
+// platformConnectionSnapshot is a small helper that produces a baseline
+// ConnectionSnapshot for a pve connection so test cases can override one
+// field at a time without restating the boilerplate.
+func platformConnectionSnapshot(id, name string, state ConnectionState) ConnectionSnapshot {
+ return ConnectionSnapshot{
+ ID: id,
+ Name: name,
+ Type: ConnectionTypePVE,
+ State: state,
+ Enabled: true,
+ }
+}
+
+func TestCheckConnection(t *testing.T) {
+ t.Run("active state never fires", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-1", "Delly PVE", ConnectionStateActive)
+
+ for i := 0; i < 5; i++ {
+ m.CheckConnection(snap)
+ }
+
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected no alert for active connection")
+ }
+ m.mu.RLock()
+ count := m.connectionDegradedCount[snap.ID]
+ m.mu.RUnlock()
+ if count != 0 {
+ t.Errorf("expected degraded count 0, got %d", count)
+ }
+ })
+
+ t.Run("three consecutive stale observations fire a warning", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-stale", "Delly PVE", ConnectionStateStale)
+ snap.StateReason = "no successful poll in 5m"
+
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+
+ m.CheckConnection(snap)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected no alert after 1 stale observation")
+ }
+ m.CheckConnection(snap)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected no alert after 2 stale observations")
+ }
+ m.CheckConnection(snap)
+
+ alert := testRequireActiveAlert(t, m, alertID)
+ if alert.Level != AlertLevelWarning {
+ t.Errorf("expected warning level for stale, got %s", alert.Level)
+ }
+ if alert.Type != connectionDegradedAlertType {
+ t.Errorf("expected alert type %s, got %s", connectionDegradedAlertType, alert.Type)
+ }
+ if alert.ResourceID != snap.ID {
+ t.Errorf("expected resourceID %s, got %s", snap.ID, alert.ResourceID)
+ }
+ if got, _ := alert.Metadata["connectionType"].(string); got != string(ConnectionTypePVE) {
+ t.Errorf("expected connectionType=pve in metadata, got %q", got)
+ }
+ if got, _ := alert.Metadata["state"].(string); got != string(ConnectionStateStale) {
+ t.Errorf("expected state=stale in metadata, got %q", got)
+ }
+ })
+
+ t.Run("unreachable escalates an already-firing warning to critical", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-esc", "Delly PVE", ConnectionStateStale)
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+
+ // Build up to a firing warning first.
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ warningAlert := testRequireActiveAlert(t, m, alertID)
+ if warningAlert.Level != AlertLevelWarning {
+ t.Fatalf("expected warning alert before escalation, got %s", warningAlert.Level)
+ }
+
+ // Now the connection goes fully unreachable.
+ snap.State = ConnectionStateUnreachable
+ snap.StateReason = "context deadline exceeded"
+ m.CheckConnection(snap)
+
+ escalated := testRequireActiveAlert(t, m, alertID)
+ if escalated.Level != AlertLevelCritical {
+ t.Errorf("expected critical level after escalation, got %s", escalated.Level)
+ }
+ if got, _ := escalated.Metadata["state"].(string); got != string(ConnectionStateUnreachable) {
+ t.Errorf("expected state=unreachable in metadata, got %q", got)
+ }
+ })
+
+ t.Run("unauthorized fires critical from cold start", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-auth", "Delly PVE", ConnectionStateUnauthorized)
+ snap.StateReason = "invalid api key"
+
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+
+ alert := testRequireActiveAlert(t, m, alertID)
+ if alert.Level != AlertLevelCritical {
+ t.Errorf("expected critical level for unauthorized, got %s", alert.Level)
+ }
+ })
+
+ t.Run("paused connection never fires", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-paused", "Delly PVE", ConnectionStatePaused)
+
+ for i := 0; i < 5; i++ {
+ m.CheckConnection(snap)
+ }
+
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected no alert for paused connection")
+ }
+ })
+
+ t.Run("disabled connection never fires even when unreachable", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-disabled", "Delly PVE", ConnectionStateUnreachable)
+ snap.Enabled = false
+
+ for i := 0; i < 5; i++ {
+ m.CheckConnection(snap)
+ }
+
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected no alert for disabled connection")
+ }
+ })
+
+ t.Run("agent connection is dropped before reaching the alert path", func(t *testing.T) {
+ m := newTestManager(t)
+ // Synthesize a non-platform snapshot directly — agents and
+ // availability targets never reach CheckConnection in production
+ // because the aggregator drops them, but a defense-in-depth test
+ // here guards the type guard.
+ snap := ConnectionSnapshot{
+ ID: "agent-1",
+ Name: "Host agent",
+ Type: ConnectionType("agent"),
+ State: ConnectionStateUnreachable,
+ Enabled: true,
+ }
+
+ for i := 0; i < 5; i++ {
+ m.CheckConnection(snap)
+ }
+
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected no alert for non-platform connection type")
+ }
+ m.mu.RLock()
+ count := m.connectionDegradedCount[snap.ID]
+ m.mu.RUnlock()
+ if count != 0 {
+ t.Errorf("expected degraded count untouched for non-platform type, got %d", count)
+ }
+ })
+}
+
+func TestClearConnectionDegradedAlert(t *testing.T) {
+ t.Run("clears an active alert after the recovery confirmation gate", func(t *testing.T) {
+ m := newTestManager(t)
+ resolvedCh := make(chan struct{}, 1)
+ m.SetResolvedCallback(func(alertID string) {
+ resolvedCh <- struct{}{}
+ })
+
+ snap := platformConnectionSnapshot("conn-recover", "Delly PVE", ConnectionStateStale)
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+
+ // Drive the alert to firing.
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ testRequireActiveAlert(t, m, alertID)
+
+ // State returns to active — first observation does NOT clear yet
+ // because the recovery confirmation gate is 3.
+ snap.State = ConnectionStateActive
+ m.CheckConnection(snap)
+ if !testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected alert to remain active until recovery confirmations are met")
+ }
+ m.mu.RLock()
+ count1 := m.offlineRecoveryConfirmations[alertID]
+ m.mu.RUnlock()
+ if count1 != 1 {
+ t.Errorf("expected recovery confirmation 1, got %d", count1)
+ }
+
+ m.CheckConnection(snap)
+ if !testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected alert to remain active until recovery confirmations are met")
+ }
+
+ m.CheckConnection(snap)
+ if testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected alert to clear after 3 recovery confirmations")
+ }
+
+ // Confirm the resolved callback fires (handled via the safeCall path).
+ select {
+ case <-resolvedCh:
+ case <-time.After(2 * time.Second):
+ t.Fatal("expected resolved callback to fire")
+ }
+ })
+
+ t.Run("no-op when nothing was ever firing", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-quiet", "Delly PVE", ConnectionStateActive)
+
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+
+ m.mu.RLock()
+ alertCount := len(m.activeAlerts)
+ recovery := m.offlineRecoveryConfirmations[canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)]
+ m.mu.RUnlock()
+
+ if alertCount != 0 {
+ t.Errorf("expected no active alerts, got %d", alertCount)
+ }
+ if recovery != 0 {
+ t.Errorf("expected no recovery confirmations tracked, got %d", recovery)
+ }
+ })
+
+ t.Run("degraded observation resets in-flight recovery confirmations", func(t *testing.T) {
+ m := newTestManager(t)
+ snap := platformConnectionSnapshot("conn-flap", "Delly PVE", ConnectionStateStale)
+ alertID := canonicalDiscreteStateStateID(snap.ID, connectionDegradedStateKey)
+
+ // Drive to firing.
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ m.CheckConnection(snap)
+ testRequireActiveAlert(t, m, alertID)
+
+ // One healthy observation builds up a recovery confirmation.
+ snap.State = ConnectionStateActive
+ m.CheckConnection(snap)
+ m.mu.RLock()
+ recoveryBefore := m.offlineRecoveryConfirmations[alertID]
+ m.mu.RUnlock()
+ if recoveryBefore != 1 {
+ t.Fatalf("expected 1 recovery confirmation, got %d", recoveryBefore)
+ }
+
+ // A degraded blip should wipe the recovery progress so a single
+ // flap doesn't pretend the outage is healed.
+ snap.State = ConnectionStateStale
+ m.CheckConnection(snap)
+ m.mu.RLock()
+ recoveryAfter := m.offlineRecoveryConfirmations[alertID]
+ m.mu.RUnlock()
+ if recoveryAfter != 0 {
+ t.Errorf("expected recovery confirmations reset to 0, got %d", recoveryAfter)
+ }
+ if !testHasActiveAlert(t, m, alertID) {
+ t.Fatal("expected alert to stay active after flap")
+ }
+ })
+}
diff --git a/internal/alerts/manager.go b/internal/alerts/manager.go
index 59bbecf523..c52137ff7f 100644
--- a/internal/alerts/manager.go
+++ b/internal/alerts/manager.go
@@ -46,6 +46,7 @@ type Manager struct {
pendingAlerts map[string]time.Time // Track when thresholds were first exceeded
// Offline confirmation tracking
nodeOfflineCount map[string]int // Track consecutive offline counts for nodes (legacy)
+ connectionDegradedCount map[string]int // Track consecutive degraded counts for platform connections (pve/pbs/pmg/vmware/truenas)
offlineConfirmations map[string]int // Track consecutive offline counts for all resources
offlineRecoveryConfirmations map[string]int // Track consecutive healthy confirmations before clearing poll-driven offline alerts
dockerOfflineCount map[string]int // Track consecutive offline counts for Docker hosts
@@ -122,6 +123,7 @@ func NewManagerWithDataDir(dataDir string) *Manager {
resolvedAlias: make(map[string]string),
pendingAlerts: make(map[string]time.Time),
nodeOfflineCount: make(map[string]int),
+ connectionDegradedCount: make(map[string]int),
offlineConfirmations: make(map[string]int),
offlineRecoveryConfirmations: make(map[string]int),
dockerOfflineCount: make(map[string]int),
diff --git a/internal/alerts/specs/types.go b/internal/alerts/specs/types.go
index 6aa6a9f753..14ce8fc9b2 100644
--- a/internal/alerts/specs/types.go
+++ b/internal/alerts/specs/types.go
@@ -1080,13 +1080,15 @@ func isKnownResourceType(rt unifiedresources.ResourceType) bool {
if rt == "" {
return false
}
- // "node", "agent-disk", "docker-host", "backup-subject", and "proxmox-disk" remain migration bridges while
- // live alerts are still keyed separately from the canonical unified resource model.
+ // "node", "agent-disk", "docker-host", "backup-subject", "proxmox-disk", and
+ // "connection" remain migration bridges while live alerts are still keyed
+ // separately from the canonical unified resource model.
if rt != unifiedresources.ResourceType("node") &&
rt != unifiedresources.ResourceType("agent-disk") &&
rt != unifiedresources.ResourceType("docker-host") &&
rt != unifiedresources.ResourceType("backup-subject") &&
rt != unifiedresources.ResourceType("proxmox-disk") &&
+ rt != unifiedresources.ResourceType("connection") &&
unifiedresources.CanonicalResourceType(rt) != rt {
return false
}
@@ -1097,6 +1099,7 @@ func isKnownResourceType(rt unifiedresources.ResourceType) bool {
unifiedresources.ResourceType("docker-host"),
unifiedresources.ResourceType("backup-subject"),
unifiedresources.ResourceType("proxmox-disk"),
+ unifiedresources.ResourceType("connection"),
unifiedresources.ResourceTypeVM,
unifiedresources.ResourceTypeSystemContainer,
unifiedresources.ResourceTypeAppContainer,
diff --git a/internal/alerts/specs/types_test.go b/internal/alerts/specs/types_test.go
index b28343aee2..be440738ac 100644
--- a/internal/alerts/specs/types_test.go
+++ b/internal/alerts/specs/types_test.go
@@ -339,6 +339,26 @@ func TestResourceAlertSpecValidateAllowsProxmoxDiskMigrationBridgeType(t *testin
}
}
+func TestResourceAlertSpecValidateAllowsConnectionMigrationBridgeType(t *testing.T) {
+ t.Parallel()
+
+ spec := ResourceAlertSpec{
+ ID: "pve:delly-connection-degraded",
+ ResourceID: "pve:delly",
+ ResourceType: unifiedresources.ResourceType("connection"),
+ Kind: AlertSpecKindDiscreteState,
+ Severity: AlertSeverityWarning,
+ DiscreteState: &DiscreteStateSpec{
+ StateKey: "connection-degraded",
+ TriggerStates: []string{"stale", "unreachable", "unauthorized"},
+ },
+ }
+
+ if err := spec.Validate(); err != nil {
+ t.Fatalf("Validate() error = %v", err)
+ }
+}
+
func TestResourceAlertSpecValidateRejectsNonCanonicalAlias(t *testing.T) {
t.Parallel()
diff --git a/internal/api/connections_alerts.go b/internal/api/connections_alerts.go
new file mode 100644
index 0000000000..2395171d46
--- /dev/null
+++ b/internal/api/connections_alerts.go
@@ -0,0 +1,119 @@
+package api
+
+import (
+ "context"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/alerts"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
+)
+
+// buildAggregatorInputs gathers the same inputs the HTTP connections handler
+// uses so the alerts pipeline can derive identical Connection rows without
+// going through the HTTP layer. Returning an empty aggregatorInputs when a
+// dependency is unavailable keeps the alerts loop a no-op rather than a hard
+// failure.
+func buildAggregatorInputs(ctx context.Context, cfg *config.Config, persistence *config.ConfigPersistence, monitor *monitoring.Monitor) aggregatorInputs {
+ inputs := aggregatorInputs{now: time.Now()}
+
+ if cfg != nil {
+ inputs.pveInstances = cfg.PVEInstances
+ inputs.pbsInstances = cfg.PBSInstances
+ inputs.pmgInstances = cfg.PMGInstances
+ }
+
+ if persistence != nil {
+ if vmw, err := persistence.LoadVMwareConfig(); err == nil {
+ inputs.vmwareInstances = vmw
+ }
+ if tn, err := persistence.LoadTrueNASConfig(); err == nil {
+ inputs.truenasInstances = tn
+ }
+ if availability, err := persistence.LoadAvailabilityTargets(); err == nil {
+ inputs.availabilityTargets = availability
+ }
+ }
+
+ if monitor != nil {
+ inputs.hosts = monitor.HostsSnapshot()
+ inputs.instanceHealth = instanceHealthByKey(monitor.SchedulerHealth())
+ inputs.availabilityStatuses = monitor.AvailabilityStatusSnapshot()
+ } else {
+ inputs.hosts = []models.Host{}
+ inputs.instanceHealth = map[string]monitoring.InstanceHealth{}
+ inputs.availabilityStatuses = map[string]monitoring.AvailabilityProbeStatus{}
+ }
+ if mock.IsMockEnabled() {
+ mockTargets, mockStatuses := mockAvailabilityConnectionInputs()
+ inputs.availabilityTargets = mergeAvailabilityTargets(inputs.availabilityTargets, mockTargets)
+ inputs.availabilityStatuses = mergeAvailabilityStatuses(inputs.availabilityStatuses, mockStatuses)
+ }
+ inputs.expectedAgentVersion = currentAgentTargetVersion()
+ _ = ctx
+ return inputs
+}
+
+// connectionTypeForAlerts maps the wire ConnectionType to the alerts package's
+// narrow platform set. Types that fall outside the platform set return false
+// so the caller drops the row before invoking CheckConnection.
+func connectionTypeForAlerts(t ConnectionType) (alerts.ConnectionType, bool) {
+ switch t {
+ case ConnectionTypePVE:
+ return alerts.ConnectionTypePVE, true
+ case ConnectionTypePBS:
+ return alerts.ConnectionTypePBS, true
+ case ConnectionTypePMG:
+ return alerts.ConnectionTypePMG, true
+ case ConnectionTypeVMware:
+ return alerts.ConnectionTypeVMware, true
+ case ConnectionTypeTrueNAS:
+ return alerts.ConnectionTypeTrueNAS, true
+ default:
+ return "", false
+ }
+}
+
+// snapshotConnectionsForAlerts translates the aggregator's rich Connection
+// rows into the narrow alerts.ConnectionSnapshot view. Non-platform types
+// (agent, availability, docker, kubernetes) are dropped because they have
+// their own alert lifecycles.
+func snapshotConnectionsForAlerts(connections []Connection) []alerts.ConnectionSnapshot {
+ out := make([]alerts.ConnectionSnapshot, 0, len(connections))
+ for _, conn := range connections {
+ alertType, ok := connectionTypeForAlerts(conn.Type)
+ if !ok {
+ continue
+ }
+
+ snap := alerts.ConnectionSnapshot{
+ ID: conn.ID,
+ Name: conn.Name,
+ Type: alertType,
+ State: alerts.ConnectionState(conn.State),
+ StateReason: conn.StateReason,
+ Enabled: conn.Enabled,
+ LastSeen: conn.LastSeen,
+ }
+ if conn.LastError != nil {
+ snap.LastError = &alerts.ConnectionErrorSnapshot{
+ At: conn.LastError.At,
+ Message: conn.LastError.Message,
+ Category: conn.LastError.Category,
+ }
+ }
+ out = append(out, snap)
+ }
+ return out
+}
+
+// BuildAlertConnectionSnapshots returns the platform-connection snapshots the
+// alerts package consumes for the connection-degraded check. This is the
+// monitor-loop counterpart to the HTTP connections handler — it runs the
+// same derivation but skips the JSON envelope.
+func BuildAlertConnectionSnapshots(ctx context.Context, cfg *config.Config, persistence *config.ConfigPersistence, monitor *monitoring.Monitor) []alerts.ConnectionSnapshot {
+ inputs := buildAggregatorInputs(ctx, cfg, persistence, monitor)
+ return snapshotConnectionsForAlerts(buildConnections(inputs))
+}
diff --git a/internal/api/connections_handlers.go b/internal/api/connections_handlers.go
index c540fdad3d..d90e9064bb 100644
--- a/internal/api/connections_handlers.go
+++ b/internal/api/connections_handlers.go
@@ -6,8 +6,6 @@ import (
"net/http"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
- "github.com/rcourtman/pulse-go-rewrite/internal/mock"
- "github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
)
@@ -49,41 +47,7 @@ func (h *ConnectionsHandlers) HandleList(w http.ResponseWriter, r *http.Request)
persistence := h.getPersistence(ctx)
monitor := h.getMonitor(ctx)
- inputs := aggregatorInputs{}
-
- if cfg != nil {
- inputs.pveInstances = cfg.PVEInstances
- inputs.pbsInstances = cfg.PBSInstances
- inputs.pmgInstances = cfg.PMGInstances
- }
-
- if persistence != nil {
- if vmw, err := persistence.LoadVMwareConfig(); err == nil {
- inputs.vmwareInstances = vmw
- }
- if tn, err := persistence.LoadTrueNASConfig(); err == nil {
- inputs.truenasInstances = tn
- }
- if availability, err := persistence.LoadAvailabilityTargets(); err == nil {
- inputs.availabilityTargets = availability
- }
- }
-
- if monitor != nil {
- inputs.hosts = monitor.HostsSnapshot()
- inputs.instanceHealth = instanceHealthByKey(monitor.SchedulerHealth())
- inputs.availabilityStatuses = monitor.AvailabilityStatusSnapshot()
- } else {
- inputs.hosts = []models.Host{}
- inputs.instanceHealth = map[string]monitoring.InstanceHealth{}
- inputs.availabilityStatuses = map[string]monitoring.AvailabilityProbeStatus{}
- }
- if mock.IsMockEnabled() {
- mockTargets, mockStatuses := mockAvailabilityConnectionInputs()
- inputs.availabilityTargets = mergeAvailabilityTargets(inputs.availabilityTargets, mockTargets)
- inputs.availabilityStatuses = mergeAvailabilityStatuses(inputs.availabilityStatuses, mockStatuses)
- }
- inputs.expectedAgentVersion = currentAgentTargetVersion()
+ inputs := buildAggregatorInputs(ctx, cfg, persistence, monitor)
connections := buildConnections(inputs)
writeJSON(w, http.StatusOK, ConnectionsListResponse{
diff --git a/internal/api/router.go b/internal/api/router.go
index 30d006255b..54a5907105 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -390,6 +390,19 @@ func (r *Router) setupRoutes() {
r.configHandlers.getPersistence,
r.configHandlers.getMonitor,
)
+ if r.monitor != nil {
+ // Drive the connection-degraded alert off the same aggregator the
+ // HTTP handler uses, so the active-notification stream stays in
+ // lockstep with the Settings → Infrastructure badges. Single-tenant
+ // only for now; multi-tenant per-org wiring is a follow-up.
+ getCfg := r.configHandlers.getConfig
+ getPersist := r.configHandlers.getPersistence
+ monitor := r.monitor
+ r.monitor.SetConnectionsSnapshotLister(func() []alerts.ConnectionSnapshot {
+ ctx := context.Background()
+ return BuildAlertConnectionSnapshots(ctx, getCfg(ctx), getPersist(ctx), monitor)
+ })
+ }
r.availabilityHandlers = NewAvailabilityHandlers(
r.configHandlers.getPersistence,
r.configHandlers.getMonitor,
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 91b13e19a2..43a2c5cbc9 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -931,6 +931,7 @@ type Monitor struct {
alertManager *alerts.Manager
alertResolvedAICallback func(*alerts.Alert)
alertTriggeredAICallback func(*alerts.Alert)
+ connectionsSnapshotLister func() []alerts.ConnectionSnapshot // returns platform connection snapshots for the connection-degraded check
incidentStore *memory.IncidentStore
notificationMgr *notifications.NotificationManager
configPersist *config.ConfigPersistence
@@ -1850,6 +1851,11 @@ func (m *Monitor) Start(ctx context.Context, wsHub *websocket.Hub) {
// Poll real infrastructure
go m.poll(ctx, wsHub)
}
+ // Connection-degraded alerts derive from the unified connections
+ // ledger, which lives behind the api layer. We invoke the
+ // registered lister here so a wedged PVE/PBS/PMG/VMware/TrueNAS
+ // connection escalates into the top-nav alert stream.
+ go m.checkConnectionAlerts()
case <-broadcastTicker.C:
// Broadcast current state regardless of polling status
diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.go
index e1b5283a6f..ec3228f926 100644
--- a/internal/monitoring/monitor_alerts.go
+++ b/internal/monitoring/monitor_alerts.go
@@ -47,6 +47,35 @@ func (m *Monitor) SetAlertResolvedAICallback(callback func(*alerts.Alert)) {
log.Info().Msg("alert-resolved AI callback registered")
}
+// SetConnectionsSnapshotLister registers the closure that produces platform
+// connection snapshots once per monitor poll cycle. The api layer owns the
+// closure because it owns the config + persistence inputs the aggregator
+// needs. Passing nil disables the connection-degraded check on this monitor.
+func (m *Monitor) SetConnectionsSnapshotLister(lister func() []alerts.ConnectionSnapshot) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.connectionsSnapshotLister = lister
+}
+
+// checkConnectionAlerts runs CheckConnection against every platform
+// connection snapshot the registered lister returns. Invoked from the main
+// poll tick so a wedged PVE / PBS / PMG / VMware / TrueNAS connection escalates
+// into the top-nav alert stream instead of staying behind on the Settings page.
+func (m *Monitor) checkConnectionAlerts() {
+ defer recoverFromPanic("checkConnectionAlerts")
+
+ m.mu.RLock()
+ lister := m.connectionsSnapshotLister
+ m.mu.RUnlock()
+
+ if lister == nil || m.alertManager == nil {
+ return
+ }
+ for _, snap := range lister() {
+ m.alertManager.CheckConnection(snap)
+ }
+}
+
func (m *Monitor) handleAlertFired(alert *alerts.Alert) {
if alert == nil {
return