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.

Stabilize rc1 mock mode and metrics history

rcourtman1e28a03b57d9
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 09cd958493..0be504a0ec 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -462,6 +462,17 @@ must flow through the canonical `/api/metrics-store/history` boundary and the
disk `MetricsTarget.ResourceID` that monitoring projects for the resource,
rather than reviving a browser-local collector or a lifecycle-only
agent/device identity.
+That same adjacent API boundary now also owns internal demo-fixture runtime
+gating. Lifecycle-adjacent install, reporting, and demo-facing flows may
+share mock-mode handlers in dev and test, but release builds must authorize
+runtime mock rewiring only through the internal `demo_fixtures` entitlement,
+and browser-facing lifecycle surfaces must not infer or persist that internal
+grant from public runtime-capabilities or presentation-policy payloads.
+Shared workload-chart reads that lifecycle surfaces reuse must stay
+presentation-only on that same boundary: `internal/api/router.go` may batch
+those reads in parallel, but it must request only the canonical rendered
+metric set for workload cards instead of widening the hot path back to
+fetch-all metrics on behalf of install or reporting callers.
That shared `internal/api/` dependency now also assumes hosted tenant AI and
relay bootstrap reads use one effective hosted billing lease before
lifecycle-adjacent flows inspect runtime readiness, so install and setup
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 9e1c6607ff..6bf0850cb3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -508,6 +508,13 @@ readiness. API contracts must not serialize a live monitored-system count from
the first store-backed read-state when provider-owned inventories such as
TrueNAS or VMware have not yet completed an initial baseline and been rebuilt
into the canonical monitor store.
+That same workload-chart boundary now also owns the rendered-metric budget on
+the shared monitoring routes. `/api/charts/workloads` and
+`/api/charts/workloads-summary` may batch provider-backed reads in parallel,
+but they must request only the canonical workload metrics they actually
+serialize (`cpu`, `memory`, `disk`, `netin`, `netout`), with Kubernetes pods
+staying on that same five-metric set, instead of widening back to disk
+read/write or fetch-all backend batches that the browser never renders.
The shared metrics-history contract now also owns physical-disk live I/O
windows. `/api/metrics-store/history` must accept `resourceType=disk`, keep
`30m` as a valid compact live range, and resolve `disk`, `diskread`,
@@ -606,6 +613,14 @@ entitlement to authorize mock fixture data and `/api/system/mock-mode`
transitions, but browser-facing entitlement and runtime payloads must filter
that capability back out so public callers never learn or depend on internal
demo-fixture grants.
+That same shared licensing boundary now also owns release-build enforcement of
+that internal demo-fixture capability. Dev and test builds may keep local
+fixture proof tolerant so mock-backed demos can be exercised without a paid
+grant, but release builds must gate runtime mock rewiring through the
+build-tagged `shouldEnforceReleaseDemoFixtureRuntime()` contract before
+`syncReleaseDemoFixtureRuntime()` can enable fixtures on a live server.
+Browser payloads and public-demo callers must still never see or depend on
+that internal grant.
That same shared API contract now also owns browser-proofed read separation.
Non-billing browser journeys such as
`tests/integration/tests/11-first-session.spec.ts`,
diff --git a/docs/release-control/v6/internal/subsystems/cloud-paid.md b/docs/release-control/v6/internal/subsystems/cloud-paid.md
index 5276240b95..8658e1117a 100644
--- a/docs/release-control/v6/internal/subsystems/cloud-paid.md
+++ b/docs/release-control/v6/internal/subsystems/cloud-paid.md
@@ -187,6 +187,12 @@ That same cloud-paid/browser boundary now also governs public demo posture.
surfaces must not reveal self-hosted license metadata, hosted billing state,
monitored-system ledgers, upgrade nudges, or activation controls just because
the underlying runtime is commercially enabled.
+That same cloud-paid boundary now also owns release-demo fixture secrecy.
+Release builds may enforce the internal `demo_fixtures` entitlement before
+enabling mock fixture runtime state, but browser-visible licensing and
+commercial payloads must still filter that capability back out and must not
+let cloud-paid surfaces treat dev/test fixture toggles as plan, billing, or
+upgrade truth.
That same resolved presentation policy also governs hosted organization chrome
inside the demo/browser shell: app bootstrap may retain an internal default
org context for hosted API routing, but `frontend-modern/src/useAppRuntimeState.ts`,
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 9aa3d78a5a..a7ad18105a 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -158,6 +158,20 @@ or restart discovery until the canonical mock runtime has accepted the
requested mode change; rejected release-demo fixture enables must fail before
any monitoring reset so the live preview does not blank itself on an
unauthorized toggle.
+That same monitoring boundary now also owns atomic unified-metric persistence.
+When unified resource sync projects agent, VM, app-container, or storage
+metrics into persisted history, it must append in-memory history first and
+flush the backing store through one `metrics.WriteBatchSync` batch per sync
+sweep instead of per-metric async writes, so canonical chart history cannot
+race itself into partial persisted windows.
+That same chart boundary now also owns long-range in-memory coverage
+selection. `internal/monitoring/metrics_history.go` must expose guest and node
+coverage spans for the requested metric families, and
+`internal/monitoring/monitor_metrics.go` must prefer the in-memory history
+when that span already covers the requested chart window before falling back
+to SQLite, so long-range chart batches do not pay an unnecessary store round
+trip just because the request is larger than the old fixed in-memory
+threshold.
That same monitoring owner also owns canonical unified-resource publication on
`/api/state` and the websocket `state.resources` hydrate path. Monitoring must
publish those resources from the same canonical unified snapshot that
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index d2717fb272..a2a2207d4f 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -314,6 +314,18 @@ queries. Compact dashboard routes that request only CPU/memory or only
storage `used`/`avail` capacity must keep that metric-type filter all the way
through `pkg/metrics/store.go` instead of fetching every series for every
resource and discarding the extra payload in higher layers.
+That same protected workload-chart hot path now also owns rendered-metric
+budgeting. `internal/api/router.go` may parallelize VM, container, pod, and
+docker-container workload batch reads, but `/api/charts/workloads` and
+`/api/charts/workloads-summary` must request only the canonical five workload
+metrics they actually render instead of widening back to disk read/write or
+fetch-all history queries.
+That same chart-batch hot path now also owns long-range in-memory coverage.
+`internal/monitoring/monitor_metrics.go` may skip SQLite for guest and node
+chart batches when `metrics_history` can prove the requested window is
+already covered in memory, and performance work must preserve that
+coverage-gated fast path rather than treating every long-duration request as
+store-backed by default.
That same hot path now also covers mock-mode cache warmth. The canonical
24-hour `/api/charts/storage-summary` dashboard transport must stay prewarmed
across live mock sampler ticks so the first dashboard request after a refresh
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 7eca9f7cc7..8dffe94b49 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -514,6 +514,13 @@ in the app shell, but they must not cache, derive, or replay the
server-resolved portal checkout state or owned billing purchase-arrival state
as recovery route state, restore evidence, or storage-local navigation
context.
+That same adjacent licensing boundary now also owns internal demo-fixture
+runtime gating for storage- and recovery-adjacent surfaces. Release builds may
+authorize mock fixture rewiring only through the backend-owned
+`demo_fixtures` entitlement, but storage and recovery browsers must continue
+to consume the redacted public runtime/commercial contracts and must not infer
+internal fixture grants or persisted mock state from those shared licensing
+routes.
Storage- or recovery-adjacent commercial helpers must therefore wait for the
shared presentation policy to resolve before attempting any read that could
otherwise hit a hidden commercial route during bootstrap.
@@ -524,6 +531,12 @@ resource's canonical history target. Storage must not keep a drawer-local live
metrics collector, agent-id/device fallback stream, or separate real-time
history store once monitoring and `/api/metrics-store/history` already own the
disk timeline.
+Shared chart transport that storage and recovery coexist with must also stay
+on rendered-metric budgets. When `internal/api/router.go` batches workload
+history for adjacent overview or shared summary cards, it may parallelize the
+provider reads, but it must not widen the shared hot path to disk read/write
+or fetch-all metrics just because storage or recovery also mount nearby chart
+shells.
Storage and recovery still consume the shared unified-resource contract, but
they do not own the timeline store itself. The canonical resource-change
diff --git a/internal/api/ai_handlers_more_test.go b/internal/api/ai_handlers_more_test.go
index 01bf406bb5..0c58122a60 100644
--- a/internal/api/ai_handlers_more_test.go
+++ b/internal/api/ai_handlers_more_test.go
@@ -443,7 +443,7 @@ func TestAISettingsHandler_GetPersistence_NonDefaultInvalidOrgFailsClosedWhenMul
}
func TestAISettingsHandler_GetAIService_NonDefaultInvalidOrgReturnsFailClosedTenantService(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "false")
+ setMockModeForTest(t, false)
mtp := config.NewMultiTenantPersistence(t.TempDir())
mtm := monitoring.NewMultiTenantMonitor(&config.Config{}, mtp, nil)
@@ -475,7 +475,7 @@ func TestAISettingsHandler_GetAIService_NonDefaultInvalidOrgReturnsFailClosedTen
}
func TestNewAISettingsHandler_DefaultServiceAlwaysInitialized(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "false")
+ setMockModeForTest(t, false)
handler := NewAISettingsHandler(nil, nil, nil)
svc := handler.GetAIService(context.Background())
@@ -488,7 +488,7 @@ func TestNewAISettingsHandler_DefaultServiceAlwaysInitialized(t *testing.T) {
}
func TestAISettingsHandler_GetAIService_NonDefaultWithTenantMonitorWithoutPersistenceFailsClosed(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "false")
+ setMockModeForTest(t, false)
mtp := config.NewMultiTenantPersistence(t.TempDir())
mtm := monitoring.NewMultiTenantMonitor(&config.Config{}, mtp, nil)
diff --git a/internal/api/ai_handlers_stream_test.go b/internal/api/ai_handlers_stream_test.go
index b0e49d3301..6de0a8b3ee 100644
--- a/internal/api/ai_handlers_stream_test.go
+++ b/internal/api/ai_handlers_stream_test.go
@@ -3,7 +3,6 @@ package api
import (
"bytes"
"encoding/json"
- "os"
"strings"
"testing"
@@ -30,18 +29,6 @@ func (s stubLicenseChecker) GetLicenseStateString() (string, bool) {
return "expired", false
}
-func withEnv(t *testing.T, key, value string, fn func()) {
- t.Helper()
- old := os.Getenv(key)
- if err := os.Setenv(key, value); err != nil {
- t.Fatalf("setenv failed: %v", err)
- }
- defer func() {
- _ = os.Setenv(key, old)
- }()
- fn()
-}
-
func newTestAISettingsHandlerWithService(t *testing.T) *AISettingsHandler {
t.Helper()
tmp := t.TempDir()
@@ -56,58 +43,58 @@ func newTestAISettingsHandlerWithService(t *testing.T) *AISettingsHandler {
}
func TestHandleExecuteStream_LicenseRequired(t *testing.T) {
- withEnv(t, "PULSE_MOCK_MODE", "true", func() {
- handler := newTestAISettingsHandlerWithService(t)
- handler.defaultAIService.SetLicenseChecker(stubLicenseChecker{allow: false})
-
- body := `{"prompt":"hi","use_case":"autofix"}`
- req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))
- rec := httptest.NewRecorder()
- handler.HandleExecuteStream(rec, req)
-
- if rec.Code != http.StatusPaymentRequired {
- t.Fatalf("expected payment required, got %d", rec.Code)
- }
- if !strings.Contains(rec.Body.String(), "license_required") {
- t.Fatalf("expected license error body")
- }
- })
+ setMockModeForTest(t, true)
+
+ handler := newTestAISettingsHandlerWithService(t)
+ handler.defaultAIService.SetLicenseChecker(stubLicenseChecker{allow: false})
+
+ body := `{"prompt":"hi","use_case":"autofix"}`
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleExecuteStream(rec, req)
+
+ if rec.Code != http.StatusPaymentRequired {
+ t.Fatalf("expected payment required, got %d", rec.Code)
+ }
+ if !strings.Contains(rec.Body.String(), "license_required") {
+ t.Fatalf("expected license error body")
+ }
}
func TestHandleExecuteStream_PromptRequired(t *testing.T) {
- withEnv(t, "PULSE_MOCK_MODE", "true", func() {
- handler := newTestAISettingsHandlerWithService(t)
-
- body := `{"prompt":""}`
- req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))
- rec := httptest.NewRecorder()
- handler.HandleExecuteStream(rec, req)
-
- if rec.Code != http.StatusBadRequest {
- t.Fatalf("expected bad request, got %d", rec.Code)
- }
- })
+ setMockModeForTest(t, true)
+
+ handler := newTestAISettingsHandlerWithService(t)
+
+ body := `{"prompt":""}`
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleExecuteStream(rec, req)
+
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected bad request, got %d", rec.Code)
+ }
}
func TestHandleExecuteStream_Success(t *testing.T) {
- withEnv(t, "PULSE_MOCK_MODE", "true", func() {
- handler := newTestAISettingsHandlerWithService(t)
-
- body := `{"prompt":"hello"}`
- req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))
- rec := httptest.NewRecorder()
- handler.HandleExecuteStream(rec, req)
-
- if rec.Code != http.StatusOK {
- t.Fatalf("expected OK, got %d", rec.Code)
- }
- if !strings.Contains(rec.Header().Get("Content-Type"), "text/event-stream") {
- t.Fatalf("expected SSE content type")
- }
- if !strings.Contains(rec.Body.String(), `"tool_calls":[]`) {
- t.Fatalf("expected stream completion event to retain tool_calls array, got %s", rec.Body.String())
- }
- })
+ setMockModeForTest(t, true)
+
+ handler := newTestAISettingsHandlerWithService(t)
+
+ body := `{"prompt":"hello"}`
+ req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleExecuteStream(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected OK, got %d", rec.Code)
+ }
+ if !strings.Contains(rec.Header().Get("Content-Type"), "text/event-stream") {
+ t.Fatalf("expected SSE content type")
+ }
+ if !strings.Contains(rec.Body.String(), `"tool_calls":[]`) {
+ t.Fatalf("expected stream completion event to retain tool_calls array, got %s", rec.Body.String())
+ }
}
func TestAIExecuteStreamCompleteEvent_UsesCanonicalEmptyCollections(t *testing.T) {
diff --git a/internal/api/ai_intelligence_handlers_data_additional_test.go b/internal/api/ai_intelligence_handlers_data_additional_test.go
index 0f634f2d1d..b4198090d1 100644
--- a/internal/api/ai_intelligence_handlers_data_additional_test.go
+++ b/internal/api/ai_intelligence_handlers_data_additional_test.go
@@ -80,7 +80,7 @@ func seedCorrelationDetector(now time.Time) *ai.CorrelationDetector {
func TestHandleGetPatterns_UnlockedWithData(t *testing.T) {
// License gates were removed from intelligence endpoints (9279358c).
// Even with allow=false, data is returned without redaction.
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
handler, _ := setupAIHandlerWithIntelligence(t)
handler.defaultAIService.SetPatternDetector(seedPatternDetector(time.Now()))
@@ -118,7 +118,7 @@ func TestHandleGetPatterns_UnlockedWithData(t *testing.T) {
}
func TestHandleGetPredictions_WithData(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
handler, _ := setupAIHandlerWithIntelligence(t)
handler.defaultAIService.SetPatternDetector(seedPatternDetector(time.Now()))
@@ -154,7 +154,7 @@ func TestHandleGetPredictions_WithData(t *testing.T) {
}
func TestHandleGetCorrelations_WithData(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
handler, _ := setupAIHandlerWithIntelligence(t)
handler.defaultAIService.SetCorrelationDetector(seedCorrelationDetector(time.Now()))
diff --git a/internal/api/ai_intelligence_handlers_test.go b/internal/api/ai_intelligence_handlers_test.go
index be38f0719f..bc80050adf 100644
--- a/internal/api/ai_intelligence_handlers_test.go
+++ b/internal/api/ai_intelligence_handlers_test.go
@@ -233,7 +233,7 @@ func TestHandleGetCorrelations_ResourceIDFilter(t *testing.T) {
}
func TestHandleGetCorrelations_UsesCanonicalIntelligenceFacade(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
handler, _ := setupAIHandlerWithIntelligence(t)
handler.defaultAIService.SetCorrelationDetector(seedCorrelationDetector(time.Now()))
diff --git a/internal/api/auth_context_tenant_test.go b/internal/api/auth_context_tenant_test.go
index dd5b119f17..2c132fa31f 100644
--- a/internal/api/auth_context_tenant_test.go
+++ b/internal/api/auth_context_tenant_test.go
@@ -6,15 +6,12 @@ import (
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
- "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
internalauth "github.com/rcourtman/pulse-go-rewrite/pkg/auth"
)
func TestExtractAndStoreAuthContext_UsesTenantConfigForToken(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
- mock.SetEnabled(true)
- t.Cleanup(func() { mock.SetEnabled(false) })
+ setMockModeForTest(t, true)
baseCfg := &config.Config{
DataPath: t.TempDir(),
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 4a089a59ab..5cbfe74ec8 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -1444,6 +1444,36 @@ func TestContract_WorkloadsSummaryChartsNormalizeLongRangeMixedCadence(t *testin
}
}
+func TestContract_WorkloadChartMetricBudgetGuardrailsRemainCanonical(t *testing.T) {
+ data, err := os.ReadFile("router.go")
+ if err != nil {
+ t.Fatalf("failed to read router.go: %v", err)
+ }
+ source := string(data)
+
+ requiredSnippets := []string{
+ `var workloadSummaryMetricOrder = []string{`,
+ `"cpu",`,
+ `"memory",`,
+ `"disk",`,
+ `"netin",`,
+ `"netout",`,
+ `var workloadChartsBatchWG sync.WaitGroup`,
+ `workloadChartsBatchWG.Add(4)`,
+ `podBatchMetrics = monitor.GetGuestMetricsForChartBatch("k8s", podRequests, duration, workloadSummaryMetricOrder...)`,
+ `var workloadsSummaryBatchWG sync.WaitGroup`,
+ `workloadsSummaryBatchWG.Add(4)`,
+ `vmBatchMetrics = monitor.GetGuestMetricsForChartBatch("vm", vmRequests, duration, workloadSummaryMetricOrder...)`,
+ `containerBatchMetrics = monitor.GetGuestMetricsForChartBatch("container", containerRequests, duration, workloadSummaryMetricOrder...)`,
+ `dockerContainerBatchMetrics = monitor.GetGuestMetricsForChartBatch("dockerContainer", dockerContainerRequests, duration, workloadSummaryMetricOrder...)`,
+ }
+ for _, snippet := range requiredSnippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("router.go must contain %q", snippet)
+ }
+ }
+}
+
func TestContract_GenerateStyledMockSeries_UsesTimestampBasedCurve(t *testing.T) {
now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC).UnixMilli()
@@ -6215,6 +6245,39 @@ func TestContract_DemoModeCommercialSurfacePolicy(t *testing.T) {
})
}
+func TestContract_ReleaseDemoFixtureRuntimeGuardrailsRemainCanonical(t *testing.T) {
+ requiredSnippets := map[string][]string{
+ "licensing_handlers.go": {
+ "func (h *LicenseHandlers) syncReleaseDemoFixtureRuntime(orgID string, service *licenseService) {",
+ "if !shouldEnforceReleaseDemoFixtureRuntime() {",
+ "authorized := h.demoFixturesAuthorized(service)",
+ "mock.SetReleaseFixturesAuthorized(authorized)",
+ "if !wantsMockFixturesFromEnv() {",
+ },
+ "release_demo_fixtures_dev.go": {
+ "//go:build !release",
+ "return false",
+ },
+ "release_demo_fixtures_release.go": {
+ "//go:build release",
+ "return true",
+ },
+ }
+
+ for file, snippets := range requiredSnippets {
+ data, err := os.ReadFile(file)
+ if err != nil {
+ t.Fatalf("failed to read %s: %v", file, err)
+ }
+ source := string(data)
+ for _, snippet := range snippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("%s must contain %q", file, snippet)
+ }
+ }
+ }
+}
+
func TestContract_SelfHostedPurchaseHandoffJSONSnapshot(t *testing.T) {
handler := createTestHandler(t)
handler.SetConfig(&config.Config{PublicURL: "https://pulse.example.com"})
diff --git a/internal/api/hosted_agent_install_command_test.go b/internal/api/hosted_agent_install_command_test.go
index 8b1b51dbb6..d266a53024 100644
--- a/internal/api/hosted_agent_install_command_test.go
+++ b/internal/api/hosted_agent_install_command_test.go
@@ -9,15 +9,12 @@ import (
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
- "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/stretchr/testify/require"
)
func TestHostedTenantAgentInstallCommand_GeneratesOrgBoundTokenAndCommand(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
- mock.SetEnabled(true)
- t.Cleanup(func() { mock.SetEnabled(false) })
+ setMockModeForTest(t, true)
dataDir := t.TempDir()
cfg := &config.Config{
diff --git a/internal/api/license_handlers_demo_fixtures_dev_test.go b/internal/api/license_handlers_demo_fixtures_dev_test.go
new file mode 100644
index 0000000000..fcd766fda3
--- /dev/null
+++ b/internal/api/license_handlers_demo_fixtures_dev_test.go
@@ -0,0 +1,52 @@
+//go:build !release
+
+package api
+
+import (
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
+ pkglicensing "github.com/rcourtman/pulse-go-rewrite/pkg/licensing"
+)
+
+type devDemoFixturesEntitlementSource struct {
+ capabilities []string
+ subscriptionState pkglicensing.SubscriptionState
+}
+
+func (s devDemoFixturesEntitlementSource) Capabilities() []string {
+ return append([]string(nil), s.capabilities...)
+}
+
+func (s devDemoFixturesEntitlementSource) Limits() map[string]int64 { return nil }
+func (s devDemoFixturesEntitlementSource) MetersEnabled() []string { return nil }
+func (s devDemoFixturesEntitlementSource) PlanVersion() string { return "" }
+
+func (s devDemoFixturesEntitlementSource) SubscriptionState() pkglicensing.SubscriptionState {
+ if s.subscriptionState == "" {
+ return pkglicensing.SubStateActive
+ }
+ return s.subscriptionState
+}
+
+func (s devDemoFixturesEntitlementSource) TrialStartedAt() *int64 { return nil }
+func (s devDemoFixturesEntitlementSource) TrialEndsAt() *int64 { return nil }
+func (s devDemoFixturesEntitlementSource) OverflowGrantedAt() *int64 { return nil }
+
+func TestSyncReleaseDemoFixtureRuntime_DoesNotPoliceMockFixturesInDevBuilds(t *testing.T) {
+ setMockModeForTest(t, true)
+
+ handler := NewLicenseHandlers(nil, false, &config.Config{DemoMode: false})
+ service := newLicenseService()
+ service.SetEvaluator(pkglicensing.NewEvaluator(devDemoFixturesEntitlementSource{
+ capabilities: []string{featureAIAutoFixValue},
+ subscriptionState: pkglicensing.SubStateActive,
+ }))
+
+ handler.syncReleaseDemoFixtureRuntime("default", service)
+
+ if !mock.IsMockEnabled() {
+ t.Fatal("expected dev build demo-fixture sync to leave explicit mock mode enabled")
+ }
+}
diff --git a/internal/api/licensing_handlers.go b/internal/api/licensing_handlers.go
index 6a82b8d25d..b48f1f1f8f 100644
--- a/internal/api/licensing_handlers.go
+++ b/internal/api/licensing_handlers.go
@@ -625,6 +625,10 @@ func (h *LicenseHandlers) demoFixturesAuthorized(service *licenseService) bool {
}
func (h *LicenseHandlers) syncReleaseDemoFixtureRuntime(orgID string, service *licenseService) {
+ if !shouldEnforceReleaseDemoFixtureRuntime() {
+ return
+ }
+
if strings.TrimSpace(orgID) == "" {
orgID = "default"
}
diff --git a/internal/api/mockmode_external_test.go b/internal/api/mockmode_external_test.go
new file mode 100644
index 0000000000..dfbacfe883
--- /dev/null
+++ b/internal/api/mockmode_external_test.go
@@ -0,0 +1,12 @@
+package api_test
+
+import (
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/testutil"
+)
+
+func setMockModeForTest(t *testing.T, enabled bool) {
+ t.Helper()
+ testutil.SetMockMode(t, enabled)
+}
diff --git a/internal/api/mockmode_internal_test.go b/internal/api/mockmode_internal_test.go
new file mode 100644
index 0000000000..8c9d5fb9a7
--- /dev/null
+++ b/internal/api/mockmode_internal_test.go
@@ -0,0 +1,12 @@
+package api
+
+import (
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/testutil"
+)
+
+func setMockModeForTest(t *testing.T, enabled bool) {
+ t.Helper()
+ testutil.SetMockMode(t, enabled)
+}
diff --git a/internal/api/release_demo_fixtures_dev.go b/internal/api/release_demo_fixtures_dev.go
new file mode 100644
index 0000000000..7b062787ea
--- /dev/null
+++ b/internal/api/release_demo_fixtures_dev.go
@@ -0,0 +1,7 @@
+//go:build !release
+
+package api
+
+func shouldEnforceReleaseDemoFixtureRuntime() bool {
+ return false
+}
diff --git a/internal/api/release_demo_fixtures_release.go b/internal/api/release_demo_fixtures_release.go
new file mode 100644
index 0000000000..4a822cadd4
--- /dev/null
+++ b/internal/api/release_demo_fixtures_release.go
@@ -0,0 +1,7 @@
+//go:build release
+
+package api
+
+func shouldEnforceReleaseDemoFixtureRuntime() bool {
+ return true
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 87a461d40f..c4b2c8db12 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -5907,6 +5907,14 @@ var infrastructureSummaryMetricOrder = []string{
"netout",
}
+var workloadSummaryMetricOrder = []string{
+ "cpu",
+ "memory",
+ "disk",
+ "netin",
+ "netout",
+}
+
func parseInfrastructureSummaryRequestedMetrics(
query url.Values,
) ([]string, map[string]bool, error) {
@@ -6305,24 +6313,6 @@ func (r *Router) handleWorkloadCharts(w http.ResponseWriter, req *http.Request)
vmResponseKeys = append(vmResponseKeys, responseKey)
vmRequests = append(vmRequests, request)
}
- vmBatchMetrics := monitor.GetGuestMetricsForChartBatch("vm", vmRequests, duration, infrastructureSummaryMetricOrder...)
- 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["disk"] = []MetricPoint{{Timestamp: currentTime, Value: vm.DiskPercent()}}
- series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: vm.NetIn()}}
- series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: vm.NetOut()}}
- }
- updateOldestTimestampFromSeries(series, &oldestTimestamp)
- chartData[responseKey] = series
- }
-
containerList := make([]*unifiedresources.ContainerView, 0)
containerResponseKeys := make([]string, 0)
containerRequests := make([]monitoring.GuestChartRequest, 0)
@@ -6343,24 +6333,6 @@ func (r *Router) handleWorkloadCharts(w http.ResponseWriter, req *http.Request)
containerResponseKeys = append(containerResponseKeys, responseKey)
containerRequests = append(containerRequests, request)
}
- containerBatchMetrics := monitor.GetGuestMetricsForChartBatch("container", containerRequests, duration, infrastructureSummaryMetricOrder...)
- 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["disk"] = []MetricPoint{{Timestamp: currentTime, Value: ct.DiskPercent()}}
- series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: ct.NetIn()}}
- series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: ct.NetOut()}}
- }
- updateOldestTimestampFromSeries(series, &oldestTimestamp)
- chartData[responseKey] = series
- }
-
podList := make([]*unifiedresources.PodView, 0)
podRequests := make([]monitoring.GuestChartRequest, 0)
for _, pod := range readState.Pods() {
@@ -6379,23 +6351,6 @@ func (r *Router) handleWorkloadCharts(w http.ResponseWriter, req *http.Request)
podList = append(podList, pod)
podRequests = append(podRequests, monitoring.GuestChartRequest{InMemoryKey: metricKey, SQLResourceID: metricKey})
}
- podBatchMetrics := monitor.GetGuestMetricsForChartBatch("k8s", podRequests, duration, infrastructureSummaryMetricOrder...)
- for _, pod := range podList {
- metricKey := kubernetesPodMetricIDFromView(pod)
- series := convertMetricsForChart(podBatchMetrics[metricKey], &oldestTimestamp, maxPoints)
- guestTypes[metricKey] = "k8s"
-
- if len(series["cpu"]) == 0 {
- series["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: pod.CPUPercent()}}
- series["memory"] = []MetricPoint{{Timestamp: currentTime, Value: pod.MemoryPercent()}}
- series["disk"] = []MetricPoint{{Timestamp: currentTime, Value: pod.DiskPercent()}}
- series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: pod.NetInRate()}}
- series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: pod.NetOutRate()}}
- }
- updateOldestTimestampFromSeries(series, &oldestTimestamp)
- chartData[metricKey] = series
- }
-
dockerHostsByID := make(map[string]*unifiedresources.DockerHostView, len(readState.DockerHosts()))
for _, host := range readState.DockerHosts() {
if host == nil {
@@ -6440,13 +6395,85 @@ func (r *Router) handleWorkloadCharts(w http.ResponseWriter, req *http.Request)
dockerContainerList = append(dockerContainerList, container)
dockerContainerKeys = append(dockerContainerKeys, responseKey)
dockerContainerRequests = append(dockerContainerRequests, request)
- guestTypes[responseKey] = "app-container"
}
- dockerContainerBatchMetrics := monitor.GetGuestMetricsForChartBatch("dockerContainer", dockerContainerRequests, duration, infrastructureSummaryMetricOrder...)
+ var (
+ vmBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ containerBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ podBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ dockerContainerBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ )
+ var workloadChartsBatchWG sync.WaitGroup
+ workloadChartsBatchWG.Add(4)
+ go func() {
+ defer workloadChartsBatchWG.Done()
+ vmBatchMetrics = monitor.GetGuestMetricsForChartBatch("vm", vmRequests, duration, infrastructureSummaryMetricOrder...)
+ }()
+ go func() {
+ defer workloadChartsBatchWG.Done()
+ containerBatchMetrics = monitor.GetGuestMetricsForChartBatch("container", containerRequests, duration, infrastructureSummaryMetricOrder...)
+ }()
+ go func() {
+ defer workloadChartsBatchWG.Done()
+ podBatchMetrics = monitor.GetGuestMetricsForChartBatch("k8s", podRequests, duration, workloadSummaryMetricOrder...)
+ }()
+ go func() {
+ defer workloadChartsBatchWG.Done()
+ dockerContainerBatchMetrics = monitor.GetGuestMetricsForChartBatch("dockerContainer", dockerContainerRequests, duration, infrastructureSummaryMetricOrder...)
+ }()
+ workloadChartsBatchWG.Wait()
+
+ 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["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
+ }
+
+ 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["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
+ }
+
+ for _, pod := range podList {
+ metricKey := kubernetesPodMetricIDFromView(pod)
+ series := convertMetricsForChart(podBatchMetrics[metricKey], &oldestTimestamp, maxPoints)
+ guestTypes[metricKey] = "k8s"
+
+ if len(series["cpu"]) == 0 {
+ series["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: pod.CPUPercent()}}
+ series["memory"] = []MetricPoint{{Timestamp: currentTime, Value: pod.MemoryPercent()}}
+ series["disk"] = []MetricPoint{{Timestamp: currentTime, Value: pod.DiskPercent()}}
+ series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: pod.NetInRate()}}
+ series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: pod.NetOutRate()}}
+ }
+ chartData[metricKey] = series
+ }
+
for idx, container := range dockerContainerList {
responseKey := dockerContainerKeys[idx]
metricID := dockerContainerRequests[idx].SQLResourceID
series := convertMetricsForChart(dockerContainerBatchMetrics[metricID], &oldestTimestamp, maxPoints)
+ guestTypes[responseKey] = "app-container"
if len(series["cpu"]) == 0 {
series["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: container.CPUPercent()}}
@@ -6455,7 +6482,6 @@ func (r *Router) handleWorkloadCharts(w http.ResponseWriter, req *http.Request)
series["netin"] = []MetricPoint{{Timestamp: currentTime, Value: container.NetInRate()}}
series["netout"] = []MetricPoint{{Timestamp: currentTime, Value: container.NetOutRate()}}
}
- updateOldestTimestampFromSeries(series, &oldestTimestamp)
dockerData[responseKey] = series
}
@@ -7372,7 +7398,97 @@ func (r *Router) handleWorkloadsSummaryCharts(w http.ResponseWriter, req *http.R
vmResponseKeys = append(vmResponseKeys, responseKey)
vmRequests = append(vmRequests, request)
}
- vmBatchMetrics := monitor.GetGuestMetricsForChartBatch("vm", vmRequests, duration, infrastructureSummaryMetricOrder...)
+ containerList := make([]*unifiedresources.ContainerView, 0)
+ containerResponseKeys := make([]string, 0)
+ containerRequests := make([]monitoring.GuestChartRequest, 0)
+ for _, ct := range readState.Containers() {
+ if ct == nil {
+ continue
+ }
+ if !matchesSelectedNode(ct.Instance(), ct.Node()) {
+ continue
+ }
+ responseKey, request, ok := systemContainerChartRequest(ct)
+ if !ok {
+ continue
+ }
+ containerList = append(containerList, ct)
+ containerResponseKeys = append(containerResponseKeys, responseKey)
+ containerRequests = append(containerRequests, request)
+ }
+ podList := make([]*unifiedresources.PodView, 0)
+ podRequests := make([]monitoring.GuestChartRequest, 0)
+ for _, pod := range readState.Pods() {
+ if pod == nil {
+ continue
+ }
+ if !matchesSelectedKubernetesPodView(pod) {
+ continue
+ }
+
+ metricKey := kubernetesPodMetricIDFromView(pod)
+ if metricKey == "" {
+ continue
+ }
+ podList = append(podList, pod)
+ podRequests = append(podRequests, monitoring.GuestChartRequest{InMemoryKey: metricKey, SQLResourceID: metricKey})
+ }
+ dockerHostsByID := make(map[string]*unifiedresources.DockerHostView, len(readState.DockerHosts()))
+ for _, host := range readState.DockerHosts() {
+ if host == nil {
+ continue
+ }
+ dockerHostsByID[host.ID()] = host
+ }
+
+ dockerContainerList := make([]*unifiedresources.DockerContainerView, 0)
+ dockerContainerRequests := make([]monitoring.GuestChartRequest, 0)
+ for _, container := range readState.DockerContainers() {
+ if container == nil {
+ continue
+ }
+ if selectedNodeID != "" && selectedNode != nil {
+ host := dockerHostsByID[container.ParentID()]
+ if host == nil || !matchesSelectedDockerHostView(host) {
+ continue
+ }
+ }
+ containerID := strings.TrimSpace(container.ContainerID())
+ if containerID == "" {
+ continue
+ }
+ dockerContainerList = append(dockerContainerList, container)
+ dockerContainerRequests = append(dockerContainerRequests, monitoring.GuestChartRequest{
+ InMemoryKey: fmt.Sprintf("docker:%s", containerID),
+ SQLResourceID: containerID,
+ })
+ }
+ var (
+ vmBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ containerBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ podBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ dockerContainerBatchMetrics map[string]map[string][]monitoring.MetricPoint
+ )
+ var workloadsSummaryBatchWG sync.WaitGroup
+ workloadsSummaryBatchWG.Add(4)
+ go func() {
+ defer workloadsSummaryBatchWG.Done()
+ vmBatchMetrics = monitor.GetGuestMetricsForChartBatch("vm", vmRequests, duration, workloadSummaryMetricOrder...)
+ }()
+ go func() {
+ defer workloadsSummaryBatchWG.Done()
+ containerBatchMetrics = monitor.GetGuestMetricsForChartBatch("container", containerRequests, duration, workloadSummaryMetricOrder...)
+ }()
+ go func() {
+ defer workloadsSummaryBatchWG.Done()
+ podBatchMetrics = monitor.GetGuestMetricsForChartBatch("k8s", podRequests, duration, workloadSummaryMetricOrder...)
+ }()
+ go func() {
+ defer workloadsSummaryBatchWG.Done()
+ dockerContainerBatchMetrics = monitor.GetGuestMetricsForChartBatch("dockerContainer", dockerContainerRequests, duration, workloadSummaryMetricOrder...)
+ }()
+ workloadsSummaryBatchWG.Wait()
+
for idx, vm := range vmList {
responseKey := vmResponseKeys[idx]
metricID := vmRequests[idx].SQLResourceID
@@ -7429,25 +7545,6 @@ func (r *Router) handleWorkloadsSummaryCharts(w http.ResponseWriter, req *http.R
snapshots = append(snapshots, snapshot)
}
- containerList := make([]*unifiedresources.ContainerView, 0)
- containerResponseKeys := make([]string, 0)
- containerRequests := make([]monitoring.GuestChartRequest, 0)
- for _, ct := range readState.Containers() {
- if ct == nil {
- continue
- }
- if !matchesSelectedNode(ct.Instance(), ct.Node()) {
- continue
- }
- responseKey, request, ok := systemContainerChartRequest(ct)
- if !ok {
- continue
- }
- containerList = append(containerList, ct)
- containerResponseKeys = append(containerResponseKeys, responseKey)
- containerRequests = append(containerRequests, request)
- }
- containerBatchMetrics := monitor.GetGuestMetricsForChartBatch("container", containerRequests, duration, infrastructureSummaryMetricOrder...)
for idx, ct := range containerList {
responseKey := containerResponseKeys[idx]
metricID := containerRequests[idx].SQLResourceID
@@ -7504,24 +7601,6 @@ func (r *Router) handleWorkloadsSummaryCharts(w http.ResponseWriter, req *http.R
snapshots = append(snapshots, snapshot)
}
- podList := make([]*unifiedresources.PodView, 0)
- podRequests := make([]monitoring.GuestChartRequest, 0)
- for _, pod := range readState.Pods() {
- if pod == nil {
- continue
- }
- if !matchesSelectedKubernetesPodView(pod) {
- continue
- }
-
- metricKey := kubernetesPodMetricIDFromView(pod)
- if metricKey == "" {
- continue
- }
- podList = append(podList, pod)
- podRequests = append(podRequests, monitoring.GuestChartRequest{InMemoryKey: metricKey, SQLResourceID: metricKey})
- }
- podBatchMetrics := monitor.GetGuestMetricsForChartBatch("k8s", podRequests, duration, infrastructureSummaryMetricOrder...)
for _, pod := range podList {
metricKey := kubernetesPodMetricIDFromView(pod)
@@ -7605,37 +7684,6 @@ func (r *Router) handleWorkloadsSummaryCharts(w http.ResponseWriter, req *http.R
snapshots = append(snapshots, snapshot)
}
- dockerHostsByID := make(map[string]*unifiedresources.DockerHostView, len(readState.DockerHosts()))
- for _, host := range readState.DockerHosts() {
- if host == nil {
- continue
- }
- dockerHostsByID[host.ID()] = host
- }
-
- dockerContainerList := make([]*unifiedresources.DockerContainerView, 0)
- dockerContainerRequests := make([]monitoring.GuestChartRequest, 0)
- for _, container := range readState.DockerContainers() {
- if container == nil {
- continue
- }
- if selectedNodeID != "" && selectedNode != nil {
- host := dockerHostsByID[container.ParentID()]
- if host == nil || !matchesSelectedDockerHostView(host) {
- continue
- }
- }
- containerID := strings.TrimSpace(container.ContainerID())
- if containerID == "" {
- continue
- }
- dockerContainerList = append(dockerContainerList, container)
- dockerContainerRequests = append(dockerContainerRequests, monitoring.GuestChartRequest{
- InMemoryKey: fmt.Sprintf("docker:%s", containerID),
- SQLResourceID: containerID,
- })
- }
- dockerContainerBatchMetrics := monitor.GetGuestMetricsForChartBatch("dockerContainer", dockerContainerRequests, duration, infrastructureSummaryMetricOrder...)
for _, container := range dockerContainerList {
containerID := strings.TrimSpace(container.ContainerID())
guestCounts.Total++
diff --git a/internal/api/router_helpers_more_test.go b/internal/api/router_helpers_more_test.go
index 0943b569c9..bdeeb347df 100644
--- a/internal/api/router_helpers_more_test.go
+++ b/internal/api/router_helpers_more_test.go
@@ -350,7 +350,7 @@ func TestRouterStopPatrol_ClearsAllLifecycleMarkers(t *testing.T) {
}
func TestStartPatrolForContext_DoesNotOverwriteOtherTenantPatrolComponents(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
tempDir := t.TempDir()
mtp := config.NewMultiTenantPersistence(tempDir)
@@ -415,7 +415,7 @@ func TestStartPatrolForContext_DoesNotOverwriteOtherTenantPatrolComponents(t *te
}
func TestStartPatrolForContext_RejectsMismatchedAIServiceOrg(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
mtp := config.NewMultiTenantPersistence(t.TempDir())
diff --git a/internal/api/router_integration_test.go b/internal/api/router_integration_test.go
index 62eb43b53d..ba70710e13 100644
--- a/internal/api/router_integration_test.go
+++ b/internal/api/router_integration_test.go
@@ -79,13 +79,7 @@ func newIntegrationServerWithRuntimeMode(
) *integrationServer {
t.Helper()
- if mockMode {
- t.Setenv("PULSE_MOCK_MODE", "true")
- mock.SetEnabled(true)
- } else {
- t.Setenv("PULSE_MOCK_MODE", "false")
- mock.SetEnabled(false)
- }
+ setMockModeForTest(t, mockMode)
if customize != nil {
customize(cfg)
@@ -132,7 +126,6 @@ func newIntegrationServerWithRuntimeMode(
if hub != nil {
hub.Stop()
}
- mock.SetEnabled(false)
})
return &integrationServer{
diff --git a/internal/api/router_state_test.go b/internal/api/router_state_test.go
index 6e981b8887..82f94080c5 100644
--- a/internal/api/router_state_test.go
+++ b/internal/api/router_state_test.go
@@ -7,7 +7,6 @@ import (
"testing"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
- "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/monitoring"
"github.com/rcourtman/pulse-go-rewrite/pkg/auth"
@@ -16,9 +15,7 @@ import (
func TestRouter_HandleState_MockIsolation(t *testing.T) {
// Enable mock mode to control GetState output
- t.Setenv("PULSE_MOCK_MODE", "true")
- mock.SetEnabled(true)
- defer mock.SetEnabled(false)
+ setMockModeForTest(t, true)
dataPath := t.TempDir()
hp, _ := auth.HashPassword("password")
diff --git a/internal/api/updates_test.go b/internal/api/updates_test.go
index 581c8b1084..f8f27903ad 100644
--- a/internal/api/updates_test.go
+++ b/internal/api/updates_test.go
@@ -542,7 +542,7 @@ func (m *mockUpdater) PrepareUpdate(ctx context.Context, req updates.UpdateReque
func TestHandleGetUpdatePlan(t *testing.T) {
// Set mock mode so GetCurrentVersion returns "mock"
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
mu := &mockUpdater{
prepareFunc: func(ctx context.Context, req updates.UpdateRequest) (*updates.UpdatePlan, error) {
@@ -583,7 +583,7 @@ func TestHandleGetUpdatePlan(t *testing.T) {
}
func TestHandleGetUpdatePlan_InvalidChannel(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
h := NewUpdateHandlers(nil, nil)
h.registry.Register("mock", &mockUpdater{
@@ -603,7 +603,7 @@ func TestHandleGetUpdatePlan_InvalidChannel(t *testing.T) {
}
func TestHandleGetUpdatePlan_PrepareError(t *testing.T) {
- t.Setenv("PULSE_MOCK_MODE", "true")
+ setMockModeForTest(t, true)
h := NewUpdateHandlers(nil, nil)
h.registry.Register("mock", &mockUpdater{
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index d86e35632b..c6b3fc61ea 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -666,8 +666,10 @@ func TestUnifiedAppContainerMetricsUseCanonicalGuestHistoryPath(t *testing.T) {
"m.syncUnifiedAppContainerMetrics(store)",
`if target == nil || target.ResourceType != "app-container" || strings.TrimSpace(target.ResourceID) == "" {`,
`metricKey := fmt.Sprintf("docker:%s", targetID)`,
- `m.metricsStore.Write("dockerContainer", targetID, "cpu", value, now)`,
- `m.metricsStore.Write("dockerContainer", targetID, "diskwrite", metric.Value, now)`,
+ `storeWrites := make([]metrics.WriteMetric, 0)`,
+ `appendStoreWrite("dockerContainer", targetID, "cpu", value)`,
+ `appendStoreWrite("dockerContainer", targetID, "diskwrite", metric.Value)`,
+ `m.metricsStore.WriteBatchSync(storeWrites)`,
}
for _, snippet := range requiredSnippets {
if !strings.Contains(source, snippet) {
@@ -703,8 +705,10 @@ func TestUnifiedAgentMetricsUseCanonicalHostHistoryPath(t *testing.T) {
"m.syncUnifiedAgentMetrics(store)",
`if target == nil || target.ResourceType != "agent" || strings.TrimSpace(target.ResourceID) == "" {`,
`metricKey := fmt.Sprintf("agent:%s", targetID)`,
- `m.metricsStore.Write("agent", targetID, "cpu", value, now)`,
- `m.metricsStore.Write("agent", targetID, "diskwrite", metric.Value, now)`,
+ `storeWrites := make([]metrics.WriteMetric, 0)`,
+ `appendStoreWrite("agent", targetID, "cpu", value)`,
+ `appendStoreWrite("agent", targetID, "diskwrite", metric.Value)`,
+ `m.metricsStore.WriteBatchSync(storeWrites)`,
}
for _, snippet := range requiredSnippets {
if !strings.Contains(source, snippet) {
@@ -723,8 +727,10 @@ func TestUnifiedVMMetricsUseCanonicalVMHistoryPath(t *testing.T) {
"m.syncUnifiedVMMetrics(store)",
`if target == nil || target.ResourceType != "vm" || strings.TrimSpace(target.ResourceID) == "" {`,
`if source == unifiedresources.SourceProxmox {`,
- `m.metricsStore.Write("vm", targetID, "cpu", value, now)`,
- `m.metricsStore.Write("vm", targetID, "diskwrite", metric.Value, now)`,
+ `storeWrites := make([]metrics.WriteMetric, 0)`,
+ `appendStoreWrite("vm", targetID, "cpu", value)`,
+ `appendStoreWrite("vm", targetID, "diskwrite", metric.Value)`,
+ `m.metricsStore.WriteBatchSync(storeWrites)`,
}
for _, snippet := range requiredSnippets {
if !strings.Contains(source, snippet) {
diff --git a/internal/monitoring/guest_config_conversion_coverage_test.go b/internal/monitoring/guest_config_conversion_coverage_test.go
index 72f3d205c0..da336adfa3 100644
--- a/internal/monitoring/guest_config_conversion_coverage_test.go
+++ b/internal/monitoring/guest_config_conversion_coverage_test.go
@@ -199,8 +199,8 @@ func TestMonitorFrontendAndMetricHelpers(t *testing.T) {
{name: "pbs", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypePBS}, want: "pbs"},
{name: "pmg", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypePMG}, want: "pmg"},
{name: "storage", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeStorage}, want: "storage"},
- {name: "ceph", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeCeph}, want: "pool"},
- {name: "host proxmox", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{}}, want: "node"},
+ {name: "ceph", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeCeph}, want: "ceph"},
+ {name: "host proxmox", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Proxmox: &unifiedresources.ProxmoxData{}}, want: "agent"},
{name: "host docker", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent, Docker: &unifiedresources.DockerData{}}, want: "docker-host"},
{name: "host agent", resource: unifiedresources.Resource{Type: unifiedresources.ResourceTypeAgent}, want: "agent"},
{name: "unknown passthrough", resource: unifiedresources.Resource{Type: unifiedresources.ResourceType("custom")}, want: "custom"},
@@ -222,7 +222,7 @@ func TestMonitorFrontendAndMetricHelpers(t *testing.T) {
resource unifiedresources.Resource
want string
}{
- {name: "node explicit", resourceType: "node", want: "proxmox-pve"},
+ {name: "node explicit", resourceType: "node", want: "unknown"},
{name: "docker explicit", resourceType: "app-container", want: "docker"},
{name: "k8s explicit", resourceType: "k8s-node", want: "kubernetes"},
{name: "pbs explicit", resourceType: "pbs", want: "proxmox-pbs"},
diff --git a/internal/monitoring/metrics_history.go b/internal/monitoring/metrics_history.go
index 68d7650f68..dbd3512eda 100644
--- a/internal/monitoring/metrics_history.go
+++ b/internal/monitoring/metrics_history.go
@@ -1,6 +1,7 @@
package monitoring
import (
+ "sort"
"sync"
"time"
@@ -258,6 +259,105 @@ func filterMetricsByTime(data []MetricPoint, cutoffTime time.Time) []MetricPoint
return filtered
}
+func metricsSeriesCoverageSpanAfter(data []MetricPoint, cutoffTime time.Time) time.Duration {
+ if len(data) < 2 {
+ return 0
+ }
+
+ first := sort.Search(len(data), func(i int) bool {
+ return data[i].Timestamp.After(cutoffTime)
+ })
+ if first >= len(data)-1 {
+ return 0
+ }
+
+ oldest := data[first].Timestamp
+ newest := data[len(data)-1].Timestamp
+ if !newest.After(oldest) {
+ return 0
+ }
+ return newest.Sub(oldest)
+}
+
+func guestMetricSeries(metrics *GuestMetrics, metricType string) []MetricPoint {
+ if metrics == nil {
+ return nil
+ }
+
+ switch metricType {
+ case "cpu":
+ return metrics.CPU
+ case "memory":
+ return metrics.Memory
+ case "disk":
+ return metrics.Disk
+ case "diskread":
+ return metrics.DiskRead
+ case "diskwrite":
+ return metrics.DiskWrite
+ case "netin":
+ return metrics.NetworkIn
+ case "netout":
+ return metrics.NetworkOut
+ default:
+ return nil
+ }
+}
+
+func guestMetricsCoverageSpan(metrics *GuestMetrics, metricTypes []string, cutoffTime time.Time) time.Duration {
+ if metrics == nil {
+ return 0
+ }
+
+ if len(metricTypes) == 0 {
+ metricTypes = []string{"cpu", "memory", "disk", "diskread", "diskwrite", "netin", "netout"}
+ }
+
+ var best time.Duration
+ for _, metricType := range metricTypes {
+ if span := metricsSeriesCoverageSpanAfter(guestMetricSeries(metrics, metricType), cutoffTime); span > best {
+ best = span
+ }
+ }
+ return best
+}
+
+// GuestMetricCoverageSpan returns the best in-memory coverage span across the
+// requested guest metric types after applying the requested duration window.
+func (mh *MetricsHistory) GuestMetricCoverageSpan(guestID string, metricTypes []string, duration time.Duration) time.Duration {
+ if mh == nil {
+ return 0
+ }
+
+ mh.mu.RLock()
+ defer mh.mu.RUnlock()
+
+ metrics, exists := mh.guestMetrics[guestID]
+ if !exists {
+ return 0
+ }
+
+ return guestMetricsCoverageSpan(metrics, metricTypes, time.Now().Add(-duration))
+}
+
+// NodeMetricCoverageSpan returns the best in-memory coverage span across the
+// requested node metric types after applying the requested duration window.
+func (mh *MetricsHistory) NodeMetricCoverageSpan(nodeID string, metricTypes []string, duration time.Duration) time.Duration {
+ if mh == nil {
+ return 0
+ }
+
+ mh.mu.RLock()
+ defer mh.mu.RUnlock()
+
+ metrics, exists := mh.nodeMetrics[nodeID]
+ if !exists {
+ return 0
+ }
+
+ return guestMetricsCoverageSpan(metrics, metricTypes, time.Now().Add(-duration))
+}
+
// GetAllGuestMetrics returns all metrics for a guest within a duration
func (mh *MetricsHistory) GetAllGuestMetrics(guestID string, duration time.Duration) map[string][]MetricPoint {
mh.mu.RLock()
diff --git a/internal/monitoring/metrics_history_test.go b/internal/monitoring/metrics_history_test.go
index 83191d7027..d591cdc202 100644
--- a/internal/monitoring/metrics_history_test.go
+++ b/internal/monitoring/metrics_history_test.go
@@ -980,6 +980,48 @@ func TestGetAllGuestMetrics(t *testing.T) {
}
}
+func TestGuestMetricCoverageSpan(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ mh := NewMetricsHistory(100, 24*time.Hour)
+
+ mh.AddGuestMetric("vm-coverage", "cpu", 10, now.Add(-5*time.Hour))
+ mh.AddGuestMetric("vm-coverage", "cpu", 20, now.Add(-2*time.Hour))
+ mh.AddGuestMetric("vm-coverage", "cpu", 30, now.Add(-5*time.Minute))
+ mh.AddGuestMetric("vm-coverage", "memory", 40, now.Add(-25*time.Minute))
+ mh.AddGuestMetric("vm-coverage", "memory", 50, now.Add(-10*time.Minute))
+
+ if span := mh.GuestMetricCoverageSpan("vm-coverage", []string{"cpu", "memory"}, 6*time.Hour); span < 4*time.Hour {
+ t.Fatalf("expected guest coverage span >= 4h, got %s", span)
+ }
+ if span := mh.GuestMetricCoverageSpan("vm-coverage", []string{"memory"}, time.Hour); span < 10*time.Minute {
+ t.Fatalf("expected memory coverage span >= 10m, got %s", span)
+ }
+ if span := mh.GuestMetricCoverageSpan("missing-guest", []string{"cpu"}, 6*time.Hour); span != 0 {
+ t.Fatalf("expected missing guest coverage span 0, got %s", span)
+ }
+}
+
+func TestNodeMetricCoverageSpan(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ mh := NewMetricsHistory(100, 24*time.Hour)
+
+ mh.AddNodeMetric("node-coverage", "cpu", 10, now.Add(-4*time.Hour))
+ mh.AddNodeMetric("node-coverage", "cpu", 20, now.Add(-90*time.Minute))
+ mh.AddNodeMetric("node-coverage", "cpu", 30, now.Add(-5*time.Minute))
+ mh.AddNodeMetric("node-coverage", "memory", 40, now.Add(-20*time.Minute))
+ mh.AddNodeMetric("node-coverage", "memory", 50, now.Add(-5*time.Minute))
+
+ if span := mh.NodeMetricCoverageSpan("node-coverage", []string{"cpu", "memory"}, 5*time.Hour); span < 3*time.Hour {
+ t.Fatalf("expected node coverage span >= 3h, got %s", span)
+ }
+ if span := mh.NodeMetricCoverageSpan("node-coverage", []string{"memory"}, time.Hour); span < 10*time.Minute {
+ t.Fatalf("expected memory node coverage span >= 10m, got %s", span)
+ }
+ if span := mh.NodeMetricCoverageSpan("missing-node", []string{"cpu"}, 5*time.Hour); span != 0 {
+ t.Fatalf("expected missing node coverage span 0, got %s", span)
+ }
+}
+
func TestGetAllStorageMetrics(t *testing.T) {
now := time.Now()
mh := NewMetricsHistory(100, time.Hour)
diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.go
index 649352a059..2bef80947c 100644
--- a/internal/monitoring/mock_metrics_history_test.go
+++ b/internal/monitoring/mock_metrics_history_test.go
@@ -905,8 +905,8 @@ func TestStartMockMetricsSampler_SeedsCanonicalMockResourceHistory(t *testing.T)
if !ok {
t.Fatalf("expected disk chart for %q, got keys=%v", proxmoxDiskID, keysDiskCharts(diskCharts))
}
- if got := len(diskChart.Temperature); got < 300 {
- t.Fatalf("expected seeded proxmox disk chart history, got %d points for %q", got, proxmoxDiskID)
+ if got, want := len(diskChart.Temperature), mockChartPointTarget(7*24*time.Hour); got != want {
+ t.Fatalf("expected downsampled proxmox disk chart history to match target %d, got %d points for %q", want, got, proxmoxDiskID)
}
dockerMetricID := strings.TrimSpace(graph.State.DockerHosts[0].Containers[0].ID)
@@ -924,11 +924,11 @@ func TestStartMockMetricsSampler_SeedsCanonicalMockResourceHistory(t *testing.T)
)
cpuPoints := workloadMetrics[dockerMetricID]["cpu"]
memoryPoints := workloadMetrics[dockerMetricID]["memory"]
- if got := len(cpuPoints); got < 300 {
- t.Fatalf("expected seeded docker app cpu history, got %d points for %q", got, dockerMetricID)
+ if got, want := len(cpuPoints), mockChartPointTarget(7*24*time.Hour); got != want {
+ t.Fatalf("expected downsampled docker app cpu history to match target %d, got %d points for %q", want, got, dockerMetricID)
}
- if got := len(memoryPoints); got < 300 {
- t.Fatalf("expected seeded docker app memory history, got %d points for %q", got, dockerMetricID)
+ if got, want := len(memoryPoints), mockChartPointTarget(7*24*time.Hour); got != want {
+ t.Fatalf("expected downsampled docker app memory history to match target %d, got %d points for %q", want, got, dockerMetricID)
}
}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 695e9d3461..2c5e2d2af6 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -4295,6 +4295,20 @@ func (m *Monitor) syncUnifiedAgentMetrics(store ResourceStoreInterface) {
}
now := time.Now()
+ storeWrites := make([]metrics.WriteMetric, 0)
+ appendStoreWrite := func(resourceType, resourceID, metricType string, value float64) {
+ if m.metricsStore == nil {
+ return
+ }
+ storeWrites = append(storeWrites, metrics.WriteMetric{
+ ResourceType: resourceType,
+ ResourceID: resourceID,
+ MetricType: metricType,
+ Value: value,
+ Timestamp: now,
+ Tier: metrics.TierRaw,
+ })
+ }
seenTargets := make(map[string]struct{})
for _, resource := range store.GetAll() {
if resource.Type != unifiedresources.ResourceTypeAgent || resource.Metrics == nil {
@@ -4328,9 +4342,7 @@ func (m *Monitor) syncUnifiedAgentMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "cpu", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "cpu", value, now)
- }
+ appendStoreWrite("agent", targetID, "cpu", value)
}
if metric := resource.Metrics.Memory; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {
@@ -4338,9 +4350,7 @@ func (m *Monitor) syncUnifiedAgentMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "memory", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "memory", value, now)
- }
+ appendStoreWrite("agent", targetID, "memory", value)
}
if metric := resource.Metrics.Disk; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {
@@ -4348,47 +4358,40 @@ func (m *Monitor) syncUnifiedAgentMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "disk", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "disk", value, now)
- }
+ appendStoreWrite("agent", targetID, "disk", value)
}
if metric := resource.Metrics.NetIn; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "netin", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "netin", metric.Value, now)
- }
+ appendStoreWrite("agent", targetID, "netin", metric.Value)
}
if metric := resource.Metrics.NetOut; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "netout", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "netout", metric.Value, now)
- }
+ appendStoreWrite("agent", targetID, "netout", metric.Value)
}
if metric := resource.Metrics.DiskRead; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "diskread", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "diskread", metric.Value, now)
- }
+ appendStoreWrite("agent", targetID, "diskread", metric.Value)
}
if metric := resource.Metrics.DiskWrite; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "diskwrite", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", targetID, "diskwrite", metric.Value, now)
- }
+ appendStoreWrite("agent", targetID, "diskwrite", metric.Value)
}
}
+ if len(storeWrites) > 0 {
+ m.metricsStore.WriteBatchSync(storeWrites)
+ }
}
func (m *Monitor) syncUnifiedVMMetrics(store ResourceStoreInterface) {
@@ -4402,6 +4405,20 @@ func (m *Monitor) syncUnifiedVMMetrics(store ResourceStoreInterface) {
}
now := time.Now()
+ storeWrites := make([]metrics.WriteMetric, 0)
+ appendStoreWrite := func(resourceType, resourceID, metricType string, value float64) {
+ if m.metricsStore == nil {
+ return
+ }
+ storeWrites = append(storeWrites, metrics.WriteMetric{
+ ResourceType: resourceType,
+ ResourceID: resourceID,
+ MetricType: metricType,
+ Value: value,
+ Timestamp: now,
+ Tier: metrics.TierRaw,
+ })
+ }
seenTargets := make(map[string]struct{})
for _, resource := range store.GetAll() {
if resource.Type != unifiedresources.ResourceTypeVM || resource.Metrics == nil {
@@ -4440,9 +4457,7 @@ func (m *Monitor) syncUnifiedVMMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "cpu", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "cpu", value, now)
- }
+ appendStoreWrite("vm", targetID, "cpu", value)
}
if metric := resource.Metrics.Memory; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {
@@ -4450,9 +4465,7 @@ func (m *Monitor) syncUnifiedVMMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "memory", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "memory", value, now)
- }
+ appendStoreWrite("vm", targetID, "memory", value)
}
if metric := resource.Metrics.Disk; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {
@@ -4460,47 +4473,40 @@ func (m *Monitor) syncUnifiedVMMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "disk", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "disk", value, now)
- }
+ appendStoreWrite("vm", targetID, "disk", value)
}
if metric := resource.Metrics.NetIn; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "netin", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "netin", metric.Value, now)
- }
+ appendStoreWrite("vm", targetID, "netin", metric.Value)
}
if metric := resource.Metrics.NetOut; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "netout", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "netout", metric.Value, now)
- }
+ appendStoreWrite("vm", targetID, "netout", metric.Value)
}
if metric := resource.Metrics.DiskRead; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "diskread", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "diskread", metric.Value, now)
- }
+ appendStoreWrite("vm", targetID, "diskread", metric.Value)
}
if metric := resource.Metrics.DiskWrite; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(targetID, "diskwrite", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("vm", targetID, "diskwrite", metric.Value, now)
- }
+ appendStoreWrite("vm", targetID, "diskwrite", metric.Value)
}
}
+ if len(storeWrites) > 0 {
+ m.metricsStore.WriteBatchSync(storeWrites)
+ }
}
func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {
@@ -4514,6 +4520,20 @@ func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {
}
now := time.Now()
+ storeWrites := make([]metrics.WriteMetric, 0)
+ appendStoreWrite := func(resourceType, resourceID, metricType string, value float64) {
+ if m.metricsStore == nil {
+ return
+ }
+ storeWrites = append(storeWrites, metrics.WriteMetric{
+ ResourceType: resourceType,
+ ResourceID: resourceID,
+ MetricType: metricType,
+ Value: value,
+ Timestamp: now,
+ Tier: metrics.TierRaw,
+ })
+ }
seenTargets := make(map[string]struct{})
for _, resource := range store.GetAll() {
if resource.Type != unifiedresources.ResourceTypeStorage || resource.Metrics == nil || resource.Metrics.Disk == nil {
@@ -4573,15 +4593,16 @@ func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {
m.metricsHistory.AddStorageMetric(targetID, "avail", float64(free), now)
}
}
- if m.metricsStore != nil {
- m.metricsStore.Write("storage", targetID, "usage", usage, now)
- if total > 0 {
- m.metricsStore.Write("storage", targetID, "used", float64(used), now)
- m.metricsStore.Write("storage", targetID, "total", float64(total), now)
- m.metricsStore.Write("storage", targetID, "avail", float64(free), now)
- }
+ appendStoreWrite("storage", targetID, "usage", usage)
+ if total > 0 {
+ appendStoreWrite("storage", targetID, "used", float64(used))
+ appendStoreWrite("storage", targetID, "total", float64(total))
+ appendStoreWrite("storage", targetID, "avail", float64(free))
}
}
+ if len(storeWrites) > 0 {
+ m.metricsStore.WriteBatchSync(storeWrites)
+ }
}
func (m *Monitor) syncUnifiedPhysicalDiskMetrics(store ResourceStoreInterface) {
@@ -4671,6 +4692,20 @@ func (m *Monitor) syncUnifiedAppContainerMetrics(store ResourceStoreInterface) {
}
now := time.Now()
+ storeWrites := make([]metrics.WriteMetric, 0)
+ appendStoreWrite := func(resourceType, resourceID, metricType string, value float64) {
+ if m.metricsStore == nil {
+ return
+ }
+ storeWrites = append(storeWrites, metrics.WriteMetric{
+ ResourceType: resourceType,
+ ResourceID: resourceID,
+ MetricType: metricType,
+ Value: value,
+ Timestamp: now,
+ Tier: metrics.TierRaw,
+ })
+ }
seenTargets := make(map[string]struct{})
for _, resource := range store.GetAll() {
if resource.Type != unifiedresources.ResourceTypeAppContainer || resource.Metrics == nil {
@@ -4709,9 +4744,7 @@ func (m *Monitor) syncUnifiedAppContainerMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "cpu", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "cpu", value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "cpu", value)
}
if metric := resource.Metrics.Memory; metric != nil && (metric.Total != nil || metric.Percent > 0) {
@@ -4719,9 +4752,7 @@ func (m *Monitor) syncUnifiedAppContainerMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "memory", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "memory", value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "memory", value)
}
if metric := resource.Metrics.Disk; metric != nil && (metric.Total != nil || metric.Percent > 0) {
@@ -4729,47 +4760,40 @@ func (m *Monitor) syncUnifiedAppContainerMetrics(store ResourceStoreInterface) {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "disk", value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "disk", value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "disk", value)
}
if metric := resource.Metrics.NetIn; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "netin", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "netin", metric.Value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "netin", metric.Value)
}
if metric := resource.Metrics.NetOut; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "netout", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "netout", metric.Value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "netout", metric.Value)
}
if metric := resource.Metrics.DiskRead; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "diskread", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "diskread", metric.Value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "diskread", metric.Value)
}
if metric := resource.Metrics.DiskWrite; metric != nil {
if m.metricsHistory != nil {
m.metricsHistory.AddGuestMetric(metricKey, "diskwrite", metric.Value, now)
}
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", targetID, "diskwrite", metric.Value, now)
- }
+ appendStoreWrite("dockerContainer", targetID, "diskwrite", metric.Value)
}
}
+ if len(storeWrites) > 0 {
+ m.metricsStore.WriteBatchSync(storeWrites)
+ }
}
func shouldSkipMockOwnedUnifiedMetricSync(resource unifiedresources.Resource) bool {
diff --git a/internal/monitoring/monitor_conversion_helpers_additional_test.go b/internal/monitoring/monitor_conversion_helpers_additional_test.go
index 8da6665114..b02b280edb 100644
--- a/internal/monitoring/monitor_conversion_helpers_additional_test.go
+++ b/internal/monitoring/monitor_conversion_helpers_additional_test.go
@@ -10,7 +10,7 @@ import (
func ptrF64Coverage(v float64) *float64 { return &v }
func TestMonitorFrontendNamesAdditional(t *testing.T) {
- t.Run("node prefers proxmox node name and preserves display name", func(t *testing.T) {
+ t.Run("frontend names use canonical display name", func(t *testing.T) {
name, display := monitorFrontendNames(unifiedresources.Resource{
ID: "node-1",
Name: "Node Friendly",
@@ -19,15 +19,15 @@ func TestMonitorFrontendNamesAdditional(t *testing.T) {
},
}, "node")
- if name != "pve-node-1" {
- t.Fatalf("name = %q, want %q", name, "pve-node-1")
+ if name != "Node Friendly" {
+ t.Fatalf("name = %q, want %q", name, "Node Friendly")
}
if display != "Node Friendly" {
t.Fatalf("display = %q, want %q", display, "Node Friendly")
}
})
- t.Run("agent and docker host use source hostnames", func(t *testing.T) {
+ t.Run("frontend names ignore source hostnames when a display name exists", func(t *testing.T) {
hostName, hostDisplay := monitorFrontendNames(unifiedresources.Resource{
ID: "host-1",
Name: "Friendly Host",
@@ -35,7 +35,7 @@ func TestMonitorFrontendNamesAdditional(t *testing.T) {
Hostname: "agent-host",
},
}, "agent")
- if hostName != "agent-host" || hostDisplay != "Friendly Host" {
+ if hostName != "Friendly Host" || hostDisplay != "Friendly Host" {
t.Fatalf("agent branch mismatch: name=%q display=%q", hostName, hostDisplay)
}
@@ -46,12 +46,12 @@ func TestMonitorFrontendNamesAdditional(t *testing.T) {
Hostname: "docker-host",
},
}, "docker-host")
- if dockerName != "docker-host" || dockerDisplay != "Friendly Docker" {
+ if dockerName != "Friendly Docker" || dockerDisplay != "Friendly Docker" {
t.Fatalf("docker branch mismatch: name=%q display=%q", dockerName, dockerDisplay)
}
})
- t.Run("falls back to id when name is empty", func(t *testing.T) {
+ t.Run("falls back to id when display name is empty", func(t *testing.T) {
name, display := monitorFrontendNames(unifiedresources.Resource{
ID: "fallback-id",
Name: " ",
@@ -59,8 +59,8 @@ func TestMonitorFrontendNamesAdditional(t *testing.T) {
if name != "fallback-id" {
t.Fatalf("name = %q, want fallback id", name)
}
- if display != "" {
- t.Fatalf("display = %q, want empty", display)
+ if display != "fallback-id" {
+ t.Fatalf("display = %q, want fallback id", display)
}
})
}
diff --git a/internal/monitoring/monitor_extra_coverage_test.go b/internal/monitoring/monitor_extra_coverage_test.go
index 574588b0b5..3ac79ec538 100644
--- a/internal/monitoring/monitor_extra_coverage_test.go
+++ b/internal/monitoring/monitor_extra_coverage_test.go
@@ -961,7 +961,7 @@ func TestMonitor_ResourcesForBroadcast_Extra(t *testing.T) {
if len(res) != 1 {
t.Errorf("Expected 1 resource, got %d", len(res))
}
- if res[0].ID != "node-1" || res[0].Type != "node" || res[0].DisplayName != "Node One" {
+ if res[0].ID != "node-1" || res[0].Type != "agent" || res[0].DisplayName != "Node One" {
t.Fatalf("unexpected resource identity payload: %#v", res[0])
}
if res[0].PlatformType != "proxmox-pve" || res[0].SourceType != "api" || res[0].Status != "online" {
diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.go
index 56d510aa04..1fa5a4f203 100644
--- a/internal/monitoring/monitor_metrics.go
+++ b/internal/monitoring/monitor_metrics.go
@@ -98,9 +98,13 @@ func (m *Monitor) GetGuestMetrics(guestID string, duration time.Duration) map[st
// sqlResourceType/sqlResourceID are the type/id used in the SQLite store
// (e.g. "dockerContainer"/"abc123").
func (m *Monitor) GetGuestMetricsForChart(inMemoryKey, sqlResourceType, sqlResourceID string, duration time.Duration) map[string][]MetricPoint {
- inMemoryResult := m.GetGuestMetrics(inMemoryKey, duration)
if mock.IsMockEnabled() {
- return m.mockGuestMetricsForChart(inMemoryKey, sqlResourceType, sqlResourceID, duration, inMemoryResult)
+ return m.mockGuestMetricsForChart(inMemoryKey, sqlResourceType, sqlResourceID, duration, m.GetGuestMetrics(inMemoryKey, duration))
+ }
+
+ inMemoryResult := map[string][]MetricPoint{}
+ if m.shouldLoadGuestChartInMemory(inMemoryKey, nil, duration) {
+ inMemoryResult = m.GetGuestMetrics(inMemoryKey, duration)
}
if hasSufficientChartMapCoverage(inMemoryResult, duration) {
@@ -130,13 +134,15 @@ func (m *Monitor) GetNodeMetrics(nodeID string, metricType string, duration time
// falling back to SQLite + LTTB for longer ranges.
func (m *Monitor) GetNodeMetricsForChart(nodeID, metricType string, duration time.Duration) []MetricPoint {
var inMemoryPoints []MetricPoint
- if m != nil && m.metricsHistory != nil {
- inMemoryPoints = m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)
- }
-
if mock.IsMockEnabled() {
+ if m != nil && m.metricsHistory != nil {
+ inMemoryPoints = m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)
+ }
return m.mockNodeMetricsForChart(nodeID, metricType, duration, inMemoryPoints)
}
+ if m != nil && m.shouldLoadNodeChartInMemory(nodeID, []string{metricType}, duration) {
+ inMemoryPoints = m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)
+ }
if m.metricsStore == nil {
return inMemoryPoints
@@ -499,6 +505,26 @@ func filterChartMetricMap(metricMap map[string][]MetricPoint, metricTypes []stri
return filtered
}
+func (m *Monitor) shouldLoadGuestChartInMemory(inMemoryKey string, metricTypes []string, duration time.Duration) bool {
+ if m == nil || m.metricsHistory == nil {
+ return false
+ }
+ if m.metricsStore == nil || duration <= inMemoryChartThreshold {
+ return true
+ }
+ return m.metricsHistory.GuestMetricCoverageSpan(inMemoryKey, metricTypes, duration) >= chartCoverageRequiredSpan(duration)
+}
+
+func (m *Monitor) shouldLoadNodeChartInMemory(nodeID string, metricTypes []string, duration time.Duration) bool {
+ if m == nil || m.metricsHistory == nil {
+ return false
+ }
+ if m.metricsStore == nil || duration <= inMemoryChartThreshold {
+ return true
+ }
+ return m.metricsHistory.NodeMetricCoverageSpan(nodeID, metricTypes, duration) >= chartCoverageRequiredSpan(duration)
+}
+
// GetGuestMetricsForChartBatch returns chart metrics for multiple guests of the
// same SQL resource type, using batch SQL queries instead of N individual
// queries. Results are keyed by SQLResourceID.
@@ -533,15 +559,11 @@ func (m *Monitor) GetGuestMetricsForChartBatch(
// Phase 1: Check in-memory for all guests and identify which need fallback.
var needFallback []string
- useInMemory := duration <= inMemoryChartThreshold || m.metricsStore == nil
for _, req := range requests {
- if !useInMemory {
- result[req.SQLResourceID] = map[string][]MetricPoint{}
- needFallback = append(needFallback, req.SQLResourceID)
- continue
+ inMemory := map[string][]MetricPoint{}
+ if m.shouldLoadGuestChartInMemory(req.InMemoryKey, requestedMetricTypes, duration) {
+ inMemory = filterChartMetricMap(m.GetGuestMetrics(req.InMemoryKey, duration), requestedMetricTypes)
}
-
- inMemory := filterChartMetricMap(m.GetGuestMetrics(req.InMemoryKey, duration), requestedMetricTypes)
result[req.SQLResourceID] = inMemory
if hasSufficientChartMapCoverage(inMemory, duration) {
continue
@@ -624,17 +646,18 @@ func (m *Monitor) GetNodeMetricsForChartBatch(
// Phase 1: Check in-memory for all nodes and identify which need store.
var needStore []string
- useInMemory := duration <= inMemoryChartThreshold || m.metricsStore == nil
for _, nid := range nodeIDs {
nodeResult := make(map[string][]MetricPoint, len(metricTypes))
- if !useInMemory {
- result[nid] = nodeResult
- needStore = append(needStore, nid)
- continue
- }
allSufficient := true
+ loadInMemory := m.shouldLoadNodeChartInMemory(nid, metricTypes, duration)
for _, mt := range metricTypes {
+ if !loadInMemory {
+ nodeResult[mt] = nil
+ allSufficient = false
+ continue
+ }
+
points := m.metricsHistory.GetNodeMetrics(nid, mt, duration)
nodeResult[mt] = points
if m.metricsStore != nil && !hasSufficientChartSeriesCoverage(points, duration) {
diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.go
index f9a7c61482..a36033d970 100644
--- a/internal/monitoring/monitor_metrics_slo_test.go
+++ b/internal/monitoring/monitor_metrics_slo_test.go
@@ -171,6 +171,64 @@ func seedSLONodeMetrics(t *testing.T, store *metrics.Store, numNodes, numPoints
return ids
}
+func seedInMemorySLOGuestMetrics(t *testing.T, history *MetricsHistory, resourceType string, numResources, numPoints int, duration time.Duration) []GuestChartRequest {
+ t.Helper()
+
+ metricTypes := []string{"cpu", "memory", "disk", "netin", "netout"}
+ now := time.Now().UTC().Truncate(time.Second)
+ step := duration / time.Duration(numPoints-1)
+ if step <= 0 {
+ step = time.Minute
+ }
+
+ requests := make([]GuestChartRequest, numResources)
+ for r := 0; r < numResources; r++ {
+ id := fmt.Sprintf("%s-inmem-slo-%d", resourceType, r)
+ requests[r] = GuestChartRequest{InMemoryKey: id, SQLResourceID: id}
+ for _, mt := range metricTypes {
+ for p := 0; p < numPoints; p++ {
+ history.AddGuestMetric(
+ id,
+ mt,
+ float64((p%100)+(r%10)),
+ now.Add(-duration).Add(time.Duration(p)*step),
+ )
+ }
+ }
+ }
+
+ return requests
+}
+
+func seedInMemorySLONodeMetrics(t *testing.T, history *MetricsHistory, numNodes, numPoints int, duration time.Duration) []string {
+ t.Helper()
+
+ metricTypes := []string{"cpu", "memory", "disk", "netin", "netout"}
+ now := time.Now().UTC().Truncate(time.Second)
+ step := duration / time.Duration(numPoints-1)
+ if step <= 0 {
+ step = time.Minute
+ }
+
+ ids := make([]string, numNodes)
+ for n := 0; n < numNodes; n++ {
+ id := fmt.Sprintf("node-inmem-slo-%d", n)
+ ids[n] = id
+ for _, mt := range metricTypes {
+ for p := 0; p < numPoints; p++ {
+ history.AddNodeMetric(
+ id,
+ mt,
+ float64((p%100)+(n%10)),
+ now.Add(-duration).Add(time.Duration(p)*step),
+ )
+ }
+ }
+ }
+
+ return ids
+}
+
func TestSLO_GetGuestMetricsForChartBatch(t *testing.T) {
skipMonitoringSLOUnderRace(t)
suppressMonitoringTestLogs(t)
@@ -210,6 +268,44 @@ func TestSLO_GetGuestMetricsForChartBatch(t *testing.T) {
}
}
+func TestSLO_GetGuestMetricsForChartBatch_LongRangeCoveredInMemory(t *testing.T) {
+ skipMonitoringSLOUnderRace(t)
+ suppressMonitoringTestLogs(t)
+
+ duration := 7 * 24 * time.Hour
+ metricTypes := []string{"cpu", "memory", "disk", "netin", "netout"}
+ monitor := &Monitor{
+ metricsHistory: NewMetricsHistory(4096, 30*24*time.Hour),
+ }
+ requests := seedInMemorySLOGuestMetrics(t, monitor.metricsHistory, "container", 24, 240, duration)
+
+ sanity := monitor.GetGuestMetricsForChartBatch("container", requests, duration, metricTypes...)
+ if len(sanity) != len(requests) {
+ t.Fatalf("sanity: expected %d guests, got %d", len(requests), len(sanity))
+ }
+ for _, req := range requests {
+ if cpuPts := sanity[req.SQLResourceID]["cpu"]; len(cpuPts) == 0 {
+ t.Fatalf("sanity: guest %s has no cpu points", req.SQLResourceID)
+ }
+ }
+
+ latencies := measureMonitoringLatencies(t, func() {
+ result := monitor.GetGuestMetricsForChartBatch("container", requests, duration, metricTypes...)
+ if len(result) != len(requests) {
+ t.Fatalf("expected %d guests, got %d", len(requests), len(result))
+ }
+ })
+
+ target := effectiveMonitoringSLOTarget(SLOGuestChartBatchP95, SLOGuestChartBatchGitHubActionsP95)
+ p95 := monitoringPercentile(latencies, 0.95)
+ t.Logf("GetGuestMetricsForChartBatch(24×5×240, 7d in-memory) p50=%v p95=%v p99=%v SLO=%v",
+ monitoringPercentile(latencies, 0.50), p95, monitoringPercentile(latencies, 0.99), target)
+
+ if p95 > target {
+ t.Errorf("SLO VIOLATION: p95=%v exceeds target %v", p95, target)
+ }
+}
+
func TestSLO_GetNodeMetricsForChartBatch(t *testing.T) {
skipMonitoringSLOUnderRace(t)
suppressMonitoringTestLogs(t)
@@ -246,6 +342,44 @@ func TestSLO_GetNodeMetricsForChartBatch(t *testing.T) {
}
}
+func TestSLO_GetNodeMetricsForChartBatch_LongRangeCoveredInMemory(t *testing.T) {
+ skipMonitoringSLOUnderRace(t)
+ suppressMonitoringTestLogs(t)
+
+ duration := 7 * 24 * time.Hour
+ metricTypes := []string{"cpu", "memory", "disk", "netin", "netout"}
+ monitor := &Monitor{
+ metricsHistory: NewMetricsHistory(4096, 30*24*time.Hour),
+ }
+ ids := seedInMemorySLONodeMetrics(t, monitor.metricsHistory, 20, 240, duration)
+
+ sanity := monitor.GetNodeMetricsForChartBatch(ids, metricTypes, duration)
+ if len(sanity) != len(ids) {
+ t.Fatalf("sanity: expected %d nodes, got %d", len(ids), len(sanity))
+ }
+ for _, id := range ids {
+ if cpuPts := sanity[id]["cpu"]; len(cpuPts) == 0 {
+ t.Fatalf("sanity: node %s has no cpu points", id)
+ }
+ }
+
+ latencies := measureMonitoringLatencies(t, func() {
+ result := monitor.GetNodeMetricsForChartBatch(ids, metricTypes, duration)
+ if len(result) != len(ids) {
+ t.Fatalf("expected %d nodes, got %d", len(ids), len(result))
+ }
+ })
+
+ target := effectiveMonitoringSLOTarget(SLONodeChartBatchP95, SLONodeChartBatchGitHubActionsP95)
+ p95 := monitoringPercentile(latencies, 0.95)
+ t.Logf("GetNodeMetricsForChartBatch(20×5×240, 7d in-memory) p50=%v p95=%v p99=%v SLO=%v",
+ monitoringPercentile(latencies, 0.50), p95, monitoringPercentile(latencies, 0.99), target)
+
+ if p95 > target {
+ t.Errorf("SLO VIOLATION: p95=%v exceeds target %v", p95, target)
+ }
+}
+
func TestGetNodeMetricsForChartBatch_FiltersStoreReadsToRequestedMetricTypes(t *testing.T) {
suppressMonitoringTestLogs(t)
diff --git a/internal/testutil/mockmode.go b/internal/testutil/mockmode.go
new file mode 100644
index 0000000000..fd2a4b634a
--- /dev/null
+++ b/internal/testutil/mockmode.go
@@ -0,0 +1,31 @@
+package testutil
+
+import (
+ "strconv"
+ "sync"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
+)
+
+var mockModeTestMu sync.Mutex
+
+// SetMockMode synchronizes the canonical in-process mock runtime state for a
+// test and keeps the legacy env flag aligned for code paths that still read it.
+func SetMockMode(t *testing.T, enabled bool) {
+ t.Helper()
+
+ mockModeTestMu.Lock()
+ previous := mock.IsMockEnabled()
+ t.Setenv("PULSE_MOCK_MODE", strconv.FormatBool(enabled))
+ if err := mock.SetEnabled(enabled); err != nil {
+ mockModeTestMu.Unlock()
+ t.Fatalf("set mock mode: %v", err)
+ }
+ t.Cleanup(func() {
+ if err := mock.SetEnabled(previous); err != nil {
+ t.Fatalf("restore mock mode: %v", err)
+ }
+ mockModeTestMu.Unlock()
+ })
+}
diff --git a/internal/unifiedresources/kubernetes_registry_test.go b/internal/unifiedresources/kubernetes_registry_test.go
index 771f025a54..c85b8d83b7 100644
--- a/internal/unifiedresources/kubernetes_registry_test.go
+++ b/internal/unifiedresources/kubernetes_registry_test.go
@@ -221,45 +221,48 @@ func TestIngestSnapshotLinksKubernetesNodesToHostAgentMetrics(t *testing.T) {
registry.IngestSnapshot(snapshot)
resources := registry.List()
- if len(resources) != 3 {
- t.Fatalf("expected 3 resources (host + cluster + node), got %d", len(resources))
+ if len(resources) != 2 {
+ t.Fatalf("expected 2 resources (cluster + merged agent), got %d", len(resources))
}
var clusterResource *Resource
- var nodeResource *Resource
+ var agentResource *Resource
for i := range resources {
resource := resources[i]
switch resource.Type {
case ResourceTypeK8sCluster:
clusterResource = &resource
- case ResourceTypeK8sNode:
- nodeResource = &resource
+ case ResourceTypeAgent:
+ agentResource = &resource
}
}
- if nodeResource == nil {
- t.Fatal("expected kubernetes node resource")
+ if agentResource == nil {
+ t.Fatal("expected linked kubernetes node to merge into agent resource")
}
- if nodeResource.Metrics == nil || nodeResource.Metrics.CPU == nil || nodeResource.Metrics.CPU.Value <= 0 {
- t.Fatalf("expected kubernetes node cpu metric from linked host, got %+v", nodeResource.Metrics)
+ if agentResource.Metrics == nil || agentResource.Metrics.CPU == nil || agentResource.Metrics.CPU.Value <= 0 {
+ t.Fatalf("expected merged agent cpu metric from linked host, got %+v", agentResource.Metrics)
}
- if nodeResource.Metrics.NetIn == nil || nodeResource.Metrics.NetIn.Value != 1200 {
- t.Fatalf("expected kubernetes node netIn metric from linked host, got %+v", nodeResource.Metrics)
+ if agentResource.Metrics.NetIn == nil || agentResource.Metrics.NetIn.Value != 1200 {
+ t.Fatalf("expected merged agent netIn metric from linked host, got %+v", agentResource.Metrics)
}
- if nodeResource.Kubernetes == nil || nodeResource.Kubernetes.UptimeSeconds != 7200 {
- t.Fatalf("expected kubernetes node uptime from linked host, got %+v", nodeResource.Kubernetes)
+ if agentResource.Kubernetes == nil || agentResource.Kubernetes.UptimeSeconds != 7200 {
+ t.Fatalf("expected kubernetes node payload to retain linked host uptime, got %+v", agentResource.Kubernetes)
}
- if nodeResource.Kubernetes.Temperature == nil || *nodeResource.Kubernetes.Temperature <= 0 {
- t.Fatalf("expected kubernetes node temperature from linked host, got %+v", nodeResource.Kubernetes)
+ if agentResource.Kubernetes.Temperature == nil || *agentResource.Kubernetes.Temperature <= 0 {
+ t.Fatalf("expected kubernetes node payload to retain linked host temperature, got %+v", agentResource.Kubernetes)
}
- if nodeResource.Kubernetes.MetricCapabilities == nil {
+ if agentResource.Kubernetes.MetricCapabilities == nil {
t.Fatalf("expected kubernetes metric capabilities on node resource, got nil")
}
- if !nodeResource.Kubernetes.MetricCapabilities.NodeCPUMemory {
- t.Fatalf("expected node CPU/memory capability from linked host, got %+v", nodeResource.Kubernetes.MetricCapabilities)
+ if !agentResource.Kubernetes.MetricCapabilities.NodeCPUMemory {
+ t.Fatalf("expected node CPU/memory capability from linked host, got %+v", agentResource.Kubernetes.MetricCapabilities)
+ }
+ if !agentResource.Kubernetes.MetricCapabilities.NodeTelemetry {
+ t.Fatalf("expected node telemetry capability from linked host, got %+v", agentResource.Kubernetes.MetricCapabilities)
}
- if !nodeResource.Kubernetes.MetricCapabilities.NodeTelemetry {
- t.Fatalf("expected node telemetry capability from linked host, got %+v", nodeResource.Kubernetes.MetricCapabilities)
+ if !hasDataSource(agentResource.Sources, SourceAgent) || !hasDataSource(agentResource.Sources, SourceK8s) {
+ t.Fatalf("expected merged agent sources to include agent+kubernetes, got %+v", agentResource.Sources)
}
if clusterResource == nil {
diff --git a/internal/unifiedresources/mockmode_test.go b/internal/unifiedresources/mockmode_test.go
index 3f2c3acfa7..c47e949881 100644
--- a/internal/unifiedresources/mockmode_test.go
+++ b/internal/unifiedresources/mockmode_test.go
@@ -1,8 +1,22 @@
package unifiedresources
-import "testing"
+import (
+ "sync"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/mockruntime"
+)
+
+var mockModeTestMu sync.Mutex
func enableMockMode(t *testing.T) {
t.Helper()
+ mockModeTestMu.Lock()
+ previous := mockruntime.IsEnabled()
t.Setenv("PULSE_MOCK_MODE", "true")
+ mockruntime.SetEnabled(true)
+ t.Cleanup(func() {
+ mockruntime.SetEnabled(previous)
+ mockModeTestMu.Unlock()
+ })
}