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.

Reconcile Ceph pool alert identity

rcourtman47e9eb9aea70
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index 115f3b1c82..db2ad528a5 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -83,6 +83,7 @@ operator-facing alert routing behavior for live runtime alerts.
61. `frontend-modern/src/components/Alerts/alertAssistantHandoffModel.ts`
62. `frontend-modern/src/components/Alerts/IncidentAssistantHandoffButton.tsx`
63. `frontend-modern/src/components/Alerts/incidentAssistantHandoffModel.ts`
+64. `internal/alerts/storage_override_identity.go`
## Shared Boundaries
@@ -204,6 +205,11 @@ incidents. ZFS device alert labels must preserve raw device names such as
`/dev/sda4`, but must not join pool and device labels with a raw slash because
device paths can already begin with `/`; browser alert surfaces consume the
runtime `resourceName` as authored rather than patching storage labels locally.
+Ceph pool storage threshold resolution is also source-alias aware. Storage
+alerts must evaluate the normalized pool storage id while accepting legacy
+`agent:<host>-ceph-pool-<name>` override keys as aliases, so operators do not
+lose saved thresholds when the same physical Ceph pool moves between
+host-agent-only fallback and Proxmox API canonical discovery.
Browser metric severity colors are also alert-backed. Workloads,
Infrastructure, and Storage may pass resolved display thresholds into their
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 60e7a3e8e9..89cbf1d77b 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -70,7 +70,8 @@ truth for live infrastructure data.
46. `internal/truenas/client.go`
47. `internal/truenas/disk_health.go`
48. `internal/truenas/provider.go`
-49. `internal/truenas/types.go`
+49. `internal/models/ceph_cluster_identity.go`
+50. `internal/truenas/types.go`
## Shared Boundaries
@@ -664,6 +665,13 @@ exposes pools, monitoring must project each pool through the shared
`models.CephPoolStorage` helper, write storage history under that pool storage
id, and evaluate alerts through `CheckStorage` so per-pool thresholds, active
alerts, and charts all use the same storage series identity.
+Ceph cluster identity is FSID-owned across discovery sources. Proxmox API Ceph
+reports are canonical when available, host-agent Ceph reports are the fallback
+or supplemental source, and state reconciliation must collapse reports for the
+same FSID into one cluster while preserving source aliases for existing pool
+thresholds. Host-agent Ceph pool storage ids must not carry `agent:` as their
+canonical identity; that prefix remains only an alert/threshold alias for
+previously persisted overrides.
That same chart boundary also owns provider-backed workload bridging.
Workload-chart consumers may query VM and system-container history through the
resolved unified-resource metrics target, but the emitted series identity must
diff --git a/internal/alerts/storage.go b/internal/alerts/storage.go
index 5642658da1..9dbdf6223b 100644
--- a/internal/alerts/storage.go
+++ b/internal/alerts/storage.go
@@ -19,47 +19,60 @@ func (m *Manager) CheckStorage(storage models.Storage) {
m.mu.RUnlock()
return
}
+ resourceIDs := storageAlertResourceIDs(storage)
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")
+ for _, resourceID := range resourceIDs {
+ usageAlertID := canonicalMetricStateID(resourceID, "usage")
+ if m.clearActiveAlertIfPresentNoLock(usageAlertID) {
+ log.Info().
+ Str("alertID", usageAlertID).
+ Str("storage", storage.Name).
+ Msg("Cleared usage alert - all storage alerts disabled")
+ }
+ offlineAlertID := canonicalConnectivityStateID(resourceID)
+ 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)
+ thresholds := m.resolveStorageThresholdsNoLock(storage)
m.mu.RUnlock()
if thresholds.Disabled {
m.mu.Lock()
- delete(m.offlineConfirmations, storage.ID)
+ for _, resourceID := range resourceIDs {
+ delete(m.offlineConfirmations, resourceID)
+ }
m.mu.Unlock()
- m.clearAlert(canonicalMetricStateID(storage.ID, "usage"))
- m.clearAlert(canonicalConnectivityStateID(storage.ID))
+ for _, resourceID := range resourceIDs {
+ m.clearAlert(canonicalMetricStateID(resourceID, "usage"))
+ m.clearAlert(canonicalConnectivityStateID(resourceID))
+ }
return
}
+ m.clearStorageAliasAlerts(storage)
+
// 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)
+ for _, resourceID := range resourceIDs {
+ delete(m.offlineConfirmations, resourceID)
+ }
m.mu.Unlock()
- m.clearAlert(canonicalConnectivityStateID(storage.ID))
+ for _, resourceID := range resourceIDs {
+ m.clearAlert(canonicalConnectivityStateID(resourceID))
+ }
} else if storage.Status == "offline" || storage.Status == "unavailable" {
m.checkStorageOffline(storage)
} else {
@@ -97,6 +110,16 @@ func (m *Manager) CheckStorage(storage models.Storage) {
}
}
+func (m *Manager) clearStorageAliasAlerts(storage models.Storage) {
+ for i, resourceID := range storageAlertResourceIDs(storage) {
+ if i == 0 {
+ continue
+ }
+ m.clearAlert(canonicalMetricStateID(resourceID, "usage"))
+ m.clearAlert(canonicalConnectivityStateID(resourceID))
+ }
+}
+
// checkZFSPoolHealth checks ZFS pool for errors and degraded state
func (m *Manager) checkZFSPoolHealth(storage models.Storage) {
pool := storage.ZFSPool
@@ -256,7 +279,9 @@ func (m *Manager) checkStorageOffline(storage models.Storage) {
delete(m.offlineRecoveryConfirmations, canonicalConnectivityStateID(storage.ID))
m.mu.Unlock()
- thresholds := m.resolveResourceThresholds("storage", storage.ID)
+ m.mu.RLock()
+ thresholds := m.resolveStorageThresholdsNoLock(storage)
+ m.mu.RUnlock()
spec, err := buildCanonicalConnectivitySpec(storage.ID, storage.Name, unifiedresources.ResourceTypeStorage, AlertLevelWarning, 2, thresholds.Disabled || thresholds.DisableConnectivity)
if err != nil {
log.Warn().
diff --git a/internal/alerts/storage_override_identity.go b/internal/alerts/storage_override_identity.go
new file mode 100644
index 0000000000..a0c906114c
--- /dev/null
+++ b/internal/alerts/storage_override_identity.go
@@ -0,0 +1,69 @@
+package alerts
+
+import (
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+func storageThresholdLookupIDs(resourceID string, aliases ...string) []string {
+ ids := make([]string, 0, len(aliases)+2)
+ for _, id := range append([]string{resourceID}, aliases...) {
+ id = strings.TrimSpace(id)
+ if id == "" {
+ continue
+ }
+ ids = appendUniqueStorageLookupID(ids, id)
+ if alias, ok := cephPoolStorageSourceAliasID(id); ok {
+ ids = appendUniqueStorageLookupID(ids, alias)
+ }
+ }
+ return ids
+}
+
+func storageAlertResourceIDs(storage models.Storage) []string {
+ return storageThresholdLookupIDs(storage.ID, storage.AliasIDs...)
+}
+
+func appendUniqueStorageLookupID(ids []string, id string) []string {
+ for _, existing := range ids {
+ if existing == id {
+ return ids
+ }
+ }
+ return append(ids, id)
+}
+
+func cephPoolStorageSourceAliasID(id string) (string, bool) {
+ const marker = "-ceph-pool-"
+ idx := strings.Index(id, marker)
+ if idx <= 0 {
+ return "", false
+ }
+ instance := strings.TrimSpace(id[:idx])
+ if instance == "" {
+ return "", false
+ }
+ suffix := id[idx:]
+ if strings.HasPrefix(instance, "agent:") {
+ unprefixed := strings.TrimSpace(strings.TrimPrefix(instance, "agent:"))
+ if unprefixed == "" {
+ return "", false
+ }
+ return unprefixed + suffix, true
+ }
+ return "agent:" + instance + suffix, true
+}
+
+func (m *Manager) resolveStorageThresholdOverride(base ThresholdConfig, resourceID string, aliases []string) ThresholdConfig {
+ for _, lookupID := range storageThresholdLookupIDs(resourceID, aliases...) {
+ if override, exists := m.config.Overrides[lookupID]; exists {
+ return m.applyThresholdOverride(base, override)
+ }
+ }
+ return base
+}
+
+func (m *Manager) resolveStorageThresholdsNoLock(storage models.Storage) ThresholdConfig {
+ return m.resolveStorageThresholdOverride(m.defaultThresholdsForResourceType("storage"), storage.ID, storage.AliasIDs)
+}
diff --git a/internal/alerts/threshold_resolution_shared_test.go b/internal/alerts/threshold_resolution_shared_test.go
index 02bd1a5dff..bde15235df 100644
--- a/internal/alerts/threshold_resolution_shared_test.go
+++ b/internal/alerts/threshold_resolution_shared_test.go
@@ -288,6 +288,30 @@ func TestReevaluateActiveAlertsUsesSharedStorageOverrideResolution(t *testing.T)
}
}
+func TestStorageThresholdResolutionUsesAliasIDs(t *testing.T) {
+ m := newTestManager(t)
+
+ m.mu.Lock()
+ m.config.StorageDefault = HysteresisThreshold{Trigger: 95, Clear: 90}
+ m.config.Overrides = map[string]ThresholdConfig{
+ "agent:pve5-ceph-pool-data_replication": {
+ Usage: &HysteresisThreshold{Trigger: 50, Clear: 45},
+ },
+ }
+ thresholds := m.resolveStorageThresholdsNoLock(models.Storage{
+ ID: "pve5-ceph-pool-data_replication",
+ AliasIDs: []string{"agent:pve5-ceph-pool-data_replication"},
+ })
+ m.mu.Unlock()
+
+ if thresholds.Usage == nil {
+ t.Fatalf("expected usage threshold to be resolved")
+ }
+ if thresholds.Usage.Trigger != 50 || thresholds.Usage.Clear != 45 {
+ t.Fatalf("usage threshold = %#v, want alias override trigger 50 clear 45", thresholds.Usage)
+ }
+}
+
func TestCheckStorageOfflineUsesSharedThresholdResolution(t *testing.T) {
m := newTestManager(t)
storage := models.Storage{
diff --git a/internal/alerts/unified_eval.go b/internal/alerts/unified_eval.go
index 1420f312af..e1151dc480 100644
--- a/internal/alerts/unified_eval.go
+++ b/internal/alerts/unified_eval.go
@@ -128,6 +128,9 @@ func (m *Manager) resolveResourceThresholds(typeKey, resourceID string) Threshol
if isGuestThresholdResourceType(typeKey) {
return m.resolveGuestThresholdOverride(m.defaultThresholdsForResourceType(typeKey), nil, resourceID)
}
+ if typeKey == "storage" {
+ return m.resolveStorageThresholdOverride(m.defaultThresholdsForResourceType(typeKey), resourceID, nil)
+ }
return m.resolveThresholdOverride(m.defaultThresholdsForResourceType(typeKey), resourceID)
}
diff --git a/internal/alerts/unified_eval_test.go b/internal/alerts/unified_eval_test.go
index ac2c3d2717..19bc7ecdf9 100644
--- a/internal/alerts/unified_eval_test.go
+++ b/internal/alerts/unified_eval_test.go
@@ -205,6 +205,27 @@ func TestCheckUnifiedResourceOverrideLowerThresholdCreatesAlert(t *testing.T) {
assertAlertPresent(t, m, canonicalMetricStateID("vm-override", "cpu"))
}
+func TestResolveResourceThresholdsUsesCephStorageSourceAlias(t *testing.T) {
+ m := newTestManager(t)
+
+ m.mu.Lock()
+ m.config.StorageDefault = HysteresisThreshold{Trigger: 95, Clear: 90}
+ m.config.Overrides = map[string]ThresholdConfig{
+ "agent:pve5-ceph-pool-data_replication": {
+ Usage: &HysteresisThreshold{Trigger: 50, Clear: 45},
+ },
+ }
+ thresholds := m.resolveResourceThresholds("storage", "pve5-ceph-pool-data_replication")
+ m.mu.Unlock()
+
+ if thresholds.Usage == nil {
+ t.Fatalf("expected storage usage threshold")
+ }
+ if thresholds.Usage.Trigger != 50 || thresholds.Usage.Clear != 45 {
+ t.Fatalf("usage threshold = %#v, want legacy agent alias override trigger 50 clear 45", thresholds.Usage)
+ }
+}
+
func TestCheckUnifiedResourceNilInputNoPanic(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
diff --git a/internal/models/ceph_cluster_identity.go b/internal/models/ceph_cluster_identity.go
new file mode 100644
index 0000000000..1c34319ae9
--- /dev/null
+++ b/internal/models/ceph_cluster_identity.go
@@ -0,0 +1,177 @@
+package models
+
+import (
+ "sort"
+ "strings"
+)
+
+const (
+ CephClusterSourceProxmoxAPI = "proxmox-api"
+ CephClusterSourceHostAgent = "host-agent"
+)
+
+func normalizeCephClusterForState(cluster CephCluster, defaultSource string) CephCluster {
+ cluster.ID = strings.TrimSpace(cluster.ID)
+ cluster.Instance = strings.TrimSpace(cluster.Instance)
+ cluster.FSID = strings.TrimSpace(cluster.FSID)
+ cluster.Source = normalizeCephClusterSource(cluster.Source, cluster.Instance, defaultSource)
+ cluster.InstanceAliases = normalizeCephInstanceAliases(cluster.Instance, cluster.InstanceAliases)
+ return cluster
+}
+
+func normalizeCephClusterSource(source, instance, fallback string) string {
+ switch strings.ToLower(strings.TrimSpace(source)) {
+ case CephClusterSourceProxmoxAPI, "proxmox", "pve", "api":
+ return CephClusterSourceProxmoxAPI
+ case CephClusterSourceHostAgent, "agent", "host":
+ return CephClusterSourceHostAgent
+ }
+
+ if fallback != "" {
+ return normalizeCephClusterSource(fallback, instance, "")
+ }
+ if strings.HasPrefix(strings.TrimSpace(instance), "agent:") {
+ return CephClusterSourceHostAgent
+ }
+ return CephClusterSourceProxmoxAPI
+}
+
+func normalizeCephInstanceAliases(instance string, aliases []string) []string {
+ instance = strings.TrimSpace(instance)
+ out := make([]string, 0, len(aliases))
+ for _, alias := range aliases {
+ alias = strings.TrimSpace(alias)
+ if alias == "" || alias == instance || containsString(out, alias) {
+ continue
+ }
+ out = append(out, alias)
+ }
+ return out
+}
+
+func containsString(values []string, target string) bool {
+ for _, value := range values {
+ if value == target {
+ return true
+ }
+ }
+ return false
+}
+
+func cephClusterSourceRank(cluster CephCluster) int {
+ switch normalizeCephClusterSource(cluster.Source, cluster.Instance, "") {
+ case CephClusterSourceProxmoxAPI:
+ return 2
+ case CephClusterSourceHostAgent:
+ return 1
+ default:
+ return 0
+ }
+}
+
+func cephClusterFSIDKey(cluster CephCluster) string {
+ return strings.ToLower(strings.TrimSpace(cluster.FSID))
+}
+
+func cephClustersSamePhysicalCluster(left, right CephCluster) bool {
+ leftFSID := cephClusterFSIDKey(left)
+ rightFSID := cephClusterFSIDKey(right)
+ return leftFSID != "" && leftFSID == rightFSID
+}
+
+func mergeCephClusterForState(existing, incoming CephCluster) CephCluster {
+ existing = normalizeCephClusterForState(existing, "")
+ incoming = normalizeCephClusterForState(incoming, "")
+ if !cephClustersSamePhysicalCluster(existing, incoming) {
+ return incoming
+ }
+
+ primary := existing
+ supplemental := incoming
+ existingRank := cephClusterSourceRank(existing)
+ incomingRank := cephClusterSourceRank(incoming)
+ if incomingRank > existingRank || (incomingRank == existingRank && (incoming.ID == existing.ID || incoming.Instance == existing.Instance)) {
+ primary = incoming
+ supplemental = existing
+ }
+
+ return supplementCephCluster(primary, supplemental)
+}
+
+func supplementCephCluster(primary, supplemental CephCluster) CephCluster {
+ aliases := append([]string(nil), primary.InstanceAliases...)
+ if supplemental.Instance != "" {
+ aliases = append(aliases, supplemental.Instance)
+ }
+ aliases = append(aliases, supplemental.InstanceAliases...)
+ primary.InstanceAliases = normalizeCephInstanceAliases(primary.Instance, aliases)
+
+ if primary.Health == "" {
+ primary.Health = supplemental.Health
+ }
+ if primary.HealthMessage == "" {
+ primary.HealthMessage = supplemental.HealthMessage
+ }
+ if primary.TotalBytes == 0 && supplemental.TotalBytes != 0 {
+ primary.TotalBytes = supplemental.TotalBytes
+ primary.UsedBytes = supplemental.UsedBytes
+ primary.AvailableBytes = supplemental.AvailableBytes
+ primary.UsagePercent = supplemental.UsagePercent
+ }
+ if primary.NumMons == 0 {
+ primary.NumMons = supplemental.NumMons
+ }
+ if primary.NumMgrs == 0 {
+ primary.NumMgrs = supplemental.NumMgrs
+ }
+ if primary.NumOSDs == 0 {
+ primary.NumOSDs = supplemental.NumOSDs
+ primary.NumOSDsUp = supplemental.NumOSDsUp
+ primary.NumOSDsIn = supplemental.NumOSDsIn
+ }
+ if primary.NumPGs == 0 {
+ primary.NumPGs = supplemental.NumPGs
+ }
+ if len(primary.Pools) == 0 && len(supplemental.Pools) > 0 {
+ primary.Pools = append([]CephPool(nil), supplemental.Pools...)
+ }
+ if len(primary.Services) == 0 && len(supplemental.Services) > 0 {
+ primary.Services = append([]CephServiceStatus(nil), supplemental.Services...)
+ }
+ if primary.LastUpdated.IsZero() {
+ primary.LastUpdated = supplemental.LastUpdated
+ }
+ return primary
+}
+
+func upsertCephClusterInSlice(clusters []CephCluster, cluster CephCluster) ([]CephCluster, CephCluster) {
+ cluster = normalizeCephClusterForState(cluster, "")
+ for i, existing := range clusters {
+ existing = normalizeCephClusterForState(existing, "")
+ if existing.ID == cluster.ID {
+ if cephClustersSamePhysicalCluster(existing, cluster) {
+ cluster = mergeCephClusterForState(existing, cluster)
+ }
+ clusters[i] = cluster
+ return clusters, cluster
+ }
+ if cephClustersSamePhysicalCluster(existing, cluster) {
+ cluster = mergeCephClusterForState(existing, cluster)
+ clusters[i] = cluster
+ return clusters, cluster
+ }
+ }
+ return append(clusters, cluster), cluster
+}
+
+func sortCephClustersForState(clusters []CephCluster) {
+ sort.Slice(clusters, func(i, j int) bool {
+ if clusters[i].Instance == clusters[j].Instance {
+ if clusters[i].Name == clusters[j].Name {
+ return clusters[i].ID < clusters[j].ID
+ }
+ return clusters[i].Name < clusters[j].Name
+ }
+ return clusters[i].Instance < clusters[j].Instance
+ })
+}
diff --git a/internal/models/ceph_pool_storage_test.go b/internal/models/ceph_pool_storage_test.go
index fdc6c929de..d86a5ee18c 100644
--- a/internal/models/ceph_pool_storage_test.go
+++ b/internal/models/ceph_pool_storage_test.go
@@ -21,6 +21,9 @@ func TestStorageFromCephPool(t *testing.T) {
if storage.ID != "Main-ceph-pool-data_replication" {
t.Fatalf("ID = %q, want Main-ceph-pool-data_replication", storage.ID)
}
+ if len(storage.AliasIDs) != 1 || storage.AliasIDs[0] != "agent:Main-ceph-pool-data_replication" {
+ t.Fatalf("AliasIDs = %#v, want agent-prefixed Ceph pool alias", storage.AliasIDs)
+ }
if storage.Name != "data_replication" || storage.Pool != "data_replication" {
t.Fatalf("name/pool = %q/%q, want data_replication", storage.Name, storage.Pool)
}
diff --git a/internal/models/deepcopy.go b/internal/models/deepcopy.go
index 9f4e38fd2b..d564f4c993 100644
--- a/internal/models/deepcopy.go
+++ b/internal/models/deepcopy.go
@@ -961,6 +961,7 @@ func cloneStorage(src Storage) Storage {
dest := src
dest.Nodes = append([]string(nil), src.Nodes...)
dest.NodeIDs = append([]string(nil), src.NodeIDs...)
+ dest.AliasIDs = append([]string(nil), src.AliasIDs...)
dest.ZFSPool = cloneZFSPool(src.ZFSPool)
return dest.NormalizeCollections()
}
@@ -988,6 +989,7 @@ func cloneStorages(src []Storage) []Storage {
func cloneCephCluster(src CephCluster) CephCluster {
dest := src
+ dest.InstanceAliases = append([]string(nil), src.InstanceAliases...)
dest.Pools = append([]CephPool(nil), src.Pools...)
dest.Services = append([]CephServiceStatus(nil), src.Services...)
return dest.NormalizeCollections()
diff --git a/internal/models/models.go b/internal/models/models.go
index 66f912d44b..155c4e3ecd 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -2048,6 +2048,7 @@ type Storage struct {
Instance string `json:"instance"`
Nodes []string `json:"nodes,omitempty"`
NodeIDs []string `json:"nodeIds,omitempty"`
+ AliasIDs []string `json:"aliasIds,omitempty"`
NodeCount int `json:"nodeCount,omitempty"`
Type string `json:"type"`
Status string `json:"status"`
@@ -2076,6 +2077,33 @@ func CephPoolStorageID(instanceName, poolName string) string {
return fmt.Sprintf("%s-ceph-pool-%s", instance, name)
}
+func CephPoolStorageAliasIDs(instanceName, poolName string, instanceAliases ...string) []string {
+ canonicalID := CephPoolStorageID(instanceName, poolName)
+ aliases := make([]string, 0, len(instanceAliases)+2)
+ for _, instance := range append([]string{instanceName}, instanceAliases...) {
+ instance = strings.TrimSpace(instance)
+ if instance == "" {
+ continue
+ }
+ candidates := []string{instance}
+ if strings.HasPrefix(instance, "agent:") {
+ if unprefixed := strings.TrimSpace(strings.TrimPrefix(instance, "agent:")); unprefixed != "" {
+ candidates = append(candidates, unprefixed)
+ }
+ } else {
+ candidates = append(candidates, "agent:"+instance)
+ }
+ for _, candidate := range candidates {
+ aliasID := CephPoolStorageID(candidate, poolName)
+ if aliasID == canonicalID || containsString(aliases, aliasID) {
+ continue
+ }
+ aliases = append(aliases, aliasID)
+ }
+ }
+ return aliases
+}
+
func StorageFromCephPool(cluster CephCluster, pool CephPool) Storage {
name := strings.TrimSpace(pool.Name)
if name == "" {
@@ -2102,6 +2130,7 @@ func StorageFromCephPool(cluster CephCluster, pool CephPool) Storage {
Name: name,
Node: "cluster",
Instance: cluster.Instance,
+ AliasIDs: CephPoolStorageAliasIDs(cluster.Instance, name, cluster.InstanceAliases...),
Type: "ceph",
Status: status,
Pool: name,
@@ -2173,28 +2202,33 @@ type ZFSDevice struct {
// CephCluster represents the health and capacity information for a Ceph cluster
type CephCluster struct {
- ID string `json:"id"`
- Instance string `json:"instance"`
- Name string `json:"name"`
- FSID string `json:"fsid,omitempty"`
- Health string `json:"health"`
- HealthMessage string `json:"healthMessage,omitempty"`
- TotalBytes int64 `json:"totalBytes"`
- UsedBytes int64 `json:"usedBytes"`
- AvailableBytes int64 `json:"availableBytes"`
- UsagePercent float64 `json:"usagePercent"`
- NumMons int `json:"numMons"`
- NumMgrs int `json:"numMgrs"`
- NumOSDs int `json:"numOsds"`
- NumOSDsUp int `json:"numOsdsUp"`
- NumOSDsIn int `json:"numOsdsIn"`
- NumPGs int `json:"numPGs"`
- Pools []CephPool `json:"pools,omitempty"`
- Services []CephServiceStatus `json:"services,omitempty"`
- LastUpdated time.Time `json:"lastUpdated"`
+ ID string `json:"id"`
+ Instance string `json:"instance"`
+ InstanceAliases []string `json:"instanceAliases,omitempty"`
+ Source string `json:"source,omitempty"`
+ Name string `json:"name"`
+ FSID string `json:"fsid,omitempty"`
+ Health string `json:"health"`
+ HealthMessage string `json:"healthMessage,omitempty"`
+ TotalBytes int64 `json:"totalBytes"`
+ UsedBytes int64 `json:"usedBytes"`
+ AvailableBytes int64 `json:"availableBytes"`
+ UsagePercent float64 `json:"usagePercent"`
+ NumMons int `json:"numMons"`
+ NumMgrs int `json:"numMgrs"`
+ NumOSDs int `json:"numOsds"`
+ NumOSDsUp int `json:"numOsdsUp"`
+ NumOSDsIn int `json:"numOsdsIn"`
+ NumPGs int `json:"numPGs"`
+ Pools []CephPool `json:"pools,omitempty"`
+ Services []CephServiceStatus `json:"services,omitempty"`
+ LastUpdated time.Time `json:"lastUpdated"`
}
func (c CephCluster) NormalizeCollections() CephCluster {
+ if c.InstanceAliases == nil {
+ c.InstanceAliases = []string{}
+ }
if c.Pools == nil {
c.Pools = []CephPool{}
}
@@ -4438,31 +4472,18 @@ func (s *State) UnlinkHostAgent(hostID string) bool {
}
// UpsertCephCluster inserts or updates a Ceph cluster in the state.
-// Uses ID (typically the FSID) for matching.
-func (s *State) UpsertCephCluster(cluster CephCluster) {
+// FSID identifies the physical Ceph cluster across API and host-agent reports.
+func (s *State) UpsertCephCluster(cluster CephCluster) CephCluster {
s.mu.Lock()
defer s.mu.Unlock()
- cluster = cloneCephCluster(cluster)
-
- updated := false
- for i, existing := range s.CephClusters {
- if existing.ID == cluster.ID {
- s.CephClusters[i] = cluster
- updated = true
- break
- }
- }
-
- if !updated {
- s.CephClusters = append(s.CephClusters, cluster)
- }
-
- sort.Slice(s.CephClusters, func(i, j int) bool {
- return s.CephClusters[i].Name < s.CephClusters[j].Name
- })
+ cluster = normalizeCephClusterForState(cloneCephCluster(cluster), "")
+ var stored CephCluster
+ s.CephClusters, stored = upsertCephClusterInSlice(s.CephClusters, cluster)
+ sortCephClustersForState(s.CephClusters)
s.LastUpdate = time.Now()
+ return cloneCephCluster(stored)
}
// SetHostStatus updates the status of a host if present.
@@ -4596,37 +4617,36 @@ func (s *State) UpdateStorageForInstance(instanceName string, storage []Storage)
s.LastUpdate = time.Now()
}
-// UpdateCephClustersForInstance updates Ceph cluster information for a specific instance
-func (s *State) UpdateCephClustersForInstance(instanceName string, clusters []CephCluster) {
+// UpdateCephClustersForInstance updates Proxmox-API Ceph cluster information for a specific instance.
+func (s *State) UpdateCephClustersForInstance(instanceName string, clusters []CephCluster) []CephCluster {
s.mu.Lock()
defer s.mu.Unlock()
- // Preserve clusters from other instances
filtered := make([]CephCluster, 0, len(s.CephClusters))
for _, cluster := range s.CephClusters {
- if cluster.Instance != instanceName {
- filtered = append(filtered, cluster)
+ cluster = normalizeCephClusterForState(cluster, "")
+ if cluster.Instance == instanceName && normalizeCephClusterSource(cluster.Source, cluster.Instance, "") == CephClusterSourceProxmoxAPI {
+ continue
}
+ filtered = append(filtered, cluster)
}
- // Add updated clusters (if any) for this instance
- if len(clusters) > 0 {
- filtered = append(filtered, cloneCephClusters(clusters)...)
- }
-
- // Sort for stable ordering in UI
- sort.Slice(filtered, func(i, j int) bool {
- if filtered[i].Instance == filtered[j].Instance {
- if filtered[i].Name == filtered[j].Name {
- return filtered[i].ID < filtered[j].ID
- }
- return filtered[i].Name < filtered[j].Name
+ stored := make([]CephCluster, 0, len(clusters))
+ for _, cluster := range clusters {
+ cluster = cloneCephCluster(cluster)
+ if strings.TrimSpace(cluster.Instance) == "" {
+ cluster.Instance = instanceName
}
- return filtered[i].Instance < filtered[j].Instance
- })
+ cluster = normalizeCephClusterForState(cluster, CephClusterSourceProxmoxAPI)
+ var reconciled CephCluster
+ filtered, reconciled = upsertCephClusterInSlice(filtered, cluster)
+ stored = append(stored, reconciled)
+ }
+ sortCephClustersForState(filtered)
s.CephClusters = filtered
s.LastUpdate = time.Now()
+ return cloneCephClusters(stored)
}
// UpdatePBSInstances updates the PBS instances in the state
diff --git a/internal/models/state_additional_test.go b/internal/models/state_additional_test.go
index 2a1ba7c1fe..f4fb84df2d 100644
--- a/internal/models/state_additional_test.go
+++ b/internal/models/state_additional_test.go
@@ -599,6 +599,60 @@ func TestStateUpsertCephCluster(t *testing.T) {
}
}
+func TestStateUpsertCephClusterMergesSourcesByFSID(t *testing.T) {
+ state := &State{}
+
+ state.UpsertCephCluster(CephCluster{
+ ID: "ceph-fsid-1",
+ Instance: "pve5",
+ Source: CephClusterSourceHostAgent,
+ Name: "pve5 Ceph",
+ FSID: "ceph-fsid-1",
+ Pools: []CephPool{{
+ Name: "data_replication",
+ PercentUsed: 61.1,
+ }},
+ })
+ stored := state.UpsertCephCluster(CephCluster{
+ ID: "ceph-fsid-1",
+ Instance: "pve-api",
+ Source: CephClusterSourceProxmoxAPI,
+ Name: "Ceph",
+ FSID: "ceph-fsid-1",
+ Pools: []CephPool{{
+ Name: "data_replication",
+ PercentUsed: 61.1,
+ }},
+ })
+
+ if stored.Instance != "pve-api" {
+ t.Fatalf("stored instance = %q, want API instance pve-api", stored.Instance)
+ }
+ if stored.Source != CephClusterSourceProxmoxAPI {
+ t.Fatalf("stored source = %q, want %q", stored.Source, CephClusterSourceProxmoxAPI)
+ }
+ if !containsString(stored.InstanceAliases, "pve5") {
+ t.Fatalf("stored aliases = %#v, want host-agent instance pve5", stored.InstanceAliases)
+ }
+
+ snapshot := state.GetSnapshot()
+ if len(snapshot.CephClusters) != 1 {
+ t.Fatalf("CephClusters = %#v, want one merged physical cluster", snapshot.CephClusters)
+ }
+
+ storage := StorageFromCephPool(snapshot.CephClusters[0], snapshot.CephClusters[0].Pools[0])
+ wantAliases := []string{
+ CephPoolStorageID("pve5", "data_replication"),
+ CephPoolStorageID("agent:pve5", "data_replication"),
+ CephPoolStorageID("agent:pve-api", "data_replication"),
+ }
+ for _, want := range wantAliases {
+ if !containsString(storage.AliasIDs, want) {
+ t.Fatalf("storage aliases = %#v, want %q", storage.AliasIDs, want)
+ }
+ }
+}
+
func TestStateSetHostCommandsEnabled(t *testing.T) {
state := &State{
Hosts: []Host{{ID: "h1", CommandsEnabled: false}},
diff --git a/internal/models/state_host_test.go b/internal/models/state_host_test.go
index ee02780a29..b4c297aa67 100644
--- a/internal/models/state_host_test.go
+++ b/internal/models/state_host_test.go
@@ -617,6 +617,95 @@ func TestUpdateCephClustersForInstance(t *testing.T) {
}
}
+func TestCephClusterStatePrefersProxmoxAPIByFSID(t *testing.T) {
+ state := NewState()
+
+ state.UpsertCephCluster(CephCluster{
+ ID: "fsid-123",
+ Instance: "pve5",
+ Source: CephClusterSourceHostAgent,
+ Name: "pve5 Ceph",
+ FSID: "fsid-123",
+ Pools: []CephPool{{
+ ID: 2,
+ Name: "data_replication",
+ StoredBytes: 70,
+ AvailableBytes: 30,
+ PercentUsed: 70,
+ }},
+ })
+
+ stored := state.UpdateCephClustersForInstance("prod", []CephCluster{{
+ ID: "prod-fsid-123",
+ Instance: "prod",
+ Source: CephClusterSourceProxmoxAPI,
+ Name: "Ceph",
+ FSID: "fsid-123",
+ Health: "HEALTH_OK",
+ }})
+
+ snapshot := state.GetSnapshot()
+ if len(snapshot.CephClusters) != 1 {
+ t.Fatalf("expected API and agent reports for same FSID to reconcile to one cluster, got %#v", snapshot.CephClusters)
+ }
+ cluster := snapshot.CephClusters[0]
+ if cluster.Source != CephClusterSourceProxmoxAPI || cluster.Instance != "prod" || cluster.ID != "prod-fsid-123" {
+ t.Fatalf("expected Proxmox API cluster to be canonical, got %+v", cluster)
+ }
+ if !containsString(cluster.InstanceAliases, "pve5") {
+ t.Fatalf("expected agent instance alias to be preserved, got %#v", cluster.InstanceAliases)
+ }
+ if len(cluster.Pools) != 1 || cluster.Pools[0].Name != "data_replication" {
+ t.Fatalf("expected agent pool data to supplement API status-only cluster, got %#v", cluster.Pools)
+ }
+ if len(stored) != 1 || stored[0].Instance != "prod" || !containsString(stored[0].InstanceAliases, "pve5") {
+ t.Fatalf("stored clusters did not return reconciled canonical cluster: %#v", stored)
+ }
+}
+
+func TestUpsertCephClusterKeepsProxmoxAPIWhenAgentRefreshArrives(t *testing.T) {
+ state := NewState()
+
+ state.UpdateCephClustersForInstance("prod", []CephCluster{{
+ ID: "prod-fsid-123",
+ Instance: "prod",
+ Source: CephClusterSourceProxmoxAPI,
+ Name: "Ceph",
+ FSID: "fsid-123",
+ Health: "HEALTH_OK",
+ Pools: []CephPool{{
+ ID: 2,
+ Name: "data_replication",
+ StoredBytes: 60,
+ AvailableBytes: 40,
+ PercentUsed: 60,
+ }},
+ }})
+
+ stored := state.UpsertCephCluster(CephCluster{
+ ID: "fsid-123",
+ Instance: "pve5",
+ Source: CephClusterSourceHostAgent,
+ Name: "pve5 Ceph",
+ FSID: "fsid-123",
+ })
+
+ snapshot := state.GetSnapshot()
+ if len(snapshot.CephClusters) != 1 {
+ t.Fatalf("expected agent refresh to merge with API cluster, got %#v", snapshot.CephClusters)
+ }
+ cluster := snapshot.CephClusters[0]
+ if cluster.Source != CephClusterSourceProxmoxAPI || cluster.Instance != "prod" {
+ t.Fatalf("expected API cluster to remain canonical, got %+v", cluster)
+ }
+ if !containsString(cluster.InstanceAliases, "pve5") {
+ t.Fatalf("expected agent instance alias to be preserved, got %#v", cluster.InstanceAliases)
+ }
+ if stored.Source != CephClusterSourceProxmoxAPI || stored.Instance != "prod" {
+ t.Fatalf("expected upsert to return canonical API cluster, got %+v", stored)
+ }
+}
+
func TestUpdateBackupTasksForInstance(t *testing.T) {
state := NewState()
diff --git a/internal/monitoring/ceph.go b/internal/monitoring/ceph.go
index befe1f14cc..4fa97e28f9 100644
--- a/internal/monitoring/ceph.go
+++ b/internal/monitoring/ceph.go
@@ -59,8 +59,10 @@ func (m *Monitor) pollCephCluster(ctx context.Context, instanceName string, clie
cluster.ID = instanceName
}
- m.state.UpdateCephClustersForInstance(instanceName, []models.CephCluster{cluster})
- m.checkCephPoolStorage(cluster)
+ storedClusters := m.state.UpdateCephClustersForInstance(instanceName, []models.CephCluster{cluster})
+ for _, storedCluster := range storedClusters {
+ m.checkCephPoolStorage(storedCluster)
+ }
}
func (m *Monitor) checkCephPoolStorage(cluster models.CephCluster) {
@@ -161,6 +163,7 @@ func buildCephClusterModel(instanceName string, status *proxmox.CephStatus, df *
cluster := models.CephCluster{
ID: clusterID,
Instance: instanceName,
+ Source: models.CephClusterSourceProxmoxAPI,
Name: "Ceph",
FSID: status.FSID,
Health: status.Health.Status,
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index 33d4991936..04179e9826 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -2015,13 +2015,14 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// If host reports Ceph data, also update the global CephClusters state
if report.Ceph != nil {
cephCluster := convertAgentCephToGlobalCluster(report.Ceph, hostname, identifier, timestamp)
- m.state.UpsertCephCluster(cephCluster)
+ storedCephCluster := m.state.UpsertCephCluster(cephCluster)
log.Debug().
Str("hostId", identifier).
Str("hostname", hostname).
- Str("fsid", cephCluster.FSID).
- Str("health", cephCluster.Health).
- Int("osds", cephCluster.NumOSDs).
+ Str("fsid", storedCephCluster.FSID).
+ Str("source", storedCephCluster.Source).
+ Str("health", storedCephCluster.Health).
+ Int("osds", storedCephCluster.NumOSDs).
Msg("Updated Ceph cluster from host agent")
// #1341: the agent-reported Ceph cluster used to land in state but
@@ -2030,7 +2031,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// agent-prefixed pool IDs (e.g. agent:hostname-ceph-pool-foo) were
// silently dormant. Run the alert check here so agent-sourced pools
// actually fire.
- m.checkCephPoolStorage(cephCluster)
+ m.checkCephPoolStorage(storedCephCluster)
}
if m.alertManager != nil {
diff --git a/internal/monitoring/monitor_helpers.go b/internal/monitoring/monitor_helpers.go
index 958c0fc44a..4ee894bad0 100644
--- a/internal/monitoring/monitor_helpers.go
+++ b/internal/monitoring/monitor_helpers.go
@@ -707,7 +707,8 @@ func convertAgentCephToGlobalCluster(ceph *agentshost.CephCluster, hostname, hos
cluster := models.CephCluster{
ID: clusterID,
- Instance: "agent:" + hostname,
+ Instance: hostname,
+ Source: models.CephClusterSourceHostAgent,
Name: hostname + " Ceph",
FSID: ceph.FSID,
Health: strings.TrimPrefix(ceph.Health.Status, "HEALTH_"),
diff --git a/internal/monitoring/monitor_helpers_test.go b/internal/monitoring/monitor_helpers_test.go
index 2fdedfd682..cb69b83c46 100644
--- a/internal/monitoring/monitor_helpers_test.go
+++ b/internal/monitoring/monitor_helpers_test.go
@@ -5,6 +5,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
)
@@ -507,8 +508,11 @@ func TestConvertAgentCephToGlobalCluster_BasicFields(t *testing.T) {
if result.NumOSDs != 6 || result.NumOSDsUp != 6 {
t.Error("OSD counts not copied")
}
- if result.Instance != "agent:server1" {
- t.Errorf("expected 'agent:server1', got %q", result.Instance)
+ if result.Instance != "server1" {
+ t.Errorf("expected 'server1', got %q", result.Instance)
+ }
+ if result.Source != models.CephClusterSourceHostAgent {
+ t.Errorf("expected host-agent source, got %q", result.Source)
}
}
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index c7a11b0e11..6742270489 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -2335,12 +2335,11 @@ func TestApplyHostReport_FallbackIdentifier(t *testing.T) {
}
}
-// Regression for #1341: when Ceph is reported by a Pulse host-agent (not the
-// Proxmox API), the agent-sourced cluster used to land in state but the
-// pool alert evaluation only ran in the Proxmox-API polling path. Per-pool
-// overrides keyed against the agent-prefixed pool ID (e.g.
-// `agent:hostname-ceph-pool-name`) were silently dormant. Verify the
-// agent path now fires checkCephPoolStorage so overrides match.
+// Regression for #1341: when Ceph is reported by a Pulse host-agent, pool
+// alert evaluation must run even when there is no Proxmox API Ceph source.
+// Existing per-pool overrides keyed against the older agent-prefixed pool ID
+// still have to resolve after the pool's canonical ID drops the agent routing
+// prefix.
func TestApplyHostReportFiresCephPoolAlertsForAgentSourcedCluster(t *testing.T) {
monitor := &Monitor{
state: models.NewState(),
@@ -2398,7 +2397,7 @@ func TestApplyHostReportFiresCephPoolAlertsForAgentSourcedCluster(t *testing.T)
active := monitor.alertManager.GetActiveAlerts()
found := false
for _, alert := range active {
- if alert.ResourceID == "agent:pve5-ceph-pool-data_replication" && alert.Type == "usage" {
+ if alert.ResourceID == "pve5-ceph-pool-data_replication" && alert.Type == "usage" {
found = true
if alert.Threshold != 50 {
t.Fatalf("Ceph pool alert fired but threshold = %.1f, want 50 (override)", alert.Threshold)
@@ -2411,6 +2410,100 @@ func TestApplyHostReportFiresCephPoolAlertsForAgentSourcedCluster(t *testing.T)
for _, a := range active {
ids = append(ids, a.ID)
}
- t.Fatalf("expected agent-sourced Ceph pool alert to fire under override at 61.1%% usage; got %d active alerts: %v", len(active), ids)
+ t.Fatalf("expected agent-sourced Ceph pool alert to fire under legacy override at 61.1%% usage; got %d active alerts: %v", len(active), ids)
}
}
+
+func TestApplyHostReportMergesAgentCephWithProxmoxAPICluster(t *testing.T) {
+ monitor := &Monitor{
+ state: models.NewState(),
+ alertManager: alerts.NewManager(),
+ hostTokenBindings: make(map[string]string),
+ config: &config.Config{},
+ rateTracker: NewRateTracker(),
+ }
+ t.Cleanup(func() { monitor.alertManager.Stop() })
+
+ overrideTrigger := alerts.HysteresisThreshold{Trigger: 50, Clear: 45}
+ cfg := monitor.alertManager.GetConfig()
+ cfg.MinimumDelta = 0
+ if cfg.TimeThresholds == nil {
+ cfg.TimeThresholds = make(map[string]int)
+ }
+ cfg.TimeThresholds["storage"] = 0
+ cfg.StorageDefault = alerts.HysteresisThreshold{Trigger: 95, Clear: 90}
+ cfg.Overrides = map[string]alerts.ThresholdConfig{
+ "agent:pve5-ceph-pool-data_replication": {Usage: &overrideTrigger},
+ }
+ monitor.alertManager.UpdateConfig(cfg)
+
+ monitor.state.UpdateCephClustersForInstance("prod", []models.CephCluster{{
+ ID: "prod-ceph-fsid-1341",
+ Instance: "prod",
+ Source: models.CephClusterSourceProxmoxAPI,
+ Name: "Ceph",
+ FSID: "ceph-fsid-1341",
+ Health: "HEALTH_OK",
+ }})
+
+ report := agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: "agent-ceph",
+ Version: "1.0.0",
+ IntervalSeconds: 30,
+ },
+ Host: agentshost.HostInfo{
+ ID: "pve5-host",
+ Hostname: "pve5",
+ Platform: "linux",
+ },
+ Timestamp: time.Now().UTC(),
+ Ceph: &agentshost.CephCluster{
+ FSID: "ceph-fsid-1341",
+ Health: agentshost.CephHealth{Status: "HEALTH_OK"},
+ Pools: []agentshost.CephPool{
+ {
+ ID: 2,
+ Name: "data_replication",
+ BytesUsed: 611,
+ BytesAvailable: 389,
+ PercentUsed: 61.1,
+ },
+ },
+ },
+ }
+
+ if _, err := monitor.ApplyHostReport(report, nil); err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+
+ snapshot := monitor.state.GetSnapshot()
+ if len(snapshot.CephClusters) != 1 {
+ t.Fatalf("expected API and agent Ceph reports to reconcile to one cluster, got %#v", snapshot.CephClusters)
+ }
+ cluster := snapshot.CephClusters[0]
+ if cluster.Source != models.CephClusterSourceProxmoxAPI || cluster.Instance != "prod" {
+ t.Fatalf("expected API cluster to remain canonical, got %+v", cluster)
+ }
+ foundAlias := false
+ for _, alias := range cluster.InstanceAliases {
+ if alias == "pve5" {
+ foundAlias = true
+ break
+ }
+ }
+ if !foundAlias {
+ t.Fatalf("expected agent hostname to be preserved as an alias, got %#v", cluster.InstanceAliases)
+ }
+
+ active := monitor.alertManager.GetActiveAlerts()
+ for _, alert := range active {
+ if alert.ResourceID == "prod-ceph-pool-data_replication" && alert.Type == "usage" {
+ if alert.Threshold != 50 {
+ t.Fatalf("Ceph pool alert threshold = %.1f, want legacy agent override 50", alert.Threshold)
+ }
+ return
+ }
+ }
+ t.Fatalf("expected canonical API Ceph pool alert using legacy agent override, got active alerts: %#v", active)
+}