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(mock): stop real infrastructure reaching mock-mode surfaces

rcourtman59773ce94eab
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f8e4d10ddb..f698262383 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -72,6 +72,21 @@ generates the operator-facing limit description consumed by server ingress
and every supported `pulse-agent` release target built from this source.
+Mock mode is a clean room on the report-admission boundary. Mock mode already
+suspends pull-based PVE/PBS/PMG collection by never building those clients, and
+push-based agent reports are held to the same rule: `ApplyHostReport`,
+`ApplyDockerReport`, and `ApplyKubernetesReport` acknowledge a report with the
+reporting agent's own identity and discard it without touching monitor state.
+Ingesting it would land a real machine in state, where it raises alerts,
+persists host continuity, records metrics, and feeds the online/offline sweep
+beside authored fixtures. Persisted host continuity is suppressed for the same
+reason, because those entries outlive the mock toggle and every consumer injects
+them after the read path has already substituted the mock snapshot. The
+acknowledgement stays a success rather than a rejection so a real agent does not
+read a demo server as an outage and retry-storm it. Tests that assert report
+admission or tenant isolation must therefore not enable mock mode, or the
+assertion passes without exercising the boundary.
+
Physical-disk evidence collected by a host agent must survive projection back
into monitoring's models. Absent evidence has to carry its declared sentinel
rather than a zero value that reads as a real measurement: an absent
diff --git a/docs/release-control/v6/internal/subsystems/alerts.md b/docs/release-control/v6/internal/subsystems/alerts.md
index dc4643e49d..cd76384bb1 100644
--- a/docs/release-control/v6/internal/subsystems/alerts.md
+++ b/docs/release-control/v6/internal/subsystems/alerts.md
@@ -145,6 +145,16 @@ lifecycle when the agent heartbeat is unhealthy, and resolves only when a
fresh result from the currently assigned agent arrives. Notification delivery,
acknowledgement, history, and recovery reuse the normal alert pipeline.
+Active-alert restore is opt-out at construction. `NewManagerWithDataDir` accepts
+`ManagerOption` values, and `WithoutPersistedAlertRestore` starts the manager
+with an empty active-alert set instead of reading `active-alerts.json`. Mock
+mode selects it: switching the mock toggle already clears active alerts, but a
+process that boots with mock mode already enabled never runs that path and would
+otherwise restore alerts raised against real infrastructure and serve them
+beside fixture data. The option changes startup restore only. Alert evaluation,
+persistence, notification, acknowledgement, and history are unaffected, and the
+default construction path still restores.
+
## Canonical Files
1. `internal/alerts/specs/types.go`
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 648b04b1a6..4cd2a96b1d 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -367,6 +367,17 @@ lifecycle, and treats a fresh result from that same assignment as recovery.
Assignment trackers are removed with their targets and reset when agent identity
changes.
+Monitoring ingest keeps mock mode hermetic. The unified read path already
+substitutes the mock snapshot wholesale, so anything that runs after that
+substitution has to be suppressed explicitly rather than assumed hidden. Server
+side agent report application discards real reports while mock mode is on, and
+`recentStandaloneHostContinuityEntries` returns nothing, so persisted continuity
+cannot reappear through the standalone host projection, the host online/offline
+sweep, or availability probe display names. There is no real-polling exception
+on this path: agent ingest is not gated on `PULSE_MOCK_KEEP_REAL_POLLING`, and
+the read state is mock-substituted either way, so injecting real hosts would
+only graft them onto fixture data.
+
## Canonical Files
1. `internal/monitoring/monitor.go`
diff --git a/internal/alerts/alerts_test.go b/internal/alerts/alerts_test.go
index 6ef5d58bc3..b5dfd74d0d 100644
--- a/internal/alerts/alerts_test.go
+++ b/internal/alerts/alerts_test.go
@@ -19734,3 +19734,54 @@ func TestCheckDiskHealthDoesNotAlertOnAbsentWearoutEvidence(t *testing.T) {
})
}
}
+
+// writeActiveAlertsFixture seeds an active-alerts.json holding one alert raised
+// against real infrastructure, the shape a demo data directory inherits when a
+// real agent reported before mock mode was enabled.
+func writeActiveAlertsFixture(t *testing.T, dataDir string) {
+ t.Helper()
+
+ alertsDir := filepath.Join(dataDir, "alerts")
+ if err := os.MkdirAll(alertsDir, 0o755); err != nil {
+ t.Fatalf("create alerts dir: %v", err)
+ }
+ payload, err := json.Marshal([]*Alert{{
+ ID: "agent:real-host/storage:unraid-array",
+ Type: "storage-topology",
+ Level: AlertLevelWarning,
+ ResourceID: "agent:real-host/storage:unraid-array",
+ ResourceName: "Tower - Unraid Array",
+ Node: "Tower",
+ StartTime: time.Now().Add(-time.Hour),
+ }})
+ if err != nil {
+ t.Fatalf("marshal alert fixture: %v", err)
+ }
+ if err := os.WriteFile(filepath.Join(alertsDir, "active-alerts.json"), payload, 0o600); err != nil {
+ t.Fatalf("write alert fixture: %v", err)
+ }
+}
+
+func TestManagerRestoresPersistedAlertsByDefault(t *testing.T) {
+ dataDir := t.TempDir()
+ writeActiveAlertsFixture(t, dataDir)
+
+ m := NewManagerWithDataDir(dataDir)
+ t.Cleanup(m.Stop)
+
+ if got := len(m.GetActiveAlerts()); got != 1 {
+ t.Fatalf("default manager must restore persisted alerts, got %d", got)
+ }
+}
+
+func TestManagerSkipsPersistedAlertRestoreForMockMode(t *testing.T) {
+ dataDir := t.TempDir()
+ writeActiveAlertsFixture(t, dataDir)
+
+ m := NewManagerWithDataDir(dataDir, WithoutPersistedAlertRestore())
+ t.Cleanup(m.Stop)
+
+ for _, alert := range m.GetActiveAlerts() {
+ t.Fatalf("mock mode must not resurface real persisted alerts, got %+v", alert)
+ }
+}
diff --git a/internal/alerts/manager.go b/internal/alerts/manager.go
index a6d083add2..269e76c1dc 100644
--- a/internal/alerts/manager.go
+++ b/internal/alerts/manager.go
@@ -121,9 +121,35 @@ func NewManager() *Manager {
return NewManagerWithDataDir(utils.GetDataDir())
}
+// ManagerOption adjusts how a Manager is constructed.
+type ManagerOption func(*managerOptions)
+
+type managerOptions struct {
+ skipPersistedAlertRestore bool
+}
+
+// WithoutPersistedAlertRestore starts the manager with an empty active-alert
+// set instead of restoring active-alerts.json from disk. Mock mode uses this so
+// a demo session never resurfaces alerts raised against real infrastructure:
+// SetMockMode already clears active alerts when the toggle flips, but a process
+// that starts with mock mode already enabled never runs that path and would
+// otherwise reload the persisted real alerts.
+func WithoutPersistedAlertRestore() ManagerOption {
+ return func(opts *managerOptions) {
+ opts.skipPersistedAlertRestore = true
+ }
+}
+
// NewManagerWithDataDir creates a new alert manager with a custom data directory.
// This enables tenant-scoped alert persistence in multi-tenant deployments.
-func NewManagerWithDataDir(dataDir string) *Manager {
+func NewManagerWithDataDir(dataDir string, options ...ManagerOption) *Manager {
+ opts := managerOptions{}
+ for _, option := range options {
+ if option != nil {
+ option(&opts)
+ }
+ }
+
if strings.TrimSpace(dataDir) == "" {
dataDir = utils.GetDataDir()
}
@@ -176,7 +202,9 @@ func NewManagerWithDataDir(dataDir string) *Manager {
}
// Load saved active alerts
- if err := m.LoadActiveAlerts(); err != nil {
+ if opts.skipPersistedAlertRestore {
+ log.Info().Msg("skipping persisted active alert restore")
+ } else if err := m.LoadActiveAlerts(); err != nil {
log.Error().Err(err).Msg("failed to load active alerts")
}
diff --git a/internal/api/hosted_agent_install_command_test.go b/internal/api/hosted_agent_install_command_test.go
index 3c21e4bad8..6a64c2bcdf 100644
--- a/internal/api/hosted_agent_install_command_test.go
+++ b/internal/api/hosted_agent_install_command_test.go
@@ -162,7 +162,11 @@ func TestHostedTenantAgentInstallTokenCannotReportToOtherTenant(t *testing.T) {
defer SetMultiTenantEnabled(false)
SetMultiTenantEnabled(true)
t.Setenv("PULSE_DEV", "true")
- setMockModeForTest(t, true)
+ // Deliberately NOT mock mode. Mock mode drops real agent reports on the
+ // floor, which would leave both tenants empty and make the isolation
+ // assertion below pass without ever exercising the boundary. The tenants
+ // here have no configured infrastructure, so nothing polls anyway.
+ setMockModeForTest(t, false)
dataDir := t.TempDir()
cfg := &config.Config{
diff --git a/internal/monitoring/kubernetes_agents.go b/internal/monitoring/kubernetes_agents.go
index 827750f562..cf7a17979c 100644
--- a/internal/monitoring/kubernetes_agents.go
+++ b/internal/monitoring/kubernetes_agents.go
@@ -9,6 +9,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/logging"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
agentsk8s "github.com/rcourtman/pulse-go-rewrite/pkg/agents/kubernetes"
"github.com/rs/zerolog"
@@ -39,6 +40,15 @@ func normalizeKubernetesClusterIdentifier(report agentsk8s.Report) string {
// ApplyKubernetesReport ingests a Kubernetes agent report into state.
func (m *Monitor) ApplyKubernetesReport(report agentsk8s.Report, tokenRecord *config.APITokenRecord) (models.KubernetesCluster, error) {
+ if mock.IsMockEnabled() {
+ // See ApplyHostReport: mock mode drops real push-based reports rather
+ // than mixing a real cluster into the fixture fabric.
+ return models.KubernetesCluster{
+ ID: strings.TrimSpace(report.Cluster.ID),
+ Name: strings.TrimSpace(report.Cluster.Name),
+ }, nil
+ }
+
identifier := normalizeKubernetesClusterIdentifier(report)
if strings.TrimSpace(identifier) == "" {
return models.KubernetesCluster{}, fmt.Errorf("kubernetes report missing cluster identifier")
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 067399486b..33c82f30d7 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -59,6 +59,18 @@ func keepRealPollingInMockMode() bool {
}
}
+// alertManagerRestoreOptions keeps mock mode a clean room across process
+// restarts. SetMockMode clears active alerts when the toggle flips, but a
+// process that boots with mock mode already enabled never runs that path, so
+// alerts raised against real infrastructure are restored from disk and served
+// beside fixture data until something clears them.
+func alertManagerRestoreOptions() []alerts.ManagerOption {
+ if mock.IsMockEnabled() {
+ return []alerts.ManagerOption{alerts.WithoutPersistedAlertRestore()}
+ }
+ return nil
+}
+
// newProxmoxClientFunc is a variable that holds the function to create a new Proxmox client.
// It is used to allow mocking the client creation in tests.
var newProxmoxClientFunc = func(cfg proxmox.ClientConfig) (PVEClientInterface, error) {
@@ -1653,7 +1665,7 @@ func New(cfg *config.Config) (*Monitor, error) {
rateTracker: NewRateTracker(),
metricsHistory: NewMetricsHistory(1000, 24*time.Hour), // Keep up to 1000 points (~8h @ 30s)
metricsStore: metricsStore, // Persistent SQLite storage
- alertManager: alerts.NewManagerWithDataDir(cfg.DataPath),
+ alertManager: alerts.NewManagerWithDataDir(cfg.DataPath, alertManagerRestoreOptions()...),
incidentStore: incidentStore,
notificationMgr: notifications.NewNotificationManagerWithDataDir(cfg.PublicURL, cfg.DataPath),
configPersist: config.NewConfigPersistence(cfg.DataPath),
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index 178dc67fe4..32bfd8c24d 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -11,6 +11,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/agentupdate"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/internal/logging"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/platformsupport"
"github.com/rcourtman/pulse-go-rewrite/internal/remoteconfig"
@@ -1434,10 +1435,44 @@ func hostFromContinuityEntry(entry config.HostContinuityEntry) models.Host {
}
}
+// mockDiscardedHostReportAck echoes the reporting agent's own identity back to
+// it without touching monitor state, so the ingest response keeps its usual
+// shape for a report mock mode deliberately dropped.
+func mockDiscardedHostReportAck(report agentshost.Report) models.Host {
+ hostname := strings.TrimSpace(report.Host.Hostname)
+ if hostname == "" {
+ hostname = strings.TrimSpace(report.Agent.Hostname)
+ }
+ return models.Host{
+ ID: strings.TrimSpace(report.Agent.ID),
+ Hostname: hostname,
+ DisplayName: strings.TrimSpace(report.Host.DisplayName),
+ Platform: strings.TrimSpace(report.Host.Platform),
+ OSName: strings.TrimSpace(report.Host.OSName),
+ OSVersion: strings.TrimSpace(report.Host.OSVersion),
+ AgentVersion: strings.TrimSpace(report.Agent.Version),
+ LastSeen: report.Timestamp,
+ }
+}
+
func (m *Monitor) recentStandaloneHostContinuityEntries() []config.HostContinuityEntry {
if m == nil || m.hostContinuityStore == nil {
return nil
}
+ // Mock mode is a clean room. Continuity entries are persisted to disk from
+ // real agent reports and outlive the mock toggle, and every consumer of
+ // this list injects them after the read path has already substituted the
+ // mock snapshot: standalone host continuity lands on Machines, host-offline
+ // alerts fire, and availability probe alerts resolve display names. A real
+ // machine that reported before mock mode was enabled would therefore
+ // resurface by its real hostname inside an otherwise synthetic view.
+ // Unlike the connections ledger there is no real-polling exception here,
+ // because agent ingestion is not gated on PULSE_MOCK_KEEP_REAL_POLLING and
+ // the unified read state is mock-substituted wholesale either way, so
+ // injecting real hosts would only graft them onto mock data.
+ if mock.IsMockEnabled() {
+ return nil
+ }
return m.hostContinuityStore.RecentEntries(m.hostContinuitySince(time.Now().UTC()))
}
@@ -1646,6 +1681,17 @@ func (m *Monitor) supersedeStaleDockerHostDuplicates(current models.DockerHost,
// ApplyDockerReport ingests a Docker / Podman module report into the shared state.
func (m *Monitor) ApplyDockerReport(report agentsdocker.Report, tokenRecord *config.APITokenRecord) (models.DockerHost, error) {
+ if mock.IsMockEnabled() {
+ // See ApplyHostReport: mock mode drops real push-based reports rather
+ // than mixing real containers into the fixture fabric.
+ return models.DockerHost{
+ ID: strings.TrimSpace(report.Agent.ID),
+ Hostname: strings.TrimSpace(report.Host.Hostname),
+ DisplayName: strings.TrimSpace(report.Host.Name),
+ LastSeen: report.Timestamp,
+ }, nil
+ }
+
readState := m.snapshotBackedUnifiedReadState()
var dockerHosts []*unifiedresources.DockerHostView
if readState != nil {
@@ -2400,6 +2446,17 @@ func (m *Monitor) supersedeStaleHostAgentDuplicates(current models.Host, tokenRe
// ApplyHostReport ingests a host agent report into the shared state.
func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.APITokenRecord) (models.Host, error) {
+ if mock.IsMockEnabled() {
+ // Mock mode suspends real pull-based collection outright (PVE/PBS/PMG
+ // clients are never built), and push-based agent reports get the same
+ // treatment. Ingesting them would land a real machine in state, where
+ // it raises alerts, persists host continuity, records metrics, and
+ // feeds the online/offline sweep, all beside fixture data. The report
+ // is acknowledged rather than rejected so a real agent does not read a
+ // demo server as an outage and retry-storm it.
+ return mockDiscardedHostReportAck(report), nil
+ }
+
m.hostAgentLifecycleMu.RLock()
defer m.hostAgentLifecycleMu.RUnlock()
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index 1817f4a884..eacac07a18 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -4944,3 +4944,120 @@ func TestMonitorStopQuiescesMetadataWritesBeforeReturning(t *testing.T) {
t.Fatalf("data directory not removable after Stop: %v", err)
}
}
+
+// TestMockModeDropsRealHostContinuity pins the mock-mode clean room on the
+// standalone host continuity path. Continuity entries are persisted to disk
+// from real agent reports and survive the mock toggle, and every consumer
+// injects them after the read path has already substituted the mock snapshot,
+// so without a guard a real machine that reported before mock mode was enabled
+// resurfaces on Machines by its real hostname.
+func TestMockModeDropsRealHostContinuity(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ if err := mock.SetEnabled(true); err != nil {
+ t.Fatalf("enable mock mode: %v", err)
+ }
+ t.Cleanup(func() { _ = mock.SetEnabled(previous) })
+
+ store := config.NewHostContinuityStore(t.TempDir(), nil)
+ if err := store.Upsert(config.HostContinuityEntry{
+ HostID: "real-host-1",
+ ReportHostID: "real-machine-1",
+ Hostname: "real-machine.lan",
+ DisplayName: "Real Machine",
+ MachineID: "real-machine-1",
+ AgentVersion: "6.2.0",
+ Platform: "darwin",
+ LastSeen: time.Now().UTC(),
+ }); err != nil {
+ t.Fatalf("Upsert continuity: %v", err)
+ }
+
+ m := &Monitor{
+ state: models.NewState(),
+ resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)),
+ hostContinuityStore: store,
+ }
+
+ for _, host := range m.HostsSnapshot() {
+ if host.Hostname == "real-machine.lan" || host.ID == "real-host-1" {
+ t.Fatalf("real continuity host leaked into the mock read state: %#v", host)
+ }
+ }
+
+ // The suppression must be mock-scoped, not a removal of continuity itself:
+ // with mock mode off the same store still backs the standalone host.
+ if err := mock.SetEnabled(false); err != nil {
+ t.Fatalf("disable mock mode: %v", err)
+ }
+ hosts := m.HostsSnapshot()
+ if len(hosts) != 1 || hosts[0].Hostname != "real-machine.lan" {
+ t.Fatalf("real mode must still restore continuity-backed hosts, got %#v", hosts)
+ }
+}
+
+// TestMockModeDiscardsRealHostReports pins the push-side of the mock clean
+// room. Mock mode already suspends pull-based PVE/PBS/PMG collection, but a
+// real agent keeps POSTing regardless; ingesting those reports lands a real
+// machine in state where it raises alerts and feeds the offline sweep beside
+// fixture data.
+func TestMockModeDiscardsRealHostReports(t *testing.T) {
+ report := agentshost.Report{
+ Agent: agentshost.AgentInfo{ID: "real-agent-1", Version: "6.2.0"},
+ Host: agentshost.HostInfo{
+ ID: "real-agent-1",
+ Hostname: "real-machine.lan",
+ Platform: "linux",
+ OSName: "Unraid",
+ },
+ Timestamp: time.Now().UTC(),
+ }
+
+ newMonitor := func(t *testing.T) *Monitor {
+ t.Helper()
+ return &Monitor{
+ state: models.NewState(),
+ resourceStore: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil)),
+ hostContinuityStore: config.NewHostContinuityStore(t.TempDir(), nil),
+ rateTracker: NewRateTracker(),
+ }
+ }
+
+ t.Run("mock mode acknowledges without ingesting", func(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ if err := mock.SetEnabled(true); err != nil {
+ t.Fatalf("enable mock mode: %v", err)
+ }
+ t.Cleanup(func() { _ = mock.SetEnabled(previous) })
+
+ m := newMonitor(t)
+ host, err := m.ApplyHostReport(report, nil)
+ if err != nil {
+ t.Fatalf("mock mode must acknowledge rather than reject the report: %v", err)
+ }
+ if host.ID != "real-agent-1" || host.Hostname != "real-machine.lan" {
+ t.Fatalf("acknowledgement must echo the reporting agent identity, got %+v", host)
+ }
+ if got := m.GetLiveHostsSnapshot(); len(got) != 0 {
+ t.Fatalf("real host reached monitor state in mock mode: %#v", got)
+ }
+ if got := m.recentStandaloneHostContinuityEntries(); len(got) != 0 {
+ t.Fatalf("real host continuity persisted in mock mode: %#v", got)
+ }
+ })
+
+ t.Run("real mode still ingests", func(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ if err := mock.SetEnabled(false); err != nil {
+ t.Fatalf("disable mock mode: %v", err)
+ }
+ t.Cleanup(func() { _ = mock.SetEnabled(previous) })
+
+ m := newMonitor(t)
+ if _, err := m.ApplyHostReport(report, nil); err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+ if got := m.GetLiveHostsSnapshot(); len(got) != 1 {
+ t.Fatalf("real mode must still ingest host reports, got %#v", got)
+ }
+ })
+}