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.

Fix offline host visibility/alerting across restarts (#1311)

rcourtmanff9dc34687a5
diff --git a/internal/config/host_runtime_store.go b/internal/config/host_runtime_store.go
new file mode 100644
index 0000000000..a5190aa3a0
--- /dev/null
+++ b/internal/config/host_runtime_store.go
@@ -0,0 +1,148 @@
+package config
+
+import (
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+ "github.com/rs/zerolog/log"
+)
+
+const hostRuntimeFileName = "host_runtime_hosts.json"
+
+// HostRuntimeStore persists the last known host-agent state so hosts remain
+// visible across server restarts, even while agents are offline.
+type HostRuntimeStore struct {
+ mu sync.RWMutex
+ hosts map[string]models.Host // keyed by host ID
+ dataPath string
+ fs FileSystem
+}
+
+// NewHostRuntimeStore creates a host runtime store and loads existing data.
+func NewHostRuntimeStore(dataPath string, fs FileSystem) *HostRuntimeStore {
+ store := &HostRuntimeStore{
+ hosts: make(map[string]models.Host),
+ dataPath: dataPath,
+ fs: fs,
+ }
+
+ if store.fs == nil {
+ store.fs = defaultFileSystem{}
+ }
+
+ if err := store.Load(); err != nil {
+ log.Warn().Err(err).Msg("Failed to load host runtime store")
+ }
+
+ return store
+}
+
+// Load reads host runtime data from disk.
+func (s *HostRuntimeStore) Load() error {
+ filePath := filepath.Join(s.dataPath, hostRuntimeFileName)
+
+ data, err := s.fs.ReadFile(filePath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ return nil
+ }
+ return fmt.Errorf("failed to read host runtime file: %w", err)
+ }
+
+ var decoded map[string]models.Host
+ if err := json.Unmarshal(data, &decoded); err != nil {
+ return fmt.Errorf("failed to decode host runtime file: %w", err)
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.hosts = make(map[string]models.Host, len(decoded))
+ for hostID, host := range decoded {
+ if hostID == "" {
+ continue
+ }
+ host.ID = hostID
+ s.hosts[hostID] = host
+ }
+
+ return nil
+}
+
+// GetAll returns a copy of all persisted hosts keyed by ID.
+func (s *HostRuntimeStore) GetAll() map[string]models.Host {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ result := make(map[string]models.Host, len(s.hosts))
+ for hostID, host := range s.hosts {
+ result[hostID] = host
+ }
+ return result
+}
+
+// Upsert inserts or updates a persisted host entry.
+func (s *HostRuntimeStore) Upsert(host models.Host) error {
+ hostID := host.ID
+ if hostID == "" {
+ return fmt.Errorf("host id is required")
+ }
+
+ host.ID = hostID
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.hosts[hostID] = host
+ return s.saveLocked()
+}
+
+// Delete removes a persisted host entry.
+func (s *HostRuntimeStore) Delete(hostID string) error {
+ if hostID == "" {
+ return nil
+ }
+
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ delete(s.hosts, hostID)
+ return s.saveLocked()
+}
+
+// Clear removes all persisted host runtime entries.
+func (s *HostRuntimeStore) Clear() error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.hosts = make(map[string]models.Host)
+ return s.saveLocked()
+}
+
+func (s *HostRuntimeStore) saveLocked() error {
+ filePath := filepath.Join(s.dataPath, hostRuntimeFileName)
+
+ data, err := json.Marshal(s.hosts)
+ if err != nil {
+ return fmt.Errorf("failed to encode host runtime file: %w", err)
+ }
+
+ if err := s.fs.MkdirAll(s.dataPath, 0755); err != nil {
+ return fmt.Errorf("failed to ensure host runtime directory: %w", err)
+ }
+
+ tempPath := filePath + ".tmp"
+ if err := s.fs.WriteFile(tempPath, data, 0644); err != nil {
+ return fmt.Errorf("failed to write host runtime temp file: %w", err)
+ }
+
+ if err := s.fs.Rename(tempPath, filePath); err != nil {
+ return fmt.Errorf("failed to replace host runtime file: %w", err)
+ }
+
+ return nil
+}
diff --git a/internal/config/host_runtime_store_test.go b/internal/config/host_runtime_store_test.go
new file mode 100644
index 0000000000..a4545d0969
--- /dev/null
+++ b/internal/config/host_runtime_store_test.go
@@ -0,0 +1,75 @@
+package config
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/models"
+)
+
+func TestHostRuntimeStoreCRUD(t *testing.T) {
+ dir := t.TempDir()
+ store := NewHostRuntimeStore(dir, nil)
+
+ lastSeen := time.Now().UTC().Truncate(time.Second)
+ host := models.Host{
+ ID: "host-1",
+ Hostname: "node-1.local",
+ DisplayName: "Node 1",
+ Status: "online",
+ IntervalSeconds: 30,
+ LastSeen: lastSeen,
+ TokenID: "token-1",
+ }
+
+ if err := store.Upsert(host); err != nil {
+ t.Fatalf("Upsert: %v", err)
+ }
+
+ reloaded := NewHostRuntimeStore(dir, nil)
+ all := reloaded.GetAll()
+ if len(all) != 1 {
+ t.Fatalf("expected 1 host, got %d", len(all))
+ }
+ got := all["host-1"]
+ if got.Hostname != host.Hostname {
+ t.Fatalf("hostname = %q, want %q", got.Hostname, host.Hostname)
+ }
+ if !got.LastSeen.Equal(lastSeen) {
+ t.Fatalf("lastSeen = %v, want %v", got.LastSeen, lastSeen)
+ }
+ if got.TokenID != host.TokenID {
+ t.Fatalf("tokenID = %q, want %q", got.TokenID, host.TokenID)
+ }
+
+ if err := reloaded.Delete("host-1"); err != nil {
+ t.Fatalf("Delete: %v", err)
+ }
+ if gotCount := len(reloaded.GetAll()); gotCount != 0 {
+ t.Fatalf("expected 0 hosts after delete, got %d", gotCount)
+ }
+}
+
+func TestHostRuntimeStoreClear(t *testing.T) {
+ dir := t.TempDir()
+ store := NewHostRuntimeStore(dir, nil)
+
+ if err := store.Upsert(models.Host{ID: "host-1", Hostname: "one"}); err != nil {
+ t.Fatalf("Upsert host-1: %v", err)
+ }
+ if err := store.Upsert(models.Host{ID: "host-2", Hostname: "two"}); err != nil {
+ t.Fatalf("Upsert host-2: %v", err)
+ }
+
+ if err := store.Clear(); err != nil {
+ t.Fatalf("Clear: %v", err)
+ }
+ if gotCount := len(store.GetAll()); gotCount != 0 {
+ t.Fatalf("expected 0 hosts after clear, got %d", gotCount)
+ }
+
+ reloaded := NewHostRuntimeStore(dir, nil)
+ if gotCount := len(reloaded.GetAll()); gotCount != 0 {
+ t.Fatalf("expected reloaded store to stay empty, got %d", gotCount)
+ }
+}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 19a393ac45..df328a6105 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -772,6 +772,7 @@ type Monitor struct {
guestMetadataStore *config.GuestMetadataStore
dockerMetadataStore *config.DockerMetadataStore
hostMetadataStore *config.HostMetadataStore
+ hostRuntimeStore *config.HostRuntimeStore
mu sync.RWMutex
startTime time.Time
rateTracker *RateTracker
@@ -810,6 +811,7 @@ type Monitor struct {
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
hostTokenBindings map[string]string // Track tokenID:hostname -> host identity bindings
+ lastHostRuntimePersist map[string]time.Time // Track last persisted host runtime write per host ID
dockerCommands map[string]*dockerHostCommand
dockerCommandIndex map[string]string
guestMetadataMu sync.RWMutex
@@ -1153,6 +1155,7 @@ const (
dockerConnectionPrefix = "docker-"
kubernetesConnectionPrefix = "kubernetes-"
hostConnectionPrefix = "host-"
+ hostRuntimePersistInterval = 2 * time.Minute
dockerOfflineGraceMultiplier = 4
dockerMinimumHealthWindow = 30 * time.Second
dockerMaximumHealthWindow = 10 * time.Minute
@@ -1437,6 +1440,173 @@ func (m *Monitor) RemoveDockerHost(hostID string) (models.DockerHost, error) {
return host, nil
}
+func hostRuntimeIdentityChanged(previous, current models.Host) bool {
+ if previous.ID != current.ID ||
+ previous.Hostname != current.Hostname ||
+ previous.DisplayName != current.DisplayName ||
+ previous.Platform != current.Platform ||
+ previous.OSName != current.OSName ||
+ previous.OSVersion != current.OSVersion ||
+ previous.KernelVersion != current.KernelVersion ||
+ previous.Architecture != current.Architecture ||
+ previous.CPUCount != current.CPUCount ||
+ previous.IntervalSeconds != current.IntervalSeconds ||
+ previous.AgentVersion != current.AgentVersion ||
+ previous.TokenID != current.TokenID ||
+ previous.TokenName != current.TokenName ||
+ previous.TokenHint != current.TokenHint ||
+ previous.CommandsEnabled != current.CommandsEnabled ||
+ previous.ReportIP != current.ReportIP ||
+ previous.IsLegacy != current.IsLegacy ||
+ previous.LinkedNodeID != current.LinkedNodeID ||
+ previous.LinkedVMID != current.LinkedVMID ||
+ previous.LinkedContainerID != current.LinkedContainerID {
+ return true
+ }
+
+ if len(previous.Tags) != len(current.Tags) {
+ return true
+ }
+ for i := range previous.Tags {
+ if previous.Tags[i] != current.Tags[i] {
+ return true
+ }
+ }
+
+ if len(previous.DiskExclude) != len(current.DiskExclude) {
+ return true
+ }
+ for i := range previous.DiskExclude {
+ if previous.DiskExclude[i] != current.DiskExclude[i] {
+ return true
+ }
+ }
+
+ if previous.TokenLastUsedAt == nil && current.TokenLastUsedAt == nil {
+ return false
+ }
+ if (previous.TokenLastUsedAt == nil) != (current.TokenLastUsedAt == nil) {
+ return true
+ }
+
+ return !previous.TokenLastUsedAt.Equal(*current.TokenLastUsedAt)
+}
+
+func (m *Monitor) persistHostRuntimeSnapshot(host models.Host, force bool) {
+ if m == nil || m.hostRuntimeStore == nil || strings.TrimSpace(host.ID) == "" {
+ return
+ }
+
+ now := time.Now()
+
+ m.mu.Lock()
+ if m.lastHostRuntimePersist == nil {
+ m.lastHostRuntimePersist = make(map[string]time.Time)
+ }
+ lastPersisted := m.lastHostRuntimePersist[host.ID]
+ shouldPersist := force || lastPersisted.IsZero() || now.Sub(lastPersisted) >= hostRuntimePersistInterval
+ m.mu.Unlock()
+
+ if !shouldPersist {
+ return
+ }
+
+ if err := m.hostRuntimeStore.Upsert(host); err != nil {
+ log.Warn().Err(err).Str("hostID", host.ID).Msg("Failed to persist host runtime snapshot")
+ return
+ }
+
+ m.mu.Lock()
+ if m.lastHostRuntimePersist == nil {
+ m.lastHostRuntimePersist = make(map[string]time.Time)
+ }
+ m.lastHostRuntimePersist[host.ID] = now
+ m.mu.Unlock()
+}
+
+func (m *Monitor) deletePersistedHostRuntime(hostID string) {
+ if m == nil || m.hostRuntimeStore == nil || strings.TrimSpace(hostID) == "" {
+ return
+ }
+
+ if err := m.hostRuntimeStore.Delete(hostID); err != nil {
+ log.Warn().Err(err).Str("hostID", hostID).Msg("Failed to delete persisted host runtime snapshot")
+ }
+
+ m.mu.Lock()
+ delete(m.lastHostRuntimePersist, hostID)
+ m.mu.Unlock()
+}
+
+func (m *Monitor) clearPersistedHostRuntime() {
+ if m == nil || m.hostRuntimeStore == nil {
+ return
+ }
+
+ if err := m.hostRuntimeStore.Clear(); err != nil {
+ log.Warn().Err(err).Msg("Failed to clear persisted host runtime snapshots")
+ }
+
+ m.mu.Lock()
+ m.lastHostRuntimePersist = make(map[string]time.Time)
+ m.mu.Unlock()
+}
+
+func (m *Monitor) restorePersistedHostAgents() {
+ if m == nil || m.state == nil || m.hostRuntimeStore == nil {
+ return
+ }
+
+ persisted := m.hostRuntimeStore.GetAll()
+ if len(persisted) == 0 {
+ return
+ }
+
+ now := time.Now().UTC()
+ restoredCount := 0
+ for hostID, host := range persisted {
+ resolvedID := strings.TrimSpace(host.ID)
+ if resolvedID == "" {
+ resolvedID = strings.TrimSpace(hostID)
+ }
+ hostname := strings.TrimSpace(host.Hostname)
+ if resolvedID == "" || hostname == "" {
+ continue
+ }
+
+ host.ID = resolvedID
+ host.Hostname = hostname
+ if strings.TrimSpace(host.DisplayName) == "" {
+ host.DisplayName = host.Hostname
+ }
+ if host.LastSeen.IsZero() {
+ host.LastSeen = now.Add(-hostMaximumHealthWindow)
+ }
+ host.Status = "offline"
+
+ // Keep server-side command override consistent on restore.
+ if cfg := m.GetHostAgentConfig(host.ID); cfg.CommandsEnabled != nil {
+ host.CommandsEnabled = *cfg.CommandsEnabled
+ }
+
+ m.state.UpsertHost(host)
+ m.state.SetConnectionHealth(hostConnectionPrefix+host.ID, false)
+
+ m.mu.Lock()
+ if m.lastHostRuntimePersist == nil {
+ m.lastHostRuntimePersist = make(map[string]time.Time)
+ }
+ m.lastHostRuntimePersist[host.ID] = now
+ m.mu.Unlock()
+
+ restoredCount++
+ }
+
+ if restoredCount > 0 {
+ log.Info().Int("hosts", restoredCount).Msg("Restored host agents from persisted runtime state")
+ }
+}
+
// RemoveHostAgent removes a host agent from monitoring state and clears related data.
func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
hostID = strings.TrimSpace(hostID)
@@ -1552,6 +1722,8 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
m.alertManager.HandleHostRemoved(host)
}
+ m.deletePersistedHostRuntime(hostID)
+
return host, nil
}
@@ -1996,6 +2168,7 @@ func (m *Monitor) ClearUnauthenticatedAgents() (int, int) {
// Clear all hosts
hostCount := m.state.ClearAllHosts()
+ m.clearPersistedHostRuntime()
// Clear all docker hosts
dockerCount := m.state.ClearAllDockerHosts()
@@ -2829,6 +3002,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
m.state.UpsertHost(host)
m.state.SetConnectionHealth(hostConnectionPrefix+host.ID, true)
+ m.persistHostRuntimeSnapshot(host, !hasPrevious || hostRuntimeIdentityChanged(previous, host))
// Update the linked PVE node to point back to this host agent
if host.LinkedNodeID != "" {
@@ -3864,6 +4038,7 @@ func New(cfg *config.Config) (*Monitor, error) {
guestMetadataStore: config.NewGuestMetadataStore(cfg.DataPath, nil),
dockerMetadataStore: config.NewDockerMetadataStore(cfg.DataPath, nil),
hostMetadataStore: config.NewHostMetadataStore(cfg.DataPath, nil),
+ hostRuntimeStore: config.NewHostRuntimeStore(cfg.DataPath, nil),
startTime: time.Now(),
rateTracker: NewRateTracker(),
metricsHistory: NewMetricsHistory(1000, 24*time.Hour), // Keep up to 1000 points (~8h @ 30s)
@@ -3893,6 +4068,7 @@ func New(cfg *config.Config) (*Monitor, error) {
removedKubernetesClusters: make(map[string]time.Time),
kubernetesTokenBindings: make(map[string]string),
hostTokenBindings: make(map[string]string),
+ lastHostRuntimePersist: make(map[string]time.Time),
dockerCommands: make(map[string]*dockerHostCommand),
dockerCommandIndex: make(map[string]string),
guestMetadataCache: make(map[string]guestMetadataCacheEntry),
@@ -3929,6 +4105,11 @@ func New(cfg *config.Config) (*Monitor, error) {
// Initialize state with config values
m.state.TemperatureMonitoringEnabled = cfg.TemperatureMonitoringEnabled
+ // Rehydrate last known host agents to preserve offline visibility/alerting
+ // when Pulse restarts while agents are offline.
+ m.restorePersistedHostAgents()
+ m.RebuildTokenBindings()
+
if m.pollMetrics != nil {
m.pollMetrics.ResetQueueDepth(0)
}
@@ -6897,6 +7078,7 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
guestRaw.BalloonMin = detailedStatus.BalloonMin
guestRaw.Agent = detailedStatus.Agent.Value
memAvailable := uint64(0)
+ memInfoTotalMinusUsed := uint64(0)
if detailedStatus.MemInfo != nil {
guestRaw.MemInfoUsed = detailedStatus.MemInfo.Used
guestRaw.MemInfoFree = detailedStatus.MemInfo.Free
@@ -6906,28 +7088,12 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
guestRaw.MemInfoCached = detailedStatus.MemInfo.Cached
guestRaw.MemInfoShared = detailedStatus.MemInfo.Shared
- // Derive memAvailable from balloon MemInfo. Prefer Available (most
- // accurate), then Free+Buffers+Cached when cache metrics are present.
- // When Buffers=0 AND Cached=0, the balloon isn't reporting cache
- // breakdown — using Free alone gives wildly inflated usage because
- // reclaimable page cache is counted as used. In that case, skip and
- // fall through to RRD/guest-agent fallbacks. Refs: #1302, #1270
- switch {
- case detailedStatus.MemInfo.Available > 0:
- memAvailable = detailedStatus.MemInfo.Available
- memorySource = "meminfo-available"
- case detailedStatus.MemInfo.Buffers > 0 || detailedStatus.MemInfo.Cached > 0:
- memAvailable = detailedStatus.MemInfo.Free +
- detailedStatus.MemInfo.Buffers +
- detailedStatus.MemInfo.Cached
- memorySource = "meminfo-derived"
- }
-
- // Record Total-Used for diagnostics even when not used as the source
- if detailedStatus.MemInfo.Total > 0 &&
- detailedStatus.MemInfo.Used > 0 &&
- detailedStatus.MemInfo.Total >= detailedStatus.MemInfo.Used {
- guestRaw.MemInfoTotalMinusUsed = detailedStatus.MemInfo.Total - detailedStatus.MemInfo.Used
+ selection := selectVMAvailableFromMemInfo(detailedStatus.MemInfo)
+ memInfoTotalMinusUsed = selection.TotalMinusUsed
+ guestRaw.MemInfoTotalMinusUsed = memInfoTotalMinusUsed
+ if selection.Available > 0 {
+ memAvailable = selection.Available
+ memorySource = selection.Source
}
}
@@ -7015,16 +7181,10 @@ func (m *Monitor) pollVMsAndContainersEfficient(ctx context.Context, instanceNam
}
}
- // Last-chance MemInfo fallback: when balloon reports Used/Total but no
- // cache breakdown (Buffers=Cached=0), use Total-Used. This may equal
- // Free (if Used=Total-Free) but is still better than status-mem which
- // can be even more inflated. Placed after RRD/agent so those get
- // priority. Refs: #1302, #1270
- if memAvailable == 0 && detailedStatus.MemInfo != nil &&
- detailedStatus.MemInfo.Total > 0 &&
- detailedStatus.MemInfo.Used > 0 &&
- detailedStatus.MemInfo.Total >= detailedStatus.MemInfo.Used {
- memAvailable = detailedStatus.MemInfo.Total - detailedStatus.MemInfo.Used
+ // Last-chance MemInfo fallback: use Total-Used only after RRD/agent
+ // attempts, so those more reliable cache-aware sources get priority.
+ if memAvailable == 0 && memInfoTotalMinusUsed > 0 {
+ memAvailable = memInfoTotalMinusUsed
memorySource = "meminfo-total-minus-used"
}
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index 6fd6627375..62afd3a54d 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -68,6 +68,143 @@ func TestEvaluateHostAgentsTriggersOfflineAlert(t *testing.T) {
}
}
+func TestRestorePersistedHostAgents(t *testing.T) {
+ dataDir := t.TempDir()
+ runtimeStore := config.NewHostRuntimeStore(dataDir, nil)
+ metadataStore := config.NewHostMetadataStore(dataDir, nil)
+
+ now := time.Now().UTC()
+ if err := runtimeStore.Upsert(models.Host{
+ ID: "host-restored",
+ Hostname: "restored.local",
+ DisplayName: "Restored Host",
+ Status: "online",
+ IntervalSeconds: 30,
+ LastSeen: now.Add(-5 * time.Minute),
+ TokenID: "token-restored",
+ }); err != nil {
+ t.Fatalf("seed runtime store: %v", err)
+ }
+
+ enabled := true
+ if err := metadataStore.Set("host-restored", &config.HostMetadata{CommandsEnabled: &enabled}); err != nil {
+ t.Fatalf("set host metadata: %v", err)
+ }
+
+ monitor := &Monitor{
+ state: models.NewState(),
+ config: &config.Config{APITokens: []config.APITokenRecord{{ID: "token-restored"}}},
+ hostMetadataStore: metadataStore,
+ hostRuntimeStore: runtimeStore,
+ hostTokenBindings: make(map[string]string),
+ lastHostRuntimePersist: make(map[string]time.Time),
+ }
+
+ monitor.restorePersistedHostAgents()
+ monitor.RebuildTokenBindings()
+
+ snapshot := monitor.state.GetSnapshot()
+ if len(snapshot.Hosts) != 1 {
+ t.Fatalf("expected 1 restored host, got %d", len(snapshot.Hosts))
+ }
+ restored := snapshot.Hosts[0]
+ if restored.ID != "host-restored" {
+ t.Fatalf("restored host id = %q, want host-restored", restored.ID)
+ }
+ if restored.Status != "offline" {
+ t.Fatalf("restored host status = %q, want offline", restored.Status)
+ }
+ if !restored.CommandsEnabled {
+ t.Fatalf("expected commandsEnabled override to apply on restore")
+ }
+
+ connKey := hostConnectionPrefix + restored.ID
+ if healthy, ok := snapshot.ConnectionHealth[connKey]; !ok || healthy {
+ t.Fatalf("expected restored host connection health false, got %v (exists=%v)", healthy, ok)
+ }
+
+ if boundID := monitor.hostTokenBindings["token-restored:restored.local"]; boundID != "host-restored" {
+ t.Fatalf("expected token binding to be rebuilt, got %q", boundID)
+ }
+}
+
+func TestApplyHostReportPersistsAndRemoveHostAgentClearsRuntime(t *testing.T) {
+ dataDir := t.TempDir()
+ runtimeStore := config.NewHostRuntimeStore(dataDir, nil)
+
+ monitor := &Monitor{
+ state: models.NewState(),
+ alertManager: alerts.NewManager(),
+ hostTokenBindings: make(map[string]string),
+ config: &config.Config{},
+ rateTracker: NewRateTracker(),
+ hostRuntimeStore: runtimeStore,
+ lastHostRuntimePersist: make(map[string]time.Time),
+ }
+ t.Cleanup(func() { monitor.alertManager.Stop() })
+
+ report := agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: "agent-runtime",
+ Version: "1.0.0",
+ IntervalSeconds: 30,
+ },
+ Host: agentshost.HostInfo{
+ ID: "machine-runtime",
+ Hostname: "runtime.local",
+ Platform: "linux",
+ },
+ Timestamp: time.Now().UTC(),
+ Metrics: agentshost.Metrics{
+ CPUUsagePercent: 5.5,
+ },
+ }
+
+ host, err := monitor.ApplyHostReport(report, nil)
+ if err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+
+ if persisted := runtimeStore.GetAll(); len(persisted) != 1 {
+ t.Fatalf("expected 1 persisted host after report, got %d", len(persisted))
+ }
+
+ if _, err := monitor.RemoveHostAgent(host.ID); err != nil {
+ t.Fatalf("RemoveHostAgent: %v", err)
+ }
+
+ if persisted := runtimeStore.GetAll(); len(persisted) != 0 {
+ t.Fatalf("expected persisted host to be removed, got %d entries", len(persisted))
+ }
+}
+
+func TestClearUnauthenticatedAgentsClearsPersistedHostRuntime(t *testing.T) {
+ dataDir := t.TempDir()
+ runtimeStore := config.NewHostRuntimeStore(dataDir, nil)
+ if err := runtimeStore.Upsert(models.Host{ID: "host-clear", Hostname: "clear.local", LastSeen: time.Now().UTC()}); err != nil {
+ t.Fatalf("seed runtime store: %v", err)
+ }
+
+ monitor := &Monitor{
+ state: models.NewState(),
+ config: &config.Config{},
+ hostRuntimeStore: runtimeStore,
+ hostTokenBindings: make(map[string]string),
+ dockerTokenBindings: make(map[string]string),
+ lastHostRuntimePersist: make(map[string]time.Time),
+ }
+ monitor.state.UpsertHost(models.Host{ID: "host-clear", Hostname: "clear.local"})
+
+ hostCount, dockerCount := monitor.ClearUnauthenticatedAgents()
+ if hostCount != 1 || dockerCount != 0 {
+ t.Fatalf("ClearUnauthenticatedAgents = (%d,%d), want (1,0)", hostCount, dockerCount)
+ }
+
+ if persisted := runtimeStore.GetAll(); len(persisted) != 0 {
+ t.Fatalf("expected persisted runtime store to be cleared, got %d entries", len(persisted))
+ }
+}
+
func TestEvaluateHostAgentsClearsAlertWhenHostReturns(t *testing.T) {
t.Helper()