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.

Implement VMware metrics history floor

rcourtman412c9821fc23
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 451228c8bc..1d1b83cd3c 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -405,3 +405,14 @@ may collect VI JSON overall status, active alarms, recent tasks, and VM
snapshot counts, but they must project those reads onto shared canonical
resources plus shared alert/resource history metadata instead of persisting a
VMware-only signal cache, event log, or provider-specific incident timeline.
+That same monitoring boundary now also owns VMware performance telemetry on
+the shared chart/history paths. `internal/vmware/client_metrics.go` must use
+the VI JSON `PerformanceManager` read surfaces to resolve current-support,
+available counters, and current samples from the supported `vCenter` release
+floor; `internal/vmware/provider.go` must project ESXi host readings onto
+canonical `agent` `ResourceMetrics` and VM readings onto canonical `vm`
+`ResourceMetrics`; and `internal/monitoring/monitor.go` must sync those
+metrics into the existing shared `agent` and `vm` history stores. Pulse must
+not add a VMware-only charts cache, host history model, or VM metrics store
+just because vSphere performance collection uses a different API family from
+inventory and alarm reads.
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 7aee09f6f5..667e3eaf35 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -256,6 +256,26 @@ func TestUnifiedAgentMetricsUseCanonicalHostHistoryPath(t *testing.T) {
}
}
+func TestUnifiedVMMetricsUseCanonicalVMHistoryPath(t *testing.T) {
+ data, err := os.ReadFile("monitor.go")
+ if err != nil {
+ t.Fatalf("failed to read monitor.go: %v", err)
+ }
+ source := string(data)
+ requiredSnippets := []string{
+ "m.syncUnifiedVMMetrics(store)",
+ `if target == nil || target.ResourceType != "vm" || strings.TrimSpace(target.ResourceID) == "" {`,
+ `if source == unifiedresources.SourceProxmox {`,
+ `m.metricsStore.Write("vm", targetID, "cpu", value, now)`,
+ `m.metricsStore.Write("vm", targetID, "diskwrite", metric.Value, now)`,
+ }
+ for _, snippet := range requiredSnippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("monitor.go must contain %q", snippet)
+ }
+ }
+}
+
func TestUnifiedPhysicalDiskMetricsUseCanonicalDiskHistoryPath(t *testing.T) {
data, err := os.ReadFile("monitor.go")
if err != nil {
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index f66d575ee3..dae10a9229 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -4144,6 +4144,7 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {
if atomicStore, ok := store.(AtomicSnapshotResourceStore); ok {
atomicStore.PopulateSnapshotAndSupplemental(snapshotForStore, recordsBySource)
m.syncUnifiedAgentMetrics(store)
+ m.syncUnifiedVMMetrics(store)
m.syncUnifiedStorageMetrics(store)
m.syncUnifiedPhysicalDiskMetrics(store)
m.syncUnifiedAppContainerMetrics(store)
@@ -4177,6 +4178,7 @@ func (m *Monitor) updateResourceStore(state models.StateSnapshot) {
}
m.syncUnifiedAgentMetrics(store)
+ m.syncUnifiedVMMetrics(store)
m.syncUnifiedStorageMetrics(store)
m.syncUnifiedPhysicalDiskMetrics(store)
m.syncUnifiedAppContainerMetrics(store)
@@ -4287,6 +4289,115 @@ func (m *Monitor) syncUnifiedAgentMetrics(store ResourceStoreInterface) {
}
}
+func (m *Monitor) syncUnifiedVMMetrics(store ResourceStoreInterface) {
+ if store == nil || (m.metricsHistory == nil && m.metricsStore == nil) {
+ return
+ }
+
+ resolver, ok := store.(MetricsTargetResourceStore)
+ if !ok {
+ return
+ }
+
+ now := time.Now()
+ seenTargets := make(map[string]struct{})
+ for _, resource := range store.GetAll() {
+ if resource.Type != unifiedresources.ResourceTypeVM || resource.Metrics == nil {
+ continue
+ }
+
+ hasNativeVMWriter := false
+ for _, source := range resource.Sources {
+ if source == unifiedresources.SourceProxmox {
+ hasNativeVMWriter = true
+ break
+ }
+ }
+ if hasNativeVMWriter {
+ continue
+ }
+
+ target := resolver.MetricsTargetForResource(resource.ID)
+ if target == nil || target.ResourceType != "vm" || strings.TrimSpace(target.ResourceID) == "" {
+ continue
+ }
+ targetID := strings.TrimSpace(target.ResourceID)
+ if _, ok := seenTargets[targetID]; ok {
+ continue
+ }
+ seenTargets[targetID] = struct{}{}
+
+ if metric := resource.Metrics.CPU; metric != nil {
+ value := metric.Percent
+ if value == 0 {
+ value = metric.Value
+ }
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "cpu", value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "cpu", value, now)
+ }
+ }
+
+ if metric := resource.Metrics.Memory; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {
+ value := metric.Percent
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "memory", value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "memory", value, now)
+ }
+ }
+
+ if metric := resource.Metrics.Disk; metric != nil && (metric.Total != nil || metric.Percent > 0 || metric.Used != nil) {
+ value := metric.Percent
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "disk", value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "disk", value, now)
+ }
+ }
+
+ if metric := resource.Metrics.NetIn; metric != nil {
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "netin", metric.Value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "netin", metric.Value, now)
+ }
+ }
+
+ if metric := resource.Metrics.NetOut; metric != nil {
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "netout", metric.Value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "netout", metric.Value, now)
+ }
+ }
+
+ if metric := resource.Metrics.DiskRead; metric != nil {
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "diskread", metric.Value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "diskread", metric.Value, now)
+ }
+ }
+
+ if metric := resource.Metrics.DiskWrite; metric != nil {
+ if m.metricsHistory != nil {
+ m.metricsHistory.AddGuestMetric(targetID, "diskwrite", metric.Value, now)
+ }
+ if m.metricsStore != nil {
+ m.metricsStore.Write("vm", targetID, "diskwrite", metric.Value, now)
+ }
+ }
+ }
+}
+
func (m *Monitor) syncUnifiedStorageMetrics(store ResourceStoreInterface) {
if store == nil || (m.metricsHistory == nil && m.metricsStore == nil) {
return
diff --git a/internal/monitoring/monitor_polling_test.go b/internal/monitoring/monitor_polling_test.go
index 578e1b205f..ea2f9f04ef 100644
--- a/internal/monitoring/monitor_polling_test.go
+++ b/internal/monitoring/monitor_polling_test.go
@@ -14,6 +14,7 @@ import (
"github.com/rcourtman/pulse-go-rewrite/internal/storagehealth"
"github.com/rcourtman/pulse-go-rewrite/internal/truenas"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/internal/vmware"
"github.com/rcourtman/pulse-go-rewrite/pkg/metrics"
"github.com/rcourtman/pulse-go-rewrite/pkg/pbs"
"github.com/rcourtman/pulse-go-rewrite/pkg/pmg"
@@ -112,6 +113,14 @@ type testMonitorSupplementalProvider struct {
lastRequestedOrg string
}
+func ptrFloat64(value float64) *float64 {
+ return &value
+}
+
+func ptrInt64(value int64) *int64 {
+ return &value
+}
+
func (p *testMonitorSupplementalProvider) SupplementalRecords(_ *Monitor, orgID string) []unifiedresources.IngestRecord {
p.lastRequestedOrg = orgID
records := p.recordsByOrg[orgID]
@@ -598,6 +607,166 @@ func TestSyncUnifiedAgentMetricsRecordsTrueNASHostHistory(t *testing.T) {
}
}
+func TestSyncUnifiedAgentMetricsRecordsVMwareHostHistory(t *testing.T) {
+ previous := vmware.IsFeatureEnabled()
+ vmware.SetFeatureEnabled(true)
+ t.Cleanup(func() {
+ vmware.SetFeatureEnabled(previous)
+ })
+
+ cfg := metrics.DefaultConfig(t.TempDir())
+ store, err := metrics.NewStore(cfg)
+ if err != nil {
+ t.Fatalf("metrics.NewStore() error = %v", err)
+ }
+ defer func() { _ = store.Close() }()
+
+ resourceStore := unifiedresources.NewMonitorAdapter(nil)
+ records := vmware.NewProvider(vmware.InventorySnapshot{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ VCenterHost: "vc.lab.local",
+ CollectedAt: time.Date(2026, time.March, 30, 18, 15, 0, 0, time.UTC),
+ Hosts: []vmware.InventoryHost{{
+ Host: "host-101",
+ Name: "esxi-01.lab.local",
+ ConnectionState: "CONNECTED",
+ PowerState: "POWERED_ON",
+ HostUUID: "uuid-host-1",
+ Metrics: &vmware.InventoryMetrics{
+ CPUPercent: ptrFloat64(21.4),
+ MemoryPercent: ptrFloat64(63.2),
+ MemoryUsedBytes: ptrInt64(27144105984),
+ MemoryTotalBytes: ptrInt64(42949672960),
+ NetInBytesPerSecond: ptrFloat64(1024),
+ NetOutBytesPerSecond: ptrFloat64(2048),
+ DiskReadBytesPerSecond: ptrFloat64(4096),
+ DiskWriteBytesPerSecond: ptrFloat64(8192),
+ },
+ }},
+ }).Records()
+ resourceStore.PopulateSnapshotAndSupplemental(models.StateSnapshot{}, map[unifiedresources.DataSource][]unifiedresources.IngestRecord{
+ unifiedresources.SourceVMware: records,
+ })
+
+ monitor := &Monitor{
+ resourceStore: resourceStore,
+ metricsHistory: NewMetricsHistory(1024, 24*time.Hour),
+ metricsStore: store,
+ }
+
+ monitor.syncUnifiedAgentMetrics(resourceStore)
+
+ var systemResourceID string
+ for _, resource := range resourceStore.GetAll() {
+ if resource.Type == unifiedresources.ResourceTypeAgent && resource.Name == "esxi-01.lab.local" {
+ systemResourceID = resource.ID
+ break
+ }
+ }
+ if systemResourceID == "" {
+ t.Fatal("expected VMware host resource in unified store")
+ }
+
+ target := resourceStore.MetricsTargetForResource(systemResourceID)
+ if target == nil || target.ResourceType != "agent" || target.ResourceID != "vc-1:host:host-101" {
+ t.Fatalf("unexpected agent metrics target %+v", target)
+ }
+
+ inMemory := monitor.GetGuestMetrics("agent:vc-1:host:host-101", time.Hour)
+ if got := len(inMemory["cpu"]); got == 0 {
+ t.Fatalf("expected in-memory cpu history for VMware host")
+ }
+ if got := len(inMemory["netin"]); got == 0 {
+ t.Fatalf("expected in-memory network history for VMware host")
+ }
+
+ storeBacked := monitor.GetGuestMetricsForChart("agent:vc-1:host:host-101", "agent", "vc-1:host:host-101", 7*24*time.Hour)
+ if got := len(storeBacked["cpu"]); got == 0 {
+ t.Fatalf("expected persisted cpu history for VMware host")
+ }
+}
+
+func TestSyncUnifiedVMMetricsRecordsVMwareVMHistory(t *testing.T) {
+ previous := vmware.IsFeatureEnabled()
+ vmware.SetFeatureEnabled(true)
+ t.Cleanup(func() {
+ vmware.SetFeatureEnabled(previous)
+ })
+
+ cfg := metrics.DefaultConfig(t.TempDir())
+ store, err := metrics.NewStore(cfg)
+ if err != nil {
+ t.Fatalf("metrics.NewStore() error = %v", err)
+ }
+ defer func() { _ = store.Close() }()
+
+ resourceStore := unifiedresources.NewMonitorAdapter(nil)
+ records := vmware.NewProvider(vmware.InventorySnapshot{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ VCenterHost: "vc.lab.local",
+ CollectedAt: time.Date(2026, time.March, 30, 18, 15, 0, 0, time.UTC),
+ VMs: []vmware.InventoryVM{{
+ VM: "vm-201",
+ Name: "app-01",
+ PowerState: "POWERED_ON",
+ CPUCount: 4,
+ MemorySizeMiB: 8192,
+ Metrics: &vmware.InventoryMetrics{
+ CPUPercent: ptrFloat64(38.1),
+ MemoryPercent: ptrFloat64(57.5),
+ MemoryUsedBytes: ptrInt64(5033164800),
+ MemoryTotalBytes: ptrInt64(8589934592),
+ NetInBytesPerSecond: ptrFloat64(512),
+ NetOutBytesPerSecond: ptrFloat64(768),
+ DiskReadBytesPerSecond: ptrFloat64(1536),
+ DiskWriteBytesPerSecond: ptrFloat64(2048),
+ },
+ }},
+ }).Records()
+ resourceStore.PopulateSnapshotAndSupplemental(models.StateSnapshot{}, map[unifiedresources.DataSource][]unifiedresources.IngestRecord{
+ unifiedresources.SourceVMware: records,
+ })
+
+ monitor := &Monitor{
+ resourceStore: resourceStore,
+ metricsHistory: NewMetricsHistory(1024, 24*time.Hour),
+ metricsStore: store,
+ }
+
+ monitor.syncUnifiedVMMetrics(resourceStore)
+
+ var vmResourceID string
+ for _, resource := range resourceStore.GetAll() {
+ if resource.Type == unifiedresources.ResourceTypeVM && resource.Name == "app-01" {
+ vmResourceID = resource.ID
+ break
+ }
+ }
+ if vmResourceID == "" {
+ t.Fatal("expected VMware VM resource in unified store")
+ }
+
+ target := resourceStore.MetricsTargetForResource(vmResourceID)
+ if target == nil || target.ResourceType != "vm" || target.ResourceID != "vc-1:vm:vm-201" {
+ t.Fatalf("unexpected vm metrics target %+v", target)
+ }
+
+ inMemory := monitor.GetGuestMetrics("vc-1:vm:vm-201", time.Hour)
+ if got := len(inMemory["cpu"]); got == 0 {
+ t.Fatalf("expected in-memory cpu history for VMware VM")
+ }
+ if got := len(inMemory["netin"]); got == 0 {
+ t.Fatalf("expected in-memory network history for VMware VM")
+ }
+
+ storeBacked := monitor.GetGuestMetricsForChart("vc-1:vm:vm-201", "vm", "vc-1:vm:vm-201", 7*24*time.Hour)
+ if got := len(storeBacked["cpu"]); got == 0 {
+ t.Fatalf("expected persisted cpu history for VMware VM")
+ }
+}
+
func TestSyncUnifiedPhysicalDiskMetricsRecordsTrueNASDiskHistory(t *testing.T) {
previous := truenas.IsFeatureEnabled()
truenas.SetFeatureEnabled(true)
diff --git a/internal/vmware/client.go b/internal/vmware/client.go
index 21fbb85972..2139894d94 100644
--- a/internal/vmware/client.go
+++ b/internal/vmware/client.go
@@ -94,6 +94,11 @@ type Client struct {
password string
}
+type viJSONServiceContentRefs struct {
+ SessionManagerMoID string
+ PerfManagerMoID string
+}
+
// NewClient constructs a VMware client from saved connection input.
func NewClient(cfg ClientConfig) (*Client, error) {
baseURL, err := normalizeBaseURL(cfg.Host, cfg.Port)
@@ -142,15 +147,19 @@ func (c *Client) TestConnection(ctx context.Context) (*InventorySummary, error)
if err != nil {
return nil, err
}
- release, sessionManagerMoID, err := c.resolveVIJSONRelease(ctx)
+ release, refs, err := c.resolveVIJSONRelease(ctx)
+ if err != nil {
+ return nil, err
+ }
+ sessionID, err := c.loginVIJSON(ctx, release, refs.SessionManagerMoID)
if err != nil {
return nil, err
}
- sessionID, err := c.loginVIJSON(ctx, release, sessionManagerMoID)
+ perfCounters, err := c.loadPerfCounterCatalog(ctx, release, sessionID, refs.PerfManagerMoID)
if err != nil {
return nil, err
}
- if err := c.validateSignalFloor(ctx, release, sessionID, inventory); err != nil {
+ if err := c.validateSignalFloor(ctx, release, sessionID, refs.PerfManagerMoID, inventory, perfCounters); err != nil {
return nil, err
}
return &InventorySummary{
@@ -168,15 +177,19 @@ func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, erro
if err != nil {
return nil, err
}
- release, sessionManagerMoID, err := c.resolveVIJSONRelease(ctx)
+ release, refs, err := c.resolveVIJSONRelease(ctx)
if err != nil {
return nil, err
}
- sessionID, err := c.loginVIJSON(ctx, release, sessionManagerMoID)
+ sessionID, err := c.loginVIJSON(ctx, release, refs.SessionManagerMoID)
if err != nil {
return nil, err
}
- if err := c.enrichInventorySnapshot(ctx, release, sessionID, inventory); err != nil {
+ perfCounters, err := c.loadPerfCounterCatalog(ctx, release, sessionID, refs.PerfManagerMoID)
+ if err != nil {
+ return nil, err
+ }
+ if err := c.enrichInventorySnapshot(ctx, release, sessionID, refs.PerfManagerMoID, perfCounters, inventory); err != nil {
return nil, err
}
inventory.CollectedAt = time.Now().UTC()
@@ -319,61 +332,66 @@ func (c *Client) listAutomationResources(
return nil
}
-func (c *Client) resolveVIJSONRelease(ctx context.Context) (string, string, error) {
+func (c *Client) resolveVIJSONRelease(ctx context.Context) (string, viJSONServiceContentRefs, error) {
releases := []string{"9.0.0.0", "8.0.3", "8.0.2.0", "8.0.1.0"}
var lastErr error
for _, release := range releases {
- moID, err := c.fetchSessionManagerMoID(ctx, release)
+ refs, err := c.fetchVIJSONServiceContentRefs(ctx, release)
if err == nil {
- return release, moID, nil
+ return release, refs, nil
}
lastErr = err
connectionErr, ok := err.(*ConnectionError)
if !ok || connectionErr.Category != "endpoint" {
- return "", "", err
+ return "", viJSONServiceContentRefs{}, err
}
}
if lastErr != nil {
- return "", "", lastErr
+ return "", viJSONServiceContentRefs{}, lastErr
}
- return "", "", &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API release negotiation failed"}
+ return "", viJSONServiceContentRefs{}, &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API release negotiation failed"}
}
-func (c *Client) fetchSessionManagerMoID(ctx context.Context, release string) (string, error) {
+func (c *Client) fetchVIJSONServiceContentRefs(ctx context.Context, release string) (viJSONServiceContentRefs, error) {
endpoint := fmt.Sprintf("%s/sdk/vim25/%s/ServiceInstance/ServiceInstance/content", c.baseURL.String(), release)
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil)
if err != nil {
- return "", fmt.Errorf("build vi-json service instance request: %w", err)
+ return viJSONServiceContentRefs{}, fmt.Errorf("build vi-json service instance request: %w", err)
}
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
- return "", classifyTransportError("vi-json service content", err)
+ return viJSONServiceContentRefs{}, classifyTransportError("vi-json service content", err)
}
defer resp.Body.Close()
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
if readErr != nil {
- return "", fmt.Errorf("read vi-json service content response: %w", readErr)
+ return viJSONServiceContentRefs{}, fmt.Errorf("read vi-json service content response: %w", readErr)
}
if resp.StatusCode == http.StatusNotFound {
- return "", &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware VI JSON API release %s is unavailable", release)}
+ return viJSONServiceContentRefs{}, &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware VI JSON API release %s is unavailable", release)}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- return "", &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware VI JSON API service-instance request failed with HTTP %d", resp.StatusCode)}
+ return viJSONServiceContentRefs{}, &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware VI JSON API service-instance request failed with HTTP %d", resp.StatusCode)}
}
var payload struct {
- SessionManager struct {
- Value string `json:"value"`
- } `json:"sessionManager"`
+ SessionManager viJSONReference `json:"sessionManager"`
+ PerfManager viJSONReference `json:"perfManager"`
}
if err := json.Unmarshal(body, &payload); err != nil {
- return "", &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API service-instance response was not valid JSON"}
+ return viJSONServiceContentRefs{}, &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API service-instance response was not valid JSON"}
+ }
+ refs := viJSONServiceContentRefs{
+ SessionManagerMoID: strings.TrimSpace(payload.SessionManager.Value),
+ PerfManagerMoID: strings.TrimSpace(payload.PerfManager.Value),
+ }
+ if refs.SessionManagerMoID == "" {
+ return viJSONServiceContentRefs{}, &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API service-instance response did not include a session manager reference"}
}
- moID := strings.TrimSpace(payload.SessionManager.Value)
- if moID == "" {
- return "", &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API service-instance response did not include a session manager reference"}
+ if refs.PerfManagerMoID == "" {
+ return viJSONServiceContentRefs{}, &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API service-instance response did not include a performance manager reference"}
}
- return moID, nil
+ return refs, nil
}
func (c *Client) loginVIJSON(ctx context.Context, release string, sessionManagerMoID string) (string, error) {
diff --git a/internal/vmware/client_metrics.go b/internal/vmware/client_metrics.go
new file mode 100644
index 0000000000..9864d07a0a
--- /dev/null
+++ b/internal/vmware/client_metrics.go
@@ -0,0 +1,492 @@
+package vmware
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "io"
+ "math"
+ "net/http"
+ "strings"
+)
+
+type perfCounterCatalog struct {
+ idsByKey map[string]int
+}
+
+type perfCounterDefinition struct {
+ logical string
+ group string
+ name string
+ rollup string
+}
+
+type viJSONPerfCounterInfo struct {
+ Key int `json:"key"`
+ GroupInfo viJSONElementDescription `json:"groupInfo"`
+ NameInfo viJSONElementDescription `json:"nameInfo"`
+ RollupType string `json:"rollupType"`
+}
+
+type viJSONElementDescription struct {
+ Key string `json:"key"`
+}
+
+type viJSONPerfProviderSummary struct {
+ CurrentSupported bool `json:"currentSupported"`
+ RefreshRate int `json:"refreshRate"`
+}
+
+type viJSONPerfMetricID struct {
+ CounterID int `json:"counterId"`
+ Instance string `json:"instance"`
+}
+
+type viJSONPerfEntityMetric struct {
+ Entity viJSONReference `json:"entity"`
+ SampleInfo []viJSONPerfSampleInfo `json:"sampleInfo"`
+ Value []viJSONPerfMetricSeries `json:"value"`
+}
+
+type viJSONPerfSampleInfo struct {
+ Interval int `json:"interval"`
+}
+
+type viJSONPerfMetricSeries struct {
+ ID viJSONPerfMetricID `json:"id"`
+ Value []int64 `json:"value"`
+}
+
+type perfMetricAccumulator struct {
+ sum float64
+ count int
+}
+
+const (
+ vmwarePerfLogicalCPUUsage = "cpu_usage"
+ vmwarePerfLogicalMemoryUsage = "memory_usage"
+ vmwarePerfLogicalHostMemoryTotal = "host_memory_total"
+ vmwarePerfLogicalNetIn = "net_in"
+ vmwarePerfLogicalNetOut = "net_out"
+ vmwarePerfLogicalDiskRead = "disk_read"
+ vmwarePerfLogicalDiskWrite = "disk_write"
+)
+
+var vmwareHostPerfCounters = []perfCounterDefinition{
+ {logical: vmwarePerfLogicalCPUUsage, group: "cpu", name: "usage", rollup: "average"},
+ {logical: vmwarePerfLogicalMemoryUsage, group: "mem", name: "usage", rollup: "average"},
+ {logical: vmwarePerfLogicalHostMemoryTotal, group: "mem", name: "totalCapacity", rollup: "average"},
+ {logical: vmwarePerfLogicalNetIn, group: "net", name: "bytesRx", rollup: "average"},
+ {logical: vmwarePerfLogicalNetOut, group: "net", name: "bytesTx", rollup: "average"},
+ {logical: vmwarePerfLogicalDiskRead, group: "disk", name: "read", rollup: "average"},
+ {logical: vmwarePerfLogicalDiskWrite, group: "disk", name: "write", rollup: "average"},
+}
+
+var vmwareVMPerfCounters = []perfCounterDefinition{
+ {logical: vmwarePerfLogicalCPUUsage, group: "cpu", name: "usage", rollup: "average"},
+ {logical: vmwarePerfLogicalMemoryUsage, group: "mem", name: "usage", rollup: "average"},
+ {logical: vmwarePerfLogicalNetIn, group: "net", name: "bytesRx", rollup: "average"},
+ {logical: vmwarePerfLogicalNetOut, group: "net", name: "bytesTx", rollup: "average"},
+ {logical: vmwarePerfLogicalDiskRead, group: "disk", name: "read", rollup: "average"},
+ {logical: vmwarePerfLogicalDiskWrite, group: "disk", name: "write", rollup: "average"},
+}
+
+func (c *Client) loadPerfCounterCatalog(ctx context.Context, release, sessionID, perfManagerMoID string) (perfCounterCatalog, error) {
+ perfManagerMoID = strings.TrimSpace(perfManagerMoID)
+ if perfManagerMoID == "" {
+ return perfCounterCatalog{}, &ConnectionError{Category: "endpoint", Message: "VMware VI JSON API service-instance response did not include a performance manager reference"}
+ }
+
+ var counters []viJSONPerfCounterInfo
+ path := fmt.Sprintf("/sdk/vim25/%s/PerformanceManager/%s/perfCounter", release, perfManagerMoID)
+ if err := c.getVIJSONJSON(ctx, sessionID, path, "vmware performance counter catalog", &counters); err != nil {
+ return perfCounterCatalog{}, err
+ }
+
+ catalog := perfCounterCatalog{idsByKey: make(map[string]int, len(counters))}
+ for _, counter := range counters {
+ if counter.Key <= 0 {
+ continue
+ }
+ key := perfCounterCatalogKey(counter.GroupInfo.Key, counter.NameInfo.Key, counter.RollupType)
+ if key == "" {
+ continue
+ }
+ catalog.idsByKey[key] = counter.Key
+ }
+ return catalog, nil
+}
+
+func (c *Client) collectHostPerformanceMetrics(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ perfCounters perfCounterCatalog,
+ host InventoryHost,
+) (*InventoryMetrics, error) {
+ return c.collectEntityPerformanceMetrics(
+ ctx,
+ release,
+ sessionID,
+ perfManagerMoID,
+ perfCounters,
+ "HostSystem",
+ host.Host,
+ vmwareHostPerfCounters,
+ 0,
+ )
+}
+
+func (c *Client) collectVMPerformanceMetrics(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ perfCounters perfCounterCatalog,
+ vm InventoryVM,
+) (*InventoryMetrics, error) {
+ var configuredMemoryBytes int64
+ if vm.MemorySizeMiB > 0 {
+ configuredMemoryBytes = vm.MemorySizeMiB * 1024 * 1024
+ }
+ return c.collectEntityPerformanceMetrics(
+ ctx,
+ release,
+ sessionID,
+ perfManagerMoID,
+ perfCounters,
+ "VirtualMachine",
+ vm.VM,
+ vmwareVMPerfCounters,
+ configuredMemoryBytes,
+ )
+}
+
+func (c *Client) collectEntityPerformanceMetrics(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ perfCounters perfCounterCatalog,
+ entityType string,
+ entityMoID string,
+ definitions []perfCounterDefinition,
+ fallbackMemoryTotalBytes int64,
+) (*InventoryMetrics, error) {
+ entityMoID = strings.TrimSpace(entityMoID)
+ if entityMoID == "" {
+ return nil, nil
+ }
+
+ summary, err := c.queryPerfProviderSummary(ctx, release, sessionID, perfManagerMoID, entityType, entityMoID)
+ if err != nil {
+ return nil, err
+ }
+ if !summary.CurrentSupported || summary.RefreshRate <= 0 {
+ return nil, nil
+ }
+
+ available, err := c.queryAvailablePerfMetrics(ctx, release, sessionID, perfManagerMoID, entityType, entityMoID, summary.RefreshRate)
+ if err != nil {
+ return nil, err
+ }
+
+ selectedMetricIDs, defsByCounterID := perfMetricIDsForEntity(perfCounters, available, definitions)
+ if len(selectedMetricIDs) == 0 {
+ return nil, nil
+ }
+
+ result, err := c.queryPerfMetrics(ctx, release, sessionID, perfManagerMoID, entityType, entityMoID, summary.RefreshRate, selectedMetricIDs)
+ if err != nil {
+ return nil, err
+ }
+
+ metrics := inventoryMetricsFromPerf(result, defsByCounterID, fallbackMemoryTotalBytes)
+ if !hasInventoryMetrics(metrics) {
+ return nil, nil
+ }
+ return metrics, nil
+}
+
+func (c *Client) queryPerfProviderSummary(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ entityType string,
+ entityMoID string,
+) (viJSONPerfProviderSummary, error) {
+ var summary viJSONPerfProviderSummary
+ path := fmt.Sprintf("/sdk/vim25/%s/PerformanceManager/%s/QueryPerfProviderSummary", release, perfManagerMoID)
+ body := map[string]any{
+ "entity": map[string]string{
+ "type": strings.TrimSpace(entityType),
+ "value": strings.TrimSpace(entityMoID),
+ },
+ }
+ if err := c.postVIJSONJSON(ctx, sessionID, path, "vmware performance provider summary", body, &summary); err != nil {
+ return viJSONPerfProviderSummary{}, err
+ }
+ return summary, nil
+}
+
+func (c *Client) queryAvailablePerfMetrics(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ entityType string,
+ entityMoID string,
+ intervalID int,
+) ([]viJSONPerfMetricID, error) {
+ path := fmt.Sprintf("/sdk/vim25/%s/PerformanceManager/%s/QueryAvailablePerfMetric", release, perfManagerMoID)
+ body := map[string]any{
+ "entity": map[string]string{
+ "type": strings.TrimSpace(entityType),
+ "value": strings.TrimSpace(entityMoID),
+ },
+ "intervalId": intervalID,
+ }
+ var available []viJSONPerfMetricID
+ if err := c.postVIJSONJSON(ctx, sessionID, path, "vmware available performance metrics", body, &available); err != nil {
+ return nil, err
+ }
+ return available, nil
+}
+
+func (c *Client) queryPerfMetrics(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ entityType string,
+ entityMoID string,
+ intervalID int,
+ metricIDs []viJSONPerfMetricID,
+) ([]viJSONPerfEntityMetric, error) {
+ path := fmt.Sprintf("/sdk/vim25/%s/PerformanceManager/%s/QueryPerf", release, perfManagerMoID)
+ body := map[string]any{
+ "querySpec": []map[string]any{{
+ "entity": map[string]string{
+ "type": strings.TrimSpace(entityType),
+ "value": strings.TrimSpace(entityMoID),
+ },
+ "intervalId": intervalID,
+ "maxSample": 1,
+ "metricId": metricIDs,
+ }},
+ }
+ var result []viJSONPerfEntityMetric
+ if err := c.postVIJSONJSON(ctx, sessionID, path, "vmware performance metrics", body, &result); err != nil {
+ return nil, err
+ }
+ return result, nil
+}
+
+func (c *Client) postVIJSONJSON(ctx context.Context, sessionID, path, label string, body any, target any) error {
+ payload, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("marshal %s request: %w", label, err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL.String()+path, strings.NewReader(string(payload)))
+ if err != nil {
+ return fmt.Errorf("build %s request: %w", label, err)
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("vmware-api-session-id", sessionID)
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return classifyTransportError(label, err)
+ }
+ defer resp.Body.Close()
+ responseBody, readErr := io.ReadAll(io.LimitReader(resp.Body, inventoryResponseLimitByte))
+ if readErr != nil {
+ return fmt.Errorf("read %s response: %w", label, readErr)
+ }
+ switch resp.StatusCode {
+ case http.StatusOK:
+ case http.StatusUnauthorized:
+ return &ConnectionError{Category: "auth", Message: fmt.Sprintf("VMware authentication failed while reading %s", label)}
+ case http.StatusForbidden:
+ return &ConnectionError{Category: "permission", Message: fmt.Sprintf("VMware permissions are insufficient for %s", label)}
+ case http.StatusNotFound:
+ return &ConnectionError{Category: "not_found", Message: fmt.Sprintf("VMware %s endpoint is unavailable", label)}
+ default:
+ return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s request failed with HTTP %d", label, resp.StatusCode)}
+ }
+ if err := json.Unmarshal(responseBody, target); err != nil {
+ return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s response was not valid JSON", label)}
+ }
+ return nil
+}
+
+func perfMetricIDsForEntity(
+ catalog perfCounterCatalog,
+ available []viJSONPerfMetricID,
+ definitions []perfCounterDefinition,
+) ([]viJSONPerfMetricID, map[int]string) {
+ if len(definitions) == 0 || len(available) == 0 {
+ return nil, nil
+ }
+
+ selected := make([]viJSONPerfMetricID, 0, len(definitions))
+ defsByCounterID := make(map[int]string, len(definitions))
+ for _, definition := range definitions {
+ counterID, ok := catalog.idsByKey[perfCounterCatalogKey(definition.group, definition.name, definition.rollup)]
+ if !ok {
+ continue
+ }
+ candidates := filterAvailablePerfMetrics(available, counterID)
+ if len(candidates) == 0 {
+ continue
+ }
+ defsByCounterID[counterID] = definition.logical
+ selected = append(selected, preferredPerfMetricInstances(candidates)...)
+ }
+ return selected, defsByCounterID
+}
+
+func filterAvailablePerfMetrics(available []viJSONPerfMetricID, counterID int) []viJSONPerfMetricID {
+ filtered := make([]viJSONPerfMetricID, 0, len(available))
+ for _, metric := range available {
+ if metric.CounterID == counterID {
+ filtered = append(filtered, metric)
+ }
+ }
+ return filtered
+}
+
+func preferredPerfMetricInstances(candidates []viJSONPerfMetricID) []viJSONPerfMetricID {
+ if len(candidates) == 0 {
+ return nil
+ }
+ for _, candidate := range candidates {
+ if strings.TrimSpace(candidate.Instance) == "" {
+ return []viJSONPerfMetricID{candidate}
+ }
+ }
+ out := make([]viJSONPerfMetricID, len(candidates))
+ copy(out, candidates)
+ return out
+}
+
+func inventoryMetricsFromPerf(
+ result []viJSONPerfEntityMetric,
+ defsByCounterID map[int]string,
+ fallbackMemoryTotalBytes int64,
+) *InventoryMetrics {
+ if len(result) == 0 || len(defsByCounterID) == 0 {
+ return nil
+ }
+
+ accumulators := make(map[string]perfMetricAccumulator)
+ for _, entityMetric := range result {
+ for _, series := range entityMetric.Value {
+ logical, ok := defsByCounterID[series.ID.CounterID]
+ if !ok {
+ continue
+ }
+ value, ok := latestPerfMetricValue(series.Value)
+ if !ok {
+ continue
+ }
+ accumulator := accumulators[logical]
+ accumulator.sum += float64(value)
+ accumulator.count++
+ accumulators[logical] = accumulator
+ }
+ }
+
+ metrics := &InventoryMetrics{}
+ if accumulator, ok := accumulators[vmwarePerfLogicalCPUUsage]; ok && accumulator.count > 0 {
+ cpuPercent := clampVMwarePercent(accumulator.sum / float64(accumulator.count) / 100.0)
+ metrics.CPUPercent = float64Ptr(cpuPercent)
+ }
+ if accumulator, ok := accumulators[vmwarePerfLogicalMemoryUsage]; ok && accumulator.count > 0 {
+ memoryPercent := clampVMwarePercent(accumulator.sum / float64(accumulator.count) / 100.0)
+ metrics.MemoryPercent = float64Ptr(memoryPercent)
+ }
+
+ memoryTotalBytes := fallbackMemoryTotalBytes
+ if accumulator, ok := accumulators[vmwarePerfLogicalHostMemoryTotal]; ok && accumulator.count > 0 {
+ memoryTotalBytes = int64(math.Round(accumulator.sum)) * 1024 * 1024
+ }
+ if memoryTotalBytes > 0 && metrics.MemoryPercent != nil {
+ metrics.MemoryTotalBytes = int64Ptr(memoryTotalBytes)
+ memoryUsedBytes := int64(math.Round((float64(memoryTotalBytes) * *metrics.MemoryPercent) / 100.0))
+ metrics.MemoryUsedBytes = int64Ptr(memoryUsedBytes)
+ }
+
+ if accumulator, ok := accumulators[vmwarePerfLogicalNetIn]; ok && accumulator.count > 0 {
+ metrics.NetInBytesPerSecond = float64Ptr(accumulator.sum * 1024.0)
+ }
+ if accumulator, ok := accumulators[vmwarePerfLogicalNetOut]; ok && accumulator.count > 0 {
+ metrics.NetOutBytesPerSecond = float64Ptr(accumulator.sum * 1024.0)
+ }
+ if accumulator, ok := accumulators[vmwarePerfLogicalDiskRead]; ok && accumulator.count > 0 {
+ metrics.DiskReadBytesPerSecond = float64Ptr(accumulator.sum * 1024.0)
+ }
+ if accumulator, ok := accumulators[vmwarePerfLogicalDiskWrite]; ok && accumulator.count > 0 {
+ metrics.DiskWriteBytesPerSecond = float64Ptr(accumulator.sum * 1024.0)
+ }
+
+ if !hasInventoryMetrics(metrics) {
+ return nil
+ }
+ return metrics
+}
+
+func latestPerfMetricValue(values []int64) (int64, bool) {
+ if len(values) == 0 {
+ return 0, false
+ }
+ value := values[len(values)-1]
+ if value < 0 {
+ return 0, false
+ }
+ return value, true
+}
+
+func perfCounterCatalogKey(group, name, rollup string) string {
+ group = strings.TrimSpace(strings.ToLower(group))
+ name = strings.TrimSpace(strings.ToLower(name))
+ rollup = strings.TrimSpace(strings.ToLower(rollup))
+ if group == "" || name == "" || rollup == "" {
+ return ""
+ }
+ return group + "." + name + "." + rollup
+}
+
+func clampVMwarePercent(value float64) float64 {
+ if value < 0 {
+ return 0
+ }
+ if value > 100 {
+ return 100
+ }
+ return value
+}
+
+func hasInventoryMetrics(metrics *InventoryMetrics) bool {
+ if metrics == nil {
+ return false
+ }
+ return metrics.CPUPercent != nil ||
+ metrics.MemoryPercent != nil ||
+ metrics.MemoryUsedBytes != nil ||
+ metrics.MemoryTotalBytes != nil ||
+ metrics.NetInBytesPerSecond != nil ||
+ metrics.NetOutBytesPerSecond != nil ||
+ metrics.DiskReadBytesPerSecond != nil ||
+ metrics.DiskWriteBytesPerSecond != nil
+}
+
+func float64Ptr(value float64) *float64 {
+ return &value
+}
+
+func int64Ptr(value int64) *int64 {
+ return &value
+}
diff --git a/internal/vmware/client_signals.go b/internal/vmware/client_signals.go
index eea10e9577..cb35fff644 100644
--- a/internal/vmware/client_signals.go
+++ b/internal/vmware/client_signals.go
@@ -64,7 +64,14 @@ type entitySignals struct {
RecentTasks []InventoryTask
}
-func (c *Client) validateSignalFloor(ctx context.Context, release, sessionID string, snapshot *InventorySnapshot) error {
+func (c *Client) validateSignalFloor(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ snapshot *InventorySnapshot,
+ perfCounters perfCounterCatalog,
+) error {
if snapshot == nil {
return nil
}
@@ -75,6 +82,13 @@ func (c *Client) validateSignalFloor(ctx context.Context, release, sessionID str
if _, err := c.collectManagedEntitySignals(ctx, release, sessionID, "HostSystem", host.Host, cache, false); err != nil {
return err
}
+ hostMetrics, err := c.collectHostPerformanceMetrics(ctx, release, sessionID, perfManagerMoID, perfCounters, host)
+ if err != nil {
+ return err
+ }
+ if hostMetrics == nil || hostMetrics.CPUPercent == nil || hostMetrics.MemoryPercent == nil {
+ return &ConnectionError{Category: "endpoint", Message: "VMware performance metrics are unavailable for host inventory"}
+ }
}
if len(snapshot.VMs) > 0 {
vm := snapshot.VMs[0]
@@ -84,6 +98,13 @@ func (c *Client) validateSignalFloor(ctx context.Context, release, sessionID str
if _, err := c.collectVMSnapshotCount(ctx, release, sessionID, vm.VM); err != nil && !isVIJSONNotFound(err) {
return err
}
+ vmMetrics, err := c.collectVMPerformanceMetrics(ctx, release, sessionID, perfManagerMoID, perfCounters, vm)
+ if err != nil {
+ return err
+ }
+ if vmMetrics == nil || vmMetrics.CPUPercent == nil || vmMetrics.MemoryPercent == nil {
+ return &ConnectionError{Category: "endpoint", Message: "VMware performance metrics are unavailable for vm inventory"}
+ }
}
if len(snapshot.Datastores) > 0 {
datastore := snapshot.Datastores[0]
@@ -94,7 +115,14 @@ func (c *Client) validateSignalFloor(ctx context.Context, release, sessionID str
return nil
}
-func (c *Client) enrichInventorySnapshot(ctx context.Context, release, sessionID string, snapshot *InventorySnapshot) error {
+func (c *Client) enrichInventorySnapshot(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ perfManagerMoID string,
+ perfCounters perfCounterCatalog,
+ snapshot *InventorySnapshot,
+) error {
if snapshot == nil {
return nil
}
@@ -129,9 +157,14 @@ func (c *Client) enrichInventorySnapshot(ctx context.Context, release, sessionID
if err != nil {
return err
}
+ metrics, err := c.collectHostPerformanceMetrics(ctx, release, sessionID, perfManagerMoID, perfCounters, snapshot.Hosts[i])
+ if err != nil {
+ return err
+ }
snapshot.Hosts[i].OverallStatus = signals.OverallStatus
snapshot.Hosts[i].TriggeredAlarms = signals.Alarms
snapshot.Hosts[i].RecentTasks = signals.RecentTasks
+ snapshot.Hosts[i].Metrics = metrics
return nil
})
}
@@ -150,6 +183,11 @@ func (c *Client) enrichInventorySnapshot(ctx context.Context, release, sessionID
if err != nil && !isVIJSONNotFound(err) {
return err
}
+ metrics, err := c.collectVMPerformanceMetrics(ctx, release, sessionID, perfManagerMoID, perfCounters, snapshot.VMs[i])
+ if err != nil {
+ return err
+ }
+ snapshot.VMs[i].Metrics = metrics
return nil
})
}
diff --git a/internal/vmware/client_test.go b/internal/vmware/client_test.go
index 5b75c52f4c..0ec0888d1a 100644
--- a/internal/vmware/client_test.go
+++ b/internal/vmware/client_test.go
@@ -40,6 +40,9 @@ func TestClientCollectInventoryEnrichesSignals(t *testing.T) {
if host.OverallStatus != "yellow" {
t.Fatalf("host overall status = %q, want yellow", host.OverallStatus)
}
+ if host.Metrics == nil || host.Metrics.CPUPercent == nil || *host.Metrics.CPUPercent != 21.4 {
+ t.Fatalf("expected host cpu metrics, got %+v", host.Metrics)
+ }
if len(host.TriggeredAlarms) != 1 || host.TriggeredAlarms[0].Name != "Host connection degraded" {
t.Fatalf("expected resolved host alarm metadata, got %+v", host.TriggeredAlarms)
}
@@ -48,6 +51,9 @@ func TestClientCollectInventoryEnrichesSignals(t *testing.T) {
}
vm := snapshot.VMs[0]
+ if vm.Metrics == nil || vm.Metrics.MemoryPercent == nil || *vm.Metrics.MemoryPercent != 57.5 {
+ t.Fatalf("expected VM memory metrics, got %+v", vm.Metrics)
+ }
if len(vm.TriggeredAlarms) != 1 || vm.TriggeredAlarms[0].OverallStatus != "red" {
t.Fatalf("expected VM alarm signals, got %+v", vm.TriggeredAlarms)
}
@@ -155,12 +161,112 @@ func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Ser
mux.HandleFunc("/sdk/vim25/9.0.0.0/ServiceInstance/ServiceInstance/content", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{
"sessionManager": map[string]any{"value": "SessionManager"},
+ "perfManager": map[string]any{"value": "PerformanceManager"},
})
})
mux.HandleFunc("/sdk/vim25/9.0.0.0/SessionManager/SessionManager/Login", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("vmware-api-session-id", "vi-session")
writeJSON(w, map[string]any{"value": "ok"})
})
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/PerformanceManager/PerformanceManager/perfCounter", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, []map[string]any{
+ {"key": 1, "groupInfo": map[string]any{"key": "cpu"}, "nameInfo": map[string]any{"key": "usage"}, "rollupType": "average"},
+ {"key": 2, "groupInfo": map[string]any{"key": "mem"}, "nameInfo": map[string]any{"key": "usage"}, "rollupType": "average"},
+ {"key": 3, "groupInfo": map[string]any{"key": "mem"}, "nameInfo": map[string]any{"key": "totalCapacity"}, "rollupType": "average"},
+ {"key": 4, "groupInfo": map[string]any{"key": "net"}, "nameInfo": map[string]any{"key": "bytesRx"}, "rollupType": "average"},
+ {"key": 5, "groupInfo": map[string]any{"key": "net"}, "nameInfo": map[string]any{"key": "bytesTx"}, "rollupType": "average"},
+ {"key": 6, "groupInfo": map[string]any{"key": "disk"}, "nameInfo": map[string]any{"key": "read"}, "rollupType": "average"},
+ {"key": 7, "groupInfo": map[string]any{"key": "disk"}, "nameInfo": map[string]any{"key": "write"}, "rollupType": "average"},
+ })
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/PerformanceManager/PerformanceManager/QueryPerfProviderSummary", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{
+ "currentSupported": true,
+ "refreshRate": 20,
+ })
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/PerformanceManager/PerformanceManager/QueryAvailablePerfMetric", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ var request struct {
+ Entity struct {
+ Type string `json:"type"`
+ } `json:"entity"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ t.Fatalf("decode available perf request: %v", err)
+ }
+ switch request.Entity.Type {
+ case "HostSystem":
+ writeJSON(w, []map[string]any{
+ {"counterId": 1, "instance": ""},
+ {"counterId": 2, "instance": ""},
+ {"counterId": 3, "instance": ""},
+ {"counterId": 4, "instance": "vmnic0"},
+ {"counterId": 5, "instance": "vmnic0"},
+ {"counterId": 6, "instance": "naa.1"},
+ {"counterId": 7, "instance": "naa.1"},
+ })
+ case "VirtualMachine":
+ writeJSON(w, []map[string]any{
+ {"counterId": 1, "instance": ""},
+ {"counterId": 2, "instance": ""},
+ {"counterId": 4, "instance": "4000"},
+ {"counterId": 5, "instance": "4000"},
+ {"counterId": 6, "instance": "2000"},
+ {"counterId": 7, "instance": "2000"},
+ })
+ default:
+ writeJSON(w, []map[string]any{})
+ }
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/PerformanceManager/PerformanceManager/QueryPerf", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ var request struct {
+ QuerySpec []struct {
+ Entity struct {
+ Type string `json:"type"`
+ Value string `json:"value"`
+ } `json:"entity"`
+ } `json:"querySpec"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
+ t.Fatalf("decode query perf request: %v", err)
+ }
+ if len(request.QuerySpec) != 1 {
+ t.Fatalf("expected single query spec, got %d", len(request.QuerySpec))
+ }
+ switch request.QuerySpec[0].Entity.Type {
+ case "HostSystem":
+ writeJSON(w, []map[string]any{{
+ "entity": map[string]any{"type": "HostSystem", "value": "host-101"},
+ "value": []map[string]any{
+ {"id": map[string]any{"counterId": 1, "instance": ""}, "value": []int64{2140}},
+ {"id": map[string]any{"counterId": 2, "instance": ""}, "value": []int64{6320}},
+ {"id": map[string]any{"counterId": 3, "instance": ""}, "value": []int64{40960}},
+ {"id": map[string]any{"counterId": 4, "instance": "vmnic0"}, "value": []int64{1}},
+ {"id": map[string]any{"counterId": 5, "instance": "vmnic0"}, "value": []int64{2}},
+ {"id": map[string]any{"counterId": 6, "instance": "naa.1"}, "value": []int64{4}},
+ {"id": map[string]any{"counterId": 7, "instance": "naa.1"}, "value": []int64{8}},
+ },
+ }})
+ case "VirtualMachine":
+ writeJSON(w, []map[string]any{{
+ "entity": map[string]any{"type": "VirtualMachine", "value": "vm-201"},
+ "value": []map[string]any{
+ {"id": map[string]any{"counterId": 1, "instance": ""}, "value": []int64{3810}},
+ {"id": map[string]any{"counterId": 2, "instance": ""}, "value": []int64{5750}},
+ {"id": map[string]any{"counterId": 4, "instance": "4000"}, "value": []int64{3}},
+ {"id": map[string]any{"counterId": 5, "instance": "4000"}, "value": []int64{4}},
+ {"id": map[string]any{"counterId": 6, "instance": "2000"}, "value": []int64{5}},
+ {"id": map[string]any{"counterId": 7, "instance": "2000"}, "value": []int64{6}},
+ },
+ }})
+ default:
+ writeJSON(w, []map[string]any{})
+ }
+ })
if !cfg.omitHostOverallStatus {
mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/overallStatus", func(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/vmware/provider.go b/internal/vmware/provider.go
index 7fada19d99..66a12237d8 100644
--- a/internal/vmware/provider.go
+++ b/internal/vmware/provider.go
@@ -30,31 +30,46 @@ type InventoryTask struct {
ErrorMessage string `json:"error_message,omitempty"`
}
+// InventoryMetrics captures the current runtime metric floor projected onto
+// canonical Pulse metrics for VMware-backed hosts and VMs.
+type InventoryMetrics struct {
+ CPUPercent *float64 `json:"cpu_percent,omitempty"`
+ MemoryPercent *float64 `json:"memory_percent,omitempty"`
+ MemoryUsedBytes *int64 `json:"memory_used_bytes,omitempty"`
+ MemoryTotalBytes *int64 `json:"memory_total_bytes,omitempty"`
+ NetInBytesPerSecond *float64 `json:"net_in_bytes_per_second,omitempty"`
+ NetOutBytesPerSecond *float64 `json:"net_out_bytes_per_second,omitempty"`
+ DiskReadBytesPerSecond *float64 `json:"disk_read_bytes_per_second,omitempty"`
+ DiskWriteBytesPerSecond *float64 `json:"disk_write_bytes_per_second,omitempty"`
+}
+
// InventoryHost is the canonical phase-1 host summary returned by the vCenter
// Automation API list endpoint.
type InventoryHost struct {
- Host string `json:"host"`
- Name string `json:"name"`
- ConnectionState string `json:"connection_state"`
- PowerState string `json:"power_state,omitempty"`
- HostUUID string `json:"host_uuid,omitempty"`
- OverallStatus string `json:"overall_status,omitempty"`
- TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
- RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
+ Host string `json:"host"`
+ Name string `json:"name"`
+ ConnectionState string `json:"connection_state"`
+ PowerState string `json:"power_state,omitempty"`
+ HostUUID string `json:"host_uuid,omitempty"`
+ OverallStatus string `json:"overall_status,omitempty"`
+ TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
+ RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
+ Metrics *InventoryMetrics `json:"metrics,omitempty"`
}
// InventoryVM is the canonical phase-1 VM summary returned by the vCenter
// Automation API list endpoint.
type InventoryVM struct {
- VM string `json:"vm"`
- Name string `json:"name"`
- PowerState string `json:"power_state"`
- CPUCount int `json:"cpu_count,omitempty"`
- MemorySizeMiB int64 `json:"memory_size_mib,omitempty"`
- OverallStatus string `json:"overall_status,omitempty"`
- TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
- RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
- SnapshotCount int `json:"snapshot_count,omitempty"`
+ VM string `json:"vm"`
+ Name string `json:"name"`
+ PowerState string `json:"power_state"`
+ CPUCount int `json:"cpu_count,omitempty"`
+ MemorySizeMiB int64 `json:"memory_size_mib,omitempty"`
+ OverallStatus string `json:"overall_status,omitempty"`
+ TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
+ RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
+ SnapshotCount int `json:"snapshot_count,omitempty"`
+ Metrics *InventoryMetrics `json:"metrics,omitempty"`
}
// InventoryDatastore is the canonical phase-1 datastore summary returned by
@@ -260,6 +275,7 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
LastSeen: collectedAt,
UpdatedAt: collectedAt,
Incidents: incidents,
+ Metrics: inventoryMetricsResourceMetrics(host.Metrics),
VMware: &unifiedresources.VMwareData{
ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
ConnectionName: connectionName,
@@ -310,6 +326,7 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
LastSeen: collectedAt,
UpdatedAt: collectedAt,
Incidents: incidents,
+ Metrics: inventoryMetricsResourceMetrics(vm.Metrics),
VMware: &unifiedresources.VMwareData{
ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
ConnectionName: connectionName,
@@ -434,6 +451,7 @@ func cloneInventoryHosts(in []InventoryHost) []InventoryHost {
out[i] = in[i]
out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)
out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)
+ out[i].Metrics = cloneInventoryMetrics(in[i].Metrics)
}
return out
}
@@ -447,6 +465,7 @@ func cloneInventoryVMs(in []InventoryVM) []InventoryVM {
out[i] = in[i]
out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)
out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)
+ out[i].Metrics = cloneInventoryMetrics(in[i].Metrics)
}
return out
}
@@ -482,6 +501,22 @@ func cloneInventoryTasks(in []InventoryTask) []InventoryTask {
return out
}
+func cloneInventoryMetrics(in *InventoryMetrics) *InventoryMetrics {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ out.CPUPercent = cloneFloat64Pointer(in.CPUPercent)
+ out.MemoryPercent = cloneFloat64Pointer(in.MemoryPercent)
+ out.MemoryUsedBytes = cloneInt64Pointer(in.MemoryUsedBytes)
+ out.MemoryTotalBytes = cloneInt64Pointer(in.MemoryTotalBytes)
+ out.NetInBytesPerSecond = cloneFloat64Pointer(in.NetInBytesPerSecond)
+ out.NetOutBytesPerSecond = cloneFloat64Pointer(in.NetOutBytesPerSecond)
+ out.DiskReadBytesPerSecond = cloneFloat64Pointer(in.DiskReadBytesPerSecond)
+ out.DiskWriteBytesPerSecond = cloneFloat64Pointer(in.DiskWriteBytesPerSecond)
+ return &out
+}
+
func vmwareSourceID(connectionID, entityType, managedObjectID string) string {
parts := filterNonEmptyStrings(strings.TrimSpace(connectionID), strings.TrimSpace(entityType), strings.TrimSpace(managedObjectID))
return strings.Join(parts, ":")
@@ -697,6 +732,91 @@ func diskMetric(total, used int64) *unifiedresources.MetricValue {
}
}
+func inventoryMetricsResourceMetrics(in *InventoryMetrics) *unifiedresources.ResourceMetrics {
+ if in == nil {
+ return nil
+ }
+
+ metrics := &unifiedresources.ResourceMetrics{}
+ if in.CPUPercent != nil {
+ metrics.CPU = &unifiedresources.MetricValue{
+ Value: *in.CPUPercent,
+ Percent: *in.CPUPercent,
+ Unit: "percent",
+ Source: unifiedresources.SourceVMware,
+ }
+ }
+ if in.MemoryPercent != nil {
+ metrics.Memory = &unifiedresources.MetricValue{
+ Percent: *in.MemoryPercent,
+ Unit: "bytes",
+ Source: unifiedresources.SourceVMware,
+ }
+ if in.MemoryUsedBytes != nil {
+ used := *in.MemoryUsedBytes
+ metrics.Memory.Used = &used
+ }
+ if in.MemoryTotalBytes != nil {
+ total := *in.MemoryTotalBytes
+ metrics.Memory.Total = &total
+ }
+ }
+ if in.NetInBytesPerSecond != nil {
+ metrics.NetIn = &unifiedresources.MetricValue{
+ Value: *in.NetInBytesPerSecond,
+ Unit: "bytes/s",
+ Source: unifiedresources.SourceVMware,
+ }
+ }
+ if in.NetOutBytesPerSecond != nil {
+ metrics.NetOut = &unifiedresources.MetricValue{
+ Value: *in.NetOutBytesPerSecond,
+ Unit: "bytes/s",
+ Source: unifiedresources.SourceVMware,
+ }
+ }
+ if in.DiskReadBytesPerSecond != nil {
+ metrics.DiskRead = &unifiedresources.MetricValue{
+ Value: *in.DiskReadBytesPerSecond,
+ Unit: "bytes/s",
+ Source: unifiedresources.SourceVMware,
+ }
+ }
+ if in.DiskWriteBytesPerSecond != nil {
+ metrics.DiskWrite = &unifiedresources.MetricValue{
+ Value: *in.DiskWriteBytesPerSecond,
+ Unit: "bytes/s",
+ Source: unifiedresources.SourceVMware,
+ }
+ }
+
+ if metrics.CPU == nil &&
+ metrics.Memory == nil &&
+ metrics.NetIn == nil &&
+ metrics.NetOut == nil &&
+ metrics.DiskRead == nil &&
+ metrics.DiskWrite == nil {
+ return nil
+ }
+ return metrics
+}
+
+func cloneFloat64Pointer(in *float64) *float64 {
+ if in == nil {
+ return nil
+ }
+ value := *in
+ return &value
+}
+
+func cloneInt64Pointer(in *int64) *int64 {
+ if in == nil {
+ return nil
+ }
+ value := *in
+ return &value
+}
+
func firstNonEmptyTrimmed(values ...string) string {
for _, value := range values {
if trimmed := strings.TrimSpace(value); trimmed != "" {
diff --git a/internal/vmware/provider_test.go b/internal/vmware/provider_test.go
index 9522443e71..a6e6205db5 100644
--- a/internal/vmware/provider_test.go
+++ b/internal/vmware/provider_test.go
@@ -25,6 +25,16 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
PowerState: "POWERED_ON",
HostUUID: "uuid-host-1",
OverallStatus: "yellow",
+ Metrics: &InventoryMetrics{
+ CPUPercent: float64Ptr(21.4),
+ MemoryPercent: float64Ptr(63.2),
+ MemoryUsedBytes: int64Ptr(27144105984),
+ MemoryTotalBytes: int64Ptr(42949672960),
+ NetInBytesPerSecond: float64Ptr(1024),
+ NetOutBytesPerSecond: float64Ptr(2048),
+ DiskReadBytesPerSecond: float64Ptr(4096),
+ DiskWriteBytesPerSecond: float64Ptr(8192),
+ },
TriggeredAlarms: []InventoryAlarm{{
Alarm: "alarm-11",
Name: "Host connection degraded",
@@ -45,6 +55,16 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
CPUCount: 4,
MemorySizeMiB: 8192,
OverallStatus: "green",
+ Metrics: &InventoryMetrics{
+ CPUPercent: float64Ptr(38.1),
+ MemoryPercent: float64Ptr(57.5),
+ MemoryUsedBytes: int64Ptr(5033164800),
+ MemoryTotalBytes: int64Ptr(8589934592),
+ NetInBytesPerSecond: float64Ptr(512),
+ NetOutBytesPerSecond: float64Ptr(768),
+ DiskReadBytesPerSecond: float64Ptr(1536),
+ DiskWriteBytesPerSecond: float64Ptr(2048),
+ },
TriggeredAlarms: []InventoryAlarm{{
Alarm: "alarm-21",
Name: "VM replication fault",
@@ -99,6 +119,15 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
if got := hostRecord.Resource.VMware.RecentTaskSummary; got != "Reconnect host (running)" {
t.Fatalf("host recent task summary = %q, want %q", got, "Reconnect host (running)")
}
+ if hostRecord.Resource.Metrics == nil || hostRecord.Resource.Metrics.CPU == nil || hostRecord.Resource.Metrics.Memory == nil {
+ t.Fatalf("expected VMware host metrics, got %+v", hostRecord.Resource.Metrics)
+ }
+ if got := hostRecord.Resource.Metrics.CPU.Percent; got != 21.4 {
+ t.Fatalf("host cpu percent = %v, want 21.4", got)
+ }
+ if got := hostRecord.Resource.Metrics.NetOut.Value; got != 2048 {
+ t.Fatalf("host net out = %v, want 2048", got)
+ }
if len(hostRecord.Resource.Incidents) != 1 || hostRecord.Resource.Incidents[0].Code != "vmware_alarm_state" {
t.Fatalf("expected host VMware incident projection, got %+v", hostRecord.Resource.Incidents)
}
@@ -128,6 +157,15 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
if got := vmRecord.Resource.VMware.SnapshotCount; got != 2 {
t.Fatalf("vm snapshot count = %d, want 2", got)
}
+ if vmRecord.Resource.Metrics == nil || vmRecord.Resource.Metrics.CPU == nil || vmRecord.Resource.Metrics.Memory == nil {
+ t.Fatalf("expected VMware VM metrics, got %+v", vmRecord.Resource.Metrics)
+ }
+ if got := vmRecord.Resource.Metrics.Memory.Percent; got != 57.5 {
+ t.Fatalf("vm memory percent = %v, want 57.5", got)
+ }
+ if got := vmRecord.Resource.Metrics.DiskWrite.Value; got != 2048 {
+ t.Fatalf("vm disk write = %v, want 2048", got)
+ }
if len(vmRecord.Resource.Incidents) != 1 || vmRecord.Resource.Incidents[0].Code != "vmware_alarm_state" {
t.Fatalf("expected VMware VM incident projection, got %+v", vmRecord.Resource.Incidents)
}