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 topology detail projection

rcourtman0ee742eb8780
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 1d1b83cd3c..1d5d9a1eba 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -125,6 +125,16 @@ folders, or datacenters may inform investigation only when they can be
attached honestly to canonical `agent`, `vm`, or `storage` resources; the
collector must not solve that ambiguity by creating VMware-only top-level
incident targets.
+That same monitoring boundary now also has a concrete detail-enrichment seam.
+`internal/vmware/client.go`, `internal/vmware/client_topology.go`, and
+`internal/vmware/provider.go` may use the official vCenter Automation API plus
+VI JSON `name`, `parent`, `runtime`, `resourcePool`, `datastore`, `host`,
+`vm`, and datastore-summary paths to enrich canonical VMware-backed resources
+with placement, guest identity, and storage consumer context. That
+enrichment remains best-effort provider detail on the shared VMware source: it
+must not create a second topology cache, a VMware-only placement store, or a
+parallel guest-identity model outside the canonical `agent` / `vm` / `storage`
+resource graph.
The monitor adapter now also acts as the canonical bridge from live registry
rebuilds and supplemental ingest into the unified-resource timeline. That means
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 7459bc237f..f8f6235b2e 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -93,6 +93,7 @@ querying, and the operator-facing storage health presentation layer.
27. Keep alert-side recovery drill-ins on that same shared route-helper contract. When alert investigation surfaces such as resource-incident panels expose recovery follow-up links for TrueNAS or future API-backed platforms, they must route through the canonical `frontend-modern/src/routing/resourceLinks.ts` recovery builder instead of freezing alert-local recovery URLs or introducing another provider-shaped recovery handoff vocabulary.
28. Keep VMware onboarding runtime and recovery semantics separate on that same adjacent platform-connections contract. When `internal/api/router.go`, `internal/api/router_routes_registration.go`, or `internal/api/vmware_handlers.go` evolve VMware connection CRUD, saved-test refresh, or observed datastore/VM snapshot visibility, storage and recovery may consume the resulting shared context but must not treat those onboarding/runtime payloads as canonical recovery artifacts, restore capability, or recovery-local control transport.
29. Keep VMware datastore projection on the shared unified-resource and storage-source contracts. When `frontend-modern/src/hooks/useUnifiedResources.ts` or shared `internal/api/router.go` wiring starts surfacing VMware-backed canonical `storage` resources, storage and recovery may expose those datastores through the owned `vmware-vsphere` source/platform vocabulary for inventory, capacity, and handoff flows only; they must not reinterpret that projection as VMware recovery support, restore semantics, or a provider-local protection surface.
+30. Keep VMware placement and guest-detail enrichment descriptive on that same shared unified-resource contract. When `internal/vmware/provider.go`, `internal/unifiedresources/types.go`, and `frontend-modern/src/hooks/useUnifiedResources.ts` project datacenter, cluster, folder, runtime-host, datastore-attachment, guest-hostname, or guest-IP metadata onto canonical VMware `agent` / `vm` / `storage` resources, storage and recovery may use that detail for labeling and navigation only; they must not promote those topology or guest fields into recovery ownership, restore targeting, protection grouping, or a VMware-local recovery taxonomy without a separately governed slice.
## Forbidden Paths
@@ -1654,3 +1655,14 @@ facing storage visibility still ends at inventory, capacity, and navigation.
Storage and recovery must not infer VMware restore support, recovery rollups,
or VMware-local protection semantics from the presence of those datastores or
VM snapshot-read context on the shared pages.
+That same shared adapter floor also now carries richer VMware placement and
+guest-detail metadata through the canonical `agent` / `vm` / `storage`
+resources that storage and recovery can inspect on shared pages.
+`internal/vmware/provider.go`, `internal/unifiedresources/types.go`, and
+`frontend-modern/src/hooks/useUnifiedResources.ts` may expose datacenter,
+cluster, folder, runtime-host, datastore-attachment, guest-hostname, and
+guest-IP detail as inventory context, but those fields stay descriptive only.
+Storage and recovery must not treat topology labels, datastore attachments, or
+guest identity as recovery ownership, restore targeting, protection grouping,
+or a new VMware-local storage/recovery taxonomy until a separately governed
+slice explicitly promotes them into recovery contracts.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 2421af0bbf..ee3badaf4e 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -223,6 +223,17 @@ Snapshot trees and VMware alarm/event/task context are also governed by that
same rule: they may enrich canonical `vm`, `agent`, or `storage` resources and
their timelines, but they do not become shared recovery artifacts, new
resource kinds, or a parallel VMware incident model.
+That same topology contract now also has a concrete projection seam.
+`internal/vmware/provider.go` must preserve VMware placement and identity
+detail on the shared `vmware` facet only: hosts may carry datacenter,
+compute-resource, cluster, folder, and attached-datastore metadata; VMs may
+carry runtime-host, folder, resource-pool, datastore, and guest-identity
+metadata plus canonical parentage to the owning ESXi `agent`; datastores may
+carry datacenter/folder placement plus shared storage-node and workload
+consumer metadata through `storage.nodes`, `storage.consumerCount`, and
+`storage.topConsumers`. Those enrichments must remain subordinate to shared
+`agent`, `vm`, and `storage` resources rather than becoming a VMware-only
+topology graph or a separate provider detail drawer contract.
TrueNAS disk telemetry now follows the same rule. API-backed TrueNAS disks must
populate canonical `physicalDisk.temperature` and reuse the shared
physical-disk risk semantics, so infrastructure, storage, charts, and AI read
diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
index 96d32255ab..c319d94b5e 100644
--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
@@ -323,6 +323,8 @@ describe('useUnifiedResources', () => {
vCenterHost: 'vc.lab.local',
managedObjectId: 'host-101',
entityType: 'host',
+ datacenterName: 'DC1',
+ clusterName: 'Compute-A',
},
},
],
@@ -344,6 +346,8 @@ describe('useUnifiedResources', () => {
connectionId: 'vc-1',
managedObjectId: 'host-101',
entityType: 'host',
+ datacenterName: 'DC1',
+ clusterName: 'Compute-A',
});
dispose();
diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.ts
index dea6ccc1af..fdcce15845 100644
--- a/frontend-modern/src/hooks/useUnifiedResources.ts
+++ b/frontend-modern/src/hooks/useUnifiedResources.ts
@@ -313,11 +313,40 @@ type APIResource = {
managedObjectId?: string;
entityType?: string;
hostUuid?: string;
+ datacenterId?: string;
+ datacenterName?: string;
+ computeResourceId?: string;
+ computeResourceName?: string;
+ clusterId?: string;
+ clusterName?: string;
+ folderId?: string;
+ folderName?: string;
+ resourcePoolId?: string;
+ resourcePoolName?: string;
+ runtimeHostId?: string;
+ runtimeHostName?: string;
connectionState?: string;
powerState?: string;
+ overallStatus?: string;
cpuCount?: number;
memorySizeMib?: number;
datastoreType?: string;
+ datastoreIds?: string[];
+ datastoreNames?: string[];
+ datastoreUrl?: string;
+ datastoreAccessible?: boolean;
+ multipleHostAccess?: boolean;
+ maintenanceMode?: string;
+ instanceUuid?: string;
+ biosUuid?: string;
+ guestOsFamily?: string;
+ guestHostname?: string;
+ guestIpAddresses?: string[];
+ activeAlarmCount?: number;
+ activeAlarmSummary?: string;
+ recentTaskCount?: number;
+ recentTaskSummary?: string;
+ snapshotCount?: number;
};
recentChanges?: ResourceChange[];
facetCounts?: ResourceFacetCounts;
diff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.ts
index bd46baa519..9ea7287d7a 100644
--- a/frontend-modern/src/types/__tests__/resource.test.ts
+++ b/frontend-modern/src/types/__tests__/resource.test.ts
@@ -114,7 +114,16 @@ describe('Resource Helper Functions', () => {
vcenterHost: 'vc.lab.local',
managedObjectId: 'vm-101',
entityType: 'vm',
+ datacenterName: 'DC1',
+ clusterName: 'Production Cluster',
+ folderName: 'Workloads',
+ resourcePoolName: 'Tier 1',
+ runtimeHostName: 'esxi-01.lab.local',
overallStatus: 'yellow',
+ datastoreNames: ['primary-vmfs'],
+ instanceUuid: 'vm-instance-101',
+ guestHostname: 'app-01.internal',
+ guestIpAddresses: ['10.0.0.21'],
activeAlarmCount: 2,
activeAlarmSummary: 'CPU ready alarm; snapshot age warning',
recentTaskCount: 1,
@@ -123,6 +132,10 @@ describe('Resource Helper Functions', () => {
};
expect(vmware.overallStatus).toBe('yellow');
+ expect(vmware.clusterName).toBe('Production Cluster');
+ expect(vmware.runtimeHostName).toBe('esxi-01.lab.local');
+ expect(vmware.datastoreNames).toEqual(['primary-vmfs']);
+ expect(vmware.guestIpAddresses).toEqual(['10.0.0.21']);
expect(vmware.activeAlarmCount).toBe(2);
expect(vmware.recentTaskSummary).toBe('Clone VM task finished');
expect(vmware.snapshotCount).toBe(3);
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index 4bfbd5d9e7..761a2967a6 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -408,12 +408,35 @@ export interface ResourceVMwareMeta {
managedObjectId?: string;
entityType?: string;
hostUuid?: string;
+ datacenterId?: string;
+ datacenterName?: string;
+ computeResourceId?: string;
+ computeResourceName?: string;
+ clusterId?: string;
+ clusterName?: string;
+ folderId?: string;
+ folderName?: string;
+ resourcePoolId?: string;
+ resourcePoolName?: string;
+ runtimeHostId?: string;
+ runtimeHostName?: string;
connectionState?: string;
powerState?: string;
overallStatus?: string;
cpuCount?: number;
memorySizeMib?: number;
datastoreType?: string;
+ datastoreIds?: string[];
+ datastoreNames?: string[];
+ datastoreUrl?: string;
+ datastoreAccessible?: boolean;
+ multipleHostAccess?: boolean;
+ maintenanceMode?: string;
+ instanceUuid?: string;
+ biosUuid?: string;
+ guestOsFamily?: string;
+ guestHostname?: string;
+ guestIpAddresses?: string[];
activeAlarmCount?: number;
activeAlarmSummary?: string;
recentTaskCount?: number;
diff --git a/internal/unifiedresources/canonical_identity_test.go b/internal/unifiedresources/canonical_identity_test.go
index 3ab4d608d4..d67ef8935e 100644
--- a/internal/unifiedresources/canonical_identity_test.go
+++ b/internal/unifiedresources/canonical_identity_test.go
@@ -335,3 +335,78 @@ func TestRefreshCanonicalIdentityScopesVMwareManagedObjectsByConnection(t *testi
}
}
}
+
+func TestRefreshCanonicalIdentityIgnoresVMwarePlacementDetailAliases(t *testing.T) {
+ resource := Resource{
+ ID: "vmware-vm-1",
+ Type: ResourceTypeVM,
+ Name: "db-vm",
+ Identity: ResourceIdentity{
+ Hostnames: []string{"db-vm.guest.lab.local"},
+ MachineID: "vm-instance-uuid-1",
+ },
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ManagedObjectID: "vm-101",
+ EntityType: "vm",
+ DatacenterName: "DC-1",
+ ComputeResourceName: "Compute-A",
+ ClusterName: "Cluster-A",
+ FolderName: "Production",
+ ResourcePoolName: "Prod-VMs",
+ RuntimeHostName: "esxi-01.lab.local",
+ DatastoreNames: []string{"vmfs-prod-01", "vmfs-prod-02"},
+ GuestHostname: "db-vm.guest.lab.local",
+ GuestIPAddresses: []string{"10.0.0.10", "10.0.0.11"},
+ InstanceUUID: "vm-instance-uuid-1",
+ BIOSUUID: "vm-bios-uuid-1",
+ },
+ }
+
+ RefreshCanonicalIdentity(&resource)
+
+ if resource.Canonical == nil {
+ t.Fatalf("expected canonical identity")
+ }
+ if got := resource.Canonical.PrimaryID; got != "vmware:vc-1:vm:vm-101" {
+ t.Fatalf("primaryId = %q, want vmware:vc-1:vm:vm-101", got)
+ }
+
+ wantAliases := []string{
+ "vmware:vc-1:vm:vm-101",
+ "vm-101",
+ "db-vm",
+ "db-vm.guest.lab.local",
+ "vm-instance-uuid-1",
+ "vmware-vm-1",
+ }
+ if len(resource.Canonical.Aliases) != len(wantAliases) {
+ t.Fatalf("aliases len = %d, want %d (%v)", len(resource.Canonical.Aliases), len(wantAliases), resource.Canonical.Aliases)
+ }
+ for i, want := range wantAliases {
+ if got := resource.Canonical.Aliases[i]; got != want {
+ t.Fatalf("alias[%d] = %q, want %q", i, got, want)
+ }
+ }
+
+ disallowedAliases := []string{
+ "DC-1",
+ "Compute-A",
+ "Cluster-A",
+ "Production",
+ "Prod-VMs",
+ "esxi-01.lab.local",
+ "vmfs-prod-01",
+ "vmfs-prod-02",
+ "10.0.0.10",
+ "10.0.0.11",
+ "vm-bios-uuid-1",
+ }
+ for _, disallowed := range disallowedAliases {
+ for _, alias := range resource.Canonical.Aliases {
+ if alias == disallowed {
+ t.Fatalf("expected VMware topology/detail value %q not to become canonical alias: %+v", disallowed, resource.Canonical.Aliases)
+ }
+ }
+ }
+}
diff --git a/internal/unifiedresources/clone.go b/internal/unifiedresources/clone.go
index b178f7f8d7..8b74dad129 100644
--- a/internal/unifiedresources/clone.go
+++ b/internal/unifiedresources/clone.go
@@ -250,6 +250,11 @@ func cloneVMwareData(in *VMwareData) *VMwareData {
return nil
}
out := *in
+ out.DatastoreIDs = cloneStringSlice(in.DatastoreIDs)
+ out.DatastoreNames = cloneStringSlice(in.DatastoreNames)
+ out.DatastoreAccessible = cloneBoolPtr(in.DatastoreAccessible)
+ out.MultipleHostAccess = cloneBoolPtr(in.MultipleHostAccess)
+ out.GuestIPAddresses = cloneStringSlice(in.GuestIPAddresses)
return &out
}
diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.go
index 4604ba2200..681d40f5c7 100644
--- a/internal/unifiedresources/registry.go
+++ b/internal/unifiedresources/registry.go
@@ -1120,6 +1120,42 @@ func mergeVMwareData(existing *VMwareData, incoming *VMwareData) *VMwareData {
if incoming.HostUUID != "" {
merged.HostUUID = incoming.HostUUID
}
+ if incoming.DatacenterID != "" {
+ merged.DatacenterID = incoming.DatacenterID
+ }
+ if incoming.DatacenterName != "" {
+ merged.DatacenterName = incoming.DatacenterName
+ }
+ if incoming.ComputeResourceID != "" {
+ merged.ComputeResourceID = incoming.ComputeResourceID
+ }
+ if incoming.ComputeResourceName != "" {
+ merged.ComputeResourceName = incoming.ComputeResourceName
+ }
+ if incoming.ClusterID != "" {
+ merged.ClusterID = incoming.ClusterID
+ }
+ if incoming.ClusterName != "" {
+ merged.ClusterName = incoming.ClusterName
+ }
+ if incoming.FolderID != "" {
+ merged.FolderID = incoming.FolderID
+ }
+ if incoming.FolderName != "" {
+ merged.FolderName = incoming.FolderName
+ }
+ if incoming.ResourcePoolID != "" {
+ merged.ResourcePoolID = incoming.ResourcePoolID
+ }
+ if incoming.ResourcePoolName != "" {
+ merged.ResourcePoolName = incoming.ResourcePoolName
+ }
+ if incoming.RuntimeHostID != "" {
+ merged.RuntimeHostID = incoming.RuntimeHostID
+ }
+ if incoming.RuntimeHostName != "" {
+ merged.RuntimeHostName = incoming.RuntimeHostName
+ }
if incoming.ConnectionState != "" {
merged.ConnectionState = incoming.ConnectionState
}
@@ -1138,6 +1174,39 @@ func mergeVMwareData(existing *VMwareData, incoming *VMwareData) *VMwareData {
if incoming.DatastoreType != "" {
merged.DatastoreType = incoming.DatastoreType
}
+ if len(incoming.DatastoreIDs) > 0 {
+ merged.DatastoreIDs = uniqueStrings(append(cloneStringSlice(merged.DatastoreIDs), incoming.DatastoreIDs...))
+ }
+ if len(incoming.DatastoreNames) > 0 {
+ merged.DatastoreNames = uniqueStrings(append(cloneStringSlice(merged.DatastoreNames), incoming.DatastoreNames...))
+ }
+ if incoming.DatastoreURL != "" {
+ merged.DatastoreURL = incoming.DatastoreURL
+ }
+ if incoming.DatastoreAccessible != nil {
+ merged.DatastoreAccessible = cloneBoolPtr(incoming.DatastoreAccessible)
+ }
+ if incoming.MultipleHostAccess != nil {
+ merged.MultipleHostAccess = cloneBoolPtr(incoming.MultipleHostAccess)
+ }
+ if incoming.MaintenanceMode != "" {
+ merged.MaintenanceMode = incoming.MaintenanceMode
+ }
+ if incoming.InstanceUUID != "" {
+ merged.InstanceUUID = incoming.InstanceUUID
+ }
+ if incoming.BIOSUUID != "" {
+ merged.BIOSUUID = incoming.BIOSUUID
+ }
+ if incoming.GuestOSFamily != "" {
+ merged.GuestOSFamily = incoming.GuestOSFamily
+ }
+ if incoming.GuestHostname != "" {
+ merged.GuestHostname = incoming.GuestHostname
+ }
+ if len(incoming.GuestIPAddresses) > 0 {
+ merged.GuestIPAddresses = uniqueStrings(append(cloneStringSlice(merged.GuestIPAddresses), incoming.GuestIPAddresses...))
+ }
if incoming.ActiveAlarmCount > 0 {
merged.ActiveAlarmCount = incoming.ActiveAlarmCount
}
diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.go
index e051bfa1c2..66588dbf82 100644
--- a/internal/unifiedresources/registry_test.go
+++ b/internal/unifiedresources/registry_test.go
@@ -1,6 +1,7 @@
package unifiedresources
import (
+ "reflect"
"testing"
"time"
@@ -209,22 +210,32 @@ func TestMergeVMwareDataMergesSignalFieldsWithoutDroppingExistingIdentity(t *tes
ManagedObjectID: "vm-101",
EntityType: "vm",
HostUUID: "uuid-host-1",
+ DatacenterName: "DC1",
+ ClusterName: "Cluster A",
+ DatastoreNames: []string{"primary-vmfs"},
ConnectionState: "connected",
PowerState: "poweredOn",
OverallStatus: "green",
+ GuestHostname: "app-01.internal",
ActiveAlarmCount: 1,
ActiveAlarmSummary: "old alarm",
RecentTaskCount: 1,
RecentTaskSummary: "old task",
SnapshotCount: 1,
}
+ accessible := false
incoming := &VMwareData{
- OverallStatus: "yellow",
- ActiveAlarmCount: 3,
- ActiveAlarmSummary: "Host connection lost; datastore latency elevated",
- RecentTaskCount: 2,
- RecentTaskSummary: "vMotion task completed",
- SnapshotCount: 4,
+ ClusterName: "Cluster A",
+ RuntimeHostName: "esxi-01.lab.local",
+ DatastoreNames: []string{"backup-nfs"},
+ DatastoreAccessible: &accessible,
+ GuestIPAddresses: []string{"10.0.0.21"},
+ OverallStatus: "yellow",
+ ActiveAlarmCount: 3,
+ ActiveAlarmSummary: "Host connection lost; datastore latency elevated",
+ RecentTaskCount: 2,
+ RecentTaskSummary: "vMotion task completed",
+ SnapshotCount: 4,
}
merged := mergeVMwareData(existing, incoming)
@@ -255,6 +266,21 @@ func TestMergeVMwareDataMergesSignalFieldsWithoutDroppingExistingIdentity(t *tes
if got := merged.SnapshotCount; got != 4 {
t.Fatalf("snapshot count = %d, want 4", got)
}
+ if got := merged.RuntimeHostName; got != "esxi-01.lab.local" {
+ t.Fatalf("runtime host name = %q, want esxi-01.lab.local", got)
+ }
+ if got := merged.DatastoreNames; !reflect.DeepEqual(got, []string{"primary-vmfs", "backup-nfs"}) {
+ t.Fatalf("datastore names = %#v", got)
+ }
+ if merged.DatastoreAccessible == nil || *merged.DatastoreAccessible {
+ t.Fatalf("datastore accessible = %#v, want false", merged.DatastoreAccessible)
+ }
+ if got := merged.GuestHostname; got != "app-01.internal" {
+ t.Fatalf("guest hostname = %q, want app-01.internal", got)
+ }
+ if got := merged.GuestIPAddresses; !reflect.DeepEqual(got, []string{"10.0.0.21"}) {
+ t.Fatalf("guest ip addresses = %#v", got)
+ }
}
func TestResourceRegistryClonesCarryPolicyMetadata(t *testing.T) {
diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.go
index 1b10e9cf8e..0eb6d56f69 100644
--- a/internal/unifiedresources/types.go
+++ b/internal/unifiedresources/types.go
@@ -931,23 +931,46 @@ type PMGData struct {
// VMwareData contains VMware vSphere metadata for canonical agent, vm, and
// storage resources projected from one vCenter connection.
type VMwareData struct {
- ConnectionID string `json:"connectionId,omitempty"`
- ConnectionName string `json:"connectionName,omitempty"`
- VCenterHost string `json:"vcenterHost,omitempty"`
- ManagedObjectID string `json:"managedObjectId,omitempty"`
- EntityType string `json:"entityType,omitempty"`
- HostUUID string `json:"hostUuid,omitempty"`
- ConnectionState string `json:"connectionState,omitempty"`
- PowerState string `json:"powerState,omitempty"`
- OverallStatus string `json:"overallStatus,omitempty"`
- CPUCount int `json:"cpuCount,omitempty"`
- MemorySizeMiB int64 `json:"memorySizeMib,omitempty"`
- DatastoreType string `json:"datastoreType,omitempty"`
- ActiveAlarmCount int `json:"activeAlarmCount,omitempty"`
- ActiveAlarmSummary string `json:"activeAlarmSummary,omitempty"`
- RecentTaskCount int `json:"recentTaskCount,omitempty"`
- RecentTaskSummary string `json:"recentTaskSummary,omitempty"`
- SnapshotCount int `json:"snapshotCount,omitempty"`
+ ConnectionID string `json:"connectionId,omitempty"`
+ ConnectionName string `json:"connectionName,omitempty"`
+ VCenterHost string `json:"vcenterHost,omitempty"`
+ ManagedObjectID string `json:"managedObjectId,omitempty"`
+ EntityType string `json:"entityType,omitempty"`
+ HostUUID string `json:"hostUuid,omitempty"`
+ DatacenterID string `json:"datacenterId,omitempty"`
+ DatacenterName string `json:"datacenterName,omitempty"`
+ ComputeResourceID string `json:"computeResourceId,omitempty"`
+ ComputeResourceName string `json:"computeResourceName,omitempty"`
+ ClusterID string `json:"clusterId,omitempty"`
+ ClusterName string `json:"clusterName,omitempty"`
+ FolderID string `json:"folderId,omitempty"`
+ FolderName string `json:"folderName,omitempty"`
+ ResourcePoolID string `json:"resourcePoolId,omitempty"`
+ ResourcePoolName string `json:"resourcePoolName,omitempty"`
+ RuntimeHostID string `json:"runtimeHostId,omitempty"`
+ RuntimeHostName string `json:"runtimeHostName,omitempty"`
+ ConnectionState string `json:"connectionState,omitempty"`
+ PowerState string `json:"powerState,omitempty"`
+ OverallStatus string `json:"overallStatus,omitempty"`
+ CPUCount int `json:"cpuCount,omitempty"`
+ MemorySizeMiB int64 `json:"memorySizeMib,omitempty"`
+ DatastoreType string `json:"datastoreType,omitempty"`
+ DatastoreIDs []string `json:"datastoreIds,omitempty"`
+ DatastoreNames []string `json:"datastoreNames,omitempty"`
+ DatastoreURL string `json:"datastoreUrl,omitempty"`
+ DatastoreAccessible *bool `json:"datastoreAccessible,omitempty"`
+ MultipleHostAccess *bool `json:"multipleHostAccess,omitempty"`
+ MaintenanceMode string `json:"maintenanceMode,omitempty"`
+ InstanceUUID string `json:"instanceUuid,omitempty"`
+ BIOSUUID string `json:"biosUuid,omitempty"`
+ GuestOSFamily string `json:"guestOsFamily,omitempty"`
+ GuestHostname string `json:"guestHostname,omitempty"`
+ GuestIPAddresses []string `json:"guestIpAddresses,omitempty"`
+ ActiveAlarmCount int `json:"activeAlarmCount,omitempty"`
+ ActiveAlarmSummary string `json:"activeAlarmSummary,omitempty"`
+ RecentTaskCount int `json:"recentTaskCount,omitempty"`
+ RecentTaskSummary string `json:"recentTaskSummary,omitempty"`
+ SnapshotCount int `json:"snapshotCount,omitempty"`
}
// TrueNASData contains TrueNAS-specific metadata for system host resources.
diff --git a/internal/vmware/client.go b/internal/vmware/client.go
index 2139894d94..b67aec3760 100644
--- a/internal/vmware/client.go
+++ b/internal/vmware/client.go
@@ -143,7 +143,7 @@ func (c *Client) Close() {
// TestConnection validates both the Automation API and VI JSON API families and
// returns a minimal inventory summary on success.
func (c *Client) TestConnection(ctx context.Context) (*InventorySummary, error) {
- inventory, err := c.collectInventoryBase(ctx)
+ inventory, _, err := c.collectInventoryBaseWithSession(ctx)
if err != nil {
return nil, err
}
@@ -173,7 +173,7 @@ func (c *Client) TestConnection(ctx context.Context) (*InventorySummary, error)
// CollectInventory fetches the phase-1 VMware inventory floor used by the
// supplemental-ingest provider.
func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, error) {
- inventory, err := c.collectInventoryBase(ctx)
+ inventory, automationSessionID, err := c.collectInventoryBaseWithSession(ctx)
if err != nil {
return nil, err
}
@@ -192,36 +192,44 @@ func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, erro
if err := c.enrichInventorySnapshot(ctx, release, sessionID, refs.PerfManagerMoID, perfCounters, inventory); err != nil {
return nil, err
}
+ if err := c.enrichInventoryTopology(ctx, automationSessionID, release, sessionID, inventory); err != nil {
+ return nil, err
+ }
inventory.CollectedAt = time.Now().UTC()
return inventory, nil
}
func (c *Client) collectInventoryBase(ctx context.Context) (*InventorySnapshot, error) {
+ snapshot, _, err := c.collectInventoryBaseWithSession(ctx)
+ return snapshot, err
+}
+
+func (c *Client) collectInventoryBaseWithSession(ctx context.Context) (*InventorySnapshot, string, error) {
automationSessionID, err := c.createAutomationSession(ctx)
if err != nil {
- return nil, err
+ return nil, "", err
}
var hosts []InventoryHost
if err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/host", "host inventory", &hosts); err != nil {
- return nil, err
+ return nil, "", err
}
var vms []InventoryVM
if err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/vm", "vm inventory", &vms); err != nil {
- return nil, err
+ return nil, "", err
}
var datastores []InventoryDatastore
if err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/datastore", "datastore inventory", &datastores); err != nil {
- return nil, err
+ return nil, "", err
}
return &InventorySnapshot{
Hosts: hosts,
VMs: vms,
Datastores: datastores,
- }, nil
+ }, automationSessionID, nil
}
func normalizeBaseURL(rawHost string, port int) (*url.URL, error) {
@@ -298,6 +306,16 @@ func (c *Client) listAutomationResources(
path string,
label string,
target any,
+) error {
+ return c.getAutomationJSON(ctx, sessionID, path, label, target)
+}
+
+func (c *Client) getAutomationJSON(
+ ctx context.Context,
+ sessionID string,
+ path string,
+ label string,
+ target any,
) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL.String()+path, nil)
if err != nil {
@@ -320,6 +338,16 @@ func (c *Client) listAutomationResources(
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),
+ }
+ case http.StatusServiceUnavailable:
+ return &ConnectionError{
+ Category: "unavailable",
+ Message: fmt.Sprintf("VMware %s is temporarily unavailable", label),
+ }
default:
return &ConnectionError{
Category: "endpoint",
diff --git a/internal/vmware/client_test.go b/internal/vmware/client_test.go
index 0ec0888d1a..58153372b5 100644
--- a/internal/vmware/client_test.go
+++ b/internal/vmware/client_test.go
@@ -40,6 +40,12 @@ func TestClientCollectInventoryEnrichesSignals(t *testing.T) {
if host.OverallStatus != "yellow" {
t.Fatalf("host overall status = %q, want yellow", host.OverallStatus)
}
+ if host.ClusterName != "Prod Compute" || host.DatacenterName != "DC1" {
+ t.Fatalf("expected host placement enrichment, got cluster=%q datacenter=%q", host.ClusterName, host.DatacenterName)
+ }
+ if len(host.DatastoreNames) != 1 || host.DatastoreNames[0] != "nvme-primary" {
+ t.Fatalf("expected host datastore names, got %+v", host.DatastoreNames)
+ }
if host.Metrics == nil || host.Metrics.CPUPercent == nil || *host.Metrics.CPUPercent != 21.4 {
t.Fatalf("expected host cpu metrics, got %+v", host.Metrics)
}
@@ -57,6 +63,15 @@ func TestClientCollectInventoryEnrichesSignals(t *testing.T) {
if len(vm.TriggeredAlarms) != 1 || vm.TriggeredAlarms[0].OverallStatus != "red" {
t.Fatalf("expected VM alarm signals, got %+v", vm.TriggeredAlarms)
}
+ if vm.RuntimeHostName != "esxi-01.lab.local" || vm.ResourcePoolName != "Tier 1" {
+ t.Fatalf("expected VM placement enrichment, got host=%q pool=%q", vm.RuntimeHostName, vm.ResourcePoolName)
+ }
+ if vm.InstanceUUID != "vm-instance-201" || vm.BIOSUUID != "vm-bios-201" {
+ t.Fatalf("expected VM identity enrichment, got instance=%q bios=%q", vm.InstanceUUID, vm.BIOSUUID)
+ }
+ if vm.GuestHostname != "app-01.internal" || len(vm.GuestIPAddresses) != 1 || vm.GuestIPAddresses[0] != "10.0.0.21" {
+ t.Fatalf("expected VM guest identity enrichment, got host=%q ips=%v", vm.GuestHostname, vm.GuestIPAddresses)
+ }
if vm.SnapshotCount != 2 {
t.Fatalf("vm snapshot count = %d, want 2", vm.SnapshotCount)
}
@@ -68,6 +83,15 @@ func TestClientCollectInventoryEnrichesSignals(t *testing.T) {
if datastore.OverallStatus != "yellow" {
t.Fatalf("datastore overall status = %q, want yellow", datastore.OverallStatus)
}
+ if datastore.Accessible == nil || !*datastore.Accessible {
+ t.Fatalf("expected datastore accessibility enrichment, got %+v", datastore.Accessible)
+ }
+ if len(datastore.HostNames) != 1 || datastore.HostNames[0] != "esxi-01.lab.local" {
+ t.Fatalf("expected datastore host attachment enrichment, got %+v", datastore.HostNames)
+ }
+ if len(datastore.VMNames) != 1 || datastore.VMNames[0] != "app-01" {
+ t.Fatalf("expected datastore VM attachment enrichment, got %+v", datastore.VMNames)
+ }
if len(datastore.RecentTasks) != 1 || datastore.RecentTasks[0].Name != "Refresh datastore" {
t.Fatalf("expected datastore recent task info, got %+v", datastore.RecentTasks)
}
@@ -157,6 +181,23 @@ func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Ser
Capacity: 100,
}})
})
+ mux.HandleFunc("/api/vcenter/vm/vm-201", func(w http.ResponseWriter, r *http.Request) {
+ requireAutomationSession(t, r)
+ writeJSON(w, map[string]any{
+ "identity": map[string]any{
+ "bios_uuid": "vm-bios-201",
+ "instance_uuid": "vm-instance-201",
+ },
+ })
+ })
+ mux.HandleFunc("/api/vcenter/vm/vm-201/guest/identity", func(w http.ResponseWriter, r *http.Request) {
+ requireAutomationSession(t, r)
+ writeJSON(w, map[string]any{
+ "family": "LINUX",
+ "host_name": "app-01.internal",
+ "ip_address": "10.0.0.21",
+ })
+ })
mux.HandleFunc("/sdk/vim25/9.0.0.0/ServiceInstance/ServiceInstance/content", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, map[string]any{
@@ -287,6 +328,18 @@ func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Ser
requireVISession(t, r)
writeJSON(w, []map[string]any{{"type": "Task", "value": "task-11"}})
})
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "esxi-01.lab.local")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "ClusterComputeResource", "value": "domain-c101"})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/HostSystem/host-101/datastore", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, []map[string]any{{"type": "Datastore", "value": "datastore-11"}})
+ })
mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/overallStatus", func(w http.ResponseWriter, r *http.Request) {
requireVISession(t, r)
@@ -313,6 +366,24 @@ func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Ser
}},
})
})
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "Folder", "value": "group-v7"})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/runtime", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{
+ "host": map[string]any{"type": "HostSystem", "value": "host-101"},
+ })
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/resourcePool", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "ResourcePool", "value": "resgroup-22"})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/VirtualMachine/vm-201/datastore", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, []map[string]any{{"type": "Datastore", "value": "datastore-11"}})
+ })
mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/overallStatus", func(w http.ResponseWriter, r *http.Request) {
requireVISession(t, r)
@@ -326,6 +397,79 @@ func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Ser
requireVISession(t, r)
writeJSON(w, []map[string]any{{"type": "Task", "value": "task-31"}})
})
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "nvme-primary")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "Folder", "value": "group-s4"})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/summary", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{
+ "accessible": true,
+ "multipleHostAccess": true,
+ "maintenanceMode": "normal",
+ "url": "ds:///vmfs/volumes/datastore-11/",
+ })
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/host", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, []map[string]any{{"type": "HostSystem", "value": "host-101"}})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datastore/datastore-11/vm", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, []map[string]any{{"type": "VirtualMachine", "value": "vm-201"}})
+ })
+
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/ClusterComputeResource/domain-c101/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "Prod Compute")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/ClusterComputeResource/domain-c101/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "Folder", "value": "group-h4"})
+ })
+
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Folder/group-h4/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "Prod Hosts")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Folder/group-h4/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "Datacenter", "value": "datacenter-1"})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Folder/group-v7/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "Production VMs")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Folder/group-v7/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "Datacenter", "value": "datacenter-1"})
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Folder/group-s4/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "Shared Datastores")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Folder/group-s4/parent", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "Datacenter", "value": "datacenter-1"})
+ })
+
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/Datacenter/datacenter-1/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "DC1")
+ })
+
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/ResourcePool/resgroup-22/name", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, "Tier 1")
+ })
+ mux.HandleFunc("/sdk/vim25/9.0.0.0/ResourcePool/resgroup-22/owner", func(w http.ResponseWriter, r *http.Request) {
+ requireVISession(t, r)
+ writeJSON(w, map[string]any{"type": "ClusterComputeResource", "value": "domain-c101"})
+ })
mux.HandleFunc("/sdk/vim25/9.0.0.0/Alarm/alarm-11/info", func(w http.ResponseWriter, r *http.Request) {
requireVISession(t, r)
diff --git a/internal/vmware/client_topology.go b/internal/vmware/client_topology.go
new file mode 100644
index 0000000000..313c4052c2
--- /dev/null
+++ b/internal/vmware/client_topology.go
@@ -0,0 +1,792 @@
+package vmware
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+)
+
+type vcenterVMIdentity struct {
+ BIOSUUID string `json:"bios_uuid"`
+ InstanceUUID string `json:"instance_uuid"`
+}
+
+type vcenterVMInfo struct {
+ Identity *vcenterVMIdentity `json:"identity"`
+}
+
+type vcenterVMGuestIdentity struct {
+ Family string `json:"family"`
+ HostName string `json:"host_name"`
+ IPAddr string `json:"ip_address"`
+}
+
+type viJSONVirtualMachineRuntimeInfo struct {
+ Host *viJSONReference `json:"host"`
+}
+
+type viJSONDatastoreSummary struct {
+ Accessible *bool `json:"accessible"`
+ MultipleHostAccess *bool `json:"multipleHostAccess"`
+ MaintenanceMode string `json:"maintenanceMode"`
+ URL string `json:"url"`
+}
+
+type vmwarePlacement struct {
+ DatacenterID string
+ DatacenterName string
+ ComputeResourceID string
+ ComputeResourceName string
+ ClusterID string
+ ClusterName string
+ FolderID string
+ FolderName string
+}
+
+type vmwareTopologyCache struct {
+ mu sync.Mutex
+
+ nameLoaded map[string]bool
+ names map[string]string
+
+ parentLoaded map[string]bool
+ parents map[string]*viJSONReference
+
+ ownerLoaded map[string]bool
+ owners map[string]*viJSONReference
+
+ placementLoaded map[string]bool
+ placements map[string]vmwarePlacement
+}
+
+func newVMwareTopologyCache() *vmwareTopologyCache {
+ return &vmwareTopologyCache{
+ nameLoaded: make(map[string]bool),
+ names: make(map[string]string),
+ parentLoaded: make(map[string]bool),
+ parents: make(map[string]*viJSONReference),
+ ownerLoaded: make(map[string]bool),
+ owners: make(map[string]*viJSONReference),
+ placementLoaded: make(map[string]bool),
+ placements: make(map[string]vmwarePlacement),
+ }
+}
+
+func (c *Client) enrichInventoryTopology(
+ ctx context.Context,
+ automationSessionID string,
+ release string,
+ sessionID string,
+ snapshot *InventorySnapshot,
+) error {
+ if snapshot == nil {
+ return nil
+ }
+
+ hostNamesByID := make(map[string]string, len(snapshot.Hosts))
+ for _, host := range snapshot.Hosts {
+ hostNamesByID[strings.TrimSpace(host.Host)] = firstNonEmptyTrimmed(host.Name, host.Host)
+ }
+ vmNamesByID := make(map[string]string, len(snapshot.VMs))
+ for _, vm := range snapshot.VMs {
+ vmNamesByID[strings.TrimSpace(vm.VM)] = firstNonEmptyTrimmed(vm.Name, vm.VM)
+ }
+ datastoreNamesByID := make(map[string]string, len(snapshot.Datastores))
+ for _, datastore := range snapshot.Datastores {
+ datastoreNamesByID[strings.TrimSpace(datastore.Datastore)] = firstNonEmptyTrimmed(datastore.Name, datastore.Datastore)
+ }
+
+ cache := newVMwareTopologyCache()
+ sem := make(chan struct{}, vmwareSignalEnrichmentConcurrency)
+ var wg sync.WaitGroup
+ var firstErr error
+ var firstErrMu sync.Mutex
+
+ run := func(fn func() error) {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+
+ if err := fn(); err != nil {
+ firstErrMu.Lock()
+ if firstErr == nil {
+ firstErr = err
+ }
+ firstErrMu.Unlock()
+ }
+ }()
+ }
+
+ for i := range snapshot.Hosts {
+ i := i
+ run(func() error {
+ host, err := c.enrichHostTopology(ctx, release, sessionID, snapshot.Hosts[i], cache, datastoreNamesByID)
+ if err != nil {
+ return err
+ }
+ snapshot.Hosts[i] = host
+ return nil
+ })
+ }
+
+ for i := range snapshot.VMs {
+ i := i
+ run(func() error {
+ vm, err := c.enrichVMTopology(
+ ctx,
+ automationSessionID,
+ release,
+ sessionID,
+ snapshot.VMs[i],
+ cache,
+ hostNamesByID,
+ datastoreNamesByID,
+ )
+ if err != nil {
+ return err
+ }
+ snapshot.VMs[i] = vm
+ return nil
+ })
+ }
+
+ for i := range snapshot.Datastores {
+ i := i
+ run(func() error {
+ datastore, err := c.enrichDatastoreTopology(ctx, release, sessionID, snapshot.Datastores[i], cache, hostNamesByID, vmNamesByID)
+ if err != nil {
+ return err
+ }
+ snapshot.Datastores[i] = datastore
+ return nil
+ })
+ }
+
+ wg.Wait()
+
+ firstErrMu.Lock()
+ defer firstErrMu.Unlock()
+ return firstErr
+}
+
+func (c *Client) enrichHostTopology(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ host InventoryHost,
+ cache *vmwareTopologyCache,
+ datastoreNamesByID map[string]string,
+) (InventoryHost, error) {
+ ref := viJSONReference{Type: "HostSystem", Value: strings.TrimSpace(host.Host)}
+ placement, err := cache.resolvePlacement(ctx, c, release, sessionID, ref)
+ if err != nil && !isVIJSONNotFound(err) {
+ return host, err
+ }
+ applyPlacementToHost(&host, placement)
+
+ datastoreRefs, err := c.collectEntityReferenceList(ctx, release, sessionID, "HostSystem", host.Host, "datastore", "host datastore attachments")
+ if err != nil && !isVIJSONNotFound(err) {
+ return host, err
+ }
+ host.DatastoreIDs = idsForReferences(datastoreRefs)
+ host.DatastoreNames = namesForReferences(datastoreRefs, datastoreNamesByID)
+
+ return host, nil
+}
+
+func (c *Client) enrichVMTopology(
+ ctx context.Context,
+ automationSessionID string,
+ release string,
+ sessionID string,
+ vm InventoryVM,
+ cache *vmwareTopologyCache,
+ hostNamesByID map[string]string,
+ datastoreNamesByID map[string]string,
+) (InventoryVM, error) {
+ vmInfo, err := c.collectVMAutomationInfo(ctx, automationSessionID, vm.VM)
+ if err != nil && !isAutomationNotFound(err) {
+ return vm, err
+ }
+ if vmInfo != nil && vmInfo.Identity != nil {
+ vm.InstanceUUID = strings.TrimSpace(vmInfo.Identity.InstanceUUID)
+ vm.BIOSUUID = strings.TrimSpace(vmInfo.Identity.BIOSUUID)
+ }
+
+ guestIdentity, err := c.collectVMGuestIdentity(ctx, automationSessionID, vm.VM)
+ if err != nil && !isAutomationNotFound(err) && !isAutomationUnavailable(err) {
+ return vm, err
+ }
+ if guestIdentity != nil {
+ vm.GuestOSFamily = strings.TrimSpace(guestIdentity.Family)
+ vm.GuestHostname = strings.TrimSpace(guestIdentity.HostName)
+ if ip := strings.TrimSpace(guestIdentity.IPAddr); ip != "" {
+ vm.GuestIPAddresses = []string{ip}
+ }
+ }
+
+ var placement vmwarePlacement
+
+ parentRef, err := c.collectEntityReference(ctx, release, sessionID, "VirtualMachine", vm.VM, "parent", "vm parent placement")
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ if parentRef != nil {
+ parentPlacement, err := cache.resolvePlacement(ctx, c, release, sessionID, *parentRef)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ mergePlacement(&placement, parentPlacement)
+ }
+
+ runtimeHostRef, err := c.collectVMRuntimeHostReference(ctx, release, sessionID, vm.VM)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ if runtimeHostRef != nil {
+ vm.RuntimeHostID = strings.TrimSpace(runtimeHostRef.Value)
+ vm.RuntimeHostName = firstNonEmptyTrimmed(hostNamesByID[vm.RuntimeHostID], vm.RuntimeHostID)
+ hostPlacement, err := cache.resolvePlacement(ctx, c, release, sessionID, *runtimeHostRef)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ mergePlacement(&placement, hostPlacement)
+ }
+
+ resourcePoolRef, err := c.collectEntityReference(ctx, release, sessionID, "VirtualMachine", vm.VM, "resourcePool", "vm resource pool")
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ if resourcePoolRef != nil {
+ vm.ResourcePoolID = strings.TrimSpace(resourcePoolRef.Value)
+ resourcePoolName, err := cache.resolveName(ctx, c, release, sessionID, *resourcePoolRef)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ vm.ResourcePoolName = firstNonEmptyTrimmed(resourcePoolName, vm.ResourcePoolID)
+
+ ownerRef, err := cache.resolveResourcePoolOwner(ctx, c, release, sessionID, *resourcePoolRef)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ if ownerRef != nil {
+ ownerPlacement, err := cache.resolvePlacement(ctx, c, release, sessionID, *ownerRef)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ mergePlacement(&placement, ownerPlacement)
+ }
+ }
+
+ datastoreRefs, err := c.collectEntityReferenceList(ctx, release, sessionID, "VirtualMachine", vm.VM, "datastore", "vm datastore attachments")
+ if err != nil && !isVIJSONNotFound(err) {
+ return vm, err
+ }
+ vm.DatastoreIDs = idsForReferences(datastoreRefs)
+ vm.DatastoreNames = namesForReferences(datastoreRefs, datastoreNamesByID)
+
+ applyPlacementToVM(&vm, placement)
+ return vm, nil
+}
+
+func (c *Client) enrichDatastoreTopology(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ datastore InventoryDatastore,
+ cache *vmwareTopologyCache,
+ hostNamesByID map[string]string,
+ vmNamesByID map[string]string,
+) (InventoryDatastore, error) {
+ ref := viJSONReference{Type: "Datastore", Value: strings.TrimSpace(datastore.Datastore)}
+ placement, err := cache.resolvePlacement(ctx, c, release, sessionID, ref)
+ if err != nil && !isVIJSONNotFound(err) {
+ return datastore, err
+ }
+ applyPlacementToDatastore(&datastore, placement)
+
+ summary, err := c.collectDatastoreSummary(ctx, release, sessionID, datastore.Datastore)
+ if err != nil && !isVIJSONNotFound(err) {
+ return datastore, err
+ }
+ if summary != nil {
+ datastore.Accessible = summary.Accessible
+ datastore.MultipleHostAccess = summary.MultipleHostAccess
+ datastore.MaintenanceMode = strings.TrimSpace(summary.MaintenanceMode)
+ datastore.URL = strings.TrimSpace(summary.URL)
+ }
+
+ hostRefs, err := c.collectEntityReferenceList(ctx, release, sessionID, "Datastore", datastore.Datastore, "host", "datastore host attachments")
+ if err != nil && !isVIJSONNotFound(err) {
+ return datastore, err
+ }
+ datastore.HostIDs = idsForReferences(hostRefs)
+ datastore.HostNames = namesForReferences(hostRefs, hostNamesByID)
+
+ vmRefs, err := c.collectEntityReferenceList(ctx, release, sessionID, "Datastore", datastore.Datastore, "vm", "datastore vm attachments")
+ if err != nil && !isVIJSONNotFound(err) {
+ return datastore, err
+ }
+ datastore.VMIDs = idsForReferences(vmRefs)
+ datastore.VMNames = namesForReferences(vmRefs, vmNamesByID)
+
+ return datastore, nil
+}
+
+func (c *Client) collectVMAutomationInfo(
+ ctx context.Context,
+ automationSessionID string,
+ vmID string,
+) (*vcenterVMInfo, error) {
+ vmID = strings.TrimSpace(vmID)
+ if vmID == "" || strings.TrimSpace(automationSessionID) == "" {
+ return nil, nil
+ }
+ var payload vcenterVMInfo
+ path := fmt.Sprintf("/api/vcenter/vm/%s", vmID)
+ if err := c.getAutomationJSON(ctx, automationSessionID, path, "vm detail", &payload); err != nil {
+ return nil, err
+ }
+ return &payload, nil
+}
+
+func (c *Client) collectVMGuestIdentity(
+ ctx context.Context,
+ automationSessionID string,
+ vmID string,
+) (*vcenterVMGuestIdentity, error) {
+ vmID = strings.TrimSpace(vmID)
+ if vmID == "" || strings.TrimSpace(automationSessionID) == "" {
+ return nil, nil
+ }
+ var payload vcenterVMGuestIdentity
+ path := fmt.Sprintf("/api/vcenter/vm/%s/guest/identity", vmID)
+ if err := c.getAutomationJSON(ctx, automationSessionID, path, "vm guest identity", &payload); err != nil {
+ return nil, err
+ }
+ return &payload, nil
+}
+
+func (c *Client) collectVMRuntimeHostReference(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ vmID string,
+) (*viJSONReference, error) {
+ vmID = strings.TrimSpace(vmID)
+ if vmID == "" {
+ return nil, nil
+ }
+ var runtime viJSONVirtualMachineRuntimeInfo
+ path := fmt.Sprintf("/sdk/vim25/%s/VirtualMachine/%s/runtime", release, vmID)
+ if err := c.getVIJSONJSON(ctx, sessionID, path, "vm runtime placement", &runtime); err != nil {
+ return nil, err
+ }
+ return cloneVIJSONReference(runtime.Host), nil
+}
+
+func (c *Client) collectDatastoreSummary(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ datastoreID string,
+) (*viJSONDatastoreSummary, error) {
+ datastoreID = strings.TrimSpace(datastoreID)
+ if datastoreID == "" {
+ return nil, nil
+ }
+ var summary viJSONDatastoreSummary
+ path := fmt.Sprintf("/sdk/vim25/%s/Datastore/%s/summary", release, datastoreID)
+ if err := c.getVIJSONJSON(ctx, sessionID, path, "datastore summary", &summary); err != nil {
+ return nil, err
+ }
+ return &summary, nil
+}
+
+func (c *Client) collectEntityReference(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ managedType string,
+ managedObjectID string,
+ property string,
+ label string,
+) (*viJSONReference, error) {
+ managedObjectID = strings.TrimSpace(managedObjectID)
+ if managedObjectID == "" {
+ return nil, nil
+ }
+ var ref *viJSONReference
+ path := fmt.Sprintf("/sdk/vim25/%s/%s/%s/%s", release, managedType, managedObjectID, property)
+ if err := c.getVIJSONJSON(ctx, sessionID, path, label, &ref); err != nil {
+ return nil, err
+ }
+ return cloneVIJSONReference(ref), nil
+}
+
+func (c *Client) collectEntityReferenceList(
+ ctx context.Context,
+ release string,
+ sessionID string,
+ managedType string,
+ managedObjectID string,
+ property string,
+ label string,
+) ([]viJSONReference, error) {
+ managedObjectID = strings.TrimSpace(managedObjectID)
+ if managedObjectID == "" {
+ return nil, nil
+ }
+ var refs []viJSONReference
+ path := fmt.Sprintf("/sdk/vim25/%s/%s/%s/%s", release, managedType, managedObjectID, property)
+ if err := c.getVIJSONJSON(ctx, sessionID, path, label, &refs); err != nil {
+ return nil, err
+ }
+ return cloneVIJSONReferences(refs), nil
+}
+
+func (cache *vmwareTopologyCache) resolvePlacement(
+ ctx context.Context,
+ client *Client,
+ release string,
+ sessionID string,
+ ref viJSONReference,
+) (vmwarePlacement, error) {
+ key := managedObjectKey(ref.Type, ref.Value)
+ if key == "" {
+ return vmwarePlacement{}, nil
+ }
+
+ cache.mu.Lock()
+ if cache.placementLoaded[key] {
+ placement := cache.placements[key]
+ cache.mu.Unlock()
+ return placement, nil
+ }
+ cache.mu.Unlock()
+
+ placement := vmwarePlacement{}
+ name, err := cache.resolveName(ctx, client, release, sessionID, ref)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vmwarePlacement{}, err
+ }
+ name = firstNonEmptyTrimmed(name, ref.Value)
+
+ switch strings.TrimSpace(ref.Type) {
+ case "Datacenter":
+ placement.DatacenterID = strings.TrimSpace(ref.Value)
+ placement.DatacenterName = name
+ case "Folder":
+ placement.FolderID = strings.TrimSpace(ref.Value)
+ placement.FolderName = name
+ case "ClusterComputeResource":
+ placement.ClusterID = strings.TrimSpace(ref.Value)
+ placement.ClusterName = name
+ placement.ComputeResourceID = strings.TrimSpace(ref.Value)
+ placement.ComputeResourceName = name
+ case "ComputeResource":
+ placement.ComputeResourceID = strings.TrimSpace(ref.Value)
+ placement.ComputeResourceName = name
+ }
+
+ parentRef, err := cache.resolveParent(ctx, client, release, sessionID, ref)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vmwarePlacement{}, err
+ }
+ if parentRef != nil {
+ parentPlacement, err := cache.resolvePlacement(ctx, client, release, sessionID, *parentRef)
+ if err != nil && !isVIJSONNotFound(err) {
+ return vmwarePlacement{}, err
+ }
+ mergePlacement(&placement, parentPlacement)
+ }
+
+ cache.mu.Lock()
+ cache.placementLoaded[key] = true
+ cache.placements[key] = placement
+ cache.mu.Unlock()
+ return placement, nil
+}
+
+func (cache *vmwareTopologyCache) resolveName(
+ ctx context.Context,
+ client *Client,
+ release string,
+ sessionID string,
+ ref viJSONReference,
+) (string, error) {
+ key := managedObjectKey(ref.Type, ref.Value)
+ if key == "" {
+ return "", nil
+ }
+
+ cache.mu.Lock()
+ if cache.nameLoaded[key] {
+ name := cache.names[key]
+ cache.mu.Unlock()
+ return name, nil
+ }
+ cache.mu.Unlock()
+
+ var name string
+ path := fmt.Sprintf("/sdk/vim25/%s/%s/%s/name", release, ref.Type, ref.Value)
+ if err := client.getVIJSONJSON(ctx, sessionID, path, strings.ToLower(strings.TrimSpace(ref.Type))+" name", &name); err != nil {
+ return "", err
+ }
+ name = strings.TrimSpace(name)
+
+ cache.mu.Lock()
+ cache.nameLoaded[key] = true
+ cache.names[key] = name
+ cache.mu.Unlock()
+ return name, nil
+}
+
+func (cache *vmwareTopologyCache) resolveParent(
+ ctx context.Context,
+ client *Client,
+ release string,
+ sessionID string,
+ ref viJSONReference,
+) (*viJSONReference, error) {
+ key := managedObjectKey(ref.Type, ref.Value)
+ if key == "" {
+ return nil, nil
+ }
+
+ cache.mu.Lock()
+ if cache.parentLoaded[key] {
+ parent := cloneVIJSONReference(cache.parents[key])
+ cache.mu.Unlock()
+ return parent, nil
+ }
+ cache.mu.Unlock()
+
+ parent, err := client.collectEntityReference(
+ ctx,
+ release,
+ sessionID,
+ strings.TrimSpace(ref.Type),
+ strings.TrimSpace(ref.Value),
+ "parent",
+ strings.ToLower(strings.TrimSpace(ref.Type))+" parent",
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ cache.mu.Lock()
+ cache.parentLoaded[key] = true
+ cache.parents[key] = cloneVIJSONReference(parent)
+ cache.mu.Unlock()
+ return parent, nil
+}
+
+func (cache *vmwareTopologyCache) resolveResourcePoolOwner(
+ ctx context.Context,
+ client *Client,
+ release string,
+ sessionID string,
+ ref viJSONReference,
+) (*viJSONReference, error) {
+ key := managedObjectKey(ref.Type, ref.Value)
+ if key == "" {
+ return nil, nil
+ }
+
+ cache.mu.Lock()
+ if cache.ownerLoaded[key] {
+ owner := cloneVIJSONReference(cache.owners[key])
+ cache.mu.Unlock()
+ return owner, nil
+ }
+ cache.mu.Unlock()
+
+ owner, err := client.collectEntityReference(
+ ctx,
+ release,
+ sessionID,
+ "ResourcePool",
+ strings.TrimSpace(ref.Value),
+ "owner",
+ "resource pool owner",
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ cache.mu.Lock()
+ cache.ownerLoaded[key] = true
+ cache.owners[key] = cloneVIJSONReference(owner)
+ cache.mu.Unlock()
+ return owner, nil
+}
+
+func applyPlacementToHost(host *InventoryHost, placement vmwarePlacement) {
+ if host == nil {
+ return
+ }
+ host.DatacenterID = firstNonEmptyTrimmed(host.DatacenterID, placement.DatacenterID)
+ host.DatacenterName = firstNonEmptyTrimmed(host.DatacenterName, placement.DatacenterName)
+ host.ComputeResourceID = firstNonEmptyTrimmed(host.ComputeResourceID, placement.ComputeResourceID)
+ host.ComputeResourceName = firstNonEmptyTrimmed(host.ComputeResourceName, placement.ComputeResourceName)
+ host.ClusterID = firstNonEmptyTrimmed(host.ClusterID, placement.ClusterID)
+ host.ClusterName = firstNonEmptyTrimmed(host.ClusterName, placement.ClusterName)
+ host.FolderID = firstNonEmptyTrimmed(host.FolderID, placement.FolderID)
+ host.FolderName = firstNonEmptyTrimmed(host.FolderName, placement.FolderName)
+}
+
+func applyPlacementToVM(vm *InventoryVM, placement vmwarePlacement) {
+ if vm == nil {
+ return
+ }
+ vm.DatacenterID = firstNonEmptyTrimmed(vm.DatacenterID, placement.DatacenterID)
+ vm.DatacenterName = firstNonEmptyTrimmed(vm.DatacenterName, placement.DatacenterName)
+ vm.ComputeResourceID = firstNonEmptyTrimmed(vm.ComputeResourceID, placement.ComputeResourceID)
+ vm.ComputeResourceName = firstNonEmptyTrimmed(vm.ComputeResourceName, placement.ComputeResourceName)
+ vm.ClusterID = firstNonEmptyTrimmed(vm.ClusterID, placement.ClusterID)
+ vm.ClusterName = firstNonEmptyTrimmed(vm.ClusterName, placement.ClusterName)
+ vm.FolderID = firstNonEmptyTrimmed(vm.FolderID, placement.FolderID)
+ vm.FolderName = firstNonEmptyTrimmed(vm.FolderName, placement.FolderName)
+}
+
+func applyPlacementToDatastore(datastore *InventoryDatastore, placement vmwarePlacement) {
+ if datastore == nil {
+ return
+ }
+ datastore.DatacenterID = firstNonEmptyTrimmed(datastore.DatacenterID, placement.DatacenterID)
+ datastore.DatacenterName = firstNonEmptyTrimmed(datastore.DatacenterName, placement.DatacenterName)
+ datastore.FolderID = firstNonEmptyTrimmed(datastore.FolderID, placement.FolderID)
+ datastore.FolderName = firstNonEmptyTrimmed(datastore.FolderName, placement.FolderName)
+}
+
+func mergePlacement(dst *vmwarePlacement, src vmwarePlacement) {
+ if dst == nil {
+ return
+ }
+ if dst.DatacenterID == "" {
+ dst.DatacenterID = strings.TrimSpace(src.DatacenterID)
+ }
+ if dst.DatacenterName == "" {
+ dst.DatacenterName = strings.TrimSpace(src.DatacenterName)
+ }
+ if dst.ComputeResourceID == "" {
+ dst.ComputeResourceID = strings.TrimSpace(src.ComputeResourceID)
+ }
+ if dst.ComputeResourceName == "" {
+ dst.ComputeResourceName = strings.TrimSpace(src.ComputeResourceName)
+ }
+ if dst.ClusterID == "" {
+ dst.ClusterID = strings.TrimSpace(src.ClusterID)
+ }
+ if dst.ClusterName == "" {
+ dst.ClusterName = strings.TrimSpace(src.ClusterName)
+ }
+ if dst.FolderID == "" {
+ dst.FolderID = strings.TrimSpace(src.FolderID)
+ }
+ if dst.FolderName == "" {
+ dst.FolderName = strings.TrimSpace(src.FolderName)
+ }
+}
+
+func idsForReferences(refs []viJSONReference) []string {
+ ids := make([]string, 0, len(refs))
+ for _, ref := range refs {
+ if id := strings.TrimSpace(ref.Value); id != "" {
+ ids = append(ids, id)
+ }
+ }
+ return uniqueSortedTrimmedStrings(ids)
+}
+
+func namesForReferences(refs []viJSONReference, namesByID map[string]string) []string {
+ names := make([]string, 0, len(refs))
+ for _, ref := range refs {
+ id := strings.TrimSpace(ref.Value)
+ if id == "" {
+ continue
+ }
+ name := firstNonEmptyTrimmed(namesByID[id], id)
+ if name != "" {
+ names = append(names, name)
+ }
+ }
+ return uniqueSortedTrimmedStrings(names)
+}
+
+func cloneVIJSONReference(in *viJSONReference) *viJSONReference {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ out.Type = strings.TrimSpace(out.Type)
+ out.Value = strings.TrimSpace(out.Value)
+ return &out
+}
+
+func cloneVIJSONReferences(in []viJSONReference) []viJSONReference {
+ if in == nil {
+ return nil
+ }
+ out := make([]viJSONReference, 0, len(in))
+ for _, ref := range in {
+ trimmed := viJSONReference{
+ Type: strings.TrimSpace(ref.Type),
+ Value: strings.TrimSpace(ref.Value),
+ }
+ if trimmed.Value == "" {
+ continue
+ }
+ out = append(out, trimmed)
+ }
+ return out
+}
+
+func managedObjectKey(managedType, managedObjectID string) string {
+ managedType = strings.TrimSpace(managedType)
+ managedObjectID = strings.TrimSpace(managedObjectID)
+ if managedType == "" || managedObjectID == "" {
+ return ""
+ }
+ return managedType + "/" + managedObjectID
+}
+
+func uniqueSortedTrimmedStrings(values []string) []string {
+ if len(values) == 0 {
+ return nil
+ }
+ seen := make(map[string]struct{}, len(values))
+ out := make([]string, 0, len(values))
+ for _, value := range values {
+ trimmed := strings.TrimSpace(value)
+ if trimmed == "" {
+ continue
+ }
+ key := strings.ToLower(trimmed)
+ if _, ok := seen[key]; ok {
+ continue
+ }
+ seen[key] = struct{}{}
+ out = append(out, trimmed)
+ }
+ sort.Strings(out)
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
+func isAutomationNotFound(err error) bool {
+ connectionErr, ok := err.(*ConnectionError)
+ return ok && connectionErr.Category == "not_found"
+}
+
+func isAutomationUnavailable(err error) bool {
+ connectionErr, ok := err.(*ConnectionError)
+ return ok && connectionErr.Category == "unavailable"
+}
diff --git a/internal/vmware/provider.go b/internal/vmware/provider.go
index 66a12237d8..d27b050ca2 100644
--- a/internal/vmware/provider.go
+++ b/internal/vmware/provider.go
@@ -46,43 +46,84 @@ type InventoryMetrics struct {
// 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"`
- Metrics *InventoryMetrics `json:"metrics,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"`
+ DatacenterID string `json:"datacenter_id,omitempty"`
+ DatacenterName string `json:"datacenter_name,omitempty"`
+ ComputeResourceID string `json:"compute_resource_id,omitempty"`
+ ComputeResourceName string `json:"compute_resource_name,omitempty"`
+ ClusterID string `json:"cluster_id,omitempty"`
+ ClusterName string `json:"cluster_name,omitempty"`
+ FolderID string `json:"folder_id,omitempty"`
+ FolderName string `json:"folder_name,omitempty"`
+ DatastoreIDs []string `json:"datastore_ids,omitempty"`
+ DatastoreNames []string `json:"datastore_names,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"`
- Metrics *InventoryMetrics `json:"metrics,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"`
+ DatacenterID string `json:"datacenter_id,omitempty"`
+ DatacenterName string `json:"datacenter_name,omitempty"`
+ ComputeResourceID string `json:"compute_resource_id,omitempty"`
+ ComputeResourceName string `json:"compute_resource_name,omitempty"`
+ ClusterID string `json:"cluster_id,omitempty"`
+ ClusterName string `json:"cluster_name,omitempty"`
+ FolderID string `json:"folder_id,omitempty"`
+ FolderName string `json:"folder_name,omitempty"`
+ ResourcePoolID string `json:"resource_pool_id,omitempty"`
+ ResourcePoolName string `json:"resource_pool_name,omitempty"`
+ RuntimeHostID string `json:"runtime_host_id,omitempty"`
+ RuntimeHostName string `json:"runtime_host_name,omitempty"`
+ DatastoreIDs []string `json:"datastore_ids,omitempty"`
+ DatastoreNames []string `json:"datastore_names,omitempty"`
+ InstanceUUID string `json:"instance_uuid,omitempty"`
+ BIOSUUID string `json:"bios_uuid,omitempty"`
+ GuestOSFamily string `json:"guest_os_family,omitempty"`
+ GuestHostname string `json:"guest_hostname,omitempty"`
+ GuestIPAddresses []string `json:"guest_ip_addresses,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
// the vCenter Automation API list endpoint.
type InventoryDatastore struct {
- Datastore string `json:"datastore"`
- Name string `json:"name"`
- Type string `json:"type"`
- FreeSpace int64 `json:"free_space,omitempty"`
- Capacity int64 `json:"capacity,omitempty"`
- OverallStatus string `json:"overall_status,omitempty"`
- TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
- RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
+ Datastore string `json:"datastore"`
+ Name string `json:"name"`
+ Type string `json:"type"`
+ FreeSpace int64 `json:"free_space,omitempty"`
+ Capacity int64 `json:"capacity,omitempty"`
+ DatacenterID string `json:"datacenter_id,omitempty"`
+ DatacenterName string `json:"datacenter_name,omitempty"`
+ FolderID string `json:"folder_id,omitempty"`
+ FolderName string `json:"folder_name,omitempty"`
+ HostIDs []string `json:"host_ids,omitempty"`
+ HostNames []string `json:"host_names,omitempty"`
+ VMIDs []string `json:"vm_ids,omitempty"`
+ VMNames []string `json:"vm_names,omitempty"`
+ Accessible *bool `json:"accessible,omitempty"`
+ MultipleHostAccess *bool `json:"multiple_host_access,omitempty"`
+ MaintenanceMode string `json:"maintenance_mode,omitempty"`
+ URL string `json:"url,omitempty"`
+ OverallStatus string `json:"overall_status,omitempty"`
+ TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
+ RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
}
// InventorySnapshot captures the projected inventory floor for one vCenter
@@ -260,6 +301,14 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
connectionName := firstNonEmptyTrimmed(snapshot.ConnectionName, snapshot.VCenterHost, snapshot.ConnectionID)
vcenterHost := strings.TrimSpace(snapshot.VCenterHost)
records := make([]unifiedresources.IngestRecord, 0, len(snapshot.Hosts)+len(snapshot.VMs)+len(snapshot.Datastores))
+ hostSourceIDsByManagedObject := make(map[string]string, len(snapshot.Hosts))
+ for _, host := range snapshot.Hosts {
+ hostID := strings.TrimSpace(host.Host)
+ if hostID == "" {
+ continue
+ }
+ hostSourceIDsByManagedObject[hostID] = vmwareSourceID(snapshot.ConnectionID, "host", hostID)
+ }
for _, host := range snapshot.Hosts {
name := firstNonEmptyTrimmed(host.Name, host.Host)
@@ -277,19 +326,29 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
Incidents: incidents,
Metrics: inventoryMetricsResourceMetrics(host.Metrics),
VMware: &unifiedresources.VMwareData{
- ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
- ConnectionName: connectionName,
- VCenterHost: vcenterHost,
- ManagedObjectID: strings.TrimSpace(host.Host),
- EntityType: "host",
- HostUUID: strings.TrimSpace(host.HostUUID),
- ConnectionState: strings.TrimSpace(host.ConnectionState),
- PowerState: strings.TrimSpace(host.PowerState),
- OverallStatus: strings.TrimSpace(host.OverallStatus),
- ActiveAlarmCount: len(host.TriggeredAlarms),
- ActiveAlarmSummary: vmwareAlarmSummary(host.TriggeredAlarms),
- RecentTaskCount: len(host.RecentTasks),
- RecentTaskSummary: vmwareRecentTaskSummary(host.RecentTasks),
+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
+ ConnectionName: connectionName,
+ VCenterHost: vcenterHost,
+ ManagedObjectID: strings.TrimSpace(host.Host),
+ EntityType: "host",
+ HostUUID: strings.TrimSpace(host.HostUUID),
+ DatacenterID: strings.TrimSpace(host.DatacenterID),
+ DatacenterName: strings.TrimSpace(host.DatacenterName),
+ ComputeResourceID: strings.TrimSpace(host.ComputeResourceID),
+ ComputeResourceName: strings.TrimSpace(host.ComputeResourceName),
+ ClusterID: strings.TrimSpace(host.ClusterID),
+ ClusterName: strings.TrimSpace(host.ClusterName),
+ FolderID: strings.TrimSpace(host.FolderID),
+ FolderName: strings.TrimSpace(host.FolderName),
+ ConnectionState: strings.TrimSpace(host.ConnectionState),
+ PowerState: strings.TrimSpace(host.PowerState),
+ OverallStatus: strings.TrimSpace(host.OverallStatus),
+ DatastoreIDs: cloneStringSlice(host.DatastoreIDs),
+ DatastoreNames: cloneStringSlice(host.DatastoreNames),
+ ActiveAlarmCount: len(host.TriggeredAlarms),
+ ActiveAlarmSummary: vmwareAlarmSummary(host.TriggeredAlarms),
+ RecentTaskCount: len(host.RecentTasks),
+ RecentTaskSummary: vmwareRecentTaskSummary(host.RecentTasks),
},
Tags: filterNonEmptyStrings(
"vmware",
@@ -302,8 +361,9 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
),
}
identity := unifiedresources.ResourceIdentity{
- DMIUUID: strings.TrimSpace(host.HostUUID),
- Hostnames: filterNonEmptyStrings(name),
+ DMIUUID: strings.TrimSpace(host.HostUUID),
+ Hostnames: filterNonEmptyStrings(name),
+ ClusterName: vmwareClusterHint(host.ClusterName, host.ComputeResourceName),
}
records = append(records, unifiedresources.IngestRecord{
SourceID: vmwareSourceID(snapshot.ConnectionID, "host", host.Host),
@@ -327,21 +387,41 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
UpdatedAt: collectedAt,
Incidents: incidents,
Metrics: inventoryMetricsResourceMetrics(vm.Metrics),
+ ParentName: strings.TrimSpace(vm.RuntimeHostName),
VMware: &unifiedresources.VMwareData{
- ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
- ConnectionName: connectionName,
- VCenterHost: vcenterHost,
- ManagedObjectID: strings.TrimSpace(vm.VM),
- EntityType: "vm",
- PowerState: strings.TrimSpace(vm.PowerState),
- CPUCount: vm.CPUCount,
- MemorySizeMiB: vm.MemorySizeMiB,
- OverallStatus: strings.TrimSpace(vm.OverallStatus),
- ActiveAlarmCount: len(vm.TriggeredAlarms),
- ActiveAlarmSummary: vmwareAlarmSummary(vm.TriggeredAlarms),
- RecentTaskCount: len(vm.RecentTasks),
- RecentTaskSummary: vmwareRecentTaskSummary(vm.RecentTasks),
- SnapshotCount: vm.SnapshotCount,
+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
+ ConnectionName: connectionName,
+ VCenterHost: vcenterHost,
+ ManagedObjectID: strings.TrimSpace(vm.VM),
+ EntityType: "vm",
+ DatacenterID: strings.TrimSpace(vm.DatacenterID),
+ DatacenterName: strings.TrimSpace(vm.DatacenterName),
+ ComputeResourceID: strings.TrimSpace(vm.ComputeResourceID),
+ ComputeResourceName: strings.TrimSpace(vm.ComputeResourceName),
+ ClusterID: strings.TrimSpace(vm.ClusterID),
+ ClusterName: strings.TrimSpace(vm.ClusterName),
+ FolderID: strings.TrimSpace(vm.FolderID),
+ FolderName: strings.TrimSpace(vm.FolderName),
+ ResourcePoolID: strings.TrimSpace(vm.ResourcePoolID),
+ ResourcePoolName: strings.TrimSpace(vm.ResourcePoolName),
+ RuntimeHostID: strings.TrimSpace(vm.RuntimeHostID),
+ RuntimeHostName: strings.TrimSpace(vm.RuntimeHostName),
+ PowerState: strings.TrimSpace(vm.PowerState),
+ CPUCount: vm.CPUCount,
+ MemorySizeMiB: vm.MemorySizeMiB,
+ DatastoreIDs: cloneStringSlice(vm.DatastoreIDs),
+ DatastoreNames: cloneStringSlice(vm.DatastoreNames),
+ InstanceUUID: strings.TrimSpace(vm.InstanceUUID),
+ BIOSUUID: strings.TrimSpace(vm.BIOSUUID),
+ GuestOSFamily: strings.TrimSpace(vm.GuestOSFamily),
+ GuestHostname: strings.TrimSpace(vm.GuestHostname),
+ GuestIPAddresses: cloneStringSlice(vm.GuestIPAddresses),
+ OverallStatus: strings.TrimSpace(vm.OverallStatus),
+ ActiveAlarmCount: len(vm.TriggeredAlarms),
+ ActiveAlarmSummary: vmwareAlarmSummary(vm.TriggeredAlarms),
+ RecentTaskCount: len(vm.RecentTasks),
+ RecentTaskSummary: vmwareRecentTaskSummary(vm.RecentTasks),
+ SnapshotCount: vm.SnapshotCount,
},
Tags: filterNonEmptyStrings(
"vmware",
@@ -352,9 +432,17 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
tagWithValue("power", strings.ToLower(strings.TrimSpace(vm.PowerState))),
),
}
+ identity := unifiedresources.ResourceIdentity{
+ MachineID: firstNonEmptyTrimmed(vm.InstanceUUID, vm.BIOSUUID),
+ Hostnames: uniqueSortedTrimmedStrings([]string{name, vm.GuestHostname}),
+ IPAddresses: uniqueSortedTrimmedStrings(vm.GuestIPAddresses),
+ ClusterName: vmwareClusterHint(vm.ClusterName, vm.ComputeResourceName),
+ }
records = append(records, unifiedresources.IngestRecord{
- SourceID: vmwareSourceID(snapshot.ConnectionID, "vm", vm.VM),
- Resource: resource,
+ SourceID: vmwareSourceID(snapshot.ConnectionID, "vm", vm.VM),
+ ParentSourceID: hostSourceIDsByManagedObject[strings.TrimSpace(vm.RuntimeHostID)],
+ Resource: resource,
+ Identity: identity,
})
}
@@ -380,23 +468,37 @@ func (p *Provider) Records() []unifiedresources.IngestRecord {
Disk: diskMetric(datastore.Capacity, used),
},
Storage: &unifiedresources.StorageMeta{
- Type: normalizeDatastoreType(datastore.Type),
- Platform: "vmware-vsphere",
- Topology: "datastore",
- Enabled: true,
+ Type: normalizeDatastoreType(datastore.Type),
+ Platform: "vmware-vsphere",
+ Topology: "datastore",
+ Enabled: vmwareDatastoreEnabled(datastore),
+ Active: vmwareDatastoreActive(datastore),
+ Shared: vmwareDatastoreShared(datastore),
+ Nodes: cloneStringSlice(datastore.HostNames),
+ ConsumerCount: len(datastore.VMNames),
+ ConsumerTypes: vmwareDatastoreConsumerTypes(datastore),
+ TopConsumers: vmwareDatastoreTopConsumers(datastore),
},
VMware: &unifiedresources.VMwareData{
- ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
- ConnectionName: connectionName,
- VCenterHost: vcenterHost,
- ManagedObjectID: strings.TrimSpace(datastore.Datastore),
- EntityType: "datastore",
- DatastoreType: strings.TrimSpace(datastore.Type),
- OverallStatus: strings.TrimSpace(datastore.OverallStatus),
- ActiveAlarmCount: len(datastore.TriggeredAlarms),
- ActiveAlarmSummary: vmwareAlarmSummary(datastore.TriggeredAlarms),
- RecentTaskCount: len(datastore.RecentTasks),
- RecentTaskSummary: vmwareRecentTaskSummary(datastore.RecentTasks),
+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
+ ConnectionName: connectionName,
+ VCenterHost: vcenterHost,
+ ManagedObjectID: strings.TrimSpace(datastore.Datastore),
+ EntityType: "datastore",
+ DatacenterID: strings.TrimSpace(datastore.DatacenterID),
+ DatacenterName: strings.TrimSpace(datastore.DatacenterName),
+ FolderID: strings.TrimSpace(datastore.FolderID),
+ FolderName: strings.TrimSpace(datastore.FolderName),
+ DatastoreType: strings.TrimSpace(datastore.Type),
+ DatastoreURL: strings.TrimSpace(datastore.URL),
+ DatastoreAccessible: cloneBoolPointer(datastore.Accessible),
+ MultipleHostAccess: cloneBoolPointer(datastore.MultipleHostAccess),
+ MaintenanceMode: strings.TrimSpace(datastore.MaintenanceMode),
+ OverallStatus: strings.TrimSpace(datastore.OverallStatus),
+ ActiveAlarmCount: len(datastore.TriggeredAlarms),
+ ActiveAlarmSummary: vmwareAlarmSummary(datastore.TriggeredAlarms),
+ RecentTaskCount: len(datastore.RecentTasks),
+ RecentTaskSummary: vmwareRecentTaskSummary(datastore.RecentTasks),
},
Tags: filterNonEmptyStrings(
"vmware",
@@ -449,6 +551,8 @@ func cloneInventoryHosts(in []InventoryHost) []InventoryHost {
out := make([]InventoryHost, len(in))
for i := range in {
out[i] = in[i]
+ out[i].DatastoreIDs = cloneStringSlice(in[i].DatastoreIDs)
+ out[i].DatastoreNames = cloneStringSlice(in[i].DatastoreNames)
out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)
out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)
out[i].Metrics = cloneInventoryMetrics(in[i].Metrics)
@@ -463,6 +567,9 @@ func cloneInventoryVMs(in []InventoryVM) []InventoryVM {
out := make([]InventoryVM, len(in))
for i := range in {
out[i] = in[i]
+ out[i].DatastoreIDs = cloneStringSlice(in[i].DatastoreIDs)
+ out[i].DatastoreNames = cloneStringSlice(in[i].DatastoreNames)
+ out[i].GuestIPAddresses = cloneStringSlice(in[i].GuestIPAddresses)
out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)
out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)
out[i].Metrics = cloneInventoryMetrics(in[i].Metrics)
@@ -477,6 +584,12 @@ func cloneInventoryDatastores(in []InventoryDatastore) []InventoryDatastore {
out := make([]InventoryDatastore, len(in))
for i := range in {
out[i] = in[i]
+ out[i].HostIDs = cloneStringSlice(in[i].HostIDs)
+ out[i].HostNames = cloneStringSlice(in[i].HostNames)
+ out[i].VMIDs = cloneStringSlice(in[i].VMIDs)
+ out[i].VMNames = cloneStringSlice(in[i].VMNames)
+ out[i].Accessible = cloneBoolPointer(in[i].Accessible)
+ out[i].MultipleHostAccess = cloneBoolPointer(in[i].MultipleHostAccess)
out[i].TriggeredAlarms = cloneInventoryAlarms(in[i].TriggeredAlarms)
out[i].RecentTasks = cloneInventoryTasks(in[i].RecentTasks)
}
@@ -555,6 +668,12 @@ func datastoreStatus(datastore InventoryDatastore) unifiedresources.ResourceStat
if strings.TrimSpace(datastore.Datastore) == "" && strings.TrimSpace(datastore.Name) == "" {
return unifiedresources.StatusUnknown
}
+ if datastore.Accessible != nil && !*datastore.Accessible {
+ return unifiedresources.StatusOffline
+ }
+ if mode := strings.ToLower(strings.TrimSpace(datastore.MaintenanceMode)); mode != "" && mode != "normal" {
+ return unifiedresources.StatusWarning
+ }
return unifiedresources.StatusOnline
}
@@ -716,6 +835,63 @@ func normalizeDatastoreType(value string) string {
return strings.ToLower(strings.TrimSpace(value))
}
+func vmwareClusterHint(clusterName, computeResourceName string) string {
+ return firstNonEmptyTrimmed(clusterName, computeResourceName)
+}
+
+func vmwareDatastoreEnabled(datastore InventoryDatastore) bool {
+ if datastore.Accessible == nil {
+ return true
+ }
+ return *datastore.Accessible
+}
+
+func vmwareDatastoreActive(datastore InventoryDatastore) bool {
+ if datastore.Accessible != nil && !*datastore.Accessible {
+ return false
+ }
+ mode := strings.ToLower(strings.TrimSpace(datastore.MaintenanceMode))
+ return mode == "" || mode == "normal"
+}
+
+func vmwareDatastoreShared(datastore InventoryDatastore) bool {
+ if datastore.MultipleHostAccess != nil {
+ return *datastore.MultipleHostAccess
+ }
+ return len(datastore.HostNames) > 1
+}
+
+func vmwareDatastoreConsumerTypes(datastore InventoryDatastore) []string {
+ if len(datastore.VMNames) == 0 {
+ return nil
+ }
+ return []string{string(unifiedresources.ResourceTypeVM)}
+}
+
+func vmwareDatastoreTopConsumers(datastore InventoryDatastore) []unifiedresources.StorageConsumerMeta {
+ if len(datastore.VMNames) == 0 {
+ return nil
+ }
+ consumers := make([]unifiedresources.StorageConsumerMeta, 0, len(datastore.VMNames))
+ for _, name := range datastore.VMNames {
+ if strings.TrimSpace(name) == "" {
+ continue
+ }
+ consumer := unifiedresources.StorageConsumerMeta{
+ ResourceType: unifiedresources.ResourceTypeVM,
+ Name: strings.TrimSpace(name),
+ }
+ consumers = append(consumers, consumer)
+ if len(consumers) == 5 {
+ break
+ }
+ }
+ if len(consumers) == 0 {
+ return nil
+ }
+ return consumers
+}
+
func diskMetric(total, used int64) *unifiedresources.MetricValue {
if total <= 0 {
return nil
@@ -817,6 +993,23 @@ func cloneInt64Pointer(in *int64) *int64 {
return &value
}
+func cloneBoolPointer(in *bool) *bool {
+ if in == nil {
+ return nil
+ }
+ value := *in
+ return &value
+}
+
+func cloneStringSlice(in []string) []string {
+ if in == nil {
+ return nil
+ }
+ out := make([]string, len(in))
+ copy(out, in)
+ return out
+}
+
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 a6e6205db5..0cc5d0356f 100644
--- a/internal/vmware/provider_test.go
+++ b/internal/vmware/provider_test.go
@@ -19,12 +19,22 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
VCenterHost: "vc.lab.local",
CollectedAt: collectedAt,
Hosts: []InventoryHost{{
- Host: "host-101",
- Name: "esxi-01.lab.local",
- ConnectionState: "CONNECTED",
- PowerState: "POWERED_ON",
- HostUUID: "uuid-host-1",
- OverallStatus: "yellow",
+ Host: "host-101",
+ Name: "esxi-01.lab.local",
+ ConnectionState: "CONNECTED",
+ PowerState: "POWERED_ON",
+ HostUUID: "uuid-host-1",
+ DatacenterID: "datacenter-1",
+ DatacenterName: "DC1",
+ ComputeResourceID: "domain-c101",
+ ComputeResourceName: "Prod Compute",
+ ClusterID: "domain-c101",
+ ClusterName: "Prod Compute",
+ FolderID: "group-h4",
+ FolderName: "Prod Hosts",
+ DatastoreIDs: []string{"datastore-11"},
+ DatastoreNames: []string{"nvme-primary"},
+ OverallStatus: "yellow",
Metrics: &InventoryMetrics{
CPUPercent: float64Ptr(21.4),
MemoryPercent: float64Ptr(63.2),
@@ -49,12 +59,31 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
}},
}},
VMs: []InventoryVM{{
- VM: "vm-201",
- Name: "app-01",
- PowerState: "POWERED_ON",
- CPUCount: 4,
- MemorySizeMiB: 8192,
- OverallStatus: "green",
+ VM: "vm-201",
+ Name: "app-01",
+ PowerState: "POWERED_ON",
+ CPUCount: 4,
+ MemorySizeMiB: 8192,
+ DatacenterID: "datacenter-1",
+ DatacenterName: "DC1",
+ ComputeResourceID: "domain-c101",
+ ComputeResourceName: "Prod Compute",
+ ClusterID: "domain-c101",
+ ClusterName: "Prod Compute",
+ FolderID: "group-v7",
+ FolderName: "Production VMs",
+ ResourcePoolID: "resgroup-22",
+ ResourcePoolName: "Tier 1",
+ RuntimeHostID: "host-101",
+ RuntimeHostName: "esxi-01.lab.local",
+ DatastoreIDs: []string{"datastore-11"},
+ DatastoreNames: []string{"nvme-primary"},
+ InstanceUUID: "vm-instance-201",
+ BIOSUUID: "vm-bios-201",
+ GuestOSFamily: "LINUX",
+ GuestHostname: "app-01.internal",
+ GuestIPAddresses: []string{"10.0.0.21"},
+ OverallStatus: "green",
Metrics: &InventoryMetrics{
CPUPercent: float64Ptr(38.1),
MemoryPercent: float64Ptr(57.5),
@@ -80,12 +109,24 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
SnapshotCount: 2,
}},
Datastores: []InventoryDatastore{{
- Datastore: "datastore-11",
- Name: "nvme-primary",
- Type: "VMFS",
- FreeSpace: 40,
- Capacity: 100,
- OverallStatus: "yellow",
+ Datastore: "datastore-11",
+ Name: "nvme-primary",
+ Type: "VMFS",
+ FreeSpace: 40,
+ Capacity: 100,
+ DatacenterID: "datacenter-1",
+ DatacenterName: "DC1",
+ FolderID: "group-s4",
+ FolderName: "Shared Datastores",
+ HostIDs: []string{"host-101"},
+ HostNames: []string{"esxi-01.lab.local"},
+ VMIDs: []string{"vm-201"},
+ VMNames: []string{"app-01"},
+ Accessible: boolPtr(true),
+ MultipleHostAccess: boolPtr(true),
+ MaintenanceMode: "normal",
+ URL: "ds:///vmfs/volumes/datastore-11/",
+ OverallStatus: "yellow",
RecentTasks: []InventoryTask{{
Task: "task-31",
Name: "Refresh datastore",
@@ -119,6 +160,12 @@ 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 got := hostRecord.Resource.VMware.ClusterName; got != "Prod Compute" {
+ t.Fatalf("host cluster name = %q, want Prod Compute", got)
+ }
+ if got := hostRecord.Resource.VMware.DatastoreNames; len(got) != 1 || got[0] != "nvme-primary" {
+ t.Fatalf("host datastore names = %#v, want [nvme-primary]", got)
+ }
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)
}
@@ -134,6 +181,9 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
if hostRecord.Identity.DMIUUID != "uuid-host-1" {
t.Fatalf("host identity DMI UUID = %q, want uuid-host-1", hostRecord.Identity.DMIUUID)
}
+ if got := hostRecord.Identity.ClusterName; got != "Prod Compute" {
+ t.Fatalf("host cluster name = %q, want Prod Compute", got)
+ }
if hostRecord.Resource.LastSeen != collectedAt {
t.Fatalf("host last seen = %v, want %v", hostRecord.Resource.LastSeen, collectedAt)
}
@@ -157,6 +207,24 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
if got := vmRecord.Resource.VMware.SnapshotCount; got != 2 {
t.Fatalf("vm snapshot count = %d, want 2", got)
}
+ if got := vmRecord.Resource.ParentName; got != "esxi-01.lab.local" {
+ t.Fatalf("vm parent name = %q, want esxi-01.lab.local", got)
+ }
+ if got := vmRecord.ParentSourceID; got != "vc-1:host:host-101" {
+ t.Fatalf("vm parent source id = %q, want vc-1:host:host-101", got)
+ }
+ if got := vmRecord.Resource.VMware.RuntimeHostName; got != "esxi-01.lab.local" {
+ t.Fatalf("vm runtime host name = %q, want esxi-01.lab.local", got)
+ }
+ if got := vmRecord.Resource.VMware.InstanceUUID; got != "vm-instance-201" {
+ t.Fatalf("vm instance uuid = %q, want vm-instance-201", got)
+ }
+ if got := vmRecord.Identity.MachineID; got != "vm-instance-201" {
+ t.Fatalf("vm machine id = %q, want vm-instance-201", got)
+ }
+ if got := vmRecord.Identity.IPAddresses; len(got) != 1 || got[0] != "10.0.0.21" {
+ t.Fatalf("vm identity IPs = %#v, want [10.0.0.21]", 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)
}
@@ -195,4 +263,23 @@ func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
if got := datastoreRecord.Resource.VMware.RecentTaskSummary; got != "Refresh datastore (queued)" {
t.Fatalf("datastore recent task summary = %q, want %q", got, "Refresh datastore (queued)")
}
+ if !datastoreRecord.Resource.Storage.Shared {
+ t.Fatal("expected datastore storage meta to mark the datastore as shared")
+ }
+ if got := datastoreRecord.Resource.Storage.Nodes; len(got) != 1 || got[0] != "esxi-01.lab.local" {
+ t.Fatalf("datastore storage nodes = %#v, want [esxi-01.lab.local]", got)
+ }
+ if got := datastoreRecord.Resource.Storage.ConsumerCount; got != 1 {
+ t.Fatalf("datastore consumer count = %d, want 1", got)
+ }
+ if got := datastoreRecord.Resource.Storage.TopConsumers; len(got) != 1 || got[0].Name != "app-01" {
+ t.Fatalf("datastore top consumers = %#v, want app-01", got)
+ }
+ if datastoreRecord.Resource.VMware.DatastoreAccessible == nil || !*datastoreRecord.Resource.VMware.DatastoreAccessible {
+ t.Fatalf("datastore accessible = %#v, want true", datastoreRecord.Resource.VMware.DatastoreAccessible)
+ }
+}
+
+func boolPtr(value bool) *bool {
+ return &value
}