Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
package alerts
import (
"testing"
"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/operationaltrust"
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
"github.com/rcourtman/pulse-go-rewrite/internal/truenas"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
func TestSyncUnifiedResourceIncidentsCreatesAndClearsAlerts(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "storage:tank",
Type: unifiedresources.ResourceTypeStorage,
Name: "tank",
ParentName: "truenas-main",
Sources: []unifiedresources.DataSource{unifiedresources.SourceTrueNAS},
Storage: &unifiedresources.StorageMeta{
Platform: "truenas",
Topology: "pool",
Protection: "zfs",
IsZFS: true,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas",
NativeID: "alert-1",
Code: "truenas_volume_status",
Severity: storagehealth.RiskWarning,
Summary: "Pool tank is DEGRADED",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := buildCanonicalStateID(resource.ID, "alertspec:provider-incident:6d90d4cfe0dab6cc")
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if alert.Type != "zfs-pool-state" {
t.Fatalf("alert type = %q, want zfs-pool-state", alert.Type)
}
if alert.ResourceID != resource.ID {
t.Fatalf("resource id = %q, want %q", alert.ResourceID, resource.ID)
}
if alert.Node != "truenas-main" {
t.Fatalf("node = %q, want truenas-main", alert.Node)
}
if got := alert.Metadata["canonicalAlertKind"]; got != "provider-incident" {
t.Fatalf("canonicalAlertKind = %v, want provider-incident", got)
}
if got := alert.Metadata["canonicalSpecID"]; got == nil || got == "" {
t.Fatalf("expected canonicalSpecID metadata, got %v", got)
}
if alert.CanonicalSpecID == "" {
t.Fatal("expected CanonicalSpecID field to be populated")
}
if alert.CanonicalKind != "provider-incident" {
t.Fatalf("CanonicalKind = %q, want provider-incident", alert.CanonicalKind)
}
if alert.CanonicalState != resource.ID+"::"+alert.CanonicalSpecID {
t.Fatalf("CanonicalState = %q, want %q", alert.CanonicalState, resource.ID+"::"+alert.CanonicalSpecID)
}
if got := alert.Metadata["canonicalSuppressionKeys"]; got == nil {
t.Fatalf("expected canonicalSuppressionKeys metadata")
}
m.SyncUnifiedResourceIncidents(nil)
assertAlertMissing(t, m, alertID)
}
func TestSyncUnifiedResourceIncidentsAttachesFirstClassIncidentEvidence(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "storage:tank",
Type: unifiedresources.ResourceTypeStorage,
Name: "tank",
ParentName: "truenas-main",
Sources: []unifiedresources.DataSource{unifiedresources.SourceTrueNAS},
Storage: &unifiedresources.StorageMeta{
Platform: "truenas",
Topology: "pool",
Protection: "zfs",
IsZFS: true,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas",
NativeID: "alert-1",
Code: "truenas_volume_status",
Severity: storagehealth.RiskWarning,
Source: "alerts",
Summary: "Pool tank is DEGRADED",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := buildCanonicalStateID(resource.ID, "alertspec:provider-incident:6d90d4cfe0dab6cc")
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if len(alert.Evidence) != 1 {
t.Fatalf("evidence count = %d, want 1", len(alert.Evidence))
}
envelope := alert.Evidence[0]
if envelope.Completeness != operationaltrust.EvidenceComplete {
t.Fatalf("completeness = %q, want complete (legacy partial shim must not back a directly observed incident)", envelope.Completeness)
}
if envelope.Confidence != operationaltrust.EvidenceConfirmed {
t.Fatalf("confidence = %q, want confirmed", envelope.Confidence)
}
if envelope.Source.Provider != "truenas" || envelope.Source.Collector != "alerts" {
t.Fatalf("source = %+v, want provider truenas / collector alerts", envelope.Source)
}
if envelope.Subject.ResourceID != resource.ID {
t.Fatalf("subject resource = %q, want %q", envelope.Subject.ResourceID, resource.ID)
}
if envelope.PayloadRef == nil || envelope.PayloadRef.Kind != "unified-incident-digest" {
t.Fatalf("payload ref = %+v, want unified-incident-digest", envelope.PayloadRef)
}
if alert.OperationalRecord == nil || len(alert.OperationalRecord.EvidenceIDs) != 1 ||
alert.OperationalRecord.EvidenceIDs[0] != envelope.ID {
t.Fatalf("operational record evidence ids = %+v, want [%s]", alert.OperationalRecord, envelope.ID)
}
// A later sync re-observes the incident: the live alert keeps accumulating
// the freshly observed envelopes instead of pinning the raise-time one.
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
m.mu.RLock()
refreshed := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if len(refreshed.Evidence) < 1 {
t.Fatalf("refreshed evidence count = %d, want >= 1", len(refreshed.Evidence))
}
latest := refreshed.Evidence[len(refreshed.Evidence)-1]
if latest.ObservedAt.Before(envelope.ObservedAt) {
t.Fatalf("latest evidence observedAt %v predates raise-time %v", latest.ObservedAt, envelope.ObservedAt)
}
if latest.Completeness != operationaltrust.EvidenceComplete {
t.Fatalf("refreshed completeness = %q, want complete", latest.Completeness)
}
}
func TestSyncUnifiedResourceIncidentsRoutesAttachedCheckThroughSourceOwnedLifecycle(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
observedAt := time.Date(2026, 7, 19, 2, 0, 0, 0, time.UTC)
source := operationaltrust.EvidenceSource{
Provider: "availability",
Collector: "availability-poller",
}
subject := operationaltrust.EvidenceSubject{ResourceID: "availability:energy-meter"}
evidenceID, err := operationaltrust.NewEvidenceID(source, subject, observedAt, "energy-meter")
if err != nil {
t.Fatalf("NewEvidenceID() error = %v", err)
}
validUntil := observedAt.Add(2 * time.Minute)
host := unifiedresources.Resource{
ID: "docker-service:api",
Type: unifiedresources.ResourceTypeDockerService,
Name: "API",
Sources: []unifiedresources.DataSource{unifiedresources.SourceDocker, unifiedresources.SourceAvailability},
Availability: &unifiedresources.AvailabilityData{
TargetID: "energy-meter",
Address: "192.0.2.44",
Protocol: "icmp",
Enabled: true,
Available: false,
ConsecutiveFailures: 2,
CorrelationState: unifiedresources.AvailabilityCorrelationAttached,
},
}
check := unifiedresources.Resource{
ID: "availability:energy-meter",
Type: unifiedresources.ResourceTypeNetworkEndpoint,
Name: "Energy meter",
Sources: []unifiedresources.DataSource{unifiedresources.SourceAvailability},
Availability: &unifiedresources.AvailabilityData{
TargetID: "energy-meter",
Address: "192.0.2.44",
Protocol: "icmp",
Enabled: true,
Available: false,
ConsecutiveFailures: 2,
FailureThreshold: 2,
CorrelationState: unifiedresources.AvailabilityCorrelationAttached,
Evidence: &operationaltrust.EvidenceEnvelope{
ID: evidenceID,
Source: source,
Subject: subject,
ObservedAt: observedAt,
IngestedAt: observedAt,
ValidUntil: &validUntil,
Completeness: operationaltrust.EvidenceComplete,
Confidence: operationaltrust.EvidenceConfirmed,
Permissions: operationaltrust.EvidencePermissionsSufficient,
PayloadRef: &operationaltrust.EvidencePayloadRef{
Kind: "availability-target",
ID: "energy-meter",
},
},
},
AvailabilityChecks: []unifiedresources.AvailabilityData{{
TargetID: "energy-meter",
Address: "192.0.2.44",
Protocol: "icmp",
Enabled: true,
Available: false,
ConsecutiveFailures: 2,
FailureThreshold: 2,
CorrelationState: unifiedresources.AvailabilityCorrelationAttached,
Evidence: &operationaltrust.EvidenceEnvelope{
ID: evidenceID,
Source: source,
Subject: subject,
ObservedAt: observedAt,
IngestedAt: observedAt,
ValidUntil: &validUntil,
Completeness: operationaltrust.EvidenceComplete,
Confidence: operationaltrust.EvidenceConfirmed,
Permissions: operationaltrust.EvidencePermissionsSufficient,
PayloadRef: &operationaltrust.EvidencePayloadRef{
Kind: "availability-target",
ID: "energy-meter",
},
},
}},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "availability",
NativeID: "energy-meter",
Code: "availability_unreachable",
Severity: storagehealth.RiskCritical,
Source: "availability",
Summary: "Energy meter is unreachable by ICMP probe",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{host, check})
alertID := unifiedIncidentAlertID(check, check.Incidents[0])
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if alert.Type != "resource-incident" {
t.Fatalf("alert type = %q, want resource-incident", alert.Type)
}
if alert.ResourceID != check.ID {
t.Fatalf("resource id = %q, want source-owned check %q", alert.ResourceID, check.ID)
}
if alert.Instance != "Availability" {
t.Fatalf("instance = %q, want Availability", alert.Instance)
}
if got := alert.Metadata["incidentCategory"]; got != unifiedresources.IncidentCategoryAvailability {
t.Fatalf("incidentCategory = %v, want %q", got, unifiedresources.IncidentCategoryAvailability)
}
if got := alert.Metadata["incidentProvider"]; got != "availability" {
t.Fatalf("incidentProvider = %v, want availability", got)
}
if len(alert.Evidence) != 1 || alert.Evidence[0].ID != evidenceID {
t.Fatalf("alert evidence = %+v, want %q", alert.Evidence, evidenceID)
}
if alert.OperationalRecord == nil ||
len(alert.OperationalRecord.EvidenceIDs) != 1 ||
alert.OperationalRecord.EvidenceIDs[0] != evidenceID {
t.Fatalf("operational record = %+v, want canonical availability evidence", alert.OperationalRecord)
}
}
func TestSyncUnifiedResourceIncidentsKeepsInstanceScopedNodeDisplayNames(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.UpdateNodeDisplayName("cluster-a", "pve", "Alpha")
m.UpdateNodeDisplayName("cluster-b", "pve", "Beta")
resourceA := unifiedresources.Resource{
ID: "vm:app-a",
Type: unifiedresources.ResourceTypeVM,
Name: "app-a",
ParentName: "pve",
Proxmox: &unifiedresources.ProxmoxData{Instance: "cluster-a"},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "incident-a",
Code: "guest_unreachable",
Severity: storagehealth.RiskWarning,
Summary: "VM app-a is unreachable",
}},
}
resourceB := unifiedresources.Resource{
ID: "vm:app-b",
Type: unifiedresources.ResourceTypeVM,
Name: "app-b",
ParentName: "pve",
Proxmox: &unifiedresources.ProxmoxData{Instance: "cluster-b"},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "incident-b",
Code: "guest_unreachable",
Severity: storagehealth.RiskWarning,
Summary: "VM app-b is unreachable",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resourceA, resourceB})
m.UpdateNodeDisplayName("cluster-a", "pve", "Alpha Updated")
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resourceA, resourceB})
alertIDA := unifiedIncidentAlertID(resourceA, resourceA.Incidents[0])
alertIDB := unifiedIncidentAlertID(resourceB, resourceB.Incidents[0])
m.mu.RLock()
alertA := testRequireActiveAlert(t, m, alertIDA)
alertB := testRequireActiveAlert(t, m, alertIDB)
m.mu.RUnlock()
if alertA.NodeDisplayName != "Alpha Updated" {
t.Fatalf("resourceA node display name = %q, want %q", alertA.NodeDisplayName, "Alpha Updated")
}
if alertB.NodeDisplayName != "Beta" {
t.Fatalf("resourceB node display name = %q, want %q", alertB.NodeDisplayName, "Beta")
}
gotByResourceID := make(map[string]Alert)
for _, alert := range m.GetActiveAlerts() {
gotByResourceID[alert.ResourceID] = alert
}
if gotByResourceID[resourceA.ID].NodeDisplayName != "Alpha Updated" {
t.Fatalf("GetActiveAlerts resourceA node display name = %q, want %q", gotByResourceID[resourceA.ID].NodeDisplayName, "Alpha Updated")
}
if gotByResourceID[resourceB.ID].NodeDisplayName != "Beta" {
t.Fatalf("GetActiveAlerts resourceB node display name = %q, want %q", gotByResourceID[resourceB.ID].NodeDisplayName, "Beta")
}
}
func TestSyncUnifiedResourceIncidentsIncludesConsumerImpact(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "storage:local-lvm",
Type: unifiedresources.ResourceTypeStorage,
Name: "local-lvm",
ParentName: "pve1",
Storage: &unifiedresources.StorageMeta{
Type: "lvmthin",
ConsumerCount: 3,
ConsumerTypes: []string{"vm", "system-container"},
TopConsumers: []unifiedresources.StorageConsumerMeta{
{Name: "app01", ResourceType: unifiedresources.ResourceTypeVM, ResourceID: "vm-101", DiskCount: 1},
{Name: "media01", ResourceType: unifiedresources.ResourceTypeSystemContainer, ResourceID: "lxc-200", DiskCount: 1},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "storage-risk-1",
Code: "capacity_runway_low",
Severity: storagehealth.RiskWarning,
Summary: "Storage local-lvm is running low on free space",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := "unified-incident-storage-local-lvm-pulse-storage-risk-1-capacity-runway-low"
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
wantMessage := "Storage local-lvm is running low on free space. Affects 3 dependent resources: app01, media01, and 1 more"
if alert.Message != wantMessage {
t.Fatalf("message = %q, want %q", alert.Message, wantMessage)
}
if got := alert.Metadata["consumerCount"]; got != 3 {
t.Fatalf("consumerCount = %v, want 3", got)
}
if got := alert.Metadata["consumerImpactSummary"]; got != "Affects 3 dependent resources: app01, media01, and 1 more" {
t.Fatalf("consumerImpactSummary = %v", got)
}
if got := alert.Metadata["incidentCategory"]; got != unifiedresources.IncidentCategoryCapacity {
t.Fatalf("incidentCategory = %v", got)
}
if got := alert.Metadata["incidentLabel"]; got != "Capacity Pressure" {
t.Fatalf("incidentLabel = %v", got)
}
if got := alert.Metadata["incidentPriority"]; got != 3203 {
t.Fatalf("incidentPriority = %v", got)
}
if got := alert.Metadata["incidentImpactSummary"]; got != "Affects 3 dependent resources: app01, media01, and 1 more" {
t.Fatalf("incidentImpactSummary = %v", got)
}
if got := alert.Metadata["incidentUrgency"]; got != unifiedresources.IncidentUrgencyToday {
t.Fatalf("incidentUrgency = %v", got)
}
if got := alert.Metadata["incidentAction"]; got != "Plan cleanup or capacity expansion soon" {
t.Fatalf("incidentAction = %v", got)
}
if got := alert.Metadata["topConsumerNames"]; got == nil {
t.Fatal("expected topConsumerNames metadata")
}
}
func TestSyncUnifiedResourceIncidentsSupportsVMwareVMs(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "vm:app-01",
Type: unifiedresources.ResourceTypeVM,
Name: "app-01",
VMware: &unifiedresources.VMwareData{
ConnectionID: "vc-1",
ConnectionName: "Lab VC",
VCenterHost: "vc.lab.local",
EntityType: "vm",
ManagedObjectID: "vm-201",
OverallStatus: "red",
ActiveAlarmCount: 1,
ActiveAlarmSummary: "VM replication fault (red)",
RecentTaskCount: 1,
RecentTaskSummary: "Create snapshot (success)",
SnapshotCount: 2,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "vmware",
NativeID: "alarm-21",
Code: "vmware_alarm_state",
Severity: storagehealth.RiskCritical,
Source: string(unifiedresources.SourceVMware),
Summary: "VM vm-201 has VMware alarm VM replication fault (red)",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := unifiedIncidentAlertID(resource, resource.Incidents[0])
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if alert.Type != "resource-incident" {
t.Fatalf("alert type = %q, want resource-incident", alert.Type)
}
if alert.Message != "VM vm-201 has VMware alarm VM replication fault (red)" {
t.Fatalf("message = %q", alert.Message)
}
if got := alert.Metadata["incidentLabel"]; got != "VM Health Issue" {
t.Fatalf("incidentLabel = %v, want VM Health Issue", got)
}
if got := alert.Metadata["incidentAction"]; got != "Investigate resource health immediately" {
t.Fatalf("incidentAction = %v, want Investigate resource health immediately", got)
}
if got := alert.Metadata["vmwareConnectionId"]; got != "vc-1" {
t.Fatalf("vmwareConnectionId = %v, want vc-1", got)
}
if got := alert.Metadata["vmwareActiveAlarmSummary"]; got != "VM replication fault (red)" {
t.Fatalf("vmwareActiveAlarmSummary = %v", got)
}
if got := alert.Metadata["vmwareSnapshotCount"]; got != 2 {
t.Fatalf("vmwareSnapshotCount = %v, want 2", got)
}
}
func TestUnifiedIncidentAlertTypeClassifiesCertificateIncidents(t *testing.T) {
resource := unifiedresources.Resource{Type: unifiedresources.ResourceTypeNetworkEndpoint}
incident := unifiedresources.ResourceIncident{Code: "certificate_expiring"}
if got := unifiedIncidentAlertType(resource, incident); got != "certificate" {
t.Fatalf("alert type = %q, want certificate", got)
}
}
func TestSyncUnifiedResourceIncidentsMarksBackupTargetExposure(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "storage:backup-store",
Type: unifiedresources.ResourceTypeStorage,
Name: "backup-store",
ParentName: "pbs-main",
Storage: &unifiedresources.StorageMeta{
Type: "pbs-datastore",
Platform: "pbs",
Topology: "datastore",
Protection: "backup-repository",
ContentTypes: []string{"backup"},
ConsumerCount: 2,
ConsumerTypes: []string{"vm", "system-container"},
TopConsumers: []unifiedresources.StorageConsumerMeta{
{Name: "app01", ResourceType: unifiedresources.ResourceTypeVM, ResourceID: "vm-101", DiskCount: 1},
{Name: "media01", ResourceType: unifiedresources.ResourceTypeSystemContainer, ResourceID: "lxc-200", DiskCount: 1},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "backup-risk-1",
Code: "backup_target_degraded",
Severity: storagehealth.RiskCritical,
Summary: "Backup datastore backup-store is degraded",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := "unified-incident-storage-backup-store-pulse-backup-risk-1-backup-target-degraded"
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if alert.Type != "backup-storage-incident" {
t.Fatalf("alert type = %q, want backup-storage-incident", alert.Type)
}
wantMessage := "Backup datastore backup-store is degraded. Puts backups for 2 protected workloads at risk: app01, media01"
if alert.Message != wantMessage {
t.Fatalf("message = %q, want %q", alert.Message, wantMessage)
}
if got := alert.Metadata["backupTarget"]; got != true {
t.Fatalf("backupTarget = %v, want true", got)
}
if got := alert.Metadata["protectedWorkloadCount"]; got != 2 {
t.Fatalf("protectedWorkloadCount = %v, want 2", got)
}
if got := alert.Metadata["protectedWorkloadSummary"]; got != "Puts backups for 2 protected workloads at risk: app01, media01" {
t.Fatalf("protectedWorkloadSummary = %v", got)
}
if got := alert.Metadata["incidentCategory"]; got != unifiedresources.IncidentCategoryRecoverability {
t.Fatalf("incidentCategory = %v", got)
}
if got := alert.Metadata["incidentLabel"]; got != "Backup Coverage At Risk" {
t.Fatalf("incidentLabel = %v", got)
}
if got := alert.Metadata["incidentPriority"]; got != 4502 {
t.Fatalf("incidentPriority = %v", got)
}
if got := alert.Metadata["incidentImpactSummary"]; got != "Puts backups for 2 protected workloads at risk: app01, media01" {
t.Fatalf("incidentImpactSummary = %v", got)
}
if got := alert.Metadata["incidentUrgency"]; got != unifiedresources.IncidentUrgencyNow {
t.Fatalf("incidentUrgency = %v", got)
}
if got := alert.Metadata["incidentAction"]; got != "Restore backup target health immediately to protect recoverability" {
t.Fatalf("incidentAction = %v", got)
}
}
func TestSyncUnifiedResourceIncidentsMarksPBSBackupPosture(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "pbs:main",
Type: unifiedresources.ResourceTypePBS,
Name: "pbs-main",
PBS: &unifiedresources.PBSData{
Hostname: "pbs-main.local",
DatastoreCount: 2,
Datastores: []unifiedresources.PBSDatastoreMeta{
{Name: "fast", Status: "ERROR", Total: 100, Used: 96},
{Name: "archive", Status: "online", Total: 100, Used: 40},
},
ProtectedWorkloadCount: 2,
ProtectedWorkloadTypes: []string{"system-container", "vm"},
ProtectedWorkloadNames: []string{"media01", "app01"},
StorageRisk: &unifiedresources.StorageRisk{
Level: storagehealth.RiskCritical,
Reasons: []unifiedresources.StorageRiskReason{
{Code: "pbs_datastore_state", Severity: storagehealth.RiskCritical, Summary: "PBS datastore fast is ERROR"},
},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "pbs-instance:pbs-main:pbs_datastore_state",
Code: "pbs_datastore_state",
Severity: storagehealth.RiskCritical,
Summary: "PBS datastore fast is ERROR",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := "unified-incident-pbs-main-pulse-pbs-instance-pbs-main-pbs-datastore-state-pbs-datastore-state"
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if alert.Type != "backup-posture-incident" {
t.Fatalf("alert type = %q, want backup-posture-incident", alert.Type)
}
wantMessage := "Backup server pbs-main has degraded datastore availability. Affects 1 backup datastore: fast"
if alert.Message != wantMessage {
t.Fatalf("message = %q, want %q", alert.Message, wantMessage)
}
if got := alert.Metadata["backupServer"]; got != true {
t.Fatalf("backupServer = %v, want true", got)
}
if got := alert.Metadata["affectedDatastoreCount"]; got != 1 {
t.Fatalf("affectedDatastoreCount = %v, want 1", got)
}
if got := alert.Metadata["protectedWorkloadCount"]; got != 2 {
t.Fatalf("protectedWorkloadCount = %v, want 2", got)
}
if got := alert.Metadata["consumerCount"]; got != 2 {
t.Fatalf("consumerCount = %v, want 2", got)
}
if got := alert.Metadata["protectedWorkloadSummary"]; got != "Puts backups for 2 protected workloads at risk: media01, app01" {
t.Fatalf("protectedWorkloadSummary = %v", got)
}
if got := alert.Metadata["incidentCategory"]; got != unifiedresources.IncidentCategoryRecoverability {
t.Fatalf("incidentCategory = %v", got)
}
if got := alert.Metadata["incidentLabel"]; got != "Backup Coverage At Risk" {
t.Fatalf("incidentLabel = %v", got)
}
if got := alert.Metadata["incidentPriority"]; got != 4502 {
t.Fatalf("incidentPriority = %v", got)
}
if got := alert.Metadata["incidentImpactSummary"]; got != "Puts backups for 2 protected workloads at risk: media01, app01" {
t.Fatalf("incidentImpactSummary = %v", got)
}
if got := alert.Metadata["incidentUrgency"]; got != unifiedresources.IncidentUrgencyNow {
t.Fatalf("incidentUrgency = %v", got)
}
if got := alert.Metadata["incidentAction"]; got != "Restore backup target health immediately to protect recoverability" {
t.Fatalf("incidentAction = %v", got)
}
}
func TestSyncUnifiedResourceIncidentsSuppressesRedundantParentAndChildAlerts(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
agentID := "agent:truenas-main"
storageID := "storage:tank"
resources := []unifiedresources.Resource{
{
ID: agentID,
Type: unifiedresources.ResourceTypeAgent,
Name: "truenas-main",
Sources: []unifiedresources.DataSource{unifiedresources.SourceTrueNAS},
TrueNAS: &unifiedresources.TrueNASData{Hostname: "truenas-main"},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas",
NativeID: "alert-1",
Code: "truenas_volume_status",
Severity: storagehealth.RiskCritical,
Summary: "Pool tank is FAULTED",
}},
},
{
ID: storageID,
Type: unifiedresources.ResourceTypeStorage,
Name: "tank",
ParentID: &agentID,
Storage: &unifiedresources.StorageMeta{
Platform: "truenas",
Topology: "pool",
IsZFS: true,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas",
NativeID: "alert-1",
Code: "truenas_volume_status",
Severity: storagehealth.RiskCritical,
Summary: "Pool tank is FAULTED",
}},
},
{
ID: "disk:sda",
Type: unifiedresources.ResourceTypePhysicalDisk,
Name: "sda",
ParentID: &storageID,
PhysicalDisk: &unifiedresources.PhysicalDiskMeta{
DevPath: "/dev/sda",
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas",
NativeID: "alert-1",
Code: "truenas_volume_status",
Severity: storagehealth.RiskCritical,
Summary: "Pool tank is FAULTED",
}},
},
}
m.SyncUnifiedResourceIncidents(resources)
active := m.GetActiveAlerts()
if len(active) != 1 {
t.Fatalf("expected only 1 active alert after parent/child suppression, got %d: %+v", len(active), active)
}
if active[0].Type != "zfs-pool-state" {
t.Fatalf("alert type = %q, want zfs-pool-state", active[0].Type)
}
if active[0].ResourceID != storageID {
t.Fatalf("resource id = %q, want %q", active[0].ResourceID, storageID)
}
}
func TestSyncUnifiedResourceIncidentsSuppressesPBSDatastoreChildWhenParentRollsUp(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
parentID := "pbs:main"
childID := "storage:fast"
resources := []unifiedresources.Resource{
{
ID: parentID,
Type: unifiedresources.ResourceTypePBS,
Name: "pbs-main",
PBS: &unifiedresources.PBSData{
DatastoreCount: 1,
Datastores: []unifiedresources.PBSDatastoreMeta{
{Name: "fast", Status: "ERROR", Total: 100, Used: 96},
},
ProtectedWorkloadCount: 2,
ProtectedWorkloadNames: []string{"media01", "app01"},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "pbs-instance:pbs-main:pbs_datastore_state",
Code: "pbs_datastore_state",
Severity: storagehealth.RiskCritical,
Summary: "PBS datastore fast is ERROR",
}},
},
{
ID: childID,
Type: unifiedresources.ResourceTypeStorage,
Name: "fast",
ParentID: &parentID,
Storage: &unifiedresources.StorageMeta{
Type: "pbs-datastore",
Platform: "pbs",
Topology: "datastore",
Protection: "backup-repository",
ContentTypes: []string{"backup"},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "pbs-instance:pbs-main:pbs_datastore_state",
Code: "pbs_datastore_state",
Severity: storagehealth.RiskCritical,
Summary: "PBS datastore fast is ERROR",
}},
},
}
m.SyncUnifiedResourceIncidents(resources)
active := m.GetActiveAlerts()
if len(active) != 1 {
t.Fatalf("expected 1 active alert after PBS parent roll-up suppression, got %d: %+v", len(active), active)
}
if active[0].ResourceID != parentID {
t.Fatalf("expected PBS parent alert to remain, got %q", active[0].ResourceID)
}
if active[0].Type != "backup-posture-incident" {
t.Fatalf("alert type = %q, want backup-posture-incident", active[0].Type)
}
}
func TestSyncUnifiedResourceIncidentsIncludesProtectionAndRebuildSemantics(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "storage:array",
Type: unifiedresources.ResourceTypeStorage,
Name: "array",
Storage: &unifiedresources.StorageMeta{
Platform: "unraid",
Topology: "array",
Protection: "single-parity",
Risk: &unifiedresources.StorageRisk{
Level: storagehealth.RiskCritical,
Reasons: []unifiedresources.StorageRiskReason{
{Code: "unraid_parity_unavailable", Severity: storagehealth.RiskCritical, Summary: "Unraid parity protection is unavailable"},
{Code: "unraid_sync_active", Severity: storagehealth.RiskWarning, Summary: "Unraid array is running parity-sync (25%)"},
},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "topology-1",
Code: "storage_topology_risk",
Severity: storagehealth.RiskCritical,
Summary: "Unraid array protection is unavailable",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := "unified-incident-storage-array-pulse-topology-1-storage-topology-risk"
assertAlertPresent(t, m, alertID)
m.mu.RLock()
alert := testRequireActiveAlert(t, m, alertID)
m.mu.RUnlock()
if got := alert.Metadata["protectionReduced"]; got != true {
t.Fatalf("protectionReduced = %v, want true", got)
}
if got := alert.Metadata["rebuildInProgress"]; got != true {
t.Fatalf("rebuildInProgress = %v, want true", got)
}
if got := alert.Metadata["protectionSummary"]; got != "Unraid parity protection is unavailable" {
t.Fatalf("protectionSummary = %v", got)
}
if got := alert.Metadata["rebuildSummary"]; got != "Unraid array is running parity-sync (25%)" {
t.Fatalf("rebuildSummary = %v", got)
}
}
func TestGetActiveAlertsPrioritizesHighImpactStorageIncidents(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{
{
ID: "storage:shared",
Type: unifiedresources.ResourceTypeStorage,
Name: "shared",
Storage: &unifiedresources.StorageMeta{
ConsumerCount: 4,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "a",
Code: "capacity_runway_low",
Severity: storagehealth.RiskCritical,
Summary: "Shared storage is nearly full",
}},
},
{
ID: "disk:sdb",
Type: unifiedresources.ResourceTypePhysicalDisk,
Name: "sdb",
PhysicalDisk: &unifiedresources.PhysicalDiskMeta{
DevPath: "/dev/sdb",
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "b",
Code: "smart_failed",
Severity: storagehealth.RiskCritical,
Summary: "Disk sdb has SMART failures",
}},
},
})
active := m.GetActiveAlerts()
if len(active) != 2 {
t.Fatalf("expected 2 alerts, got %d", len(active))
}
if active[0].ResourceID != "storage:shared" {
t.Fatalf("expected storage incident first, got %q then %q", active[0].ResourceID, active[1].ResourceID)
}
}
func TestGetActiveAlertsPrioritizesProtectionLossAboveRebuildOnly(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{
{
ID: "storage:protection-loss",
Type: unifiedresources.ResourceTypeStorage,
Name: "protection-loss",
Storage: &unifiedresources.StorageMeta{
Risk: &unifiedresources.StorageRisk{
Level: storagehealth.RiskCritical,
Reasons: []unifiedresources.StorageRiskReason{
{Code: "unraid_parity_unavailable", Severity: storagehealth.RiskCritical, Summary: "Parity unavailable"},
},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "protection",
Code: "storage_topology_risk",
Severity: storagehealth.RiskCritical,
Summary: "Protection lost",
}},
},
{
ID: "storage:rebuild",
Type: unifiedresources.ResourceTypeStorage,
Name: "rebuild",
Storage: &unifiedresources.StorageMeta{
Risk: &unifiedresources.StorageRisk{
Level: storagehealth.RiskWarning,
Reasons: []unifiedresources.StorageRiskReason{
{Code: "raid_rebuilding", Severity: storagehealth.RiskWarning, Summary: "RAID is rebuilding"},
},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "rebuild",
Code: "storage_topology_risk",
Severity: storagehealth.RiskWarning,
Summary: "Rebuild in progress",
}},
},
})
active := m.GetActiveAlerts()
if len(active) != 2 {
t.Fatalf("expected 2 alerts, got %d", len(active))
}
if active[0].ResourceID != "storage:protection-loss" {
t.Fatalf("expected protection-loss alert first, got %q then %q", active[0].ResourceID, active[1].ResourceID)
}
}
func TestGetActiveAlertsPrioritizesBackupTargetExposure(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{
{
ID: "storage:backup-store",
Type: unifiedresources.ResourceTypeStorage,
Name: "backup-store",
Storage: &unifiedresources.StorageMeta{
Type: "pbs-datastore",
Platform: "pbs",
Topology: "datastore",
Protection: "backup-repository",
ContentTypes: []string{"backup"},
ConsumerCount: 2,
TopConsumers: []unifiedresources.StorageConsumerMeta{
{Name: "app01", ResourceType: unifiedresources.ResourceTypeVM, ResourceID: "vm-101", DiskCount: 1},
},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "backup",
Code: "backup_target_degraded",
Severity: storagehealth.RiskCritical,
Summary: "Backup target is degraded",
}},
},
{
ID: "storage:shared",
Type: unifiedresources.ResourceTypeStorage,
Name: "shared",
Storage: &unifiedresources.StorageMeta{
ConsumerCount: 4,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "shared",
Code: "capacity_runway_low",
Severity: storagehealth.RiskCritical,
Summary: "Shared storage is nearly full",
}},
},
})
active := m.GetActiveAlerts()
if len(active) != 2 {
t.Fatalf("expected 2 alerts, got %d", len(active))
}
if active[0].ResourceID != "storage:backup-store" {
t.Fatalf("expected backup target incident first, got %q then %q", active[0].ResourceID, active[1].ResourceID)
}
}
func TestGetActiveAlertsPrioritizesBackupPostureExposure(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{
{
ID: "pbs:main",
Type: unifiedresources.ResourceTypePBS,
Name: "pbs-main",
PBS: &unifiedresources.PBSData{
DatastoreCount: 1,
Datastores: []unifiedresources.PBSDatastoreMeta{
{Name: "fast", Status: "ERROR", Total: 100, Used: 96},
},
ProtectedWorkloadCount: 2,
ProtectedWorkloadNames: []string{"media01", "app01"},
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "pbs-instance:pbs-main:pbs_datastore_state",
Code: "pbs_datastore_state",
Severity: storagehealth.RiskCritical,
Summary: "PBS datastore fast is ERROR",
}},
},
{
ID: "storage:shared",
Type: unifiedresources.ResourceTypeStorage,
Name: "shared",
Storage: &unifiedresources.StorageMeta{
ConsumerCount: 4,
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "pulse",
NativeID: "shared",
Code: "capacity_runway_low",
Severity: storagehealth.RiskCritical,
Summary: "Shared storage is nearly full",
}},
},
})
active := m.GetActiveAlerts()
if len(active) != 2 {
t.Fatalf("expected 2 alerts, got %d", len(active))
}
if active[0].ResourceID != "pbs:main" {
t.Fatalf("expected backup posture alert first, got %q then %q", active[0].ResourceID, active[1].ResourceID)
}
}
func TestSyncUnifiedResourceIncidentsRespectsDisableAllStorage(t *testing.T) {
m := newTestManager(t)
cfg := unifiedEvalBaseConfig()
cfg.DisableAllStorage = true
configureUnifiedEvalManager(t, m, cfg)
resource := unifiedresources.Resource{
ID: "disk:ada0",
Type: unifiedresources.ResourceTypePhysicalDisk,
Name: "ada0",
PhysicalDisk: &unifiedresources.PhysicalDiskMeta{
DevPath: "/dev/ada0",
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas",
NativeID: "alert-2",
Code: "truenas_smart",
Severity: storagehealth.RiskCritical,
Summary: "Device /dev/ada0 has SMART failures",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := "unified-incident-disk-ada0-truenas-alert-2-truenas-smart"
assertAlertMissing(t, m, alertID)
}
func TestSyncUnifiedResourceIncidentsSupportsVMwareNetworkIncidentsAndGlobalDisable(t *testing.T) {
m := newTestManager(t)
cfg := unifiedEvalBaseConfig()
configureUnifiedEvalManager(t, m, cfg)
resource := unifiedresources.Resource{
ID: "vmware:vc-1:network:network-401",
Type: unifiedresources.ResourceTypeNetwork,
Name: "VM Network",
Sources: []unifiedresources.DataSource{unifiedresources.SourceVMware},
VMware: &unifiedresources.VMwareData{
ConnectionName: "Lab vCenter",
DatacenterName: "Lab Datacenter",
EntityType: "network",
},
Incidents: []unifiedresources.ResourceIncident{{
Provider: "vmware",
NativeID: "alarm-401",
Code: "vmware_alarm_state",
Severity: storagehealth.RiskWarning,
Summary: "vSphere network has an active alarm",
}},
}
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
alertID := "unified-incident-vmware-vc-1-network-network-401-vmware-alarm-401-vmware-alarm-state"
assertAlertPresent(t, m, alertID)
cfg.DisableAllVMware = true
m.UpdateConfig(cfg)
m.mu.Lock()
m.config.TimeThresholds = map[string]int{}
m.config.MetricTimeThresholds = nil
m.config.SuppressionWindow = 0
m.config.MinimumDelta = 0
m.mu.Unlock()
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
assertAlertMissing(t, m, alertID)
}
func TestDeriveCanonicalIdentityDoesNotMutateLegacyAlert(t *testing.T) {
alert := &Alert{
ID: "node-offline-pve-a",
Type: "connectivity",
Node: "pve-a",
Message: "node offline",
}
identity := deriveCanonicalIdentity(alert)
if identity.ResourceID != "pve-a" {
t.Fatalf("ResourceID = %q, want %q", identity.ResourceID, "pve-a")
}
if identity.SpecID != "pve-a-connectivity" {
t.Fatalf("SpecID = %q, want %q", identity.SpecID, "pve-a-connectivity")
}
if identity.Kind != "connectivity" {
t.Fatalf("Kind = %q, want %q", identity.Kind, "connectivity")
}
if identity.State != "pve-a::pve-a-connectivity" {
t.Fatalf("State = %q, want %q", identity.State, "pve-a::pve-a-connectivity")
}
if alert.ResourceID != "" || alert.CanonicalSpecID != "" || alert.CanonicalKind != "" || alert.CanonicalState != "" {
t.Fatalf("deriveCanonicalIdentity mutated legacy alert: %+v", alert)
}
}
// Provider information remains available on the resource without becoming an
// acknowledgement-required incident. Warnings still activate and clear.
func TestSyncUnifiedResourceIncidentsTrueNASInformation(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
resource := unifiedresources.Resource{
ID: "storage:replication", Type: unifiedresources.ResourceTypeStorage,
Incidents: []unifiedresources.ResourceIncident{{
Provider: "truenas", NativeID: "replication-1", Code: "replication",
Severity: storagehealth.RiskMonitor, Summary: "Replication succeeded.",
}},
}
for _, severity := range []storagehealth.RiskLevel{storagehealth.RiskMonitor, storagehealth.RiskWarning, storagehealth.RiskMonitor} {
resource.Incidents[0].Severity = severity
m.SyncUnifiedResourceIncidents([]unifiedresources.Resource{resource})
want := 0
if severity == storagehealth.RiskWarning {
want = 1
}
if got := len(m.GetActiveAlerts()); got != want {
t.Fatalf("severity %s: active alerts = %d, want %d", severity, got, want)
}
}
if len(resource.Incidents) != 1 {
t.Fatal("provider information removed")
}
}
// Exercise native projection as well as alert synchronisation: INFO and NOTICE
// share a canonical risk level but have different notification semantics.
func TestSyncUnifiedResourceIncidentsTrueNASNativeNotice(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
for _, tc := range []struct {
level string
want int
}{
{"NOTICE", 1}, {"INFO", 0}, {"WARNING", 1}, {"INFO", 0}, {" notice ", 1}, {" info ", 0},
} {
records := truenas.FixtureRecords(truenas.FixtureSnapshot{
CollectedAt: time.Now(),
System: truenas.SystemInfo{Hostname: "native-notice", Healthy: true},
Alerts: []truenas.Alert{{ID: "native-1", Level: tc.level, Message: "Provider condition"}},
})
resources := make([]unifiedresources.Resource, 0, len(records))
for _, record := range records {
// Ingestion assigns the canonical identity before evaluation.
record.Resource.ID = "host:" + record.SourceID
resources = append(resources, record.Resource)
}
// Native alerts require two recovery observations.
m.SyncUnifiedResourceIncidents(resources)
m.SyncUnifiedResourceIncidents(resources)
if got := len(m.GetActiveAlerts()); got != tc.want {
t.Fatalf("native %s: active alerts = %d, want %d", tc.level, got, tc.want)
}
if tc.level == "NOTICE" {
for _, alert := range m.GetActiveAlerts() {
if alert.Level != AlertLevelInfo {
t.Fatalf("NOTICE changed canonical severity to %s", alert.Level)
}
}
}
}
}
// A single informational poll must not resolve a native incident, and a
// renewed actionable observation must reset the recovery streak.
func TestSyncUnifiedResourceIncidentsTrueNASNativeRecoveryStreak(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
var identity string
for i, tc := range []struct {
native string
level AlertLevel
count int
}{
{"NOTICE", AlertLevelInfo, 1},
{"WARNING", AlertLevelWarning, 1},
{"CRITICAL", AlertLevelCritical, 1},
{"EMERGENCY", AlertLevelCritical, 1},
{"EMERGENCY", AlertLevelCritical, 1},
{"INFO", AlertLevelCritical, 1},
{"WARNING", AlertLevelWarning, 1},
{"INFO", AlertLevelWarning, 1},
{"INFO", "", 0},
{"NOTICE", AlertLevelInfo, 1},
} {
records := truenas.FixtureRecords(truenas.FixtureSnapshot{
CollectedAt: time.Now(),
System: truenas.SystemInfo{Hostname: "native-recovery", Healthy: true},
Alerts: []truenas.Alert{{ID: "native-1", Level: tc.native, Message: "Provider condition"}},
})
var resources []unifiedresources.Resource
for _, record := range records {
record.Resource.ID = "host:" + record.SourceID
resources = append(resources, record.Resource)
}
m.SyncUnifiedResourceIncidents(resources)
active := m.GetActiveAlerts()
if len(active) != tc.count {
t.Fatalf("poll %d (%s): active = %d, want %d", i, tc.native, len(active), tc.count)
}
for _, alert := range active {
if identity == "" {
identity = alert.ID
}
if alert.ID != identity || alert.Level != tc.level {
t.Fatalf("poll %d (%s): identity/level = %s/%s, want %s/%s", i, tc.native, alert.ID, alert.Level, identity, tc.level)
}
}
}
}
// A severity change must retain the incident identity without silently losing
// the critical notification or dispatching on every subsequent observation.
func TestTrueNASNativeCriticalTransition(t *testing.T) {
for _, gate := range []string{"active", "acknowledged", "rate-limited"} {
t.Run(gate, func(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
var dispatched []Alert
m.SetAlertCallback(func(a *Alert) { dispatched = append(dispatched, *a) })
resolved := make(chan string, 4)
m.SetResolvedCallback(func(id string) { resolved <- id })
syncLevel := func(level string) {
records := truenas.FixtureRecords(truenas.FixtureSnapshot{
CollectedAt: time.Now(),
System: truenas.SystemInfo{Hostname: "native-transition", Healthy: true},
Alerts: []truenas.Alert{{ID: "native-1", Level: level, Message: "Provider condition"}},
})
var resources []unifiedresources.Resource
for _, record := range records {
record.Resource.ID = "host:" + record.SourceID
resources = append(resources, record.Resource)
}
m.SyncUnifiedResourceIncidents(resources)
}
syncLevel("WARNING")
if len(dispatched) != 1 {
t.Fatalf("initial dispatches = %d", len(dispatched))
}
initial := dispatched[0]
if gate != "active" {
m.mu.Lock()
for key, a := range m.activeAlerts {
if gate == "acknowledged" {
a.Acknowledged = true
} else {
// Exhaust the canonical incident budget before escalation.
m.config.Schedule.MaxAlertsHour = 1
m.alertRateLimit[key] = []time.Time{time.Now()}
}
}
m.mu.Unlock()
}
syncLevel("EMERGENCY")
syncLevel("EMERGENCY")
active := m.GetActiveAlerts()
if len(active) != 1 || active[0].ID != initial.ID || active[0].Level != AlertLevelCritical || !active[0].StartTime.Equal(initial.StartTime) {
t.Fatalf("critical transition lost lifecycle identity: %+v", active)
}
want := 2
if gate != "active" {
want = 1
}
if len(dispatched) != want {
t.Fatalf("dispatches = %d, want %d", len(dispatched), want)
}
if gate == "active" && (dispatched[1].ID != initial.ID || dispatched[1].Level != AlertLevelCritical) {
t.Fatal("critical notification lost severity or identity")
}
syncLevel("WARNING")
if len(dispatched) != want {
t.Fatal("downgrade dispatched")
}
syncLevel("INFO")
syncLevel("INFO")
if len(m.GetActiveAlerts()) != 0 {
t.Fatal("confirmed recovery retained incident")
}
select {
case id := <-resolved:
if id != initial.ID {
t.Fatalf("recovery ID = %s, want %s", id, initial.ID)
}
case <-time.After(2 * time.Second):
t.Fatal("missing recovery callback")
}
})
}
}
// PBS capacity has one policy owner: CheckStorage. Topology risk remains
// visible, but must not create threshold-independent child/parent alerts.
func TestPBSCapacityUsesStoragePolicyNotTopologyBands(t *testing.T) {
m := newTestManager(t)
config := unifiedEvalBaseConfig()
config.StorageDefault = HysteresisThreshold{Trigger: 90, Clear: 85}
config.Overrides = map[string]ThresholdConfig{"pbs-main/fast": {Usage: &HysteresisThreshold{Trigger: 99, Clear: 98}}}
configureUnifiedEvalManager(t, m, config)
disableTestTimeThresholds(m)
instance := models.PBSInstance{ID: "pbs-main", Name: "main", Status: "online", LastSeen: time.Now(), Datastores: []models.PBSDatastore{{Name: "fast", Status: "online", Total: 1000, Used: 979, Free: 21, Usage: 97.9}}}
registry := unifiedresources.NewRegistry(unifiedresources.NewMemoryStore())
registry.IngestSnapshot(models.StateSnapshot{PBSInstances: []models.PBSInstance{instance}})
resources := registry.List()
capacityResources := 0
for _, r := range resources {
for _, i := range r.Incidents {
if i.Code == "capacity_runway_low" {
capacityResources++
break
}
}
}
if capacityResources != 2 {
t.Fatalf("want real parent and child capacity evidence, got %d", capacityResources)
}
storage := models.Storage{ID: "pbs-main-fast", AliasIDs: []string{"pbs-main/fast"}, Name: "fast", Instance: "pbs-main", Type: "pbs", Status: "online", Total: 1000, Used: 979, Free: 21, Usage: 97.9}
observe := func() {
for range 5 {
m.CheckStorage(storage)
m.SyncUnifiedResourceIncidents(resources)
}
}
observe()
if active := m.GetActiveAlerts(); len(active) != 0 {
t.Fatalf("99%% policy bypassed by topology incidents: %+v", active)
}
// Seed both pre-upgrade canonical alerts, with unchanged risk evidence.
// The next sync must retire them without deleting resource observations.
m.mu.Lock()
for _, spec := range alertspecs.BuildUnifiedResourceAlertSpecs(resources) {
if spec.Kind != alertspecs.AlertSpecKindProviderIncident {
continue
}
for _, resource := range resources {
if resource.ID != spec.ResourceID {
continue
}
incident, ok := incidentForProviderSpec(resource, spec)
if !ok || incident.Code != "capacity_runway_low" {
continue
}
alert := unifiedIncidentAlert(resource, incident, AlertLevelCritical, time.Now())
applyCanonicalIdentity(alert, spec.ID, string(spec.Kind))
m.setActiveAlertNoLock(canonicalTrackingKeyForSpec(spec, alert.ID), alert)
}
}
m.mu.Unlock()
if active := m.GetActiveAlerts(); len(active) != 2 {
t.Fatalf("want two pre-upgrade duplicates, got %d", len(active))
}
observe()
if active := m.GetActiveAlerts(); len(active) != 0 {
t.Fatalf("pre-upgrade duplicates retained: %+v", active)
}
config.Overrides["pbs-main/fast"] = ThresholdConfig{Usage: &HysteresisThreshold{Trigger: 90, Clear: 85}}
m.UpdateConfig(config)
disableTestTimeThresholds(m)
observe()
active := m.GetActiveAlerts()
if len(active) != 1 || active[0].ResourceID != storage.ID || active[0].CanonicalKind != "metric-threshold" {
t.Fatalf("want one policy-owned capacity alert, got %+v", active)
}
config.Overrides["pbs-main/fast"] = ThresholdConfig{Usage: &HysteresisThreshold{Trigger: 99, Clear: 98}}
m.UpdateConfig(config)
disableTestTimeThresholds(m)
observe()
if active := m.GetActiveAlerts(); len(active) != 0 {
t.Fatalf("raising policy did not clear capacity: %+v", active)
}
// The same nearly-full datastore failing is still actionable.
instance.Datastores[0].Status = "ERROR"
registry.IngestSnapshot(models.StateSnapshot{PBSInstances: []models.PBSInstance{instance}})
resources = registry.List()
observe()
if active := m.GetActiveAlerts(); len(active) == 0 {
t.Fatal("capacity policy hid datastore failure")
}
}
// #1815: a failed PBS-to-PBS sync raises its own alert on the store the sync
// writes to, through the ordinary incident pipeline, and the alert clears once
// the job's newest run succeeds. Guest protection is not involved.
func TestSyncUnifiedResourceIncidentsAlertsOnFailedPBSSyncJob(t *testing.T) {
m := newTestManager(t)
configureUnifiedEvalManager(t, m, unifiedEvalBaseConfig())
ranAt := time.Now().Add(-time.Hour).UTC().Truncate(time.Second)
snapshot := func(posture string) []unifiedresources.Resource {
instance := models.PBSInstance{
ID: "pbs-main", Name: "main", Status: "online", LastSeen: time.Now(),
Datastores: []models.PBSDatastore{
{Name: "fast", Status: "available", Total: 1000, Used: 100, Free: 900, Usage: 10},
{Name: "offsite", Status: "available", Total: 1000, Used: 100, Free: 900, Usage: 10},
},
JobHealthEvidence: []models.PBSJobHealthEvidence{{
ID: "s-offsite", Family: "sync", Store: "offsite", Remote: "pbs-main", Enabled: true,
Posture: posture, LastRunEndtime: ranAt.Unix(),
Freshness: models.PBSJobHealthFreshness{LastRunEndTime: ranAt},
}},
}
registry := unifiedresources.NewRegistry(unifiedresources.NewMemoryStore())
registry.IngestSnapshot(models.StateSnapshot{PBSInstances: []models.PBSInstance{instance}})
return registry.List()
}
m.SyncUnifiedResourceIncidents(snapshot("critical"))
active := m.GetActiveAlerts()
if len(active) != 1 {
t.Fatalf("expected one failed-sync alert, got %d: %+v", len(active), active)
}
alert := active[0]
if alert.Type != "backup-storage-incident" || alert.Level != AlertLevelWarning {
t.Fatalf("alert type/level = %q/%q, want backup-storage-incident/warning", alert.Type, alert.Level)
}
if want := "Sync job s-offsite failed on datastore offsite (copying from pbs-main)"; alert.Message != want {
t.Fatalf("message = %q, want %q", alert.Message, want)
}
if alert.ResourceName != "offsite" {
t.Fatalf("resource name = %q, want the sync's store", alert.ResourceName)
}
// A PBS outage drops the datastore from the poll: unknown, not recovery.
m.SyncUnifiedResourceIncidents(nil)
if active := m.GetActiveAlerts(); len(active) != 1 {
t.Fatalf("an outage must keep the alert, got %+v", active)
}
// Recovery needs two polls that see the job succeed.
m.SyncUnifiedResourceIncidents(snapshot("healthy"))
if active := m.GetActiveAlerts(); len(active) != 1 {
t.Fatalf("one successful poll must not clear the alert yet, got %+v", active)
}
m.SyncUnifiedResourceIncidents(snapshot("healthy"))
if active := m.GetActiveAlerts(); len(active) != 0 {
t.Fatalf("a confirmed successful sync must clear the alert, got %+v", active)
}
}