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.

feat(vmware): ingest real vCenter tags instead of provenance placeholders

rcourtmaneac9ffcabf8f
diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
index a55cfd706d..d07d828e5c 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -624,13 +624,33 @@ change may globally weaken the Task 03 lifecycle-state idempotency invariant.
control on that page. The migration only fires where the id is already in
that scope's effective default-hidden set, and it records a marker so a
column the user deliberately restores is never re-hidden.
- vSphere additionally default-hides `tags`. The vSphere adapter does not
- read vCenter's tag/category API; `internal/vmware/provider.go` fills
- `Resource.Tags` with fixed provenance strings, so the column repeats the
- same values on every row and filtering on any of them selects the whole
- estate. The tags stay in the payload because search and facet counts
- consume them. This hide is a stopgap and must be removed once the adapter
- ingests real vCenter tags, not treated as the settled contract.
+ vSphere previously default-hid `tags` as well, because the adapter filled
+ `Resource.Tags` with fixed provenance strings and never read vCenter's own
+ tag/category system. That stopgap is retired: `internal/vmware/client_tags.go`
+ reads the CIS tagging service and `internal/vmware/provider.go` projects the
+ result onto both the flat `Resource.Tags` keyword set and the canonical
+ `VMware.Tags` facet, so `tags` is default-visible on every workload scope
+ again.
+ The two tag surfaces have distinct contracts and must not be collapsed.
+ `Resource.Tags` is the flat keyword set that resource search, the `?tags=`
+ resources filter, and saved report-schedule tag filters read, so the
+ adapter's provenance strings stay in it and real vCenter labels are
+ appended, never substituted. `VMware.Tags` carries only the operator's own
+ tags with their vCenter category, and is what per-row presentation reads:
+ `useWorkloads.ts` maps `WorkloadGuest.tags` from that facet for any
+ resource carrying VMware metadata, including the empty case, so an untagged
+ vSphere VM renders an empty cell rather than falling back to six identical
+ provenance dots. A future adapter that mixes provenance into `Resource.Tags`
+ owes the same facet split rather than a column hide.
+ Tag reads are optional enrichment on the collection hot path and are
+ bounded accordingly. Associations come from one batched
+ `list-attached-tags-on-objects` POST per bounded object batch, never a
+ per-object request; tag and category names resolve at most once per client
+ TTL through the client-scoped catalog, so a steady-state refresh of a
+ tagged estate costs only the association reads. A vCenter without the
+ tagging service, or an account without the tag read privilege, must degrade
+ into an `InventoryEnrichmentIssue` on the `tags` stage and leave the
+ inventory untagged; it must never fail the refresh.
Column visibility that depends on whether data exists at all is data-gated
rather than preference-gated. `availability` is the current case: the cell
renders nothing until an availability check is linked to that workload, so
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 0506de4685..ffab53eb5d 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -1433,7 +1433,15 @@ recovery scope, or a storage/recovery-owned secret source.
when linking to an owning runtime/platform page; they must not reinterpret
container block I/O totals as backup throughput, recovery-point evidence,
protection cadence, or storage-health ownership.
-30. Keep VMware placement, cluster service state, guest-detail, VM snapshot-tree, VM virtual-hardware configuration, VMware Tools, VM hardware Ethernet, VM hardware disk, and network 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, `vmware.clusterHaEnabled`, `vmware.clusterDrsEnabled`, folder, runtime-host, datastore-attachment, guest-hostname, guest-IP, `vmware.currentSnapshotId`, `vmware.snapshotTree`, snapshot creation/state/quiesce/current markers, child snapshot metadata, `vmware.hardware`, virtual hardware version, hardware upgrade policy/version/status/error, boot type/order/retry/setup-mode flags, CPU cores-per-socket and hot-add/remove flags, memory hot-add settings, `vmware.tools`, Tools run state, version status, version number/string, install type, upgrade policy, auto-update support, install-attempt count, guest reboot requests, `vmware.networkAdapters`, adapter MAC address/type, backing network id/name, backing type, connection state, start-connected / guest-control flags, `vmware.virtualDisks`, virtual disk label/type, IDE/SCSI/SATA/NVMe placement, VMDK path, backing type, datastore name, capacity, `vmware.networkType`, `vmware.networkHostNames`, or `vmware.networkVmNames` onto canonical VMware `agent` / `vm` / `storage` / `network` resources, storage and recovery may use that detail for labeling, navigation, and VM investigation context only; they must not promote those topology, cluster-service, guest, snapshot-tree, virtual-hardware, VMware Tools, vNIC, virtual disk, or network fields into recovery ownership, restore targeting, protection grouping, compliance scoring, or a VMware-local recovery taxonomy without a separately governed slice.
+30. Keep VMware placement, cluster service state, guest-detail, VM snapshot-tree, VM virtual-hardware configuration, VMware Tools, VM hardware Ethernet, VM hardware disk, and network 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, `vmware.clusterHaEnabled`, `vmware.clusterDrsEnabled`, folder, runtime-host, datastore-attachment, guest-hostname, guest-IP, `vmware.currentSnapshotId`, `vmware.snapshotTree`, snapshot creation/state/quiesce/current markers, child snapshot metadata, `vmware.hardware`, virtual hardware version, hardware upgrade policy/version/status/error, boot type/order/retry/setup-mode flags, CPU cores-per-socket and hot-add/remove flags, memory hot-add settings, `vmware.tools`, Tools run state, version status, version number/string, install type, upgrade policy, auto-update support, install-attempt count, guest reboot requests, `vmware.networkAdapters`, adapter MAC address/type, backing network id/name, backing type, connection state, start-connected / guest-control flags, `vmware.virtualDisks`, virtual disk label/type, IDE/SCSI/SATA/NVMe placement, VMDK path, backing type, datastore name, capacity, `vmware.networkType`, `vmware.networkHostNames`, `vmware.networkVmNames`, or `vmware.tags` onto canonical VMware `agent` / `vm` / `storage` / `network` resources, storage and recovery may use that detail for labeling, navigation, and VM investigation context only; they must not promote those topology, cluster-service, guest, snapshot-tree, virtual-hardware, VMware Tools, vNIC, virtual disk, tag, or network fields into recovery ownership, restore targeting, protection grouping, compliance scoring, or a VMware-local recovery taxonomy without a separately governed slice.
+ `vmware.tags` is the sharpest case of that boundary, because vCenter tag
+ vocabularies routinely read like backup policy — an operator-authored
+ `Backup:Nightly` or `Compliance:PCI` is a label the operator wrote, not a
+ protection fact Pulse observed. Recovery may surface those tags as
+ descriptive context and may filter by them, but a tag must never stand in
+ for an observed backup, satisfy a protection requirement, or move a
+ resource's coverage or compliance verdict; those verdicts continue to come
+ from recovery-owned evidence alone.
31. Keep VMware datastore classification neutral on the shared storage adapter contract. When `frontend-modern/src/features/storageBackups/resourceStorageMapping.ts`, `frontend-modern/src/features/storageBackups/resourceStoragePresentation.ts`, and `frontend-modern/src/features/storageBackups/storageAdapters.ts` evolve canonical storage-record mapping, VMware-backed datastores must continue to land on the shared storage route as inventory-only datastores with neutral protection fallback, not as backup repositories, backup targets, or recovery-protected resources.
That same shared storage adapter boundary also owns canonical platform
family vocabulary through the governed platform manifest.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index e4d0a20cfb..87fe98a507 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -554,6 +554,21 @@ The same split applies to VMware vSphere detail sections: unified-resource
VMware metadata owns the vCenter-specific row selection, but the section/row
shape and renderer must be the shared frontend-primitives detail-section
contract instead of a VMware-local row model or custom vSphere detail shell.
+Resource tags carry two distinct contracts that must not be collapsed into
+one another. The flat `Resource.Tags` string set is the searchable keyword
+union: it is what `resourceSearchMatch.ts`, the `?tags=` resources filter, and
+saved report-schedule tag filters read, and an adapter may put provenance
+keywords in it that repeat across every resource it emits — the vSphere
+adapter does exactly that. `VMware.Tags` (`VMwareTagData`, cloned through
+`cloneVMwareData`) is the narrower facet: operator-authored vCenter tags only,
+each carrying the vCenter category alongside the name because tag names are
+unique only inside their category, plus the flat `category:name` label so
+consumers do not each re-derive it. Any surface that renders a per-row tag
+list must read the facet, not the keyword union, and must treat a present-but-
+empty facet as "this resource has no operator tags" rather than falling back
+to the union. An adapter that needs provenance keywords in `Resource.Tags`
+owes the same facet split rather than asking presentation to pattern-match
+the union.
The split also applies to web-interface launch affordances. Unified-resource
tables own whether a row has a saved, inferred, or source-native web-interface
URL and how that URL is derived, but the visible launch affordance belongs on
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index e525565c07..37ba884032 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,33 +1,28 @@
{
"version": 1,
- "base_sha": "a959d50dcec61c90128b90516b209bfe2a21b0e7",
- "verified_at": "2026-08-06T16:57:33Z",
+ "base_sha": "9615b5f2b0e461809399a7ea101a4e75c082e202",
+ "verified_at": "2026-08-06T19:55:00Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/features/alerts/AlertHistoryItemActions.tsx",
- "frontend-modern/src/features/alerts/AlertHistoryMobileList.tsx",
- "frontend-modern/src/features/alerts/AlertHistoryTableAlertRow.tsx",
- "frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx",
- "frontend-modern/src/features/alerts/tabs/HistoryTab.tsx",
- "frontend-modern/src/features/alerts/useAlertHistoryState.ts",
- "frontend-modern/src/features/alerts/useAlertResourceIncidentsState.ts"
+ "frontend-modern/src/components/Workloads/useWorkloadsControlsState.ts",
+ "frontend-modern/src/features/vmware/VmwarePageSurface.tsx",
+ "frontend-modern/src/hooks/useWorkloads.ts",
+ "frontend-modern/src/types/resource.ts"
],
"content_sha256": {
- "frontend-modern/src/features/alerts/AlertHistoryItemActions.tsx": "4855ab08d2455ef16a5e41ad722646f7e2a53a1a93e3da13feb405bc1f98898f",
- "frontend-modern/src/features/alerts/AlertHistoryMobileList.tsx": "ad2d9c41b11e414f4c54177ba4fb6e4f3bb0ce8c0831e0eaf95a09904ce95e51",
- "frontend-modern/src/features/alerts/AlertHistoryTableAlertRow.tsx": "a400738ec0054729c25506edc23b4aff4b92fa6de80b4ea94c82f673ae786939",
- "frontend-modern/src/features/alerts/AlertResourceIncidentsPanel.tsx": "1f24d6d8523b3976906d01f47167b0389334df629473bfc98e3d26cbee76b905",
- "frontend-modern/src/features/alerts/tabs/HistoryTab.tsx": "bf14cbca7e0f79aeb503a8062c890474e39722503b15f13febf97cc889efd2a1",
- "frontend-modern/src/features/alerts/useAlertHistoryState.ts": "89f038b0d5335774dda21312b9e04a9b02ae37c661e640a58c9edbb1b45c9b2c",
- "frontend-modern/src/features/alerts/useAlertResourceIncidentsState.ts": "6a39b8d2cdec5f751992077bb2129ad3310d648a18a8e891209de12adc7d528b"
+ "frontend-modern/src/components/Workloads/useWorkloadsControlsState.ts": "ad066cb0146c00f5d4e4763a80152dfbcfcb85643f69ed416897309e0e0733ee",
+ "frontend-modern/src/features/vmware/VmwarePageSurface.tsx": "5525ce1b10c753bc56dd0fddb53a089fc2052fa5dcc271884a86619af1896c6e",
+ "frontend-modern/src/hooks/useWorkloads.ts": "b49585f16a65ef30d4a6dd27358674ca912f9313fd6c73919150b86ee6e404b7",
+ "frontend-modern/src/types/resource.ts": "1618f592fae6d13ef4f366f3b60f6049293f41493292024903884115ce423d5e"
},
"routes": [
- "/alerts/history"
+ "/vmware/overview",
+ "/proxmox?status=all"
],
"viewports": [
{
- "width": 1280,
- "height": 800
+ "width": 1680,
+ "height": 1000
},
{
"width": 390,
@@ -35,17 +30,26 @@
}
],
"states": [
- "Baseline reproduction of #1687 at 1280px: scrolled 3200px into the history and clicked a row's Resource button; the panel opened 2595px above the viewport top, so the only visible effect was the row list shifting down under the cursor",
- "After the fix at 1280px: the same click renders the panel in the row immediately below the button, showing 'Resource incidents, pve1, 2 incidents' with the event filter chips and two incident cards carrying full absolute timestamps",
- "Desktop row timestamps render in the browser locale (23:50 rather than the previously hardcoded en-US 11:50 PM) and every timestamp cell carries a full absolute date-time title, verified across all 98 rendered rows",
- "Mobile card list at 390px: tapping Resource on a card scrolled 2600px down opens the panel inside that same card at y=550, fully in view, with no horizontal document overflow",
- "A row that does not own the panel renders no incidents block, so only one panel is open at a time even when several alerts share one resource",
- "Resource button re-clicked on the same row closes the panel, matching the neighbouring Timeline toggle"
+ "vSphere VM table for a user with no saved preference at 1680px: header is Name, ID, CPU, Mem, Disk, Uptime, Tags, Net I/O, Disk I/O, so Tags is default-visible again on the scope that used to hide it",
+ "vSphere Tags cells now vary per row instead of repeating: warehouse-api-01 3 dots, warehouse-db-01 4, client-portal-01 2, finance-jump-01 3, ops-observability-01 2, edge-api-01 3, and 38 dots across the whole table",
+ "vSphere VMs that carry no vCenter tags render an empty Tags cell rather than falling back to the provenance keyword set: etl-batch-01 and ingress-proxy-02 show 0 dots",
+ "vSphere host group-header rows carry no tag dots, so host tags do not leak into the VM rows grouped beneath them",
+ "vSphere VM table for a user whose saved preference predates this change (seeded workloadsHiddenColumns:vmware-vms of aiContext/os/ip): the one-time migration adds only backup, the applied marker records aiContext/backup, and Tags stays visible",
+ "vSphere column picker reports 4 hidden and offers Tags checked, Backup unchecked, AI Context unchecked, OS unchecked, IP unchecked, Disk/Uptime/Net I/O/Disk I/O checked",
+ "vSphere at 390px: the phone stage renders Name, CPU, Mem across 25 rows with Tags dropped by the responsive stage as the wide-only contract requires, and no horizontal body overflow (table scrollWidth within container clientWidth for both tables)",
+ "Proxmox workload table unaffected at 1680px: Tags and Backup both still visible with genuine per-guest counts varying 3 to 7 dots per row, and the stored hidden list unchanged at aiContext/os/ip",
+ "Tag tooltip on a vSphere dot reads the real vCenter label Backup:Nightly rather than a provenance string",
+ "Filtered state after clicking that dot: search reads tags:Backup:Nightly and the table narrows from 18 VMs to the 3 that carry the tag (warehouse-api-01, warehouse-db-01, mariadb-replica-01) plus their host group headers"
],
"interactions": [
- "Scrolled the app-scroll-shell container to 3200px and clicked a row-level Resource button before and after the change, measuring the panel's viewport offset each time",
- "Read the rendered timestamp cells' text and title attributes directly from the DOM to confirm locale formatting and the absolute date-time tooltip",
- "Resized to 390px, reloaded, scrolled to 2600px and tapped a card's Resource button, then measured the panel position relative to its own card",
- "Checked document scrollWidth against the viewport at 390px for horizontal overflow"
+ "Built this worktree's frontend and backend and ran a mock-mode scratch instance on port 7712 so the page exercised this branch's adapter rather than the shared dev instance",
+ "Cleared every workloadsHiddenColumns scope key to reproduce a first-time user, then reloaded /vmware/overview",
+ "Seeded a pre-change workloadsHiddenColumns:vmware-vms preference of aiContext/os/ip and reloaded to confirm the migration now retires only backup and leaves tags alone",
+ "Opened the View preferences popover and the Columns multiselect on /vmware/overview to read the offered toggles and their checked state",
+ "Hovered a vSphere tag dot to read its tooltip, then clicked it to drive the tag filter and counted the surviving rows",
+ "Resized between 1680x1000 and 390x844 with a reload at each stage, and measured documentElement scrollWidth against clientWidth plus per-table scrollWidth against container clientWidth",
+ "Navigated to /proxmox?status=all at 1680px to confirm Proxmox tag counts and stored preferences are untouched",
+ "Queried /api/resources?source=vmware-vsphere&type=vm to confirm the flat tags array keeps the six provenance strings and appends real labels, while vmware.tags carries only the operator's labels and is empty for untagged VMs",
+ "Re-verified after rebasing onto main 9615b5f2b: rebuilt frontend and backend from the rebased tree, reloaded /vmware/overview at 1680x1000 and reproduced the same 38 tag dots with the same per-row counts, the same Backup:Nightly tooltip, and the same tags:Backup:Nightly filter narrowing to 3 VMs"
]
}
diff --git a/frontend-modern/src/components/Workloads/__tests__/useWorkloadsControlsState.test.ts b/frontend-modern/src/components/Workloads/__tests__/useWorkloadsControlsState.test.ts
index b405bec711..52839800c4 100644
--- a/frontend-modern/src/components/Workloads/__tests__/useWorkloadsControlsState.test.ts
+++ b/frontend-modern/src/components/Workloads/__tests__/useWorkloadsControlsState.test.ts
@@ -314,9 +314,11 @@ describe('useWorkloadsControlsState', () => {
});
});
- // vSphere tags are adapter provenance strings that repeat on every row, so
- // the scope hides the column; Proxmox tags are real per-guest labels.
- it('retires a stale Tags preference only on scopes that default-hide it', async () => {
+ // vSphere briefly default-hid Tags while the adapter shipped provenance
+ // strings in place of real vCenter tags. The adapter now reads vCenter's
+ // tagging API, so no scope default-hides the column and none retires a saved
+ // preference for it — a scoped hide must not outlive the reason for it.
+ it('keeps the Tags column on every scope now that vSphere carries real vCenter tags', async () => {
localStorage.setItem(
'workloadsHiddenColumns:vmware-vms',
JSON.stringify(['aiContext', 'os', 'ip']),
@@ -329,14 +331,13 @@ describe('useWorkloadsControlsState', () => {
showFilters,
setShowFilters,
columnVisibilityStorageScope: 'vmware-vms',
- additionalDefaultHiddenColumnIds: ['backup', 'tags'],
+ // The vSphere scope's live default-hidden set: Backup only.
+ additionalDefaultHiddenColumnIds: ['backup'],
});
- expect(state.columnVisibility.hiddenColumns()).toContain('tags');
- expect(state.visibleColumns().map((column) => column.id)).not.toContain('tags');
- // Still offered in the column picker for anyone who wants it back.
- expect(state.columnVisibility.availableToggles().map((column) => column.id)).toContain(
- 'tags',
- );
+ expect(state.columnVisibility.hiddenColumns()).not.toContain('tags');
+ expect(state.visibleColumns().map((column) => column.id)).toContain('tags');
+ // The Backup hide is unrelated and still stands.
+ expect(state.columnVisibility.hiddenColumns()).toContain('backup');
return dispose;
});
diff --git a/frontend-modern/src/components/Workloads/useWorkloadsControlsState.ts b/frontend-modern/src/components/Workloads/useWorkloadsControlsState.ts
index 028908905a..18f3854d44 100644
--- a/frontend-modern/src/components/Workloads/useWorkloadsControlsState.ts
+++ b/frontend-modern/src/components/Workloads/useWorkloadsControlsState.ts
@@ -242,12 +242,14 @@ export function useWorkloadsControlsState(options: WorkloadsControlsStateOptions
relevantColumns,
{},
// One-time hides for users who already have a saved column preference for
- // this scope. `backup` reads exclusively from `resource.proxmox.lastBackup`
- // and `tags` on vSphere carries only adapter provenance strings, so on the
- // scopes that opt into hiding them those columns say the same thing on
- // every row forever. The migration only fires where the id is already in
- // that scope's default-hidden set, so Proxmox keeps both columns visible.
- ['aiContext', 'backup', 'tags'],
+ // this scope. `backup` reads exclusively from `resource.proxmox.lastBackup`,
+ // so on the scopes that opt into hiding it the column says the same thing
+ // on every row forever. The migration only fires where the id is already in
+ // that scope's default-hidden set, so Proxmox keeps the column visible.
+ // `tags` was on this list while vSphere shipped adapter provenance strings
+ // in place of real tags; the adapter now reads vCenter's tagging API, so no
+ // scope default-hides it and retiring the preference would be wrong.
+ ['aiContext', 'backup'],
);
const visibleColumns = columnVisibility.visibleColumns;
diff --git a/frontend-modern/src/features/vmware/VmwarePageSurface.tsx b/frontend-modern/src/features/vmware/VmwarePageSurface.tsx
index d668995c34..446a466701 100644
--- a/frontend-modern/src/features/vmware/VmwarePageSurface.tsx
+++ b/frontend-modern/src/features/vmware/VmwarePageSurface.tsx
@@ -62,17 +62,14 @@ const VMWARE_WORKLOAD_COLUMN_VISIBILITY_SCOPE = 'vmware-vms';
// none of which surface through vCenter's inventory API. Hide the
// column by default rather than render a permanently blank cell.
//
-// Tags is hidden for a different reason, and this one is a stopgap rather
-// than the canonical fix. vCenter does have a real tag/category system, but
-// the vSphere adapter never reads it: `internal/vmware/provider.go` fills
-// `Resource.Tags` with fixed provenance strings instead (`vmware`, `vsphere`,
-// `vm`, `source:vcenter`, `connection:<name>`, `power:<state>`). Five of those
-// six are identical across an entire estate and the sixth restates the power
-// state the status filter already owns, so the column renders the same dots on
-// every row and filtering on any of them selects everything. The tags stay in
-// the payload because search and facet counts consume them; only the column is
-// suppressed. Drop this hide once the adapter reads vCenter's tagging API.
-const VMWARE_WORKLOAD_DEFAULT_HIDDEN_COLUMN_IDS: readonly string[] = ['backup', 'tags'];
+// `tags` used to be hidden here too, as a stopgap: the adapter filled
+// `Resource.Tags` with fixed provenance strings and never read vCenter's own
+// tag/category system, so the column repeated the same dots on every row. The
+// adapter now ingests real vCenter tags through the CIS tagging service
+// (`internal/vmware/client_tags.go`), `useWorkloads` reads the operator's tags
+// from the `vmware.tags` facet rather than the mixed keyword set, and the
+// column carries per-row meaning, so the hide is gone.
+const VMWARE_WORKLOAD_DEFAULT_HIDDEN_COLUMN_IDS: readonly string[] = ['backup'];
const VMWARE_WORKLOAD_STATUS_OPTIONS: readonly WorkloadsStatusOption[] = [
{ value: 'all', label: 'All' },
{ value: 'running', label: 'Powered on' },
diff --git a/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts b/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts
index db4e8e34c5..926aa69493 100644
--- a/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts
+++ b/frontend-modern/src/hooks/__tests__/useWorkloads.test.ts
@@ -585,6 +585,79 @@ describe('useWorkloads', () => {
dispose();
});
+ it('renders vSphere row tags from the vCenter facet, never the provenance keyword set', async () => {
+ // `Resource.Tags` on vSphere is a mixed keyword set: adapter provenance
+ // strings (kept so resource search and the `?tags=` filter keep matching)
+ // plus the operator's real vCenter tags. A per-row Tags cell must show
+ // only the vCenter tags, and a vSphere VM nobody tagged must show nothing
+ // rather than falling back to six identical provenance dots.
+ apiFetchJSONMock.mockResolvedValueOnce({
+ data: [
+ {
+ ...sampleResource,
+ id: 'vmware-vm-tagged',
+ name: 'tagged-app-01',
+ sources: ['vmware'],
+ proxmox: undefined,
+ tags: [
+ 'vmware',
+ 'vsphere',
+ 'vm',
+ 'source:vcenter',
+ 'Environment:Production',
+ 'Owner:Data',
+ ],
+ vmware: {
+ managedObjectId: 'vm-902',
+ powerState: 'poweredOn',
+ tags: [
+ { name: 'Production', category: 'Environment', label: 'Environment:Production' },
+ { name: 'Data', category: 'Owner', label: 'Owner:Data' },
+ ],
+ },
+ },
+ {
+ ...sampleResource,
+ id: 'vmware-vm-untagged',
+ name: 'untagged-app-01',
+ sources: ['vmware'],
+ proxmox: undefined,
+ tags: ['vmware', 'vsphere', 'vm', 'source:vcenter'],
+ vmware: {
+ managedObjectId: 'vm-903',
+ powerState: 'poweredOn',
+ },
+ },
+ {
+ ...sampleResource,
+ id: 'proxmox-vm-tagged',
+ name: 'pve-app-01',
+ tags: ['production', 'web'],
+ },
+ ],
+ meta: { totalPages: 1 },
+ });
+
+ let dispose = () => {};
+ let result: ReturnType<UseWorkloadsModule['useWorkloads']> | undefined;
+ createRoot((d) => {
+ dispose = d;
+ const [enabled] = createSignal(true);
+ result = useWorkloads(enabled);
+ });
+
+ await flushAsync();
+ await waitForWorkloadCount(() => result!.workloads().length, 3);
+
+ const byName = (name: string) => result!.workloads().find((workload) => workload.name === name);
+ expect(byName('tagged-app-01')?.tags).toEqual(['Environment:Production', 'Owner:Data']);
+ expect(byName('untagged-app-01')?.tags).toEqual([]);
+ // Platforms whose flat tags are already real labels are untouched.
+ expect(byName('pve-app-01')?.tags).toEqual(['production', 'web']);
+
+ dispose();
+ });
+
it('preserves canonical discovery targets for workloads instead of inferring them from platform type', async () => {
apiFetchJSONMock.mockResolvedValueOnce({
data: [
diff --git a/frontend-modern/src/hooks/useWorkloads.ts b/frontend-modern/src/hooks/useWorkloads.ts
index e17de71294..083f2c9fdc 100644
--- a/frontend-modern/src/hooks/useWorkloads.ts
+++ b/frontend-modern/src/hooks/useWorkloads.ts
@@ -24,6 +24,7 @@ import type {
ResourceAvailabilityMeta,
ResourceDiscoveryReadiness,
ResourceDiscoveryTarget,
+ ResourceVMwareTag,
} from '@/types/resource';
const WORKLOADS_URL = '/api/resources?type=vm,system-container,app-container,pod';
@@ -153,6 +154,7 @@ type APIResource = {
managedObjectId?: string;
powerState?: string;
guestOsFamily?: string;
+ tags?: ResourceVMwareTag[];
};
discoveryTarget?: {
resourceType?: string;
@@ -353,6 +355,24 @@ const resolveWorkloadDiscoveryTarget = (
}
};
+/**
+ * vCenter tag labels for one resource, or undefined when the resource is not
+ * a vSphere workload at all.
+ *
+ * A vSphere workload the operator never tagged returns an empty array on
+ * purpose. Falling through to the flat `resource.tags` there would put the
+ * adapter's provenance strings back in the cell, which is the whole reason the
+ * column was worth nothing before.
+ */
+const vmwareRowTags = (resource: APIResource): string[] | undefined => {
+ if (!resource.vmware) return undefined;
+ const tags = resource.vmware.tags;
+ if (!Array.isArray(tags)) return [];
+ return tags
+ .map((tag) => (tag?.label || tag?.name || '').trim())
+ .filter((label) => label.length > 0);
+};
+
const mapResourceToWorkload = (resource: APIResource): WorkloadGuest | null => {
const workloadType = resolveWorkloadType(resource.type);
if (!workloadType) return null;
@@ -524,7 +544,13 @@ const mapResourceToWorkload = (resource: APIResource): WorkloadGuest | null => {
// Go zero time "0001-01-01T00:00:00Z" parses to a large negative number
return parsed > 0 ? parsed : 0;
})(),
- tags: resource.tags ?? [],
+ // vSphere's flat `resource.tags` is a mixed keyword set: the adapter keeps
+ // provenance strings there (`vmware`, `vsphere`, `source:vcenter`, ...) so
+ // resource search and the `?tags=` filter keep matching, and appends the
+ // operator's real vCenter tags. Only the latter belong in a per-row Tags
+ // cell, so the vSphere facet wins for every vSphere workload — including
+ // the untagged ones, which must render empty rather than fall back.
+ tags: vmwareRowTags(resource) ?? resource.tags ?? [],
lock: '',
lastSeen: toIsoString(resource.lastSeen),
isOci: workloadType === 'system-container' ? (resource.proxmox?.isOci ?? false) : false,
diff --git a/frontend-modern/src/types/__tests__/resource.test.ts b/frontend-modern/src/types/__tests__/resource.test.ts
index 5246a23e95..26dfd6b339 100644
--- a/frontend-modern/src/types/__tests__/resource.test.ts
+++ b/frontend-modern/src/types/__tests__/resource.test.ts
@@ -524,6 +524,42 @@ describe('Resource Helper Functions', () => {
expect(vmware.hardware?.memoryHotAddLimitMib).toBe(16384);
expect(vmware.snapshotTree?.[0]?.children?.[0]?.current).toBe(true);
});
+
+ // Operator-authored vCenter tags ride their own facet rather than the flat
+ // `Resource.tags` keyword set, which also carries adapter provenance
+ // strings identical on every vSphere resource. Per-row tag presentation
+ // reads this facet, so its shape is part of the consumer contract.
+ it('carries operator-authored vCenter tags with their category', () => {
+ const vmware: ResourceVMwareMeta = {
+ entityType: 'vm',
+ managedObjectId: 'vm-201',
+ tags: [
+ {
+ tagId: 'urn:vmomi:InventoryServiceTag:env-prod:GLOBAL',
+ name: 'Production',
+ categoryId: 'urn:vmomi:InventoryServiceCategory:environment:GLOBAL',
+ category: 'Environment',
+ description: 'Customer-facing workloads',
+ label: 'Environment:Production',
+ },
+ { name: 'Nightly', category: 'Backup', label: 'Backup:Nightly' },
+ ],
+ };
+
+ expect(vmware.tags).toHaveLength(2);
+ expect(vmware.tags?.[0]?.category).toBe('Environment');
+ expect(vmware.tags?.[0]?.name).toBe('Production');
+ // vCenter tag names are unique only inside their category, so the flat
+ // label a consumer renders has to carry both.
+ expect(vmware.tags?.[0]?.label).toBe('Environment:Production');
+ expect(vmware.tags?.[1]?.label).toBe('Backup:Nightly');
+ expect(vmware.tags?.[1]?.tagId).toBeUndefined();
+ });
+
+ it('treats vCenter tags as optional so untagged estates stay valid', () => {
+ const vmware: ResourceVMwareMeta = { entityType: 'vm', managedObjectId: 'vm-202' };
+ expect(vmware.tags).toBeUndefined();
+ });
});
describe('getPreferredResourceDisplayName', () => {
diff --git a/frontend-modern/src/types/resource.ts b/frontend-modern/src/types/resource.ts
index c749a470e5..cf16c5bf60 100644
--- a/frontend-modern/src/types/resource.ts
+++ b/frontend-modern/src/types/resource.ts
@@ -1443,6 +1443,25 @@ export interface ResourceVMwareMeta {
virtualDisks?: ResourceVMwareVirtualDisk[];
tools?: ResourceVMwareTools;
hardware?: ResourceVMwareHardware;
+ tags?: ResourceVMwareTag[];
+}
+
+/**
+ * One operator-authored vCenter tag.
+ *
+ * The flat `Resource.tags` keyword set carries these labels too, but it also
+ * carries adapter provenance strings that are identical on every vSphere
+ * resource. Per-row tag presentation reads this facet so it renders only what
+ * the operator actually tagged in vCenter.
+ */
+export interface ResourceVMwareTag {
+ tagId?: string;
+ name: string;
+ categoryId?: string;
+ category?: string;
+ description?: string;
+ /** Flat `category:name` form used by tag search and tag filters. */
+ label?: string;
}
export interface ResourceAvailabilityMeta {
diff --git a/internal/unifiedresources/clone.go b/internal/unifiedresources/clone.go
index 4da5e55c3e..620b832f10 100644
--- a/internal/unifiedresources/clone.go
+++ b/internal/unifiedresources/clone.go
@@ -443,9 +443,19 @@ func cloneVMwareData(in *VMwareData) *VMwareData {
out.VirtualDisks = cloneVMwareVirtualDiskDataSlice(in.VirtualDisks)
out.Tools = cloneVMwareToolsData(in.Tools)
out.Hardware = cloneVMwareVMHardwareData(in.Hardware)
+ out.Tags = cloneVMwareTagDataSlice(in.Tags)
return &out
}
+func cloneVMwareTagDataSlice(in []VMwareTagData) []VMwareTagData {
+ if in == nil {
+ return nil
+ }
+ out := make([]VMwareTagData, len(in))
+ copy(out, in)
+ return out
+}
+
func cloneVMwareSnapshotDataSlice(in []VMwareSnapshotData) []VMwareSnapshotData {
if in == nil {
return nil
diff --git a/internal/unifiedresources/clone_test.go b/internal/unifiedresources/clone_test.go
index 2f5d35a03e..d1df6232ea 100644
--- a/internal/unifiedresources/clone_test.go
+++ b/internal/unifiedresources/clone_test.go
@@ -303,10 +303,19 @@ func TestCloneResource_MutateVMwareDetailSlices(t *testing.T) {
CPUCoresPerSocket: &coresPerSocket,
MemoryHotAddLimitMiB: &memoryHotAddLimitMiB,
},
+ Tags: []VMwareTagData{{
+ TagID: "urn:vmomi:InventoryServiceTag:env-prod:GLOBAL",
+ Name: "Production",
+ CategoryID: "urn:vmomi:InventoryServiceCategory:environment:GLOBAL",
+ Category: "Environment",
+ Label: "Environment:Production",
+ }},
},
}
cloned := cloneResource(original)
+ cloned.VMware.Tags[0].Name = "mutated"
+ cloned.VMware.Tags[0].Label = "mutated"
cloned.VMware.SnapshotTree[0].Name = "mutated"
cloned.VMware.SnapshotTree[0].Children[0].Name = "mutated-child"
*cloned.VMware.SnapshotTree[0].CreatedAt = createdAt.Add(time.Hour)
@@ -327,6 +336,12 @@ func TestCloneResource_MutateVMwareDetailSlices(t *testing.T) {
cloned.VMware.Hardware.BootDevices[0].Disks[0] = "mutated"
*cloned.VMware.Hardware.MemoryHotAddLimitMiB = 1
+ // vCenter tags are operator-authored labels the presentation layer renders
+ // per row, so a cloned snapshot must never write back onto the registry's
+ // copy of them.
+ if original.VMware.Tags[0].Name != "Production" || original.VMware.Tags[0].Label != "Environment:Production" {
+ t.Fatalf("mutating cloned VMware tags should not affect original: %+v", original.VMware.Tags)
+ }
if original.VMware.SnapshotTree[0].Name != "pre-upgrade" {
t.Fatalf("mutating cloned VMware snapshot should not affect original: %+v", original.VMware.SnapshotTree)
}
diff --git a/internal/unifiedresources/types.go b/internal/unifiedresources/types.go
index 89085e0863..6a93d43414 100644
--- a/internal/unifiedresources/types.go
+++ b/internal/unifiedresources/types.go
@@ -1436,6 +1436,24 @@ type VMwareData struct {
VirtualDisks []VMwareVirtualDiskData `json:"virtualDisks,omitempty"`
Tools *VMwareToolsData `json:"tools,omitempty"`
Hardware *VMwareVMHardwareData `json:"hardware,omitempty"`
+ Tags []VMwareTagData `json:"tags,omitempty"`
+}
+
+// VMwareTagData is one operator-authored vCenter tag attached to a host or VM.
+//
+// The flat `Resource.Tags` keyword set carries these too, but it also carries
+// adapter provenance strings that are identical for every vSphere resource.
+// Presentation surfaces that show a per-row tag list read this facet so they
+// render what the operator actually tagged in vCenter and nothing else.
+type VMwareTagData struct {
+ TagID string `json:"tagId,omitempty"`
+ Name string `json:"name"`
+ CategoryID string `json:"categoryId,omitempty"`
+ Category string `json:"category,omitempty"`
+ Description string `json:"description,omitempty"`
+ // Label is the flat `category:name` form used by tag search and tag
+ // filters, so consumers do not each re-derive it.
+ Label string `json:"label,omitempty"`
}
// VMwareSnapshotData contains one node in the vSphere VM snapshot tree. It is
diff --git a/internal/vmware/client.go b/internal/vmware/client.go
index 8e5024b226..b99d9054e2 100644
--- a/internal/vmware/client.go
+++ b/internal/vmware/client.go
@@ -1,6 +1,7 @@
package vmware
import (
+ "bytes"
"context"
"crypto/tls"
"crypto/x509"
@@ -103,6 +104,10 @@ type Client struct {
httpClient *http.Client
username string
password string
+ // tagCatalog memoizes CIS tag and category names across refreshes. The
+ // poller keeps one client per vCenter connection, so the cache spans the
+ // whole poll loop rather than one collection.
+ tagCatalog vmwareTagCatalog
}
type viJSONServiceContentRefs struct {
@@ -213,10 +218,15 @@ func (c *Client) CollectInventory(ctx context.Context) (*InventorySnapshot, erro
if err != nil {
return nil, err
}
+ tagIssues, err := c.enrichInventoryTags(ctx, automationSessionID, inventory)
+ if err != nil {
+ return nil, err
+ }
inventory.VIRelease = strings.TrimSpace(release)
inventory.CollectedAt = time.Now().UTC()
inventory.EnrichmentIssues = append(inventory.EnrichmentIssues, signalIssues...)
inventory.EnrichmentIssues = append(inventory.EnrichmentIssues, topologyIssues...)
+ inventory.EnrichmentIssues = append(inventory.EnrichmentIssues, tagIssues...)
return inventory, nil
}
@@ -409,6 +419,47 @@ func (c *Client) getSessionScopedJSON(
return nil
}
+// postSessionScopedJSON posts a JSON body to a session-authenticated vCenter
+// endpoint and decodes the response into target. The vSphere Automation API
+// models several reads as POST actions — CIS tag association lookups are the
+// current case — so they cannot go through getSessionScopedJSON.
+func (c *Client) postSessionScopedJSON(
+ ctx context.Context,
+ sessionID string,
+ path string,
+ label string,
+ payload any,
+ target any,
+) error {
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return fmt.Errorf("marshal %s request: %w", label, err)
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.baseURL.String()+path, bytes.NewReader(body))
+ if err != nil {
+ return fmt.Errorf("build %s request: %w", label, err)
+ }
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("vmware-api-session-id", sessionID)
+ resp, err := c.httpClient.Do(req)
+ if err != nil {
+ return classifyTransportError(label, err)
+ }
+ defer resp.Body.Close()
+ responseBody, readErr := io.ReadAll(io.LimitReader(resp.Body, inventoryResponseLimitByte))
+ if readErr != nil {
+ return fmt.Errorf("read %s response: %w", label, readErr)
+ }
+ if resp.StatusCode != http.StatusOK {
+ return classifyReadStatusCode(label, resp.StatusCode)
+ }
+ if err := json.Unmarshal(responseBody, target); err != nil {
+ return &ConnectionError{Category: "endpoint", Message: fmt.Sprintf("VMware %s response was not valid JSON", label)}
+ }
+ return nil
+}
+
func (c *Client) getAutomationJSON(
ctx context.Context,
sessionID string,
diff --git a/internal/vmware/client_tags.go b/internal/vmware/client_tags.go
new file mode 100644
index 0000000000..cf4cc7927b
--- /dev/null
+++ b/internal/vmware/client_tags.go
@@ -0,0 +1,420 @@
+package vmware
+
+import (
+ "context"
+ "net/url"
+ "sort"
+ "strings"
+ "sync"
+ "time"
+)
+
+const (
+ // vmwareTagObjectBatchSize caps how many inventory objects ride in one
+ // list-attached-tags-on-objects request. vCenter accepts large object
+ // lists, but a bounded batch keeps a big estate from building one
+ // unbounded request body and one unbounded response.
+ vmwareTagObjectBatchSize = 400
+
+ // vmwareTagCatalogTTL bounds how long resolved tag and category names are
+ // reused. Associations are re-read every refresh because they follow the
+ // estate; names change rarely, so a renamed tag converges within one TTL
+ // instead of needing a Pulse restart.
+ vmwareTagCatalogTTL = 10 * time.Minute
+
+ // vmwareTagMetadataConcurrency bounds the cold-start metadata fan-out. The
+ // catalog makes this a once-per-TTL cost, but an estate with many distinct
+ // tags should not serialize that first refresh.
+ vmwareTagMetadataConcurrency = 8
+)
+
+// vCenter managed object type names used by the CIS tagging association API.
+const (
+ vmwareTagObjectTypeHost = "HostSystem"
+ vmwareTagObjectTypeVM = "VirtualMachine"
+)
+
+// cisObjectID identifies one inventory object to the CIS tagging service.
+type cisObjectID struct {
+ ID string `json:"id"`
+ Type string `json:"type"`
+}
+
+// cisTagAssociation is one entry of the batched association response.
+type cisTagAssociation struct {
+ ObjectID cisObjectID `json:"object_id"`
+ TagIDs []string `json:"tag_ids"`
+}
+
+type cisTagInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+ Description string `json:"description"`
+ CategoryID string `json:"category_id"`
+}
+
+type cisCategoryInfo struct {
+ ID string `json:"id"`
+ Name string `json:"name"`
+}
+
+// vmwareTagCatalog caches resolved vCenter tag and category names for one
+// client. Tag identifiers are opaque URNs, so every tagged object would
+// otherwise cost two extra GETs per refresh just to learn names that the whole
+// estate shares. The catalog reduces the steady state to the association reads
+// alone.
+type vmwareTagCatalog struct {
+ mu sync.Mutex
+ loadedAt time.Time
+ tags map[string]InventoryTag
+ categories map[string]string
+}
+
+// beginRefresh drops the cached catalog once its TTL lapses so renames and
+// deletions in vCenter converge on the next refresh.
+func (t *vmwareTagCatalog) beginRefresh(now time.Time) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.tags == nil || t.categories == nil {
+ t.tags = make(map[string]InventoryTag)
+ t.categories = make(map[string]string)
+ t.loadedAt = now
+ return
+ }
+ if now.Sub(t.loadedAt) < vmwareTagCatalogTTL {
+ return
+ }
+ t.tags = make(map[string]InventoryTag)
+ t.categories = make(map[string]string)
+ t.loadedAt = now
+}
+
+func (t *vmwareTagCatalog) tag(id string) (InventoryTag, bool) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ tag, ok := t.tags[id]
+ return tag, ok
+}
+
+func (t *vmwareTagCatalog) putTag(id string, tag InventoryTag) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.tags == nil {
+ t.tags = make(map[string]InventoryTag)
+ }
+ t.tags[id] = tag
+}
+
+func (t *vmwareTagCatalog) category(id string) (string, bool) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ name, ok := t.categories[id]
+ return name, ok
+}
+
+func (t *vmwareTagCatalog) putCategory(id string, name string) {
+ t.mu.Lock()
+ defer t.mu.Unlock()
+ if t.categories == nil {
+ t.categories = make(map[string]string)
+ }
+ t.categories[id] = name
+}
+
+// enrichInventoryTags attaches operator-authored vCenter tags to the hosts and
+// VMs already present in snapshot.
+//
+// Tags live in the CIS tagging service (`/api/cis/tagging/...`), not in the
+// `/api/vcenter/...` inventory endpoints the rest of this client reads. Both
+// are the vSphere Automation API and share the `/api/session` token, so this
+// reuses the caller's Automation session rather than opening a second one.
+//
+// The read is optional: an account without the tagging read privilege, or a
+// vCenter with the service unavailable, degrades into an enrichment issue and
+// leaves the inventory untagged rather than failing the refresh.
+func (c *Client) enrichInventoryTags(
+ ctx context.Context,
+ automationSessionID string,
+ snapshot *InventorySnapshot,
+) ([]InventoryEnrichmentIssue, error) {
+ if snapshot == nil {
+ return nil, nil
+ }
+
+ hostIndexByID := make(map[string]int, len(snapshot.Hosts))
+ vmIndexByID := make(map[string]int, len(snapshot.VMs))
+ refs := make([]cisObjectID, 0, len(snapshot.Hosts)+len(snapshot.VMs))
+ for i := range snapshot.Hosts {
+ id := strings.TrimSpace(snapshot.Hosts[i].Host)
+ if id == "" {
+ continue
+ }
+ hostIndexByID[id] = i
+ refs = append(refs, cisObjectID{ID: id, Type: vmwareTagObjectTypeHost})
+ }
+ for i := range snapshot.VMs {
+ id := strings.TrimSpace(snapshot.VMs[i].VM)
+ if id == "" {
+ continue
+ }
+ vmIndexByID[id] = i
+ refs = append(refs, cisObjectID{ID: id, Type: vmwareTagObjectTypeVM})
+ }
+ if len(refs) == 0 {
+ return nil, nil
+ }
+
+ associations, err := c.listAttachedTagsOnObjects(ctx, automationSessionID, refs)
+ if issue, ok := classifyInventoryEnrichmentIssue("tags", "tag", "", err); ok {
+ return []InventoryEnrichmentIssue{*issue}, nil
+ } else if err != nil {
+ return nil, err
+ }
+
+ resolved, issues, err := c.resolveTagCatalog(ctx, automationSessionID, distinctTagIDs(associations))
+ if err != nil {
+ return nil, err
+ }
+
+ for _, association := range associations {
+ objectID := strings.TrimSpace(association.ObjectID.ID)
+ if objectID == "" {
+ continue
+ }
+ tags := make([]InventoryTag, 0, len(association.TagIDs))
+ for _, tagID := range association.TagIDs {
+ if tag, ok := resolved[strings.TrimSpace(tagID)]; ok {
+ tags = append(tags, tag)
+ }
+ }
+ if len(tags) == 0 {
+ continue
+ }
+ sortInventoryTags(tags)
+ switch {
+ case strings.EqualFold(strings.TrimSpace(association.ObjectID.Type), vmwareTagObjectTypeHost):
+ if index, ok := hostIndexByID[objectID]; ok {
+ snapshot.Hosts[index].Tags = tags
+ }
+ case strings.EqualFold(strings.TrimSpace(association.ObjectID.Type), vmwareTagObjectTypeVM):
+ if index, ok := vmIndexByID[objectID]; ok {
+ snapshot.VMs[index].Tags = tags
+ }
+ }
+ }
+
+ sort.Slice(issues, func(i, j int) bool {
+ return inventoryEnrichmentIssueSortKey(issues[i]) < inventoryEnrichmentIssueSortKey(issues[j])
+ })
+ return issues, nil
+}
+
+// listAttachedTagsOnObjects reads tag associations for every supplied object in
+// bounded batches. This is the only per-refresh tagging cost for an estate
+// whose tag names are already cached.
+func (c *Client) listAttachedTagsOnObjects(
+ ctx context.Context,
+ sessionID string,
+ refs []cisObjectID,
+) ([]cisTagAssociation, error) {
+ out := make([]cisTagAssociation, 0, len(refs))
+ for start := 0; start < len(refs); start += vmwareTagObjectBatchSize {
+ end := start + vmwareTagObjectBatchSize
+ if end > len(refs) {
+ end = len(refs)
+ }
+ payload := struct {
+ ObjectIDs []cisObjectID `json:"object_ids"`
+ }{ObjectIDs: refs[start:end]}
+ var batch []cisTagAssociation
+ if err := c.postSessionScopedJSON(
+ ctx,
+ sessionID,
+ "/api/cis/tagging/tag-association?action=list-attached-tags-on-objects",
+ "vcenter tag associations",
+ payload,
+ &batch,
+ ); err != nil {
+ return nil, err
+ }
+ out = append(out, batch...)
+ }
+ return out, nil
+}
+
+// resolveTagCatalog turns the opaque tag URNs carried by associations into
+// named tags, reading only the identifiers the catalog has not already cached.
+// A tag whose metadata cannot be read is reported and skipped: one unreadable
+// tag must not blank out the tags Pulse can resolve.
+func (c *Client) resolveTagCatalog(
+ ctx context.Context,
+ sessionID string,
+ tagIDs []string,
+) (map[string]InventoryTag, []InventoryEnrichmentIssue, error) {
+ resolved := make(map[string]InventoryTag, len(tagIDs))
+ if len(tagIDs) == 0 {
+ return resolved, nil, nil
+ }
+
+ c.tagCatalog.beginRefresh(time.Now())
+
+ // Cached hits are drained first so every write to `resolved` from this
+ // goroutine happens before any worker starts writing to it.
+ missing := make([]string, 0, len(tagIDs))
+ for _, tagID := range tagIDs {
+ if cached, ok := c.tagCatalog.tag(tagID); ok {
+ resolved[tagID] = cached
+ continue
+ }
+ missing = append(missing, tagID)
+ }
+ if len(missing) == 0 {
+ return resolved, nil, nil
+ }
+
+ var (
+ mu sync.Mutex
+ issues []InventoryEnrichmentIssue
+ firstErr error
+ wg sync.WaitGroup
+ )
+ sem := make(chan struct{}, vmwareTagMetadataConcurrency)
+
+ for _, tagID := range missing {
+ wg.Add(1)
+ go func(tagID string) {
+ defer wg.Done()
+ sem <- struct{}{}
+ defer func() { <-sem }()
+
+ tag, err := c.fetchTag(ctx, sessionID, tagID)
+ mu.Lock()
+ defer mu.Unlock()
+ if err != nil {
+ if issue, ok := classifyInventoryEnrichmentIssue("tags", "tag", tagID, err); ok {
+ issues = append(issues, *issue)
+ return
+ }
+ if firstErr == nil {
+ firstErr = err
+ }
+ return
+ }
+ // A tag whose category could not be resolved is usable but
+ // incomplete, so it is not cached: caching it would pin the
+ // degraded label for the rest of the TTL instead of retrying on
+ // the next refresh.
+ if tag.CategoryID == "" || tag.Category != "" {
+ c.tagCatalog.putTag(tagID, tag)
+ }
+ resolved[tagID] = tag
+ }(tagID)
+ }
+ wg.Wait()
+
+ if firstErr != nil {
+ return nil, nil, firstErr
+ }
+ return resolved, issues, nil
+}
+
+// fetchTag reads one tag and resolves its category name, reusing the cached
+// category when another tag in the same category already resolved it.
+func (c *Client) fetchTag(ctx context.Context, sessionID string, tagID string) (InventoryTag, error) {
+ var info cisTagInfo
+ if err := c.getSessionScopedJSON(
+ ctx,
+ sessionID,
+ "/api/cis/tagging/tag/"+url.PathEscape(tagID),
+ "vcenter tag",
+ &info,
+ ); err != nil {
+ return InventoryTag{}, err
+ }
+
+ tag := InventoryTag{
+ TagID: strings.TrimSpace(firstNonEmptyTrimmed(info.ID, tagID)),
+ Name: strings.TrimSpace(info.Name),
+ CategoryID: strings.TrimSpace(info.CategoryID),
+ Description: strings.TrimSpace(info.Description),
+ }
+ if tag.Name == "" {
+ return InventoryTag{}, &ConnectionError{
+ Category: "endpoint",
+ Message: "VMware vcenter tag response did not include a tag name",
+ }
+ }
+ if tag.CategoryID == "" {
+ return tag, nil
+ }
+
+ if name, ok := c.tagCatalog.category(tag.CategoryID); ok {
+ tag.Category = name
+ return tag, nil
+ }
+ var category cisCategoryInfo
+ if err := c.getSessionScopedJSON(
+ ctx,
+ sessionID,
+ "/api/cis/tagging/category/"+url.PathEscape(tag.CategoryID),
+ "vcenter tag category",
+ &category,
+ ); err != nil {
+ // A readable tag whose category is not readable is still a usable
+ // label; report nothing and fall back to the bare tag name.
+ return tag, nil
+ }
+ tag.Category = strings.TrimSpace(category.Name)
+ if tag.Category != "" {
+ c.tagCatalog.putCategory(tag.CategoryID, tag.Category)
+ }
+ return tag, nil
+}
+
+func distinctTagIDs(associations []cisTagAssociation) []string {
+ seen := make(map[string]struct{})
+ out := make([]string, 0, len(associations))
+ for _, association := range associations {
+ for _, tagID := range association.TagIDs {
+ tagID = strings.TrimSpace(tagID)
+ if tagID == "" {
+ continue
+ }
+ if _, ok := seen[tagID]; ok {
+ continue
+ }
+ seen[tagID] = struct{}{}
+ out = append(out, tagID)
+ }
+ }
+ sort.Strings(out)
+ return out
+}
+
+func sortInventoryTags(tags []InventoryTag) {
+ sort.Slice(tags, func(i, j int) bool {
+ return inventoryTagSortKey(tags[i]) < inventoryTagSortKey(tags[j])
+ })
+}
+
+func inventoryTagSortKey(tag InventoryTag) string {
+ return strings.ToLower(strings.TrimSpace(tag.Category)) + "\x00" +
+ strings.ToLower(strings.TrimSpace(tag.Name)) + "\x00" +
+ strings.TrimSpace(tag.TagID)
+}
+
+// InventoryTagLabel renders one vCenter tag as the flat label Pulse uses in
+// tag search, tag filters, and the workload Tags column. vCenter tag names are
+// only unique inside their category, so the category is part of the label
+// whenever vCenter reports one.
+func InventoryTagLabel(tag InventoryTag) string {
+ name := strings.TrimSpace(tag.Name)
+ if name == "" {
+ return ""
+ }
+ category := strings.TrimSpace(tag.Category)
+ if category == "" {
+ return name
+ }
+ return category + ":" + name
+}
diff --git a/internal/vmware/client_tags_test.go b/internal/vmware/client_tags_test.go
new file mode 100644
index 0000000000..b79c750bca
--- /dev/null
+++ b/internal/vmware/client_tags_test.go
@@ -0,0 +1,242 @@
+package vmware
+
+import (
+ "context"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
+)
+
+func newTagTestClient(t *testing.T, serverURL string) *Client {
+ t.Helper()
+ client, err := NewClient(ClientConfig{
+ Host: serverURL,
+ Username: "admin",
+ Password: "secret",
+ InsecureSkipVerify: true,
+ Timeout: 5 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("NewClient: %v", err)
+ }
+ return client
+}
+
+func TestClientCollectInventoryAttachesVCenterTags(t *testing.T) {
+ server := newVMwareTestServer(t, vmwareTestServerConfig{})
+ defer server.Close()
+
+ client := newTagTestClient(t, server.URL)
+ snapshot, err := client.CollectInventory(context.Background())
+ if err != nil {
+ t.Fatalf("CollectInventory: %v", err)
+ }
+ // The one tag whose metadata cannot be read is reported and skipped; it
+ // must not blank out the tags that did resolve.
+ var tagIssues []InventoryEnrichmentIssue
+ for _, issue := range snapshot.EnrichmentIssues {
+ if issue.Stage == "tags" {
+ tagIssues = append(tagIssues, issue)
+ }
+ }
+ if len(tagIssues) != 1 || tagIssues[0].EntityID != "urn:tag:orphan" || tagIssues[0].Category != "not_found" {
+ t.Fatalf("expected one not_found issue for the unresolvable tag, got %+v", tagIssues)
+ }
+
+ host := snapshot.Hosts[0]
+ if len(host.Tags) != 1 {
+ t.Fatalf("expected one host tag, got %+v", host.Tags)
+ }
+ if host.Tags[0].Name != "R1" || host.Tags[0].Category != "Rack" {
+ t.Fatalf("unexpected host tag: %+v", host.Tags[0])
+ }
+
+ vm := snapshot.VMs[0]
+ // The server answers with the tags out of order and includes one id it
+ // will not resolve; the client sorts by category and drops the orphan.
+ if len(vm.Tags) != 2 {
+ t.Fatalf("expected two resolvable VM tags, got %+v", vm.Tags)
+ }
+ if vm.Tags[0].Category != "Environment" || vm.Tags[0].Name != "Production" {
+ t.Fatalf("unexpected first VM tag: %+v", vm.Tags[0])
+ }
+ if vm.Tags[1].Category != "Owner" || vm.Tags[1].Name != "Platform" {
+ t.Fatalf("unexpected second VM tag: %+v", vm.Tags[1])
+ }
+}
+
+func TestClientTagCatalogReusesResolvedNamesAcrossCollections(t *testing.T) {
+ counts := map[string]int{}
+ var mu sync.Mutex
+ server := newVMwareTestServer(t, vmwareTestServerConfig{
+ tagRequestCounts: counts,
+ tagRequestCountsMu: &mu,
+ })
+ defer server.Close()
+
+ client := newTagTestClient(t, server.URL)
+ for i := 0; i < 3; i++ {
+ if _, err := client.CollectInventory(context.Background()); err != nil {
+ t.Fatalf("CollectInventory %d: %v", i, err)
+ }
+ }
+
+ mu.Lock()
+ defer mu.Unlock()
+ // Associations follow the estate, so they are re-read every refresh.
+ if counts["tag-association"] != 3 {
+ t.Fatalf("expected 3 association reads, got %d", counts["tag-association"])
+ }
+ // Tag and category names are estate-wide and stable, so they resolve once
+ // per TTL rather than once per refresh.
+ for _, tagID := range []string{"urn:tag:env-production", "urn:tag:owner-platform", "urn:tag:rack-r1"} {
+ if got := counts["tag:"+tagID]; got != 1 {
+ t.Fatalf("expected 1 metadata read for %s, got %d", tagID, got)
+ }
+ }
+ for _, categoryID := range []string{"urn:category:environment", "urn:category:owner", "urn:category:rack"} {
+ if got := counts["category:"+categoryID]; got != 1 {
+ t.Fatalf("expected 1 metadata read for %s, got %d", categoryID, got)
+ }
+ }
+ // The unresolvable id is retried because it never enters the catalog, but
+ // it must not be cached as a real tag either.
+ if got := counts["tag:urn:tag:orphan"]; got != 3 {
+ t.Fatalf("expected the unresolvable tag to be retried each refresh, got %d", got)
+ }
+}
+
+func TestEnrichInventoryTagsSkipsCollectionWithoutObjects(t *testing.T) {
+ server := newVMwareTestServer(t, vmwareTestServerConfig{})
+ defer server.Close()
+
+ client := newTagTestClient(t, server.URL)
+ issues, err := client.enrichInventoryTags(context.Background(), "automation-session", &InventorySnapshot{})
+ if err != nil {
+ t.Fatalf("enrichInventoryTags: %v", err)
+ }
+ if len(issues) != 0 {
+ t.Fatalf("expected no issues for an empty snapshot, got %+v", issues)
+ }
+ if issues, err := client.enrichInventoryTags(context.Background(), "automation-session", nil); err != nil || issues != nil {
+ t.Fatalf("expected a nil snapshot to be a no-op, got issues=%+v err=%v", issues, err)
+ }
+}
+
+func TestInventoryTagLabel(t *testing.T) {
+ cases := []struct {
+ name string
+ tag InventoryTag
+ want string
+ }{
+ {"category and name", InventoryTag{Category: "Environment", Name: "Production"}, "Environment:Production"},
+ {"name only", InventoryTag{Name: "Production"}, "Production"},
+ {"blank name is not a label", InventoryTag{Category: "Environment", Name: " "}, ""},
+ {"whitespace is trimmed", InventoryTag{Category: " Owner ", Name: " Platform "}, "Owner:Platform"},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := InventoryTagLabel(tc.tag); got != tc.want {
+ t.Fatalf("InventoryTagLabel(%+v) = %q, want %q", tc.tag, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestFixtureRecordsCarryVCenterTagsOnBothSurfaces(t *testing.T) {
+ records := FixtureRecords(DefaultFixtures())
+
+ var vmRecord *unifiedresources.IngestRecord
+ var hostRecord *unifiedresources.IngestRecord
+ labelSets := make(map[string]struct{})
+ for i := range records {
+ resource := records[i].Resource
+ if resource.VMware == nil {
+ continue
+ }
+ switch resource.VMware.EntityType {
+ case "vm":
+ labelSets[strings.Join(vmwareTagLabels(resource.VMware.Tags), "|")] = struct{}{}
+ if resource.Name == "postgres-ha-01" {
+ vmRecord = &records[i]
+ }
+ case "host":
+ if resource.Name == "esxi-01.lab.local" {
+ hostRecord = &records[i]
+ }
+ }
+ }
+
+ if vmRecord == nil || hostRecord == nil {
+ t.Fatal("expected the default fixtures to contain postgres-ha-01 and esxi-01.lab.local")
+ }
+ // The whole point of reading real tags is that rows stop looking alike.
+ // One label set across the fixture estate would mean the Tags column is
+ // still decoration.
+ if len(labelSets) < 5 {
+ t.Fatalf("expected the fixture VMs to carry varied tag sets, got %d distinct sets", len(labelSets))
+ }
+
+ wantVMLabels := []string{"Backup:Nightly", "Compliance:PCI", "Environment:Production", "Owner:Data"}
+ if got := vmwareTagLabels(vmRecord.Resource.VMware.Tags); strings.Join(got, "|") != strings.Join(wantVMLabels, "|") {
+ t.Fatalf("postgres-ha-01 VMware.Tags = %v, want %v", got, wantVMLabels)
+ }
+ wantHostLabels := []string{"Environment:Production", "Rack:R1"}
+ if got := vmwareTagLabels(hostRecord.Resource.VMware.Tags); strings.Join(got, "|") != strings.Join(wantHostLabels, "|") {
+ t.Fatalf("esxi-01 VMware.Tags = %v, want %v", got, wantHostLabels)
+ }
+
+ // The flat keyword set keeps provenance so resource search, the `?tags=`
+ // filter, and saved report schedules keep matching, and gains the real
+ // labels alongside it.
+ flat := vmRecord.Resource.Tags
+ for _, want := range []string{"vmware", "vsphere", "vm", "source:vcenter", "Environment:Production", "Compliance:PCI"} {
+ if !containsString(flat, want) {
+ t.Fatalf("expected flat resource tags to contain %q, got %v", want, flat)
+ }
+ }
+}
+
+func vmwareTagLabels(tags []unifiedresources.VMwareTagData) []string {
+ out := make([]string, 0, len(tags))
+ for _, tag := range tags {
+ out = append(out, tag.Label)
+ }
+ return out
+}
+
+func containsString(values []string, needle string) bool {
+ for _, value := range values {
+ if value == needle {
+ return true
+ }
+ }
+ return false
+}
+
+func TestVMwareResourceTagsKeepsProvenanceAndAppendsRealTags(t *testing.T) {
+ got := vmwareResourceTags(
+ []string{"vmware", "vsphere", "vm", "source:vcenter", "connection:lab vcenter", "power:powered_on"},
+ []InventoryTag{
+ {Category: "Environment", Name: "Production"},
+ {Name: "Uncategorized"},
+ {Name: " "},
+ },
+ )
+ want := []string{
+ "vmware",
+ "vsphere",
+ "vm",
+ "source:vcenter",
+ "connection:lab vcenter",
+ "power:powered_on",
+ "Environment:Production",
+ "Uncategorized",
+ }
+ if strings.Join(got, "|") != strings.Join(want, "|") {
+ t.Fatalf("vmwareResourceTags = %v, want %v", got, want)
+ }
+}
diff --git a/internal/vmware/client_test.go b/internal/vmware/client_test.go
index 4f4d04683d..5251632789 100644
--- a/internal/vmware/client_test.go
+++ b/internal/vmware/client_test.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/http/httptest"
"strings"
+ "sync"
"testing"
"time"
)
@@ -208,6 +209,7 @@ func TestClientCollectInventoryPreservesBaseInventoryWhenOptionalEnrichmentDegra
denyHostOverallStatus: true,
unavailableVMGuestInfo: true,
denyClusterInventory: true,
+ denyTagAssociations: true,
})
defer server.Close()
@@ -235,9 +237,10 @@ func TestClientCollectInventoryPreservesBaseInventoryWhenOptionalEnrichmentDegra
// The unavailableVMGuestInfo knob now degrades two REST reads: the
// guest identity endpoint (topology stage) and the guest local
// filesystem endpoint (signals stage). That plus the per-stage
- // permission denials gives four issues.
- if len(snapshot.EnrichmentIssues) != 4 {
- t.Fatalf("expected 4 enrichment issues, got %+v", snapshot.EnrichmentIssues)
+ // permission denials and the denied tag-association read gives five
+ // issues.
+ if len(snapshot.EnrichmentIssues) != 5 {
+ t.Fatalf("expected 5 enrichment issues, got %+v", snapshot.EnrichmentIssues)
}
seen := make(map[string]InventoryEnrichmentIssue, len(snapshot.EnrichmentIssues))
for _, issue := range snapshot.EnrichmentIssues {
@@ -264,6 +267,17 @@ func TestClientCollectInventoryPreservesBaseInventoryWhenOptionalEnrichmentDegra
} else if !strings.Contains(issue.Message, "guest identity") {
t.Fatalf("unexpected topology/vm unavailable message: %+v", issue)
}
+ // A vCenter without the tagging service, or an account without the tag
+ // read privilege, must degrade to untagged inventory rather than failing
+ // the whole refresh.
+ if issue, ok := seen["tags/tag/not_found"]; !ok {
+ t.Fatalf("expected tags/tag not_found issue, got %+v", snapshot.EnrichmentIssues)
+ } else if !strings.Contains(issue.Message, "tag associations") {
+ t.Fatalf("unexpected tags/tag message: %+v", issue)
+ }
+ if len(snapshot.Hosts[0].Tags) != 0 || len(snapshot.VMs[0].Tags) != 0 {
+ t.Fatalf("expected untagged inventory after degraded tag read, got host=%+v vm=%+v", snapshot.Hosts[0].Tags, snapshot.VMs[0].Tags)
+ }
host := snapshot.Hosts[0]
if host.OverallStatus != "" {
@@ -516,6 +530,9 @@ type vmwareTestServerConfig struct {
unauthorizedHostOverallStatus bool
denyClusterInventory bool
unavailableVMGuestInfo bool
+ denyTagAssociations bool
+ tagRequestCounts map[string]int
+ tagRequestCountsMu *sync.Mutex
}
func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Server {
@@ -589,6 +606,84 @@ func newVMwareTestServer(t *testing.T, cfg vmwareTestServerConfig) *httptest.Ser
"drs_enabled": false,
}})
})
+ countTagRequest := func(path string) {
+ if cfg.tagRequestCounts == nil || cfg.tagRequestCountsMu == nil {
+ return
+ }
+ cfg.tagRequestCountsMu.Lock()
+ defer cfg.tagRequestCountsMu.Unlock()
+ cfg.tagRequestCounts[path]++
+ }
+ mux.HandleFunc("/api/cis/tagging/tag-association", func(w http.ResponseWriter, r *http.Request) {
+ requireAutomationSession(t, r)
+ countTagRequest("tag-association")
+ if cfg.denyTagAssociations {
+ http.Error(w, "not found", http.StatusNotFound)
+ return
+ }
+ if r.Method != http.MethodPost {
+ http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ if got := r.URL.Query().Get("action"); got != "list-attached-tags-on-objects" {
+ t.Fatalf("tag association action = %q, want list-attached-tags-on-objects", got)
+ }
+ var payload struct {
+ ObjectIDs []cisObjectID `json:"object_ids"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode tag association request: %v", err)
+ }
+ associations := make([]cisTagAssociation, 0, len(payload.ObjectIDs))
+ for _, object := range payload.ObjectIDs {
+ switch object.ID {
+ case "host-101":
+ associations = append(associations, cisTagAssociation{
+ ObjectID: object,
+ TagIDs: []string{"urn:tag:rack-r1"},
+ })
+ case "vm-201":
+ associations = append(associations, cisTagAssociation{
+ ObjectID: object,
+ // Deliberately unsorted, and one id the catalog cannot
+ // resolve, so the client's ordering and skip behaviour
+ // both get exercised.
+ TagIDs: []string{"urn:tag:owner-platform", "urn:tag:env-production", "urn:tag:orphan"},
+ })
+ }
+ }
+ writeJSON(w, associations)
+ })
+ mux.HandleFunc("/api/cis/tagging/tag/", func(w http.ResponseWriter, r *http.Request) {
+ requireAutomationSession(t, r)
+ tagID := strings.TrimPrefix(r.URL.Path, "/api/cis/tagging/tag/")
+ countTagRequest("tag:" + tagID)
+ switch tagID {
+ case "urn:tag:env-production":
+ writeJSON(w, cisTagInfo{ID: tagID, Name: "Production", CategoryID: "urn:category:environment"})
+ case "urn:tag:owner-platform":
+ writeJSON(w, cisTagInfo{ID: tagID, Name: "Platform", CategoryID: "urn:category:owner"})
+ case "urn:tag:rack-r1":
+ writeJSON(w, cisTagInfo{ID: tagID, Name: "R1", CategoryID: "urn:category:rack"})
+ default:
+ http.Error(w, "not found", http.StatusNotFound)
+ }
+ })
+ mux.HandleFunc("/api/cis/tagging/category/", func(w http.ResponseWriter, r *http.Request) {
+ requireAutomationSession(t, r)
+ categoryID := strings.TrimPrefix(r.URL.Path, "/api/cis/tagging/category/")
+ countTagRequest("category:" + categoryID)
+ switch categoryID {
+ case "urn:category:environment":
+ writeJSON(w, cisCategoryInfo{ID: categoryID, Name: "Environment"})
+ case "urn:category:owner":
+ writeJSON(w, cisCategoryInfo{ID: categoryID, Name: "Owner"})
+ case "urn:category:rack":
+ writeJSON(w, cisCategoryInfo{ID: categoryID, Name: "Rack"})
+ default:
+ http.Error(w, "not found", http.StatusNotFound)
+ }
+ })
mux.HandleFunc("/api/vcenter/vm/vm-201", func(w http.ResponseWriter, r *http.Request) {
requireAutomationSession(t, r)
writeJSON(w, map[string]any{
diff --git a/internal/vmware/fixtures.go b/internal/vmware/fixtures.go
index d6e35c5432..8af54e07b4 100644
--- a/internal/vmware/fixtures.go
+++ b/internal/vmware/fixtures.go
@@ -2,6 +2,7 @@ package vmware
import (
"fmt"
+ "strings"
"time"
)
@@ -14,9 +15,70 @@ func DefaultFixtures() InventorySnapshot {
snapshot := defaultFixturesPrimaryCluster(collectedAt, accessible, multipleHostAccess)
appendEdgeClusterFixtures(&snapshot, collectedAt, accessible, multipleHostAccess)
applyInventoryClusterServices(&snapshot)
+ applyFixtureTags(&snapshot)
return snapshot
}
+// applyFixtureTags attaches the mock estate's vCenter tags. Real estates are
+// tagged unevenly — some objects carry several categories, some carry one, and
+// some were never tagged at all — so the fixture keeps that shape rather than
+// giving every object an identical set. A uniform set would hide exactly the
+// bug this data is meant to exercise: a Tags column that repeats itself on
+// every row.
+func applyFixtureTags(snapshot *InventorySnapshot) {
+ if snapshot == nil {
+ return
+ }
+
+ tag := func(category, name string) InventoryTag {
+ return InventoryTag{
+ TagID: fmt.Sprintf("urn:vmomi:InventoryServiceTag:mock-%s-%s:GLOBAL", strings.ToLower(category), strings.ToLower(name)),
+ Name: name,
+ CategoryID: fmt.Sprintf("urn:vmomi:InventoryServiceCategory:mock-%s:GLOBAL", strings.ToLower(category)),
+ Category: category,
+ }
+ }
+
+ hostTags := map[string][]InventoryTag{
+ "host-101": {tag("Environment", "Production"), tag("Rack", "R1")},
+ "host-102": {tag("Environment", "Production"), tag("Rack", "R1")},
+ "host-103": {tag("Environment", "Production"), tag("Rack", "R2")},
+ "host-104": {tag("Environment", "Staging"), tag("Rack", "R2")},
+ "host-201": {tag("Environment", "Production"), tag("Site", "Edge")},
+ "host-202": {tag("Environment", "Production"), tag("Site", "Edge")},
+ }
+ vmTags := map[string][]InventoryTag{
+ "vm-201": {tag("Environment", "Production"), tag("Owner", "Platform"), tag("Backup", "Nightly")},
+ "vm-202": {tag("Environment", "Production"), tag("Owner", "Data"), tag("Backup", "Nightly"), tag("Compliance", "PCI")},
+ "vm-203": {tag("Environment", "Production"), tag("Owner", "AppDev")},
+ "vm-204": {tag("Environment", "Staging"), tag("Owner", "AppDev")},
+ "vm-205": {tag("Environment", "Production"), tag("Owner", "Platform"), tag("Backup", "Weekly")},
+ "vm-301": {tag("Environment", "Production"), tag("Owner", "AppDev"), tag("Site", "Edge")},
+ "vm-302": {tag("Environment", "Production"), tag("Owner", "AppDev"), tag("Site", "Edge")},
+ "vm-303": {tag("Environment", "Production"), tag("Owner", "Data"), tag("Backup", "Nightly")},
+ "vm-304": {tag("Owner", "Platform"), tag("Backup", "None")},
+ "vm-305": {tag("Owner", "Platform"), tag("Backup", "None")},
+ "vm-306": {tag("Environment", "Production"), tag("Owner", "Platform")},
+ "vm-308": {tag("Environment", "Production"), tag("Owner", "Desktop"), tag("Compliance", "PCI")},
+ "vm-309": {tag("Environment", "Production"), tag("Owner", "Desktop")},
+ "vm-310": {tag("Owner", "Platform"), tag("Site", "Edge")},
+ "vm-311": {tag("Owner", "Platform"), tag("Site", "Edge")},
+ }
+
+ for i := range snapshot.Hosts {
+ if tags, ok := hostTags[snapshot.Hosts[i].Host]; ok {
+ sortInventoryTags(tags)
+ snapshot.Hosts[i].Tags = tags
+ }
+ }
+ for i := range snapshot.VMs {
+ if tags, ok := vmTags[snapshot.VMs[i].VM]; ok {
+ sortInventoryTags(tags)
+ snapshot.VMs[i].Tags = tags
+ }
+ }
+}
+
func defaultFixturesPrimaryCluster(
collectedAt time.Time,
accessible bool,
diff --git a/internal/vmware/provider.go b/internal/vmware/provider.go
index 240f9a5126..f5c55b0a85 100644
--- a/internal/vmware/provider.go
+++ b/internal/vmware/provider.go
@@ -189,6 +189,19 @@ type InventoryEnrichmentIssue struct {
Message string `json:"message,omitempty"`
}
+// InventoryTag is one operator-authored vCenter tag attached to an inventory
+// object, read from the CIS tagging service. vCenter tags always belong to a
+// category ("Environment", "Owner", ...), so the category travels with the tag
+// name: two categories may each hold a tag called "Production", and dropping
+// the category would merge them into one meaningless label.
+type InventoryTag struct {
+ TagID string `json:"tag_id,omitempty"`
+ Name string `json:"name"`
+ CategoryID string `json:"category_id,omitempty"`
+ Category string `json:"category,omitempty"`
+ Description string `json:"description,omitempty"`
+}
+
// InventoryCluster is the vCenter Automation API cluster summary. Pulse keeps
// clusters as read-only topology metadata on hosts and VMs, not top-level
// resources.
@@ -241,6 +254,7 @@ type InventoryHost struct {
DatastoreIDs []string `json:"datastore_ids,omitempty"`
DatastoreNames []string `json:"datastore_names,omitempty"`
OverallStatus string `json:"overall_status,omitempty"`
+ Tags []InventoryTag `json:"tags,omitempty"`
TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
RecentEvents []InventoryEvent `json:"recent_events,omitempty"`
@@ -277,6 +291,7 @@ type InventoryVM struct {
GuestHostname string `json:"guest_hostname,omitempty"`
GuestIPAddresses []string `json:"guest_ip_addresses,omitempty"`
OverallStatus string `json:"overall_status,omitempty"`
+ Tags []InventoryTag `json:"tags,omitempty"`
TriggeredAlarms []InventoryAlarm `json:"triggered_alarms,omitempty"`
RecentTasks []InventoryTask `json:"recent_tasks,omitempty"`
RecentEvents []InventoryEvent `json:"recent_events,omitempty"`
@@ -560,8 +575,9 @@ func vmwareRecordsFromSnapshot(snapshot *InventorySnapshot, now func() time.Time
ActiveAlarmSummary: vmwareAlarmSummary(host.TriggeredAlarms),
RecentTaskCount: len(host.RecentTasks),
RecentTaskSummary: vmwareRecentTaskSummary(host.RecentTasks),
+ Tags: vmwareTagsData(host.Tags),
},
- Tags: filterNonEmptyStrings(
+ Tags: vmwareResourceTags([]string{
"vmware",
"vsphere",
"host",
@@ -569,7 +585,7 @@ func vmwareRecordsFromSnapshot(snapshot *InventorySnapshot, now func() time.Time
tagWithValue("connection", strings.ToLower(connectionName)),
tagWithValue("power", strings.ToLower(strings.TrimSpace(host.PowerState))),
tagWithValue("state", strings.ToLower(strings.TrimSpace(host.ConnectionState))),
- ),
+ }, host.Tags),
}
identity := unifiedresources.ResourceIdentity{
DMIUUID: strings.TrimSpace(host.HostUUID),
@@ -642,15 +658,16 @@ func vmwareRecordsFromSnapshot(snapshot *InventorySnapshot, now func() time.Time
VirtualDisks: vmwareVirtualDisksData(vm.VirtualDisks),
Tools: vmwareToolsData(vm.Tools),
Hardware: vmwareVMHardwareData(vm.Hardware),
+ Tags: vmwareTagsData(vm.Tags),
},
- Tags: filterNonEmptyStrings(
+ Tags: vmwareResourceTags([]string{
"vmware",
"vsphere",
"vm",
"source:vcenter",
tagWithValue("connection", strings.ToLower(connectionName)),
tagWithValue("power", strings.ToLower(strings.TrimSpace(vm.PowerState))),
- ),
+ }, vm.Tags),
}
identity := unifiedresources.ResourceIdentity{
MachineID: firstNonEmptyTrimmed(vm.InstanceUUID, vm.BIOSUUID),
@@ -1714,6 +1731,54 @@ func filterNonEmptyStrings(values ...string) []string {
return out
}
+// vmwareResourceTags merges the adapter's provenance keywords with the
+// operator's real vCenter tag labels into the flat searchable keyword set.
+//
+// The provenance strings stay. `Resource.Tags` is the only keyword set
+// `resourceSearchMatch.ts`, the `?tags=` resources filter, and saved report
+// schedules read, so dropping "vmware"/"vsphere"/"source:vcenter" would
+// silently stop matching searches and saved filters that rely on them. Real
+// vCenter tags are appended to that set, never substituted for it.
+//
+// Because the set is deliberately mixed, it is not what a per-row Tags cell
+// should render — surfaces that show the operator's own labels read the
+// `VMware.Tags` facet instead.
+func vmwareResourceTags(provenance []string, tags []InventoryTag) []string {
+ values := make([]string, 0, len(provenance)+len(tags))
+ values = append(values, provenance...)
+ for _, tag := range tags {
+ values = append(values, InventoryTagLabel(tag))
+ }
+ return filterNonEmptyStrings(values...)
+}
+
+// vmwareTagsData projects vCenter tags onto the canonical VMware facet. Tags
+// without a resolvable name are dropped rather than rendered as empty chips.
+func vmwareTagsData(tags []InventoryTag) []unifiedresources.VMwareTagData {
+ if len(tags) == 0 {
+ return nil
+ }
+ out := make([]unifiedresources.VMwareTagData, 0, len(tags))
+ for _, tag := range tags {
+ label := InventoryTagLabel(tag)
+ if label == "" {
+ continue
+ }
+ out = append(out, unifiedresources.VMwareTagData{
+ TagID: strings.TrimSpace(tag.TagID),
+ Name: strings.TrimSpace(tag.Name),
+ CategoryID: strings.TrimSpace(tag.CategoryID),
+ Category: strings.TrimSpace(tag.Category),
+ Description: strings.TrimSpace(tag.Description),
+ Label: label,
+ })
+ }
+ if len(out) == 0 {
+ return nil
+ }
+ return out
+}
+
func tagWithValue(prefix, value string) string {
prefix = strings.TrimSpace(prefix)
value = strings.TrimSpace(value)