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.

Canonicalize mock chart history continuity

rcourtman83f4b28b3a27
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index a3bd6b20f6..2bfeba45c3 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -46,6 +46,8 @@ truth for live infrastructure data.
22. `internal/monitoring/monitor_pve_guest_builders.go`
23. `internal/monitoring/monitor_pve_guest_poll.go`
24. `internal/monitoring/guest_disk_stability.go`
+25. `internal/monitoring/mock_metrics_history.go`
+26. `internal/monitoring/mock_chart_history.go`
## Shared Boundaries
@@ -59,6 +61,9 @@ truth for live infrastructure data.
4. Add unified supplemental ingest through `internal/monitoring/poll_providers.go`
5. Add or change container startup ownership/bootstrap behavior for hosted or managed Pulse runtime mounts through `docker-entrypoint.sh`
6. Add or change Docker Swarm manager task/service runtime collection through `internal/dockeragent/swarm.go`
+7. Add or change mock chart synthesis, seeded history continuity, or mock-owned
+ chart fallbacks through `internal/monitoring/mock_metrics_history.go` and
+ `internal/monitoring/mock_chart_history.go`
## Forbidden Paths
diff --git a/internal/mock/config_validation.go b/internal/mock/config_validation.go
index f1b9275eda..a0889ca363 100644
--- a/internal/mock/config_validation.go
+++ b/internal/mock/config_validation.go
@@ -41,6 +41,32 @@ func normalizeMockConfig(cfg MockConfig) MockConfig {
return cfg
}
+func mockConfigsEqual(a, b MockConfig) bool {
+ if a.NodeCount != b.NodeCount ||
+ a.VMsPerNode != b.VMsPerNode ||
+ a.LXCsPerNode != b.LXCsPerNode ||
+ a.DockerHostCount != b.DockerHostCount ||
+ a.DockerContainersPerHost != b.DockerContainersPerHost ||
+ a.GenericHostCount != b.GenericHostCount ||
+ a.K8sClusterCount != b.K8sClusterCount ||
+ a.K8sNodesPerCluster != b.K8sNodesPerCluster ||
+ a.K8sPodsPerCluster != b.K8sPodsPerCluster ||
+ a.K8sDeploymentsPerCluster != b.K8sDeploymentsPerCluster ||
+ a.RandomMetrics != b.RandomMetrics ||
+ a.StoppedPercent != b.StoppedPercent {
+ return false
+ }
+ if len(a.HighLoadNodes) != len(b.HighLoadNodes) {
+ return false
+ }
+ for i := range a.HighLoadNodes {
+ if a.HighLoadNodes[i] != b.HighLoadNodes[i] {
+ return false
+ }
+ }
+ return true
+}
+
func normalizeStoppedPercent(v float64) float64 {
if math.IsNaN(v) || math.IsInf(v, 0) {
return DefaultConfig.StoppedPercent
diff --git a/internal/mock/integration.go b/internal/mock/integration.go
index 417fd341f5..6394f176a1 100644
--- a/internal/mock/integration.go
+++ b/internal/mock/integration.go
@@ -414,26 +414,33 @@ func SetMockConfig(cfg MockConfig) {
log.Warn().Float64("provided", cfg.StoppedPercent).Float64("applied", normalized.StoppedPercent).Msg("Normalized invalid mock StoppedPercent")
}
+ var configChanged bool
dataMu.Lock()
+ configChanged = !mockConfigsEqual(mockConfig, normalized)
mockConfig = normalized
- if enabled.Load() {
+ if configChanged && enabled.Load() {
mockGraph = buildFixtureGraph(normalized, time.Now())
}
dataMu.Unlock()
+ if !configChanged {
+ log.Debug().Msg("Mock configuration unchanged")
+ return
+ }
+
log.Info().
- Int("nodes", cfg.NodeCount).
- Int("vms_per_node", cfg.VMsPerNode).
- Int("lxcs_per_node", cfg.LXCsPerNode).
- Int("agent_hosts", cfg.GenericHostCount).
- Int("docker_hosts", cfg.DockerHostCount).
- Int("docker_containers_per_host", cfg.DockerContainersPerHost).
- Int("k8s_clusters", cfg.K8sClusterCount).
- Int("k8s_nodes_per_cluster", cfg.K8sNodesPerCluster).
- Int("k8s_pods_per_cluster", cfg.K8sPodsPerCluster).
- Int("k8s_deployments_per_cluster", cfg.K8sDeploymentsPerCluster).
- Bool("random_metrics", cfg.RandomMetrics).
- Float64("stopped_percent", cfg.StoppedPercent).
+ Int("nodes", normalized.NodeCount).
+ Int("vms_per_node", normalized.VMsPerNode).
+ Int("lxcs_per_node", normalized.LXCsPerNode).
+ Int("agent_hosts", normalized.GenericHostCount).
+ Int("docker_hosts", normalized.DockerHostCount).
+ Int("docker_containers_per_host", normalized.DockerContainersPerHost).
+ Int("k8s_clusters", normalized.K8sClusterCount).
+ Int("k8s_nodes_per_cluster", normalized.K8sNodesPerCluster).
+ Int("k8s_pods_per_cluster", normalized.K8sPodsPerCluster).
+ Int("k8s_deployments_per_cluster", normalized.K8sDeploymentsPerCluster).
+ Bool("random_metrics", normalized.RandomMetrics).
+ Float64("stopped_percent", normalized.StoppedPercent).
Msg("Mock configuration updated")
}
diff --git a/internal/mock/integration_coverage_test.go b/internal/mock/integration_coverage_test.go
index af06e5e547..34a759d7fd 100644
--- a/internal/mock/integration_coverage_test.go
+++ b/internal/mock/integration_coverage_test.go
@@ -289,6 +289,35 @@ func TestSetEnabledUsesCurrentConfigInsteadOfReloadingEnv(t *testing.T) {
}
}
+func TestSetMockConfigEquivalentEnabledConfigDoesNotRebuildGraph(t *testing.T) {
+ resetMockIntegrationState(t)
+
+ cfg := DefaultConfig
+ cfg.NodeCount = 3
+ cfg.DockerHostCount = 2
+ cfg.DockerContainersPerHost = 5
+
+ dataMu.Lock()
+ mockConfig = cfg
+ mockGraph = buildFixtureGraph(cfg, time.Unix(1700000000, 0).UTC())
+ enabled.Store(true)
+ dataMu.Unlock()
+
+ before := CurrentFixtureGraph()
+ SetMockConfig(cfg)
+ after := CurrentFixtureGraph()
+
+ if !after.State.LastUpdate.Equal(before.State.LastUpdate) {
+ t.Fatalf("expected equivalent config update to preserve graph freshness, before=%s after=%s", before.State.LastUpdate, after.State.LastUpdate)
+ }
+ if len(after.State.DockerHosts) != len(before.State.DockerHosts) {
+ t.Fatalf("expected equivalent config update to preserve docker host count, before=%d after=%d", len(before.State.DockerHosts), len(after.State.DockerHosts))
+ }
+ if len(after.State.PhysicalDisks) != len(before.State.PhysicalDisks) {
+ t.Fatalf("expected equivalent config update to preserve physical disk count, before=%d after=%d", len(before.State.PhysicalDisks), len(after.State.PhysicalDisks))
+ }
+}
+
func TestUpdateMetricsGuardAndTimestamp(t *testing.T) {
resetMockIntegrationState(t)
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index ea828f50a5..598899082d 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -722,6 +722,14 @@ func TestMockNativePollersDeferToCanonicalMockSampler(t *testing.T) {
"return nil",
},
},
+ {
+ file: "mock_chart_history.go",
+ snippets: []string{
+ "func mockCanonicalMetricSeries(resourceType, resourceID, metricType string, timestamps []time.Time) []MetricPoint {",
+ "values := canonicalMetricSeries(resourceType, resourceID, metricType, timestamps)",
+ "return lttb(points, chartDownsampleTarget)",
+ },
+ },
{
file: "mock_metrics_history.go",
snippets: []string{
diff --git a/internal/monitoring/kubernetes_agents.go b/internal/monitoring/kubernetes_agents.go
index 7b74f4d2da..e364ae3cb1 100644
--- a/internal/monitoring/kubernetes_agents.go
+++ b/internal/monitoring/kubernetes_agents.go
@@ -374,6 +374,9 @@ func (m *Monitor) recordKubernetesPodMetrics(cluster models.KubernetesCluster, t
if timestamp.IsZero() {
timestamp = time.Now().UTC()
}
+ if shouldSkipNativeMockStateMetricWrites() {
+ return
+ }
for _, pod := range cluster.Pods {
metricID := kubernetesPodMetricID(cluster, pod)
diff --git a/internal/monitoring/memory_source_catalog_test.go b/internal/monitoring/memory_source_catalog_test.go
index dada002573..fd4b8546f4 100644
--- a/internal/monitoring/memory_source_catalog_test.go
+++ b/internal/monitoring/memory_source_catalog_test.go
@@ -1,6 +1,10 @@
package monitoring
-import "testing"
+import (
+ "os"
+ "strings"
+ "testing"
+)
func TestDescribeMemorySourceCanonicalizesAliases(t *testing.T) {
t.Parallel()
@@ -122,3 +126,24 @@ func TestDescribeMemorySourceCanonicalizesAliases(t *testing.T) {
})
}
}
+
+func TestMockVMPollingDefersMemoryHistoryToCanonicalSampler(t *testing.T) {
+ t.Parallel()
+
+ data, err := os.ReadFile("monitor_polling_vm.go")
+ if err != nil {
+ t.Fatalf("failed to read monitor_polling_vm.go: %v", err)
+ }
+ source := string(data)
+
+ requiredSnippets := []string{
+ "if !shouldSkipNativeMockStateMetricWrites() {",
+ `m.metricsHistory.AddGuestMetric(vm.ID, "memory", vm.Memory.Usage, now)`,
+ `m.metricsStore.Write("vm", vm.ID, "memory", vm.Memory.Usage, now)`,
+ }
+ for _, snippet := range requiredSnippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("monitor_polling_vm.go must contain %q", snippet)
+ }
+ }
+}
diff --git a/internal/monitoring/mock_chart_history.go b/internal/monitoring/mock_chart_history.go
new file mode 100644
index 0000000000..0da4050d13
--- /dev/null
+++ b/internal/monitoring/mock_chart_history.go
@@ -0,0 +1,217 @@
+package monitoring
+
+import (
+ "math"
+ "strings"
+ "time"
+)
+
+var (
+ mockGuestChartMetricTypes = []string{"cpu", "memory", "disk", "diskread", "diskwrite", "netin", "netout"}
+ mockNodeChartMetricTypes = []string{"cpu", "memory", "disk", "netin", "netout"}
+)
+
+func normalizeMockChartResourceType(resourceType string) string {
+ switch strings.TrimSpace(resourceType) {
+ case "system-container":
+ return "container"
+ case "app-container", "docker":
+ return "dockerContainer"
+ case "pod":
+ return "k8s"
+ default:
+ return strings.TrimSpace(resourceType)
+ }
+}
+
+func mockChartTimestamps(duration time.Duration) []time.Time {
+ if duration <= 0 {
+ duration = time.Hour
+ }
+
+ now := normalizeMockMetricTimestamp(time.Now().UTC(), defaultMockSampleInterval)
+ timestamps := buildTieredTimestamps(now, duration)
+ if len(timestamps) > 0 {
+ return timestamps
+ }
+
+ return []time.Time{
+ now.Add(-duration),
+ now,
+ }
+}
+
+func mockCanonicalMetricSeries(resourceType, resourceID, metricType string, timestamps []time.Time) []MetricPoint {
+ resourceType = normalizeMockChartResourceType(resourceType)
+ resourceID = strings.TrimSpace(resourceID)
+ metricType = strings.TrimSpace(metricType)
+ if resourceType == "" || resourceID == "" || metricType == "" || len(timestamps) == 0 {
+ return nil
+ }
+
+ values := canonicalMetricSeries(resourceType, resourceID, metricType, timestamps)
+ if len(values) == 0 {
+ return nil
+ }
+
+ points := make([]MetricPoint, len(values))
+ for i, value := range values {
+ points[i] = MetricPoint{
+ Timestamp: timestamps[i],
+ Value: value,
+ }
+ }
+
+ return lttb(points, chartDownsampleTarget)
+}
+
+func mockGuestMetricsForChart(resourceType, resourceID string, duration time.Duration) map[string][]MetricPoint {
+ resourceType = normalizeMockChartResourceType(resourceType)
+ switch resourceType {
+ case "vm", "container", "dockerContainer", "dockerHost", "agent", "k8s":
+ default:
+ return map[string][]MetricPoint{}
+ }
+
+ timestamps := mockChartTimestamps(duration)
+ result := make(map[string][]MetricPoint, len(mockGuestChartMetricTypes))
+ for _, metricType := range mockGuestChartMetricTypes {
+ result[metricType] = mockCanonicalMetricSeries(resourceType, resourceID, metricType, timestamps)
+ }
+ return result
+}
+
+func mockNodeMetricsForChart(nodeID string, metricTypes []string, duration time.Duration) map[string][]MetricPoint {
+ nodeID = strings.TrimSpace(nodeID)
+ if nodeID == "" {
+ return map[string][]MetricPoint{}
+ }
+ if len(metricTypes) == 0 {
+ metricTypes = mockNodeChartMetricTypes
+ }
+
+ timestamps := mockChartTimestamps(duration)
+ result := make(map[string][]MetricPoint, len(metricTypes))
+ for _, metricType := range metricTypes {
+ result[metricType] = mockCanonicalMetricSeries("node", nodeID, metricType, timestamps)
+ }
+ return result
+}
+
+func latestMetricPoint(points []MetricPoint) (MetricPoint, bool) {
+ if len(points) == 0 {
+ return MetricPoint{}, false
+ }
+
+ latest := points[0]
+ for i := 1; i < len(points); i++ {
+ if points[i].Timestamp.After(latest.Timestamp) {
+ latest = points[i]
+ }
+ }
+ return latest, true
+}
+
+func (m *Monitor) resolveMockStorageTotal(storageID string, inMemory map[string][]MetricPoint) float64 {
+ readState := m.GetUnifiedReadStateOrSnapshot()
+ if readState != nil {
+ for _, pool := range readState.StoragePools() {
+ if pool == nil || strings.TrimSpace(pool.SourceID()) != strings.TrimSpace(storageID) {
+ continue
+ }
+ if total := float64(pool.DiskTotal()); total > 0 {
+ return total
+ }
+ }
+ }
+
+ if latest, ok := latestMetricPoint(inMemory["total"]); ok && latest.Value > 0 {
+ return latest.Value
+ }
+
+ return 0
+}
+
+func (m *Monitor) mockStorageMetricsForChart(storageID string, duration time.Duration, inMemory map[string][]MetricPoint) map[string][]MetricPoint {
+ total := m.resolveMockStorageTotal(storageID, inMemory)
+ if total <= 0 {
+ return cloneMetricPointMap(inMemory)
+ }
+
+ timestamps := mockChartTimestamps(duration)
+ usageValues := canonicalMetricSeries("storage", storageID, "usage", timestamps)
+ if len(usageValues) == 0 {
+ return cloneMetricPointMap(inMemory)
+ }
+
+ usagePoints := make([]MetricPoint, len(timestamps))
+ usedPoints := make([]MetricPoint, len(timestamps))
+ availPoints := make([]MetricPoint, len(timestamps))
+ totalPoints := make([]MetricPoint, len(timestamps))
+ for i, ts := range timestamps {
+ usage := clampFloat(usageValues[i], 0, 100)
+ used := total * (usage / 100.0)
+ avail := math.Max(0, total-used)
+ usagePoints[i] = MetricPoint{Timestamp: ts, Value: usage}
+ usedPoints[i] = MetricPoint{Timestamp: ts, Value: used}
+ availPoints[i] = MetricPoint{Timestamp: ts, Value: avail}
+ totalPoints[i] = MetricPoint{Timestamp: ts, Value: total}
+ }
+
+ return map[string][]MetricPoint{
+ "usage": lttb(usagePoints, chartDownsampleTarget),
+ "used": lttb(usedPoints, chartDownsampleTarget),
+ "avail": lttb(availPoints, chartDownsampleTarget),
+ "total": lttb(totalPoints, chartDownsampleTarget),
+ }
+}
+
+func (m *Monitor) mockPhysicalDiskTemperatureCharts(duration time.Duration) map[string]DiskChartEntry {
+ if m == nil {
+ return nil
+ }
+
+ readState := m.GetUnifiedReadStateOrSnapshot()
+ if readState == nil {
+ return nil
+ }
+ metricsTargetStore := m.currentMetricsTargetStore()
+ timestamps := mockChartTimestamps(duration)
+ if len(timestamps) == 0 {
+ return nil
+ }
+
+ result := make(map[string]DiskChartEntry)
+ for _, disk := range readState.PhysicalDisks() {
+ if disk == nil || disk.Temperature() <= 0 {
+ continue
+ }
+
+ resourceID := ""
+ if metricsTargetStore != nil {
+ if target := metricsTargetStore.MetricsTargetForResource(disk.ID()); target != nil {
+ resourceID = strings.TrimSpace(target.ResourceID)
+ }
+ }
+ if resourceID == "" {
+ resourceID = strings.TrimSpace(disk.MetricResourceID())
+ }
+ if resourceID == "" {
+ continue
+ }
+
+ name := strings.TrimSpace(disk.Model())
+ if name == "" {
+ name = strings.TrimSpace(disk.DevPath())
+ }
+
+ result[resourceID] = DiskChartEntry{
+ Name: name,
+ Node: strings.TrimSpace(disk.Node()),
+ Instance: strings.TrimSpace(disk.Instance()),
+ Temperature: mockCanonicalMetricSeries("disk", resourceID, "smart_temp", timestamps),
+ }
+ }
+
+ return result
+}
diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.go
index c2f165101a..bc86f9e38d 100644
--- a/internal/monitoring/mock_metrics_history.go
+++ b/internal/monitoring/mock_metrics_history.go
@@ -101,143 +101,6 @@ func kubernetesPodMetricID(cluster models.KubernetesCluster, pod models.Kubernet
return fmt.Sprintf("k8s:%s:pod:%s", clusterKey, podKey)
}
-func kubernetesPodCurrentMetrics(cluster models.KubernetesCluster, pod models.KubernetesPod) map[string]float64 {
- clusterKey := kubernetesClusterMetricID(cluster)
- podKey := strings.TrimSpace(pod.UID)
- if podKey == "" {
- podKey = strings.TrimSpace(pod.Namespace) + "/" + strings.TrimSpace(pod.Name)
- }
- seed := HashSeed("k8s-pod-current", clusterKey, podKey)
- rng := rand.New(rand.NewSource(int64(seed)))
-
- phase := strings.ToLower(strings.TrimSpace(pod.Phase))
- totalContainers := len(pod.Containers)
- if totalContainers <= 0 {
- totalContainers = 1
- }
- readyContainers := 0
- for _, container := range pod.Containers {
- if container.Ready {
- readyContainers++
- }
- }
- readiness := float64(readyContainers) / float64(totalContainers)
- if readiness <= 0 && phase == "running" {
- readiness = 0.35
- }
-
- restarts := float64(pod.Restarts)
- if restarts < 0 {
- restarts = 0
- }
- restartFactor := math.Min(restarts*1.6, 16)
-
- cpu := clampFloat(pod.UsageCPUPercent, 0, 100)
- memory := clampFloat(pod.UsageMemoryPercent, 0, 100)
- disk := clampFloat(pod.DiskUsagePercent, 0, 100)
- netIn := clampFloat(pod.NetInRate, 0, math.Max(pod.NetInRate, 0))
- netOut := clampFloat(pod.NetOutRate, 0, math.Max(pod.NetOutRate, 0))
-
- // When the live report has no usage sample yet, synthesize only the metrics
- // that exist in real production Kubernetes collection paths.
- if cpu <= 0 || memory <= 0 || disk <= 0 || netIn <= 0 || netOut <= 0 {
- switch phase {
- case "running":
- if cpu <= 0 {
- cpu = 7 + readiness*52 + rng.Float64()*14 - restartFactor*0.35
- }
- if memory <= 0 {
- memory = 26 + readiness*46 + rng.Float64()*14 + restartFactor*0.25
- }
- if disk <= 0 {
- disk = 17 + readiness*42 + rng.Float64()*16
- }
- if netIn <= 0 {
- netIn = 14 + readiness*220 + rng.Float64()*70 + restarts*2
- }
- if netOut <= 0 {
- netOut = 10 + readiness*180 + rng.Float64()*55 + restarts*1.6
- }
- case "pending":
- if cpu <= 0 {
- cpu = 2 + rng.Float64()*7
- }
- if memory <= 0 {
- memory = 14 + rng.Float64()*16
- }
- if disk <= 0 {
- disk = 8 + rng.Float64()*14
- }
- if netIn <= 0 {
- netIn = 1 + rng.Float64()*10
- }
- if netOut <= 0 {
- netOut = 1 + rng.Float64()*8
- }
- case "failed", "unknown":
- if cpu <= 0 {
- cpu = 1 + rng.Float64()*8
- }
- if memory <= 0 {
- memory = 9 + rng.Float64()*15 + restartFactor*0.5
- }
- if disk <= 0 {
- disk = 7 + rng.Float64()*16
- }
- if netIn <= 0 {
- netIn = 1 + rng.Float64()*14 + restarts*1.4
- }
- if netOut <= 0 {
- netOut = 1 + rng.Float64()*11 + restarts*1.2
- }
- default:
- if cpu <= 0 {
- cpu = 1 + rng.Float64()*6
- }
- if memory <= 0 {
- memory = 8 + rng.Float64()*12
- }
- if disk <= 0 {
- disk = 6 + rng.Float64()*12
- }
- if netIn <= 0 {
- netIn = 1 + rng.Float64()*7
- }
- if netOut <= 0 {
- netOut = 1 + rng.Float64()*6
- }
- }
- if totalContainers > 1 {
- multi := 1 + math.Min(float64(totalContainers-1)*0.08, 0.6)
- if cpu > 0 {
- cpu *= multi
- }
- if memory > 0 {
- memory *= 1 + math.Min(float64(totalContainers-1)*0.1, 0.8)
- }
- if disk > 0 {
- disk *= 1 + math.Min(float64(totalContainers-1)*0.07, 0.5)
- }
- if netIn > 0 {
- netIn *= 1 + math.Min(float64(totalContainers-1)*0.09, 0.7)
- }
- if netOut > 0 {
- netOut *= 1 + math.Min(float64(totalContainers-1)*0.08, 0.65)
- }
- }
- }
-
- return map[string]float64{
- "cpu": clampFloat(cpu, 0, 100),
- "memory": clampFloat(memory, 0, 100),
- "disk": clampFloat(disk, 0, 100),
- "netin": clampFloat(netIn, 0, math.Max(1800, netIn+50)),
- "netout": clampFloat(netOut, 0, math.Max(1700, netOut+40)),
- "diskread": 0,
- "diskwrite": 0,
- }
-}
-
// SeriesStyle controls the visual character of generated metric series.
type SeriesStyle int
@@ -555,6 +418,25 @@ func buildTieredTimestamps(now time.Time, totalDuration time.Duration) []time.Ti
return timestamps
}
+func normalizeMockMetricTimestamp(at time.Time, interval time.Duration) time.Time {
+ if interval <= 0 {
+ interval = time.Minute
+ }
+ return at.UTC().Truncate(interval)
+}
+
+func canonicalMetricSeries(resourceType, resourceID, metric string, timestamps []time.Time) []float64 {
+ if len(timestamps) == 0 || strings.TrimSpace(resourceID) == "" {
+ return nil
+ }
+
+ values := make([]float64, len(timestamps))
+ for i, ts := range timestamps {
+ values[i] = mock.SampleMetric(resourceType, resourceID, metric, ts)
+ }
+ return values
+}
+
func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.FixtureGraph, now time.Time, seedDuration, interval time.Duration) {
if mh == nil {
return
@@ -563,6 +445,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
if seedDuration <= 0 || interval <= 0 {
return
}
+ now = normalizeMockMetricTimestamp(now, interval)
// Build one canonical timestamp list so seeded history and subsequent live
// mock ticks sample the same runtime timeline model.
@@ -601,20 +484,12 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
seedBatch = seedBatch[:0]
}
}
- recordStorageTimeline := func(storageID string, currentUsed, currentTotal float64) {
+ recordStorageTimeline := func(storageID string, currentTotal float64) {
if strings.TrimSpace(storageID) == "" || currentTotal <= 0 || numPoints == 0 {
return
}
- currentUsage := clampFloat((currentUsed/currentTotal)*100, 0, 100)
- usageSeries := GenerateSeededResourceMetricSeriesForTimestamps(
- currentUsage,
- seedTimestamps,
- "storage",
- storageID,
- "usage",
- styleFlat,
- )
+ usageSeries := canonicalMetricSeries("storage", storageID, "usage", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
usage := clampFloat(usageSeries[i], 0, 100)
@@ -637,13 +512,9 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
return
}
- role := mock.MetricRole("node", node.ID)
- cpuMin, cpuMax := mock.MetricBoundsForResource("node", node.ID, "cpu")
- memMin, memMax := mock.MetricBoundsForResource("node", node.ID, "memory")
- diskMin, diskMax := mock.MetricBoundsForResource("node", node.ID, "disk")
- cpuSeries := GenerateSeededMetricSeriesForTimestampsWithRole(node.CPU*100, seedTimestamps, mock.MetricSeed("node", node.ID, "cpu"), cpuMin, cpuMax, "cpu", styleSpiky, role)
- memSeries := GenerateSeededMetricSeriesForTimestampsWithRole(node.Memory.Usage, seedTimestamps, mock.MetricSeed("node", node.ID, "memory"), memMin, memMax, "memory", stylePlateau, role)
- diskSeries := GenerateSeededMetricSeriesForTimestampsWithRole(node.Disk.Usage, seedTimestamps, mock.MetricSeed("node", node.ID, "disk"), diskMin, diskMax, "disk", styleFlat, role)
+ cpuSeries := canonicalMetricSeries("node", node.ID, "cpu", seedTimestamps)
+ memSeries := canonicalMetricSeries("node", node.ID, "memory", seedTimestamps)
+ diskSeries := canonicalMetricSeries("node", node.ID, "disk", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
@@ -659,7 +530,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
recordGuest := func(
metricIDs []string, storeType, storeID string,
- cpuPercent, memPercent, diskPercent, diskRead, diskWrite, netIn, netOut float64,
includeDisk bool,
includeDiskIO bool,
includeNetwork bool,
@@ -684,28 +554,20 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
return
}
- role := mock.MetricRole(storeType, storeID)
- cpuMin, cpuMax := mock.MetricBoundsForResource(storeType, storeID, "cpu")
- memMin, memMax := mock.MetricBoundsForResource(storeType, storeID, "memory")
- diskMin, diskMax := mock.MetricBoundsForResource(storeType, storeID, "disk")
- readMin, readMax := mock.MetricBoundsForResource(storeType, storeID, "diskread")
- writeMin, writeMax := mock.MetricBoundsForResource(storeType, storeID, "diskwrite")
- netInMin, netInMax := mock.MetricBoundsForResource(storeType, storeID, "netin")
- netOutMin, netOutMax := mock.MetricBoundsForResource(storeType, storeID, "netout")
- cpuSeries := GenerateSeededMetricSeriesForTimestampsWithRole(cpuPercent, seedTimestamps, mock.MetricSeed(storeType, storeID, "cpu"), cpuMin, cpuMax, "cpu", styleSpiky, role)
- memSeries := GenerateSeededMetricSeriesForTimestampsWithRole(memPercent, seedTimestamps, mock.MetricSeed(storeType, storeID, "memory"), memMin, memMax, "memory", stylePlateau, role)
+ cpuSeries := canonicalMetricSeries(storeType, storeID, "cpu", seedTimestamps)
+ memSeries := canonicalMetricSeries(storeType, storeID, "memory", seedTimestamps)
var diskSeries []float64
if includeDisk {
- diskSeries = GenerateSeededMetricSeriesForTimestampsWithRole(diskPercent, seedTimestamps, mock.MetricSeed(storeType, storeID, "disk"), diskMin, diskMax, "disk", styleFlat, role)
+ diskSeries = canonicalMetricSeries(storeType, storeID, "disk", seedTimestamps)
}
var diskReadSeries, diskWriteSeries, netInSeries, netOutSeries []float64
if includeDiskIO {
- diskReadSeries = GenerateSeededMetricSeriesForTimestampsWithRole(diskRead, seedTimestamps, mock.MetricSeed(storeType, storeID, "diskread"), readMin, readMax, "diskread", styleSpiky, role)
- diskWriteSeries = GenerateSeededMetricSeriesForTimestampsWithRole(diskWrite, seedTimestamps, mock.MetricSeed(storeType, storeID, "diskwrite"), writeMin, writeMax, "diskwrite", styleSpiky, role)
+ diskReadSeries = canonicalMetricSeries(storeType, storeID, "diskread", seedTimestamps)
+ diskWriteSeries = canonicalMetricSeries(storeType, storeID, "diskwrite", seedTimestamps)
}
if includeNetwork {
- netInSeries = GenerateSeededMetricSeriesForTimestampsWithRole(netIn, seedTimestamps, mock.MetricSeed(storeType, storeID, "netin"), netInMin, netInMax, "netin", styleSpiky, role)
- netOutSeries = GenerateSeededMetricSeriesForTimestampsWithRole(netOut, seedTimestamps, mock.MetricSeed(storeType, storeID, "netout"), netOutMin, netOutMax, "netout", styleSpiky, role)
+ netInSeries = canonicalMetricSeries(storeType, storeID, "netin", seedTimestamps)
+ netOutSeries = canonicalMetricSeries(storeType, storeID, "netout", seedTimestamps)
}
for i := 0; i < numPoints; i++ {
@@ -756,27 +618,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
}
log.Debug().Int("total", len(state.VMs)).Int("running", runningVMs).Msg("mock seeding: processing VMs (including stopped)")
for _, vm := range state.VMs {
- cpuPct := vm.CPU * 100
- memPct := vm.Memory.Usage
- diskPct := vm.Disk.Usage
- diskR := float64(vm.DiskRead)
- diskW := float64(vm.DiskWrite)
- netI := float64(vm.NetworkIn)
- netO := float64(vm.NetworkOut)
-
- // Stopped VMs have 0 metrics; synthesize "was running" baselines so
- // their charts show historical activity before the resource stopped.
- if vm.Status != "running" {
- h := HashSeed("vm", vm.ID, "baseline")
- cpuPct = 10 + float64(h%30) // 10-39 %
- memPct = 30 + float64((h>>8)%40) // 30-69 %
- diskPct = 15 + float64((h>>16)%35) // 15-49 %
- diskR = float64(1000 + h%5000)
- diskW = float64(500 + (h>>8)%3000)
- netI = float64(2000 + (h>>16)%8000)
- netO = float64(1000 + (h>>24)%4000)
- }
- recordGuest([]string{vm.ID}, "vm", vm.ID, cpuPct, memPct, diskPct, diskR, diskW, netI, netO, true, true, true)
+ recordGuest([]string{vm.ID}, "vm", vm.ID, true, true, true)
time.Sleep(50 * time.Millisecond) // Reduced from 200ms for faster startup
}
@@ -788,25 +630,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
}
log.Debug().Int("total", len(state.Containers)).Int("running", runningContainers).Msg("mock seeding: processing containers (including stopped)")
for _, ct := range state.Containers {
- cpuPct := ct.CPU * 100
- memPct := ct.Memory.Usage
- diskPct := ct.Disk.Usage
- diskR := float64(ct.DiskRead)
- diskW := float64(ct.DiskWrite)
- netI := float64(ct.NetworkIn)
- netO := float64(ct.NetworkOut)
-
- if ct.Status != "running" {
- h := HashSeed("container", ct.ID, "baseline")
- cpuPct = 10 + float64(h%30)
- memPct = 30 + float64((h>>8)%40)
- diskPct = 15 + float64((h>>16)%35)
- diskR = float64(1000 + h%5000)
- diskW = float64(500 + (h>>8)%3000)
- netI = float64(2000 + (h>>16)%8000)
- netO = float64(1000 + (h>>24)%4000)
- }
- recordGuest([]string{ct.ID}, "container", ct.ID, cpuPct, memPct, diskPct, diskR, diskW, netI, netO, true, true, true)
+ recordGuest([]string{ct.ID}, "container", ct.ID, true, true, true)
time.Sleep(50 * time.Millisecond) // Reduced from 200ms for faster startup
}
@@ -827,18 +651,10 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
if metricID == "" {
continue
}
- current := kubernetesPodCurrentMetrics(cluster, pod)
recordGuest(
[]string{metricID},
"k8s",
metricID,
- current["cpu"],
- current["memory"],
- current["disk"],
- current["diskread"],
- current["diskwrite"],
- current["netin"],
- current["netout"],
true,
false,
true,
@@ -852,8 +668,8 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
if storage.ID == "" {
continue
}
- _, used, total, _ := normalizedStorageCapacityMetrics(storage.Total, storage.Used, storage.Free, storage.Usage)
- recordStorageTimeline(storage.ID, used, total)
+ _, _, total, _ := normalizedStorageCapacityMetrics(storage.Total, storage.Used, storage.Free, storage.Usage)
+ recordStorageTimeline(storage.ID, total)
time.Sleep(50 * time.Millisecond) // Reduced from 200ms for faster startup
}
@@ -867,17 +683,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
continue
}
- tempMin, tempMax := mock.MetricBoundsForResource("disk", resourceID, "smart_temp")
- tempSeries := GenerateSeededMetricSeriesForTimestampsWithRole(
- float64(disk.Temperature),
- seedTimestamps,
- mock.MetricSeed("disk", resourceID, "smart_temp"),
- tempMin,
- tempMax,
- "smart_temp",
- styleFlat,
- mock.MetricRole("disk", resourceID),
- )
+ tempSeries := canonicalMetricSeries("disk", resourceID, "smart_temp", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)
@@ -899,16 +705,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
continue
}
- usageSeries := GenerateSeededMetricSeriesForTimestampsWithRole(
- cluster.UsagePercent,
- seedTimestamps,
- mock.MetricSeed("ceph", cephID, "usage"),
- 0,
- 100,
- "usage",
- styleFlat,
- mock.MetricRole("ceph", cephID),
- )
+ usageSeries := canonicalMetricSeries("ceph", cephID, "usage", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
queueMetric("ceph", cephID, "usage", usageSeries[i], ts)
@@ -922,39 +719,27 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
continue
}
- var diskPercent float64
- var usedTotal, totalTotal int64
- for _, d := range host.Disks {
- if d.Total > 0 {
- usedTotal += d.Used
- totalTotal += d.Total
- }
- }
- if totalTotal > 0 {
- diskPercent = float64(usedTotal) / float64(totalTotal) * 100
- }
-
- recordGuest([]string{"dockerHost:" + host.ID}, "dockerHost", host.ID, host.CPUUsage, host.Memory.Usage, diskPercent, 0, 0, 0, 0, true, false, false)
+ recordGuest(
+ []string{"dockerHost:" + host.ID},
+ "dockerHost",
+ host.ID,
+ true,
+ false,
+ false,
+ )
for _, container := range host.Containers {
if container.ID == "" {
continue
}
-
- cpuPct := container.CPUPercent
- memPct := container.MemoryPercent
- var diskPct float64
- if container.RootFilesystemBytes > 0 && container.WritableLayerBytes > 0 {
- diskPct = float64(container.WritableLayerBytes) / float64(container.RootFilesystemBytes) * 100
- diskPct = clampFloat(diskPct, 0, 100)
- }
- if container.State != "running" {
- h := HashSeed("dockerContainer", container.ID, "baseline")
- cpuPct = 5 + float64(h%25) // 5-29 %
- memPct = 10 + float64((h>>8)%40) // 10-49 %
- diskPct = 5 + float64((h>>16)%30)
- }
- recordGuest([]string{"docker:" + container.ID}, "dockerContainer", container.ID, cpuPct, memPct, diskPct, 0, 0, 0, 0, true, false, false)
+ recordGuest(
+ []string{"docker:" + container.ID},
+ "dockerContainer",
+ container.ID,
+ true,
+ false,
+ false,
+ )
}
time.Sleep(50 * time.Millisecond) // Add delay for docker hosts
}
@@ -965,12 +750,14 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
continue
}
- var diskPercent float64
- if len(host.Disks) > 0 {
- diskPercent = host.Disks[0].Usage
- }
-
- recordGuest([]string{"agent:" + host.ID}, "agent", host.ID, host.CPUUsage, host.Memory.Usage, diskPercent, host.DiskReadRate, host.DiskWriteRate, host.NetInRate, host.NetOutRate, true, true, true)
+ recordGuest(
+ []string{"agent:" + host.ID},
+ "agent",
+ host.ID,
+ true,
+ true,
+ true,
+ )
time.Sleep(50 * time.Millisecond)
}
@@ -979,23 +766,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
log.Debug().Int("pools", len(trueNASFixtures.Pools)).Int("datasets", len(trueNASFixtures.Datasets)).Msg("mock seeding: processing TrueNAS fixtures")
// System host: aggregated disk usage across all pools
- totalCap, totalUsed := int64(0), int64(0)
- for _, pool := range trueNASFixtures.Pools {
- totalCap += pool.TotalBytes
- totalUsed += pool.UsedBytes
- }
- systemDisk := float64(0)
- if totalCap > 0 {
- systemDisk = float64(totalUsed) / float64(totalCap) * 100
- }
- systemMemoryPercent := float64(0)
- if trueNASFixtures.System.MemoryTotalBytes > 0 {
- usedMemory := trueNASFixtures.System.MemoryTotalBytes - trueNASFixtures.System.MemoryAvailableBytes
- if usedMemory < 0 {
- usedMemory = 0
- }
- systemMemoryPercent = (float64(usedMemory) / float64(trueNASFixtures.System.MemoryTotalBytes)) * 100
- }
systemMetricIDs := []string{
"system:" + trueNASFixtures.System.Hostname,
"agent:" + trueNASFixtures.System.Hostname,
@@ -1004,13 +774,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
systemMetricIDs,
"agent",
trueNASFixtures.System.Hostname,
- trueNASFixtures.System.CPUPercent,
- systemMemoryPercent,
- systemDisk,
- trueNASFixtures.System.DiskReadRate,
- trueNASFixtures.System.DiskWriteRate,
- trueNASFixtures.System.NetInRate,
- trueNASFixtures.System.NetOutRate,
true,
true,
true,
@@ -1018,51 +781,23 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
for _, pool := range trueNASFixtures.Pools {
poolKey := "pool:" + pool.Name
- diskPercent := float64(0)
- if pool.TotalBytes > 0 {
- diskPercent = float64(pool.UsedBytes) / float64(pool.TotalBytes) * 100
- }
- diskSeries := GenerateSeededMetricSeriesForTimestampsWithRole(
- diskPercent,
- seedTimestamps,
- mock.MetricSeed("storage", poolKey, "usage"),
- 0,
- 100,
- "usage",
- styleFlat,
- mock.MetricRole("storage", poolKey),
- )
+ diskSeries := canonicalMetricSeries("storage", poolKey, "usage", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
mh.AddGuestMetric(poolKey, "disk", diskSeries[i], ts)
- queueMetric("storage", poolKey, "usage", diskSeries[i], ts)
}
- recordStorageTimeline(poolKey, float64(pool.UsedBytes), float64(pool.TotalBytes))
+ recordStorageTimeline(poolKey, float64(pool.TotalBytes))
}
for _, dataset := range trueNASFixtures.Datasets {
dsKey := "dataset:" + dataset.Name
totalBytes := dataset.UsedBytes + dataset.AvailBytes
- diskPercent := float64(0)
- if totalBytes > 0 {
- diskPercent = float64(dataset.UsedBytes) / float64(totalBytes) * 100
- }
- diskSeries := GenerateSeededMetricSeriesForTimestampsWithRole(
- diskPercent,
- seedTimestamps,
- mock.MetricSeed("storage", dsKey, "usage"),
- 0,
- 100,
- "usage",
- styleFlat,
- mock.MetricRole("storage", dsKey),
- )
+ diskSeries := canonicalMetricSeries("storage", dsKey, "usage", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
mh.AddGuestMetric(dsKey, "disk", diskSeries[i], ts)
- queueMetric("storage", dsKey, "usage", diskSeries[i], ts)
}
- recordStorageTimeline(dsKey, float64(dataset.UsedBytes), float64(totalBytes))
+ recordStorageTimeline(dsKey, float64(totalBytes))
}
for _, disk := range trueNASFixtures.Disks {
@@ -1074,17 +809,7 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
continue
}
- tempMin, tempMax := mock.MetricBoundsForResource("disk", resourceID, "smart_temp")
- tempSeries := GenerateSeededMetricSeriesForTimestampsWithRole(
- float64(disk.Temperature),
- seedTimestamps,
- mock.MetricSeed("disk", resourceID, "smart_temp"),
- tempMin,
- tempMax,
- "smart_temp",
- styleFlat,
- mock.MetricRole("disk", resourceID),
- )
+ tempSeries := canonicalMetricSeries("disk", resourceID, "smart_temp", seedTimestamps)
for i := 0; i < numPoints; i++ {
ts := seedTimestamps[i]
mh.AddDiskMetric(resourceID, "smart_temp", tempSeries[i], ts)
@@ -1093,9 +818,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
}
for _, app := range trueNASFixtures.Apps {
- if app.Stats == nil {
- continue
- }
appID := strings.TrimSpace(app.ID)
if appID == "" {
appID = strings.TrimSpace(app.Name)
@@ -1103,25 +825,10 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
if appID == "" {
continue
}
- memPercent := float64(0)
- if trueNASFixtures.System.MemoryTotalBytes > 0 {
- memPercent = (float64(app.Stats.MemoryBytes) / float64(trueNASFixtures.System.MemoryTotalBytes)) * 100
- }
- diskPercent := 8 + float64(HashSeed("truenas-app", appID, "disk")%35)
- if strings.EqualFold(strings.TrimSpace(app.State), "stopped") {
- diskPercent = clampFloat(diskPercent*0.6, 0, 100)
- }
recordGuest(
[]string{"docker:" + appID},
"dockerContainer",
appID,
- app.Stats.CPUPercent,
- memPercent,
- diskPercent,
- app.Stats.DiskReadRate,
- app.Stats.DiskWriteRate,
- app.Stats.NetInRate,
- app.Stats.NetOutRate,
true,
true,
true,
@@ -1129,7 +836,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
}
vmwareFixtures := platformFixtures.VMware
- vmwareDatastoreUsage := vmwareDatastoreUsageByID(vmwareFixtures.Datastores)
log.Debug().
Int("hosts", len(vmwareFixtures.Hosts)).
Int("vms", len(vmwareFixtures.VMs)).
@@ -1145,13 +851,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
[]string{"agent:" + sourceID},
"agent",
sourceID,
- vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }),
- vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }),
- vmwareAverageDatastoreUsage(vmwareDatastoreUsage, host.DatastoreIDs),
- vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }),
- vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }),
- vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }),
- vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }),
true,
true,
true,
@@ -1167,13 +866,6 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
[]string{sourceID},
"vm",
sourceID,
- vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }),
- vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }),
- vmwareAverageDatastoreUsage(vmwareDatastoreUsage, guest.DatastoreIDs),
- vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }),
- vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }),
- vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }),
- vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }),
true,
true,
true,
@@ -1181,21 +873,15 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
}
for _, datastore := range vmwareFixtures.Datastores {
- usage := vmwareDatastoreUsagePercent(datastore)
total := datastore.Capacity
- avail := datastore.FreeSpace
- used := total - avail
- if used < 0 {
- used = 0
- }
- if usage <= 0 && total <= 0 {
+ if total <= 0 {
continue
}
sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "datastore", datastore.Datastore)
if sourceID == "" {
continue
}
- recordStorageTimeline(sourceID, float64(used), float64(total))
+ recordStorageTimeline(sourceID, float64(total))
}
if ms != nil && len(seedBatch) > 0 {
@@ -1209,66 +895,56 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, graph mock.Fi
func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixtures mock.PlatformFixtures, ts time.Time) {
snapshot := fixtures.TrueNAS
- totalCap, totalUsed := int64(0), int64(0)
- for _, pool := range snapshot.Pools {
- totalCap += pool.TotalBytes
- totalUsed += pool.UsedBytes
- }
- if totalCap > 0 {
- systemDisk := float64(totalUsed) / float64(totalCap) * 100
+ if strings.TrimSpace(snapshot.System.Hostname) != "" {
+ systemCPU := mock.SampleMetric("agent", snapshot.System.Hostname, "cpu", ts)
+ systemMemory := mock.SampleMetric("agent", snapshot.System.Hostname, "memory", ts)
+ systemDisk := mock.SampleMetric("agent", snapshot.System.Hostname, "disk", ts)
+ systemDiskRead := mock.SampleMetric("agent", snapshot.System.Hostname, "diskread", ts)
+ systemDiskWrite := mock.SampleMetric("agent", snapshot.System.Hostname, "diskwrite", ts)
+ systemNetIn := mock.SampleMetric("agent", snapshot.System.Hostname, "netin", ts)
+ systemNetOut := mock.SampleMetric("agent", snapshot.System.Hostname, "netout", ts)
systemMetricIDs := []string{
"system:" + snapshot.System.Hostname,
"agent:" + snapshot.System.Hostname,
}
for _, metricID := range systemMetricIDs {
- mh.AddGuestMetric(metricID, "cpu", snapshot.System.CPUPercent, ts)
- if snapshot.System.MemoryTotalBytes > 0 {
- usedMemory := snapshot.System.MemoryTotalBytes - snapshot.System.MemoryAvailableBytes
- if usedMemory < 0 {
- usedMemory = 0
- }
- mh.AddGuestMetric(metricID, "memory", (float64(usedMemory)/float64(snapshot.System.MemoryTotalBytes))*100, ts)
- }
+ mh.AddGuestMetric(metricID, "cpu", systemCPU, ts)
+ mh.AddGuestMetric(metricID, "memory", systemMemory, ts)
mh.AddGuestMetric(metricID, "disk", systemDisk, ts)
- mh.AddGuestMetric(metricID, "diskread", snapshot.System.DiskReadRate, ts)
- mh.AddGuestMetric(metricID, "diskwrite", snapshot.System.DiskWriteRate, ts)
- mh.AddGuestMetric(metricID, "netin", snapshot.System.NetInRate, ts)
- mh.AddGuestMetric(metricID, "netout", snapshot.System.NetOutRate, ts)
+ mh.AddGuestMetric(metricID, "diskread", systemDiskRead, ts)
+ mh.AddGuestMetric(metricID, "diskwrite", systemDiskWrite, ts)
+ mh.AddGuestMetric(metricID, "netin", systemNetIn, ts)
+ mh.AddGuestMetric(metricID, "netout", systemNetOut, ts)
}
if ms != nil {
- var systemMemoryPercent float64
- if snapshot.System.MemoryTotalBytes > 0 {
- usedMemory := snapshot.System.MemoryTotalBytes - snapshot.System.MemoryAvailableBytes
- if usedMemory < 0 {
- usedMemory = 0
- }
- systemMemoryPercent = (float64(usedMemory) / float64(snapshot.System.MemoryTotalBytes)) * 100
- }
- ms.Write("agent", snapshot.System.Hostname, "cpu", snapshot.System.CPUPercent, ts)
- ms.Write("agent", snapshot.System.Hostname, "memory", systemMemoryPercent, ts)
+ ms.Write("agent", snapshot.System.Hostname, "cpu", systemCPU, ts)
+ ms.Write("agent", snapshot.System.Hostname, "memory", systemMemory, ts)
ms.Write("agent", snapshot.System.Hostname, "disk", systemDisk, ts)
- ms.Write("agent", snapshot.System.Hostname, "diskread", snapshot.System.DiskReadRate, ts)
- ms.Write("agent", snapshot.System.Hostname, "diskwrite", snapshot.System.DiskWriteRate, ts)
- ms.Write("agent", snapshot.System.Hostname, "netin", snapshot.System.NetInRate, ts)
- ms.Write("agent", snapshot.System.Hostname, "netout", snapshot.System.NetOutRate, ts)
+ ms.Write("agent", snapshot.System.Hostname, "diskread", systemDiskRead, ts)
+ ms.Write("agent", snapshot.System.Hostname, "diskwrite", systemDiskWrite, ts)
+ ms.Write("agent", snapshot.System.Hostname, "netin", systemNetIn, ts)
+ ms.Write("agent", snapshot.System.Hostname, "netout", systemNetOut, ts)
}
}
for _, pool := range snapshot.Pools {
if pool.TotalBytes > 0 {
poolKey := "pool:" + pool.Name
- diskPct := float64(pool.UsedBytes) / float64(pool.TotalBytes) * 100
- mh.AddGuestMetric(poolKey, "disk", diskPct, ts)
- mh.AddStorageMetric(poolKey, "usage", diskPct, ts)
- mh.AddStorageMetric(poolKey, "used", float64(pool.UsedBytes), ts)
- mh.AddStorageMetric(poolKey, "avail", float64(pool.FreeBytes), ts)
- mh.AddStorageMetric(poolKey, "total", float64(pool.TotalBytes), ts)
+ total := float64(pool.TotalBytes)
+ usage := clampFloat(mock.SampleMetric("storage", poolKey, "usage", ts), 0, 100)
+ used := total * (usage / 100.0)
+ avail := math.Max(0, total-used)
+ mh.AddGuestMetric(poolKey, "disk", usage, ts)
+ mh.AddStorageMetric(poolKey, "usage", usage, ts)
+ mh.AddStorageMetric(poolKey, "used", used, ts)
+ mh.AddStorageMetric(poolKey, "avail", avail, ts)
+ mh.AddStorageMetric(poolKey, "total", total, ts)
if ms != nil {
- ms.Write("pool", pool.Name, "disk", diskPct, ts)
- ms.Write("storage", poolKey, "usage", diskPct, ts)
- ms.Write("storage", poolKey, "used", float64(pool.UsedBytes), ts)
- ms.Write("storage", poolKey, "avail", float64(pool.FreeBytes), ts)
- ms.Write("storage", poolKey, "total", float64(pool.TotalBytes), ts)
+ ms.Write("pool", pool.Name, "disk", usage, ts)
+ ms.Write("storage", poolKey, "usage", usage, ts)
+ ms.Write("storage", poolKey, "used", used, ts)
+ ms.Write("storage", poolKey, "avail", avail, ts)
+ ms.Write("storage", poolKey, "total", total, ts)
}
}
}
@@ -1277,18 +953,21 @@ func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixture
totalBytes := dataset.UsedBytes + dataset.AvailBytes
if totalBytes > 0 {
dsKey := "dataset:" + dataset.Name
- diskPct := float64(dataset.UsedBytes) / float64(totalBytes) * 100
- mh.AddGuestMetric(dsKey, "disk", diskPct, ts)
- mh.AddStorageMetric(dsKey, "usage", diskPct, ts)
- mh.AddStorageMetric(dsKey, "used", float64(dataset.UsedBytes), ts)
- mh.AddStorageMetric(dsKey, "avail", float64(dataset.AvailBytes), ts)
- mh.AddStorageMetric(dsKey, "total", float64(totalBytes), ts)
+ total := float64(totalBytes)
+ usage := clampFloat(mock.SampleMetric("storage", dsKey, "usage", ts), 0, 100)
+ used := total * (usage / 100.0)
+ avail := math.Max(0, total-used)
+ mh.AddGuestMetric(dsKey, "disk", usage, ts)
+ mh.AddStorageMetric(dsKey, "usage", usage, ts)
+ mh.AddStorageMetric(dsKey, "used", used, ts)
+ mh.AddStorageMetric(dsKey, "avail", avail, ts)
+ mh.AddStorageMetric(dsKey, "total", total, ts)
if ms != nil {
- ms.Write("dataset", dataset.Name, "disk", diskPct, ts)
- ms.Write("storage", dsKey, "usage", diskPct, ts)
- ms.Write("storage", dsKey, "used", float64(dataset.UsedBytes), ts)
- ms.Write("storage", dsKey, "avail", float64(dataset.AvailBytes), ts)
- ms.Write("storage", dsKey, "total", float64(totalBytes), ts)
+ ms.Write("dataset", dataset.Name, "disk", usage, ts)
+ ms.Write("storage", dsKey, "usage", usage, ts)
+ ms.Write("storage", dsKey, "used", used, ts)
+ ms.Write("storage", dsKey, "avail", avail, ts)
+ ms.Write("storage", dsKey, "total", total, ts)
}
}
}
@@ -1301,17 +980,15 @@ func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixture
if resourceID == "" {
continue
}
+ temp := mock.SampleMetric("disk", resourceID, "smart_temp", ts)
- mh.AddDiskMetric(resourceID, "smart_temp", float64(disk.Temperature), ts)
+ mh.AddDiskMetric(resourceID, "smart_temp", temp, ts)
if ms != nil {
- ms.Write("disk", resourceID, "smart_temp", float64(disk.Temperature), ts)
+ ms.Write("disk", resourceID, "smart_temp", temp, ts)
}
}
for _, app := range snapshot.Apps {
- if app.Stats == nil {
- continue
- }
appID := strings.TrimSpace(app.ID)
if appID == "" {
appID = strings.TrimSpace(app.Name)
@@ -1319,58 +996,63 @@ func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixture
if appID == "" {
continue
}
- memPercent := float64(0)
- if snapshot.System.MemoryTotalBytes > 0 {
- memPercent = (float64(app.Stats.MemoryBytes) / float64(snapshot.System.MemoryTotalBytes)) * 100
- }
- diskPercent := 8 + float64(HashSeed("truenas-app", appID, "disk")%35)
- if strings.EqualFold(strings.TrimSpace(app.State), "stopped") {
- diskPercent = clampFloat(diskPercent*0.6, 0, 100)
- }
+ cpu := mock.SampleMetric("dockerContainer", appID, "cpu", ts)
+ memPercent := mock.SampleMetric("dockerContainer", appID, "memory", ts)
+ diskPercent := mock.SampleMetric("dockerContainer", appID, "disk", ts)
+ diskRead := mock.SampleMetric("dockerContainer", appID, "diskread", ts)
+ diskWrite := mock.SampleMetric("dockerContainer", appID, "diskwrite", ts)
+ netIn := mock.SampleMetric("dockerContainer", appID, "netin", ts)
+ netOut := mock.SampleMetric("dockerContainer", appID, "netout", ts)
metricKey := "docker:" + appID
- mh.AddGuestMetric(metricKey, "cpu", app.Stats.CPUPercent, ts)
+ mh.AddGuestMetric(metricKey, "cpu", cpu, ts)
mh.AddGuestMetric(metricKey, "memory", memPercent, ts)
mh.AddGuestMetric(metricKey, "disk", diskPercent, ts)
- mh.AddGuestMetric(metricKey, "diskread", app.Stats.DiskReadRate, ts)
- mh.AddGuestMetric(metricKey, "diskwrite", app.Stats.DiskWriteRate, ts)
- mh.AddGuestMetric(metricKey, "netin", app.Stats.NetInRate, ts)
- mh.AddGuestMetric(metricKey, "netout", app.Stats.NetOutRate, ts)
+ mh.AddGuestMetric(metricKey, "diskread", diskRead, ts)
+ mh.AddGuestMetric(metricKey, "diskwrite", diskWrite, ts)
+ mh.AddGuestMetric(metricKey, "netin", netIn, ts)
+ mh.AddGuestMetric(metricKey, "netout", netOut, ts)
if ms != nil {
- ms.Write("dockerContainer", appID, "cpu", app.Stats.CPUPercent, ts)
+ ms.Write("dockerContainer", appID, "cpu", cpu, ts)
ms.Write("dockerContainer", appID, "memory", memPercent, ts)
ms.Write("dockerContainer", appID, "disk", diskPercent, ts)
- ms.Write("dockerContainer", appID, "diskread", app.Stats.DiskReadRate, ts)
- ms.Write("dockerContainer", appID, "diskwrite", app.Stats.DiskWriteRate, ts)
- ms.Write("dockerContainer", appID, "netin", app.Stats.NetInRate, ts)
- ms.Write("dockerContainer", appID, "netout", app.Stats.NetOutRate, ts)
+ ms.Write("dockerContainer", appID, "diskread", diskRead, ts)
+ ms.Write("dockerContainer", appID, "diskwrite", diskWrite, ts)
+ ms.Write("dockerContainer", appID, "netin", netIn, ts)
+ ms.Write("dockerContainer", appID, "netout", netOut, ts)
}
}
}
func recordVMwareFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixtures mock.PlatformFixtures, ts time.Time) {
snapshot := fixtures.VMware
- datastoreUsage := vmwareDatastoreUsageByID(snapshot.Datastores)
for _, host := range snapshot.Hosts {
sourceID := vmware.SourceID(snapshot.ConnectionID, "host", host.Host)
if sourceID == "" {
continue
}
- mh.AddGuestMetric("agent:"+sourceID, "cpu", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)
- mh.AddGuestMetric("agent:"+sourceID, "memory", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)
- mh.AddGuestMetric("agent:"+sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, host.DatastoreIDs), ts)
- mh.AddGuestMetric("agent:"+sourceID, "diskread", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)
- mh.AddGuestMetric("agent:"+sourceID, "diskwrite", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)
- mh.AddGuestMetric("agent:"+sourceID, "netin", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)
- mh.AddGuestMetric("agent:"+sourceID, "netout", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)
+ cpu := mock.SampleMetric("agent", sourceID, "cpu", ts)
+ memory := mock.SampleMetric("agent", sourceID, "memory", ts)
+ disk := mock.SampleMetric("agent", sourceID, "disk", ts)
+ diskRead := mock.SampleMetric("agent", sourceID, "diskread", ts)
+ diskWrite := mock.SampleMetric("agent", sourceID, "diskwrite", ts)
+ netIn := mock.SampleMetric("agent", sourceID, "netin", ts)
+ netOut := mock.SampleMetric("agent", sourceID, "netout", ts)
+ mh.AddGuestMetric("agent:"+sourceID, "cpu", cpu, ts)
+ mh.AddGuestMetric("agent:"+sourceID, "memory", memory, ts)
+ mh.AddGuestMetric("agent:"+sourceID, "disk", disk, ts)
+ mh.AddGuestMetric("agent:"+sourceID, "diskread", diskRead, ts)
+ mh.AddGuestMetric("agent:"+sourceID, "diskwrite", diskWrite, ts)
+ mh.AddGuestMetric("agent:"+sourceID, "netin", netIn, ts)
+ mh.AddGuestMetric("agent:"+sourceID, "netout", netOut, ts)
if ms != nil {
- ms.Write("agent", sourceID, "cpu", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)
- ms.Write("agent", sourceID, "memory", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)
- ms.Write("agent", sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, host.DatastoreIDs), ts)
- ms.Write("agent", sourceID, "diskread", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)
- ms.Write("agent", sourceID, "diskwrite", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)
- ms.Write("agent", sourceID, "netin", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)
- ms.Write("agent", sourceID, "netout", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)
+ ms.Write("agent", sourceID, "cpu", cpu, ts)
+ ms.Write("agent", sourceID, "memory", memory, ts)
+ ms.Write("agent", sourceID, "disk", disk, ts)
+ ms.Write("agent", sourceID, "diskread", diskRead, ts)
+ ms.Write("agent", sourceID, "diskwrite", diskWrite, ts)
+ ms.Write("agent", sourceID, "netin", netIn, ts)
+ ms.Write("agent", sourceID, "netout", netOut, ts)
}
}
@@ -1379,21 +1061,28 @@ func recordVMwareFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixtures
if sourceID == "" {
continue
}
- mh.AddGuestMetric(sourceID, "cpu", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)
- mh.AddGuestMetric(sourceID, "memory", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)
- mh.AddGuestMetric(sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, guest.DatastoreIDs), ts)
- mh.AddGuestMetric(sourceID, "diskread", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)
- mh.AddGuestMetric(sourceID, "diskwrite", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)
- mh.AddGuestMetric(sourceID, "netin", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)
- mh.AddGuestMetric(sourceID, "netout", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)
+ cpu := mock.SampleMetric("vm", sourceID, "cpu", ts)
+ memory := mock.SampleMetric("vm", sourceID, "memory", ts)
+ disk := mock.SampleMetric("vm", sourceID, "disk", ts)
+ diskRead := mock.SampleMetric("vm", sourceID, "diskread", ts)
+ diskWrite := mock.SampleMetric("vm", sourceID, "diskwrite", ts)
+ netIn := mock.SampleMetric("vm", sourceID, "netin", ts)
+ netOut := mock.SampleMetric("vm", sourceID, "netout", ts)
+ mh.AddGuestMetric(sourceID, "cpu", cpu, ts)
+ mh.AddGuestMetric(sourceID, "memory", memory, ts)
+ mh.AddGuestMetric(sourceID, "disk", disk, ts)
+ mh.AddGuestMetric(sourceID, "diskread", diskRead, ts)
+ mh.AddGuestMetric(sourceID, "diskwrite", diskWrite, ts)
+ mh.AddGuestMetric(sourceID, "netin", netIn, ts)
+ mh.AddGuestMetric(sourceID, "netout", netOut, ts)
if ms != nil {
- ms.Write("vm", sourceID, "cpu", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)
- ms.Write("vm", sourceID, "memory", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)
- ms.Write("vm", sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, guest.DatastoreIDs), ts)
- ms.Write("vm", sourceID, "diskread", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)
- ms.Write("vm", sourceID, "diskwrite", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)
- ms.Write("vm", sourceID, "netin", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)
- ms.Write("vm", sourceID, "netout", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)
+ ms.Write("vm", sourceID, "cpu", cpu, ts)
+ ms.Write("vm", sourceID, "memory", memory, ts)
+ ms.Write("vm", sourceID, "disk", disk, ts)
+ ms.Write("vm", sourceID, "diskread", diskRead, ts)
+ ms.Write("vm", sourceID, "diskwrite", diskWrite, ts)
+ ms.Write("vm", sourceID, "netin", netIn, ts)
+ ms.Write("vm", sourceID, "netout", netOut, ts)
}
}
@@ -1402,12 +1091,15 @@ func recordVMwareFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, fixtures
if sourceID == "" {
continue
}
- usage := vmwareDatastoreUsagePercent(datastore)
+ usage := clampFloat(mock.SampleMetric("storage", sourceID, "usage", ts), 0, 100)
total := datastore.Capacity
- avail := datastore.FreeSpace
- used := total - avail
- if used < 0 {
- used = 0
+ used := int64(float64(total) * (usage / 100.0))
+ if used > total {
+ used = total
+ }
+ avail := total - used
+ if avail < 0 {
+ avail = 0
}
mh.AddStorageMetric(sourceID, "usage", usage, ts)
mh.AddStorageMetric(sourceID, "used", float64(used), ts)
@@ -1479,38 +1171,17 @@ func vmwareDatastoreUsagePercent(datastore vmware.InventoryDatastore) float64 {
type guestMetricSource interface {
GetID() string
GetStatus() string
- GetCPU() float64
- GetMemory() models.Memory
- GetDisk() models.Disk
- GetDiskRead() int64
- GetDiskWrite() int64
- GetNetworkIn() int64
- GetNetworkOut() int64
}
type vmAdapter struct{ *models.VM }
-func (v vmAdapter) GetID() string { return v.VM.ID }
-func (v vmAdapter) GetStatus() string { return v.VM.Status }
-func (v vmAdapter) GetCPU() float64 { return v.VM.CPU }
-func (v vmAdapter) GetMemory() models.Memory { return v.VM.Memory }
-func (v vmAdapter) GetDisk() models.Disk { return v.VM.Disk }
-func (v vmAdapter) GetDiskRead() int64 { return v.VM.DiskRead }
-func (v vmAdapter) GetDiskWrite() int64 { return v.VM.DiskWrite }
-func (v vmAdapter) GetNetworkIn() int64 { return v.VM.NetworkIn }
-func (v vmAdapter) GetNetworkOut() int64 { return v.VM.NetworkOut }
+func (v vmAdapter) GetID() string { return v.VM.ID }
+func (v vmAdapter) GetStatus() string { return v.VM.Status }
type containerAdapter struct{ *models.Container }
-func (c containerAdapter) GetID() string { return c.Container.ID }
-func (c containerAdapter) GetStatus() string { return c.Container.Status }
-func (c containerAdapter) GetCPU() float64 { return c.Container.CPU }
-func (c containerAdapter) GetMemory() models.Memory { return c.Container.Memory }
-func (c containerAdapter) GetDisk() models.Disk { return c.Container.Disk }
-func (c containerAdapter) GetDiskRead() int64 { return c.Container.DiskRead }
-func (c containerAdapter) GetDiskWrite() int64 { return c.Container.DiskWrite }
-func (c containerAdapter) GetNetworkIn() int64 { return c.Container.NetworkIn }
-func (c containerAdapter) GetNetworkOut() int64 { return c.Container.NetworkOut }
+func (c containerAdapter) GetID() string { return c.Container.ID }
+func (c containerAdapter) GetStatus() string { return c.Container.Status }
func recordGuestMetrics[T guestMetricSource](mh *MetricsHistory, ms *metrics.Store, guests []T, prefix string, ts time.Time) {
for _, guest := range guests {
@@ -1519,13 +1190,13 @@ func recordGuestMetrics[T guestMetricSource](mh *MetricsHistory, ms *metrics.Sto
}
id := guest.GetID()
- cpu := guest.GetCPU() * 100
- memory := guest.GetMemory().Usage
- disk := guest.GetDisk().Usage
- diskread := float64(guest.GetDiskRead())
- diskwrite := float64(guest.GetDiskWrite())
- netin := float64(guest.GetNetworkIn())
- netout := float64(guest.GetNetworkOut())
+ cpu := mock.SampleMetric(prefix, id, "cpu", ts)
+ memory := mock.SampleMetric(prefix, id, "memory", ts)
+ disk := mock.SampleMetric(prefix, id, "disk", ts)
+ diskread := mock.SampleMetric(prefix, id, "diskread", ts)
+ diskwrite := mock.SampleMetric(prefix, id, "diskwrite", ts)
+ netin := mock.SampleMetric(prefix, id, "netin", ts)
+ netout := mock.SampleMetric(prefix, id, "netout", ts)
mh.AddGuestMetric(id, "cpu", cpu, ts)
mh.AddGuestMetric(id, "memory", memory, ts)
@@ -1574,14 +1245,17 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
continue
}
- mh.AddNodeMetric(node.ID, "cpu", node.CPU*100, ts)
- mh.AddNodeMetric(node.ID, "memory", node.Memory.Usage, ts)
- mh.AddNodeMetric(node.ID, "disk", node.Disk.Usage, ts)
+ cpu := mock.SampleMetric("node", node.ID, "cpu", ts)
+ memory := mock.SampleMetric("node", node.ID, "memory", ts)
+ disk := mock.SampleMetric("node", node.ID, "disk", ts)
+ mh.AddNodeMetric(node.ID, "cpu", cpu, ts)
+ mh.AddNodeMetric(node.ID, "memory", memory, ts)
+ mh.AddNodeMetric(node.ID, "disk", disk, ts)
if ms != nil {
- ms.Write("node", node.ID, "cpu", node.CPU*100, ts)
- ms.Write("node", node.ID, "memory", node.Memory.Usage, ts)
- ms.Write("node", node.ID, "disk", node.Disk.Usage, ts)
+ ms.Write("node", node.ID, "cpu", cpu, ts)
+ ms.Write("node", node.ID, "memory", memory, ts)
+ ms.Write("node", node.ID, "disk", disk, ts)
}
}
@@ -1597,43 +1271,24 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
if metricID == "" {
continue
}
- current := kubernetesPodCurrentMetrics(cluster, pod)
- mh.AddGuestMetric(metricID, "cpu", current["cpu"], ts)
- mh.AddGuestMetric(metricID, "memory", current["memory"], ts)
- if current["disk"] > 0 {
- mh.AddGuestMetric(metricID, "disk", current["disk"], ts)
- }
- if current["diskread"] > 0 {
- mh.AddGuestMetric(metricID, "diskread", current["diskread"], ts)
- }
- if current["diskwrite"] > 0 {
- mh.AddGuestMetric(metricID, "diskwrite", current["diskwrite"], ts)
- }
- if current["netin"] > 0 {
- mh.AddGuestMetric(metricID, "netin", current["netin"], ts)
- }
- if current["netout"] > 0 {
- mh.AddGuestMetric(metricID, "netout", current["netout"], ts)
- }
+ cpu := mock.SampleMetric("k8s", metricID, "cpu", ts)
+ memory := mock.SampleMetric("k8s", metricID, "memory", ts)
+ disk := mock.SampleMetric("k8s", metricID, "disk", ts)
+ netIn := mock.SampleMetric("k8s", metricID, "netin", ts)
+ netOut := mock.SampleMetric("k8s", metricID, "netout", ts)
+
+ mh.AddGuestMetric(metricID, "cpu", cpu, ts)
+ mh.AddGuestMetric(metricID, "memory", memory, ts)
+ mh.AddGuestMetric(metricID, "disk", disk, ts)
+ mh.AddGuestMetric(metricID, "netin", netIn, ts)
+ mh.AddGuestMetric(metricID, "netout", netOut, ts)
if ms != nil {
- ms.Write("k8s", metricID, "cpu", current["cpu"], ts)
- ms.Write("k8s", metricID, "memory", current["memory"], ts)
- if current["disk"] > 0 {
- ms.Write("k8s", metricID, "disk", current["disk"], ts)
- }
- if current["diskread"] > 0 {
- ms.Write("k8s", metricID, "diskread", current["diskread"], ts)
- }
- if current["diskwrite"] > 0 {
- ms.Write("k8s", metricID, "diskwrite", current["diskwrite"], ts)
- }
- if current["netin"] > 0 {
- ms.Write("k8s", metricID, "netin", current["netin"], ts)
- }
- if current["netout"] > 0 {
- ms.Write("k8s", metricID, "netout", current["netout"], ts)
- }
+ ms.Write("k8s", metricID, "cpu", cpu, ts)
+ ms.Write("k8s", metricID, "memory", memory, ts)
+ ms.Write("k8s", metricID, "disk", disk, ts)
+ ms.Write("k8s", metricID, "netin", netIn, ts)
+ ms.Write("k8s", metricID, "netout", netOut, ts)
}
}
}
@@ -1642,7 +1297,21 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
if storage.ID == "" || storage.Status != "available" {
continue
}
- usage, used, total, avail := normalizedStorageCapacityMetrics(storage.Total, storage.Used, storage.Free, storage.Usage)
+ _, currentUsed, currentTotal, currentAvail := normalizedStorageCapacityMetrics(storage.Total, storage.Used, storage.Free, storage.Usage)
+ total := currentTotal
+ if total <= 0 {
+ total = currentUsed + currentAvail
+ }
+ usage := mock.SampleMetric("storage", storage.ID, "usage", ts)
+ usage = clampFloat(usage, 0, 100)
+ used := total * (usage / 100.0)
+ if used < 0 {
+ used = 0
+ }
+ if total > 0 && used > total {
+ used = total
+ }
+ avail := math.Max(0, total-used)
mh.AddStorageMetric(storage.ID, "usage", usage, ts)
mh.AddStorageMetric(storage.ID, "used", used, ts)
mh.AddStorageMetric(storage.ID, "total", total, ts)
@@ -1664,10 +1333,11 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
if resourceID == "" {
continue
}
+ temp := mock.SampleMetric("disk", resourceID, "smart_temp", ts)
- mh.AddDiskMetric(resourceID, "smart_temp", float64(disk.Temperature), ts)
+ mh.AddDiskMetric(resourceID, "smart_temp", temp, ts)
if ms != nil {
- ms.Write("disk", resourceID, "smart_temp", float64(disk.Temperature), ts)
+ ms.Write("disk", resourceID, "smart_temp", temp, ts)
}
}
@@ -1693,27 +1363,18 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
continue
}
- var diskPercent float64
- var usedTotal, totalTotal int64
- for _, d := range host.Disks {
- if d.Total > 0 {
- usedTotal += d.Used
- totalTotal += d.Total
- }
- }
- if totalTotal > 0 {
- diskPercent = float64(usedTotal) / float64(totalTotal) * 100
- }
-
hostKey := "dockerHost:" + host.ID
- mh.AddGuestMetric(hostKey, "cpu", host.CPUUsage, ts)
- mh.AddGuestMetric(hostKey, "memory", host.Memory.Usage, ts)
- mh.AddGuestMetric(hostKey, "disk", diskPercent, ts)
+ cpu := mock.SampleMetric("dockerHost", host.ID, "cpu", ts)
+ memory := mock.SampleMetric("dockerHost", host.ID, "memory", ts)
+ disk := mock.SampleMetric("dockerHost", host.ID, "disk", ts)
+ mh.AddGuestMetric(hostKey, "cpu", cpu, ts)
+ mh.AddGuestMetric(hostKey, "memory", memory, ts)
+ mh.AddGuestMetric(hostKey, "disk", disk, ts)
if ms != nil {
- ms.Write("dockerHost", host.ID, "cpu", host.CPUUsage, ts)
- ms.Write("dockerHost", host.ID, "memory", host.Memory.Usage, ts)
- ms.Write("dockerHost", host.ID, "disk", diskPercent, ts)
+ ms.Write("dockerHost", host.ID, "cpu", cpu, ts)
+ ms.Write("dockerHost", host.ID, "memory", memory, ts)
+ ms.Write("dockerHost", host.ID, "disk", disk, ts)
}
for _, container := range host.Containers {
@@ -1721,21 +1382,18 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
continue
}
- var containerDisk float64
- if container.RootFilesystemBytes > 0 && container.WritableLayerBytes > 0 {
- containerDisk = float64(container.WritableLayerBytes) / float64(container.RootFilesystemBytes) * 100
- containerDisk = clampFloat(containerDisk, 0, 100)
- }
-
metricKey := "docker:" + container.ID
- mh.AddGuestMetric(metricKey, "cpu", container.CPUPercent, ts)
- mh.AddGuestMetric(metricKey, "memory", container.MemoryPercent, ts)
- mh.AddGuestMetric(metricKey, "disk", containerDisk, ts)
+ cpu := mock.SampleMetric("dockerContainer", container.ID, "cpu", ts)
+ memory := mock.SampleMetric("dockerContainer", container.ID, "memory", ts)
+ disk := mock.SampleMetric("dockerContainer", container.ID, "disk", ts)
+ mh.AddGuestMetric(metricKey, "cpu", cpu, ts)
+ mh.AddGuestMetric(metricKey, "memory", memory, ts)
+ mh.AddGuestMetric(metricKey, "disk", disk, ts)
if ms != nil {
- ms.Write("dockerContainer", container.ID, "cpu", container.CPUPercent, ts)
- ms.Write("dockerContainer", container.ID, "memory", container.MemoryPercent, ts)
- ms.Write("dockerContainer", container.ID, "disk", containerDisk, ts)
+ ms.Write("dockerContainer", container.ID, "cpu", cpu, ts)
+ ms.Write("dockerContainer", container.ID, "memory", memory, ts)
+ ms.Write("dockerContainer", container.ID, "disk", disk, ts)
}
}
}
@@ -1745,28 +1403,30 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, grap
continue
}
- var diskPercent float64
- if len(host.Disks) > 0 {
- diskPercent = host.Disks[0].Usage
- }
-
hostKey := "agent:" + host.ID
- mh.AddGuestMetric(hostKey, "cpu", host.CPUUsage, ts)
- mh.AddGuestMetric(hostKey, "memory", host.Memory.Usage, ts)
- mh.AddGuestMetric(hostKey, "disk", diskPercent, ts)
- mh.AddGuestMetric(hostKey, "diskread", host.DiskReadRate, ts)
- mh.AddGuestMetric(hostKey, "diskwrite", host.DiskWriteRate, ts)
- mh.AddGuestMetric(hostKey, "netin", host.NetInRate, ts)
- mh.AddGuestMetric(hostKey, "netout", host.NetOutRate, ts)
+ cpu := mock.SampleMetric("agent", host.ID, "cpu", ts)
+ memory := mock.SampleMetric("agent", host.ID, "memory", ts)
+ disk := mock.SampleMetric("agent", host.ID, "disk", ts)
+ diskread := mock.SampleMetric("agent", host.ID, "diskread", ts)
+ diskwrite := mock.SampleMetric("agent", host.ID, "diskwrite", ts)
+ netin := mock.SampleMetric("agent", host.ID, "netin", ts)
+ netout := mock.SampleMetric("agent", host.ID, "netout", ts)
+ mh.AddGuestMetric(hostKey, "cpu", cpu, ts)
+ mh.AddGuestMetric(hostKey, "memory", memory, ts)
+ mh.AddGuestMetric(hostKey, "disk", disk, ts)
+ mh.AddGuestMetric(hostKey, "diskread", diskread, ts)
+ mh.AddGuestMetric(hostKey, "diskwrite", diskwrite, ts)
+ mh.AddGuestMetric(hostKey, "netin", netin, ts)
+ mh.AddGuestMetric(hostKey, "netout", netout, ts)
if ms != nil {
- ms.Write("agent", host.ID, "cpu", host.CPUUsage, ts)
- ms.Write("agent", host.ID, "memory", host.Memory.Usage, ts)
- ms.Write("agent", host.ID, "disk", diskPercent, ts)
- ms.Write("agent", host.ID, "diskread", host.DiskReadRate, ts)
- ms.Write("agent", host.ID, "diskwrite", host.DiskWriteRate, ts)
- ms.Write("agent", host.ID, "netin", host.NetInRate, ts)
- ms.Write("agent", host.ID, "netout", host.NetOutRate, ts)
+ ms.Write("agent", host.ID, "cpu", cpu, ts)
+ ms.Write("agent", host.ID, "memory", memory, ts)
+ ms.Write("agent", host.ID, "disk", disk, ts)
+ ms.Write("agent", host.ID, "diskread", diskread, ts)
+ ms.Write("agent", host.ID, "diskwrite", diskwrite, ts)
+ ms.Write("agent", host.ID, "netin", netin, ts)
+ ms.Write("agent", host.ID, "netout", netout, ts)
}
}
@@ -1871,7 +1531,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {
Msg("Mock metrics sampler: seeding historical data")
// Keep mock trend generation in-memory only so production history in the
// persistent metrics store remains untouched while mock mode is active.
- seedMockMetricsHistory(m.metricsHistory, nil, graph, time.Now(), seedDuration, cfg.SampleInterval)
+ seedMockMetricsHistory(m.metricsHistory, nil, graph, normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval), seedDuration, cfg.SampleInterval)
m.mockMetricsWg.Add(1)
go func() {
@@ -1888,7 +1548,7 @@ func (m *Monitor) startMockMetricsSampler(ctx context.Context) {
if !mock.IsMockEnabled() {
continue
}
- recordMockStateToMetricsHistory(m.metricsHistory, nil, mock.CurrentFixtureGraph(), time.Now())
+ recordMockStateToMetricsHistory(m.metricsHistory, nil, mock.CurrentFixtureGraph(), normalizeMockMetricTimestamp(time.Now(), cfg.SampleInterval))
}
}
}()
diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.go
index bd88093d70..d990daa58a 100644
--- a/internal/monitoring/mock_metrics_history_test.go
+++ b/internal/monitoring/mock_metrics_history_test.go
@@ -34,6 +34,7 @@ func TestBuildTieredTimestamps_IncludesCanonicalTerminalNow(t *testing.T) {
}
func TestSeedMockMetricsHistory_PopulatesSeries(t *testing.T) {
+ const interval = 30 * time.Second
now := time.Now()
state := models.StateSnapshot{
@@ -106,30 +107,30 @@ func TestSeedMockMetricsHistory_PopulatesSeries(t *testing.T) {
}
mh := NewMetricsHistory(1000, 24*time.Hour)
- seedMockMetricsHistory(mh, nil, fixtureGraphWithState(state), now, time.Hour, 30*time.Second)
+ seedMockMetricsHistory(mh, nil, fixtureGraphWithState(state), now, time.Hour, interval)
nodeCPU := mh.GetNodeMetrics("node-1", "cpu", time.Hour)
if len(nodeCPU) < 10 {
t.Fatalf("expected seeded node cpu points, got %d", len(nodeCPU))
}
- if got, want := nodeCPU[len(nodeCPU)-1].Value, state.Nodes[0].CPU*100; math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last node cpu point to match current, got=%v want=%v", got, want)
+ if got, want := nodeCPU[len(nodeCPU)-1].Value, mock.SampleMetric("node", "node-1", "cpu", nodeCPU[len(nodeCPU)-1].Timestamp); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last node cpu point to match canonical sampler, got=%v want=%v", got, want)
}
vmCPU := mh.GetGuestMetrics("vm-100", "cpu", time.Hour)
if len(vmCPU) < 10 {
t.Fatalf("expected seeded vm cpu points, got %d", len(vmCPU))
}
- if got, want := vmCPU[len(vmCPU)-1].Value, state.VMs[0].CPU*100; math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last vm cpu point to match current, got=%v want=%v", got, want)
+ if got, want := vmCPU[len(vmCPU)-1].Value, mock.SampleMetric("vm", "vm-100", "cpu", vmCPU[len(vmCPU)-1].Timestamp); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last vm cpu point to match canonical sampler, got=%v want=%v", got, want)
}
dockerCPU := mh.GetGuestMetrics("docker:cont-1", "cpu", time.Hour)
if len(dockerCPU) < 10 {
t.Fatalf("expected seeded docker container cpu points, got %d", len(dockerCPU))
}
- if got, want := dockerCPU[len(dockerCPU)-1].Value, state.DockerHosts[0].Containers[0].CPUPercent; math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last docker cpu point to match current, got=%v want=%v", got, want)
+ if got, want := dockerCPU[len(dockerCPU)-1].Value, mock.SampleMetric("dockerContainer", "cont-1", "cpu", dockerCPU[len(dockerCPU)-1].Timestamp); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last docker cpu point to match canonical sampler, got=%v want=%v", got, want)
}
storageMetrics := mh.GetAllStorageMetrics("local", time.Hour)
@@ -137,11 +138,14 @@ func TestSeedMockMetricsHistory_PopulatesSeries(t *testing.T) {
t.Fatalf("expected seeded storage capacity history, got usage=%d used=%d avail=%d", len(storageMetrics["usage"]), len(storageMetrics["used"]), len(storageMetrics["avail"]))
}
last := len(storageMetrics["usage"]) - 1
- if got, want := storageMetrics["used"][last].Value, float64(state.Storage[0].Used); math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last storage used point to match current, got=%v want=%v", got, want)
+ storageUsageNow := mock.SampleMetric("storage", "local", "usage", storageMetrics["usage"][last].Timestamp)
+ storageUsedNow := float64(state.Storage[0].Total) * (storageUsageNow / 100.0)
+ storageAvailNow := float64(state.Storage[0].Total) - storageUsedNow
+ if got, want := storageMetrics["used"][last].Value, storageUsedNow; math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last storage used point to match canonical sampler, got=%v want=%v", got, want)
}
- if got, want := storageMetrics["avail"][last].Value, float64(state.Storage[0].Free); math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last storage avail point to match current, got=%v want=%v", got, want)
+ if got, want := storageMetrics["avail"][last].Value, storageAvailNow; math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last storage avail point to match canonical sampler, got=%v want=%v", got, want)
}
for i := range storageMetrics["usage"] {
if diff := math.Abs(storageMetrics["used"][i].Value + storageMetrics["avail"][i].Value - float64(state.Storage[0].Total)); diff > 0.001 {
@@ -153,13 +157,15 @@ func TestSeedMockMetricsHistory_PopulatesSeries(t *testing.T) {
if len(diskTemps) < 10 {
t.Fatalf("expected seeded disk temperature history, got %d points", len(diskTemps))
}
- if got, want := diskTemps[len(diskTemps)-1].Value, float64(state.PhysicalDisks[0].Temperature); math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last disk temp point to match current, got=%v want=%v", got, want)
+ if got, want := diskTemps[len(diskTemps)-1].Value, mock.SampleMetric("disk", "SERIAL-LOCAL-1", "smart_temp", diskTemps[len(diskTemps)-1].Timestamp); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last disk temp point to match canonical sampler, got=%v want=%v", got, want)
}
}
func TestSeedMockMetricsHistory_AppendsSingleTerminalNowPoint(t *testing.T) {
+ const interval = 30 * time.Second
now := time.Now().UTC().Truncate(time.Second)
+ alignedNow := normalizeMockMetricTimestamp(now, interval)
state := models.StateSnapshot{
DockerHosts: []models.DockerHost{
@@ -186,7 +192,7 @@ func TestSeedMockMetricsHistory_AppendsSingleTerminalNowPoint(t *testing.T) {
}
mh := NewMetricsHistory(1000, 24*time.Hour)
- seedMockMetricsHistory(mh, nil, fixtureGraphWithState(state), now, time.Hour, 30*time.Second)
+ seedMockMetricsHistory(mh, nil, fixtureGraphWithState(state), now, time.Hour, interval)
memorySeries := mh.GetGuestMetrics("docker:cont-1", "memory", time.Hour)
if len(memorySeries) < 2 {
@@ -194,13 +200,13 @@ func TestSeedMockMetricsHistory_AppendsSingleTerminalNowPoint(t *testing.T) {
}
last := memorySeries[len(memorySeries)-1]
- if !last.Timestamp.Equal(now) {
- t.Fatalf("expected terminal docker memory timestamp %v, got %v", now, last.Timestamp)
+ if !last.Timestamp.Equal(alignedNow) {
+ t.Fatalf("expected terminal docker memory timestamp %v, got %v", alignedNow, last.Timestamp)
}
nowCount := 0
for _, point := range memorySeries {
- if point.Timestamp.Equal(now) {
+ if point.Timestamp.Equal(alignedNow) {
nowCount++
}
}
@@ -210,6 +216,7 @@ func TestSeedMockMetricsHistory_AppendsSingleTerminalNowPoint(t *testing.T) {
}
func TestSeedMockMetricsHistory_PopulatesKubernetesPodSeries(t *testing.T) {
+ const interval = 30 * time.Second
now := time.Now()
state := models.StateSnapshot{
@@ -234,7 +241,7 @@ func TestSeedMockMetricsHistory_PopulatesKubernetesPodSeries(t *testing.T) {
}
mh := NewMetricsHistory(1000, 24*time.Hour)
- seedMockMetricsHistory(mh, nil, fixtureGraphWithState(state), now, time.Hour, 30*time.Second)
+ seedMockMetricsHistory(mh, nil, fixtureGraphWithState(state), now, time.Hour, interval)
metricID := kubernetesPodMetricID(state.KubernetesClusters[0], state.KubernetesClusters[0].Pods[0])
if metricID == "" {
@@ -246,9 +253,8 @@ func TestSeedMockMetricsHistory_PopulatesKubernetesPodSeries(t *testing.T) {
t.Fatalf("expected seeded kubernetes cpu points, got %d", len(cpuSeries))
}
- current := kubernetesPodCurrentMetrics(state.KubernetesClusters[0], state.KubernetesClusters[0].Pods[0])
- if got, want := cpuSeries[len(cpuSeries)-1].Value, current["cpu"]; math.Abs(got-want) > 1e-9 {
- t.Fatalf("expected last kubernetes cpu point to match current, got=%v want=%v", got, want)
+ if got, want := cpuSeries[len(cpuSeries)-1].Value, mock.SampleMetric("k8s", metricID, "cpu", cpuSeries[len(cpuSeries)-1].Timestamp); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected last kubernetes cpu point to match canonical sampler, got=%v want=%v", got, want)
}
}
@@ -419,6 +425,9 @@ func TestSeedMockMetricsHistory_SeedsVMwareMetricsStore(t *testing.T) {
if len(storagePoints) == 0 {
t.Fatal("expected metrics store to have seeded VMware datastore usage points")
}
+ if got, want := storagePoints[len(storagePoints)-1].Value, mock.SampleMetric("storage", "vc-mock-1:datastore:datastore-201", "usage", now); math.Abs(got-want) > 0.1 {
+ t.Fatalf("expected VMware datastore usage seed to match canonical sampler, got=%v want=%v", got, want)
+ }
storageUsedPoints, err := store.Query("storage", "vc-mock-1:datastore:datastore-201", "used", now.Add(-7*24*time.Hour), now, 3600)
if err != nil {
@@ -485,6 +494,9 @@ func TestSeedMockMetricsHistory_SeedsTrueNASMetricsStore(t *testing.T) {
if len(datasetPoints) == 0 {
t.Fatal("expected metrics store to have seeded canonical TrueNAS dataset usage points")
}
+ if got, want := datasetPoints[len(datasetPoints)-1].Value, mock.SampleMetric("storage", "dataset:"+fixtures.Datasets[0].Name, "usage", now); math.Abs(got-want) > 0.1 {
+ t.Fatalf("expected TrueNAS dataset usage seed to match canonical sampler, got=%v want=%v", got, want)
+ }
poolUsedPoints, err := store.Query("storage", "pool:"+fixtures.Pools[0].Name, "used", now.Add(-7*24*time.Hour), now, 3600)
if err != nil {
@@ -930,6 +942,7 @@ func TestSeedMockMetricsHistory_StaysContinuousWithSubsequentLiveMockTicks(t *te
now := time.Date(2026, time.March, 31, 12, 0, 0, 0, time.UTC)
next := now.Add(time.Minute)
const storageTotal = int64(2 * 1024 * 1024 * 1024 * 1024)
+ const k8sMetricID = "k8s:k8s-tail:pod:workloads/api-tail"
storageUsageAt := func(at time.Time) (float64, int64, int64) {
usage := mock.SampleMetric("storage", "storage-tail", "usage", at)
@@ -979,6 +992,26 @@ func TestSeedMockMetricsHistory_StaysContinuousWithSubsequentLiveMockTicks(t *te
Usage: storageUsageNow,
},
},
+ KubernetesClusters: []models.KubernetesCluster{
+ {
+ ID: "k8s-tail",
+ Name: "k8s-tail",
+ DisplayName: "Tail Cluster",
+ Pods: []models.KubernetesPod{
+ {
+ UID: "workloads/api-tail",
+ Namespace: "workloads",
+ Name: "api-tail",
+ Phase: "running",
+ UsageCPUPercent: 3,
+ UsageMemoryPercent: 99,
+ DiskUsagePercent: 91,
+ NetInRate: 9_999_999,
+ NetOutRate: 8_888_888,
+ },
+ },
+ },
+ },
}
mh := NewMetricsHistory(5000, 7*24*time.Hour)
@@ -1006,6 +1039,17 @@ func TestSeedMockMetricsHistory_StaysContinuousWithSubsequentLiveMockTicks(t *te
}
}
+ k8sSeeded := mh.GetGuestMetrics(k8sMetricID, "memory", 7*24*time.Hour)
+ if len(k8sSeeded) == 0 {
+ t.Fatal("expected seeded kubernetes pod memory history")
+ }
+ for i, point := range k8sSeeded {
+ want := mock.SampleMetric("k8s", k8sMetricID, "memory", point.Timestamp)
+ if diff := math.Abs(point.Value - want); diff > 1e-9 {
+ t.Fatalf("expected seeded k8s memory point %d to follow canonical runtime timeline: got=%f want=%f ts=%v", i, point.Value, want, point.Timestamp)
+ }
+ }
+
vmMemoryNext := mock.SampleMetric("vm", "vm-tail", "memory", next)
vmDiskNext := mock.SampleMetric("vm", "vm-tail", "disk", next)
storageUsageNext, storageUsedNext, storageFreeNext := storageUsageAt(next)
@@ -1041,6 +1085,26 @@ func TestSeedMockMetricsHistory_StaysContinuousWithSubsequentLiveMockTicks(t *te
Usage: storageUsageNext,
},
},
+ KubernetesClusters: []models.KubernetesCluster{
+ {
+ ID: "k8s-tail",
+ Name: "k8s-tail",
+ DisplayName: "Tail Cluster",
+ Pods: []models.KubernetesPod{
+ {
+ UID: "workloads/api-tail",
+ Namespace: "workloads",
+ Name: "api-tail",
+ Phase: "running",
+ UsageCPUPercent: 4,
+ UsageMemoryPercent: 12,
+ DiskUsagePercent: 7,
+ NetInRate: 123,
+ NetOutRate: 456,
+ },
+ },
+ },
+ },
}
recordMockStateToMetricsHistory(mh, nil, fixtureGraphWithState(liveState), next)
@@ -1066,4 +1130,331 @@ func TestSeedMockMetricsHistory_StaysContinuousWithSubsequentLiveMockTicks(t *te
if got := storageAfterTick[len(storageAfterTick)-2].Timestamp; !got.Equal(now) {
t.Fatalf("expected penultimate storage point to remain anchored at seed now %v, got %v", now, got)
}
+
+ k8sMemoryAfterTick := mh.GetGuestMetrics(k8sMetricID, "memory", 7*24*time.Hour)
+ if got := k8sMemoryAfterTick[len(k8sMemoryAfterTick)-1].Timestamp; !got.Equal(next) {
+ t.Fatalf("expected latest k8s memory point at %v, got %v", next, got)
+ }
+ if got, want := k8sMemoryAfterTick[len(k8sMemoryAfterTick)-1].Value, mock.SampleMetric("k8s", k8sMetricID, "memory", next); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected live k8s memory tick to continue canonical runtime timeline: got=%f want=%f", got, want)
+ }
+ if got := k8sMemoryAfterTick[len(k8sMemoryAfterTick)-2].Timestamp; !got.Equal(now) {
+ t.Fatalf("expected penultimate k8s memory point to remain anchored at seed now %v, got %v", now, got)
+ }
+}
+
+func TestSeedMockMetricsHistory_UsesCanonicalMetricModelForPlatformFixtures(t *testing.T) {
+ ts := time.Now().UTC().Truncate(time.Minute)
+ graph := mock.FixtureGraph{
+ PlatformFixtures: mock.PlatformFixtures{
+ TrueNAS: truenas.DefaultFixtures(),
+ VMware: vmware.DefaultFixtures(),
+ },
+ }
+
+ mh := NewMetricsHistory(20_000, 4*time.Hour)
+ seedMockMetricsHistory(mh, nil, graph, ts, 4*time.Hour, time.Minute)
+
+ assertCanonicalSeries := func(series []MetricPoint, resourceType, resourceID, metric string) {
+ t.Helper()
+ if len(series) == 0 {
+ t.Fatalf("expected seeded %s/%s history", resourceType, metric)
+ }
+ for i, point := range series {
+ want := mock.SampleMetric(resourceType, resourceID, metric, point.Timestamp)
+ if diff := math.Abs(point.Value - want); diff > 1e-9 {
+ t.Fatalf(
+ "expected seeded %s/%s point %d to follow canonical runtime timeline: got=%f want=%f ts=%v",
+ resourceType,
+ metric,
+ i,
+ point.Value,
+ want,
+ point.Timestamp,
+ )
+ }
+ }
+ }
+
+ trueNASHost := strings.TrimSpace(graph.PlatformFixtures.TrueNAS.System.Hostname)
+ if trueNASHost == "" {
+ t.Fatal("expected TrueNAS fixture host")
+ }
+ assertCanonicalSeries(mh.GetGuestMetrics("agent:"+trueNASHost, "cpu", 8*time.Hour), "agent", trueNASHost, "cpu")
+
+ if len(graph.PlatformFixtures.TrueNAS.Apps) == 0 {
+ t.Fatal("expected TrueNAS app fixtures")
+ }
+ trueNASAppID := strings.TrimSpace(graph.PlatformFixtures.TrueNAS.Apps[0].ID)
+ if trueNASAppID == "" {
+ trueNASAppID = strings.TrimSpace(graph.PlatformFixtures.TrueNAS.Apps[0].Name)
+ }
+ if trueNASAppID == "" {
+ t.Fatal("expected TrueNAS app identifier")
+ }
+ assertCanonicalSeries(mh.GetGuestMetrics("docker:"+trueNASAppID, "netin", 8*time.Hour), "dockerContainer", trueNASAppID, "netin")
+
+ if len(graph.PlatformFixtures.VMware.VMs) == 0 || len(graph.PlatformFixtures.VMware.Datastores) == 0 {
+ t.Fatal("expected VMware VM and datastore fixtures")
+ }
+ vmwareVMID := vmware.SourceID(
+ graph.PlatformFixtures.VMware.ConnectionID,
+ "vm",
+ graph.PlatformFixtures.VMware.VMs[0].VM,
+ )
+ assertCanonicalSeries(mh.GetGuestMetrics(vmwareVMID, "memory", 8*time.Hour), "vm", vmwareVMID, "memory")
+
+ vmwareDatastoreID := vmware.SourceID(
+ graph.PlatformFixtures.VMware.ConnectionID,
+ "datastore",
+ graph.PlatformFixtures.VMware.Datastores[0].Datastore,
+ )
+ assertCanonicalSeries(mh.GetAllStorageMetrics(vmwareDatastoreID, 8*time.Hour)["usage"], "storage", vmwareDatastoreID, "usage")
+}
+
+func TestSeedMockMetricsHistory_NormalizesTerminalTimestampToCanonicalGrid(t *testing.T) {
+ now := time.Now().UTC().Add(-53 * time.Second).Truncate(time.Second).Add(482 * time.Millisecond)
+ alignedNow := normalizeMockMetricTimestamp(now, time.Minute)
+ graph := fixtureGraphWithState(models.StateSnapshot{
+ VMs: []models.VM{
+ {ID: "vm-grid", Status: "running"},
+ },
+ })
+
+ mh := NewMetricsHistory(4_000, 2*time.Hour)
+ seedMockMetricsHistory(mh, nil, graph, now, 2*time.Hour, time.Minute)
+
+ points := mh.GetGuestMetrics("vm-grid", "cpu", 2*time.Hour)
+ if len(points) == 0 {
+ t.Fatal("expected seeded vm cpu history")
+ }
+ last := points[len(points)-1]
+ if !last.Timestamp.Equal(alignedNow) {
+ t.Fatalf("expected seeded terminal timestamp %v, got %v", alignedNow, last.Timestamp)
+ }
+ if got, want := last.Value, mock.SampleMetric("vm", "vm-grid", "cpu", alignedNow); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected seeded terminal point to use canonical aligned timeline: got=%f want=%f", got, want)
+ }
+}
+
+func TestRecordMockStateToMetricsHistory_UsesCanonicalMetricModelForStateBackedResources(t *testing.T) {
+ ts := time.Date(2026, time.April, 1, 14, 0, 0, 0, time.UTC)
+ const storageTotal = int64(4 * 1024 * 1024 * 1024 * 1024)
+
+ graph := fixtureGraphWithState(models.StateSnapshot{
+ Nodes: []models.Node{
+ {
+ ID: "node-live",
+ Status: "online",
+ CPU: 0.91,
+ Memory: models.Memory{Usage: 97, Total: 128 * 1024 * 1024 * 1024},
+ Disk: models.Disk{Usage: 92, Total: 1024, Used: 950},
+ },
+ },
+ VMs: []models.VM{
+ {
+ ID: "vm-live",
+ Status: "running",
+ CPU: 0.87,
+ Memory: models.Memory{Usage: 94, Total: 16 * 1024 * 1024 * 1024},
+ Disk: models.Disk{Usage: 89, Total: 512 * 1024 * 1024 * 1024, Used: 500 * 1024 * 1024 * 1024},
+ NetworkIn: 99_000_000,
+ NetworkOut: 77_000_000,
+ DiskRead: 55_000_000,
+ DiskWrite: 44_000_000,
+ },
+ },
+ Containers: []models.Container{
+ {
+ ID: "container-live",
+ Status: "running",
+ CPU: 0.83,
+ Memory: models.Memory{Usage: 88, Total: 2 * 1024 * 1024 * 1024},
+ Disk: models.Disk{Usage: 84, Total: 128 * 1024 * 1024 * 1024, Used: 100 * 1024 * 1024 * 1024},
+ NetworkIn: 21_000_000,
+ NetworkOut: 12_000_000,
+ DiskRead: 11_000_000,
+ DiskWrite: 9_000_000,
+ },
+ },
+ Storage: []models.Storage{
+ {
+ ID: "storage-live",
+ Status: "available",
+ Total: storageTotal,
+ Used: storageTotal - (256 * 1024 * 1024 * 1024),
+ Free: 256 * 1024 * 1024 * 1024,
+ Usage: 94,
+ },
+ },
+ PhysicalDisks: []models.PhysicalDisk{
+ {
+ ID: "disk-live",
+ Serial: "disk-live-serial",
+ Temperature: 68,
+ },
+ },
+ DockerHosts: []models.DockerHost{
+ {
+ ID: "docker-host-live",
+ Status: "online",
+ CPUUsage: 91,
+ Memory: models.Memory{Usage: 95, Total: 32 * 1024 * 1024 * 1024},
+ Containers: []models.DockerContainer{
+ {
+ ID: "docker-cont-live",
+ State: "running",
+ CPUPercent: 93,
+ MemoryPercent: 96,
+ },
+ },
+ },
+ },
+ Hosts: []models.Host{
+ {
+ ID: "agent-live",
+ Status: "online",
+ CPUUsage: 92,
+ Memory: models.Memory{Usage: 98, Total: 64 * 1024 * 1024 * 1024},
+ DiskReadRate: 88_000_000,
+ DiskWriteRate: 77_000_000,
+ NetInRate: 66_000_000,
+ NetOutRate: 55_000_000,
+ Disks: []models.Disk{
+ {Usage: 93, Total: 2 * 1024 * 1024 * 1024 * 1024, Used: 1800 * 1024 * 1024 * 1024},
+ },
+ },
+ },
+ KubernetesClusters: []models.KubernetesCluster{
+ {
+ ID: "k8s-live",
+ Name: "k8s-live",
+ DisplayName: "Live Cluster",
+ Pods: []models.KubernetesPod{
+ {
+ UID: "production/api-live",
+ Namespace: "production",
+ Name: "api-live",
+ Phase: "running",
+ UsageCPUPercent: 2,
+ UsageMemoryPercent: 99,
+ DiskUsagePercent: 91,
+ NetInRate: 91_000_000,
+ NetOutRate: 77_000_000,
+ },
+ },
+ },
+ },
+ })
+
+ mh := NewMetricsHistory(256, 24*time.Hour)
+ recordMockStateToMetricsHistory(mh, nil, graph, ts)
+
+ const lookback = 24 * time.Hour
+
+ if got, want := mh.GetNodeMetrics("node-live", "cpu", lookback)[0].Value, mock.SampleMetric("node", "node-live", "cpu", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected node cpu live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+ if got, want := mh.GetGuestMetrics("vm-live", "diskread", lookback)[0].Value, mock.SampleMetric("vm", "vm-live", "diskread", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected vm diskread live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+ if got, want := mh.GetGuestMetrics("container-live", "memory", lookback)[0].Value, mock.SampleMetric("container", "container-live", "memory", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected container memory live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+
+ storageMetrics := mh.GetAllStorageMetrics("storage-live", lookback)
+ storageUsage := storageMetrics["usage"][0].Value
+ if want := mock.SampleMetric("storage", "storage-live", "usage", ts); math.Abs(storageUsage-want) > 1e-9 {
+ t.Fatalf("expected storage usage live tick to use canonical metric model: got=%f want=%f", storageUsage, want)
+ }
+ wantUsed := float64(storageTotal) * (storageUsage / 100.0)
+ if diff := math.Abs(storageMetrics["used"][0].Value - wantUsed); diff > 1e-6 {
+ t.Fatalf("expected storage used live tick to derive from canonical usage: got=%f want=%f", storageMetrics["used"][0].Value, wantUsed)
+ }
+
+ if got, want := mh.GetDiskMetrics("disk-live-serial", "smart_temp", lookback)[0].Value, mock.SampleMetric("disk", "disk-live-serial", "smart_temp", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected disk temperature live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+ if got, want := mh.GetGuestMetrics("dockerHost:docker-host-live", "disk", lookback)[0].Value, mock.SampleMetric("dockerHost", "docker-host-live", "disk", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected docker host disk live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+ if got, want := mh.GetGuestMetrics("docker:docker-cont-live", "cpu", lookback)[0].Value, mock.SampleMetric("dockerContainer", "docker-cont-live", "cpu", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected docker container cpu live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+ if got, want := mh.GetGuestMetrics("agent:agent-live", "netin", lookback)[0].Value, mock.SampleMetric("agent", "agent-live", "netin", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected agent netin live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+ const k8sMetricID = "k8s:k8s-live:pod:production/api-live"
+ if got, want := mh.GetGuestMetrics(k8sMetricID, "memory", lookback)[0].Value, mock.SampleMetric("k8s", k8sMetricID, "memory", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected k8s pod memory live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+}
+
+func TestRecordMockStateToMetricsHistory_UsesCanonicalMetricModelForPlatformFixtures(t *testing.T) {
+ ts := time.Date(2026, time.April, 1, 14, 37, 0, 0, time.UTC)
+
+ graph := mock.FixtureGraph{
+ PlatformFixtures: mock.PlatformFixtures{
+ TrueNAS: truenas.DefaultFixtures(),
+ VMware: vmware.DefaultFixtures(),
+ },
+ }
+
+ mh := NewMetricsHistory(256, 24*time.Hour)
+ recordMockStateToMetricsHistory(mh, nil, graph, ts)
+
+ const lookback = 24 * time.Hour
+
+ trueNASHost := strings.TrimSpace(graph.PlatformFixtures.TrueNAS.System.Hostname)
+ if trueNASHost == "" {
+ t.Fatal("expected TrueNAS fixture host")
+ }
+ if got, want := mh.GetGuestMetrics("agent:"+trueNASHost, "cpu", lookback)[0].Value, mock.SampleMetric("agent", trueNASHost, "cpu", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected TrueNAS host cpu live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+
+ if len(graph.PlatformFixtures.TrueNAS.Pools) == 0 {
+ t.Fatal("expected TrueNAS pool fixtures")
+ }
+ trueNASPoolID := "pool:" + graph.PlatformFixtures.TrueNAS.Pools[0].Name
+ trueNASPoolMetrics := mh.GetAllStorageMetrics(trueNASPoolID, lookback)
+ if got, want := trueNASPoolMetrics["usage"][0].Value, mock.SampleMetric("storage", trueNASPoolID, "usage", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected TrueNAS pool usage live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+
+ if len(graph.PlatformFixtures.TrueNAS.Apps) == 0 {
+ t.Fatal("expected TrueNAS app fixtures")
+ }
+ trueNASAppID := strings.TrimSpace(graph.PlatformFixtures.TrueNAS.Apps[0].ID)
+ if trueNASAppID == "" {
+ trueNASAppID = strings.TrimSpace(graph.PlatformFixtures.TrueNAS.Apps[0].Name)
+ }
+ if trueNASAppID == "" {
+ t.Fatal("expected TrueNAS app identifier")
+ }
+ if got, want := mh.GetGuestMetrics("docker:"+trueNASAppID, "netin", lookback)[0].Value, mock.SampleMetric("dockerContainer", trueNASAppID, "netin", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected TrueNAS app netin live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+
+ if len(graph.PlatformFixtures.VMware.Hosts) == 0 || len(graph.PlatformFixtures.VMware.Datastores) == 0 {
+ t.Fatal("expected VMware host and datastore fixtures")
+ }
+ vmwareHostID := vmware.SourceID(
+ graph.PlatformFixtures.VMware.ConnectionID,
+ "host",
+ graph.PlatformFixtures.VMware.Hosts[0].Host,
+ )
+ if got, want := mh.GetGuestMetrics("agent:"+vmwareHostID, "memory", lookback)[0].Value, mock.SampleMetric("agent", vmwareHostID, "memory", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected VMware host memory live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
+
+ vmwareDatastoreID := vmware.SourceID(
+ graph.PlatformFixtures.VMware.ConnectionID,
+ "datastore",
+ graph.PlatformFixtures.VMware.Datastores[0].Datastore,
+ )
+ vmwareDatastoreMetrics := mh.GetAllStorageMetrics(vmwareDatastoreID, lookback)
+ if got, want := vmwareDatastoreMetrics["usage"][0].Value, mock.SampleMetric("storage", vmwareDatastoreID, "usage", ts); math.Abs(got-want) > 1e-9 {
+ t.Fatalf("expected VMware datastore usage live tick to use canonical metric model: got=%f want=%f", got, want)
+ }
}
diff --git a/internal/monitoring/mock_mode_config_test.go b/internal/monitoring/mock_mode_config_test.go
index 66d3eefe70..9b3035d044 100644
--- a/internal/monitoring/mock_mode_config_test.go
+++ b/internal/monitoring/mock_mode_config_test.go
@@ -9,10 +9,10 @@ import (
)
func TestKeepRealPollingInMockMode(t *testing.T) {
- t.Run("default_true", func(t *testing.T) {
+ t.Run("default_false", func(t *testing.T) {
t.Setenv(mockKeepRealPollingEnv, "")
- if !keepRealPollingInMockMode() {
- t.Fatal("expected default behavior to keep real polling enabled")
+ if keepRealPollingInMockMode() {
+ t.Fatal("expected default behavior to disable real polling in mock mode")
}
})
@@ -58,7 +58,7 @@ func TestNew_MockModeClientInitializationRespectsKeepRealPollingSetting(t *testi
fn(&called)
}
- t.Run("enabled_by_default", func(t *testing.T) {
+ t.Run("disabled_by_default", func(t *testing.T) {
t.Setenv(mockKeepRealPollingEnv, "")
mock.SetEnabled(true)
t.Cleanup(func() { mock.SetEnabled(false) })
@@ -70,11 +70,11 @@ func TestNew_MockModeClientInitializationRespectsKeepRealPollingSetting(t *testi
}
t.Cleanup(func() { monitor.Stop() })
- if !*called {
- t.Fatal("expected PVE client initialization in mock mode by default")
+ if *called {
+ t.Fatal("expected PVE client initialization to be skipped in mock mode by default")
}
- if len(monitor.pveClients) != 1 {
- t.Fatalf("expected 1 initialized PVE client, got %d", len(monitor.pveClients))
+ if len(monitor.pveClients) != 0 {
+ t.Fatalf("expected 0 initialized PVE clients, got %d", len(monitor.pveClients))
}
})
})
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index ebcf39c55f..5909ebe8b7 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -47,12 +47,12 @@ const mockKeepRealPollingEnv = "PULSE_MOCK_KEEP_REAL_POLLING"
func keepRealPollingInMockMode() bool {
raw := strings.TrimSpace(strings.ToLower(os.Getenv(mockKeepRealPollingEnv)))
switch raw {
- case "", "1", "true", "yes", "on":
+ case "1", "true", "yes", "on":
return true
- case "0", "false", "no", "off":
+ case "", "0", "false", "no", "off":
return false
default:
- return true
+ return false
}
}
@@ -691,6 +691,10 @@ func hostsFromReadState(readState unifiedresources.ReadState) []models.Host {
// writeSMARTMetrics writes SMART temperature history to the in-memory chart
// buffer and persists SMART attributes when the metrics store is enabled.
func (m *Monitor) writeSMARTMetrics(disk models.PhysicalDisk, now time.Time) {
+ if shouldSkipNativeMockStateMetricWrites() {
+ return
+ }
+
resourceID := unifiedresources.PhysicalDiskMetricID(disk)
if resourceID == "" {
return
@@ -1557,11 +1561,11 @@ func New(cfg *config.Config) (*Monitor, error) {
log.Warn().Err(err).Msg("failed to load webhook configuration")
}
- // In mock mode we keep real polling enabled by default so production metrics
- // continue to accumulate while the UI renders mock data.
+ // In mock mode the canonical sampler owns demo chart history by default.
+ // Support-only hybrid runs can opt back into real client initialization.
mockEnabled := mock.IsMockEnabled()
if mockEnabled && !keepRealPollingInMockMode() {
- log.Info().Msg("mock mode enabled - real client initialization disabled by env override")
+ log.Info().Msg("mock mode enabled - real client initialization disabled")
} else {
m.initPVEClients(cfg)
m.initPBSClients(cfg)
@@ -4754,14 +4758,15 @@ func shouldSkipMockOwnedUnifiedMetricSync(resource unifiedresources.Resource) bo
return false
}
- for _, source := range resource.Sources {
- switch source {
- case unifiedresources.SourceTrueNAS, unifiedresources.SourceVMware:
- return true
- }
- }
+ // In mock mode the canonical mock sampler owns chart/history continuity for
+ // the entire demo estate. Unified-resource sync must not append a second
+ // live timeline on top of seeded mock history for any resource class.
+ _ = resource
+ return true
+}
- return false
+func shouldSkipNativeMockStateMetricWrites() bool {
+ return mock.IsMockEnabled()
}
// getUnifiedResourcesForBroadcast retrieves all resources from the store.
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index 3169477fa3..e934b72c71 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -1274,94 +1274,90 @@ func (m *Monitor) ApplyDockerReport(report agentsdocker.Report, tokenRecord *con
m.alertManager.CheckDockerHost(host)
}
- // Record Docker HOST metrics for sparkline charts
- now := time.Now()
- hostMetricKey := fmt.Sprintf("dockerHost:%s", host.ID)
-
- // Record host CPU usage
- m.metricsHistory.AddGuestMetric(hostMetricKey, "cpu", host.CPUUsage, now)
-
- // Record host Memory usage
- m.metricsHistory.AddGuestMetric(hostMetricKey, "memory", host.Memory.Usage, now)
+ // Record Docker HOST and CONTAINER metrics for sparkline charts unless the
+ // canonical mock sampler owns history continuity.
+ if !shouldSkipNativeMockStateMetricWrites() {
+ now := time.Now()
+ hostMetricKey := fmt.Sprintf("dockerHost:%s", host.ID)
- // Record host Disk usage (use first disk or calculate total)
- var hostDiskPercent float64
- if len(host.Disks) > 0 {
- hostDiskPercent = host.Disks[0].Usage
- }
- m.metricsHistory.AddGuestMetric(hostMetricKey, "disk", hostDiskPercent, now)
-
- // Also write to persistent SQLite store
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerHost", host.ID, "cpu", host.CPUUsage, now)
- m.metricsStore.Write("dockerHost", host.ID, "memory", host.Memory.Usage, now)
- m.metricsStore.Write("dockerHost", host.ID, "disk", hostDiskPercent, now)
- }
-
- // Record Docker CONTAINER metrics for sparkline charts
- // Use a prefixed key (docker:containerID) to distinguish from Proxmox containers
- for _, container := range containers {
- if container.ID == "" {
- continue
+ // Record host Disk usage (use first disk or calculate total)
+ var hostDiskPercent float64
+ if len(host.Disks) > 0 {
+ hostDiskPercent = host.Disks[0].Usage
}
- // Build a unique metric key for Docker containers
- metricKey := fmt.Sprintf("docker:%s", container.ID)
- // Record CPU (already a percentage 0-100)
- m.metricsHistory.AddGuestMetric(metricKey, "cpu", container.CPUPercent, now)
-
- // Record Memory (already a percentage 0-100)
- m.metricsHistory.AddGuestMetric(metricKey, "memory", container.MemoryPercent, now)
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "cpu", host.CPUUsage, now)
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "memory", host.Memory.Usage, now)
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "disk", hostDiskPercent, now)
+ }
- // Record Disk usage as percentage of writable layer vs root filesystem
- var diskPercent float64
- if container.RootFilesystemBytes > 0 && container.WritableLayerBytes > 0 {
- diskPercent = float64(container.WritableLayerBytes) / float64(container.RootFilesystemBytes) * 100
- if diskPercent > 100 {
- diskPercent = 100
- }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("dockerHost", host.ID, "cpu", host.CPUUsage, now)
+ m.metricsStore.Write("dockerHost", host.ID, "memory", host.Memory.Usage, now)
+ m.metricsStore.Write("dockerHost", host.ID, "disk", hostDiskPercent, now)
}
- m.metricsHistory.AddGuestMetric(metricKey, "disk", diskPercent, now)
- var diskReadRate float64
- var diskWriteRate float64
- if container.BlockIO != nil {
- if container.BlockIO.ReadRateBytesPerSecond != nil {
- diskReadRate = *container.BlockIO.ReadRateBytesPerSecond
- }
- if container.BlockIO.WriteRateBytesPerSecond != nil {
- diskWriteRate = *container.BlockIO.WriteRateBytesPerSecond
+ // Use a prefixed key (docker:containerID) to distinguish from Proxmox containers.
+ for _, container := range containers {
+ if container.ID == "" {
+ continue
}
- }
- if container.NetInRate >= 0 {
- m.metricsHistory.AddGuestMetric(metricKey, "netin", container.NetInRate, now)
- }
- if container.NetOutRate >= 0 {
- m.metricsHistory.AddGuestMetric(metricKey, "netout", container.NetOutRate, now)
- }
- if diskReadRate >= 0 {
- m.metricsHistory.AddGuestMetric(metricKey, "diskread", diskReadRate, now)
- }
- if diskWriteRate >= 0 {
- m.metricsHistory.AddGuestMetric(metricKey, "diskwrite", diskWriteRate, now)
- }
+ metricKey := fmt.Sprintf("docker:%s", container.ID)
- // Also write to persistent SQLite store for long-term storage
- if m.metricsStore != nil {
- m.metricsStore.Write("dockerContainer", container.ID, "cpu", container.CPUPercent, now)
- m.metricsStore.Write("dockerContainer", container.ID, "memory", container.MemoryPercent, now)
- m.metricsStore.Write("dockerContainer", container.ID, "disk", diskPercent, now)
- if container.NetInRate >= 0 {
- m.metricsStore.Write("dockerContainer", container.ID, "netin", container.NetInRate, now)
+ var diskPercent float64
+ if container.RootFilesystemBytes > 0 && container.WritableLayerBytes > 0 {
+ diskPercent = float64(container.WritableLayerBytes) / float64(container.RootFilesystemBytes) * 100
+ if diskPercent > 100 {
+ diskPercent = 100
+ }
}
- if container.NetOutRate >= 0 {
- m.metricsStore.Write("dockerContainer", container.ID, "netout", container.NetOutRate, now)
+
+ var diskReadRate float64
+ var diskWriteRate float64
+ if container.BlockIO != nil {
+ if container.BlockIO.ReadRateBytesPerSecond != nil {
+ diskReadRate = *container.BlockIO.ReadRateBytesPerSecond
+ }
+ if container.BlockIO.WriteRateBytesPerSecond != nil {
+ diskWriteRate = *container.BlockIO.WriteRateBytesPerSecond
+ }
}
- if diskReadRate >= 0 {
- m.metricsStore.Write("dockerContainer", container.ID, "diskread", diskReadRate, now)
+
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(metricKey, "cpu", container.CPUPercent, now)
+ m.metricsHistory.AddGuestMetric(metricKey, "memory", container.MemoryPercent, now)
+ m.metricsHistory.AddGuestMetric(metricKey, "disk", diskPercent, now)
+ if container.NetInRate >= 0 {
+ m.metricsHistory.AddGuestMetric(metricKey, "netin", container.NetInRate, now)
+ }
+ if container.NetOutRate >= 0 {
+ m.metricsHistory.AddGuestMetric(metricKey, "netout", container.NetOutRate, now)
+ }
+ if diskReadRate >= 0 {
+ m.metricsHistory.AddGuestMetric(metricKey, "diskread", diskReadRate, now)
+ }
+ if diskWriteRate >= 0 {
+ m.metricsHistory.AddGuestMetric(metricKey, "diskwrite", diskWriteRate, now)
+ }
}
- if diskWriteRate >= 0 {
- m.metricsStore.Write("dockerContainer", container.ID, "diskwrite", diskWriteRate, now)
+
+ if m.metricsStore != nil {
+ m.metricsStore.Write("dockerContainer", container.ID, "cpu", container.CPUPercent, now)
+ m.metricsStore.Write("dockerContainer", container.ID, "memory", container.MemoryPercent, now)
+ m.metricsStore.Write("dockerContainer", container.ID, "disk", diskPercent, now)
+ if container.NetInRate >= 0 {
+ m.metricsStore.Write("dockerContainer", container.ID, "netin", container.NetInRate, now)
+ }
+ if container.NetOutRate >= 0 {
+ m.metricsStore.Write("dockerContainer", container.ID, "netout", container.NetOutRate, now)
+ }
+ if diskReadRate >= 0 {
+ m.metricsStore.Write("dockerContainer", container.ID, "diskread", diskReadRate, now)
+ }
+ if diskWriteRate >= 0 {
+ m.metricsStore.Write("dockerContainer", container.ID, "diskwrite", diskWriteRate, now)
+ }
}
}
}
@@ -1828,41 +1824,43 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
hostDiskPercent = host.Disks[0].Usage
}
- if m.metricsHistory != nil {
- m.metricsHistory.AddGuestMetric(hostMetricKey, "cpu", host.CPUUsage, now)
- m.metricsHistory.AddGuestMetric(hostMetricKey, "memory", host.Memory.Usage, now)
- m.metricsHistory.AddGuestMetric(hostMetricKey, "disk", hostDiskPercent, now)
+ if !shouldSkipNativeMockStateMetricWrites() {
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "cpu", host.CPUUsage, now)
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "memory", host.Memory.Usage, now)
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "disk", hostDiskPercent, now)
- if netInRate >= 0 {
- m.metricsHistory.AddGuestMetric(hostMetricKey, "netin", netInRate, now)
- }
- if netOutRate >= 0 {
- m.metricsHistory.AddGuestMetric(hostMetricKey, "netout", netOutRate, now)
- }
- if diskReadRate >= 0 {
- m.metricsHistory.AddGuestMetric(hostMetricKey, "diskread", diskReadRate, now)
- }
- if diskWriteRate >= 0 {
- m.metricsHistory.AddGuestMetric(hostMetricKey, "diskwrite", diskWriteRate, now)
+ if netInRate >= 0 {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "netin", netInRate, now)
+ }
+ if netOutRate >= 0 {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "netout", netOutRate, now)
+ }
+ if diskReadRate >= 0 {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "diskread", diskReadRate, now)
+ }
+ if diskWriteRate >= 0 {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "diskwrite", diskWriteRate, now)
+ }
}
- }
- if m.metricsStore != nil {
- m.metricsStore.Write("agent", host.ID, "cpu", host.CPUUsage, now)
- m.metricsStore.Write("agent", host.ID, "memory", host.Memory.Usage, now)
- m.metricsStore.Write("agent", host.ID, "disk", hostDiskPercent, now)
- m.writeHostSMARTMetrics(host, now)
- if netInRate >= 0 {
- m.metricsStore.Write("agent", host.ID, "netin", netInRate, now)
- }
- if netOutRate >= 0 {
- m.metricsStore.Write("agent", host.ID, "netout", netOutRate, now)
- }
- if diskReadRate >= 0 {
- m.metricsStore.Write("agent", host.ID, "diskread", diskReadRate, now)
- }
- if diskWriteRate >= 0 {
- m.metricsStore.Write("agent", host.ID, "diskwrite", diskWriteRate, now)
+ if m.metricsStore != nil {
+ m.metricsStore.Write("agent", host.ID, "cpu", host.CPUUsage, now)
+ m.metricsStore.Write("agent", host.ID, "memory", host.Memory.Usage, now)
+ m.metricsStore.Write("agent", host.ID, "disk", hostDiskPercent, now)
+ m.writeHostSMARTMetrics(host, now)
+ if netInRate >= 0 {
+ m.metricsStore.Write("agent", host.ID, "netin", netInRate, now)
+ }
+ if netOutRate >= 0 {
+ m.metricsStore.Write("agent", host.ID, "netout", netOutRate, now)
+ }
+ if diskReadRate >= 0 {
+ m.metricsStore.Write("agent", host.ID, "diskread", diskReadRate, now)
+ }
+ if diskWriteRate >= 0 {
+ m.metricsStore.Write("agent", host.ID, "diskwrite", diskWriteRate, now)
+ }
}
}
@@ -1873,6 +1871,10 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
}
func (m *Monitor) writeHostSMARTMetrics(host models.Host, now time.Time) {
+ if shouldSkipNativeMockStateMetricWrites() || m.metricsStore == nil {
+ return
+ }
+
for _, disk := range host.Sensors.SMART {
resourceID := unifiedresources.HostSMARTDiskSourceID(host, disk)
if resourceID == "" {
diff --git a/internal/monitoring/monitor_docker_test.go b/internal/monitoring/monitor_docker_test.go
index 3cf18c3308..61b50edc37 100644
--- a/internal/monitoring/monitor_docker_test.go
+++ b/internal/monitoring/monitor_docker_test.go
@@ -7,6 +7,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
agentsdocker "github.com/rcourtman/pulse-go-rewrite/pkg/agents/docker"
)
@@ -192,6 +193,73 @@ func TestApplyDockerReportUsesTokenToDisambiguateAgentIDCollisions(t *testing.T)
}
}
+func TestApplyDockerReportSkipsMetricsHistoryInMockMode(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ mock.SetEnabled(true)
+ t.Cleanup(func() { mock.SetEnabled(previous) })
+
+ monitor := newTestMonitor(t)
+ report := agentsdocker.Report{
+ Agent: agentsdocker.AgentInfo{
+ ID: "docker-agent-1",
+ Version: "1.0.0",
+ IntervalSeconds: 30,
+ },
+ Host: agentsdocker.HostInfo{
+ Hostname: "docker-demo",
+ Name: "Docker Demo",
+ MachineID: "docker-machine",
+ DockerVersion: "26.0.0",
+ TotalCPU: 4,
+ TotalMemoryBytes: 8 << 30,
+ UptimeSeconds: 120,
+ CPUUsagePercent: 37,
+ Memory: agentsdocker.MemoryMetric{
+ TotalBytes: 8 << 30,
+ UsedBytes: 4 << 30,
+ FreeBytes: 4 << 30,
+ Usage: 50,
+ },
+ Disks: []agentsdocker.Disk{
+ {
+ Device: "/dev/vda1",
+ Mountpoint: "/",
+ TotalBytes: 1000,
+ UsedBytes: 500,
+ FreeBytes: 500,
+ Usage: 50,
+ },
+ },
+ },
+ Containers: []agentsdocker.Container{
+ {
+ ID: "docker-cont-1",
+ Name: "api",
+ CPUPercent: 48,
+ MemoryPercent: 62,
+ RootFilesystemBytes: 1000,
+ WritableLayerBytes: 240,
+ NetworkRXBytes: 120,
+ NetworkTXBytes: 80,
+ BlockIO: &agentsdocker.ContainerBlockIO{ReadBytes: 220, WriteBytes: 140},
+ },
+ },
+ Timestamp: time.Now().UTC(),
+ }
+
+ host, err := monitor.ApplyDockerReport(report, nil)
+ if err != nil {
+ t.Fatalf("ApplyDockerReport: %v", err)
+ }
+
+ if got := monitor.metricsHistory.GetGuestMetrics("dockerHost:"+host.ID, "cpu", time.Hour); len(got) != 0 {
+ t.Fatalf("expected mock mode to skip docker host metrics history, got %+v", got)
+ }
+ if got := monitor.metricsHistory.GetGuestMetrics("docker:docker-cont-1", "cpu", time.Hour); len(got) != 0 {
+ t.Fatalf("expected mock mode to skip docker container metrics history, got %+v", got)
+ }
+}
+
func TestApplyDockerReportIncludesContainerDiskDetails(t *testing.T) {
timestamp := time.Now().UTC()
report := agentsdocker.Report{
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index 363989076b..20c518930c 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -6,6 +6,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/alerts"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
"github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
@@ -669,6 +670,77 @@ func TestApplyHostReportPersistsSMARTMetricsForAgentDisksWithFallbackID(t *testi
}
}
+func TestApplyHostReportSkipsMetricsAndSMARTWritesInMockMode(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ mock.SetEnabled(true)
+ t.Cleanup(func() { mock.SetEnabled(previous) })
+
+ storeCfg := metrics.DefaultConfig(t.TempDir())
+ storeCfg.WriteBufferSize = 1
+ store, err := metrics.NewStore(storeCfg)
+ if err != nil {
+ t.Fatalf("NewStore: %v", err)
+ }
+ defer store.Close()
+
+ monitor := &Monitor{
+ state: models.NewState(),
+ alertManager: alerts.NewManager(),
+ hostTokenBindings: make(map[string]string),
+ config: &config.Config{},
+ rateTracker: NewRateTracker(),
+ metricsHistory: NewMetricsHistory(1000, 24*time.Hour),
+ metricsStore: store,
+ }
+ t.Cleanup(func() { monitor.alertManager.Stop() })
+
+ report := agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: "agent-demo",
+ Version: "1.0.0",
+ IntervalSeconds: 30,
+ },
+ Host: agentshost.HostInfo{
+ ID: "machine-demo",
+ Hostname: "demo-host",
+ MachineID: "machine-demo",
+ },
+ Metrics: agentshost.Metrics{
+ CPUUsagePercent: 44,
+ Memory: agentshost.MemoryMetric{TotalBytes: 1024, UsedBytes: 512, FreeBytes: 512, Usage: 50},
+ },
+ Sensors: agentshost.Sensors{
+ SMART: []agentshost.DiskSMART{
+ {
+ Device: "/dev/sda",
+ Serial: "SERIAL-DEMO-1",
+ Temperature: 39,
+ },
+ },
+ },
+ Timestamp: time.Now().UTC(),
+ }
+
+ host, err := monitor.ApplyHostReport(report, nil)
+ if err != nil {
+ t.Fatalf("ApplyHostReport: %v", err)
+ }
+ store.Flush()
+
+ if got := monitor.metricsHistory.GetGuestMetrics("agent:"+host.ID, "cpu", time.Hour); len(got) != 0 {
+ t.Fatalf("expected mock mode to skip host-agent metrics history, got %+v", got)
+ }
+
+ now := time.Now().UTC()
+ points, err := store.Query("disk", "SERIAL-DEMO-1", "smart_temp", now.Add(-time.Hour), now.Add(time.Hour), 60)
+ if err != nil {
+ t.Fatalf("Query smart_temp: %v", err)
+ }
+ if len(points) != 0 {
+ t.Fatalf("expected mock mode to skip SMART metric persistence, got %+v", points)
+ }
+}
+
func waitForStoredDiskMetric(t *testing.T, store *metrics.Store, resourceID, metric string) []metrics.MetricPoint {
t.Helper()
diff --git a/internal/monitoring/monitor_metrics.go b/internal/monitoring/monitor_metrics.go
index a0ada1c873..54e78d01c1 100644
--- a/internal/monitoring/monitor_metrics.go
+++ b/internal/monitoring/monitor_metrics.go
@@ -4,6 +4,7 @@ import (
"strings"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
)
@@ -35,6 +36,8 @@ const (
shortRangeCoverageMaxSlack = 2 * time.Minute
)
+var storageChartMetricTypes = []string{"usage", "used", "avail", "total"}
+
// MonitorGuestMetricHistoryProvider optionally exposes source-native guest
// metric history through the canonical chart boundary when local Pulse history
// is shallow.
@@ -77,8 +80,15 @@ 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 {
+ if mock.IsMockEnabled() {
+ if synthetic := mockGuestMetricsForChart(sqlResourceType, sqlResourceID, duration); len(synthetic) > 0 {
+ return synthetic
+ }
+ return m.GetGuestMetrics(inMemoryKey, duration)
+ }
+
inMemoryResult := m.GetGuestMetrics(inMemoryKey, duration)
- if duration <= inMemoryChartThreshold && hasSufficientChartMapCoverage(inMemoryResult, duration) {
+ if hasSufficientChartMapCoverage(inMemoryResult, duration) {
return inMemoryResult
}
@@ -104,11 +114,15 @@ func (m *Monitor) GetNodeMetrics(nodeID string, metricType string, duration time
// GetNodeMetricsForChart returns node metrics for a single metric type,
// falling back to SQLite + LTTB for longer ranges.
func (m *Monitor) GetNodeMetricsForChart(nodeID, metricType string, duration time.Duration) []MetricPoint {
+ if mock.IsMockEnabled() {
+ return mockNodeMetricsForChart(nodeID, []string{metricType}, duration)[metricType]
+ }
+
inMemoryPoints := m.metricsHistory.GetNodeMetrics(nodeID, metricType, duration)
if m.metricsStore == nil {
return inMemoryPoints
}
- if duration <= inMemoryChartThreshold && hasSufficientChartSeriesCoverage(inMemoryPoints, duration) {
+ if hasSufficientChartSeriesCoverage(inMemoryPoints, duration) {
return inMemoryPoints
}
@@ -116,7 +130,7 @@ func (m *Monitor) GetNodeMetricsForChart(nodeID, metricType string, duration tim
if !ok {
return inMemoryPoints
}
- if duration <= inMemoryChartThreshold && chartSeriesCoverageSpan(downsampled) <= chartSeriesCoverageSpan(inMemoryPoints) {
+ if chartSeriesCoverageSpan(downsampled) <= chartSeriesCoverageSpan(inMemoryPoints) {
return inMemoryPoints
}
return downsampled
@@ -124,28 +138,34 @@ func (m *Monitor) GetNodeMetricsForChart(nodeID, metricType string, duration tim
// GetStorageMetrics returns historical metrics for storage
func (m *Monitor) GetStorageMetrics(storageID string, duration time.Duration) map[string][]MetricPoint {
+ if m == nil || m.metricsHistory == nil {
+ return map[string][]MetricPoint{}
+ }
return m.metricsHistory.GetAllStorageMetrics(storageID, duration)
}
// GetStorageMetricsForChart returns storage metrics, falling back to SQLite +
// LTTB for longer ranges.
func (m *Monitor) GetStorageMetricsForChart(storageID string, duration time.Duration) map[string][]MetricPoint {
- inMemoryResult := m.metricsHistory.GetAllStorageMetrics(storageID, duration)
+ inMemoryResult := map[string][]MetricPoint{}
+ if m != nil && m.metricsHistory != nil {
+ inMemoryResult = m.metricsHistory.GetAllStorageMetrics(storageID, duration)
+ }
+ if mock.IsMockEnabled() {
+ return m.mockStorageMetricsForChart(storageID, duration, inMemoryResult)
+ }
if m.metricsStore == nil {
return inMemoryResult
}
- if duration <= inMemoryChartThreshold && hasSufficientChartMapCoverage(inMemoryResult, duration) {
+ if hasSufficientChartMapCoverageForMetrics(inMemoryResult, duration, storageChartMetricTypes) {
return inMemoryResult
}
- converted, ok := m.queryStoreMetricMapWithGapFill("storage", storageID, duration)
- if !ok {
- return inMemoryResult
- }
- if duration <= inMemoryChartThreshold && chartMapCoverageSpan(converted) <= chartMapCoverageSpan(inMemoryResult) {
- return inMemoryResult
+ best := cloneMetricPointMap(inMemoryResult)
+ if converted, ok := m.queryStoreMetricMapWithGapFill("storage", storageID, duration); ok {
+ best = mergeMetricHistory(best, converted, duration)
}
- return converted
+ return best
}
// DiskChartEntry holds temperature chart data and display metadata for a
@@ -169,6 +189,10 @@ func (m *Monitor) GetPhysicalDiskTemperatureCharts(duration time.Duration) map[s
return nil
}
+ if mock.IsMockEnabled() {
+ return m.mockPhysicalDiskTemperatureCharts(duration)
+ }
+
readState := m.GetUnifiedReadStateOrSnapshot()
if readState == nil {
return nil
@@ -222,23 +246,30 @@ func (m *Monitor) GetPhysicalDiskTemperatureCharts(duration time.Duration) map[s
for i, d := range disks {
resourceIDs[i] = d.resourceID
}
+ inMemoryHistory := make(map[string][]MetricPoint, len(disks))
+ if m.metricsHistory != nil {
+ for _, d := range disks {
+ inMemoryHistory[d.resourceID] = m.metricsHistory.GetDiskMetrics(d.resourceID, "smart_temp", duration)
+ }
+ }
batchMetrics := m.queryStoreBatchMetricMapWithGapFill("disk", resourceIDs, duration)
nativeHistory := m.nativePhysicalDiskTemperatureHistory(duration)
// Phase 3: Build result entries.
result := make(map[string]DiskChartEntry, len(disks))
for _, d := range disks {
- var tempPoints []MetricPoint
+ tempPoints := cloneMetricSeries(inMemoryHistory[d.resourceID])
if resMetrics, ok := batchMetrics[d.resourceID]; ok {
if pts, found := resMetrics["smart_temp"]; found {
- tempPoints = pts
+ if shouldPreferMetricSeries(tempPoints, pts, duration) {
+ tempPoints = cloneMetricSeries(pts)
+ }
}
}
if nativePoints, ok := nativeHistory[d.resourceID]; ok {
nativePoints = lttb(nativePoints, chartDownsampleTarget)
- if chartSeriesCoverageSpan(nativePoints) > chartSeriesCoverageSpan(tempPoints) &&
- (!hasSufficientChartSeriesCoverage(tempPoints, duration) || len(tempPoints) < 2) {
- tempPoints = nativePoints
+ if shouldPreferMetricSeries(tempPoints, nativePoints, duration) {
+ tempPoints = cloneMetricSeries(nativePoints)
}
}
@@ -265,6 +296,10 @@ func (m *Monitor) GetPhysicalDiskTemperatureCharts(duration time.Duration) map[s
}
func (m *Monitor) nativePhysicalDiskTemperatureHistory(duration time.Duration) map[string][]MetricPoint {
+ if mock.IsMockEnabled() {
+ return nil
+ }
+
providers := m.supplementalProviderSnapshot()
if len(providers) == 0 {
return nil
@@ -383,6 +418,18 @@ func (m *Monitor) GetGuestMetricsForChartBatch(
return nil
}
+ if mock.IsMockEnabled() {
+ result := make(map[string]map[string][]MetricPoint, len(requests))
+ for _, req := range requests {
+ if synthetic := mockGuestMetricsForChart(sqlResourceType, req.SQLResourceID, duration); len(synthetic) > 0 {
+ result[req.SQLResourceID] = synthetic
+ continue
+ }
+ result[req.SQLResourceID] = m.GetGuestMetrics(req.InMemoryKey, duration)
+ }
+ return result
+ }
+
result := make(map[string]map[string][]MetricPoint, len(requests))
// Phase 1: Check in-memory for all guests and identify which need fallback.
@@ -390,7 +437,7 @@ func (m *Monitor) GetGuestMetricsForChartBatch(
for _, req := range requests {
inMemory := m.GetGuestMetrics(req.InMemoryKey, duration)
result[req.SQLResourceID] = inMemory
- if duration <= inMemoryChartThreshold && hasSufficientChartMapCoverage(inMemory, duration) {
+ if hasSufficientChartMapCoverage(inMemory, duration) {
result[req.SQLResourceID] = inMemory
continue
}
@@ -452,6 +499,14 @@ func (m *Monitor) GetNodeMetricsForChartBatch(
return nil
}
+ if mock.IsMockEnabled() {
+ result := make(map[string]map[string][]MetricPoint, len(nodeIDs))
+ for _, nodeID := range nodeIDs {
+ result[nodeID] = mockNodeMetricsForChart(nodeID, metricTypes, duration)
+ }
+ return result
+ }
+
result := make(map[string]map[string][]MetricPoint, len(nodeIDs))
// Phase 1: Check in-memory for all nodes and identify which need store.
@@ -462,7 +517,7 @@ func (m *Monitor) GetNodeMetricsForChartBatch(
for _, mt := range metricTypes {
points := m.metricsHistory.GetNodeMetrics(nid, mt, duration)
nodeResult[mt] = points
- if m.metricsStore != nil && (duration > inMemoryChartThreshold || !hasSufficientChartSeriesCoverage(points, duration)) {
+ if m.metricsStore != nil && !hasSufficientChartSeriesCoverage(points, duration) {
allSufficient = false
}
}
@@ -491,7 +546,7 @@ func (m *Monitor) GetNodeMetricsForChartBatch(
continue
}
inMemory := result[nid][mt]
- if duration <= inMemoryChartThreshold && chartSeriesCoverageSpan(storePoints) <= chartSeriesCoverageSpan(inMemory) {
+ if chartSeriesCoverageSpan(storePoints) <= chartSeriesCoverageSpan(inMemory) {
continue
}
result[nid][mt] = storePoints
@@ -514,15 +569,29 @@ func (m *Monitor) GetStorageMetricsForChartBatch(
result := make(map[string]map[string][]MetricPoint, len(storageIDs))
+ if mock.IsMockEnabled() {
+ for _, sid := range storageIDs {
+ inMemory := map[string][]MetricPoint{}
+ if m.metricsHistory != nil {
+ inMemory = m.metricsHistory.GetAllStorageMetrics(sid, duration)
+ }
+ result[sid] = m.mockStorageMetricsForChart(sid, duration, inMemory)
+ }
+ return result
+ }
+
// Phase 1: Check in-memory for all storage pools.
var needStore []string
for _, sid := range storageIDs {
- inMemory := m.metricsHistory.GetAllStorageMetrics(sid, duration)
+ inMemory := map[string][]MetricPoint{}
+ if m.metricsHistory != nil {
+ inMemory = m.metricsHistory.GetAllStorageMetrics(sid, duration)
+ }
if m.metricsStore == nil {
result[sid] = inMemory
continue
}
- if duration <= inMemoryChartThreshold && hasSufficientChartMapCoverage(inMemory, duration) {
+ if hasSufficientChartMapCoverageForMetrics(inMemory, duration, storageChartMetricTypes) {
result[sid] = inMemory
continue
}
@@ -543,11 +612,7 @@ func (m *Monitor) GetStorageMetricsForChartBatch(
if !ok {
continue
}
- inMemory := result[id]
- if duration <= inMemoryChartThreshold && chartMapCoverageSpan(storeData) <= chartMapCoverageSpan(inMemory) {
- continue
- }
- result[id] = storeData
+ result[id] = mergeMetricHistory(result[id], storeData, duration)
}
return result
@@ -714,13 +779,17 @@ func cloneMetricPointMap(metrics map[string][]MetricPoint) map[string][]MetricPo
}
func mergeGuestMetricHistory(base, candidate map[string][]MetricPoint, duration time.Duration) map[string][]MetricPoint {
+ return mergeMetricHistory(base, candidate, duration)
+}
+
+func mergeMetricHistory(base, candidate map[string][]MetricPoint, duration time.Duration) map[string][]MetricPoint {
if len(candidate) == 0 {
return cloneMetricPointMap(base)
}
merged := cloneMetricPointMap(base)
for metricType, candidateSeries := range candidate {
- if !shouldPreferGuestMetricSeries(merged[metricType], candidateSeries, duration) {
+ if !shouldPreferMetricSeries(merged[metricType], candidateSeries, duration) {
continue
}
merged[metricType] = cloneMetricSeries(candidateSeries)
@@ -728,7 +797,7 @@ func mergeGuestMetricHistory(base, candidate map[string][]MetricPoint, duration
return merged
}
-func shouldPreferGuestMetricSeries(current, candidate []MetricPoint, duration time.Duration) bool {
+func shouldPreferMetricSeries(current, candidate []MetricPoint, duration time.Duration) bool {
if len(candidate) == 0 {
return false
}
@@ -738,15 +807,13 @@ func shouldPreferGuestMetricSeries(current, candidate []MetricPoint, duration ti
candidateSpan := chartSeriesCoverageSpan(candidate)
currentSpan := chartSeriesCoverageSpan(current)
- if duration <= inMemoryChartThreshold {
- currentSufficient := hasSufficientChartSeriesCoverage(current, duration)
- candidateSufficient := hasSufficientChartSeriesCoverage(candidate, duration)
- switch {
- case currentSufficient && !candidateSufficient:
- return false
- case !currentSufficient && candidateSufficient:
- return true
- }
+ currentSufficient := hasSufficientChartSeriesCoverage(current, duration)
+ candidateSufficient := hasSufficientChartSeriesCoverage(candidate, duration)
+ switch {
+ case currentSufficient && !candidateSufficient:
+ return false
+ case !currentSufficient && candidateSufficient:
+ return true
}
if candidateSpan > currentSpan {
@@ -844,3 +911,15 @@ func hasSufficientChartSeriesCoverage(points []MetricPoint, duration time.Durati
func hasSufficientChartMapCoverage(metrics map[string][]MetricPoint, duration time.Duration) bool {
return chartMapCoverageSpan(metrics) >= chartCoverageRequiredSpan(duration)
}
+
+func hasSufficientChartMapCoverageForMetrics(metrics map[string][]MetricPoint, duration time.Duration, metricTypes []string) bool {
+ if len(metricTypes) == 0 {
+ return hasSufficientChartMapCoverage(metrics, duration)
+ }
+ for _, metricType := range metricTypes {
+ if !hasSufficientChartSeriesCoverage(metrics[metricType], duration) {
+ return false
+ }
+ }
+ return true
+}
diff --git a/internal/monitoring/monitor_metrics_chart_fallback_test.go b/internal/monitoring/monitor_metrics_chart_fallback_test.go
index ced0fbb809..ccb1fbee70 100644
--- a/internal/monitoring/monitor_metrics_chart_fallback_test.go
+++ b/internal/monitoring/monitor_metrics_chart_fallback_test.go
@@ -1,9 +1,11 @@
package monitoring
import (
+ "math"
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
@@ -96,6 +98,30 @@ func writeRawMetricBatch(t *testing.T, store *metrics.Store, resourceType, resou
store.WriteBatchSync(records)
}
+func assertFollowsCanonicalMockSeries(t *testing.T, points []MetricPoint, resourceType, resourceID, metricType string) {
+ t.Helper()
+ if len(points) < 2 {
+ t.Fatalf("expected canonical mock series with at least 2 points, got %+v", points)
+ }
+
+ checkIndices := []int{0, len(points) / 2, len(points) - 1}
+ seen := map[int]struct{}{}
+ for _, idx := range checkIndices {
+ if idx < 0 || idx >= len(points) {
+ continue
+ }
+ if _, ok := seen[idx]; ok {
+ continue
+ }
+ seen[idx] = struct{}{}
+
+ want := mock.SampleMetric(resourceType, resourceID, metricType, points[idx].Timestamp)
+ if diff := math.Abs(points[idx].Value - want); diff > 1e-9 {
+ t.Fatalf("points[%d] = %+v, want canonical %.12f", idx, points[idx], want)
+ }
+ }
+}
+
func TestGetGuestMetricsForChart_ShortRangeFallsBackToStoreWhenInMemoryCoverageShallow(t *testing.T) {
t.Parallel()
@@ -119,6 +145,34 @@ func TestGetGuestMetricsForChart_ShortRangeFallsBackToStoreWhenInMemoryCoverageS
}
}
+func TestGetGuestMetricsForChart_LongRangeUsesInMemoryWhenCoverageSufficient(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 12 * time.Hour
+
+ inMemoryKey := "agent:host-1"
+ for _, offset := range []time.Duration{-11 * time.Hour, -6 * time.Hour, -1 * time.Minute} {
+ monitor.metricsHistory.AddGuestMetric(inMemoryKey, "cpu", 17, now.Add(offset))
+ }
+
+ writeRawMetricBatch(t, monitor.metricsStore, "agent", "host-1", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-11 * time.Hour), Value: 91},
+ {Timestamp: now.Add(-6 * time.Hour), Value: 94},
+ {Timestamp: now.Add(-1 * time.Minute), Value: 99},
+ })
+
+ result := monitor.GetGuestMetricsForChart(inMemoryKey, "agent", "host-1", duration)
+ cpuPoints := result["cpu"]
+ if len(cpuPoints) == 0 {
+ t.Fatal("expected in-memory guest chart points")
+ }
+ if cpuPoints[0].Value != 17 {
+ t.Fatalf("expected long-range in-memory guest history to win, got first value %.2f", cpuPoints[0].Value)
+ }
+}
+
func TestGetNodeMetricsForChart_ShortRangeUsesInMemoryWhenCoverageSufficient(t *testing.T) {
t.Parallel()
@@ -145,6 +199,32 @@ func TestGetNodeMetricsForChart_ShortRangeUsesInMemoryWhenCoverageSufficient(t *
}
}
+func TestGetNodeMetricsForChart_LongRangeUsesInMemoryWhenCoverageSufficient(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 12 * time.Hour
+
+ for _, offset := range []time.Duration{-11 * time.Hour, -6 * time.Hour, -1 * time.Minute} {
+ monitor.metricsHistory.AddNodeMetric("node-1", "cpu", 13, now.Add(offset))
+ }
+
+ writeRawMetricBatch(t, monitor.metricsStore, "node", "node-1", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-11 * time.Hour), Value: 88},
+ {Timestamp: now.Add(-6 * time.Hour), Value: 92},
+ {Timestamp: now.Add(-1 * time.Minute), Value: 96},
+ })
+
+ result := monitor.GetNodeMetricsForChart("node-1", "cpu", duration)
+ if len(result) == 0 {
+ t.Fatal("expected in-memory node chart series")
+ }
+ if result[0].Value != 13 {
+ t.Fatalf("expected long-range in-memory node history to win, got first value %.2f", result[0].Value)
+ }
+}
+
func TestGetNodeMetricsForChart_ShortRangeFallsBackToStoreWhenInMemoryCoverageShallow(t *testing.T) {
t.Parallel()
@@ -189,6 +269,69 @@ func TestGetStorageMetricsForChart_ShortRangeFallsBackToStoreWhenInMemoryCoverag
}
}
+func TestGetStorageMetricsForChart_LongRangeUsesInMemoryWhenCoverageSufficient(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 12 * time.Hour
+
+ for _, offset := range []time.Duration{-11 * time.Hour, -6 * time.Hour, -1 * time.Minute} {
+ monitor.metricsHistory.AddStorageMetric("storage-1", "usage", 26, now.Add(offset))
+ }
+
+ writeRawMetricBatch(t, monitor.metricsStore, "storage", "storage-1", "usage", []MetricPoint{
+ {Timestamp: now.Add(-11 * time.Hour), Value: 71},
+ {Timestamp: now.Add(-6 * time.Hour), Value: 74},
+ {Timestamp: now.Add(-1 * time.Minute), Value: 79},
+ })
+
+ result := monitor.GetStorageMetricsForChart("storage-1", duration)
+ usagePoints := result["usage"]
+ if len(usagePoints) == 0 {
+ t.Fatal("expected in-memory storage chart points")
+ }
+ if usagePoints[0].Value != 26 {
+ t.Fatalf("expected long-range in-memory storage history to win, got first value %.2f", usagePoints[0].Value)
+ }
+}
+
+func TestGetStorageMetricsForChart_MergesStorageMetricsPerMetricType(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := time.Hour
+
+ for _, offset := range []time.Duration{-58 * time.Minute, -30 * time.Minute, -1 * time.Minute} {
+ monitor.metricsHistory.AddStorageMetric("storage-1", "usage", 42, now.Add(offset))
+ }
+ monitor.metricsHistory.AddStorageMetric("storage-1", "used", 420, now.Add(-2*time.Minute))
+ monitor.metricsHistory.AddStorageMetric("storage-1", "avail", 580, now.Add(-2*time.Minute))
+
+ writeRawMetricBatch(t, monitor.metricsStore, "storage", "storage-1", "used", []MetricPoint{
+ {Timestamp: now.Add(-58 * time.Minute), Value: 390},
+ {Timestamp: now.Add(-30 * time.Minute), Value: 405},
+ {Timestamp: now.Add(-1 * time.Minute), Value: 420},
+ })
+ writeRawMetricBatch(t, monitor.metricsStore, "storage", "storage-1", "avail", []MetricPoint{
+ {Timestamp: now.Add(-58 * time.Minute), Value: 610},
+ {Timestamp: now.Add(-30 * time.Minute), Value: 595},
+ {Timestamp: now.Add(-1 * time.Minute), Value: 580},
+ })
+
+ result := monitor.GetStorageMetricsForChart("storage-1", duration)
+ if len(result["usage"]) != 3 {
+ t.Fatalf("expected in-memory usage series to remain intact, got %d points", len(result["usage"]))
+ }
+ if got, wantMin := chartSeriesCoverageSpan(result["used"]), 45*time.Minute; got < wantMin {
+ t.Fatalf("expected store-backed used coverage >= %s, got %s", wantMin, got)
+ }
+ if got, wantMin := chartSeriesCoverageSpan(result["avail"]), 45*time.Minute; got < wantMin {
+ t.Fatalf("expected store-backed avail coverage >= %s, got %s", wantMin, got)
+ }
+}
+
func TestGetPhysicalDiskTemperatureCharts_UsesUnifiedReadStateDiskViews(t *testing.T) {
t.Parallel()
@@ -237,6 +380,53 @@ func TestGetPhysicalDiskTemperatureCharts_UsesUnifiedReadStateDiskViews(t *testi
}
}
+func TestGetPhysicalDiskTemperatureCharts_UsesInMemoryHistoryWithoutMetricsStore(t *testing.T) {
+ t.Parallel()
+
+ registry := unifiedresources.NewRegistry(nil)
+ registry.IngestSnapshot(models.StateSnapshot{
+ PhysicalDisks: []models.PhysicalDisk{
+ {
+ ID: "disk-1",
+ Node: "node-a",
+ Instance: "lab-a",
+ DevPath: "/dev/nvme0n1",
+ Model: "Samsung PM9A3",
+ Serial: "SERIAL-DISK-1",
+ Temperature: 42,
+ LastChecked: time.Now().UTC(),
+ },
+ },
+ })
+
+ monitor := &Monitor{
+ metricsHistory: NewMetricsHistory(1024, 24*time.Hour),
+ state: models.NewState(),
+ resourceStore: unifiedresources.NewMonitorAdapter(registry),
+ }
+
+ now := time.Now().UTC().Truncate(time.Second)
+ for _, sample := range []struct {
+ offset time.Duration
+ value float64
+ }{
+ {-58 * time.Minute, 39},
+ {-30 * time.Minute, 41},
+ {-1 * time.Minute, 42},
+ } {
+ monitor.metricsHistory.AddDiskMetric("SERIAL-DISK-1", "smart_temp", sample.value, now.Add(sample.offset))
+ }
+
+ charts := monitor.GetPhysicalDiskTemperatureCharts(time.Hour)
+ entry, ok := charts["SERIAL-DISK-1"]
+ if !ok {
+ t.Fatalf("expected chart entry for canonical disk metric ID, got %#v", charts)
+ }
+ if got, wantMin := chartSeriesCoverageSpan(entry.Temperature), 45*time.Minute; got < wantMin {
+ t.Fatalf("expected in-memory disk temperature coverage >= %s, got %s", wantMin, got)
+ }
+}
+
func TestGetPhysicalDiskTemperatureCharts_UsesNativeHistoryWhenStoreCoverageShallow(t *testing.T) {
t.Parallel()
@@ -286,6 +476,103 @@ func TestGetPhysicalDiskTemperatureCharts_UsesNativeHistoryWhenStoreCoverageShal
}
}
+func TestGetPhysicalDiskTemperatureCharts_SkipsNativeHistoryInMockMode(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ mock.SetEnabled(true)
+ defer mock.SetEnabled(previous)
+
+ graph := mock.CurrentFixtureGraph()
+ if len(graph.PlatformFixtures.TrueNAS.Disks) == 0 {
+ t.Fatal("expected mock mode TrueNAS disks")
+ }
+ resourceID := trueNASDiskMetricsResourceID(graph.PlatformFixtures.TrueNAS.Disks[0])
+ if resourceID == "" {
+ t.Fatal("expected canonical TrueNAS disk metric id")
+ }
+
+ now := time.Now().UTC().Truncate(time.Minute)
+ monitor := &Monitor{
+ metricsHistory: NewMetricsHistory(1024, 24*time.Hour),
+ state: models.NewState(),
+ supplementalProviders: map[unifiedresources.DataSource]MonitorSupplementalRecordsProvider{
+ unifiedresources.SourceTrueNAS: &stubDiskTemperatureHistoryProvider{
+ history: map[string][]MetricPoint{
+ resourceID: {
+ {Timestamp: now.Add(-2 * time.Hour), Value: 29},
+ {Timestamp: now.Add(-1 * time.Hour), Value: 31},
+ {Timestamp: now, Value: 34},
+ },
+ },
+ },
+ },
+ }
+ for _, sample := range []struct {
+ offset time.Duration
+ value float64
+ }{
+ {-4 * time.Minute, 32},
+ {-2 * time.Minute, 33},
+ {0, 34},
+ } {
+ monitor.metricsHistory.AddDiskMetric(resourceID, "smart_temp", sample.value, now.Add(sample.offset))
+ }
+
+ charts := monitor.GetPhysicalDiskTemperatureCharts(time.Hour)
+ entry, ok := charts[resourceID]
+ if !ok {
+ t.Fatalf("expected chart entry for canonical disk metric id, got %#v", charts)
+ }
+ assertFollowsCanonicalMockSeries(t, entry.Temperature, "disk", resourceID, "smart_temp")
+}
+
+func TestGetGuestMetricsForChart_UsesCanonicalMockSamplerInMockMode(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ mock.SetEnabled(true)
+ defer mock.SetEnabled(previous)
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := time.Hour
+
+ writeRawMetricBatch(t, monitor.metricsStore, "vm", "vm-1", "memory", []MetricPoint{
+ {Timestamp: now.Add(-3 * time.Minute), Value: 12},
+ {Timestamp: now.Add(-1 * time.Minute), Value: 91},
+ })
+
+ result := monitor.GetGuestMetricsForChart("vm-1", "vm", "vm-1", duration)
+ assertFollowsCanonicalMockSeries(t, result["memory"], "vm", "vm-1", "memory")
+}
+
+func TestGetStorageMetricsForChart_UsesCanonicalMockSamplerInMockMode(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ mock.SetEnabled(true)
+ defer mock.SetEnabled(previous)
+
+ graph := mock.CurrentFixtureGraph()
+ if len(graph.State.Storage) == 0 {
+ t.Fatal("expected canonical mock storage fixtures")
+ }
+ storageID := graph.State.Storage[0].ID
+ if storageID == "" {
+ t.Fatal("expected canonical storage id")
+ }
+
+ monitor := &Monitor{
+ metricsHistory: NewMetricsHistory(1024, 24*time.Hour),
+ state: models.NewState(),
+ }
+
+ result := monitor.GetStorageMetricsForChart(storageID, time.Hour)
+ assertFollowsCanonicalMockSeries(t, result["usage"], "storage", storageID, "usage")
+ if len(result["used"]) == 0 || len(result["avail"]) == 0 || len(result["total"]) == 0 {
+ t.Fatalf("expected full storage capacity series, got %+v", result)
+ }
+ total := result["total"][len(result["total"])-1].Value
+ if total <= 0 {
+ t.Fatalf("expected positive storage total, got %+v", result["total"])
+ }
+}
+
func TestGetGuestMetricsForChart_UsesGapFillLookbackWhenRequestedRangeIsEmpty(t *testing.T) {
t.Parallel()
@@ -447,6 +734,35 @@ func TestGetGuestMetricsForChartBatch_PrefersInMemoryForShortRanges(t *testing.T
}
}
+func TestGetGuestMetricsForChartBatch_PrefersInMemoryWhenLongRangeCoverageIsSufficient(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 12 * time.Hour
+
+ for _, offset := range []time.Duration{-11 * time.Hour, -6 * time.Hour, -5 * time.Minute} {
+ monitor.metricsHistory.AddGuestMetric("vm-1", "cpu", 19, now.Add(offset))
+ }
+
+ writeRawMetricBatch(t, monitor.metricsStore, "vm", "vm-1", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-11 * time.Hour), Value: 89},
+ {Timestamp: now.Add(-6 * time.Hour), Value: 93},
+ {Timestamp: now.Add(-5 * time.Minute), Value: 98},
+ })
+
+ requests := []GuestChartRequest{{InMemoryKey: "vm-1", SQLResourceID: "vm-1"}}
+ result := monitor.GetGuestMetricsForChartBatch("vm", requests, duration)
+
+ cpuPoints := result["vm-1"]["cpu"]
+ if len(cpuPoints) == 0 {
+ t.Fatal("expected non-empty cpu series")
+ }
+ if cpuPoints[0].Value != 19 {
+ t.Fatalf("expected long-range in-memory batch series to win, got %.2f", cpuPoints[0].Value)
+ }
+}
+
func TestGetGuestMetricsForChartBatch_UsesNativeAgentHistoryWhenStoreCoverageShallow(t *testing.T) {
t.Parallel()
@@ -584,6 +900,39 @@ func TestGetNodeMetricsForChartBatch_BatchesMultipleNodesAndMetricTypes(t *testi
}
}
+func TestGetNodeMetricsForChartBatch_PrefersInMemoryWhenLongRangeCoverageIsSufficient(t *testing.T) {
+ t.Parallel()
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := 12 * time.Hour
+
+ for _, offset := range []time.Duration{-11 * time.Hour, -6 * time.Hour, -5 * time.Minute} {
+ monitor.metricsHistory.AddNodeMetric("node-1", "cpu", 14, now.Add(offset))
+ monitor.metricsHistory.AddNodeMetric("node-1", "memory", 37, now.Add(offset))
+ }
+
+ writeRawMetricBatch(t, monitor.metricsStore, "node", "node-1", "cpu", []MetricPoint{
+ {Timestamp: now.Add(-11 * time.Hour), Value: 84},
+ {Timestamp: now.Add(-6 * time.Hour), Value: 88},
+ {Timestamp: now.Add(-5 * time.Minute), Value: 94},
+ })
+ writeRawMetricBatch(t, monitor.metricsStore, "node", "node-1", "memory", []MetricPoint{
+ {Timestamp: now.Add(-11 * time.Hour), Value: 74},
+ {Timestamp: now.Add(-6 * time.Hour), Value: 78},
+ {Timestamp: now.Add(-5 * time.Minute), Value: 82},
+ })
+
+ result := monitor.GetNodeMetricsForChartBatch([]string{"node-1"}, []string{"cpu", "memory"}, duration)
+
+ if cpuPoints := result["node-1"]["cpu"]; len(cpuPoints) == 0 || cpuPoints[0].Value != 14 {
+ t.Fatalf("expected long-range in-memory node batch cpu history to win, got %+v", cpuPoints)
+ }
+ if memoryPoints := result["node-1"]["memory"]; len(memoryPoints) == 0 || memoryPoints[0].Value != 37 {
+ t.Fatalf("expected long-range in-memory node batch memory history to win, got %+v", memoryPoints)
+ }
+}
+
func TestGetNodeMetricsForChartBatch_EmptyNodeIDs(t *testing.T) {
t.Parallel()
diff --git a/internal/monitoring/monitor_metrics_slo_test.go b/internal/monitoring/monitor_metrics_slo_test.go
index 3824817cfe..b37c2a3841 100644
--- a/internal/monitoring/monitor_metrics_slo_test.go
+++ b/internal/monitoring/monitor_metrics_slo_test.go
@@ -7,6 +7,7 @@ import (
"testing"
"time"
+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
"github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
@@ -354,3 +355,53 @@ func TestSLO_GetGuestMetricsForChart_WithNativeHistoryFallback(t *testing.T) {
t.Errorf("SLO VIOLATION: p95=%v exceeds target %v", p95, target)
}
}
+
+func TestSLO_GetGuestMetricsForChartBatch_DoesNotStitchSparseStoreTailOntoCoveredInMemorySeries(t *testing.T) {
+ previous := mock.IsMockEnabled()
+ mock.SetEnabled(true)
+ t.Cleanup(func() { mock.SetEnabled(previous) })
+
+ monitor := newChartFallbackTestMonitor(t)
+ now := time.Now().UTC().Truncate(time.Second)
+ duration := time.Hour
+
+ inMemorySeries := []MetricPoint{
+ {Timestamp: now.Add(-58 * time.Minute), Value: 74},
+ {Timestamp: now.Add(-36 * time.Minute), Value: 75},
+ {Timestamp: now.Add(-14 * time.Minute), Value: 77},
+ {Timestamp: now.Add(-2 * time.Minute), Value: 78},
+ }
+ for _, point := range inMemorySeries {
+ monitor.metricsHistory.AddGuestMetric("vm-1", "memory", point.Value, point.Timestamp)
+ }
+
+ // This sparse late store point models the old stitched-tail behavior. In
+ // mock mode the batch chart path must ignore persisted history entirely and
+ // serve the canonical sampler timeline instead.
+ writeRawMetricBatch(t, monitor.metricsStore, "vm", "vm-1", "memory", []MetricPoint{
+ {Timestamp: now.Add(-1 * time.Minute), Value: 21},
+ })
+
+ result := monitor.GetGuestMetricsForChartBatch("vm", []GuestChartRequest{{
+ InMemoryKey: "vm-1",
+ SQLResourceID: "vm-1",
+ }}, duration)
+
+ memoryPoints := result["vm-1"]["memory"]
+ if len(memoryPoints) < 2 {
+ t.Fatalf("expected canonical mock memory series, got %+v", memoryPoints)
+ }
+ checkIndices := []int{0, len(memoryPoints) / 2, len(memoryPoints) - 1}
+ seen := map[int]struct{}{}
+ for _, idx := range checkIndices {
+ if _, ok := seen[idx]; ok {
+ continue
+ }
+ seen[idx] = struct{}{}
+
+ want := mock.SampleMetric("vm", "vm-1", "memory", memoryPoints[idx].Timestamp)
+ if memoryPoints[idx].Value != want {
+ t.Fatalf("memoryPoints[%d] = %+v, want canonical %.12f", idx, memoryPoints[idx], want)
+ }
+ }
+}
diff --git a/internal/monitoring/monitor_polling_containers.go b/internal/monitoring/monitor_polling_containers.go
index 56e639d96d..d9b7c7b757 100644
--- a/internal/monitoring/monitor_polling_containers.go
+++ b/internal/monitoring/monitor_polling_containers.go
@@ -296,9 +296,12 @@ func (m *Monitor) pollContainersWithNodes(ctx context.Context, instanceName stri
m.state.UpdateContainersForInstance(instanceName, allContainers)
// Record guest metrics history for running containers (enables sparkline/trends view)
- now := time.Now()
- for _, ct := range allContainers {
- if ct.Status == "running" {
+ if !shouldSkipNativeMockStateMetricWrites() {
+ now := time.Now()
+ for _, ct := range allContainers {
+ if ct.Status != "running" {
+ continue
+ }
m.metricsHistory.AddGuestMetric(ct.ID, "cpu", ct.CPU*100, now)
m.metricsHistory.AddGuestMetric(ct.ID, "memory", ct.Memory.Usage, now)
if ct.Disk.Usage >= 0 {
diff --git a/internal/monitoring/monitor_polling_storage.go b/internal/monitoring/monitor_polling_storage.go
index 5918fbab38..8ddbf98ffb 100644
--- a/internal/monitoring/monitor_polling_storage.go
+++ b/internal/monitoring/monitor_polling_storage.go
@@ -581,7 +581,7 @@ func (m *Monitor) pollStorageWithNodes(ctx context.Context, instanceName string,
// Record metrics and check alerts for all storage devices
for _, storage := range allStorage {
- if m.metricsHistory != nil {
+ if m.metricsHistory != nil && !shouldSkipNativeMockStateMetricWrites() {
timestamp := time.Now()
m.metricsHistory.AddStorageMetric(storage.ID, "usage", storage.Usage, timestamp)
m.metricsHistory.AddStorageMetric(storage.ID, "used", float64(storage.Used), timestamp)
diff --git a/internal/monitoring/monitor_polling_vm.go b/internal/monitoring/monitor_polling_vm.go
index b3fd603cd5..c36fc85595 100644
--- a/internal/monitoring/monitor_polling_vm.go
+++ b/internal/monitoring/monitor_polling_vm.go
@@ -638,9 +638,12 @@ func (m *Monitor) pollVMsWithNodes(ctx context.Context, instanceName string, clu
m.state.UpdateVMsForInstance(instanceName, allVMs)
// Record guest metrics history for running VMs (enables sparkline/trends view)
- now := time.Now()
- for _, vm := range allVMs {
- if vm.Status == "running" {
+ if !shouldSkipNativeMockStateMetricWrites() {
+ now := time.Now()
+ for _, vm := range allVMs {
+ if vm.Status != "running" {
+ continue
+ }
m.metricsHistory.AddGuestMetric(vm.ID, "cpu", vm.CPU*100, now)
m.metricsHistory.AddGuestMetric(vm.ID, "memory", vm.Memory.Usage, now)
if vm.Disk.Usage >= 0 {
diff --git a/internal/monitoring/monitor_pve_guest_helpers.go b/internal/monitoring/monitor_pve_guest_helpers.go
index 8ea42521ff..e30e94eade 100644
--- a/internal/monitoring/monitor_pve_guest_helpers.go
+++ b/internal/monitoring/monitor_pve_guest_helpers.go
@@ -127,22 +127,28 @@ func (m *Monitor) recordGuestMetric(
diskRead, diskWrite, networkIn, networkOut int64,
now time.Time,
) {
- m.metricsHistory.AddGuestMetric(resourceID, "cpu", cpu, now)
- m.metricsHistory.AddGuestMetric(resourceID, "memory", memory, now)
- if diskUsage >= 0 {
- m.metricsHistory.AddGuestMetric(resourceID, "disk", diskUsage, now)
+ if m == nil || shouldSkipNativeMockStateMetricWrites() {
+ return
}
- if diskRead >= 0 {
- m.metricsHistory.AddGuestMetric(resourceID, "diskread", float64(diskRead), now)
- }
- if diskWrite >= 0 {
- m.metricsHistory.AddGuestMetric(resourceID, "diskwrite", float64(diskWrite), now)
- }
- if networkIn >= 0 {
- m.metricsHistory.AddGuestMetric(resourceID, "netin", float64(networkIn), now)
- }
- if networkOut >= 0 {
- m.metricsHistory.AddGuestMetric(resourceID, "netout", float64(networkOut), now)
+
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(resourceID, "cpu", cpu, now)
+ m.metricsHistory.AddGuestMetric(resourceID, "memory", memory, now)
+ if diskUsage >= 0 {
+ m.metricsHistory.AddGuestMetric(resourceID, "disk", diskUsage, now)
+ }
+ if diskRead >= 0 {
+ m.metricsHistory.AddGuestMetric(resourceID, "diskread", float64(diskRead), now)
+ }
+ if diskWrite >= 0 {
+ m.metricsHistory.AddGuestMetric(resourceID, "diskwrite", float64(diskWrite), now)
+ }
+ if networkIn >= 0 {
+ m.metricsHistory.AddGuestMetric(resourceID, "netin", float64(networkIn), now)
+ }
+ if networkOut >= 0 {
+ m.metricsHistory.AddGuestMetric(resourceID, "netout", float64(networkOut), now)
+ }
}
if m.metricsStore != nil {