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
add PDM alert bridge substrate in internal/ai
rcourtman8aad44174b79
diff --git a/internal/ai/findings_pdm_alert_bridge.go b/internal/ai/findings_pdm_alert_bridge.gonew file mode 100644index 0000000000..1910d0ffc5--- /dev/null+++ b/internal/ai/findings_pdm_alert_bridge.go@@ -0,0 +1,213 @@+// findings_pdm_alert_bridge.go implements a poll-based bridge from Proxmox+// Datacenter Manager (PDM) into the Pulse findings store. On every patrol+// observe trip the bridge fetches the PDM resource list via the+// pdmAlertSource interface, diffs each resource's status against a prior-state+// map, and returns reliability findings for resources that have transitioned+// into a known-offline state. Resources that come back online emit a lazy+// resolve sentinel on the next observe trip -- there is no sweep goroutine.+//+// MVP: the real HTTP client is a follow-on; this lane ships only the+// interface, the diff machinery, and a nil-source guard at the call site.+// pdmAlertBridgeConfig is reserved for the future env-based credential+// surface; the MVP leaves it zero-valued.+package ai++import (+ "context"+ "fmt"+ "sync"+ "time"+)++const (+ // PDMAlertFindingPrefix is the dedup-key prefix for PDM resource alerts.+ // Concrete keys are prefix + ":" + remoteID + "/" + resourceType + "/" + resourceName.+ PDMAlertFindingPrefix = "pdm:resource:offline"++ pdmAlertSourceLabel = "pdm-alert-bridge"+ pdmAlertResolveReason = "pdm:resource:back_online"+)++// pdmAlertSource is the interface the bridge uses to fetch resource+// snapshots. Unit tests inject a deterministic fake; the real implementation+// (future) makes an authenticated HTTP call to /api2/json/resources.+type pdmAlertSource interface {+ ResourceList(ctx context.Context) ([]pdmResource, error)+}++// pdmResource is the minimal shape Pulse needs from a PDM resource list item.+type pdmResource struct {+ ID string // unique per remote+type+name, e.g. "datacenter-a/node/pve1"+ RemoteID string // PDM remote cluster identifier, e.g. "datacenter-a"+ Name string // resource name, e.g. "pve1"+ Type string // "node", "qemu", "lxc", "storage"+ Status string // "online", "offline", "running", "stopped", "failed", "unknown"+}++// pdmAlertBridgeConfig is reserved for the forward-compatible credential+// surface (PDM_API_URL, PDM_API_TOKEN). MVP leaves it zero-valued.+type pdmAlertBridgeConfig struct{}++// pdmAlertBridge diffs PDM resource status across observe trips.+type pdmAlertBridge struct {+ mu sync.Mutex+ source pdmAlertSource+ prior map[string]string // resource key -> last known status+}++// newPDMAlertBridge returns a bridge bound to the given source. A nil source+// is permitted: the constructor returns a bridge whose Observe is a no-op+// until a real source is injected.+func newPDMAlertBridge(source pdmAlertSource) *pdmAlertBridge {+ return &pdmAlertBridge{+ source: source,+ prior: make(map[string]string),+ }+}++// Observe polls the configured source, diffs each resource's status against+// the prior-state map, and returns (emit, resolve) sentinels. The first+// observe trip for a given resource seeds prior state and returns nothing+// for that resource. Subsequent trips:+// - status transitioned into a known-offline state -> emit one finding.+// - status transitioned back to online from a known-offline state -> emit+// one resolve sentinel.+// - status of "unknown" or other non-actionable values -> ignored.+//+// Concurrency: holds b.mu for the duration of the trip.+func (b *pdmAlertBridge) Observe(ctx context.Context, now time.Time) (emit []*Finding, resolve []resolveSentinel) {+ if b == nil || b.source == nil {+ return nil, nil+ }+ resources, err := b.source.ResourceList(ctx)+ if err != nil {+ return nil, nil+ }++ b.mu.Lock()+ defer b.mu.Unlock()++ seen := make(map[string]struct{}, len(resources))+ for _, r := range resources {+ key := pdmResourceKey(r)+ seen[key] = struct{}{}++ if !isPDMStatusActionable(r.Status) {+ // Don't seed unknown/empty status as prior state -- we can't+ // distinguish a flap from a genuine transition later.+ continue+ }++ prev, hadPrior := b.prior[key]+ b.prior[key] = r.Status++ if !hadPrior {+ // Seed only -- no emit on first observation of this resource.+ continue+ }+ if prev == r.Status {+ continue+ }++ nowOffline := isPDMOffline(r.Status)+ wasOffline := isPDMOffline(prev)++ switch {+ case nowOffline && !wasOffline:+ emit = append(emit, buildPDMAlertFinding(r, now))+ case !nowOffline && wasOffline:+ resolve = append(resolve, resolveSentinel{+ DedupKey: pdmAlertDedupKey(r),+ Reason: pdmAlertResolveReason,+ })+ }+ }++ // Drop prior-state entries for resources that disappeared from the list+ // entirely; we can't reason about them and they would otherwise leak.+ for k := range b.prior {+ if _, ok := seen[k]; !ok {+ delete(b.prior, k)+ }+ }++ return emit, resolve+}++// isPDMStatusActionable reports whether a status value is one we can diff+// against. Empty and "unknown" are treated as non-actionable so we don't+// seed them as prior state.+func isPDMStatusActionable(status string) bool {+ switch status {+ case "online", "running", "offline", "stopped", "failed":+ return true+ }+ return false+}++// isPDMOffline reports whether a status value represents a known-offline+// condition that should emit a reliability finding.+func isPDMOffline(status string) bool {+ switch status {+ case "offline", "stopped", "failed":+ return true+ }+ return false+}++// pdmResourceKey is the in-memory map key for a PDM resource.+func pdmResourceKey(r pdmResource) string {+ return r.RemoteID + "/" + r.Type + "/" + r.Name+}++// pdmAlertDedupKey is the dedup key written onto the Finding (and used by+// the resolve sentinel). Format:+//+// pdm:resource:offline:<remote>/<type>/<name>+func pdmAlertDedupKey(r pdmResource) string {+ return PDMAlertFindingPrefix + ":" + pdmResourceKey(r)+}++// findingResourceType maps a PDM resource type onto the Pulse finding+// resource_type vocabulary already rendered by FindingsPanel.+func findingResourceType(pdmType string) string {+ switch pdmType {+ case "qemu", "lxc":+ return "vm"+ case "node":+ return "node"+ case "storage":+ return "storage"+ }+ return pdmType+}++// buildPDMAlertFinding constructs a reliability finding for a PDM resource+// that has transitioned into a known-offline state.+func buildPDMAlertFinding(r pdmResource, now time.Time) *Finding {+ dedup := pdmAlertDedupKey(r)+ resType := findingResourceType(r.Type)+ title := fmt.Sprintf("PDM: %s %q is %s", resType, r.Name, r.Status)+ desc := fmt.Sprintf(+ "Proxmox Datacenter Manager reports %s %q in remote %q is %s.",+ resType, r.Name, r.RemoteID, r.Status,+ )+ evidence := fmt.Sprintf("status=%s remote=%s", r.Status, r.RemoteID)++ return &Finding{+ ID: dedup,+ Key: dedup,+ Severity: FindingSeverityWarning,+ Category: FindingCategoryReliability,+ ResourceID: pdmResourceKey(r),+ ResourceName: r.Name,+ ResourceType: resType,+ Node: r.RemoteID,+ Title: title,+ Description: desc,+ Evidence: evidence,+ Source: pdmAlertSourceLabel,+ DetectedAt: now,+ LastSeenAt: now,+ }+}diff --git a/internal/ai/findings_pdm_alert_bridge_test.go b/internal/ai/findings_pdm_alert_bridge_test.gonew file mode 100644index 0000000000..006aee7e98--- /dev/null+++ b/internal/ai/findings_pdm_alert_bridge_test.go@@ -0,0 +1,183 @@+package ai++import (+ "context"+ "errors"+ "testing"+ "time"+)++// fakePDMSource returns scripted ResourceList snapshots, one per call.+type fakePDMSource struct {+ snapshots [][]pdmResource+ err error+ idx int+}++func (f *fakePDMSource) ResourceList(_ context.Context) ([]pdmResource, error) {+ if f.err != nil {+ return nil, f.err+ }+ if f.idx >= len(f.snapshots) {+ return f.snapshots[len(f.snapshots)-1], nil+ }+ snap := f.snapshots[f.idx]+ f.idx+++ return snap, nil+}++func pdmRes(remote, typ, name, status string) pdmResource {+ return pdmResource{+ ID: remote + "/" + typ + "/" + name,+ RemoteID: remote,+ Name: name,+ Type: typ,+ Status: status,+ }+}++// TestPDMAlertBridge_NilSourceIsNoOp verifies that a bridge constructed with+// a nil source emits nothing on Observe -- the patrol-loop wire-in relies on+// this for the MVP no-op behavior.+func TestPDMAlertBridge_NilSourceIsNoOp(t *testing.T) {+ b := newPDMAlertBridge(nil)+ emit, resolve := b.Observe(context.Background(), time.Now())+ if len(emit) != 0 || len(resolve) != 0 {+ t.Fatalf("nil source: want silent, got emit=%d resolve=%d", len(emit), len(resolve))+ }+}++// TestPDMAlertBridge_SeedOfflineOnlineCycle drives the bridge through three+// snapshots:+// 1. seed -- node online, first observation, nothing emitted.+// 2. offline -- node transitions to offline, one finding emitted.+// 3. online -- node returns to online, one resolve sentinel emitted.+func TestPDMAlertBridge_SeedOfflineOnlineCycle(t *testing.T) {+ src := &fakePDMSource{+ snapshots: [][]pdmResource{+ {pdmRes("datacenter-a", "node", "pve-edge-01", "online")},+ {pdmRes("datacenter-a", "node", "pve-edge-01", "offline")},+ {pdmRes("datacenter-a", "node", "pve-edge-01", "online")},+ },+ }+ b := newPDMAlertBridge(src)+ t0 := time.Now()++ emit1, res1 := b.Observe(context.Background(), t0)+ if len(emit1) != 0 || len(res1) != 0 {+ t.Fatalf("seed trip: want silent, got emit=%d resolve=%d", len(emit1), len(res1))+ }++ emit2, res2 := b.Observe(context.Background(), t0.Add(5*time.Second))+ if len(emit2) != 1 {+ t.Fatalf("offline trip: want 1 finding, got %d", len(emit2))+ }+ if len(res2) != 0 {+ t.Fatalf("offline trip: want 0 resolves, got %d", len(res2))+ }+ f := emit2[0]+ wantKey := PDMAlertFindingPrefix + ":datacenter-a/node/pve-edge-01"+ if f.ID != wantKey {+ t.Errorf("dedup id: want %q, got %q", wantKey, f.ID)+ }+ if f.Key != wantKey {+ t.Errorf("dedup key: want %q, got %q", wantKey, f.Key)+ }+ if f.ResourceType != "node" {+ t.Errorf("resource_type: want %q, got %q", "node", f.ResourceType)+ }+ if f.ResourceName != "pve-edge-01" {+ t.Errorf("resource_name: want %q, got %q", "pve-edge-01", f.ResourceName)+ }+ if f.Severity != FindingSeverityWarning {+ t.Errorf("severity: want %q, got %q", FindingSeverityWarning, f.Severity)+ }+ if f.Category != FindingCategoryReliability {+ t.Errorf("category: want %q, got %q", FindingCategoryReliability, f.Category)+ }+ if f.Source != pdmAlertSourceLabel {+ t.Errorf("source: want %q, got %q", pdmAlertSourceLabel, f.Source)+ }+ if f.Node != "datacenter-a" {+ t.Errorf("node: want %q, got %q", "datacenter-a", f.Node)+ }++ emit3, res3 := b.Observe(context.Background(), t0.Add(10*time.Second))+ if len(emit3) != 0 {+ t.Fatalf("online trip: want 0 findings, got %d", len(emit3))+ }+ if len(res3) != 1 {+ t.Fatalf("online trip: want 1 resolve sentinel, got %d", len(res3))+ }+ if res3[0].DedupKey != wantKey {+ t.Errorf("resolve DedupKey: want %q, got %q", wantKey, res3[0].DedupKey)+ }+ if res3[0].Reason != pdmAlertResolveReason {+ t.Errorf("resolve Reason: want %q, got %q", pdmAlertResolveReason, res3[0].Reason)+ }+}++// TestPDMAlertBridge_UnknownStatusIgnored verifies that resources reporting+// "unknown" status are not seeded as prior state and do not emit on any trip.+func TestPDMAlertBridge_UnknownStatusIgnored(t *testing.T) {+ src := &fakePDMSource{+ snapshots: [][]pdmResource{+ {pdmRes("dc1", "node", "pve1", "unknown")},+ {pdmRes("dc1", "node", "pve1", "unknown")},+ {pdmRes("dc1", "node", "pve1", "offline")},+ },+ }+ b := newPDMAlertBridge(src)+ t0 := time.Now()++ // First two trips: unknown -> never seeded, no emit.+ for i := 0; i < 2; i++ {+ emit, res := b.Observe(context.Background(), t0.Add(time.Duration(i)*time.Second))+ if len(emit) != 0 || len(res) != 0 {+ t.Fatalf("unknown trip %d: want silent, got emit=%d resolve=%d", i, len(emit), len(res))+ }+ }+ // Third trip: offline arrives as the first actionable observation -> seed,+ // no emit.+ emit3, res3 := b.Observe(context.Background(), t0.Add(2*time.Second))+ if len(emit3) != 0 || len(res3) != 0 {+ t.Fatalf("first actionable trip: want silent (seed), got emit=%d resolve=%d", len(emit3), len(res3))+ }+}++// TestPDMAlertBridge_SourceErrorIsSilent verifies that a source error short-+// circuits Observe without panicking or mutating prior-state.+func TestPDMAlertBridge_SourceErrorIsSilent(t *testing.T) {+ src := &fakePDMSource{err: errors.New("boom")}+ b := newPDMAlertBridge(src)+ emit, resolve := b.Observe(context.Background(), time.Now())+ if len(emit) != 0 || len(resolve) != 0 {+ t.Fatalf("source error: want silent, got emit=%d resolve=%d", len(emit), len(resolve))+ }+ if len(b.prior) != 0 {+ t.Errorf("source error: prior should not be mutated, got %d entries", len(b.prior))+ }+}++// TestPDMAlertBridge_VMStatusMapsToResourceTypeVM verifies that a PDM resource+// of type "qemu" surfaces as ResourceType "vm" on the finding, matching the+// vocabulary FindingsPanel already renders.+func TestPDMAlertBridge_VMStatusMapsToResourceTypeVM(t *testing.T) {+ src := &fakePDMSource{+ snapshots: [][]pdmResource{+ {pdmRes("dc1", "qemu", "vm-101", "running")},+ {pdmRes("dc1", "qemu", "vm-101", "stopped")},+ },+ }+ b := newPDMAlertBridge(src)+ t0 := time.Now()+ b.Observe(context.Background(), t0)++ emit, _ := b.Observe(context.Background(), t0.Add(time.Second))+ if len(emit) != 1 {+ t.Fatalf("stopped vm: want 1 finding, got %d", len(emit))+ }+ if emit[0].ResourceType != "vm" {+ t.Errorf("resource_type: want %q, got %q", "vm", emit[0].ResourceType)+ }+}