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
Restore backend lint to green: real dedup + errcheck idiom fixes
rcourtman245177e53123
diff --git a/internal/api/router.go b/internal/api/router.goindex 85be27dd60..628a01baf3 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -7058,6 +7058,39 @@ func convertMetricsForChart(return converted}+// guestLiveMetricsView is the slice of the unified workload view API needed+// to seed a chart from live values; VM and container views both satisfy it.+type guestLiveMetricsView interface {+ CPUPercent() float64+ MemoryPercent() float64+ MemoryUsed() int64+ DiskPercent() float64+ NetIn() float64+ NetOut() float64+}++// guestChartSeriesWithLiveFallback converts a guest's batched metric history+// into chart series, substituting single live-value points when no history+// exists yet so freshly added guests still chart.+func guestChartSeriesWithLiveFallback(+ metrics map[string][]monitoring.MetricPoint,+ guest guestLiveMetricsView,+ oldestTimestamp *int64,+ maxPoints int,+ currentTime int64,+) VMChartData {+ series := convertMetricsForChart(metrics, oldestTimestamp, maxPoints)+ if len(series["cpu"]) == 0 {+ series["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: guest.CPUPercent()}}+ series["memory"] = []MetricPoint{{Timestamp: currentTime, Value: guest.MemoryPercent()}}+ series["memoryused"] = []MetricPoint{{Timestamp: currentTime, Value: float64(guest.MemoryUsed())}}+ series["disk"] = []MetricPoint{{Timestamp: currentTime, Value: guest.DiskPercent()}}+ series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: guest.NetIn()}}+ series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: guest.NetOut()}}+ }+ return series+}+const (mockWorkloadMinSeriesPoints = 24mockWorkloadMaxSeriesPoints = 180@@ -7530,35 +7563,15 @@ func (r *Router) buildWorkloadChartsResponse(for idx, vm := range vmList {responseKey := vmResponseKeys[idx]metricID := vmRequests[idx].SQLResourceID- series := convertMetricsForChart(vmBatchMetrics[metricID], &oldestTimestamp, maxPoints)guestTypes[responseKey] = "vm"-- if len(series["cpu"]) == 0 {- series["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: vm.CPUPercent()}}- series["memory"] = []MetricPoint{{Timestamp: currentTime, Value: vm.MemoryPercent()}}- series["memoryused"] = []MetricPoint{{Timestamp: currentTime, Value: float64(vm.MemoryUsed())}}- series["disk"] = []MetricPoint{{Timestamp: currentTime, Value: vm.DiskPercent()}}- series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: vm.NetIn()}}- series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: vm.NetOut()}}- }- chartData[responseKey] = series+ chartData[responseKey] = guestChartSeriesWithLiveFallback(vmBatchMetrics[metricID], vm, &oldestTimestamp, maxPoints, currentTime)}for idx, ct := range containerList {responseKey := containerResponseKeys[idx]metricID := containerRequests[idx].SQLResourceID- series := convertMetricsForChart(containerBatchMetrics[metricID], &oldestTimestamp, maxPoints)guestTypes[responseKey] = "system-container"-- if len(series["cpu"]) == 0 {- series["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: ct.CPUPercent()}}- series["memory"] = []MetricPoint{{Timestamp: currentTime, Value: ct.MemoryPercent()}}- series["memoryused"] = []MetricPoint{{Timestamp: currentTime, Value: float64(ct.MemoryUsed())}}- series["disk"] = []MetricPoint{{Timestamp: currentTime, Value: ct.DiskPercent()}}- series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: ct.NetIn()}}- series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: ct.NetOut()}}- }- chartData[responseKey] = series+ chartData[responseKey] = guestChartSeriesWithLiveFallback(containerBatchMetrics[metricID], ct, &oldestTimestamp, maxPoints, currentTime)}for _, pod := range podList {diff --git a/internal/monitoring/docker_identity_conflict.go b/internal/monitoring/docker_identity_conflict.goindex 7e11c6a498..0a5c1732c8 100644--- a/internal/monitoring/docker_identity_conflict.go+++ b/internal/monitoring/docker_identity_conflict.go@@ -1,8 +1,6 @@package monitoringimport (- "sort"- "strings""time""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -15,124 +13,26 @@ import (// report cycles even for agents on multi-minute intervals.const dockerIdentityConflictWindow = 15 * time.Minute-// dockerIdentityFlapTracker watches the stream of reports folded into a single-// Docker host identity and detects when two distinct machines are behind it.-//-// The signal is a *revisit*: the reported hostname (or machine ID) switches-// away from the previous value and back to one already seen inside the-// window. A genuine hostname rename transitions exactly once and never-// revisits the old value, so it does not trip the detector; cloned VMs that-// share /etc/machine-id alternate every report cycle and trip it immediately.-type dockerIdentityFlapTracker struct {- hostnames map[string]time.Time- machineIDs map[string]time.Time-- lastHostname string- lastMachineID string-- conflictSince time.Time- conflictLastSeen time.Time-}--func newDockerIdentityFlapTracker() *dockerIdentityFlapTracker {- return &dockerIdentityFlapTracker{- hostnames: make(map[string]time.Time),- machineIDs: make(map[string]time.Time),- }-}--// observe records one report's identity fields and returns the active-// conflict, or nil when the identity looks healthy.-func (t *dockerIdentityFlapTracker) observe(hostname, machineID string, now time.Time) *models.DockerHostIdentityConflict {- hostname = strings.TrimSpace(hostname)- machineID = strings.TrimSpace(machineID)-- pruneOlderThan(t.hostnames, now.Add(-dockerIdentityConflictWindow))- pruneOlderThan(t.machineIDs, now.Add(-dockerIdentityConflictWindow))-- revisit := false- if hostname != "" {- if _, seen := t.hostnames[hostname]; seen && t.lastHostname != "" && t.lastHostname != hostname {- revisit = true- }- t.hostnames[hostname] = now- t.lastHostname = hostname- }- if machineID != "" {- if _, seen := t.machineIDs[machineID]; seen && t.lastMachineID != "" && t.lastMachineID != machineID {- revisit = true- }- t.machineIDs[machineID] = now- t.lastMachineID = machineID- }-- if revisit {- if t.conflictSince.IsZero() || now.Sub(t.conflictLastSeen) > dockerIdentityConflictWindow {- t.conflictSince = now- }- t.conflictLastSeen = now- }-- if t.conflictLastSeen.IsZero() || now.Sub(t.conflictLastSeen) > dockerIdentityConflictWindow {- t.conflictSince = time.Time{}- t.conflictLastSeen = time.Time{}- return nil- }-- conflict := &models.DockerHostIdentityConflict{- Hostnames: sortedKeys(t.hostnames),- FirstSeen: t.conflictSince,- LastSeen: t.conflictLastSeen,- }- // Machine IDs are only interesting when they themselves diverge; in the- // common cloned-VM case there is exactly one shared machine ID and the- // hostname list carries the story.- if len(t.machineIDs) > 1 {- conflict.MachineIDs = sortedKeys(t.machineIDs)- }- return conflict-}--func pruneOlderThan(entries map[string]time.Time, cutoff time.Time) {- for key, seenAt := range entries {- if seenAt.Before(cutoff) {- delete(entries, key)- }- }-}--func sortedKeys(entries map[string]time.Time) []string {- keys := make([]string, 0, len(entries))- for key := range entries {- keys = append(keys, key)- }- sort.Strings(keys)- return keys-}-// trackDockerHostIdentity feeds one report's identity fields into the flap// tracker for the resolved host identifier and returns the active conflict,-// if any. Callers must not hold m.mu.+// if any. The secondary identity field is the reported machine ID: cloned+// VMs that share /etc/machine-id alternate hostnames every report cycle and+// trip the revisit detector immediately. Callers must not hold m.mu.func (m *Monitor) trackDockerHostIdentity(identifier, hostname, machineID string, now time.Time) *models.DockerHostIdentityConflict {- if strings.TrimSpace(identifier) == "" {+ conflict := m.observeIdentityFlap(&m.dockerIdentityFlaps, dockerIdentityConflictWindow, identifier, hostname, machineID, now)+ if conflict == nil {return nil}-- m.mu.Lock()- defer m.mu.Unlock()- if m.dockerIdentityFlaps == nil {- m.dockerIdentityFlaps = make(map[string]*dockerIdentityFlapTracker)- }- tracker, ok := m.dockerIdentityFlaps[identifier]- if !ok {- tracker = newDockerIdentityFlapTracker()- m.dockerIdentityFlaps[identifier] = tracker+ return &models.DockerHostIdentityConflict{+ Hostnames: conflict.hostnames,+ MachineIDs: conflict.secondaries,+ FirstSeen: conflict.firstSeen,+ LastSeen: conflict.lastSeen,}- return tracker.observe(hostname, machineID, now)}-// clearDockerHostIdentityTracking drops flap state for a host identity, e.g.-// when the host is deliberately removed. Callers must hold m.mu.+// clearDockerHostIdentityTrackingLocked drops flap state for a host identity,+// e.g. when the host is deliberately removed. Callers must hold m.mu.func (m *Monitor) clearDockerHostIdentityTrackingLocked(hostID string) {delete(m.dockerIdentityFlaps, hostID)}diff --git a/internal/monitoring/docker_identity_conflict_test.go b/internal/monitoring/docker_identity_conflict_test.goindex 5865f00488..5cb414c534 100644--- a/internal/monitoring/docker_identity_conflict_test.go+++ b/internal/monitoring/docker_identity_conflict_test.go@@ -7,90 +7,27 @@ import (agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker")-func TestDockerIdentityFlapTrackerDetectsAlternatingHostnames(t *testing.T) {- tracker := newDockerIdentityFlapTracker()+func TestTrackDockerHostIdentityTranslatesConflict(t *testing.T) {+ monitor := newTestMonitor(t)base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)- interval := 30 * time.Second- if conflict := tracker.observe("clone-a", "machine-1", base); conflict != nil {- t.Fatalf("first report should not conflict, got %+v", conflict)- }- // First switch could be a legitimate rename, so it must not warn yet.- if conflict := tracker.observe("clone-b", "machine-1", base.Add(interval)); conflict != nil {- t.Fatalf("single hostname switch should not conflict, got %+v", conflict)- }- // The revisit of clone-a proves two machines are alternating.- conflict := tracker.observe("clone-a", "machine-1", base.Add(2*interval))+ // When the machine IDs behind one host identity diverge, the model's+ // MachineIDs field must carry them alongside the shared hostname.+ monitor.trackDockerHostIdentity("host-1", "shared-host", "machine-a", base)+ monitor.trackDockerHostIdentity("host-1", "shared-host", "machine-b", base.Add(30*time.Second))+ conflict := monitor.trackDockerHostIdentity("host-1", "shared-host", "machine-a", base.Add(60*time.Second))if conflict == nil {- t.Fatal("expected conflict after hostname revisit")+ t.Fatal("expected conflict after machine ID revisit")}- if len(conflict.Hostnames) != 2 || conflict.Hostnames[0] != "clone-a" || conflict.Hostnames[1] != "clone-b" {- t.Fatalf("expected sorted hostnames [clone-a clone-b], got %v", conflict.Hostnames)+ if len(conflict.Hostnames) != 1 || conflict.Hostnames[0] != "shared-host" {+ t.Fatalf("expected hostnames [shared-host], got %v", conflict.Hostnames)}- if len(conflict.MachineIDs) != 0 {- t.Fatalf("shared machine ID should not be listed as conflicting, got %v", conflict.MachineIDs)+ if len(conflict.MachineIDs) != 2 || conflict.MachineIDs[0] != "machine-a" || conflict.MachineIDs[1] != "machine-b" {+ t.Fatalf("expected sorted machine IDs [machine-a machine-b], got %v", conflict.MachineIDs)}if conflict.FirstSeen.IsZero() || conflict.LastSeen.IsZero() {t.Fatalf("expected conflict timestamps, got %+v", conflict)}-- // Continued flapping keeps the conflict alive and refreshes LastSeen.- later := tracker.observe("clone-b", "machine-1", base.Add(3*interval))- if later == nil {- t.Fatal("expected conflict to persist while flapping continues")- }- if !later.LastSeen.After(conflict.LastSeen) {- t.Fatalf("expected LastSeen to advance, got %v then %v", conflict.LastSeen, later.LastSeen)- }- if !later.FirstSeen.Equal(conflict.FirstSeen) {- t.Fatalf("expected FirstSeen to be stable, got %v then %v", conflict.FirstSeen, later.FirstSeen)- }-}--func TestDockerIdentityFlapTrackerIgnoresSingleRename(t *testing.T) {- tracker := newDockerIdentityFlapTracker()- base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)-- if conflict := tracker.observe("old-name", "machine-1", base); conflict != nil {- t.Fatalf("unexpected conflict: %+v", conflict)- }- for i := 1; i <= 5; i++ {- if conflict := tracker.observe("new-name", "machine-1", base.Add(time.Duration(i)*30*time.Second)); conflict != nil {- t.Fatalf("rename should never conflict, got %+v on report %d", conflict, i)- }- }-}--func TestDockerIdentityFlapTrackerConflictExpiresAfterWindow(t *testing.T) {- tracker := newDockerIdentityFlapTracker()- base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)-- tracker.observe("clone-a", "machine-1", base)- tracker.observe("clone-b", "machine-1", base.Add(30*time.Second))- if conflict := tracker.observe("clone-a", "machine-1", base.Add(60*time.Second)); conflict == nil {- t.Fatal("expected conflict after revisit")- }-- // One clone goes away; steady reports from the survivor eventually clear it.- steady := base.Add(60 * time.Second).Add(dockerIdentityConflictWindow + time.Minute)- if conflict := tracker.observe("clone-a", "machine-1", steady); conflict != nil {- t.Fatalf("expected conflict to expire after quiet window, got %+v", conflict)- }-}--func TestDockerIdentityFlapTrackerDetectsAlternatingMachineIDs(t *testing.T) {- tracker := newDockerIdentityFlapTracker()- base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)-- tracker.observe("shared-host", "machine-a", base)- tracker.observe("shared-host", "machine-b", base.Add(30*time.Second))- conflict := tracker.observe("shared-host", "machine-a", base.Add(60*time.Second))- if conflict == nil {- t.Fatal("expected conflict after machine ID revisit")- }- if len(conflict.MachineIDs) != 2 || conflict.MachineIDs[0] != "machine-a" || conflict.MachineIDs[1] != "machine-b" {- t.Fatalf("expected sorted machine IDs [machine-a machine-b], got %v", conflict.MachineIDs)- }}func TestApplyDockerReportFlagsClonedMachineIDIdentity(t *testing.T) {diff --git a/internal/monitoring/host_identity_conflict.go b/internal/monitoring/host_identity_conflict.goindex 4a48f3d565..f5d576c7ea 100644--- a/internal/monitoring/host_identity_conflict.go+++ b/internal/monitoring/host_identity_conflict.go@@ -1,7 +1,6 @@package monitoringimport (- "strings""time""github.com/rcourtman/pulse-go-rewrite/internal/models"@@ -14,105 +13,23 @@ import (// report cycles even for agents on multi-minute intervals.const hostIdentityConflictWindow = 15 * time.Minute-// hostIdentityFlapTracker watches the stream of reports folded into a single-// host agent identity and detects when two distinct machines are behind it.-//-// The signal is a *revisit*: the reported hostname (or report IP) switches-// away from the previous value and back to one already seen inside the-// window. A genuine hostname rename transitions exactly once and never-// revisits the old value, so it does not trip the detector; template-cloned-// machines that share /etc/machine-id alternate every report cycle and trip-// it immediately. The report IP is tracked alongside the hostname because-// MSP-style template deployments often reuse hostnames too (pve01 at two-// sites), leaving the address as the only field that betrays the clone.-type hostIdentityFlapTracker struct {- hostnames map[string]time.Time- reportIPs map[string]time.Time-- lastHostname string- lastReportIP string-- conflictSince time.Time- conflictLastSeen time.Time-}--func newHostIdentityFlapTracker() *hostIdentityFlapTracker {- return &hostIdentityFlapTracker{- hostnames: make(map[string]time.Time),- reportIPs: make(map[string]time.Time),- }-}--// observe records one report's identity fields and returns the active-// conflict, or nil when the identity looks healthy.-func (t *hostIdentityFlapTracker) observe(hostname, reportIP string, now time.Time) *models.HostIdentityConflict {- hostname = strings.TrimSpace(hostname)- reportIP = strings.TrimSpace(reportIP)-- pruneOlderThan(t.hostnames, now.Add(-hostIdentityConflictWindow))- pruneOlderThan(t.reportIPs, now.Add(-hostIdentityConflictWindow))-- revisit := false- if hostname != "" {- if _, seen := t.hostnames[hostname]; seen && t.lastHostname != "" && t.lastHostname != hostname {- revisit = true- }- t.hostnames[hostname] = now- t.lastHostname = hostname- }- if reportIP != "" {- if _, seen := t.reportIPs[reportIP]; seen && t.lastReportIP != "" && t.lastReportIP != reportIP {- revisit = true- }- t.reportIPs[reportIP] = now- t.lastReportIP = reportIP- }-- if revisit {- if t.conflictSince.IsZero() || now.Sub(t.conflictLastSeen) > hostIdentityConflictWindow {- t.conflictSince = now- }- t.conflictLastSeen = now- }-- if t.conflictLastSeen.IsZero() || now.Sub(t.conflictLastSeen) > hostIdentityConflictWindow {- t.conflictSince = time.Time{}- t.conflictLastSeen = time.Time{}- return nil- }-- conflict := &models.HostIdentityConflict{- Hostnames: sortedKeys(t.hostnames),- FirstSeen: t.conflictSince,- LastSeen: t.conflictLastSeen,- }- // Report IPs are only interesting when they themselves diverge; when the- // clones alternate hostnames the hostname list already carries the story.- if len(t.reportIPs) > 1 {- conflict.ReportIPs = sortedKeys(t.reportIPs)- }- return conflict-}-// trackHostAgentIdentity feeds one report's identity fields into the flap// tracker for the resolved host identifier and returns the active conflict,-// if any. Callers must not hold m.mu.+// if any. The secondary identity field is the report IP: MSP-style template+// deployments often reuse hostnames too (pve01 at two sites), leaving the+// address as the only field that betrays the clone. Callers must not hold+// m.mu.func (m *Monitor) trackHostAgentIdentity(identifier, hostname, reportIP string, now time.Time) *models.HostIdentityConflict {- if strings.TrimSpace(identifier) == "" {+ conflict := m.observeIdentityFlap(&m.hostIdentityFlaps, hostIdentityConflictWindow, identifier, hostname, reportIP, now)+ if conflict == nil {return nil}-- m.mu.Lock()- defer m.mu.Unlock()- if m.hostIdentityFlaps == nil {- m.hostIdentityFlaps = make(map[string]*hostIdentityFlapTracker)- }- tracker, ok := m.hostIdentityFlaps[identifier]- if !ok {- tracker = newHostIdentityFlapTracker()- m.hostIdentityFlaps[identifier] = tracker+ return &models.HostIdentityConflict{+ Hostnames: conflict.hostnames,+ ReportIPs: conflict.secondaries,+ FirstSeen: conflict.firstSeen,+ LastSeen: conflict.lastSeen,}- return tracker.observe(hostname, reportIP, now)}// clearHostAgentIdentityTrackingLocked drops flap state for a host identity,diff --git a/internal/monitoring/host_identity_conflict_test.go b/internal/monitoring/host_identity_conflict_test.goindex 31b3cafd0d..945a2f7faf 100644--- a/internal/monitoring/host_identity_conflict_test.go+++ b/internal/monitoring/host_identity_conflict_test.go@@ -7,58 +7,15 @@ import (agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host")-func TestHostIdentityFlapTrackerDetectsAlternatingHostnames(t *testing.T) {- tracker := newHostIdentityFlapTracker()- base := time.Date(2026, 7, 27, 12, 0, 0, 0, time.UTC)- interval := 30 * time.Second-- if conflict := tracker.observe("clone-a", "", base); conflict != nil {- t.Fatalf("first report should not conflict, got %+v", conflict)- }- // First switch could be a legitimate rename, so it must not warn yet.- if conflict := tracker.observe("clone-b", "", base.Add(interval)); conflict != nil {- t.Fatalf("single hostname switch should not conflict, got %+v", conflict)- }- // The revisit of clone-a proves two machines are alternating.- conflict := tracker.observe("clone-a", "", base.Add(2*interval))- if conflict == nil {- t.Fatal("expected conflict after hostname revisit")- }- if len(conflict.Hostnames) != 2 || conflict.Hostnames[0] != "clone-a" || conflict.Hostnames[1] != "clone-b" {- t.Fatalf("expected sorted hostnames [clone-a clone-b], got %v", conflict.Hostnames)- }- if len(conflict.ReportIPs) != 0 {- t.Fatalf("absent report IPs should not be listed as conflicting, got %v", conflict.ReportIPs)- }- if conflict.FirstSeen.IsZero() || conflict.LastSeen.IsZero() {- t.Fatalf("expected conflict timestamps, got %+v", conflict)- }-- // Continued flapping keeps the conflict alive and refreshes LastSeen.- later := tracker.observe("clone-b", "", base.Add(3*interval))- if later == nil {- t.Fatal("expected conflict to persist while flapping continues")- }- if !later.LastSeen.After(conflict.LastSeen) {- t.Fatalf("expected LastSeen to advance, got %v then %v", conflict.LastSeen, later.LastSeen)- }- if !later.FirstSeen.Equal(conflict.FirstSeen) {- t.Fatalf("expected FirstSeen to be stable, got %v then %v", conflict.FirstSeen, later.FirstSeen)- }-}--func TestHostIdentityFlapTrackerDetectsAlternatingReportIPsBehindOneHostname(t *testing.T) {- // MSP template deployments reuse hostnames across sites (pve01 at two- // customers), so the alternating report IP is the only field that betrays- // the clone.- tracker := newHostIdentityFlapTracker()+func TestTrackHostAgentIdentityTranslatesConflict(t *testing.T) {+ monitor := newTestMonitor(t)base := time.Date(2026, 7, 27, 12, 0, 0, 0, time.UTC)- tracker.observe("pve01", "192.168.1.10", base)- if conflict := tracker.observe("pve01", "10.0.0.10", base.Add(30*time.Second)); conflict != nil {- t.Fatalf("single report IP switch should not conflict, got %+v", conflict)- }- conflict := tracker.observe("pve01", "192.168.1.10", base.Add(60*time.Second))+ // When the report IPs behind one host identity diverge, the model's+ // ReportIPs field must carry them alongside the shared hostname.+ monitor.trackHostAgentIdentity("host-1", "pve01", "192.168.1.10", base)+ monitor.trackHostAgentIdentity("host-1", "pve01", "10.0.0.10", base.Add(30*time.Second))+ conflict := monitor.trackHostAgentIdentity("host-1", "pve01", "192.168.1.10", base.Add(60*time.Second))if conflict == nil {t.Fatal("expected conflict after report IP revisit")}@@ -68,36 +25,8 @@ func TestHostIdentityFlapTrackerDetectsAlternatingReportIPsBehindOneHostname(t *if len(conflict.ReportIPs) != 2 || conflict.ReportIPs[0] != "10.0.0.10" || conflict.ReportIPs[1] != "192.168.1.10" {t.Fatalf("expected sorted report IPs [10.0.0.10 192.168.1.10], got %v", conflict.ReportIPs)}-}--func TestHostIdentityFlapTrackerIgnoresSingleRename(t *testing.T) {- tracker := newHostIdentityFlapTracker()- base := time.Date(2026, 7, 27, 12, 0, 0, 0, time.UTC)-- if conflict := tracker.observe("old-name", "", base); conflict != nil {- t.Fatalf("unexpected conflict: %+v", conflict)- }- for i := 1; i <= 5; i++ {- if conflict := tracker.observe("new-name", "", base.Add(time.Duration(i)*30*time.Second)); conflict != nil {- t.Fatalf("rename should never conflict, got %+v on report %d", conflict, i)- }- }-}--func TestHostIdentityFlapTrackerConflictExpiresAfterWindow(t *testing.T) {- tracker := newHostIdentityFlapTracker()- base := time.Date(2026, 7, 27, 12, 0, 0, 0, time.UTC)-- tracker.observe("clone-a", "", base)- tracker.observe("clone-b", "", base.Add(30*time.Second))- if conflict := tracker.observe("clone-a", "", base.Add(60*time.Second)); conflict == nil {- t.Fatal("expected conflict after revisit")- }-- // One clone goes away; steady reports from the survivor eventually clear it.- steady := base.Add(60 * time.Second).Add(hostIdentityConflictWindow + time.Minute)- if conflict := tracker.observe("clone-a", "", steady); conflict != nil {- t.Fatalf("expected conflict to expire after quiet window, got %+v", conflict)+ if conflict.FirstSeen.IsZero() || conflict.LastSeen.IsZero() {+ t.Fatalf("expected conflict timestamps, got %+v", conflict)}}diff --git a/internal/monitoring/identity_flap_tracker.go b/internal/monitoring/identity_flap_tracker.gonew file mode 100644index 0000000000..c12653d4e2--- /dev/null+++ b/internal/monitoring/identity_flap_tracker.go@@ -0,0 +1,141 @@+package monitoring++import (+ "sort"+ "strings"+ "time"+)++// identityFlapTracker is the shared revisit-detection core behind the+// Docker-host and host-agent identity conflict trackers. It watches the+// stream of (hostname, secondary) identity pairs folded into a single+// resource identity and detects when two distinct machines are behind it.+//+// The signal is a *revisit*: a value switches away from the previous one and+// back to one already seen inside the window. A genuine rename transitions+// exactly once and never revisits the old value, so it does not trip the+// detector; clones that share an identity alternate every report cycle and+// trip it immediately. The window also controls how long a detected conflict+// stays visible after the flapping stops.+//+// What the secondary field means (machine ID, report IP) is the adapter's+// business; this core only tracks values.+type identityFlapTracker struct {+ window time.Duration++ hostnames map[string]time.Time+ secondaries map[string]time.Time++ lastHostname string+ lastSecondary string++ conflictSince time.Time+ conflictLastSeen time.Time+}++// identityConflict is the tracker's domain-neutral verdict; adapters+// translate it into their platform's conflict model.+type identityConflict struct {+ hostnames []string+ // secondaries is nil unless the secondary values themselves diverge; when+ // clones share one machine ID / report IP the hostname list already+ // carries the story.+ secondaries []string+ firstSeen time.Time+ lastSeen time.Time+}++func newIdentityFlapTracker(window time.Duration) *identityFlapTracker {+ return &identityFlapTracker{+ window: window,+ hostnames: make(map[string]time.Time),+ secondaries: make(map[string]time.Time),+ }+}++// observe records one report's identity fields and returns the active+// conflict, or nil when the identity looks healthy.+func (t *identityFlapTracker) observe(hostname, secondary string, now time.Time) *identityConflict {+ hostname = strings.TrimSpace(hostname)+ secondary = strings.TrimSpace(secondary)++ pruneOlderThan(t.hostnames, now.Add(-t.window))+ pruneOlderThan(t.secondaries, now.Add(-t.window))++ revisit := false+ if hostname != "" {+ if _, seen := t.hostnames[hostname]; seen && t.lastHostname != "" && t.lastHostname != hostname {+ revisit = true+ }+ t.hostnames[hostname] = now+ t.lastHostname = hostname+ }+ if secondary != "" {+ if _, seen := t.secondaries[secondary]; seen && t.lastSecondary != "" && t.lastSecondary != secondary {+ revisit = true+ }+ t.secondaries[secondary] = now+ t.lastSecondary = secondary+ }++ if revisit {+ if t.conflictSince.IsZero() || now.Sub(t.conflictLastSeen) > t.window {+ t.conflictSince = now+ }+ t.conflictLastSeen = now+ }++ if t.conflictLastSeen.IsZero() || now.Sub(t.conflictLastSeen) > t.window {+ t.conflictSince = time.Time{}+ t.conflictLastSeen = time.Time{}+ return nil+ }++ conflict := &identityConflict{+ hostnames: sortedKeys(t.hostnames),+ firstSeen: t.conflictSince,+ lastSeen: t.conflictLastSeen,+ }+ if len(t.secondaries) > 1 {+ conflict.secondaries = sortedKeys(t.secondaries)+ }+ return conflict+}++// observeIdentityFlap feeds one report's identity fields into the flap+// tracker for the resolved identifier, lazily creating the tracker map and+// entry, and returns the active conflict, if any. Callers must not hold m.mu.+func (m *Monitor) observeIdentityFlap(trackers *map[string]*identityFlapTracker, window time.Duration, identifier, hostname, secondary string, now time.Time) *identityConflict {+ if strings.TrimSpace(identifier) == "" {+ return nil+ }++ m.mu.Lock()+ defer m.mu.Unlock()+ if *trackers == nil {+ *trackers = make(map[string]*identityFlapTracker)+ }+ tracker, ok := (*trackers)[identifier]+ if !ok {+ tracker = newIdentityFlapTracker(window)+ (*trackers)[identifier] = tracker+ }+ return tracker.observe(hostname, secondary, now)+}++func pruneOlderThan(entries map[string]time.Time, cutoff time.Time) {+ for key, seenAt := range entries {+ if seenAt.Before(cutoff) {+ delete(entries, key)+ }+ }+}++func sortedKeys(entries map[string]time.Time) []string {+ keys := make([]string, 0, len(entries))+ for key := range entries {+ keys = append(keys, key)+ }+ sort.Strings(keys)+ return keys+}diff --git a/internal/monitoring/identity_flap_tracker_test.go b/internal/monitoring/identity_flap_tracker_test.gonew file mode 100644index 0000000000..ca0a901321--- /dev/null+++ b/internal/monitoring/identity_flap_tracker_test.go@@ -0,0 +1,117 @@+package monitoring++import (+ "testing"+ "time"+)++const testIdentityFlapWindow = 15 * time.Minute++func TestIdentityFlapTrackerDetectsAlternatingHostnames(t *testing.T) {+ tracker := newIdentityFlapTracker(testIdentityFlapWindow)+ base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)+ interval := 30 * time.Second++ if conflict := tracker.observe("clone-a", "machine-1", base); conflict != nil {+ t.Fatalf("first report should not conflict, got %+v", conflict)+ }+ // First switch could be a legitimate rename, so it must not warn yet.+ if conflict := tracker.observe("clone-b", "machine-1", base.Add(interval)); conflict != nil {+ t.Fatalf("single hostname switch should not conflict, got %+v", conflict)+ }+ // The revisit of clone-a proves two machines are alternating.+ conflict := tracker.observe("clone-a", "machine-1", base.Add(2*interval))+ if conflict == nil {+ t.Fatal("expected conflict after hostname revisit")+ }+ if len(conflict.hostnames) != 2 || conflict.hostnames[0] != "clone-a" || conflict.hostnames[1] != "clone-b" {+ t.Fatalf("expected sorted hostnames [clone-a clone-b], got %v", conflict.hostnames)+ }+ if len(conflict.secondaries) != 0 {+ t.Fatalf("shared secondary value should not be listed as conflicting, got %v", conflict.secondaries)+ }+ if conflict.firstSeen.IsZero() || conflict.lastSeen.IsZero() {+ t.Fatalf("expected conflict timestamps, got %+v", conflict)+ }++ // Continued flapping keeps the conflict alive and refreshes lastSeen.+ later := tracker.observe("clone-b", "machine-1", base.Add(3*interval))+ if later == nil {+ t.Fatal("expected conflict to persist while flapping continues")+ }+ if !later.lastSeen.After(conflict.lastSeen) {+ t.Fatalf("expected lastSeen to advance, got %v then %v", conflict.lastSeen, later.lastSeen)+ }+ if !later.firstSeen.Equal(conflict.firstSeen) {+ t.Fatalf("expected firstSeen to be stable, got %v then %v", conflict.firstSeen, later.firstSeen)+ }+}++func TestIdentityFlapTrackerDetectsAlternatingSecondariesBehindOneHostname(t *testing.T) {+ // MSP template deployments reuse hostnames across sites (pve01 at two+ // customers), so the alternating secondary value (report IP) is the only+ // field that betrays the clone.+ tracker := newIdentityFlapTracker(testIdentityFlapWindow)+ base := time.Date(2026, 7, 27, 12, 0, 0, 0, time.UTC)++ tracker.observe("pve01", "192.168.1.10", base)+ if conflict := tracker.observe("pve01", "10.0.0.10", base.Add(30*time.Second)); conflict != nil {+ t.Fatalf("single secondary switch should not conflict, got %+v", conflict)+ }+ conflict := tracker.observe("pve01", "192.168.1.10", base.Add(60*time.Second))+ if conflict == nil {+ t.Fatal("expected conflict after secondary revisit")+ }+ if len(conflict.hostnames) != 1 || conflict.hostnames[0] != "pve01" {+ t.Fatalf("expected shared hostname [pve01], got %v", conflict.hostnames)+ }+ if len(conflict.secondaries) != 2 || conflict.secondaries[0] != "10.0.0.10" || conflict.secondaries[1] != "192.168.1.10" {+ t.Fatalf("expected sorted secondaries [10.0.0.10 192.168.1.10], got %v", conflict.secondaries)+ }+}++func TestIdentityFlapTrackerIgnoresSingleRename(t *testing.T) {+ tracker := newIdentityFlapTracker(testIdentityFlapWindow)+ base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)++ if conflict := tracker.observe("old-name", "machine-1", base); conflict != nil {+ t.Fatalf("unexpected conflict: %+v", conflict)+ }+ for i := 1; i <= 5; i++ {+ if conflict := tracker.observe("new-name", "machine-1", base.Add(time.Duration(i)*30*time.Second)); conflict != nil {+ t.Fatalf("rename should never conflict, got %+v on report %d", conflict, i)+ }+ }+}++func TestIdentityFlapTrackerHandlesAbsentSecondary(t *testing.T) {+ tracker := newIdentityFlapTracker(testIdentityFlapWindow)+ base := time.Date(2026, 7, 27, 12, 0, 0, 0, time.UTC)++ tracker.observe("clone-a", "", base)+ tracker.observe("clone-b", "", base.Add(30*time.Second))+ conflict := tracker.observe("clone-a", "", base.Add(60*time.Second))+ if conflict == nil {+ t.Fatal("expected conflict after hostname revisit")+ }+ if len(conflict.secondaries) != 0 {+ t.Fatalf("absent secondaries should not be listed as conflicting, got %v", conflict.secondaries)+ }+}++func TestIdentityFlapTrackerConflictExpiresAfterWindow(t *testing.T) {+ tracker := newIdentityFlapTracker(testIdentityFlapWindow)+ base := time.Date(2026, 7, 16, 12, 0, 0, 0, time.UTC)++ tracker.observe("clone-a", "machine-1", base)+ tracker.observe("clone-b", "machine-1", base.Add(30*time.Second))+ if conflict := tracker.observe("clone-a", "machine-1", base.Add(60*time.Second)); conflict == nil {+ t.Fatal("expected conflict after revisit")+ }++ // One clone goes away; steady reports from the survivor eventually clear it.+ steady := base.Add(60 * time.Second).Add(testIdentityFlapWindow + time.Minute)+ if conflict := tracker.observe("clone-a", "machine-1", steady); conflict != nil {+ t.Fatalf("expected conflict to expire after quiet window, got %+v", conflict)+ }+}diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 8c23da990d..84877b8653 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1118,14 +1118,14 @@ type Monitor struct {rrdCacheMu sync.RWMutex // Protects short-lived guest memory caches.nodeRRDMemCache map[string]rrdMemCacheEntryvmAgentMemCache map[string]agentMemCacheEntry- removedDockerHosts map[string]time.Time // Track deliberately removed Docker hosts (ID -> removal time)- dockerTokenBindings map[string]string // Track token ID -> Docker host identity bindings to enforce uniqueness- dockerIdentityFlaps map[string]*dockerIdentityFlapTracker // Track per-host identity flapping (cloned VMs sharing machine-id)- removedKubernetesClusters map[string]time.Time // Track deliberately removed Kubernetes clusters (ID -> removal time)- kubernetesTokenBindings map[string]string // Track token ID -> agent ID bindings to enforce uniqueness- removedHostAgents map[string]time.Time // Track deliberately removed host agents (ID -> removal time)- hostTokenBindings map[string]string // Track tokenID:hostname -> host identity bindings- hostIdentityFlaps map[string]*hostIdentityFlapTracker // Track per-host-agent identity flapping (cloned machines sharing machine-id)+ removedDockerHosts map[string]time.Time // Track deliberately removed Docker hosts (ID -> removal time)+ dockerTokenBindings map[string]string // Track token ID -> Docker host identity bindings to enforce uniqueness+ dockerIdentityFlaps map[string]*identityFlapTracker // Track per-host identity flapping (cloned VMs sharing machine-id)+ removedKubernetesClusters map[string]time.Time // Track deliberately removed Kubernetes clusters (ID -> removal time)+ kubernetesTokenBindings map[string]string // Track token ID -> agent ID bindings to enforce uniqueness+ removedHostAgents map[string]time.Time // Track deliberately removed host agents (ID -> removal time)+ hostTokenBindings map[string]string // Track tokenID:hostname -> host identity bindings+ hostIdentityFlaps map[string]*identityFlapTracker // Track per-host-agent identity flapping (cloned machines sharing machine-id)hostReportApplyLocksMu sync.MutexhostReportApplyLocks map[string]*hostReportApplyLockhostReportOrderMu sync.Mutex@@ -1673,12 +1673,12 @@ func New(cfg *config.Config) (*Monitor, error) {vmAgentMemCache: make(map[string]agentMemCacheEntry),removedDockerHosts: make(map[string]time.Time),dockerTokenBindings: make(map[string]string),- dockerIdentityFlaps: make(map[string]*dockerIdentityFlapTracker),+ dockerIdentityFlaps: make(map[string]*identityFlapTracker),removedKubernetesClusters: make(map[string]time.Time),kubernetesTokenBindings: make(map[string]string),removedHostAgents: make(map[string]time.Time),hostTokenBindings: make(map[string]string),- hostIdentityFlaps: make(map[string]*hostIdentityFlapTracker),+ hostIdentityFlaps: make(map[string]*identityFlapTracker),hostReportApplyLocks: make(map[string]*hostReportApplyLock),hostReportOrders: make(map[string]hostReportOrder),clusterSensorsCache: make(map[string]clusterSensorsCacheEntry),diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.goindex 417b5737ad..732eb1ada3 100644--- a/internal/monitoring/monitor_agents.go+++ b/internal/monitoring/monitor_agents.go@@ -1542,8 +1542,8 @@ func (m *Monitor) ClearUnauthenticatedAgents() (int, int) {m.mu.Lock()m.dockerTokenBindings = make(map[string]string)m.hostTokenBindings = make(map[string]string)- m.dockerIdentityFlaps = make(map[string]*dockerIdentityFlapTracker)- m.hostIdentityFlaps = make(map[string]*hostIdentityFlapTracker)+ m.dockerIdentityFlaps = make(map[string]*identityFlapTracker)+ m.hostIdentityFlaps = make(map[string]*identityFlapTracker)m.mu.Unlock()if hostCount > 0 || dockerCount > 0 {diff --git a/internal/notifications/notification_delivery_target_test.go b/internal/notifications/notification_delivery_target_test.goindex 994816faed..4236b588e8 100644--- a/internal/notifications/notification_delivery_target_test.go+++ b/internal/notifications/notification_delivery_target_test.go@@ -94,7 +94,7 @@ func TestGroupedAlertsUseInitialNotifyTarget(t *testing.T) {if err != nil {t.Fatalf("create queue: %v", err)}- defer queue.Stop()+ defer func() { _ = queue.Stop() }()manager := &NotificationManager{enabled: true,diff --git a/internal/storagehealth/risk.go b/internal/storagehealth/risk.goindex eb0f026ecd..1259873cd1 100644--- a/internal/storagehealth/risk.go+++ b/internal/storagehealth/risk.go@@ -55,46 +55,7 @@ func AssessPhysicalDisk(disk models.PhysicalDisk) Assessment {Wearout: disk.Wearout,WearoutKnown: WearoutReported(disk.Wearout, disk.Type),}- if attrs := disk.SmartAttributes; attrs != nil {- if attrs.PowerOnHours != nil {- sample.PowerOnHours = *attrs.PowerOnHours- }- if attrs.PowerCycles != nil {- sample.PowerCycles = *attrs.PowerCycles- }- if attrs.ReallocatedSectors != nil {- sample.ReallocatedSectors = *attrs.ReallocatedSectors- }- if attrs.PendingSectors != nil {- sample.PendingSectors = *attrs.PendingSectors- }- if attrs.OfflineUncorrectable != nil {- sample.OfflineUncorrectable = *attrs.OfflineUncorrectable- }- if attrs.UDMACRCErrors != nil {- sample.UDMACRCErrors = *attrs.UDMACRCErrors- }- if attrs.PercentageUsed != nil {- sample.PercentageUsed = *attrs.PercentageUsed- if remaining := RemainingLifeFromPercentageUsed(*attrs.PercentageUsed); remaining >= 0 {- sample.Wearout = remaining- sample.WearoutKnown = true- } else {- sample.Wearout = -1- sample.WearoutKnown = false- }- }- if attrs.AvailableSpare != nil {- sample.AvailableSpare = *attrs.AvailableSpare- sample.AvailableSpareKnown = true- }- if attrs.MediaErrors != nil {- sample.MediaErrors = *attrs.MediaErrors- }- if attrs.UnsafeShutdowns != nil {- sample.UnsafeShutdowns = *attrs.UnsafeShutdowns- }- }+ applySMARTAttributes(&sample, disk.SmartAttributes)return AssessSample(sample)}@@ -105,47 +66,52 @@ func AssessHostSMARTDisk(disk models.HostDiskSMART) Assessment {Temperature: disk.Temperature,Wearout: -1,}- if attrs := disk.Attributes; attrs != nil {- if attrs.PowerOnHours != nil {- sample.PowerOnHours = *attrs.PowerOnHours- }- if attrs.PowerCycles != nil {- sample.PowerCycles = *attrs.PowerCycles- }- if attrs.ReallocatedSectors != nil {- sample.ReallocatedSectors = *attrs.ReallocatedSectors- }- if attrs.PendingSectors != nil {- sample.PendingSectors = *attrs.PendingSectors- }- if attrs.OfflineUncorrectable != nil {- sample.OfflineUncorrectable = *attrs.OfflineUncorrectable- }- if attrs.UDMACRCErrors != nil {- sample.UDMACRCErrors = *attrs.UDMACRCErrors- }- if attrs.PercentageUsed != nil {- sample.PercentageUsed = *attrs.PercentageUsed- if remaining := RemainingLifeFromPercentageUsed(*attrs.PercentageUsed); remaining >= 0 {- sample.Wearout = remaining- sample.WearoutKnown = true- } else {- sample.Wearout = -1- sample.WearoutKnown = false- }- }- if attrs.AvailableSpare != nil {- sample.AvailableSpare = *attrs.AvailableSpare- sample.AvailableSpareKnown = true- }- if attrs.MediaErrors != nil {- sample.MediaErrors = *attrs.MediaErrors- }- if attrs.UnsafeShutdowns != nil {- sample.UnsafeShutdowns = *attrs.UnsafeShutdowns+ applySMARTAttributes(&sample, disk.Attributes)+ return AssessSample(sample)+}++func applySMARTAttributes(sample *Sample, attrs *models.SMARTAttributes) {+ if attrs == nil {+ return+ }+ if attrs.PowerOnHours != nil {+ sample.PowerOnHours = *attrs.PowerOnHours+ }+ if attrs.PowerCycles != nil {+ sample.PowerCycles = *attrs.PowerCycles+ }+ if attrs.ReallocatedSectors != nil {+ sample.ReallocatedSectors = *attrs.ReallocatedSectors+ }+ if attrs.PendingSectors != nil {+ sample.PendingSectors = *attrs.PendingSectors+ }+ if attrs.OfflineUncorrectable != nil {+ sample.OfflineUncorrectable = *attrs.OfflineUncorrectable+ }+ if attrs.UDMACRCErrors != nil {+ sample.UDMACRCErrors = *attrs.UDMACRCErrors+ }+ if attrs.PercentageUsed != nil {+ sample.PercentageUsed = *attrs.PercentageUsed+ if remaining := RemainingLifeFromPercentageUsed(*attrs.PercentageUsed); remaining >= 0 {+ sample.Wearout = remaining+ sample.WearoutKnown = true+ } else {+ sample.Wearout = -1+ sample.WearoutKnown = false}}- return AssessSample(sample)+ if attrs.AvailableSpare != nil {+ sample.AvailableSpare = *attrs.AvailableSpare+ sample.AvailableSpareKnown = true+ }+ if attrs.MediaErrors != nil {+ sample.MediaErrors = *attrs.MediaErrors+ }+ if attrs.UnsafeShutdowns != nil {+ sample.UnsafeShutdowns = *attrs.UnsafeShutdowns+ }}func AssessSample(sample Sample) Assessment {diff --git a/internal/telemetry/telemetry_test.go b/internal/telemetry/telemetry_test.goindex 3016764259..868a682890 100644--- a/internal/telemetry/telemetry_test.go+++ b/internal/telemetry/telemetry_test.go@@ -1012,7 +1012,9 @@ func TestSend_Success(t *testing.T) {OS: "linux",Arch: "amd64",}- send(ctx, ping)+ if err := send(ctx, ping); err != nil {+ t.Fatalf("send: %v", err)+ }if received.Load() != 1 {t.Fatalf("expected 1 request to reach server, got %d", received.Load())@@ -1053,7 +1055,7 @@ func TestSend_UsesReducedCommercialSignals(t *testing.T) {ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)defer cancel()- send(ctx, Ping{+ if err := send(ctx, Ping{InstallID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",Version: "6.0.0",Event: "heartbeat",@@ -1062,7 +1064,9 @@ func TestSend_UsesReducedCommercialSignals(t *testing.T) {Arch: "amd64",PaidLicense: true,HasAPITokens: true,- })+ }); err != nil {+ t.Fatalf("send: %v", err)+ }var payload map[string]anyif err := json.Unmarshal(rawBody, &payload); err != nil {diff --git a/pkg/audit/sqlite_logger.go b/pkg/audit/sqlite_logger.goindex 58c25ee9dd..5a4e09428d 100644--- a/pkg/audit/sqlite_logger.go+++ b/pkg/audit/sqlite_logger.go@@ -339,7 +339,7 @@ func (l *SQLiteLogger) migrateLegacyTimestamps() error {if err != nil {return err}- defer tx.Rollback()+ defer func() { _ = tx.Rollback() }()needsRebuild, err := auditEventsNeedRebuild(tx)if err != nil {@@ -726,7 +726,7 @@ func (l *SQLiteLogger) QueryPage(filter QueryFilter) ([]Event, int, error) {if err != nil {return err}- defer tx.Rollback()+ defer func() { _ = tx.Rollback() }()events, err = queryAuditEvents(tx, filter)if err != nil {@@ -1080,7 +1080,7 @@ func (l *SQLiteLogger) cleanupOldEvents() {if err != nil {return err}- defer tx.Rollback()+ defer func() { _ = tx.Rollback() }()result, err := tx.Exec(`DELETE FROM audit_events WHERE timestamp < ?`, cutoff)if err != nil {