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.

Batch incident recorder metrics lookups

rcourtman81de801e5852
diff --git a/internal/ai/adapters/adapters.go b/internal/ai/adapters/adapters.go
index 9bc677ba41..85e160a9ad 100644
--- a/internal/ai/adapters/adapters.go
+++ b/internal/ai/adapters/adapters.go
@@ -8,6 +8,7 @@ import (
"fmt"
"os"
"path/filepath"
+ "strconv"
"strings"
"sync"
"time"
@@ -116,6 +117,64 @@ func (a *MetricsAdapter) GetMonitoredResourceIDs() []string {
return ids
}
+// GetCurrentMetricsBatch returns current metrics for every resource
+// GetCurrentMetrics can resolve, in one pass over the views, keyed by every
+// ID form GetCurrentMetrics matches (unified ID, source ID, VMID string,
+// name). The per-ID method scans all views per call, so a sampler asking for
+// thousands of resources per tick must use this instead: first-key-wins
+// mirrors the per-ID method's VM -> container -> node -> storage precedence.
+func (a *MetricsAdapter) GetCurrentMetricsBatch() map[string]map[string]float64 {
+ out := make(map[string]map[string]float64)
+ put := func(metrics map[string]float64, keys ...string) {
+ for _, key := range keys {
+ if key == "" {
+ continue
+ }
+ if _, exists := out[key]; !exists {
+ out[key] = metrics
+ }
+ }
+ }
+
+ for _, vm := range a.readState.VMs() {
+ put(map[string]float64{
+ "cpu": vm.CPUPercent(),
+ "memory": vm.MemoryPercent(),
+ "disk": vm.DiskPercent(),
+ "netin": vm.NetIn(),
+ "netout": vm.NetOut(),
+ "diskread": vm.DiskRead(),
+ "diskwrite": vm.DiskWrite(),
+ }, vm.ID(), vm.SourceID(), strconv.Itoa(vm.VMID()))
+ }
+ for _, ct := range a.readState.Containers() {
+ put(map[string]float64{
+ "cpu": ct.CPUPercent(),
+ "memory": ct.MemoryPercent(),
+ "disk": ct.DiskPercent(),
+ "netin": ct.NetIn(),
+ "netout": ct.NetOut(),
+ "diskread": ct.DiskRead(),
+ "diskwrite": ct.DiskWrite(),
+ }, ct.ID(), ct.SourceID(), strconv.Itoa(ct.VMID()))
+ }
+ for _, node := range a.readState.Nodes() {
+ put(map[string]float64{
+ "cpu": node.CPUPercent(),
+ "memory": node.MemoryPercent(),
+ "disk": node.DiskPercent(),
+ }, node.ID(), node.SourceID(), node.Name())
+ }
+ for _, sp := range a.readState.StoragePools() {
+ put(map[string]float64{
+ "disk": sp.DiskPercent(),
+ "used": float64(sp.DiskUsed()),
+ "total": float64(sp.DiskTotal()),
+ }, sp.ID(), sp.SourceID(), sp.Name())
+ }
+ return out
+}
+
// GetCurrentMetrics returns current metrics for a resource.
// Matches by unified ID, Proxmox source ID, VMID string, or name.
// CPU/memory/disk values are normalized to 0-100 percentage scale.
@@ -124,7 +183,7 @@ func (a *MetricsAdapter) GetCurrentMetrics(resourceID string) (map[string]float6
// Check VMs
for _, vm := range a.readState.VMs() {
- if vm.ID() == resourceID || vm.SourceID() == resourceID || fmt.Sprintf("%d", vm.VMID()) == resourceID {
+ if vm.ID() == resourceID || vm.SourceID() == resourceID || strconv.Itoa(vm.VMID()) == resourceID {
metrics["cpu"] = vm.CPUPercent()
metrics["memory"] = vm.MemoryPercent()
metrics["disk"] = vm.DiskPercent()
@@ -138,7 +197,7 @@ func (a *MetricsAdapter) GetCurrentMetrics(resourceID string) (map[string]float6
// Check containers
for _, ct := range a.readState.Containers() {
- if ct.ID() == resourceID || ct.SourceID() == resourceID || fmt.Sprintf("%d", ct.VMID()) == resourceID {
+ if ct.ID() == resourceID || ct.SourceID() == resourceID || strconv.Itoa(ct.VMID()) == resourceID {
metrics["cpu"] = ct.CPUPercent()
metrics["memory"] = ct.MemoryPercent()
metrics["disk"] = ct.DiskPercent()
diff --git a/internal/ai/adapters/adapters_batch_test.go b/internal/ai/adapters/adapters_batch_test.go
new file mode 100644
index 0000000000..ef9b234795
--- /dev/null
+++ b/internal/ai/adapters/adapters_batch_test.go
@@ -0,0 +1,80 @@
+package adapters
+
+import (
+ "reflect"
+ "strconv"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+// The batch method must return exactly what per-ID lookups return for every
+// ID form the per-ID method matches, including colliding VMID strings where
+// the VM -> container precedence decides the winner.
+func TestGetCurrentMetricsBatchMatchesPerIDLookups(t *testing.T) {
+ state := models.StateSnapshot{
+ Nodes: []models.Node{
+ {ID: "node/pve1", Name: "pve1", Instance: "inst1", CPU: 0.35, Memory: models.Memory{Usage: 60}},
+ },
+ VMs: []models.VM{
+ {
+ ID: "qemu/100", VMID: 100, Name: "webserver", Node: "pve1", Instance: "inst1",
+ CPU: 45.5, Memory: models.Memory{Usage: 72.3}, Disk: models.Disk{Usage: 55},
+ NetworkIn: 1024, NetworkOut: 512, DiskRead: 2048, DiskWrite: 1024,
+ },
+ },
+ Containers: []models.Container{
+ {
+ ID: "lxc/104", VMID: 104, Name: "auth", Node: "pve1", Instance: "inst1",
+ CPU: 12.5, Memory: models.Memory{Usage: 30}, Disk: models.Disk{Usage: 20},
+ },
+ },
+ Storage: []models.Storage{
+ {ID: "storage/local", Name: "local", Node: "pve1", Instance: "inst1", Usage: 41, Used: 41, Total: 100},
+ },
+ }
+
+ adapter := NewMetricsAdapter(readStateFromSnapshot(state))
+ batch := adapter.GetCurrentMetricsBatch()
+ if len(batch) == 0 {
+ t.Fatal("batch returned no entries for a populated state")
+ }
+
+ for id := range batch {
+ perID, err := adapter.GetCurrentMetrics(id)
+ if err != nil {
+ t.Fatalf("GetCurrentMetrics(%q) error: %v", id, err)
+ }
+ if !reflect.DeepEqual(batch[id], perID) {
+ t.Fatalf("metrics diverged for %q:\nbatch: %+v\nper-ID: %+v", id, batch[id], perID)
+ }
+ }
+
+ // Every monitored ID must be resolvable through the batch.
+ for _, id := range adapter.GetMonitoredResourceIDs() {
+ if _, ok := batch[id]; !ok {
+ t.Fatalf("monitored ID %q missing from batch", id)
+ }
+ }
+}
+
+func TestGetCurrentMetricsBatchVMIDCollisionPrefersVM(t *testing.T) {
+ state := models.StateSnapshot{
+ Nodes: []models.Node{
+ {ID: "node/pve1", Name: "pve1", Instance: "inst1"},
+ },
+ VMs: []models.VM{
+ {ID: "qemu/200", VMID: 200, Name: "vm-two-hundred", Node: "pve1", Instance: "inst1", CPU: 80},
+ },
+ Containers: []models.Container{
+ {ID: "lxc/200", VMID: 200, Name: "ct-two-hundred", Node: "pve1", Instance: "inst1", CPU: 10},
+ },
+ }
+
+ adapter := NewMetricsAdapter(readStateFromSnapshot(state))
+ batch := adapter.GetCurrentMetricsBatch()
+ perID, _ := adapter.GetCurrentMetrics(strconv.Itoa(200))
+ if !reflect.DeepEqual(batch["200"], perID) {
+ t.Fatalf("VMID collision winner diverged:\nbatch: %+v\nper-ID: %+v", batch["200"], perID)
+ }
+}
diff --git a/internal/metrics/incident_recorder.go b/internal/metrics/incident_recorder.go
index 69abc8c575..96987fa7f1 100644
--- a/internal/metrics/incident_recorder.go
+++ b/internal/metrics/incident_recorder.go
@@ -99,6 +99,14 @@ type MetricsProvider interface {
GetMonitoredResourceIDs() []string // Returns all resource IDs being monitored
}
+// BatchMetricsProvider is an optional MetricsProvider extension. recordSample
+// asks for metrics once per monitored resource every tick; a provider whose
+// per-ID lookup scans all resources turns that into an O(n^2) tick, so when
+// this is implemented the recorder fetches the whole batch in one pass.
+type BatchMetricsProvider interface {
+ GetCurrentMetricsBatch() map[string]map[string]float64
+}
+
// IncidentRecorder captures high-frequency metrics during incidents
type IncidentRecorder struct {
mu sync.RWMutex
@@ -280,6 +288,24 @@ func (r *IncidentRecorder) recordSample() {
now := time.Now()
shouldSave := false
+ // One pass over the provider when it supports batching; the per-ID
+ // fallback preserves behavior for providers that do not. A missing batch
+ // entry maps to the empty metrics the per-ID method returns for unknown
+ // IDs.
+ var metricsBatch map[string]map[string]float64
+ if batchProvider, ok := r.provider.(BatchMetricsProvider); ok {
+ metricsBatch = batchProvider.GetCurrentMetricsBatch()
+ }
+ currentMetrics := func(resourceID string) (map[string]float64, error) {
+ if metricsBatch != nil {
+ if metrics, ok := metricsBatch[resourceID]; ok {
+ return metrics, nil
+ }
+ return map[string]float64{}, nil
+ }
+ return r.provider.GetCurrentMetrics(resourceID)
+ }
+
// Record for active windows
for _, window := range r.activeWindows {
if window.Status != IncidentWindowStatusRecording {
@@ -306,7 +332,7 @@ func (r *IncidentRecorder) recordSample() {
}
// Get metrics
- metrics, err := r.provider.GetCurrentMetrics(window.ResourceID)
+ metrics, err := currentMetrics(window.ResourceID)
if err != nil {
log.Debug().
Str("window_id", window.ID).
@@ -328,7 +354,7 @@ func (r *IncidentRecorder) recordSample() {
bufferCutoff := now.Add(-r.config.PreIncidentWindow)
for _, resourceID := range monitoredResources {
- metrics, err := r.provider.GetCurrentMetrics(resourceID)
+ metrics, err := currentMetrics(resourceID)
if err != nil {
log.Debug().
Str("resource_id", resourceID).