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.

refactor: split PBS and storage alert checkers

rcourtmana0e88968931f
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 206fe731ec..b91176150f 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -58,6 +58,8 @@ operator-facing alert routing behavior for live runtime alerts.
36. `internal/alerts/read_model.go`
37. `internal/alerts/pmg.go`
38. `internal/alerts/docker.go`
+39. `internal/alerts/pbs.go`
+40. `internal/alerts/storage.go`
## Shared Boundaries
@@ -235,6 +237,16 @@ owns Docker host connectivity, container state and health, container metric
projection, service gap/update-state checks, image-update timing, and Docker
tracking cleanup; future Docker alert behavior should extend that resource
checker owner rather than expanding the central Manager file.
+PBS alert evaluation now lives in `internal/alerts/pbs.go`. That file owns PBS
+connectivity normalization, PBS metric projection, PBS metric cleanup, and PBS
+offline lifecycle handling; future PBS alert behavior should extend that
+resource checker owner rather than expanding the central Manager file.
+Storage alert evaluation now lives in `internal/alerts/storage.go`. That file
+owns storage connectivity handling, storage usage projection, ZFS pool/device
+health checks, and storage offline lifecycle handling; future storage alert
+behavior should extend that resource checker owner while shared storage-health
+assessment helpers remain package-level until host and storage health paths are
+separated cleanly.
Commercial alert handoffs now follow the same shared navigation boundary.
`frontend-modern/src/components/Alerts/InvestigateAlertButton.tsx` may resolve
the canonical `ai_alerts` destination from the shared license/commercial
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.go
index 76c09e4116..a4d2ccfa5a 100644
--- a/internal/alerts/alerts.go
+++ b/internal/alerts/alerts.go
@@ -3014,219 +3014,6 @@ func (m *Manager) syncHostUnraidStorageAlert(host models.Host, nodeName, instanc
})
}
-func isPBSOffline(pbs models.PBSInstance) bool {
- status := strings.ToLower(strings.TrimSpace(pbs.Status))
- health := strings.ToLower(strings.TrimSpace(pbs.ConnectionHealth))
- return status == "offline" || health == "error" || health == "failed" || health == "unhealthy"
-}
-
-func (m *Manager) clearPBSMetricAlerts(pbsID string) {
- if strings.TrimSpace(pbsID) == "" {
- return
- }
-
- m.clearAlert(canonicalMetricStateID(pbsID, "cpu"))
- m.clearAlert(canonicalMetricStateID(pbsID, "memory"))
-}
-
-// CheckPBS checks PBS instance metrics against thresholds
-func (m *Manager) CheckPBS(pbs models.PBSInstance) {
- m.mu.RLock()
- if !m.config.Enabled {
- m.mu.RUnlock()
- return
- }
- if m.config.DisableAllPBS {
- m.mu.RUnlock()
- // Clear any existing PBS alerts when all PBS alerts are disabled
- m.mu.Lock()
- // Reset offline confirmation tracking
- delete(m.offlineConfirmations, pbs.ID)
- // Clear CPU alert
- cpuAlertID := canonicalMetricStateID(pbs.ID, "cpu")
- if m.clearActiveAlertIfPresentNoLock(cpuAlertID) {
- log.Info().
- Str("alertID", cpuAlertID).
- Str("pbs", pbs.Name).
- Msg("Cleared CPU alert - all PBS alerts disabled")
- }
- // Clear Memory alert
- memAlertID := canonicalMetricStateID(pbs.ID, "memory")
- if m.clearActiveAlertIfPresentNoLock(memAlertID) {
- log.Info().
- Str("alertID", memAlertID).
- Str("pbs", pbs.Name).
- Msg("Cleared Memory alert - all PBS alerts disabled")
- }
- // Clear offline alert
- offlineAlertID := canonicalConnectivityStateID(pbs.ID)
- if m.clearActiveAlertIfPresentNoLock(offlineAlertID) {
- log.Info().
- Str("alertID", offlineAlertID).
- Str("pbs", pbs.Name).
- Msg("Cleared offline alert - all PBS alerts disabled")
- }
- m.mu.Unlock()
- return
- }
-
- thresholds := m.resolveResourceThresholds("pbs", pbs.ID)
- disablePBSOffline := m.config.DisableAllPBSOffline
- m.mu.RUnlock()
-
- // Check override disable BEFORE offline detection to prevent spurious notifications
- if thresholds.Disabled {
- m.mu.Lock()
- // Reset offline confirmation tracking
- delete(m.offlineConfirmations, pbs.ID)
- // Clear CPU alert
- cpuAlertID := canonicalMetricStateID(pbs.ID, "cpu")
- if m.clearActiveAlertIfPresentNoLock(cpuAlertID) {
- log.Debug().
- Str("alertID", cpuAlertID).
- Str("pbs", pbs.Name).
- Msg("Cleared CPU alert - PBS has alerts disabled")
- }
- // Clear Memory alert
- memAlertID := canonicalMetricStateID(pbs.ID, "memory")
- if m.clearActiveAlertIfPresentNoLock(memAlertID) {
- log.Debug().
- Str("alertID", memAlertID).
- Str("pbs", pbs.Name).
- Msg("Cleared Memory alert - PBS has alerts disabled")
- }
- // Clear offline alert
- offlineAlertID := canonicalConnectivityStateID(pbs.ID)
- if m.clearActiveAlertIfPresentNoLock(offlineAlertID) {
- log.Debug().
- Str("alertID", offlineAlertID).
- Str("pbs", pbs.Name).
- Msg("Cleared offline alert - PBS has alerts disabled")
- }
- m.mu.Unlock()
- return
- }
-
- pbsOffline := isPBSOffline(pbs)
-
- if disablePBSOffline || thresholds.DisableConnectivity {
- // Clear tracking and any existing offline alerts when globally disabled
- m.mu.Lock()
- delete(m.offlineConfirmations, pbs.ID)
- m.mu.Unlock()
- m.clearAlert(canonicalConnectivityStateID(pbs.ID))
- } else {
- // Check if PBS is offline first (similar to nodes)
- if pbsOffline {
- m.checkPBSOffline(pbs)
- } else {
- // Clear any existing offline alert if PBS is back online
- m.clearPBSOfflineAlert(pbs)
- }
- }
-
- // When PBS is offline/unhealthy, clear stale metric alerts immediately.
- if pbsOffline {
- m.clearPBSMetricAlerts(pbs.ID)
- return
- }
-
- m.evaluateUnifiedMetrics(&UnifiedResourceInput{
- ID: pbs.ID,
- Type: "pbs",
- Name: pbs.Name,
- Node: pbs.Host,
- Instance: pbs.Name,
- CPU: &UnifiedResourceMetric{Percent: pbs.CPU},
- Memory: &UnifiedResourceMetric{Percent: pbs.Memory},
- }, thresholds, nil)
-}
-
-// CheckStorage checks storage against thresholds
-func (m *Manager) CheckStorage(storage models.Storage) {
- m.mu.RLock()
- if !m.config.Enabled {
- m.mu.RUnlock()
- return
- }
- if m.config.DisableAllStorage {
- m.mu.RUnlock()
- // Clear any existing storage alerts when all storage alerts are disabled
- m.mu.Lock()
- usageAlertID := canonicalMetricStateID(storage.ID, "usage")
- if m.clearActiveAlertIfPresentNoLock(usageAlertID) {
- log.Info().
- Str("alertID", usageAlertID).
- Str("storage", storage.Name).
- Msg("Cleared usage alert - all storage alerts disabled")
- }
- offlineAlertID := canonicalConnectivityStateID(storage.ID)
- if m.clearActiveAlertIfPresentNoLock(offlineAlertID) {
- log.Info().
- Str("alertID", offlineAlertID).
- Str("storage", storage.Name).
- Msg("Cleared offline alert - all storage alerts disabled")
- }
- m.mu.Unlock()
- return
- }
-
- thresholds := m.resolveResourceThresholds("storage", storage.ID)
- m.mu.RUnlock()
-
- if thresholds.Disabled {
- m.mu.Lock()
- delete(m.offlineConfirmations, storage.ID)
- m.mu.Unlock()
- m.clearAlert(canonicalMetricStateID(storage.ID, "usage"))
- m.clearAlert(canonicalConnectivityStateID(storage.ID))
- return
- }
-
- // Check if storage is truly offline/unavailable (not just inactive from other nodes)
- // Note: In a cluster, local storage from other nodes shows as inactive which is normal
- if thresholds.DisableConnectivity {
- m.mu.Lock()
- delete(m.offlineConfirmations, storage.ID)
- m.mu.Unlock()
- m.clearAlert(canonicalConnectivityStateID(storage.ID))
- } else if storage.Status == "offline" || storage.Status == "unavailable" {
- m.checkStorageOffline(storage)
- } else {
- // Clear any existing offline alert if storage is back online
- m.clearStorageOfflineAlert(storage)
- }
-
- // Check usage if storage has valid data (even if not currently active on this node)
- // In clusters, storage may show as inactive on nodes where it's not currently mounted
- // but we still want to alert on high usage
- log.Debug().
- Str("storage", storage.Name).
- Str("id", storage.ID).
- Float64("usage", storage.Usage).
- Str("status", storage.Status).
- Float64("trigger", thresholds.Usage.Trigger).
- Float64("clear", thresholds.Usage.Clear).
- Msg("Checking storage thresholds")
-
- // Check usage if storage is online - checkMetric will skip if threshold is nil or <= 0
- if storage.Status != "offline" && storage.Status != "unavailable" && storage.Usage > 0 {
- m.evaluateUnifiedMetrics(&UnifiedResourceInput{
- ID: storage.ID,
- Type: "storage",
- Name: storage.Name,
- Node: storage.Node,
- Instance: storage.Instance,
- Disk: &UnifiedResourceMetric{Percent: storage.Usage},
- }, thresholds, nil)
- }
-
- // Check ZFS pool status if this is ZFS storage
- if storage.ZFSPool != nil {
- m.checkZFSPoolHealth(storage)
- }
-}
-
// BuildGuestKey constructs a unique key for a guest from instance, node, and VMID.
// Uses the canonical format: instance:node:vmid
// This matches the format used by makeGuestID in the monitoring package.
@@ -4017,157 +3804,6 @@ func parseGuestID(raw string) (instance string, node string, vmid int, ok bool)
return strings.TrimSpace(inst), strings.TrimSpace(prev), n, true
}
-// checkZFSPoolHealth checks ZFS pool for errors and degraded state
-func (m *Manager) checkZFSPoolHealth(storage models.Storage) {
- pool := storage.ZFSPool
- if pool == nil {
- return
- }
-
- poolResourceName := fmt.Sprintf("%s (%s)", storage.Name, pool.Name)
- poolAssessment := storagehealth.AssessZFSPool(*pool)
-
- // Check pool state (DEGRADED, FAULTED, etc.)
- stateAlertID := fmt.Sprintf("zfs-pool-state-%s", storage.ID)
- stateMetadata := map[string]interface{}{
- "pool_name": pool.Name,
- "pool_state": pool.State,
- }
- stateReasons := filterStorageHealthReasonsByCodes(poolAssessment.Reasons, zfsPoolAssessmentCodes)
- stateResult, _ := m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{
- SpecID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name) + "-state",
- Signal: "zfs-pool",
- Codes: zfsPoolAssessmentCodes,
- Reasons: stateReasons,
- AlertID: stateAlertID,
- AlertType: "zfs-pool-state",
- SpecResourceID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name),
- ResourceID: storage.ID,
- ResourceName: poolResourceName,
- ResourceType: unifiedresources.ResourceTypeStorage,
- Node: storage.Node,
- Instance: storage.Instance,
- Metadata: stateMetadata,
- })
- if stateResult.Transition != nil && stateResult.Transition.Kind == alertspecs.EvaluationTransitionActivated {
- log.Warn().
- Str("pool", pool.Name).
- Str("state", pool.State).
- Str("node", storage.Node).
- Msg("ZFS pool is not healthy")
- }
-
- // Check for read/write/checksum errors
- totalErrors := pool.ReadErrors + pool.WriteErrors + pool.ChecksumErrors
- errorsAlertID := fmt.Sprintf("zfs-pool-errors-%s", storage.ID)
- errorsSpecResourceID := storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name)
- errorsSpecID := errorsSpecResourceID + "-errors"
- if totalErrors > 0 {
- existingValue, exists := m.activeAlertValue(buildCanonicalStateID(errorsSpecResourceID, errorsSpecID))
- if !exists || float64(totalErrors) > existingValue {
- errorMetadata := map[string]interface{}{
- "pool_name": pool.Name,
- "read_errors": pool.ReadErrors,
- "write_errors": pool.WriteErrors,
- "checksum_errors": pool.ChecksumErrors,
- }
- errorReasons := filterStorageHealthReasonsByCodes(poolAssessment.Reasons, zfsPoolErrorAssessmentCodes)
- result, _ := m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{
- SpecID: errorsSpecID,
- Signal: "zfs-pool-errors",
- Codes: zfsPoolErrorAssessmentCodes,
- Reasons: errorReasons,
- AlertID: errorsAlertID,
- AlertType: "zfs-pool-errors",
- SpecResourceID: errorsSpecResourceID,
- ResourceID: storage.ID,
- ResourceName: poolResourceName,
- ResourceType: unifiedresources.ResourceTypeStorage,
- Node: storage.Node,
- Instance: storage.Instance,
- Metadata: errorMetadata,
- MessageBuilder: func(result alertspecs.EvaluationResult) (string, float64, float64) {
- return fmt.Sprintf(
- "ZFS pool '%s' has errors: %d read, %d write, %d checksum",
- pool.Name, pool.ReadErrors, pool.WriteErrors, pool.ChecksumErrors,
- ), float64(totalErrors), 0
- },
- })
- if result.Transition != nil && result.Transition.Kind == alertspecs.EvaluationTransitionActivated {
- log.Error().
- Str("pool", pool.Name).
- Int64("read_errors", pool.ReadErrors).
- Int64("write_errors", pool.WriteErrors).
- Int64("checksum_errors", pool.ChecksumErrors).
- Str("node", storage.Node).
- Msg("ZFS pool has I/O errors")
- }
- }
- } else {
- m.clearAlert(buildCanonicalStateID(errorsSpecResourceID, errorsSpecID))
- }
-
- // Check individual devices for errors
- for _, device := range pool.Devices {
- alertID := fmt.Sprintf("zfs-device-%s-%s", storage.ID, device.Name)
- deviceAssessment := zfsDeviceAssessment(device)
- metadata := map[string]interface{}{
- "pool_name": pool.Name,
- "device_name": device.Name,
- "device_state": device.State,
- "read_errors": device.ReadErrors,
- "write_errors": device.WriteErrors,
- "checksum_errors": device.ChecksumErrors,
- }
- result, _ := m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{
- SpecID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name) + "/device:" + sanitizeHostComponent(device.Name) + "-health",
- Signal: "zfs-device",
- Codes: zfsDeviceAssessmentCodes,
- Reasons: deviceAssessment.Reasons,
- AlertID: alertID,
- AlertType: "zfs-device",
- SpecResourceID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name) + "/device:" + sanitizeHostComponent(device.Name),
- ResourceID: storage.ID,
- ResourceName: formatZFSDeviceResourceName(storage.Name, pool.Name, device.Name),
- ResourceType: unifiedresources.ResourceTypeStorage,
- Node: storage.Node,
- Instance: storage.Instance,
- Metadata: metadata,
- MessageBuilder: func(result alertspecs.EvaluationResult) (string, float64, float64) {
- return strings.Join(storageHealthReasonSummaries(deviceAssessment.Reasons), "; "), float64(device.ReadErrors + device.WriteErrors + device.ChecksumErrors), 0
- },
- })
- if result.Transition != nil && result.Transition.Kind == alertspecs.EvaluationTransitionActivated {
- log.Warn().
- Str("pool", pool.Name).
- Str("device", device.Name).
- Str("state", device.State).
- Int64("errors", device.ReadErrors+device.WriteErrors+device.ChecksumErrors).
- Str("node", storage.Node).
- Msg("ZFS device has issues")
- }
- }
-}
-
-func formatZFSDeviceResourceName(storageName, poolName, deviceName string) string {
- storageName = strings.TrimSpace(storageName)
- if storageName == "" {
- storageName = "storage"
- }
-
- parts := make([]string, 0, 2)
- if poolName = strings.TrimSpace(poolName); poolName != "" {
- parts = append(parts, poolName)
- }
- if deviceName = strings.TrimSpace(deviceName); deviceName != "" {
- parts = append(parts, deviceName)
- }
- if len(parts) == 0 {
- return storageName
- }
- return fmt.Sprintf("%s (%s)", storageName, strings.Join(parts, ", "))
-}
-
// clearAlert removes an alert if it exists
func (m *Manager) clearAlert(alertID string) {
m.mu.Lock()
@@ -5117,95 +4753,6 @@ func (m *Manager) clearNodeOfflineAlert(node models.Node) {
Msg("Node is back online")
}
-// checkPBSOffline creates an alert for offline PBS instances
-func (m *Manager) checkPBSOffline(pbs models.PBSInstance) {
- m.mu.Lock()
- delete(m.offlineRecoveryConfirmations, canonicalConnectivityStateID(pbs.ID))
- m.mu.Unlock()
-
- thresholds := m.resolveResourceThresholds("pbs", pbs.ID)
- spec, err := buildCanonicalConnectivitySpec(pbs.ID, pbs.Name, unifiedresources.ResourceTypePBS, AlertLevelCritical, 3, thresholds.Disabled || thresholds.DisableConnectivity)
- if err != nil {
- log.Warn().
- Err(err).
- Str("pbs", pbs.Name).
- Str("pbsID", pbs.ID).
- Msg("Skipping invalid canonical PBS connectivity spec")
- return
- }
-
- _, _ = m.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
- Spec: spec,
- Evidence: alertspecs.AlertEvidence{ObservedAt: time.Now(), Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: false}},
- Tracking: m.offlineConfirmations,
- TrackingKey: pbs.ID,
- AlertID: fmt.Sprintf("pbs-offline-%s", pbs.ID),
- AlertType: "offline",
- ResourceID: pbs.ID,
- ResourceName: pbs.Name,
- Node: pbs.Host,
- Instance: pbs.Name,
- Message: fmt.Sprintf("PBS instance %s is offline", pbs.Name),
- Metadata: map[string]interface{}{
- "resourceType": "pbs",
- "status": pbs.Status,
- "connectionHealth": pbs.ConnectionHealth,
- },
- RateLimit: true,
- DispatchAsync: true,
- })
-}
-
-// clearPBSOfflineAlert removes offline alert when PBS comes back online
-func (m *Manager) clearPBSOfflineAlert(pbs models.PBSInstance) {
- m.clearResourceOfflineAlert(pbs.ID, pbs.Name, pbs.Host, "PBS", offlineRecoveryConfirmationsDefault)
-}
-
-// checkStorageOffline creates an alert for offline/unavailable storage
-func (m *Manager) checkStorageOffline(storage models.Storage) {
- alertID := fmt.Sprintf("storage-offline-%s", storage.ID)
-
- m.mu.Lock()
- delete(m.offlineRecoveryConfirmations, canonicalConnectivityStateID(storage.ID))
- m.mu.Unlock()
-
- thresholds := m.resolveResourceThresholds("storage", storage.ID)
- spec, err := buildCanonicalConnectivitySpec(storage.ID, storage.Name, unifiedresources.ResourceTypeStorage, AlertLevelWarning, 2, thresholds.Disabled || thresholds.DisableConnectivity)
- if err != nil {
- log.Warn().
- Err(err).
- Str("storage", storage.Name).
- Str("storageID", storage.ID).
- Msg("Skipping invalid canonical storage connectivity spec")
- return
- }
-
- _, _ = m.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
- Spec: spec,
- Evidence: alertspecs.AlertEvidence{ObservedAt: time.Now(), Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: false}},
- Tracking: m.offlineConfirmations,
- TrackingKey: storage.ID,
- AlertID: alertID,
- AlertType: "offline",
- ResourceID: storage.ID,
- ResourceName: storage.Name,
- Node: storage.Node,
- Instance: storage.Instance,
- Message: fmt.Sprintf("Storage %s on node %s is unavailable", storage.Name, storage.Node),
- Metadata: map[string]interface{}{
- "resourceType": "storage",
- "status": storage.Status,
- },
- RateLimit: true,
- DispatchAsync: true,
- })
-}
-
-// clearStorageOfflineAlert removes offline alert when storage comes back online
-func (m *Manager) clearStorageOfflineAlert(storage models.Storage) {
- m.clearResourceOfflineAlert(storage.ID, storage.Name, storage.Node, "Storage", offlineRecoveryConfirmationsStorage)
-}
-
// checkGuestPoweredOff creates an alert for powered-off guests
func (m *Manager) checkGuestPoweredOff(guestID, name, node, instanceName, guestType string, monitorOnly bool) {
m.mu.RLock()
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index e957f66bc1..7cba121b8d 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -30,6 +30,58 @@ func ptrTime(t time.Time) *time.Time {
return &tt
}
+func TestPBSOfflineNormalizesStatusAndConnectionHealth(t *testing.T) {
+ tests := []struct {
+ name string
+ pbs models.PBSInstance
+ want bool
+ }{
+ {
+ name: "status offline",
+ pbs: models.PBSInstance{Status: " OFFLINE "},
+ want: true,
+ },
+ {
+ name: "connection health error",
+ pbs: models.PBSInstance{Status: "online", ConnectionHealth: " Error "},
+ want: true,
+ },
+ {
+ name: "connection health failed",
+ pbs: models.PBSInstance{Status: "online", ConnectionHealth: "FAILED"},
+ want: true,
+ },
+ {
+ name: "connection health unhealthy",
+ pbs: models.PBSInstance{Status: "online", ConnectionHealth: " unhealthy "},
+ want: true,
+ },
+ {
+ name: "online and healthy",
+ pbs: models.PBSInstance{Status: "online", ConnectionHealth: "healthy"},
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := isPBSOffline(tt.pbs); got != tt.want {
+ t.Fatalf("isPBSOffline() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestFormatZFSDeviceResourceNamePreservesDevicePath(t *testing.T) {
+ got := formatZFSDeviceResourceName("local-zfs", "data", "/dev/sda4")
+ if got != "local-zfs (data, /dev/sda4)" {
+ t.Fatalf("formatZFSDeviceResourceName() = %q, want %q", got, "local-zfs (data, /dev/sda4)")
+ }
+ if strings.Contains(got, "//") {
+ t.Fatalf("expected formatted resource name not to contain doubled slash, got %q", got)
+ }
+}
+
// newTestManager creates a Manager with an isolated temp directory for testing.
// It uses os.Setenv with a mutex to safely handle parallel tests that call // t.Parallel()
// before invoking this function (t.Setenv cannot be used after t.Parallel).
diff --git a/internal/alerts/pbs.go b/internal/alerts/pbs.go
new file mode 100644
index 0000000000..6e40177566
--- /dev/null
+++ b/internal/alerts/pbs.go
@@ -0,0 +1,184 @@
+package alerts
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+func isPBSOffline(pbs models.PBSInstance) bool {
+ status := strings.ToLower(strings.TrimSpace(pbs.Status))
+ health := strings.ToLower(strings.TrimSpace(pbs.ConnectionHealth))
+ return status == "offline" || health == "error" || health == "failed" || health == "unhealthy"
+}
+
+func (m *Manager) clearPBSMetricAlerts(pbsID string) {
+ if strings.TrimSpace(pbsID) == "" {
+ return
+ }
+
+ m.clearAlert(canonicalMetricStateID(pbsID, "cpu"))
+ m.clearAlert(canonicalMetricStateID(pbsID, "memory"))
+}
+
+// CheckPBS checks PBS instance metrics against thresholds
+func (m *Manager) CheckPBS(pbs models.PBSInstance) {
+ m.mu.RLock()
+ if !m.config.Enabled {
+ m.mu.RUnlock()
+ return
+ }
+ if m.config.DisableAllPBS {
+ m.mu.RUnlock()
+ // Clear any existing PBS alerts when all PBS alerts are disabled
+ m.mu.Lock()
+ // Reset offline confirmation tracking
+ delete(m.offlineConfirmations, pbs.ID)
+ // Clear CPU alert
+ cpuAlertID := canonicalMetricStateID(pbs.ID, "cpu")
+ if m.clearActiveAlertIfPresentNoLock(cpuAlertID) {
+ log.Info().
+ Str("alertID", cpuAlertID).
+ Str("pbs", pbs.Name).
+ Msg("Cleared CPU alert - all PBS alerts disabled")
+ }
+ // Clear Memory alert
+ memAlertID := canonicalMetricStateID(pbs.ID, "memory")
+ if m.clearActiveAlertIfPresentNoLock(memAlertID) {
+ log.Info().
+ Str("alertID", memAlertID).
+ Str("pbs", pbs.Name).
+ Msg("Cleared Memory alert - all PBS alerts disabled")
+ }
+ // Clear offline alert
+ offlineAlertID := canonicalConnectivityStateID(pbs.ID)
+ if m.clearActiveAlertIfPresentNoLock(offlineAlertID) {
+ log.Info().
+ Str("alertID", offlineAlertID).
+ Str("pbs", pbs.Name).
+ Msg("Cleared offline alert - all PBS alerts disabled")
+ }
+ m.mu.Unlock()
+ return
+ }
+
+ thresholds := m.resolveResourceThresholds("pbs", pbs.ID)
+ disablePBSOffline := m.config.DisableAllPBSOffline
+ m.mu.RUnlock()
+
+ // Check override disable BEFORE offline detection to prevent spurious notifications
+ if thresholds.Disabled {
+ m.mu.Lock()
+ // Reset offline confirmation tracking
+ delete(m.offlineConfirmations, pbs.ID)
+ // Clear CPU alert
+ cpuAlertID := canonicalMetricStateID(pbs.ID, "cpu")
+ if m.clearActiveAlertIfPresentNoLock(cpuAlertID) {
+ log.Debug().
+ Str("alertID", cpuAlertID).
+ Str("pbs", pbs.Name).
+ Msg("Cleared CPU alert - PBS has alerts disabled")
+ }
+ // Clear Memory alert
+ memAlertID := canonicalMetricStateID(pbs.ID, "memory")
+ if m.clearActiveAlertIfPresentNoLock(memAlertID) {
+ log.Debug().
+ Str("alertID", memAlertID).
+ Str("pbs", pbs.Name).
+ Msg("Cleared Memory alert - PBS has alerts disabled")
+ }
+ // Clear offline alert
+ offlineAlertID := canonicalConnectivityStateID(pbs.ID)
+ if m.clearActiveAlertIfPresentNoLock(offlineAlertID) {
+ log.Debug().
+ Str("alertID", offlineAlertID).
+ Str("pbs", pbs.Name).
+ Msg("Cleared offline alert - PBS has alerts disabled")
+ }
+ m.mu.Unlock()
+ return
+ }
+
+ pbsOffline := isPBSOffline(pbs)
+
+ if disablePBSOffline || thresholds.DisableConnectivity {
+ // Clear tracking and any existing offline alerts when globally disabled
+ m.mu.Lock()
+ delete(m.offlineConfirmations, pbs.ID)
+ m.mu.Unlock()
+ m.clearAlert(canonicalConnectivityStateID(pbs.ID))
+ } else {
+ // Check if PBS is offline first (similar to nodes)
+ if pbsOffline {
+ m.checkPBSOffline(pbs)
+ } else {
+ // Clear any existing offline alert if PBS is back online
+ m.clearPBSOfflineAlert(pbs)
+ }
+ }
+
+ // When PBS is offline/unhealthy, clear stale metric alerts immediately.
+ if pbsOffline {
+ m.clearPBSMetricAlerts(pbs.ID)
+ return
+ }
+
+ m.evaluateUnifiedMetrics(&UnifiedResourceInput{
+ ID: pbs.ID,
+ Type: "pbs",
+ Name: pbs.Name,
+ Node: pbs.Host,
+ Instance: pbs.Name,
+ CPU: &UnifiedResourceMetric{Percent: pbs.CPU},
+ Memory: &UnifiedResourceMetric{Percent: pbs.Memory},
+ }, thresholds, nil)
+}
+
+// checkPBSOffline creates an alert for offline PBS instances
+func (m *Manager) checkPBSOffline(pbs models.PBSInstance) {
+ m.mu.Lock()
+ delete(m.offlineRecoveryConfirmations, canonicalConnectivityStateID(pbs.ID))
+ m.mu.Unlock()
+
+ thresholds := m.resolveResourceThresholds("pbs", pbs.ID)
+ spec, err := buildCanonicalConnectivitySpec(pbs.ID, pbs.Name, unifiedresources.ResourceTypePBS, AlertLevelCritical, 3, thresholds.Disabled || thresholds.DisableConnectivity)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("pbs", pbs.Name).
+ Str("pbsID", pbs.ID).
+ Msg("Skipping invalid canonical PBS connectivity spec")
+ return
+ }
+
+ _, _ = m.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
+ Spec: spec,
+ Evidence: alertspecs.AlertEvidence{ObservedAt: time.Now(), Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: false}},
+ Tracking: m.offlineConfirmations,
+ TrackingKey: pbs.ID,
+ AlertID: fmt.Sprintf("pbs-offline-%s", pbs.ID),
+ AlertType: "offline",
+ ResourceID: pbs.ID,
+ ResourceName: pbs.Name,
+ Node: pbs.Host,
+ Instance: pbs.Name,
+ Message: fmt.Sprintf("PBS instance %s is offline", pbs.Name),
+ Metadata: map[string]interface{}{
+ "resourceType": "pbs",
+ "status": pbs.Status,
+ "connectionHealth": pbs.ConnectionHealth,
+ },
+ RateLimit: true,
+ DispatchAsync: true,
+ })
+}
+
+// clearPBSOfflineAlert removes offline alert when PBS comes back online
+func (m *Manager) clearPBSOfflineAlert(pbs models.PBSInstance) {
+ m.clearResourceOfflineAlert(pbs.ID, pbs.Name, pbs.Host, "PBS", offlineRecoveryConfirmationsDefault)
+}
diff --git a/internal/alerts/storage.go b/internal/alerts/storage.go
new file mode 100644
index 0000000000..5642658da1
--- /dev/null
+++ b/internal/alerts/storage.go
@@ -0,0 +1,294 @@
+package alerts
+
+import (
+ "fmt"
+ "strings"
+ "time"
+
+ alertspecs "github.com/rcourtman/pulse-go-rewrite/internal/alerts/specs"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rs/zerolog/log"
+)
+
+// CheckStorage checks storage against thresholds
+func (m *Manager) CheckStorage(storage models.Storage) {
+ m.mu.RLock()
+ if !m.config.Enabled {
+ m.mu.RUnlock()
+ return
+ }
+ if m.config.DisableAllStorage {
+ m.mu.RUnlock()
+ // Clear any existing storage alerts when all storage alerts are disabled
+ m.mu.Lock()
+ usageAlertID := canonicalMetricStateID(storage.ID, "usage")
+ if m.clearActiveAlertIfPresentNoLock(usageAlertID) {
+ log.Info().
+ Str("alertID", usageAlertID).
+ Str("storage", storage.Name).
+ Msg("Cleared usage alert - all storage alerts disabled")
+ }
+ offlineAlertID := canonicalConnectivityStateID(storage.ID)
+ if m.clearActiveAlertIfPresentNoLock(offlineAlertID) {
+ log.Info().
+ Str("alertID", offlineAlertID).
+ Str("storage", storage.Name).
+ Msg("Cleared offline alert - all storage alerts disabled")
+ }
+ m.mu.Unlock()
+ return
+ }
+
+ thresholds := m.resolveResourceThresholds("storage", storage.ID)
+ m.mu.RUnlock()
+
+ if thresholds.Disabled {
+ m.mu.Lock()
+ delete(m.offlineConfirmations, storage.ID)
+ m.mu.Unlock()
+ m.clearAlert(canonicalMetricStateID(storage.ID, "usage"))
+ m.clearAlert(canonicalConnectivityStateID(storage.ID))
+ return
+ }
+
+ // Check if storage is truly offline/unavailable (not just inactive from other nodes)
+ // Note: In a cluster, local storage from other nodes shows as inactive which is normal
+ if thresholds.DisableConnectivity {
+ m.mu.Lock()
+ delete(m.offlineConfirmations, storage.ID)
+ m.mu.Unlock()
+ m.clearAlert(canonicalConnectivityStateID(storage.ID))
+ } else if storage.Status == "offline" || storage.Status == "unavailable" {
+ m.checkStorageOffline(storage)
+ } else {
+ // Clear any existing offline alert if storage is back online
+ m.clearStorageOfflineAlert(storage)
+ }
+
+ // Check usage if storage has valid data (even if not currently active on this node)
+ // In clusters, storage may show as inactive on nodes where it's not currently mounted
+ // but we still want to alert on high usage
+ log.Debug().
+ Str("storage", storage.Name).
+ Str("id", storage.ID).
+ Float64("usage", storage.Usage).
+ Str("status", storage.Status).
+ Float64("trigger", thresholds.Usage.Trigger).
+ Float64("clear", thresholds.Usage.Clear).
+ Msg("Checking storage thresholds")
+
+ // Check usage if storage is online - checkMetric will skip if threshold is nil or <= 0
+ if storage.Status != "offline" && storage.Status != "unavailable" && storage.Usage > 0 {
+ m.evaluateUnifiedMetrics(&UnifiedResourceInput{
+ ID: storage.ID,
+ Type: "storage",
+ Name: storage.Name,
+ Node: storage.Node,
+ Instance: storage.Instance,
+ Disk: &UnifiedResourceMetric{Percent: storage.Usage},
+ }, thresholds, nil)
+ }
+
+ // Check ZFS pool status if this is ZFS storage
+ if storage.ZFSPool != nil {
+ m.checkZFSPoolHealth(storage)
+ }
+}
+
+// checkZFSPoolHealth checks ZFS pool for errors and degraded state
+func (m *Manager) checkZFSPoolHealth(storage models.Storage) {
+ pool := storage.ZFSPool
+ if pool == nil {
+ return
+ }
+
+ poolResourceName := fmt.Sprintf("%s (%s)", storage.Name, pool.Name)
+ poolAssessment := storagehealth.AssessZFSPool(*pool)
+
+ // Check pool state (DEGRADED, FAULTED, etc.)
+ stateAlertID := fmt.Sprintf("zfs-pool-state-%s", storage.ID)
+ stateMetadata := map[string]interface{}{
+ "pool_name": pool.Name,
+ "pool_state": pool.State,
+ }
+ stateReasons := filterStorageHealthReasonsByCodes(poolAssessment.Reasons, zfsPoolAssessmentCodes)
+ stateResult, _ := m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{
+ SpecID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name) + "-state",
+ Signal: "zfs-pool",
+ Codes: zfsPoolAssessmentCodes,
+ Reasons: stateReasons,
+ AlertID: stateAlertID,
+ AlertType: "zfs-pool-state",
+ SpecResourceID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name),
+ ResourceID: storage.ID,
+ ResourceName: poolResourceName,
+ ResourceType: unifiedresources.ResourceTypeStorage,
+ Node: storage.Node,
+ Instance: storage.Instance,
+ Metadata: stateMetadata,
+ })
+ if stateResult.Transition != nil && stateResult.Transition.Kind == alertspecs.EvaluationTransitionActivated {
+ log.Warn().
+ Str("pool", pool.Name).
+ Str("state", pool.State).
+ Str("node", storage.Node).
+ Msg("ZFS pool is not healthy")
+ }
+
+ // Check for read/write/checksum errors
+ totalErrors := pool.ReadErrors + pool.WriteErrors + pool.ChecksumErrors
+ errorsAlertID := fmt.Sprintf("zfs-pool-errors-%s", storage.ID)
+ errorsSpecResourceID := storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name)
+ errorsSpecID := errorsSpecResourceID + "-errors"
+ if totalErrors > 0 {
+ existingValue, exists := m.activeAlertValue(buildCanonicalStateID(errorsSpecResourceID, errorsSpecID))
+ if !exists || float64(totalErrors) > existingValue {
+ errorMetadata := map[string]interface{}{
+ "pool_name": pool.Name,
+ "read_errors": pool.ReadErrors,
+ "write_errors": pool.WriteErrors,
+ "checksum_errors": pool.ChecksumErrors,
+ }
+ errorReasons := filterStorageHealthReasonsByCodes(poolAssessment.Reasons, zfsPoolErrorAssessmentCodes)
+ result, _ := m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{
+ SpecID: errorsSpecID,
+ Signal: "zfs-pool-errors",
+ Codes: zfsPoolErrorAssessmentCodes,
+ Reasons: errorReasons,
+ AlertID: errorsAlertID,
+ AlertType: "zfs-pool-errors",
+ SpecResourceID: errorsSpecResourceID,
+ ResourceID: storage.ID,
+ ResourceName: poolResourceName,
+ ResourceType: unifiedresources.ResourceTypeStorage,
+ Node: storage.Node,
+ Instance: storage.Instance,
+ Metadata: errorMetadata,
+ MessageBuilder: func(result alertspecs.EvaluationResult) (string, float64, float64) {
+ return fmt.Sprintf(
+ "ZFS pool '%s' has errors: %d read, %d write, %d checksum",
+ pool.Name, pool.ReadErrors, pool.WriteErrors, pool.ChecksumErrors,
+ ), float64(totalErrors), 0
+ },
+ })
+ if result.Transition != nil && result.Transition.Kind == alertspecs.EvaluationTransitionActivated {
+ log.Error().
+ Str("pool", pool.Name).
+ Int64("read_errors", pool.ReadErrors).
+ Int64("write_errors", pool.WriteErrors).
+ Int64("checksum_errors", pool.ChecksumErrors).
+ Str("node", storage.Node).
+ Msg("ZFS pool has I/O errors")
+ }
+ }
+ } else {
+ m.clearAlert(buildCanonicalStateID(errorsSpecResourceID, errorsSpecID))
+ }
+
+ // Check individual devices for errors
+ for _, device := range pool.Devices {
+ alertID := fmt.Sprintf("zfs-device-%s-%s", storage.ID, device.Name)
+ deviceAssessment := zfsDeviceAssessment(device)
+ metadata := map[string]interface{}{
+ "pool_name": pool.Name,
+ "device_name": device.Name,
+ "device_state": device.State,
+ "read_errors": device.ReadErrors,
+ "write_errors": device.WriteErrors,
+ "checksum_errors": device.ChecksumErrors,
+ }
+ result, _ := m.syncCanonicalHealthAssessmentAlert(canonicalHealthAssessmentAlertParams{
+ SpecID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name) + "/device:" + sanitizeHostComponent(device.Name) + "-health",
+ Signal: "zfs-device",
+ Codes: zfsDeviceAssessmentCodes,
+ Reasons: deviceAssessment.Reasons,
+ AlertID: alertID,
+ AlertType: "zfs-device",
+ SpecResourceID: storage.ID + "/zfs-pool:" + sanitizeHostComponent(pool.Name) + "/device:" + sanitizeHostComponent(device.Name),
+ ResourceID: storage.ID,
+ ResourceName: formatZFSDeviceResourceName(storage.Name, pool.Name, device.Name),
+ ResourceType: unifiedresources.ResourceTypeStorage,
+ Node: storage.Node,
+ Instance: storage.Instance,
+ Metadata: metadata,
+ MessageBuilder: func(result alertspecs.EvaluationResult) (string, float64, float64) {
+ return strings.Join(storageHealthReasonSummaries(deviceAssessment.Reasons), "; "), float64(device.ReadErrors + device.WriteErrors + device.ChecksumErrors), 0
+ },
+ })
+ if result.Transition != nil && result.Transition.Kind == alertspecs.EvaluationTransitionActivated {
+ log.Warn().
+ Str("pool", pool.Name).
+ Str("device", device.Name).
+ Str("state", device.State).
+ Int64("errors", device.ReadErrors+device.WriteErrors+device.ChecksumErrors).
+ Str("node", storage.Node).
+ Msg("ZFS device has issues")
+ }
+ }
+}
+
+func formatZFSDeviceResourceName(storageName, poolName, deviceName string) string {
+ storageName = strings.TrimSpace(storageName)
+ if storageName == "" {
+ storageName = "storage"
+ }
+
+ parts := make([]string, 0, 2)
+ if poolName = strings.TrimSpace(poolName); poolName != "" {
+ parts = append(parts, poolName)
+ }
+ if deviceName = strings.TrimSpace(deviceName); deviceName != "" {
+ parts = append(parts, deviceName)
+ }
+ if len(parts) == 0 {
+ return storageName
+ }
+ return fmt.Sprintf("%s (%s)", storageName, strings.Join(parts, ", "))
+}
+
+// checkStorageOffline creates an alert for offline/unavailable storage
+func (m *Manager) checkStorageOffline(storage models.Storage) {
+ alertID := fmt.Sprintf("storage-offline-%s", storage.ID)
+
+ m.mu.Lock()
+ delete(m.offlineRecoveryConfirmations, canonicalConnectivityStateID(storage.ID))
+ m.mu.Unlock()
+
+ thresholds := m.resolveResourceThresholds("storage", storage.ID)
+ spec, err := buildCanonicalConnectivitySpec(storage.ID, storage.Name, unifiedresources.ResourceTypeStorage, AlertLevelWarning, 2, thresholds.Disabled || thresholds.DisableConnectivity)
+ if err != nil {
+ log.Warn().
+ Err(err).
+ Str("storage", storage.Name).
+ Str("storageID", storage.ID).
+ Msg("Skipping invalid canonical storage connectivity spec")
+ return
+ }
+
+ _, _ = m.evaluateCanonicalLifecycleAlert(canonicalLifecycleAlertParams{
+ Spec: spec,
+ Evidence: alertspecs.AlertEvidence{ObservedAt: time.Now(), Connectivity: &alertspecs.ConnectivityEvidence{Signal: "status", Connected: false}},
+ Tracking: m.offlineConfirmations,
+ TrackingKey: storage.ID,
+ AlertID: alertID,
+ AlertType: "offline",
+ ResourceID: storage.ID,
+ ResourceName: storage.Name,
+ Node: storage.Node,
+ Instance: storage.Instance,
+ Message: fmt.Sprintf("Storage %s on node %s is unavailable", storage.Name, storage.Node),
+ Metadata: map[string]interface{}{
+ "resourceType": "storage",
+ "status": storage.Status,
+ },
+ RateLimit: true,
+ DispatchAsync: true,
+ })
+}
+
+// clearStorageOfflineAlert removes offline alert when storage comes back online
+func (m *Manager) clearStorageOfflineAlert(storage models.Storage) {
+ m.clearResourceOfflineAlert(storage.ID, storage.Name, storage.Node, "Storage", offlineRecoveryConfirmationsStorage)
+}