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.

Keep absent host disk readings out of live charts and history

pulse-triage[bot]c93757fb4b11
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e031fa86c7..e655dc19d1 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -15,6 +15,16 @@
## Purpose
+### Accepted host reports preserve disk-reading presence
+
+An accepted host report is not evidence of a disk measurement. Disk history
+recording and live fallback share canonical first-filesystem admission:
+unavailable/absent readings stay absent while measured zero remains available.
+Enrollment, receipt freshness, removal, correlation and stored observations keep
+their existing semantics. The host disk recording and API presence regressions
+cover this distinction; they do not establish installed guest recovery.
+
+
### Command access is a named token-step choice, not a legacy option (21 October 2026)
The installer's command-access checkbox reads **Allow Pulse to run commands on
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 86758f19ed..68cbdea54e 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -21,6 +21,22 @@
## Purpose
+### Host-agent disk history distinguishes absence from zero
+
+History and full/infrastructure summary charts synthesize host-agent disk usage
+only when its canonical disk reading is present. An accepted report without a
+filesystem reading must not create a live 0% sample; a measured 0% remains
+available. A recorded disk series keeps its original values and timestamps,
+including when CPU has no history. Existing lease, error, query-selection and
+provider-aggregate contracts remain unchanged.
+
+`TestHostDiskUsageHistoryAndSummaryRespectPresence` exercises cold and recorded
+History (all/selected metrics), both summary routes and disk-only selection for
+missing, unavailable, measured-zero, low-percentage and nonzero readings on
+online/offline hosts. Browser proof must exercise the returned producer payload
+through the existing Machines drawer at desktop and narrow widths.
+
+
### Webhook deletion has an explicit committed acknowledgement
`DELETE /api/notifications/webhooks/{id}` returns `success: true` after saved and
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 3b9abdd4b6..f3babc1da0 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -17,6 +17,17 @@
## Purpose
+### Missing host-agent disk readings are not recorded as idle
+
+`ApplyHostReport` applies the canonical first-filesystem disk admission before
+writing host disk usage to recent memory or the persistent metrics store.
+Absent/unavailable inventory emits no disk sample; an observed zero still emits
+zero. Other accepted host fields and existing observations are not withdrawn,
+rewritten or deleted. No guest operation or collection/retry policy changes.
+`TestHostDiskUsageRecordingSkipsAbsenceAndPreservesZero` covers accepted absent,
+zero and absent-again reports, retained history and ordinary store reopen.
+
+
### Ended backup jobs do not supply missing guest verdicts
For multi-guest vzdump jobs, only an explicit guest finish or failure line
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index b9004a204e..1faf910f76 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -23,6 +23,18 @@ and sort the complete canonical change table while startup and ingestion wait.
## Purpose
+### Host disk usage retains explicit presence
+
+`HostDiskUsagePercent` shares the existing canonical first-filesystem admission
+with host metric projection, history recording and legacy live fallback.
+`HostView.DiskUsagePercent` returns the presence of the canonical disk metric,
+not the zero default of a missing scalar accessor. Provider aggregate readings
+need no agent filesystem inventory. Neither helper establishes freshness or
+changes selection/identity. `TestHostDiskUsagePercentMatchesCanonicalPresence`
+pins absent/invalid/zero/low readings, unchanged first-filesystem selection and
+provider aggregate zero.
+
+
### Drawer history follows current source authority
Resource drawers withdraw current chart fallbacks and cached live-only replies
diff --git a/internal/api/chartapi/service.go b/internal/api/chartapi/service.go
index 662c65648f..6d507582cf 100644
--- a/internal/api/chartapi/service.go
+++ b/internal/api/chartapi/service.go
@@ -362,10 +362,18 @@ func (r *Service) HandleCharts(w http.ResponseWriter, req *http.Request) {
if batchMetrics, ok := agentBatchMetrics[request.SQLResourceID]; ok {
oldestTimestamp = fillChartSeriesFromBatch(agentData[hID], batchMetrics, oldestTimestamp)
}
- if len(agentData[hID]["cpu"]) == 0 && hostAgentCanSupplyLiveChartFallback(h) {
- agentData[hID]["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: h.CPUPercent()}}
- agentData[hID]["memory"] = []MetricPoint{{Timestamp: currentTime, Value: h.MemoryPercent()}}
- agentData[hID]["disk"] = []MetricPoint{{Timestamp: currentTime, Value: h.DiskPercent()}}
+ if hostAgentCanSupplyLiveChartFallback(h) {
+ if len(agentData[hID]["cpu"]) == 0 {
+ agentData[hID]["cpu"] = []MetricPoint{{Timestamp: currentTime, Value: h.CPUPercent()}}
+ }
+ if len(agentData[hID]["memory"]) == 0 {
+ agentData[hID]["memory"] = []MetricPoint{{Timestamp: currentTime, Value: h.MemoryPercent()}}
+ }
+ if len(agentData[hID]["disk"]) == 0 {
+ if value, ok := h.DiskUsagePercent(); ok {
+ agentData[hID]["disk"] = []MetricPoint{{Timestamp: currentTime, Value: value}}
+ }
+ }
}
}
@@ -1997,7 +2005,7 @@ func (r *Service) HandleInfrastructureCharts(w http.ResponseWriter, req *http.Re
case "memory":
value = h.MemoryPercent()
case "disk":
- value = h.DiskPercent()
+ value, hasFallbackValue = h.DiskUsagePercent()
default:
hasFallbackValue = false
}
diff --git a/internal/api/chartapi/service_handlers_test.go b/internal/api/chartapi/service_handlers_test.go
index 27c57f422a..e360f0a076 100644
--- a/internal/api/chartapi/service_handlers_test.go
+++ b/internal/api/chartapi/service_handlers_test.go
@@ -206,7 +206,7 @@ func TestHandleCharts_UsesCanonicalMockUnifiedReadStateForVMwareHosts(t *testing
Hostname: "live-store-host-1",
CPUUsage: 11.0,
Memory: models.Memory{Usage: 22.0},
- Disks: []models.Disk{{Usage: 33.0}},
+ Disks: []models.Disk{{Total: 100, Used: 33, Usage: 33.0}},
Status: "online",
}}
syncTestResourceStore(t, monitor, state)
@@ -310,7 +310,7 @@ func TestHandleInfrastructureCharts_Lightweight(t *testing.T) {
Hostname: "host-one",
CPUUsage: 11.0,
Memory: models.Memory{Usage: 22.0},
- Disks: []models.Disk{{Usage: 33.0}},
+ Disks: []models.Disk{{Total: 100, Used: 33, Usage: 33.0}},
Status: "online",
}}
syncTestResourceStore(t, monitor, state)
@@ -393,7 +393,7 @@ func TestHandleInfrastructureCharts_MetricFilter(t *testing.T) {
Hostname: "host-one",
CPUUsage: 11.0,
Memory: models.Memory{Usage: 22.0},
- Disks: []models.Disk{{Usage: 33.0}},
+ Disks: []models.Disk{{Total: 100, Used: 33, Usage: 33.0}},
Status: "online",
}}
syncTestResourceStore(t, monitor, state)
@@ -448,7 +448,7 @@ func TestHandleInfrastructureCharts_UsesCanonicalMockUnifiedReadStateForVMwareHo
Hostname: "live-store-host-1",
CPUUsage: 11.0,
Memory: models.Memory{Usage: 22.0},
- Disks: []models.Disk{{Usage: 33.0}},
+ Disks: []models.Disk{{Total: 100, Used: 33, Usage: 33.0}},
Status: "online",
}}
syncTestResourceStore(t, monitor, state)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 1a70e11215..0a40eed941 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -27873,3 +27873,90 @@ func TestContract_ChartIndexFallbackPreservesObservations(t *testing.T) {
}
}
}
+
+func TestHostDiskUsageHistoryAndSummaryRespectPresence(t *testing.T) {
+ setMockModeForTest(t, false)
+ for _, tc := range []struct {
+ name string
+ disks []models.Disk
+ present bool
+ value float64
+ }{
+ {name: "absent"},
+ {name: "empty", disks: []models.Disk{}},
+ {name: "capacity unavailable", disks: []models.Disk{{Usage: 0}}},
+ {name: "unavailable", disks: []models.Disk{{Total: 100, Usage: -1}}},
+ {name: "measured zero", disks: []models.Disk{{Total: 100, Free: 100, Usage: 0}}, present: true},
+ {name: "small percent", disks: []models.Disk{{Total: 1000, Used: 2, Usage: 0.2}}, present: true, value: 0.2},
+ {name: "measured usage", disks: []models.Disk{{Total: 100, Used: 61, Usage: 61}}, present: true, value: 61},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ for _, stored := range []bool{false, true} {
+ for _, status := range []string{"online", "offline"} {
+ t.Run(status+map[bool]string{false: "/cold", true: "/recorded"}[stored], func(t *testing.T) {
+ monitor, state, history := newTestMonitor(t)
+ state.Hosts = []models.Host{{ID: "fixture-host", Hostname: "Disk presence host", Status: status, LastSeen: time.Now(), CPUUsage: 12, Memory: models.Memory{Total: 8192, Used: 2048, Usage: 25}, Disks: tc.disks}}
+ syncTestResourceStore(t, monitor, state)
+ recordedAt := time.Now().Add(-2 * time.Minute)
+ if stored {
+ history.AddGuestMetric("agent:fixture-host", "disk", 43, recordedAt)
+ }
+ router := &Router{monitor: monitor}
+ for _, path := range []string{"/api/metrics-store/history?resourceType=agent&resourceId=fixture-host&range=1h", "/api/metrics-store/history?resourceType=agent&resourceId=fixture-host&metric=disk&range=1h", "/api/charts?range=1h", "/api/charts/infrastructure?range=1h", "/api/charts/infrastructure?range=1h&metrics=disk"} {
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest(http.MethodGet, path, nil)
+ switch {
+ case strings.HasPrefix(path, "/api/metrics-store/history"):
+ router.handleMetricsHistory(rec, req)
+ case strings.HasPrefix(path, "/api/charts/infrastructure"):
+ router.handleInfrastructureCharts(rec, req)
+ default:
+ router.handleCharts(rec, req)
+ }
+ want := stored || (status == "online" && tc.present)
+ var payload struct {
+ Points []chartapi.MetricPoint `json:"points"`
+ Metrics map[string][]chartapi.MetricPoint `json:"metrics"`
+ AgentData map[string]map[string][]chartapi.MetricPoint `json:"agentData"`
+ }
+ // A wholly unmeasured history target keeps its existing no-source error;
+ // a missing metric must never turn into a successful zero sample.
+ if rec.Code == http.StatusServiceUnavailable && !want && strings.HasPrefix(path, "/api/metrics-store/history") {
+ continue
+ }
+ if rec.Code != http.StatusOK {
+ t.Fatalf("%s status %d: %s", path, rec.Code, rec.Body.String())
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil {
+ t.Fatal(err)
+ }
+ points := payload.Points
+ if !strings.Contains(path, "metric=disk") {
+ if payload.AgentData != nil {
+ points = payload.AgentData["fixture-host"]["disk"]
+ } else {
+ points = payload.Metrics["disk"]
+ }
+ }
+ if (len(points) > 0) != want {
+ t.Fatalf("%s disk presence=%v want=%v; %s", path, len(points) > 0, want, rec.Body.String())
+ }
+ if want {
+ value := tc.value
+ if stored {
+ value = 43
+ }
+ if len(points) != 1 || points[0].Value != value {
+ t.Fatalf("%s lost real reading: %+v want %v", path, points, value)
+ }
+ if stored && points[0].Timestamp != recordedAt.UnixMilli() {
+ t.Fatalf("%s replaced original recorded timestamp: %+v", path, points)
+ }
+ }
+ }
+ })
+ }
+ }
+ })
+ }
+}
diff --git a/internal/api/router.go b/internal/api/router.go
index 05c9663f75..d92ff447d3 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -6713,11 +6713,9 @@ func (r *Router) handleMetricsHistory(w http.ResponseWriter, req *http.Request)
if host != nil {
points["cpu"] = monitoring.MetricPoint{Timestamp: now, Value: host.CPUUsage}
points["memory"] = monitoring.MetricPoint{Timestamp: now, Value: host.Memory.Usage}
- diskPercent := float64(0)
- if len(host.Disks) > 0 {
- diskPercent = host.Disks[0].Usage
+ if diskPercent, ok := unifiedresources.HostDiskUsagePercent(host.Disks); ok {
+ points["disk"] = monitoring.MetricPoint{Timestamp: now, Value: diskPercent}
}
- points["disk"] = monitoring.MetricPoint{Timestamp: now, Value: diskPercent}
if temperature := models.HostSensorPrimaryCPUTemperatureCelsius(host.Sensors); temperature != nil {
points["temperature"] = monitoring.MetricPoint{Timestamp: now, Value: *temperature}
}
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index 6305f771b7..a5df94fa92 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -3837,10 +3837,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// Record host-agent metrics for sparkline charts.
hostMetricKey := fmt.Sprintf("agent:%s", host.ID)
- var hostDiskPercent float64
- if len(host.Disks) > 0 {
- hostDiskPercent = host.Disks[0].Usage
- }
+ hostDiskPercent, hasHostDiskUsage := unifiedresources.HostDiskUsagePercent(host.Disks)
hostTemperature := models.HostSensorPrimaryCPUTemperatureCelsius(host.Sensors)
hostGPUUtilization, hostGPUMemory, hostGPUTemperature := hostGPUMetrics(host.Sensors)
@@ -3850,7 +3847,9 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
if host.Memory.HasKnownUsage() {
m.metricsHistory.AddGuestMetric(hostMetricKey, "memory", host.Memory.Usage, now)
}
- m.metricsHistory.AddGuestMetric(hostMetricKey, "disk", hostDiskPercent, now)
+ if hasHostDiskUsage {
+ m.metricsHistory.AddGuestMetric(hostMetricKey, "disk", hostDiskPercent, now)
+ }
if hostTemperature != nil {
m.metricsHistory.AddGuestMetric(hostMetricKey, "temperature", *hostTemperature, now)
}
@@ -3885,7 +3884,9 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
if host.Memory.HasKnownUsage() {
m.metricsStore.Write("agent", host.ID, "memory", host.Memory.Usage, now)
}
- m.metricsStore.Write("agent", host.ID, "disk", hostDiskPercent, now)
+ if hasHostDiskUsage {
+ m.metricsStore.Write("agent", host.ID, "disk", hostDiskPercent, now)
+ }
if hostTemperature != nil {
m.metricsStore.Write("agent", host.ID, "temperature", *hostTemperature, now)
}
diff --git a/internal/monitoring/monitor_host_agents_test.go b/internal/monitoring/monitor_host_agents_test.go
index 31fd41d691..fc63622366 100644
--- a/internal/monitoring/monitor_host_agents_test.go
+++ b/internal/monitoring/monitor_host_agents_test.go
@@ -8753,3 +8753,75 @@ func TestMonitorDiscoveryEventsStayWithOwningOrganization(t *testing.T) {
}
}
}
+
+func TestHostDiskUsageRecordingSkipsAbsenceAndPreservesZero(t *testing.T) {
+ cfg := metrics.DefaultConfig(t.TempDir())
+ cfg.WriteBufferSize = 1
+ store, err := metrics.NewStore(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ closed := false
+ t.Cleanup(func() {
+ if !closed {
+ store.Close()
+ }
+ })
+ monitor := issue1654Monitor()
+ monitor.metricsHistory = NewMetricsHistory(20, time.Hour)
+ monitor.metricsStore = store
+ // Close drains ordinary queued writes before the final read; no polling for
+ // a favourable absence result and no changes to the store or its driver.
+ report := issue1654Report(time.Now().UTC())
+ report.Disks = nil
+ report.Metrics = agentshost.Metrics{CPUUsagePercent: 12, Memory: agentshost.MemoryMetric{TotalBytes: 8192, UsedBytes: 2048, Usage: 25}}
+ report.SequenceID = agentshost.FormatReportSequenceID("disk-presence", 1)
+ host, err := monitor.ApplyHostReport(report, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if points := monitor.metricsHistory.GetGuestMetrics("agent:"+host.ID, "disk", time.Hour); len(points) != 0 {
+ t.Fatalf("absent inventory recorded disk zero: %+v", points)
+ }
+ recordedAt := time.Now().Add(-2 * time.Minute)
+ monitor.metricsHistory.AddGuestMetric("agent:"+host.ID, "disk", 43, recordedAt)
+ store.Write("agent", host.ID, "disk", 43, recordedAt)
+ report.Disks = []agentshost.Disk{{Device: "/dev/sda", Mountpoint: "/", Type: "ext4", TotalBytes: 100, FreeBytes: 100, Usage: 0}}
+ report.SequenceID = agentshost.FormatReportSequenceID("disk-presence", 2)
+ report.Timestamp = time.Now().UTC()
+ if _, err := monitor.ApplyHostReport(report, nil); err != nil {
+ t.Fatal(err)
+ }
+ report.Disks = nil
+ report.SequenceID = agentshost.FormatReportSequenceID("disk-presence", 3)
+ report.Timestamp = time.Now().UTC()
+ if _, err := monitor.ApplyHostReport(report, nil); err != nil {
+ t.Fatal(err)
+ }
+ points := monitor.metricsHistory.GetGuestMetrics("agent:"+host.ID, "disk", time.Hour)
+ if len(points) != 2 || points[0].Value != 43 || points[1].Value != 0 || !points[0].Timestamp.Equal(recordedAt) {
+ t.Fatalf("absence changed recorded/real-zero observations: %+v", points)
+ }
+ if err := store.Close(); err != nil {
+ t.Fatal(err)
+ }
+ closed = true
+ reopened, err := metrics.NewStore(cfg)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer reopened.Close()
+ saved, err := reopened.Query("agent", host.ID, "disk", recordedAt.Add(-time.Minute), time.Now().Add(time.Minute), 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(saved) != 2 || saved[0].Value != 43 || saved[1].Value != 0 {
+ t.Fatalf("persisted disk series invented or lost a sample: %+v", saved)
+ }
+ if saved[0].Timestamp.UnixMilli() != recordedAt.UnixMilli() {
+ t.Fatalf("persisted observation time changed: %+v", saved[0])
+ }
+ if got := monitor.HostsSnapshot(); len(got) != 1 || len(got[0].Disks) != 0 || got[0].Memory.Total != 8192 {
+ t.Fatalf("accepted no-disk report was not retained: %+v", got)
+ }
+}
diff --git a/internal/unifiedresources/host_disk_usage.go b/internal/unifiedresources/host_disk_usage.go
new file mode 100644
index 0000000000..3bfe93ba4f
--- /dev/null
+++ b/internal/unifiedresources/host_disk_usage.go
@@ -0,0 +1,21 @@
+package unifiedresources
+
+import "github.com/rcourtman/pulse-go-rewrite/internal/models"
+
+// HostDiskUsagePercent uses the same first-filesystem admission as the
+// canonical host metric. Missing or unavailable inventory is not measured zero.
+func HostDiskUsagePercent(disks []models.Disk) (float64, bool) {
+ if len(disks) == 0 || !hasObservedDiskUsage(disks[0]) {
+ return 0, false
+ }
+ return disks[0].Usage, true
+}
+
+// DiskUsagePercent preserves canonical metric presence, including provider
+// readings without agent filesystem inventory. Reporting freshness is separate.
+func (v HostView) DiskUsagePercent() (float64, bool) {
+ if v.r == nil || v.r.Metrics == nil || v.r.Metrics.Disk == nil {
+ return 0, false
+ }
+ return v.r.Metrics.Disk.Percent, true
+}
diff --git a/internal/unifiedresources/metrics.go b/internal/unifiedresources/metrics.go
index e691009e02..737cb71ff8 100644
--- a/internal/unifiedresources/metrics.go
+++ b/internal/unifiedresources/metrics.go
@@ -112,12 +112,9 @@ func buildHostMetricPayload(
percent := percentFromReportedPercent(memory.Usage)
metrics.Memory = &MetricValue{Used: &memory.Used, Total: &memory.Total, Percent: percent, Unit: "bytes", Source: source, Observation: memory.Observation}
}
- if len(disks) > 0 {
+ if percent, ok := HostDiskUsagePercent(disks); ok {
disk := disks[0]
- if hasObservedDiskUsage(disk) {
- percent := percentFromReportedPercent(disk.Usage)
- metrics.Disk = &MetricValue{Used: &disk.Used, Total: &disk.Total, Percent: percent, Unit: "bytes", Source: source}
- }
+ metrics.Disk = &MetricValue{Used: &disk.Used, Total: &disk.Total, Percent: percent, Unit: "bytes", Source: source}
}
setNetworkAndDiskIOMetricsHost(metrics, netInRate, netOutRate, diskReadRate, diskWriteRate, source)
return metrics
diff --git a/internal/unifiedresources/metrics_test.go b/internal/unifiedresources/metrics_test.go
index cd487ebe8f..d035bbedfa 100644
--- a/internal/unifiedresources/metrics_test.go
+++ b/internal/unifiedresources/metrics_test.go
@@ -663,3 +663,44 @@ func TestGuestMemoryClusterResourcesIsTypeAware(t *testing.T) {
}
}
}
+
+func TestHostDiskUsagePercentMatchesCanonicalPresence(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ disks []models.Disk
+ present bool
+ value float64
+ }{
+ {name: "absent"},
+ {name: "no capacity", disks: []models.Disk{{}}},
+ {name: "unavailable", disks: []models.Disk{{Total: 100, Usage: -1}}},
+ {name: "invalid", disks: []models.Disk{{Total: 100, Usage: math.NaN()}}},
+ {name: "infinite", disks: []models.Disk{{Total: 100, Usage: math.Inf(1)}}},
+ {name: "inconsistent bytes", disks: []models.Disk{{Total: 100, Used: 101, Usage: 0}}},
+ {name: "zero", disks: []models.Disk{{Total: 100, Free: 100}}, present: true},
+ {name: "small percent", disks: []models.Disk{{Total: 1000, Used: 2, Usage: 0.2}}, present: true, value: 0.2},
+ {name: "first filesystem only", disks: []models.Disk{{}, {Total: 100, Usage: 25}}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ value, present := HostDiskUsagePercent(tc.disks)
+ if present != tc.present || value != tc.value {
+ t.Fatalf("disk usage = %v/%v, want %v/%v", value, present, tc.value, tc.present)
+ }
+ resource, _ := resourceFromHost(models.Host{ID: "disk-host", Disks: tc.disks})
+ viewValue, viewPresent := NewHostView(&resource).DiskUsagePercent()
+ if viewPresent != present || viewValue != value {
+ t.Fatalf("canonical view = %v/%v, report = %v/%v", viewValue, viewPresent, value, present)
+ }
+ })
+ }
+ for _, resource := range []*Resource{nil, {}, {Metrics: &ResourceMetrics{}}} {
+ if _, present := NewHostView(resource).DiskUsagePercent(); present {
+ t.Fatal("missing canonical metric became zero")
+ }
+ }
+ // Non-agent providers can report an aggregate without an agent inventory.
+ provider := &Resource{Metrics: &ResourceMetrics{Disk: &MetricValue{Percent: 0}}}
+ if value, present := NewHostView(provider).DiskUsagePercent(); !present || value != 0 {
+ t.Fatal("provider's explicit zero requires no agent inventory")
+ }
+}