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 vCenter resource projection slice

rcourtmane1474cfc924f
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 9e6629baf1..fd02d6505c 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -533,6 +533,17 @@ may show one VMware connection's poll health, last error classification, and
observed contribution summary, but it must not force the operator to manage
separate Automation API versus VI JSON sessions or understand multi-client
runtime wiring just to use the shared platform-connections path.
+That lifecycle-owned VMware slice now also includes the first live runtime
+handoff rule. `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`,
+`frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`,
+`frontend-modern/src/components/Settings/PlatformConnectionsWorkspace.tsx`,
+`frontend-modern/src/components/Settings/InfrastructurePlatformConnectionsSummaryCard.tsx`,
+and `internal/api/router.go` must keep VMware on the shared platform-
+connections workflow with one `vCenter` connection family and one summary card
+count. Lifecycle-adjacent install or discovery surfaces must not fork that
+into a VMware-only install wizard, direct-ESXi setup branch, or agent-first
+bootstrap story just because the runtime now has a live VMware connection
+panel and poller.
That same lifecycle-owned settings slice now also owns the shared VMware
summary and handoff framing. `InfrastructurePlatformConnectionsSummaryCard.tsx`,
`InfrastructureReportingPanel.tsx`, `useInfrastructureSettingsState.ts`, and
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 58ef94a7d7..40bbf8fdd1 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -715,6 +715,15 @@ the stored summary until a real save succeeds. The explicit disabled path also
stays on this boundary: `404 vmware_disabled` means the operator or runtime has
opted out of the default-on VMware candidate, not that the platform requires a
different onboarding contract.
+That same VMware API boundary now also owns the phase-1 runtime negative
+space around inventory projection. `internal/api/router.go` may wire VMware's
+supplemental ingest into the shared `/api/resources` surface so canonical
+`agent`, `vm`, and `storage` records can appear elsewhere in Pulse, but the
+public backend contract must still stop at `/api/vmware/connections*` for
+provider-local routes. Phase 1 must not add public `/api/vmware/resources`,
+`/api/vmware/history`, `/api/vmware/alerts`, or VMware-specific recovery
+transport just because the internal poller now projects VMware-backed
+resources into the shared canonical inventory.
That same backend API boundary now also owns the negative space around
assistant control. Wiring native TrueNAS app actions into
`internal/api/router.go`, `internal/api/ai_handler.go`, or adjacent backend
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 60aec03319..abb0679745 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -34,6 +34,7 @@ truth for live infrastructure data.
10. `internal/monitoring/reload.go`
11. `docker-entrypoint.sh`
12. `internal/monitoring/truenas_poller.go`
+13. `internal/monitoring/vmware_poller.go`
## Shared Boundaries
@@ -100,6 +101,14 @@ health record, even if that provider keeps separate authenticated Automation
API and VI JSON clients internally. Connection edits that change host, auth,
TLS, or poll cadence must replace that live provider state instead of leaving
stale VMware sessions resident until restart.
+That provider ownership now has a concrete phase-1 runtime seam:
+`internal/monitoring/vmware_poller.go` must keep VMware inventory on the
+shared supplemental-ingest path, declare `SourceVMware` as its owned source,
+and cache per-organization, per-connection provider records instead of
+projecting VMware through `StateSnapshot`-local host or storage arrays.
+`internal/api/router.go` may start and stop that poller as shared runtime
+infrastructure, but monitoring still owns the provider lifecycle, source
+ownership, and canonical record emission rules for VMware.
That same VMware monitoring boundary now also includes the proof rule for
history depth. `PerformanceManager.QueryPerfComposite` clearly supports
host-plus-child metric collection, but exact VM and datastore history fidelity
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index f510e42931..7459bc237f 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -92,6 +92,7 @@ querying, and the operator-facing storage health presentation layer.
26. Keep cross-surface recovery handoffs on the shared route-helper contract. When infrastructure or other unified-resource consumers expose TrueNAS recovery links, they must reuse the canonical `frontend-modern/src/routing/resourceLinks.ts` recovery builder with owned `platform` and `node` queries instead of inventing drawer-local recovery URLs or treating PBS services as the only infrastructure-to-recovery path.
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.
## Forbidden Paths
@@ -1644,3 +1645,12 @@ health refresh, and observed datastore/VM snapshot visibility on the shared
platform-connections surface, but storage and recovery must treat that data as
setup/runtime context only, not as proof that VMware has joined the canonical
recovery artifact or restore plane.
+That same bounded phase-1 slice now also includes the shared unified-resource
+adapter floor. `frontend-modern/src/hooks/useUnifiedResources.ts`,
+`frontend-modern/src/routing/resourceLinks.ts`, and adjacent storage filters
+may surface VMware-backed datastores as canonical `storage` resources under
+the shared `vmware-vsphere` source/platform vocabulary, but that operator-
+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.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 7f2887032a..28869122d3 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -94,6 +94,9 @@ cross-source deduplication.
72. `frontend-modern/src/utils/resourceIdentity.ts`
73. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerIdentityModel.ts`
74. `frontend-modern/src/hooks/useDashboardTrends.ts`
+75. `frontend-modern/src/hooks/useUnifiedResources.ts`
+76. `frontend-modern/src/types/resource.ts`
+77. `frontend-modern/src/utils/sourcePlatforms.ts`
## Shared Boundaries
@@ -187,6 +190,16 @@ VMware source key plus `platformType: vmware-vsphere`, not through separate
host, VM, or datastore from VMware should therefore still look like one shared
Pulse `agent`, `vm`, or `storage` resource to downstream selectors, drawers,
alerts, AI, and route filters.
+That shared source boundary now also has a concrete frontend/runtime adapter
+floor. `internal/unifiedresources/types.go`, `internal/unifiedresources/registry.go`,
+`internal/unifiedresources/views.go`, `frontend-modern/src/hooks/useUnifiedResources.ts`,
+`frontend-modern/src/types/resource.ts`, and
+`frontend-modern/src/utils/sourcePlatforms.ts` must keep raw VMware ingest on
+`SourceVMware` while projecting the operator-facing platform as
+`vmware-vsphere`. Shared filters, route state, and badges may normalize that
+single source onto the canonical platform vocabulary, but they must not invent
+separate `vcenter` or `esxi` filter keys or a VMware-only top-level resource
+family to make the phase-1 slice render.
That same VMware contract now also includes the identity rule. VMware managed
object identifiers are phase-1 provider identities, but they must be scoped by
the owning `vCenter` connection or discovered vCenter identity so bare object
diff --git a/frontend-modern/src/features/infrastructure/__tests__/infrastructurePageModel.test.ts b/frontend-modern/src/features/infrastructure/__tests__/infrastructurePageModel.test.ts
index d705ed8c6b..9f6053219e 100644
--- a/frontend-modern/src/features/infrastructure/__tests__/infrastructurePageModel.test.ts
+++ b/frontend-modern/src/features/infrastructure/__tests__/infrastructurePageModel.test.ts
@@ -118,4 +118,28 @@ describe('infrastructurePageModel', () => {
expect(derivation.activeFilterCount).toBe(1);
expect(derivation.hasActiveFilters).toBe(true);
});
+
+ it('normalizes raw VMware sources into the canonical vSphere infrastructure filter', () => {
+ const derivation = buildInfrastructurePageFilterDerivation(
+ [
+ makeResource({
+ id: 'resource-vmware-1',
+ displayName: 'ESXi 01',
+ platformType: 'vmware-vsphere',
+ sourceType: 'api',
+ platformData: { sources: ['vmware'] },
+ }),
+ ],
+ 'vmware-vsphere',
+ '',
+ '',
+ );
+
+ expect(Array.from(derivation.availableSources)).toEqual(['vmware-vsphere']);
+ expect(derivation.sourceOptions).toEqual([{ key: 'vmware-vsphere', label: 'vSphere' }]);
+ expect(derivation.filteredResources.map((resource) => resource.id)).toEqual([
+ 'resource-vmware-1',
+ ]);
+ expect(derivation.hasFilteredResources).toBe(true);
+ });
});
diff --git a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
index da01be3a15..96d32255ab 100644
--- a/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
+++ b/frontend-modern/src/hooks/__tests__/useUnifiedResources.test.ts
@@ -302,6 +302,53 @@ describe('useUnifiedResources', () => {
dispose();
});
+ it('projects raw VMware sources onto the canonical vSphere platform model', async () => {
+ apiFetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({
+ data: [
+ {
+ ...v2Resource,
+ id: 'vmware-host-1',
+ name: 'esxi-01.lab.local',
+ sources: ['vmware'],
+ canonicalIdentity: {
+ displayName: 'ESXi 01',
+ hostname: 'esxi-01.lab.local',
+ platformId: 'vmware-host-1',
+ },
+ vmware: {
+ connectionId: 'vc-1',
+ connectionName: 'Lab VC',
+ vCenterHost: 'vc.lab.local',
+ managedObjectId: 'host-101',
+ entityType: 'host',
+ },
+ },
+ ],
+ }),
+ });
+
+ let dispose = () => {};
+ let result: ReturnType<UseUnifiedResourcesModule['useUnifiedResources']> | undefined;
+ createRoot((d) => {
+ dispose = d;
+ result = useUnifiedResources();
+ });
+
+ await result!.refetch();
+ expect(result!.resources()[0].platformType).toBe('vmware-vsphere');
+ expect(result!.resources()[0].sourceType).toBe('api');
+ expect(result!.resources()[0].platformData?.sources).toEqual(['vmware']);
+ expect(result!.resources()[0].vmware).toMatchObject({
+ connectionId: 'vc-1',
+ managedObjectId: 'host-101',
+ entityType: 'host',
+ });
+
+ dispose();
+ });
+
it('maps discoveryTarget.agentId into canonical discovery agentId', async () => {
apiFetchMock.mockResolvedValueOnce({
ok: true,
diff --git a/frontend-modern/src/hooks/useUnifiedResources.ts b/frontend-modern/src/hooks/useUnifiedResources.ts
index 17ff3e7699..dea6ccc1af 100644
--- a/frontend-modern/src/hooks/useUnifiedResources.ts
+++ b/frontend-modern/src/hooks/useUnifiedResources.ts
@@ -16,6 +16,7 @@ import type {
ResourceStatus,
ResourceStorageMeta,
ResourceType,
+ ResourceVMwareMeta,
} from '@/types/resource';
import { normalizeDiskArray } from '@/utils/format';
import { logger } from '@/utils/logger';
@@ -305,6 +306,19 @@ type APIResource = {
lastUpdated?: string;
};
kubernetes?: APIKubernetesData;
+ vmware?: {
+ connectionId?: string;
+ connectionName?: string;
+ vcenterHost?: string;
+ managedObjectId?: string;
+ entityType?: string;
+ hostUuid?: string;
+ connectionState?: string;
+ powerState?: string;
+ cpuCount?: number;
+ memorySizeMib?: number;
+ datastoreType?: string;
+ };
recentChanges?: ResourceChange[];
facetCounts?: ResourceFacetCounts;
physicalDisk?: {
@@ -564,6 +578,7 @@ const toResource = (v2: APIResource): Resource => {
incidentAction: v2.incidentAction,
agent: v2.agent,
kubernetes: v2.kubernetes,
+ vmware: v2.vmware as ResourceVMwareMeta | undefined,
pbs: v2.pbs as ResourcePBSMeta | undefined,
physicalDisk: v2.physicalDisk,
storage: v2.storage as ResourceStorageMeta | undefined,
@@ -633,6 +648,7 @@ const toResource = (v2: APIResource): Resource => {
storage: v2.storage,
pmg: v2.pmg,
kubernetes: v2.kubernetes,
+ vmware: v2.vmware,
physicalDisk: v2.physicalDisk,
ceph: v2.ceph,
metrics: v2.metrics,
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index d8b109c3d9..496f1cfeb0 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -47,6 +47,7 @@ export type PlatformType =
| 'docker'
| 'kubernetes'
| 'truenas'
+ | 'vmware-vsphere'
| 'agent';
// Source types - how data is collected
@@ -400,6 +401,20 @@ export interface ResourceKubernetesMeta {
metricCapabilities?: ResourceKubernetesMetricCapabilities;
}
+export interface ResourceVMwareMeta {
+ connectionId?: string;
+ connectionName?: string;
+ vcenterHost?: string;
+ managedObjectId?: string;
+ entityType?: string;
+ hostUuid?: string;
+ connectionState?: string;
+ powerState?: string;
+ cpuCount?: number;
+ memorySizeMib?: number;
+ datastoreType?: string;
+}
+
/**
* The core unified Resource type.
* This is what the frontend receives from WebSocket state.resources[].
@@ -468,6 +483,7 @@ export interface Resource {
// Prefer these over casting `platformData` when available.
agent?: ResourceAgentMeta;
kubernetes?: ResourceKubernetesMeta;
+ vmware?: ResourceVMwareMeta;
proxmox?: ResourceProxmoxMeta;
pbs?: ResourcePBSMeta;
physicalDisk?: ResourcePhysicalDiskMeta;
diff --git a/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts b/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts
index cccd025e71..29fda69203 100644
--- a/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts
+++ b/frontend-modern/src/utils/__tests__/sourcePlatforms.test.ts
@@ -75,6 +75,7 @@ describe('sourcePlatforms', () => {
hasPbs: true,
hasPmg: false,
hasTrueNAS: false,
+ hasVMware: false,
});
});
@@ -87,6 +88,7 @@ describe('sourcePlatforms', () => {
hasPbs: false,
hasPmg: false,
hasTrueNAS: false,
+ hasVMware: false,
});
});
@@ -99,6 +101,20 @@ describe('sourcePlatforms', () => {
hasPbs: false,
hasPmg: false,
hasTrueNAS: true,
+ hasVMware: false,
+ });
+ });
+
+ it('tracks VMware as a canonical API-backed platform source', () => {
+ expect(readSourcePlatformFlags(['agent', 'vmware'])).toEqual({
+ hasAgent: true,
+ hasProxmox: false,
+ hasDocker: false,
+ hasKubernetes: false,
+ hasPbs: false,
+ hasPmg: false,
+ hasTrueNAS: false,
+ hasVMware: true,
});
});
});
@@ -108,6 +124,7 @@ describe('sourcePlatforms', () => {
expect(resolvePlatformTypeFromSources(['agent', 'docker'])).toBe('docker');
expect(resolvePlatformTypeFromSources(['agent', 'pbs'])).toBe('proxmox-pbs');
expect(resolvePlatformTypeFromSources(['pmg', 'docker'])).toBe('proxmox-pmg');
+ expect(resolvePlatformTypeFromSources(['agent', 'vmware'])).toBe('vmware-vsphere');
expect(resolvePlatformTypeFromSources(['agent', 'truenas'])).toBe('truenas');
expect(resolvePlatformTypeFromSources(['agent'])).toBe('agent');
expect(resolvePlatformTypeFromSources(['custom-source'])).toBeUndefined();
@@ -119,6 +136,7 @@ describe('sourcePlatforms', () => {
expect(resolveSourceTypeFromSources(['agent'])).toBe('agent');
expect(resolveSourceTypeFromSources(['pve'])).toBe('api');
expect(resolveSourceTypeFromSources(['agent', 'proxmox'])).toBe('hybrid');
+ expect(resolveSourceTypeFromSources(['agent', 'vmware'])).toBe('hybrid');
expect(resolveSourceTypeFromSources(['agent', 'truenas'])).toBe('hybrid');
expect(resolveSourceTypeFromSources(['custom-source'])).toBe('api');
});
diff --git a/frontend-modern/src/utils/sourcePlatforms.ts b/frontend-modern/src/utils/sourcePlatforms.ts
index c790f68c70..aead90dba1 100644
--- a/frontend-modern/src/utils/sourcePlatforms.ts
+++ b/frontend-modern/src/utils/sourcePlatforms.ts
@@ -31,6 +31,7 @@ export interface SourcePlatformFlags {
hasPbs: boolean;
hasPmg: boolean;
hasTrueNAS: boolean;
+ hasVMware: boolean;
}
export const SOURCE_PLATFORM_PRESENTATION: Record<KnownSourcePlatform, SourcePlatformPresentation> =
@@ -103,6 +104,7 @@ const PLATFORM_ALIASES: Record<string, KnownSourcePlatform> = {
pbs: 'proxmox-pbs',
pmg: 'proxmox-pmg',
k8s: 'kubernetes',
+ vmware: 'vmware-vsphere',
};
export const normalizeSourcePlatformKey = (
@@ -143,6 +145,7 @@ export const readSourcePlatformFlags = (sources?: string[]): SourcePlatformFlags
hasPbs: false,
hasPmg: false,
hasTrueNAS: false,
+ hasVMware: false,
};
if (!sources || sources.length === 0) {
@@ -172,6 +175,9 @@ export const readSourcePlatformFlags = (sources?: string[]): SourcePlatformFlags
case 'truenas':
flags.hasTrueNAS = true;
break;
+ case 'vmware-vsphere':
+ flags.hasVMware = true;
+ break;
default:
break;
}
@@ -185,6 +191,7 @@ export const resolvePlatformTypeFromSources = (sources?: string[]): PlatformType
if (flags.hasProxmox) return 'proxmox-pve';
if (flags.hasPbs) return 'proxmox-pbs';
if (flags.hasPmg) return 'proxmox-pmg';
+ if (flags.hasVMware) return 'vmware-vsphere';
if (flags.hasTrueNAS) return 'truenas';
if (flags.hasKubernetes) return 'kubernetes';
if (flags.hasDocker) return 'docker';
@@ -200,7 +207,8 @@ export const resolveSourceTypeFromSources = (sources?: string[]): SourceType =>
flags.hasKubernetes ||
flags.hasPbs ||
flags.hasPmg ||
- flags.hasTrueNAS;
+ flags.hasTrueNAS ||
+ flags.hasVMware;
if (flags.hasAgent && hasOther) return 'hybrid';
if (flags.hasAgent) return 'agent';
return 'api';
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index b3d10eca6a..518b24af68 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -194,6 +194,69 @@ func TestContract_VMwareSavedConnectionTestsUpdateRuntimeSummary(t *testing.T) {
}
}
+func TestContract_VMwareConnectionListCarriesObservedSummary(t *testing.T) {
+ setVMwareFeatureForTest(t, true)
+
+ connection := config.VMwareVCenterInstance{
+ ID: "conn-1",
+ Name: "lab-vcenter",
+ Host: "vcsa.lab.local",
+ Port: 443,
+ Username: "[email protected]",
+ Password: "super-secret",
+ Enabled: true,
+ }
+ handler, persistence := newVMwareHandlersForTest(t)
+ if err := persistence.SaveVMwareConfig([]config.VMwareVCenterInstance{connection}); err != nil {
+ t.Fatalf("seed vmware config: %v", err)
+ }
+
+ collectedAt := time.Date(2026, 3, 30, 18, 0, 0, 0, time.UTC)
+ handler.recordTestSuccess(connection.ID, &vmware.InventorySummary{
+ Hosts: 4,
+ VMs: 24,
+ Datastores: 6,
+ VIRelease: "8.0.3",
+ }, collectedAt)
+
+ req := httptest.NewRequest(http.MethodGet, "/api/vmware/connections", nil)
+ rec := httptest.NewRecorder()
+ handler.HandleList(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+
+ var responses []vmwareConnectionResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &responses); err != nil {
+ t.Fatalf("unmarshal vmware list response: %v", err)
+ }
+ if len(responses) != 1 {
+ t.Fatalf("expected 1 vmware connection response, got %d", len(responses))
+ }
+ if responses[0].Password != "********" {
+ t.Fatalf("expected redacted password in vmware list response, got %q", responses[0].Password)
+ }
+ if responses[0].Observed == nil {
+ t.Fatalf("expected observed summary in vmware list response, got %+v", responses[0])
+ }
+ if got := responses[0].Observed.Hosts; got != 4 {
+ t.Fatalf("observed hosts = %d, want 4", got)
+ }
+ if got := responses[0].Observed.VMs; got != 24 {
+ t.Fatalf("observed vms = %d, want 24", got)
+ }
+ if got := responses[0].Observed.Datastores; got != 6 {
+ t.Fatalf("observed datastores = %d, want 6", got)
+ }
+ if got := responses[0].Observed.VIRelease; got != "8.0.3" {
+ t.Fatalf("observed viRelease = %q, want 8.0.3", got)
+ }
+ if responses[0].Observed.CollectedAt == nil || !responses[0].Observed.CollectedAt.Equal(collectedAt) {
+ t.Fatalf("observed collectedAt = %+v, want %s", responses[0].Observed.CollectedAt, collectedAt.Format(time.RFC3339))
+ }
+}
+
func TestContract_SSOTestRejectsMetadataURLWithUserinfo(t *testing.T) {
called := make(chan struct{}, 1)
metadataServer := newIPv4HTTPServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/api/router.go b/internal/api/router.go
index aac0069769..f3af99b59c 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -84,6 +84,7 @@ type Router struct {
resourceHandlers *ResourceHandlers
resourceRegistry *unifiedresources.ResourceRegistry
trueNASPoller *monitoring.TrueNASPoller
+ vmwarePoller *monitoring.VMwarePoller
monitorResourceAdapter *unifiedresources.MonitorAdapter
monitorResourceAdapters map[string]*unifiedresources.MonitorAdapter
monitorAdapterMu sync.Mutex
@@ -365,6 +366,8 @@ func (r *Router) setupRoutes() {
}
r.trueNASPoller = monitoring.NewTrueNASPoller(r.multiTenant, 0, recoveryManager)
r.trueNASPoller.Start(r.lifecycleCtx)
+ r.vmwarePoller = monitoring.NewVMwarePoller(r.multiTenant, 0)
+ r.vmwarePoller.Start(r.lifecycleCtx)
updateHandlers := NewUpdateHandlersWithContext(r.updateManager, r.updateHistory, r.lifecycleCtx)
r.dockerAgentHandlers = NewDockerAgentHandlers(r.mtMonitor, r.monitor, r.wsHub, r.config)
r.kubernetesAgentHandlers = NewKubernetesAgentHandlers(r.mtMonitor, r.monitor, r.wsHub)
@@ -387,6 +390,10 @@ func (r *Router) setupRoutes() {
r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, r.trueNASPoller)
r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, r.trueNASPoller)
}
+ if r.vmwarePoller != nil {
+ r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceVMware, r.vmwarePoller)
+ r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceVMware, r.vmwarePoller)
+ }
if r.monitor != nil {
r.configureMonitorDependencies(r.monitor)
if r.resourceHandlers != nil {
@@ -2107,6 +2114,9 @@ func (r *Router) shutdownBackgroundWorkers() {
if r.trueNASPoller != nil {
r.trueNASPoller.Stop()
}
+ if r.vmwarePoller != nil {
+ r.vmwarePoller.Stop()
+ }
if r.deployStore != nil {
if err := r.deployStore.Close(); err != nil {
log.Error().Err(err).Msg("Failed to close deploy store")
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 5fe3eaa5fa..512007ca42 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -111,6 +111,25 @@ func TestConnectedInfrastructureKeepsPlatformConnectionsAndProjectsTrueNAS(t *te
}
}
+func TestVMwarePollerUsesCanonicalSupplementalIngestOwnership(t *testing.T) {
+ data, err := os.ReadFile("vmware_poller.go")
+ if err != nil {
+ t.Fatalf("failed to read vmware_poller.go: %v", err)
+ }
+ source := string(data)
+ requiredSnippets := []string{
+ "func (p *VMwarePoller) SupplementalRecords(_ *Monitor, orgID string) []unifiedresources.IngestRecord {",
+ "func (p *VMwarePoller) SnapshotOwnedSources() []unifiedresources.DataSource {",
+ "return []unifiedresources.DataSource{unifiedresources.SourceVMware}",
+ "return vmware.NewAPIProvider(vmware.ProviderMetadata{",
+ }
+ for _, snippet := range requiredSnippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("vmware_poller.go must contain %q", snippet)
+ }
+ }
+}
+
func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {
t.Parallel()
diff --git a/internal/monitoring/vmware_poller.go b/internal/monitoring/vmware_poller.go
new file mode 100644
index 0000000000..00cbf0f146
--- /dev/null
+++ b/internal/monitoring/vmware_poller.go
@@ -0,0 +1,444 @@
+package monitoring
+
+import (
+ "context"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/internal/vmware"
+ "github.com/rs/zerolog/log"
+)
+
+const defaultVMwarePollInterval = 60 * time.Second
+
+type vmwarePollerProvider interface {
+ Refresh(ctx context.Context) error
+ Records() []unifiedresources.IngestRecord
+ Close()
+}
+
+// VMwarePoller manages periodic polling of configured VMware vCenter connections.
+type VMwarePoller struct {
+ multiTenant *config.MultiTenantPersistence
+
+ mu sync.Mutex
+ // providersByOrg is keyed by orgID, then connection ID.
+ providersByOrg map[string]map[string]vmwarePollerProvider
+ // configsByOrg is keyed by orgID, then connection ID.
+ configsByOrg map[string]map[string]config.VMwareVCenterInstance
+ // cachedRecordsByOrg is keyed by orgID, then connection ID.
+ cachedRecordsByOrg map[string]map[string][]unifiedresources.IngestRecord
+ newProvider func(config.VMwareVCenterInstance) (vmwarePollerProvider, error)
+ cancel context.CancelFunc
+ stopped chan struct{}
+ interval time.Duration
+ explicitInterval bool
+}
+
+type vmwarePollerProviderEntry struct {
+ orgID string
+ connectionID string
+ provider vmwarePollerProvider
+}
+
+// NewVMwarePoller builds a new VMware poller with the provided interval.
+func NewVMwarePoller(multiTenant *config.MultiTenantPersistence, interval time.Duration) *VMwarePoller {
+ explicitInterval := interval > 0
+ if interval <= 0 {
+ interval = defaultVMwarePollInterval
+ }
+
+ stopped := make(chan struct{})
+ close(stopped)
+
+ poller := &VMwarePoller{
+ multiTenant: multiTenant,
+ providersByOrg: make(map[string]map[string]vmwarePollerProvider),
+ configsByOrg: make(map[string]map[string]config.VMwareVCenterInstance),
+ cachedRecordsByOrg: make(map[string]map[string][]unifiedresources.IngestRecord),
+ stopped: stopped,
+ interval: interval,
+ explicitInterval: explicitInterval,
+ }
+ poller.newProvider = poller.defaultProvider
+ return poller
+}
+
+// Start begins periodic VMware polling if the feature flag is enabled.
+func (p *VMwarePoller) Start(ctx context.Context) {
+ if p == nil || !vmware.IsFeatureEnabled() {
+ return
+ }
+ if ctx == nil {
+ ctx = context.Background()
+ }
+
+ p.mu.Lock()
+ if p.cancel != nil {
+ p.mu.Unlock()
+ return
+ }
+
+ runCtx, cancel := context.WithCancel(ctx)
+ p.cancel = cancel
+ p.stopped = make(chan struct{})
+ stopped := p.stopped
+ p.mu.Unlock()
+
+ go func() {
+ defer close(stopped)
+ defer func() {
+ p.mu.Lock()
+ if p.stopped == stopped {
+ p.cancel = nil
+ }
+ p.mu.Unlock()
+ }()
+
+ p.syncConnections()
+ p.pollAll(runCtx)
+ for {
+ wait := p.nextWaitDuration(time.Now())
+ timer := time.NewTimer(wait)
+ select {
+ case <-runCtx.Done():
+ if !timer.Stop() {
+ select {
+ case <-timer.C:
+ default:
+ }
+ }
+ return
+ case <-timer.C:
+ p.syncConnections()
+ p.pollAll(runCtx)
+ }
+ }
+ }()
+}
+
+// Stop requests poller shutdown and waits up to five seconds for exit.
+func (p *VMwarePoller) Stop() {
+ if p == nil {
+ return
+ }
+
+ p.mu.Lock()
+ cancel := p.cancel
+ stopped := p.stopped
+ p.mu.Unlock()
+
+ if cancel != nil {
+ cancel()
+ }
+ if stopped == nil {
+ return
+ }
+
+ timer := time.NewTimer(5 * time.Second)
+ defer timer.Stop()
+
+ select {
+ case <-stopped:
+ case <-timer.C:
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "stop").
+ Dur("timeout", 5*time.Second).
+ Msg("VMware poller stop timed out waiting for shutdown")
+ }
+}
+
+func (p *VMwarePoller) syncConnections() {
+ if p == nil {
+ return
+ }
+ if p.multiTenant == nil {
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "sync_connections").
+ Msg("VMware poller cannot sync connections because multi-tenant persistence is nil")
+ return
+ }
+
+ orgs, err := p.multiTenant.ListOrganizations()
+ if err != nil {
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "list_organizations").
+ Err(err).
+ Msg("VMware poller failed to list organizations")
+ return
+ }
+
+ active := make(map[string]map[string]config.VMwareVCenterInstance, len(orgs))
+ for _, org := range orgs {
+ if org == nil {
+ continue
+ }
+ orgID := strings.TrimSpace(org.ID)
+ if orgID == "" {
+ continue
+ }
+ persistence, err := p.multiTenant.GetPersistence(orgID)
+ if err != nil || persistence == nil {
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "get_persistence").
+ Str("org_id", orgID).
+ Err(err).
+ Msg("VMware poller failed to open tenant persistence")
+ continue
+ }
+
+ instances, err := persistence.LoadVMwareConfig()
+ if err != nil {
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "load_vmware_config").
+ Str("org_id", orgID).
+ Err(err).
+ Msg("VMware poller failed to load tenant VMware config")
+ continue
+ }
+
+ activeByConnection := make(map[string]config.VMwareVCenterInstance)
+ for _, instance := range instances {
+ instance.ApplyDefaults()
+ if !instance.Enabled {
+ continue
+ }
+ connectionID := strings.TrimSpace(instance.ID)
+ if connectionID == "" {
+ continue
+ }
+ activeByConnection[connectionID] = instance
+ }
+ active[orgID] = activeByConnection
+ }
+
+ p.mu.Lock()
+ defer p.mu.Unlock()
+
+ for orgID, connectionMap := range active {
+ if p.providersByOrg[orgID] == nil {
+ p.providersByOrg[orgID] = make(map[string]vmwarePollerProvider)
+ }
+ if p.configsByOrg[orgID] == nil {
+ p.configsByOrg[orgID] = make(map[string]config.VMwareVCenterInstance)
+ }
+ if p.cachedRecordsByOrg[orgID] == nil {
+ p.cachedRecordsByOrg[orgID] = make(map[string][]unifiedresources.IngestRecord)
+ }
+
+ for connectionID, instance := range connectionMap {
+ existingConfig, exists := p.configsByOrg[orgID][connectionID]
+ if exists && existingConfig == instance && p.providersByOrg[orgID][connectionID] != nil {
+ continue
+ }
+
+ if provider := p.providersByOrg[orgID][connectionID]; provider != nil {
+ provider.Close()
+ }
+
+ provider, err := p.newProvider(instance)
+ if err != nil {
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "build_provider").
+ Str("org_id", orgID).
+ Str("connection_id", connectionID).
+ Err(err).
+ Msg("VMware poller failed to build provider")
+ delete(p.providersByOrg[orgID], connectionID)
+ delete(p.cachedRecordsByOrg[orgID], connectionID)
+ p.configsByOrg[orgID][connectionID] = instance
+ continue
+ }
+
+ p.providersByOrg[orgID][connectionID] = provider
+ p.configsByOrg[orgID][connectionID] = instance
+ }
+ }
+
+ for orgID, providers := range p.providersByOrg {
+ activeConnections := active[orgID]
+ for connectionID, provider := range providers {
+ if _, ok := activeConnections[connectionID]; ok {
+ continue
+ }
+ if provider != nil {
+ provider.Close()
+ }
+ delete(providers, connectionID)
+ if p.cachedRecordsByOrg[orgID] != nil {
+ delete(p.cachedRecordsByOrg[orgID], connectionID)
+ }
+ if p.configsByOrg[orgID] != nil {
+ delete(p.configsByOrg[orgID], connectionID)
+ }
+ }
+
+ if len(providers) == 0 {
+ delete(p.providersByOrg, orgID)
+ delete(p.configsByOrg, orgID)
+ delete(p.cachedRecordsByOrg, orgID)
+ }
+ }
+}
+
+func (p *VMwarePoller) pollAll(ctx context.Context) {
+ for _, entry := range p.providerEntries() {
+ p.pollConnection(ctx, entry)
+ }
+}
+
+func (p *VMwarePoller) pollConnection(ctx context.Context, entry vmwarePollerProviderEntry) {
+ if entry.provider == nil {
+ return
+ }
+
+ pollCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
+ defer cancel()
+
+ if err := entry.provider.Refresh(pollCtx); err != nil {
+ log.Warn().
+ Str("component", "vmware_poller").
+ Str("action", "refresh").
+ Str("org_id", entry.orgID).
+ Str("connection_id", entry.connectionID).
+ Err(err).
+ Msg("VMware poller refresh failed")
+ return
+ }
+
+ records := cloneIngestRecords(entry.provider.Records())
+
+ p.mu.Lock()
+ if p.cachedRecordsByOrg[entry.orgID] == nil {
+ p.cachedRecordsByOrg[entry.orgID] = make(map[string][]unifiedresources.IngestRecord)
+ }
+ p.cachedRecordsByOrg[entry.orgID][entry.connectionID] = records
+ p.mu.Unlock()
+}
+
+func (p *VMwarePoller) providerEntries() []vmwarePollerProviderEntry {
+ if p == nil {
+ return nil
+ }
+
+ p.mu.Lock()
+ defer p.mu.Unlock()
+
+ var entries []vmwarePollerProviderEntry
+ for orgID, providers := range p.providersByOrg {
+ for connectionID, provider := range providers {
+ if provider == nil {
+ continue
+ }
+ entries = append(entries, vmwarePollerProviderEntry{
+ orgID: orgID,
+ connectionID: connectionID,
+ provider: provider,
+ })
+ }
+ }
+ sort.Slice(entries, func(i, j int) bool {
+ if entries[i].orgID == entries[j].orgID {
+ return entries[i].connectionID < entries[j].connectionID
+ }
+ return entries[i].orgID < entries[j].orgID
+ })
+ return entries
+}
+
+func (p *VMwarePoller) defaultProvider(instance config.VMwareVCenterInstance) (vmwarePollerProvider, error) {
+ client, err := vmware.NewClient(vmware.ClientConfig{
+ Host: instance.Host,
+ Port: instance.Port,
+ Username: instance.Username,
+ Password: instance.Password,
+ InsecureSkipVerify: instance.InsecureSkipVerify,
+ Timeout: 20 * time.Second,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return vmware.NewAPIProvider(vmware.ProviderMetadata{
+ ConnectionID: strings.TrimSpace(instance.ID),
+ ConnectionName: strings.TrimSpace(instance.Name),
+ VCenterHost: strings.TrimSpace(instance.Host),
+ }, client), nil
+}
+
+func (p *VMwarePoller) nextWaitDuration(now time.Time) time.Duration {
+ if p == nil || p.interval <= 0 {
+ return defaultVMwarePollInterval
+ }
+ return p.interval
+}
+
+// GetCurrentRecords returns the latest known VMware records for the default org.
+func (p *VMwarePoller) GetCurrentRecords() []unifiedresources.IngestRecord {
+ return p.GetCurrentRecordsForOrg("default")
+}
+
+// SupplementalRecords implements the monitor supplemental-record provider contract.
+func (p *VMwarePoller) SupplementalRecords(_ *Monitor, orgID string) []unifiedresources.IngestRecord {
+ return p.GetCurrentRecordsForOrg(orgID)
+}
+
+// SnapshotOwnedSources declares that VMware records are ingested through the
+// supplemental resource path rather than legacy monitor snapshot slices.
+func (p *VMwarePoller) SnapshotOwnedSources() []unifiedresources.DataSource {
+ return []unifiedresources.DataSource{unifiedresources.SourceVMware}
+}
+
+// SnapshotOwnedSourcesForOrg is the tenant-aware variant of SnapshotOwnedSources.
+func (p *VMwarePoller) SnapshotOwnedSourcesForOrg(string) []unifiedresources.DataSource {
+ return []unifiedresources.DataSource{unifiedresources.SourceVMware}
+}
+
+// GetCurrentRecordsForOrg returns the latest known VMware records for the specified org.
+func (p *VMwarePoller) GetCurrentRecordsForOrg(orgID string) []unifiedresources.IngestRecord {
+ if p == nil {
+ return nil
+ }
+
+ orgID = strings.TrimSpace(orgID)
+ if orgID == "" {
+ orgID = "default"
+ }
+
+ p.mu.Lock()
+ defer p.mu.Unlock()
+
+ recordsByConnection := p.cachedRecordsByOrg[orgID]
+ if len(recordsByConnection) == 0 {
+ return nil
+ }
+
+ connectionIDs := make([]string, 0, len(recordsByConnection))
+ for connectionID := range recordsByConnection {
+ connectionIDs = append(connectionIDs, connectionID)
+ }
+ sort.Strings(connectionIDs)
+
+ total := 0
+ for _, connectionID := range connectionIDs {
+ total += len(recordsByConnection[connectionID])
+ }
+ if total == 0 {
+ return nil
+ }
+
+ records := make([]unifiedresources.IngestRecord, 0, total)
+ for _, connectionID := range connectionIDs {
+ records = append(records, cloneIngestRecords(recordsByConnection[connectionID])...)
+ }
+ return records
+}
diff --git a/internal/monitoring/vmware_poller_test.go b/internal/monitoring/vmware_poller_test.go
new file mode 100644
index 0000000000..939d8d9ac8
--- /dev/null
+++ b/internal/monitoring/vmware_poller_test.go
@@ -0,0 +1,121 @@
+package monitoring
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+ "github.com/rcourtman/pulse-go-rewrite/internal/vmware"
+)
+
+func TestVMwarePollerPollsConfiguredConnections(t *testing.T) {
+ previous := vmware.IsFeatureEnabled()
+ vmware.SetFeatureEnabled(true)
+ t.Cleanup(func() { vmware.SetFeatureEnabled(previous) })
+
+ mtp, persistence := newTestTenantPersistence(t)
+ connection := config.NewVMwareVCenterInstance()
+ connection.ID = "vc-1"
+ connection.Name = "Lab VC"
+ connection.Host = "vc.lab.local"
+ connection.Username = "[email protected]"
+ connection.Password = "super-secret"
+
+ if err := persistence.SaveVMwareConfig([]config.VMwareVCenterInstance{connection}); err != nil {
+ t.Fatalf("SaveVMwareConfig() error = %v", err)
+ }
+
+ poller := NewVMwarePoller(mtp, 20*time.Millisecond)
+ poller.newProvider = func(instance config.VMwareVCenterInstance) (vmwarePollerProvider, error) {
+ return vmware.NewProvider(vmware.InventorySnapshot{
+ ConnectionID: instance.ID,
+ ConnectionName: instance.Name,
+ VCenterHost: instance.Host,
+ CollectedAt: time.Now().UTC(),
+ Hosts: []vmware.InventoryHost{{
+ Host: "host-101",
+ Name: "esxi-01.lab.local",
+ ConnectionState: "CONNECTED",
+ PowerState: "POWERED_ON",
+ HostUUID: "uuid-host-1",
+ }},
+ VMs: []vmware.InventoryVM{{
+ VM: "vm-201",
+ Name: "app-01",
+ PowerState: "POWERED_ON",
+ CPUCount: 2,
+ MemorySizeMiB: 4096,
+ }},
+ Datastores: []vmware.InventoryDatastore{{
+ Datastore: "datastore-11",
+ Name: "nvme-primary",
+ Type: "VMFS",
+ FreeSpace: 50,
+ Capacity: 100,
+ }},
+ }), nil
+ }
+ poller.Start(context.Background())
+ t.Cleanup(poller.Stop)
+
+ waitForCondition(t, 2*time.Second, func() bool {
+ return len(poller.GetCurrentRecordsForOrg("default")) == 3
+ }, "expected VMware poller to ingest projected records")
+
+ records := poller.GetCurrentRecordsForOrg("default")
+ if len(records) != 3 {
+ t.Fatalf("expected 3 VMware records, got %d", len(records))
+ }
+ gotSourceIDs := make([]string, 0, len(records))
+ for _, record := range records {
+ gotSourceIDs = append(gotSourceIDs, record.SourceID)
+ }
+ wantSourceIDs := []string{
+ "vc-1:host:host-101",
+ "vc-1:vm:vm-201",
+ "vc-1:datastore:datastore-11",
+ }
+ for i, want := range wantSourceIDs {
+ if gotSourceIDs[i] != want {
+ t.Fatalf("record %d sourceID = %q, want %q", i, gotSourceIDs[i], want)
+ }
+ }
+
+ ownedSources := poller.SnapshotOwnedSourcesForOrg("default")
+ if len(ownedSources) != 1 || ownedSources[0] != unifiedresources.SourceVMware {
+ t.Fatalf("owned sources = %#v, want [%q]", ownedSources, unifiedresources.SourceVMware)
+ }
+}
+
+func TestVMwarePollerFeatureFlagGate(t *testing.T) {
+ previous := vmware.IsFeatureEnabled()
+ vmware.SetFeatureEnabled(false)
+ t.Cleanup(func() { vmware.SetFeatureEnabled(previous) })
+
+ mtp, persistence := newTestTenantPersistence(t)
+ connection := config.NewVMwareVCenterInstance()
+ connection.ID = "vc-flag-off"
+ connection.Host = "vc.disabled.local"
+ connection.Username = "user"
+ connection.Password = "secret"
+
+ if err := persistence.SaveVMwareConfig([]config.VMwareVCenterInstance{connection}); err != nil {
+ t.Fatalf("SaveVMwareConfig() error = %v", err)
+ }
+
+ poller := NewVMwarePoller(mtp, 20*time.Millisecond)
+ initialStopped := poller.stopped
+ poller.Start(context.Background())
+
+ if poller.cancel != nil {
+ t.Fatal("expected Start() to be a no-op with feature flag disabled")
+ }
+ if poller.stopped != initialStopped {
+ t.Fatal("expected stopped channel to remain unchanged when Start() is gated")
+ }
+ if records := poller.GetCurrentRecordsForOrg("default"); len(records) != 0 {
+ t.Fatalf("expected no VMware records when feature flag is disabled, got %d", len(records))
+ }
+}
diff --git a/internal/unifiedresources/canonical_identity.go b/internal/unifiedresources/canonical_identity.go
index 5696e6aa76..4c97adc020 100644
--- a/internal/unifiedresources/canonical_identity.go
+++ b/internal/unifiedresources/canonical_identity.go
@@ -55,6 +55,9 @@ func canonicalPrimaryID(resource Resource) string {
if instanceID := strings.TrimSpace(canonicalPMGInstanceID(resource)); instanceID != "" {
return "pmg:" + instanceID
}
+ if identity := canonicalVMwarePrimaryID(resource); identity != "" {
+ return identity
+ }
return strings.TrimSpace(resource.ID)
}
@@ -80,6 +83,8 @@ func canonicalAliases(resource Resource, primaryID, platformID, hostname string)
canonicalAgentID(resource),
canonicalPBSInstanceID(resource),
canonicalPMGInstanceID(resource),
+ canonicalVMwareManagedObjectID(resource),
+ canonicalVMwareHostUUID(resource),
platformID,
hostname,
strings.TrimSpace(resource.Identity.MachineID),
@@ -218,6 +223,39 @@ func canonicalPMGInstanceID(resource Resource) string {
return strings.TrimSpace(resource.PMG.InstanceID)
}
+func canonicalVMwarePrimaryID(resource Resource) string {
+ if resource.VMware == nil {
+ return ""
+ }
+ managedObjectID := strings.TrimSpace(resource.VMware.ManagedObjectID)
+ if managedObjectID == "" {
+ return ""
+ }
+ entityType := strings.TrimSpace(resource.VMware.EntityType)
+ if entityType == "" {
+ entityType = string(CanonicalResourceType(resource.Type))
+ }
+ connectionID := strings.TrimSpace(resource.VMware.ConnectionID)
+ if connectionID != "" {
+ return "vmware:" + connectionID + ":" + entityType + ":" + managedObjectID
+ }
+ return "vmware:" + entityType + ":" + managedObjectID
+}
+
+func canonicalVMwareManagedObjectID(resource Resource) string {
+ if resource.VMware == nil {
+ return ""
+ }
+ return strings.TrimSpace(resource.VMware.ManagedObjectID)
+}
+
+func canonicalVMwareHostUUID(resource Resource) string {
+ if resource.VMware == nil {
+ return ""
+ }
+ return strings.TrimSpace(resource.VMware.HostUUID)
+}
+
func firstIdentityHostname(identity ResourceIdentity) string {
for _, hostname := range identity.Hostnames {
if trimmed := strings.TrimSpace(hostname); trimmed != "" {
diff --git a/internal/unifiedresources/canonical_identity_test.go b/internal/unifiedresources/canonical_identity_test.go
index 290df88f0a..56dc426c00 100644
--- a/internal/unifiedresources/canonical_identity_test.go
+++ b/internal/unifiedresources/canonical_identity_test.go
@@ -240,3 +240,56 @@ func TestRefreshCanonicalIdentityIgnoresProxmoxPoolAsPlatformIdentity(t *testing
}
}
}
+
+func TestRefreshCanonicalIdentityScopesVMwareManagedObjectsByConnection(t *testing.T) {
+ resource := Resource{
+ ID: "vmware-host-1",
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Identity: ResourceIdentity{
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ VCenterHost: "vc.lab.local",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ }
+
+ RefreshCanonicalIdentity(&resource)
+
+ if resource.Canonical == nil {
+ t.Fatalf("expected canonical identity")
+ }
+ if got := resource.Canonical.DisplayName; got != "esxi-01.lab.local" {
+ t.Fatalf("displayName = %q, want esxi-01.lab.local", got)
+ }
+ if got := resource.Canonical.Hostname; got != "esxi-01.lab.local" {
+ t.Fatalf("hostname = %q, want esxi-01.lab.local", got)
+ }
+ if got := resource.Canonical.PlatformID; got != "esxi-01.lab.local" {
+ t.Fatalf("platformId = %q, want esxi-01.lab.local", got)
+ }
+ if got := resource.Canonical.PrimaryID; got != "vmware:vc-1:host:host-101" {
+ t.Fatalf("primaryId = %q, want vmware:vc-1:host:host-101", got)
+ }
+
+ wantAliases := []string{
+ "vmware:vc-1:host:host-101",
+ "host-101",
+ "uuid-host-1",
+ "esxi-01.lab.local",
+ "vmware-host-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)
+ }
+ }
+}
diff --git a/internal/unifiedresources/clone.go b/internal/unifiedresources/clone.go
index 22a1a10be3..b178f7f8d7 100644
--- a/internal/unifiedresources/clone.go
+++ b/internal/unifiedresources/clone.go
@@ -40,6 +40,7 @@ func cloneResource(in *Resource) Resource {
out.PhysicalDisk = clonePhysicalDiskMeta(in.PhysicalDisk)
out.Ceph = cloneCephMeta(in.Ceph)
out.TrueNAS = cloneTrueNASData(in.TrueNAS)
+ out.VMware = cloneVMwareData(in.VMware)
out.FacetCounts = resourceFacetCounts(out)
RefreshCanonicalMetadata(&out)
return out
@@ -244,6 +245,14 @@ func clonePMGData(in *PMGData) *PMGData {
return &out
}
+func cloneVMwareData(in *VMwareData) *VMwareData {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ return &out
+}
+
func clonePMGRelayDomainMetaSlice(in []PMGRelayDomainMeta) []PMGRelayDomainMeta {
if in == nil {
return nil
diff --git a/internal/unifiedresources/metrics_targets.go b/internal/unifiedresources/metrics_targets.go
index b99a764238..57d81174f6 100644
--- a/internal/unifiedresources/metrics_targets.go
+++ b/internal/unifiedresources/metrics_targets.go
@@ -23,6 +23,9 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metric
if st, ok := bySource[SourceProxmox]; ok {
return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}
}
+ if st, ok := bySource[SourceVMware]; ok {
+ return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}
+ }
if st, ok := bySource[SourceAgent]; ok {
return &MetricsTarget{ResourceType: "agent", ResourceID: st.SourceID}
}
@@ -38,6 +41,9 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metric
if st, ok := bySource[SourceProxmox]; ok {
return &MetricsTarget{ResourceType: "vm", ResourceID: st.SourceID}
}
+ if st, ok := bySource[SourceVMware]; ok {
+ return &MetricsTarget{ResourceType: "vm", ResourceID: st.SourceID}
+ }
case ResourceTypeSystemContainer:
if st, ok := bySource[SourceProxmox]; ok {
return &MetricsTarget{ResourceType: "system-container", ResourceID: st.SourceID}
@@ -55,6 +61,9 @@ func BuildMetricsTarget(resource Resource, sourceTargets []SourceTarget) *Metric
if st, ok := bySource[SourceProxmox]; ok {
return &MetricsTarget{ResourceType: "storage", ResourceID: st.SourceID}
}
+ if st, ok := bySource[SourceVMware]; ok {
+ return &MetricsTarget{ResourceType: "storage", ResourceID: st.SourceID}
+ }
if st, ok := bySource[SourceTrueNAS]; ok {
return &MetricsTarget{ResourceType: "storage", ResourceID: st.SourceID}
}
diff --git a/internal/unifiedresources/metrics_targets_test.go b/internal/unifiedresources/metrics_targets_test.go
index 9444914ea1..4697daa43e 100644
--- a/internal/unifiedresources/metrics_targets_test.go
+++ b/internal/unifiedresources/metrics_targets_test.go
@@ -20,6 +20,17 @@ func TestBuildMetricsTarget_UsesCanonicalAgentTypeForInfrastructureFamilies(t *t
}},
wantID: "pve-node-1",
},
+ {
+ name: "vmware host",
+ resource: Resource{
+ Type: ResourceTypeAgent,
+ },
+ sourceTargets: []SourceTarget{{
+ Source: SourceVMware,
+ SourceID: "vc-1:host:host-101",
+ }},
+ wantID: "vc-1:host:host-101",
+ },
{
name: "pbs instance",
resource: Resource{
@@ -122,6 +133,56 @@ func TestBuildMetricsTarget_CanonicalizesSourceIDWhitespace(t *testing.T) {
}
}
+func TestBuildMetricsTarget_UsesCanonicalTargetsForVMwareWorkloadAndStorage(t *testing.T) {
+ tests := []struct {
+ name string
+ resource Resource
+ sourceTargets []SourceTarget
+ wantType string
+ wantID string
+ }{
+ {
+ name: "vmware vm",
+ resource: Resource{
+ Type: ResourceTypeVM,
+ },
+ sourceTargets: []SourceTarget{{
+ Source: SourceVMware,
+ SourceID: "vc-1:vm:vm-201",
+ }},
+ wantType: "vm",
+ wantID: "vc-1:vm:vm-201",
+ },
+ {
+ name: "vmware datastore",
+ resource: Resource{
+ Type: ResourceTypeStorage,
+ },
+ sourceTargets: []SourceTarget{{
+ Source: SourceVMware,
+ SourceID: "vc-1:datastore:datastore-11",
+ }},
+ wantType: "storage",
+ wantID: "vc-1:datastore:datastore-11",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ target := BuildMetricsTarget(tt.resource, tt.sourceTargets)
+ if target == nil {
+ t.Fatal("BuildMetricsTarget() returned nil")
+ }
+ if target.ResourceType != tt.wantType {
+ t.Fatalf("ResourceType = %q, want %q", target.ResourceType, tt.wantType)
+ }
+ if target.ResourceID != tt.wantID {
+ t.Fatalf("ResourceID = %q, want %q", target.ResourceID, tt.wantID)
+ }
+ })
+ }
+}
+
func TestBuildMetricsTarget_RejectsEmptyCanonicalSourceID(t *testing.T) {
tests := []struct {
name string
diff --git a/internal/unifiedresources/monitored_systems.go b/internal/unifiedresources/monitored_systems.go
index 1cee77b8df..46d60b356b 100644
--- a/internal/unifiedresources/monitored_systems.go
+++ b/internal/unifiedresources/monitored_systems.go
@@ -376,12 +376,14 @@ func monitoredSystemResourcePriority(resource *Resource) int {
switch {
case resource.Proxmox != nil:
return 0
- case resource.TrueNAS != nil:
+ case resource.VMware != nil:
return 1
- case resource.Docker != nil:
+ case resource.TrueNAS != nil:
return 2
- case resource.Agent != nil:
+ case resource.Docker != nil:
return 3
+ case resource.Agent != nil:
+ return 4
case resource.PBS != nil:
return 10
case resource.PMG != nil:
@@ -415,6 +417,8 @@ func monitoredSystemResourceDisplayName(resource *Resource) string {
switch {
case resource.Proxmox != nil && strings.TrimSpace(resource.Proxmox.NodeName) != "":
return strings.TrimSpace(resource.Proxmox.NodeName)
+ case resource.VMware != nil && strings.TrimSpace(resource.Name) != "":
+ return strings.TrimSpace(resource.Name)
case resource.Agent != nil && strings.TrimSpace(resource.Agent.Hostname) != "":
return strings.TrimSpace(resource.Agent.Hostname)
case resource.Docker != nil && strings.TrimSpace(resource.Docker.Hostname) != "":
@@ -440,6 +444,8 @@ func monitoredSystemType(resource *Resource) string {
switch {
case resource.Proxmox != nil:
return "proxmox-node"
+ case resource.VMware != nil:
+ return "vmware-host"
case resource.TrueNAS != nil:
return "truenas-system"
case resource.Docker != nil:
@@ -928,6 +934,8 @@ func monitoredSystemPrimarySource(resource *Resource) string {
switch {
case resource.Proxmox != nil:
return string(SourceProxmox)
+ case resource.VMware != nil:
+ return string(SourceVMware)
case resource.TrueNAS != nil:
return string(SourceTrueNAS)
case resource.Docker != nil:
@@ -963,6 +971,8 @@ func monitoredSystemStatusSourceLabel(value string) string {
return "Proxmox"
case "truenas":
return "TrueNAS"
+ case "vmware":
+ return "VMware"
case "", "unknown":
return "Unknown source"
default:
diff --git a/internal/unifiedresources/registry.go b/internal/unifiedresources/registry.go
index 6d59e74d1e..b986246d9c 100644
--- a/internal/unifiedresources/registry.go
+++ b/internal/unifiedresources/registry.go
@@ -23,6 +23,7 @@ var defaultStaleThresholds = map[DataSource]time.Duration{
SourcePMG: 120 * time.Second,
SourceK8s: 120 * time.Second,
SourceTrueNAS: 120 * time.Second,
+ SourceVMware: 120 * time.Second,
}
// IngestRecord is a source-native resource entry normalized for registry ingestion.
@@ -83,6 +84,7 @@ func NewRegistry(store ResourceStore) *ResourceRegistry {
rr.bySource[SourcePMG] = make(map[string]string)
rr.bySource[SourceK8s] = make(map[string]string)
rr.bySource[SourceTrueNAS] = make(map[string]string)
+ rr.bySource[SourceVMware] = make(map[string]string)
rr.loadOverrides()
return rr
@@ -917,6 +919,8 @@ func (rr *ResourceRegistry) mergeInto(existing *Resource, incoming Resource, sou
existing.Kubernetes = incoming.Kubernetes
case SourcePMG:
existing.PMG = incoming.PMG
+ case SourceVMware:
+ existing.VMware = mergeVMwareData(existing.VMware, incoming.VMware)
}
existing.Sources = addSource(existing.Sources, source)
@@ -1089,6 +1093,52 @@ func mergePhysicalDiskData(existing *PhysicalDiskMeta, incoming *PhysicalDiskMet
return &merged
}
+func mergeVMwareData(existing *VMwareData, incoming *VMwareData) *VMwareData {
+ if existing == nil {
+ return incoming
+ }
+ if incoming == nil {
+ return existing
+ }
+
+ merged := *existing
+ if incoming.ConnectionID != "" {
+ merged.ConnectionID = incoming.ConnectionID
+ }
+ if incoming.ConnectionName != "" {
+ merged.ConnectionName = incoming.ConnectionName
+ }
+ if incoming.VCenterHost != "" {
+ merged.VCenterHost = incoming.VCenterHost
+ }
+ if incoming.ManagedObjectID != "" {
+ merged.ManagedObjectID = incoming.ManagedObjectID
+ }
+ if incoming.EntityType != "" {
+ merged.EntityType = incoming.EntityType
+ }
+ if incoming.HostUUID != "" {
+ merged.HostUUID = incoming.HostUUID
+ }
+ if incoming.ConnectionState != "" {
+ merged.ConnectionState = incoming.ConnectionState
+ }
+ if incoming.PowerState != "" {
+ merged.PowerState = incoming.PowerState
+ }
+ if incoming.CPUCount > 0 {
+ merged.CPUCount = incoming.CPUCount
+ }
+ if incoming.MemorySizeMiB > 0 {
+ merged.MemorySizeMiB = incoming.MemorySizeMiB
+ }
+ if incoming.DatastoreType != "" {
+ merged.DatastoreType = incoming.DatastoreType
+ }
+
+ return &merged
+}
+
func (rr *ResourceRegistry) applyManualLinks() {
if len(rr.links) == 0 {
return
@@ -1649,6 +1699,8 @@ func sourcePriority(source DataSource) int {
return 2
case SourceDocker:
return 1
+ case SourceVMware:
+ return 2
default:
return 0
}
@@ -1782,7 +1834,7 @@ func (rr *ResourceRegistry) rebuildViews() {
v := NewNodeView(viewResource)
rr.cachedNodes = append(rr.cachedNodes, &v)
}
- if r.Agent != nil {
+ if r.Agent != nil || r.VMware != nil {
v := NewHostView(viewResource)
rr.cachedHosts = append(rr.cachedHosts, &v)
}
diff --git a/internal/unifiedresources/registry_test.go b/internal/unifiedresources/registry_test.go
index b209c863b4..b4c0cebb26 100644
--- a/internal/unifiedresources/registry_test.go
+++ b/internal/unifiedresources/registry_test.go
@@ -154,6 +154,53 @@ func TestResourceRegistry_MergesPhysicalDiskTemperatureAggregate(t *testing.T) {
}
}
+func TestResourceRegistry_IngestsVMwareSourceAsCanonicalResources(t *testing.T) {
+ rr := NewRegistry(nil)
+ now := time.Date(2026, 3, 30, 18, 30, 0, 0, time.UTC)
+
+ rr.IngestRecords(SourceVMware, []IngestRecord{
+ {
+ SourceID: "vc-1:host:host-101",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: StatusOnline,
+ LastSeen: now,
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ VCenterHost: "vc.lab.local",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ },
+ })
+
+ agents := rr.ListByType(ResourceTypeAgent)
+ if len(agents) != 1 {
+ t.Fatalf("expected 1 VMware agent resource, got %d", len(agents))
+ }
+ agent := agents[0]
+ if len(agent.Sources) != 1 || agent.Sources[0] != SourceVMware {
+ t.Fatalf("expected VMware source ownership, got %+v", agent.Sources)
+ }
+ if agent.VMware == nil {
+ t.Fatalf("expected VMware metadata on merged resource, got %+v", agent)
+ }
+ if got := agent.VMware.ConnectionID; got != "vc-1" {
+ t.Fatalf("vmware connection id = %q, want vc-1", got)
+ }
+ if got := agent.Canonical.PrimaryID; got != "vmware:vc-1:host:host-101" {
+ t.Fatalf("canonical primary id = %q, want vmware:vc-1:host:host-101", got)
+ }
+}
+
func TestResourceRegistryClonesCarryPolicyMetadata(t *testing.T) {
rr := NewRegistry(nil)
now := time.Date(2026, 3, 17, 12, 0, 0, 0, time.UTC)
diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.go
index e1377b5783..dcd553fd4a 100644
--- a/internal/unifiedresources/types.go
+++ b/internal/unifiedresources/types.go
@@ -64,6 +64,7 @@ type Resource struct {
PhysicalDisk *PhysicalDiskMeta `json:"physicalDisk,omitempty"`
Ceph *CephMeta `json:"ceph,omitempty"`
TrueNAS *TrueNASData `json:"truenas,omitempty"`
+ VMware *VMwareData `json:"vmware,omitempty"`
}
// ResourceFacetCounts captures the total count of each resource facet that
@@ -151,6 +152,7 @@ const (
SourcePMG DataSource = "pmg"
SourceK8s DataSource = "kubernetes"
SourceTrueNAS DataSource = "truenas"
+ SourceVMware DataSource = "vmware"
)
// SourceStatus describes the freshness of data from a source.
@@ -926,6 +928,22 @@ type PMGData struct {
DomainStatsAsOf time.Time `json:"domainStatsAsOf,omitempty"`
}
+// 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"`
+ CPUCount int `json:"cpuCount,omitempty"`
+ MemorySizeMiB int64 `json:"memorySizeMib,omitempty"`
+ DatastoreType string `json:"datastoreType,omitempty"`
+}
+
// TrueNASData contains TrueNAS-specific metadata for system host resources.
type TrueNASData struct {
Hostname string `json:"hostname,omitempty"`
diff --git a/internal/unifiedresources/views.go b/internal/unifiedresources/views.go
index d0cf36070e..422c58e11a 100644
--- a/internal/unifiedresources/views.go
+++ b/internal/unifiedresources/views.go
@@ -846,17 +846,29 @@ func (v HostView) Name() string {
}
func (v HostView) Hostname() string {
- if v.r == nil || v.r.Agent == nil {
+ if v.r == nil {
return ""
}
- return v.r.Agent.Hostname
+ if v.r.Agent != nil {
+ return v.r.Agent.Hostname
+ }
+ if v.r.VMware != nil {
+ return firstTrimmed(firstIdentityHostname(v.r.Identity), v.r.Name)
+ }
+ return ""
}
func (v HostView) MachineID() string {
- if v.r == nil || v.r.Agent == nil {
+ if v.r == nil {
return ""
}
- return v.r.Agent.MachineID
+ if v.r.Agent != nil {
+ return v.r.Agent.MachineID
+ }
+ if v.r.VMware != nil {
+ return strings.TrimSpace(v.r.VMware.HostUUID)
+ }
+ return ""
}
func (v HostView) TokenID() string {
@@ -889,10 +901,16 @@ func (v HostView) TokenLastUsedAt() *time.Time {
}
func (v HostView) Platform() string {
- if v.r == nil || v.r.Agent == nil {
+ if v.r == nil {
return ""
}
- return v.r.Agent.Platform
+ if v.r.Agent != nil {
+ return v.r.Agent.Platform
+ }
+ if v.r.VMware != nil {
+ return "vmware-vsphere"
+ }
+ return ""
}
func (v HostView) OSName() string {
diff --git a/internal/unifiedresources/views_test.go b/internal/unifiedresources/views_test.go
index 5a5cde0a2b..25c8fa3da8 100644
--- a/internal/unifiedresources/views_test.go
+++ b/internal/unifiedresources/views_test.go
@@ -1740,3 +1740,44 @@ func TestView_ReadStateInterfaceUsage(t *testing.T) {
t.Fatalf("expected 3 infrastructure resources (node + host + docker) via ReadState, got %d", len(got))
}
}
+
+func TestViews_HostsIncludesVMwareInfrastructureResources(t *testing.T) {
+ rr := NewRegistry(nil)
+ now := time.Now().UTC()
+
+ rr.IngestRecords(SourceVMware, []IngestRecord{{
+ SourceID: "vc-1:host:host-101",
+ Resource: Resource{
+ Type: ResourceTypeAgent,
+ Name: "esxi-01.lab.local",
+ Status: StatusOnline,
+ LastSeen: now,
+ UpdatedAt: now,
+ VMware: &VMwareData{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ ManagedObjectID: "host-101",
+ EntityType: "host",
+ HostUUID: "uuid-host-1",
+ },
+ },
+ Identity: ResourceIdentity{
+ DMIUUID: "uuid-host-1",
+ Hostnames: []string{"esxi-01.lab.local"},
+ },
+ }})
+
+ hosts := rr.Hosts()
+ if len(hosts) != 1 {
+ t.Fatalf("expected 1 VMware host view, got %d", len(hosts))
+ }
+ if got := hosts[0].Hostname(); got != "esxi-01.lab.local" {
+ t.Fatalf("Hostname() = %q, want esxi-01.lab.local", got)
+ }
+ if got := hosts[0].Platform(); got != "vmware-vsphere" {
+ t.Fatalf("Platform() = %q, want vmware-vsphere", got)
+ }
+ if got := hosts[0].MachineID(); got != "uuid-host-1" {
+ t.Fatalf("MachineID() = %q, want uuid-host-1", got)
+ }
+}
diff --git a/internal/vmware/client.go b/internal/vmware/client.go
index 2a860d6f1f..40dffa5a02 100644
--- a/internal/vmware/client.go
+++ b/internal/vmware/client.go
@@ -22,8 +22,9 @@ import (
const (
// FeatureVMware allows explicit opt-out of the default-on VMware vCenter
// platform integration.
- FeatureVMware = "PULSE_ENABLE_VMWARE"
- defaultTimeout = 10 * time.Second
+ FeatureVMware = "PULSE_ENABLE_VMWARE"
+ defaultTimeout = 10 * time.Second
+ inventoryResponseLimitByte = 8 << 20
)
var featureVMwareEnabled atomic.Bool
@@ -137,34 +138,53 @@ 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) {
- automationSessionID, err := c.createAutomationSession(ctx)
+ inventory, err := c.CollectInventory(ctx)
if err != nil {
return nil, err
}
- hosts, err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/host", "host inventory")
+ release, sessionManagerMoID, err := c.resolveVIJSONRelease(ctx)
if err != nil {
return nil, err
}
- vms, err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/vm", "vm inventory")
- if err != nil {
+ if err := c.loginVIJSON(ctx, release, sessionManagerMoID); err != nil {
return nil, err
}
- datastores, err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/datastore", "datastore inventory")
+ return &InventorySummary{
+ Hosts: len(inventory.Hosts),
+ VMs: len(inventory.VMs),
+ Datastores: len(inventory.Datastores),
+ VIRelease: release,
+ }, nil
+}
+
+// CollectInventory fetches the phase-1 VMware inventory floor used by the
+// supplemental-ingest provider.
+func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, error) {
+ automationSessionID, err := c.createAutomationSession(ctx)
if err != nil {
return nil, err
}
- release, sessionManagerMoID, err := c.resolveVIJSONRelease(ctx)
- if err != nil {
+
+ var hosts []InventoryHost
+ if err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/host", "host inventory", &hosts); err != nil {
return nil, err
}
- if err := c.loginVIJSON(ctx, release, sessionManagerMoID); err != nil {
+
+ var vms []InventoryVM
+ if err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/vm", "vm inventory", &vms); err != nil {
return nil, err
}
- return &InventorySummary{
- Hosts: len(hosts),
- VMs: len(vms),
- Datastores: len(datastores),
- VIRelease: release,
+
+ var datastores []InventoryDatastore
+ if err := c.listAutomationResources(ctx, automationSessionID, "/api/vcenter/datastore", "datastore inventory", &datastores); err != nil {
+ return nil, err
+ }
+
+ return &InventorySnapshot{
+ CollectedAt: time.Now().UTC(),
+ Hosts: hosts,
+ VMs: vms,
+ Datastores: datastores,
}, nil
}
@@ -241,39 +261,39 @@ func (c *Client) listAutomationResources(
sessionID string,
path string,
label string,
-) ([]json.RawMessage, error) {
+ target any,
+) error {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL.String()+path, nil)
if err != nil {
- return nil, fmt.Errorf("build %s request: %w", label, err)
+ return fmt.Errorf("build %s request: %w", label, err)
}
req.Header.Set("Accept", "application/json")
req.Header.Set("vmware-api-session-id", sessionID)
resp, err := c.httpClient.Do(req)
if err != nil {
- return nil, classifyTransportError(label, err)
+ return classifyTransportError(label, err)
}
defer resp.Body.Close()
- body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
+ body, readErr := io.ReadAll(io.LimitReader(resp.Body, inventoryResponseLimitByte))
if readErr != nil {
- return nil, fmt.Errorf("read %s response: %w", label, readErr)
+ return fmt.Errorf("read %s response: %w", label, readErr)
}
switch resp.StatusCode {
case http.StatusOK:
case http.StatusUnauthorized:
- return nil, &ConnectionError{Category: "auth", Message: fmt.Sprintf("VMware authentication failed while reading %s", label)}
+ return &ConnectionError{Category: "auth", Message: fmt.Sprintf("VMware authentication failed while reading %s", label)}
case http.StatusForbidden:
- return nil, &ConnectionError{Category: "permission", Message: fmt.Sprintf("VMware permissions are insufficient for %s", label)}
+ return &ConnectionError{Category: "permission", Message: fmt.Sprintf("VMware permissions are insufficient for %s", label)}
default:
- return nil, &ConnectionError{
+ return &ConnectionError{
Category: "endpoint",
Message: fmt.Sprintf("VMware %s request failed with HTTP %d", label, resp.StatusCode),
}
}
- var items []json.RawMessage
- if err := json.Unmarshal(body, &items); err != nil {
- return nil, &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s response was not valid JSON", label)}
+ if err := json.Unmarshal(body, target); err != nil {
+ return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s response was not valid JSON", label)}
}
- return items, nil
+ return nil
}
func (c *Client) resolveVIJSONRelease(ctx context.Context) (string, string, error) {
diff --git a/internal/vmware/provider.go b/internal/vmware/provider.go
new file mode 100644
index 0000000000..b42bab2707
--- /dev/null
+++ b/internal/vmware/provider.go
@@ -0,0 +1,479 @@
+package vmware
+
+import (
+ "context"
+ "fmt"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+// 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"`
+}
+
+// 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"`
+}
+
+// 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"`
+}
+
+// InventorySnapshot captures the projected inventory floor for one vCenter
+// connection at one point in time.
+type InventorySnapshot struct {
+ ConnectionID string
+ ConnectionName string
+ VCenterHost string
+ CollectedAt time.Time
+ Hosts []InventoryHost
+ VMs []InventoryVM
+ Datastores []InventoryDatastore
+}
+
+// ProviderMetadata carries operator-owned vCenter connection labels onto the
+// projected resource graph.
+type ProviderMetadata struct {
+ ConnectionID string
+ ConnectionName string
+ VCenterHost string
+}
+
+// Fetcher loads a VMware inventory snapshot from a concrete source.
+type Fetcher interface {
+ Fetch(ctx context.Context) (*InventorySnapshot, error)
+}
+
+type fetcherCloser interface {
+ Close()
+}
+
+// APIFetcher loads inventory from the live VMware client.
+type APIFetcher struct {
+ Client *Client
+ Metadata ProviderMetadata
+}
+
+// Fetch implements Fetcher.
+func (f *APIFetcher) Fetch(ctx context.Context) (*InventorySnapshot, error) {
+ if f == nil || f.Client == nil {
+ return nil, fmt.Errorf("vmware api fetcher client is nil")
+ }
+ snapshot, err := f.Client.CollectInventory(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if snapshot == nil {
+ return nil, fmt.Errorf("vmware api fetcher returned nil inventory")
+ }
+ snapshot.ConnectionID = strings.TrimSpace(f.Metadata.ConnectionID)
+ snapshot.ConnectionName = strings.TrimSpace(f.Metadata.ConnectionName)
+ snapshot.VCenterHost = strings.TrimSpace(f.Metadata.VCenterHost)
+ return snapshot, nil
+}
+
+// Close releases idle resources held by the underlying VMware client.
+func (f *APIFetcher) Close() {
+ if f == nil || f.Client == nil {
+ return
+ }
+ f.Client.Close()
+}
+
+// FixtureFetcher loads inventory from static fixtures for tests.
+type FixtureFetcher struct {
+ Snapshot InventorySnapshot
+}
+
+// Fetch implements Fetcher.
+func (f *FixtureFetcher) Fetch(context.Context) (*InventorySnapshot, error) {
+ if f == nil {
+ return nil, nil
+ }
+ return cloneInventorySnapshot(&f.Snapshot), nil
+}
+
+// Provider converts VMware inventory snapshots into unified resources.
+type Provider struct {
+ fetcher Fetcher
+ lastSnapshot *InventorySnapshot
+ mu sync.Mutex
+ now func() time.Time
+}
+
+// NewLiveProvider returns a provider backed by a concrete fetcher.
+func NewLiveProvider(fetcher Fetcher) *Provider {
+ return &Provider{
+ fetcher: fetcher,
+ now: func() time.Time {
+ return time.Now().UTC()
+ },
+ }
+}
+
+// NewAPIProvider returns a provider backed by the live VMware API client.
+func NewAPIProvider(metadata ProviderMetadata, client *Client) *Provider {
+ return NewLiveProvider(&APIFetcher{
+ Client: client,
+ Metadata: metadata,
+ })
+}
+
+// NewProvider returns a fixture-backed provider.
+func NewProvider(snapshot InventorySnapshot) *Provider {
+ if snapshot.CollectedAt.IsZero() {
+ snapshot.CollectedAt = time.Now().UTC()
+ }
+ provider := NewLiveProvider(&FixtureFetcher{Snapshot: snapshot})
+ provider.lastSnapshot = cloneInventorySnapshot(&snapshot)
+ return provider
+}
+
+// Refresh fetches and caches the latest snapshot.
+func (p *Provider) Refresh(ctx context.Context) error {
+ if p == nil {
+ return fmt.Errorf("vmware provider is nil")
+ }
+ if p.fetcher == nil {
+ return fmt.Errorf("vmware provider fetcher is nil")
+ }
+
+ snapshot, err := p.fetcher.Fetch(ctx)
+ if err != nil {
+ return fmt.Errorf("refresh vmware inventory: %w", err)
+ }
+ if snapshot == nil {
+ return fmt.Errorf("vmware provider fetcher returned nil inventory")
+ }
+
+ sortInventorySnapshot(snapshot)
+
+ p.mu.Lock()
+ p.lastSnapshot = cloneInventorySnapshot(snapshot)
+ p.mu.Unlock()
+ return nil
+}
+
+// Close releases resources held by the active fetcher, if supported.
+func (p *Provider) Close() {
+ if p == nil || p.fetcher == nil {
+ return
+ }
+ if closer, ok := p.fetcher.(fetcherCloser); ok {
+ closer.Close()
+ }
+}
+
+// Snapshot returns a defensive copy of the cached inventory snapshot.
+func (p *Provider) Snapshot() *InventorySnapshot {
+ if p == nil {
+ return nil
+ }
+ p.mu.Lock()
+ snapshot := cloneInventorySnapshot(p.lastSnapshot)
+ p.mu.Unlock()
+ return snapshot
+}
+
+// Records returns canonical VMware unified resources if the integration is enabled.
+func (p *Provider) Records() []unifiedresources.IngestRecord {
+ if p == nil || !IsFeatureEnabled() {
+ return nil
+ }
+
+ snapshot := p.Snapshot()
+ if snapshot == nil {
+ return nil
+ }
+
+ collectedAt := snapshot.CollectedAt
+ if collectedAt.IsZero() {
+ collectedAt = p.now()
+ }
+
+ 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))
+
+ for _, host := range snapshot.Hosts {
+ name := firstNonEmptyTrimmed(host.Name, host.Host)
+ if name == "" {
+ continue
+ }
+ resource := unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeAgent,
+ Technology: "vmware",
+ Name: name,
+ Status: hostStatus(host),
+ LastSeen: collectedAt,
+ UpdatedAt: collectedAt,
+ 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),
+ },
+ Tags: filterNonEmptyStrings(
+ "vmware",
+ "vsphere",
+ "host",
+ "source:vcenter",
+ tagWithValue("connection", strings.ToLower(connectionName)),
+ tagWithValue("power", strings.ToLower(strings.TrimSpace(host.PowerState))),
+ tagWithValue("state", strings.ToLower(strings.TrimSpace(host.ConnectionState))),
+ ),
+ }
+ identity := unifiedresources.ResourceIdentity{
+ DMIUUID: strings.TrimSpace(host.HostUUID),
+ Hostnames: filterNonEmptyStrings(name),
+ }
+ records = append(records, unifiedresources.IngestRecord{
+ SourceID: vmwareSourceID(snapshot.ConnectionID, "host", host.Host),
+ Resource: resource,
+ Identity: identity,
+ })
+ }
+
+ for _, vm := range snapshot.VMs {
+ name := firstNonEmptyTrimmed(vm.Name, vm.VM)
+ if name == "" {
+ continue
+ }
+ resource := unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeVM,
+ Technology: "vmware",
+ Name: name,
+ Status: vmStatus(vm),
+ LastSeen: collectedAt,
+ UpdatedAt: collectedAt,
+ 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,
+ },
+ Tags: filterNonEmptyStrings(
+ "vmware",
+ "vsphere",
+ "vm",
+ "source:vcenter",
+ tagWithValue("connection", strings.ToLower(connectionName)),
+ tagWithValue("power", strings.ToLower(strings.TrimSpace(vm.PowerState))),
+ ),
+ }
+ records = append(records, unifiedresources.IngestRecord{
+ SourceID: vmwareSourceID(snapshot.ConnectionID, "vm", vm.VM),
+ Resource: resource,
+ })
+ }
+
+ for _, datastore := range snapshot.Datastores {
+ name := firstNonEmptyTrimmed(datastore.Name, datastore.Datastore)
+ if name == "" {
+ continue
+ }
+ used := datastore.Capacity - datastore.FreeSpace
+ if used < 0 {
+ used = 0
+ }
+ resource := unifiedresources.Resource{
+ Type: unifiedresources.ResourceTypeStorage,
+ Technology: "vmware",
+ Name: name,
+ Status: datastoreStatus(datastore),
+ LastSeen: collectedAt,
+ UpdatedAt: collectedAt,
+ Metrics: &unifiedresources.ResourceMetrics{
+ Disk: diskMetric(datastore.Capacity, used),
+ },
+ Storage: &unifiedresources.StorageMeta{
+ Type: normalizeDatastoreType(datastore.Type),
+ Platform: "vmware-vsphere",
+ Topology: "datastore",
+ Enabled: true,
+ },
+ VMware: &unifiedresources.VMwareData{
+ ConnectionID: strings.TrimSpace(snapshot.ConnectionID),
+ ConnectionName: connectionName,
+ VCenterHost: vcenterHost,
+ ManagedObjectID: strings.TrimSpace(datastore.Datastore),
+ EntityType: "datastore",
+ DatastoreType: strings.TrimSpace(datastore.Type),
+ },
+ Tags: filterNonEmptyStrings(
+ "vmware",
+ "vsphere",
+ "datastore",
+ "source:vcenter",
+ tagWithValue("connection", strings.ToLower(connectionName)),
+ tagWithValue("type", strings.ToLower(strings.TrimSpace(datastore.Type))),
+ ),
+ }
+ records = append(records, unifiedresources.IngestRecord{
+ SourceID: vmwareSourceID(snapshot.ConnectionID, "datastore", datastore.Datastore),
+ Resource: resource,
+ })
+ }
+
+ return records
+}
+
+func sortInventorySnapshot(snapshot *InventorySnapshot) {
+ if snapshot == nil {
+ return
+ }
+ sort.Slice(snapshot.Hosts, func(i, j int) bool {
+ return vmwareSortKey(snapshot.Hosts[i].Host, snapshot.Hosts[i].Name) < vmwareSortKey(snapshot.Hosts[j].Host, snapshot.Hosts[j].Name)
+ })
+ sort.Slice(snapshot.VMs, func(i, j int) bool {
+ return vmwareSortKey(snapshot.VMs[i].VM, snapshot.VMs[i].Name) < vmwareSortKey(snapshot.VMs[j].VM, snapshot.VMs[j].Name)
+ })
+ sort.Slice(snapshot.Datastores, func(i, j int) bool {
+ return vmwareSortKey(snapshot.Datastores[i].Datastore, snapshot.Datastores[i].Name) < vmwareSortKey(snapshot.Datastores[j].Datastore, snapshot.Datastores[j].Name)
+ })
+}
+
+func cloneInventorySnapshot(in *InventorySnapshot) *InventorySnapshot {
+ if in == nil {
+ return nil
+ }
+ out := *in
+ out.Hosts = append([]InventoryHost(nil), in.Hosts...)
+ out.VMs = append([]InventoryVM(nil), in.VMs...)
+ out.Datastores = append([]InventoryDatastore(nil), in.Datastores...)
+ return &out
+}
+
+func vmwareSourceID(connectionID, entityType, managedObjectID string) string {
+ parts := filterNonEmptyStrings(strings.TrimSpace(connectionID), strings.TrimSpace(entityType), strings.TrimSpace(managedObjectID))
+ return strings.Join(parts, ":")
+}
+
+func hostStatus(host InventoryHost) unifiedresources.ResourceStatus {
+ switch strings.ToUpper(strings.TrimSpace(host.ConnectionState)) {
+ case "CONNECTED":
+ switch strings.ToUpper(strings.TrimSpace(host.PowerState)) {
+ case "", "POWERED_ON":
+ return unifiedresources.StatusOnline
+ case "POWERED_OFF":
+ return unifiedresources.StatusOffline
+ default:
+ return unifiedresources.StatusWarning
+ }
+ case "DISCONNECTED", "NOT_RESPONDING":
+ return unifiedresources.StatusOffline
+ default:
+ return unifiedresources.StatusUnknown
+ }
+}
+
+func vmStatus(vm InventoryVM) unifiedresources.ResourceStatus {
+ switch strings.ToUpper(strings.TrimSpace(vm.PowerState)) {
+ case "POWERED_ON":
+ return unifiedresources.StatusOnline
+ case "POWERED_OFF", "SUSPENDED":
+ return unifiedresources.StatusOffline
+ default:
+ return unifiedresources.StatusUnknown
+ }
+}
+
+func datastoreStatus(datastore InventoryDatastore) unifiedresources.ResourceStatus {
+ if strings.TrimSpace(datastore.Datastore) == "" && strings.TrimSpace(datastore.Name) == "" {
+ return unifiedresources.StatusUnknown
+ }
+ return unifiedresources.StatusOnline
+}
+
+func normalizeDatastoreType(value string) string {
+ return strings.ToLower(strings.TrimSpace(value))
+}
+
+func diskMetric(total, used int64) *unifiedresources.MetricValue {
+ if total <= 0 {
+ return nil
+ }
+ totalCopy := total
+ usedCopy := used
+ percent := (float64(used) / float64(total)) * 100
+ return &unifiedresources.MetricValue{
+ Total: &totalCopy,
+ Used: &usedCopy,
+ Value: percent,
+ Percent: percent,
+ Unit: "bytes",
+ }
+}
+
+func firstNonEmptyTrimmed(values ...string) string {
+ for _, value := range values {
+ if trimmed := strings.TrimSpace(value); trimmed != "" {
+ return trimmed
+ }
+ }
+ return ""
+}
+
+func filterNonEmptyStrings(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)
+ }
+ return out
+}
+
+func tagWithValue(prefix, value string) string {
+ prefix = strings.TrimSpace(prefix)
+ value = strings.TrimSpace(value)
+ if prefix == "" || value == "" {
+ return ""
+ }
+ return prefix + ":" + value
+}
+
+func vmwareSortKey(id, name string) string {
+ return firstNonEmptyTrimmed(strings.ToLower(strings.TrimSpace(id)), strings.ToLower(strings.TrimSpace(name)))
+}
diff --git a/internal/vmware/provider_test.go b/internal/vmware/provider_test.go
new file mode 100644
index 0000000000..30f42625af
--- /dev/null
+++ b/internal/vmware/provider_test.go
@@ -0,0 +1,99 @@
+package vmware
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func TestProviderRecords_ProjectCanonicalVMwareResources(t *testing.T) {
+ previous := IsFeatureEnabled()
+ SetFeatureEnabled(true)
+ t.Cleanup(func() { SetFeatureEnabled(previous) })
+
+ collectedAt := time.Date(2026, time.March, 30, 18, 15, 0, 0, time.UTC)
+ provider := NewProvider(InventorySnapshot{
+ ConnectionID: "vc-1",
+ ConnectionName: "Lab VC",
+ 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",
+ }},
+ VMs: []InventoryVM{{
+ VM: "vm-201",
+ Name: "app-01",
+ PowerState: "POWERED_ON",
+ CPUCount: 4,
+ MemorySizeMiB: 8192,
+ }},
+ Datastores: []InventoryDatastore{{
+ Datastore: "datastore-11",
+ Name: "nvme-primary",
+ Type: "VMFS",
+ FreeSpace: 40,
+ Capacity: 100,
+ }},
+ })
+
+ records := provider.Records()
+ if len(records) != 3 {
+ t.Fatalf("expected 3 VMware records, got %d", len(records))
+ }
+
+ hostRecord := records[0]
+ if hostRecord.SourceID != "vc-1:host:host-101" {
+ t.Fatalf("host source id = %q, want vc-1:host:host-101", hostRecord.SourceID)
+ }
+ if hostRecord.Resource.Type != unifiedresources.ResourceTypeAgent {
+ t.Fatalf("host resource type = %q, want %q", hostRecord.Resource.Type, unifiedresources.ResourceTypeAgent)
+ }
+ if hostRecord.Resource.Status != unifiedresources.StatusOnline {
+ t.Fatalf("host status = %q, want %q", hostRecord.Resource.Status, unifiedresources.StatusOnline)
+ }
+ if hostRecord.Resource.VMware == nil || hostRecord.Resource.VMware.ManagedObjectID != "host-101" {
+ t.Fatalf("expected VMware host metadata, got %+v", hostRecord.Resource.VMware)
+ }
+ if hostRecord.Identity.DMIUUID != "uuid-host-1" {
+ t.Fatalf("host identity DMI UUID = %q, want uuid-host-1", hostRecord.Identity.DMIUUID)
+ }
+ if hostRecord.Resource.LastSeen != collectedAt {
+ t.Fatalf("host last seen = %v, want %v", hostRecord.Resource.LastSeen, collectedAt)
+ }
+
+ vmRecord := records[1]
+ if vmRecord.SourceID != "vc-1:vm:vm-201" {
+ t.Fatalf("vm source id = %q, want vc-1:vm:vm-201", vmRecord.SourceID)
+ }
+ if vmRecord.Resource.Type != unifiedresources.ResourceTypeVM {
+ t.Fatalf("vm resource type = %q, want %q", vmRecord.Resource.Type, unifiedresources.ResourceTypeVM)
+ }
+ if vmRecord.Resource.VMware == nil || vmRecord.Resource.VMware.CPUCount != 4 {
+ t.Fatalf("expected VMware VM metadata with cpu count, got %+v", vmRecord.Resource.VMware)
+ }
+ if vmRecord.Resource.Status != unifiedresources.StatusOnline {
+ t.Fatalf("vm status = %q, want %q", vmRecord.Resource.Status, unifiedresources.StatusOnline)
+ }
+
+ datastoreRecord := records[2]
+ if datastoreRecord.SourceID != "vc-1:datastore:datastore-11" {
+ t.Fatalf("datastore source id = %q, want vc-1:datastore:datastore-11", datastoreRecord.SourceID)
+ }
+ if datastoreRecord.Resource.Type != unifiedresources.ResourceTypeStorage {
+ t.Fatalf("datastore resource type = %q, want %q", datastoreRecord.Resource.Type, unifiedresources.ResourceTypeStorage)
+ }
+ if datastoreRecord.Resource.Storage == nil || datastoreRecord.Resource.Storage.Platform != "vmware-vsphere" {
+ t.Fatalf("expected canonical VMware storage metadata, got %+v", datastoreRecord.Resource.Storage)
+ }
+ if datastoreRecord.Resource.Metrics == nil || datastoreRecord.Resource.Metrics.Disk == nil {
+ t.Fatal("expected datastore disk metrics to be populated")
+ }
+ if got := datastoreRecord.Resource.Metrics.Disk.Percent; got != 60 {
+ t.Fatalf("datastore disk usage percent = %v, want 60", got)
+ }
+}
diff --git a/scripts/release_control/canonical_completion_guard_test.py b/scripts/release_control/canonical_completion_guard_test.py
index a41ef812e0..f9f2d97ee4 100644
--- a/scripts/release_control/canonical_completion_guard_test.py
+++ b/scripts/release_control/canonical_completion_guard_test.py
@@ -2832,8 +2832,8 @@ class CanonicalCompletionGuardTest(unittest.TestCase):
{
"heading": "## Extension Points",
"path": "internal/unifiedresources/views.go",
- "line": 46,
- "heading_line": 42,
+ "line": 47,
+ "heading_line": 43,
},
],
)
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 07f7fa5779..94a0f8985e 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -4614,8 +4614,8 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Extension Points",
"path": "internal/unifiedresources/views.go",
- "line": 46,
- "heading_line": 42,
+ "line": 47,
+ "heading_line": 43,
},
],
)
diff --git a/tests/integration/tests/35-vmware-infrastructure-source-filter.spec.ts b/tests/integration/tests/35-vmware-infrastructure-source-filter.spec.ts
new file mode 100644
index 0000000000..33047dec49
--- /dev/null
+++ b/tests/integration/tests/35-vmware-infrastructure-source-filter.spec.ts
@@ -0,0 +1,114 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { expect, test as base } from '@playwright/test';
+
+import { createAuthenticatedStorageState } from './helpers';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const SCREENSHOT_PATH = '/tmp/vmware-infrastructure-source-filter.png';
+
+type WorkerFixtures = {
+ authStorageStatePath: string;
+};
+
+const test = base.extend<{}, WorkerFixtures>({
+ storageState: async ({ authStorageStatePath }, use) => {
+ await use(authStorageStatePath);
+ },
+ authStorageStatePath: [async ({ browser }, use, workerInfo) => {
+ const storageStatePath = path.resolve(
+ __dirname,
+ '..',
+ '..',
+ 'tmp',
+ 'playwright-auth',
+ `vmware-infrastructure-source-filter-${workerInfo.project.name}.json`,
+ );
+ fs.mkdirSync(path.dirname(storageStatePath), { recursive: true });
+ await createAuthenticatedStorageState(browser, storageStatePath);
+ try {
+ await use(storageStatePath);
+ } finally {
+ fs.rmSync(storageStatePath, { force: true });
+ }
+ }, { scope: 'worker' }],
+});
+
+test.describe('VMware infrastructure source filter', () => {
+ test.setTimeout(180_000);
+
+ test('surfaces VMware resources under the canonical vSphere infrastructure filter', async ({
+ page,
+ }) => {
+ await page.route('**/api/resources**', async (route) => {
+ const requestUrl = new URL(route.request().url());
+ if (requestUrl.pathname !== '/api/resources') {
+ await route.continue();
+ return;
+ }
+
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ data: [
+ {
+ id: 'vmware-host-1',
+ type: 'agent',
+ name: 'esxi-01.lab.local',
+ displayName: 'ESXi 01',
+ platformId: 'vmware-host-1',
+ platformType: 'vmware-vsphere',
+ sourceType: 'api',
+ sources: ['vmware-vsphere'],
+ status: 'online',
+ lastSeen: '2026-03-30T17:00:00Z',
+ canonicalIdentity: {
+ displayName: 'ESXi 01',
+ hostname: 'esxi-01.lab.local',
+ platformId: 'vmware-host-1',
+ },
+ agent: {
+ hostname: 'esxi-01.lab.local',
+ platform: 'VMware ESXi',
+ uptimeSeconds: 86400,
+ },
+ platformData: {
+ sources: ['vmware-vsphere'],
+ },
+ },
+ ],
+ meta: {
+ page: 1,
+ limit: 200,
+ total: 1,
+ totalPages: 1,
+ },
+ }),
+ });
+ });
+
+ await page.goto('/infrastructure?source=vmware-vsphere', {
+ waitUntil: 'domcontentloaded',
+ });
+
+ await expect(page.getByTestId('infrastructure-page')).toBeVisible();
+ await expect(page).toHaveURL(/\/infrastructure\?source=vmware-vsphere/);
+ await expect(page.locator('#infra-source-filter')).toHaveValue('vmware-vsphere');
+
+ const sourceOptions = await page.locator('#infra-source-filter option').evaluateAll((options) =>
+ options.map((option) => ({
+ value: option.getAttribute('value'),
+ label: option.textContent?.trim(),
+ })),
+ );
+ expect(sourceOptions).toEqual([
+ { value: '', label: 'All' },
+ { value: 'vmware-vsphere', label: 'vSphere' },
+ ]);
+
+ await expect(page.getByText('ESXi 01')).toBeVisible();
+ await page.screenshot({ path: SCREENSHOT_PATH, fullPage: true });
+ });
+});