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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Wire TrueNAS and VMware into mock runtime
rcourtmanc511638acc76
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 87cf3aab5a..29db5e5e7b 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -260,6 +260,12 @@ but the canonical contract is that a successful handoff exchange must reconciletenant organization membership for the handed-off account member before thebrowser follows the new session into protected routes, rather than landing on afresh `access_denied` immediately after session minting.+That same platform-connections ownership now also includes mock-runtime+continuity for API-backed platforms. When `/api/system/mock-mode` flips a+running server between real and mock data, the canonical TrueNAS and VMware+settings routes must keep surfacing through the same Platform connections+workspace and handoff URLs instead of depending on process-start-only wiring+or a mock-only alternate shell.That same hosted continuity contract also applies to the older direct tenantmagic-link path. Lifecycle-adjacent control-plane redirects through`/auth/cloud-handoff` must preserve canonical account/user/role identity in thediff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex d6461b56e9..413321f2e7 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -703,6 +703,15 @@ remains the saved connection retest surface. The explicit disabled path alsostays on this boundary: `404 vmware_disabled` means the operator or runtime hasopted out of the default-on VMware candidate, not that the platform requires adifferent onboarding contract.+That same TrueNAS and VMware platform-connections contract now also owns+runtime mock continuity. When `/api/system/mock-mode` flips on a running+server, `/api/truenas/connections` and `/api/vmware/connections` must+immediately return the canonical mock connection payloads without restart, and+the shared `/api/resources` surface must expose the corresponding platform+inventory through `source=truenas` and `source=vmware-vsphere`. Shared query+parsing may accept `vmware-vsphere` as the operator-facing VMware alias, but+the emitted canonical resource source remains the shared `vmware` source+family rather than a second backend source key.That same VMware test contract now also owns structured setup-failureclassification. When `POST /api/vmware/connections/test` or`POST /api/vmware/connections/{id}/test` fails, the backend payload mustdiff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.mdindex 0619d13dcf..dc0d9743df 100644--- a/docs/release-control/v6/internal/subsystems/monitoring.md+++ b/docs/release-control/v6/internal/subsystems/monitoring.md@@ -109,6 +109,12 @@ with no edit overlay must refresh that same summary owner, andrecomputing or shadowing it inside handler-local runtime state. Internalsub-second test harness intervals must not leak `intervalSeconds: 0` onto thatoperator-facing contract.+That same monitoring boundary now also owns runtime mock rebind continuity for+API-backed supplemental providers. When `/api/system/mock-mode` flips on a+running server, the live TrueNAS and VMware provider bindings must swap to the+mock-backed supplemental records and refresh canonical read-state immediately+instead of waiting for a process restart before shared resource consumers can+see the platform inventory.That same summary owner also owns VMware partial-success classification.Optional VI JSON or Automation enrichment reads that fail after basehost/VM/datastore inventory succeeds must not collapse the whole poll into a@@ -354,6 +360,11 @@ physical-disk resources such as TrueNAS disks into the shared `disk`metrics-store contract via the existing SMART-temperature writer, so physicaldisk charts and disk-health consumers read one history path instead of aTrueNAS-only temperature cache.+That same TrueNAS monitoring ownership also includes runtime mock continuity.+When `/api/system/mock-mode` changes on a live server, the TrueNAS supplemental+provider must rebind immediately and repopulate the canonical read state so+settings, infrastructure, storage, and other shared consumers see the same+mock-backed inventory without restart.That same boundary now also owns native disk-history fallback when Pulse's ownhistory is shallow. `internal/truenas/client.go`,`internal/truenas/provider.go`, `internal/monitoring/truenas_poller.go`, anddiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 8313e964e7..1e98685f0b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -142,6 +142,12 @@ querying, and the operator-facing storage health presentation layer.a platform should be treated as recovery-capable only when that model marksrecovery as part of its support floor and the owning ingest/projection pathexists in the same governed slice.+10. Keep runtime mock inventory on the same bounded support contract. When+ `/api/system/mock-mode` surfaces mock TrueNAS pools/datasets or mock+ VMware datastores through shared storage/recovery-adjacent pages, that+ data remains inventory-only context and must not be treated as proof of+ restore capability, recovery artifacts, or widened platform recovery+ support.## Current State@@ -1660,6 +1666,11 @@ recovery-protected targets. Shared storage rows may show datastore topology,capacity, accessibility, and multi-host context, but they must keep fallbackprotection semantics neutral unless a separately governed recovery slice addsreal VMware protection contracts.+That same inventory-only contract also applies when the operator turns on+runtime mock data. Mock TrueNAS pools/datasets and mock VMware datastores may+surface through the shared storage and recovery-adjacent pages as canonical+inventory context, but that visibility still does not widen Pulse's recovery+support claim or imply restore capability for either platform.Storage and recovery must not infer VMware restore support, recovery rollups,or VMware-local protection semantics from the presence of those datastores orVM 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.mdindex 54d0188857..d43a4b9155 100644--- a/docs/release-control/v6/internal/subsystems/unified-resources.md+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md@@ -208,6 +208,13 @@ floor. `internal/unifiedresources/types.go`, `internal/unifiedresources/registrysingle source onto the canonical platform vocabulary, but they must not inventseparate `vcenter` or `esxi` filter keys or a VMware-only top-level resourcefamily to make the phase-1 slice render.+That same shared source boundary also applies when unified seeds and+supplemental providers coexist. If a canonical unified-resource seed omits an+owned supplemental source such as TrueNAS or VMware, the shared resource API+must still ingest that provider-owned source instead of letting the seed+silence the platform entirely. Operator-facing source filters may accept the+`vmware-vsphere` alias for the VMware platform, but the emitted shared source+family remains canonical `vmware`.That same VMware contract now also includes the identity rule. VMware managedobject identifiers are phase-1 provider identities, but they must be scoped bythe owning `vCenter` connection or discovered vCenter identity so bare object@@ -250,6 +257,11 @@ history. When a provider such as TrueNAS can supply `disk.temperature_agg`min/avg/max readings, it must project those onto`physicalDisk.temperatureAggregate` instead of introducing a provider-localhistory blob or a parallel disk-temperature presentation model.+That same canonical source and seed contract now also applies to runtime mock+mode. When mock-backed TrueNAS or VMware supplemental records are present, they+must enter the shared resource graph through the same canonical source/type+rules as live providers instead of introducing a mock-only source family or+resource kind.TrueNAS-managed applications now follow the same canonical workload rule. OneTrueNAS app instance from `app.query` must project as one canonical`app-container` resource under `SourceTrueNAS`, reusing the shared workload anddiff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.goindex 41163d3e12..964d5faffa 100644--- a/internal/api/config_handlers.go+++ b/internal/api/config_handlers.go@@ -193,6 +193,7 @@ type ConfigHandlers struct {reloadFunc func() errorreloadSystemSettingsFunc func() // Function to reload cached system settings+ mockModeChanged func(bool)wsHub *websocket.HubguestMetadataHandler *GuestMetadataHandlersetupTokens map[string]*SetupTokenRecord // Map of token hash -> setup token details@@ -290,6 +291,13 @@ func (h *ConfigHandlers) SetConfig(cfg *config.Config) {h.defaultConfig = cfg}+// SetMockModeChangeHook registers a callback invoked after mock mode changes.+func (h *ConfigHandlers) SetMockModeChangeHook(hook func(bool)) {+ h.stateMu.Lock()+ defer h.stateMu.Unlock()+ h.mockModeChanged = hook+}+// getContextState helper to retrieve tenant-specific statefunc (h *ConfigHandlers) getContextState(ctx context.Context) (*config.Config, *config.ConfigPersistence, *monitoring.Monitor) {h.stateMu.RLock()diff --git a/internal/api/config_handlers_cluster_additional_test.go b/internal/api/config_handlers_cluster_additional_test.goindex 1288a53413..7b1be84fb8 100644--- a/internal/api/config_handlers_cluster_additional_test.go+++ b/internal/api/config_handlers_cluster_additional_test.go@@ -488,6 +488,35 @@ func TestHandleGetMockMode(t *testing.T) {}}+func TestHandleUpdateMockMode_InvokesChangeHook(t *testing.T) {+ prevEnabled := mock.IsMockEnabled()+ t.Cleanup(func() {+ mock.SetEnabled(prevEnabled)+ })++ handler := newTestConfigHandlers(t, &config.Config{DataPath: t.TempDir()})+ called := false+ gotEnabled := false+ handler.SetMockModeChangeHook(func(enabled bool) {+ called = true+ gotEnabled = enabled+ })++ req := httptest.NewRequest(http.MethodPost, "/api/config/mock", bytes.NewReader([]byte(`{"enabled":true}`)))+ rec := httptest.NewRecorder()+ handler.HandleUpdateMockMode(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected status OK, got %d: %s", rec.Code, rec.Body.String())+ }+ if !called {+ t.Fatal("expected mock mode change hook to be invoked")+ }+ if !gotEnabled {+ t.Fatal("expected mock mode change hook to receive enabled=true")+ }+}+func TestHandleAgentInstallCommand(t *testing.T) {cfg := &config.Config{DataPath: t.TempDir(), AuthUser: "admin", AuthPass: "hashed-password"}handler := newTestConfigHandlers(t, cfg)diff --git a/internal/api/config_system_handlers.go b/internal/api/config_system_handlers.goindex d65a63d337..4a6cd729aa 100644--- a/internal/api/config_system_handlers.go+++ b/internal/api/config_system_handlers.go@@ -243,6 +243,13 @@ func (h *ConfigHandlers) handleUpdateMockMode(w http.ResponseWriter, r *http.Req} else {mock.SetEnabled(*req.Enabled)}++ h.stateMu.RLock()+ mockModeChanged := h.mockModeChanged+ h.stateMu.RUnlock()+ if mockModeChanged != nil {+ mockModeChanged(*req.Enabled)+ }}w.Header().Set("Content-Type", "application/json")diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex ac63dd1f0b..173592bf63 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -25,6 +25,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/alerts""github.com/rcourtman/pulse-go-rewrite/internal/config""github.com/rcourtman/pulse-go-rewrite/internal/license/entitlements"+ "github.com/rcourtman/pulse-go-rewrite/internal/mock""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/monitoring""github.com/rcourtman/pulse-go-rewrite/internal/recovery"@@ -264,6 +265,89 @@ func TestContract_VMwareConnectionListCarriesObservedSummary(t *testing.T) {}}+func TestContract_PlatformMockToggleRebindsRuntimeConnectionsAndResources(t *testing.T) {+ t.Setenv("PULSE_MOCK_MODE", "false")+ prevMock := mock.IsMockEnabled()+ mock.SetEnabled(false)+ t.Cleanup(func() {+ mock.SetEnabled(prevMock)+ })++ cfg := &config.Config{DataPath: t.TempDir()}+ monitor, err := monitoring.New(cfg)+ if err != nil {+ t.Fatalf("new monitor: %v", err)+ }+ monitor.SetMockMode(false)++ router := NewRouter(cfg, monitor, nil, nil, nil, "1.0.0")+ t.Cleanup(func() {+ router.shutdownBackgroundWorkers()+ })++ toggleReq := httptest.NewRequest(http.MethodPost, "/api/system/mock-mode", strings.NewReader(`{"enabled":true}`))+ toggleRec := httptest.NewRecorder()+ router.configHandlers.HandleUpdateMockMode(toggleRec, toggleReq)+ if toggleRec.Code != http.StatusOK {+ t.Fatalf("toggle status = %d, body=%s", toggleRec.Code, toggleRec.Body.String())+ }++ truenasListRec := httptest.NewRecorder()+ truenasListReq := httptest.NewRequest(http.MethodGet, "/api/truenas/connections", nil)+ router.trueNASHandlers.HandleList(truenasListRec, truenasListReq)+ if truenasListRec.Code != http.StatusOK {+ t.Fatalf("truenas connections status = %d, body=%s", truenasListRec.Code, truenasListRec.Body.String())+ }+ var truenasConnections []trueNASConnectionResponse+ if err := json.Unmarshal(truenasListRec.Body.Bytes(), &truenasConnections); err != nil {+ t.Fatalf("decode truenas connections: %v", err)+ }+ if len(truenasConnections) != 1 || truenasConnections[0].ID != "truenas-mock-1" {+ t.Fatalf("expected mock truenas connection, got %#v", truenasConnections)+ }++ vmwareListRec := httptest.NewRecorder()+ vmwareListReq := httptest.NewRequest(http.MethodGet, "/api/vmware/connections", nil)+ router.vmwareHandlers.HandleList(vmwareListRec, vmwareListReq)+ if vmwareListRec.Code != http.StatusOK {+ t.Fatalf("vmware connections status = %d, body=%s", vmwareListRec.Code, vmwareListRec.Body.String())+ }+ var vmwareConnections []vmwareConnectionResponse+ if err := json.Unmarshal(vmwareListRec.Body.Bytes(), &vmwareConnections); err != nil {+ t.Fatalf("decode vmware connections: %v", err)+ }+ if len(vmwareConnections) != 1 || vmwareConnections[0].ID != "vc-mock-1" {+ t.Fatalf("expected mock vmware connection, got %#v", vmwareConnections)+ }++ assertResourceSource := func(path string, wantSource unifiedresources.DataSource) {+ t.Helper()++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, path, nil)+ router.resourceHandlers.HandleListResources(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("%s status = %d, body=%s", path, rec.Code, rec.Body.String())+ }++ var resp ResourcesResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatalf("decode %s response: %v", path, err)+ }+ for _, resource := range resp.Data {+ for _, source := range resource.Sources {+ if source == wantSource {+ return+ }+ }+ }+ t.Fatalf("expected %s response to include source %q, got %#v", path, wantSource, resp.Data)+ }++ assertResourceSource("/api/resources?source=truenas", unifiedresources.SourceTrueNAS)+ assertResourceSource("/api/resources?source=vmware-vsphere", unifiedresources.SourceVMware)+}+func TestContract_VMwareConnectionListCarriesDegradedObservedSummary(t *testing.T) {setVMwareFeatureForTest(t, true)diff --git a/internal/api/platform_mock_connections.go b/internal/api/platform_mock_connections.gonew file mode 100644index 0000000000..602a40f42d--- /dev/null+++ b/internal/api/platform_mock_connections.go@@ -0,0 +1,95 @@+package api++import (+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/monitoring"+ "github.com/rcourtman/pulse-go-rewrite/internal/truenas"+ "github.com/rcourtman/pulse-go-rewrite/internal/vmware"+)++const defaultMockPlatformPollIntervalSeconds = 60++func mockTrueNASConnectionResponses() []trueNASConnectionResponse {+ fixtures := truenas.DefaultFixtures()+ collectedAt := fixtures.CollectedAt+ if collectedAt.IsZero() {+ collectedAt = fixtures.System.CollectedAt+ }++ instance := config.TrueNASInstance{+ ID: "truenas-mock-1",+ Name: "Archive NAS",+ Host: strings.TrimSpace(fixtures.System.Hostname),+ Port: 443,+ APIKey: "mock-truenas-api-key",+ UseHTTPS: true,+ Enabled: true,+ PollIntervalSecs: defaultMockPlatformPollIntervalSeconds,+ }+ instance.ApplyDefaults()++ observed := &monitoring.TrueNASConnectionObservedSummary{+ Host: strings.TrimSpace(fixtures.System.Hostname),+ ResourceID: strings.TrimSpace(fixtures.System.Hostname),+ Systems: 1,+ StoragePools: len(fixtures.Pools),+ Datasets: len(fixtures.Datasets),+ Apps: len(fixtures.Apps),+ Disks: len(fixtures.Disks),+ RecoveryArtifacts: len(fixtures.ZFSSnapshots) + len(fixtures.ReplicationTasks),+ CollectedAt: mockPlatformTimePointer(collectedAt),+ }++ return []trueNASConnectionResponse{{+ TrueNASInstance: instance.Redacted(),+ Poll: &monitoring.TrueNASConnectionPollStatus{+ IntervalSeconds: instance.EffectivePollIntervalSecs(),+ LastAttemptAt: mockPlatformTimePointer(collectedAt),+ LastSuccessAt: mockPlatformTimePointer(collectedAt),+ },+ Observed: observed,+ }}+}++func mockVMwareConnectionResponses() []vmwareConnectionResponse {+ snapshot := vmware.DefaultFixtures()+ collectedAt := snapshot.CollectedAt++ instance := config.VMwareVCenterInstance{+ ID: strings.TrimSpace(snapshot.ConnectionID),+ Name: strings.TrimSpace(snapshot.ConnectionName),+ Host: strings.TrimSpace(snapshot.VCenterHost),+ Port: 443,+ Username: "[email protected]",+ Password: "mock-vcenter-password",+ Enabled: true,+ }+ instance.ApplyDefaults()++ return []vmwareConnectionResponse{{+ VMwareVCenterInstance: instance.Redacted(),+ Poll: &monitoring.VMwareConnectionPollStatus{+ IntervalSeconds: defaultMockPlatformPollIntervalSeconds,+ LastAttemptAt: mockPlatformTimePointer(collectedAt),+ LastSuccessAt: mockPlatformTimePointer(collectedAt),+ },+ Observed: &monitoring.VMwareConnectionObservedSummary{+ CollectedAt: mockPlatformTimePointer(collectedAt),+ Hosts: len(snapshot.Hosts),+ VMs: len(snapshot.VMs),+ Datastores: len(snapshot.Datastores),+ VIRelease: strings.TrimSpace(snapshot.VIRelease),+ },+ }}+}++func mockPlatformTimePointer(value time.Time) *time.Time {+ if value.IsZero() {+ return nil+ }+ copied := value+ return &copied+}diff --git a/internal/api/resources.go b/internal/api/resources.goindex 5e89169941..897c280fb2 100644--- a/internal/api/resources.go+++ b/internal/api/resources.go@@ -836,22 +836,28 @@ func (h *ResourceHandlers) buildRegistry(orgID string) (*unified.ResourceRegistrh.supplementalMu.RUnlock()registry := unified.NewRegistry(store)+ ownedSources := supplementalSnapshotOwnedSources(supplementalProviders, orgID)if seed.unifiedSource {registry.IngestResources(seed.resources)+ seedSources := unifiedSeedSources(seed.resources)+ for source, provider := range supplementalProviders {+ if provider == nil || !sourceOwnedBySupplementalProvider(source, ownedSources) || unifiedSeedIncludesSource(seedSources, source) {+ continue+ }+ records := supplementalRecordsForOrg(provider, orgID)+ if len(records) == 0 {+ continue+ }+ registry.IngestRecords(source, records)+ }} else {- ownedSources := supplementalSnapshotOwnedSources(supplementalProviders, orgID)registry.IngestSnapshot(unified.SnapshotWithoutSources(seed.snapshot, ownedSources))for source, provider := range supplementalProviders {if provider == nil {continue}- var records []unified.IngestRecord- if tenantProvider, ok := any(provider).(TenantSupplementalRecordsProvider); ok {- records = tenantProvider.GetCurrentRecordsForOrg(orgID)- } else {- records = provider.GetCurrentRecords()- }+ records := supplementalRecordsForOrg(provider, orgID)if len(records) == 0 {continue}@@ -941,6 +947,87 @@ func supplementalSnapshotOwnedSources(providers map[unified.DataSource]Supplemenreturn out}+func supplementalRecordsForOrg(provider SupplementalRecordsProvider, orgID string) []unified.IngestRecord {+ if provider == nil {+ return nil+ }++ var records []unified.IngestRecord+ if tenantProvider, ok := any(provider).(TenantSupplementalRecordsProvider); ok {+ records = tenantProvider.GetCurrentRecordsForOrg(orgID)+ } else {+ records = provider.GetCurrentRecords()+ }+ if len(records) == 0 {+ return nil+ }++ out := make([]unified.IngestRecord, len(records))+ copy(out, records)+ return out+}++func unifiedSeedSources(resources []unified.Resource) map[unified.DataSource]struct{} {+ if len(resources) == 0 {+ return nil+ }++ sources := make(map[unified.DataSource]struct{})+ for _, resource := range resources {+ for _, source := range resource.Sources {+ if normalized := normalizeDataSourceAlias(source); normalized != "" {+ sources[normalized] = struct{}{}+ }+ }+ for source := range resource.SourceStatus {+ if normalized := normalizeDataSourceAlias(source); normalized != "" {+ sources[normalized] = struct{}{}+ }+ }+ switch {+ case resource.TrueNAS != nil:+ sources[unified.SourceTrueNAS] = struct{}{}+ case resource.VMware != nil:+ sources[unified.SourceVMware] = struct{}{}+ }+ }+ return sources+}++func unifiedSeedIncludesSource(seedSources map[unified.DataSource]struct{}, source unified.DataSource) bool {+ if len(seedSources) == 0 {+ return false+ }+ _, ok := seedSources[normalizeDataSourceAlias(source)]+ return ok+}++func sourceOwnedBySupplementalProvider(source unified.DataSource, ownedSources []unified.DataSource) bool {+ normalized := normalizeDataSourceAlias(source)+ if normalized == "" {+ return false+ }+ for _, ownedSource := range ownedSources {+ if normalizeDataSourceAlias(ownedSource) == normalized {+ return true+ }+ }+ return false+}++func normalizeDataSourceAlias(source unified.DataSource) unified.DataSource {+ switch strings.ToLower(strings.TrimSpace(string(source))) {+ case "", "all":+ return ""+ case "k8s":+ return unified.SourceK8s+ case "vmware-vsphere":+ return unified.SourceVMware+ default:+ return unified.DataSource(strings.ToLower(strings.TrimSpace(string(source))))+ }+}+func (h *ResourceHandlers) getStore(orgID string) (unified.ResourceStore, error) {h.storeMu.Lock()defer h.storeMu.Unlock()@@ -1710,6 +1797,8 @@ func parseSources(raw string) map[unified.DataSource]struct{} {result[unified.SourceK8s] = struct{}{}case "truenas":result[unified.SourceTrueNAS] = struct{}{}+ case "vmware", "vmware-vsphere":+ result[unified.SourceVMware] = struct{}{}}}return resultdiff --git a/internal/api/resources_test.go b/internal/api/resources_test.goindex 7829f019b2..26d70bb0cb 100644--- a/internal/api/resources_test.go+++ b/internal/api/resources_test.go@@ -3370,6 +3370,72 @@ func TestResourceListUnifiedSeedSkipsSupplementalReingest(t *testing.T) {}}+func TestResourceListUnifiedSeedIngestsOwnedSupplementalWhenSourceMissing(t *testing.T) {+ now := time.Now().UTC()++ cfg := &config.Config{DataPath: t.TempDir()}+ h := NewResourceHandlers(cfg)+ h.SetStateProvider(resourceUnifiedSeedProvider{+ snapshot: models.StateSnapshot{LastUpdate: now},+ resources: []unified.Resource{+ {+ ID: "agent-generic-seeded",+ Type: unified.ResourceTypeAgent,+ Name: "generic-host",+ Status: unified.StatusOnline,+ LastSeen: now,+ UpdatedAt: now,+ Sources: []unified.DataSource{unified.SourceAgent},+ Identity: unified.ResourceIdentity{+ MachineID: "generic-host",+ Hostnames: []string{"generic-host"},+ },+ },+ },+ })+ h.SetSupplementalRecordsProvider(unified.SourceVMware, mockSupplementalRecordsProvider{+ ownedSources: []unified.DataSource{unified.SourceVMware},+ records: []unified.IngestRecord{+ {+ SourceID: "vmware:host-1",+ Resource: unified.Resource{+ Type: unified.ResourceTypeAgent,+ Name: "esxi-01.lab.local",+ Status: unified.StatusOnline,+ LastSeen: now,+ UpdatedAt: now,+ },+ Identity: unified.ResourceIdentity{+ MachineID: "esxi-01",+ Hostnames: []string{"esxi-01.lab.local"},+ },+ },+ },+ })++ rec := httptest.NewRecorder()+ req := httptest.NewRequest(http.MethodGet, "/api/resources?source=vmware-vsphere", nil)+ h.HandleListResources(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("status = %d, body=%s", rec.Code, rec.Body.String())+ }++ var resp ResourcesResponse+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if len(resp.Data) != 1 {+ t.Fatalf("expected 1 vmware resource from owned supplemental provider, got %d", len(resp.Data))+ }+ if got := resp.Data[0].Name; got != "esxi-01.lab.local" {+ t.Fatalf("resource name = %q, want esxi-01.lab.local", got)+ }+ if !containsSource(resp.Data[0].Sources, unified.SourceVMware) {+ t.Fatalf("expected vmware source, got %+v", resp.Data[0].Sources)+ }+}+func TestResourceListSupplementalOwnerSuppressesSnapshotSource(t *testing.T) {now := time.Now().UTC()snapshot := models.StateSnapshot{@@ -3487,3 +3553,15 @@ func TestSupplementalSnapshotOwnedSources_TrueNASProviders(t *testing.T) {t.Fatalf("expected owned sources [%q], got %#v", unified.SourceTrueNAS, sources)}}++func TestParseSources_AcceptsVMwareAliases(t *testing.T) {+ for _, raw := range []string{"vmware", "vmware-vsphere"} {+ sources := parseSources(raw)+ if len(sources) != 1 {+ t.Fatalf("parseSources(%q) returned %d entries, want 1", raw, len(sources))+ }+ if _, ok := sources[unified.SourceVMware]; !ok {+ t.Fatalf("parseSources(%q) did not normalize to vmware: %#v", raw, sources)+ }+ }+}diff --git a/internal/api/router.go b/internal/api/router.goindex ab106fe968..5ab0243c52 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -347,6 +347,7 @@ func (r *Router) setupRoutes() {if r.monitor != nil {r.configHandlers.SetMonitor(r.monitor)}+ r.configHandlers.SetMockModeChangeHook(r.syncPlatformSupplementalProviders)r.trueNASHandlers = &TrueNASHandlers{getPersistence: r.configHandlers.getPersistence,getConfig: r.configHandlers.getConfig,@@ -380,21 +381,7 @@ func (r *Router) setupRoutes() {r.monitorResourceAdapter = unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store))}}- if mock.IsMockEnabled() {- truenas.SetFeatureEnabled(true)- vmware.SetFeatureEnabled(true)- mockTrueNASProvider := truenas.NewDefaultProvider()- adapter := trueNASRecordsAdapter{provider: mockTrueNASProvider}- r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, adapter)- r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, adapter)- } else if r.trueNASPoller != nil {- 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)- }+ r.syncPlatformSupplementalProviders(mock.IsMockEnabled())if r.monitor != nil {r.configureMonitorDependencies(r.monitor)if r.resourceHandlers != nil {@@ -1266,6 +1253,35 @@ func (r *Router) setMonitorSupplementalRecordsProvider(source unifiedresources.D}}+func (r *Router) syncPlatformSupplementalProviders(mockEnabled bool) {+ if r == nil {+ return+ }++ if mockEnabled {+ truenas.SetFeatureEnabled(true)+ vmware.SetFeatureEnabled(true)++ trueNASAdapter := trueNASRecordsAdapter{provider: truenas.NewDefaultProvider()}+ vmwareAdapter := vmwareRecordsAdapter{provider: vmware.NewDefaultProvider()}++ if r.resourceHandlers != nil {+ r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, trueNASAdapter)+ r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceVMware, vmwareAdapter)+ }+ r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, trueNASAdapter)+ r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceVMware, vmwareAdapter)+ return+ }++ if r.resourceHandlers != nil {+ r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, r.trueNASPoller)+ r.resourceHandlers.SetSupplementalRecordsProvider(unifiedresources.SourceVMware, r.vmwarePoller)+ }+ r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceTrueNAS, r.trueNASPoller)+ r.setMonitorSupplementalRecordsProvider(unifiedresources.SourceVMware, r.vmwarePoller)+}+// getTenantMonitor returns the appropriate monitor for the current request's tenant.// For non-default orgs, it fails closed when tenant monitor resolution fails.func (r *Router) getTenantMonitor(ctx context.Context) *monitoring.Monitor {@@ -9079,4 +9095,34 @@ func (a trueNASRecordsAdapter) SnapshotOwnedSourcesForOrg(string) []unifiedresoureturn []unifiedresources.DataSource{unifiedresources.SourceTrueNAS}}+type vmwareRecordsAdapter struct {+ provider *vmware.Provider+}++func (a vmwareRecordsAdapter) GetCurrentRecords() []unifiedresources.IngestRecord {+ return a.GetCurrentRecordsForOrg("default")+}++func (a vmwareRecordsAdapter) GetCurrentRecordsForOrg(orgID string) []unifiedresources.IngestRecord {+ if strings.TrimSpace(orgID) != "" && strings.TrimSpace(orgID) != "default" {+ return nil+ }+ if a.provider == nil {+ return nil+ }+ return a.provider.Records()+}++func (a vmwareRecordsAdapter) SupplementalRecords(_ *monitoring.Monitor, orgID string) []unifiedresources.IngestRecord {+ return a.GetCurrentRecordsForOrg(orgID)+}++func (a vmwareRecordsAdapter) SnapshotOwnedSources() []unifiedresources.DataSource {+ return []unifiedresources.DataSource{unifiedresources.SourceVMware}+}++func (a vmwareRecordsAdapter) SnapshotOwnedSourcesForOrg(string) []unifiedresources.DataSource {+ return []unifiedresources.DataSource{unifiedresources.SourceVMware}+}+// trigger rebuild Fri Jan 16 10:52:41 UTC 2026diff --git a/internal/api/router_integration_test.go b/internal/api/router_integration_test.goindex 5cdd0e8767..62eb43b53d 100644--- a/internal/api/router_integration_test.go+++ b/internal/api/router_integration_test.go@@ -1225,6 +1225,63 @@ func TestMockModeToggleEndpoint(t *testing.T) {}}+func TestMockModeToggleFromRealDataRebindsPlatformSupplementalProviders(t *testing.T) {+ srv := newIntegrationServerWithoutMock(t, nil)++ if mock.IsMockEnabled() {+ t.Fatalf("mock mode should be disabled at start of test")+ }++ enablePayload := bytes.NewBufferString(`{"enabled": true}`)+ resEnable, err := http.Post(srv.server.URL+"/api/system/mock-mode", "application/json", enablePayload)+ if err != nil {+ t.Fatalf("enable mock mode request failed: %v", err)+ }+ defer resEnable.Body.Close()++ if resEnable.StatusCode != http.StatusOK {+ t.Fatalf("unexpected status enabling mock mode: got %d want %d", resEnable.StatusCode, http.StatusOK)+ }++ checkResourceSource := func(path string, wantSource string) {+ t.Helper()++ deadline := time.Now().Add(5 * time.Second)+ for {+ res, err := http.Get(srv.server.URL + path)+ if err != nil {+ t.Fatalf("GET %s failed: %v", path, err)+ }++ var payload api.ResourcesResponse+ decodeErr := json.NewDecoder(res.Body).Decode(&payload)+ res.Body.Close()+ if decodeErr != nil {+ t.Fatalf("decode %s response: %v", path, decodeErr)+ }+ if res.StatusCode != http.StatusOK {+ t.Fatalf("unexpected %s status: got %d want %d", path, res.StatusCode, http.StatusOK)+ }++ for _, resource := range payload.Data {+ for _, source := range resource.Sources {+ if string(source) == wantSource {+ return+ }+ }+ }++ if time.Now().After(deadline) {+ t.Fatalf("expected %s resources after mock toggle, got %#v", wantSource, payload.Data)+ }+ time.Sleep(100 * time.Millisecond)+ }+ }++ checkResourceSource("/api/resources?source=truenas", "truenas")+ checkResourceSource("/api/resources?source=vmware-vsphere", "vmware")+}+func TestAuthenticatedEndpointsRequireToken(t *testing.T) {const apiToken = "test-token"diff --git a/internal/api/router_mock_platforms_test.go b/internal/api/router_mock_platforms_test.gonew file mode 100644index 0000000000..9b51298b74--- /dev/null+++ b/internal/api/router_mock_platforms_test.go@@ -0,0 +1,69 @@+package api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/config"+ "github.com/rcourtman/pulse-go-rewrite/internal/mock"+ unified "github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"+)++func TestRouterMockMode_SeedsTrueNASAndVMwareSupplementalResources(t *testing.T) {+ previous := mock.IsMockEnabled()+ mock.SetEnabled(true)+ t.Cleanup(func() {+ mock.SetEnabled(previous)+ })++ cfg := &config.Config{DataPath: t.TempDir()}+ router := NewRouter(cfg, nil, nil, nil, nil, "1.0.0")+ t.Cleanup(func() {+ router.shutdownBackgroundWorkers()+ })++ for _, tc := range []struct {+ name string+ source string+ want unified.DataSource+ }{+ {name: "truenas", source: "truenas", want: unified.SourceTrueNAS},+ {name: "vmware", source: "vmware-vsphere", want: unified.SourceVMware},+ } {+ t.Run(tc.name, func(t *testing.T) {+ req := httptest.NewRequest(http.MethodGet, "/api/resources?source="+tc.source, nil)+ rec := httptest.NewRecorder()++ router.resourceHandlers.HandleListResources(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())+ }++ var resp ResourcesResponse+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode resources response: %v", err)+ }+ if len(resp.Data) == 0 {+ t.Fatalf("expected mock %s resources, got none", tc.source)+ }+ foundSource := false+ for _, resource := range resp.Data {+ for _, source := range resource.Sources {+ if source == tc.want {+ foundSource = true+ break+ }+ }+ if foundSource {+ break+ }+ }+ if !foundSource {+ t.Fatalf("expected at least one resource with source %q, got %#v", tc.want, resp.Data)+ }+ })+ }+}diff --git a/internal/api/truenas_handlers.go b/internal/api/truenas_handlers.goindex c4eaf7b1db..5a2e784c3e 100644--- a/internal/api/truenas_handlers.go+++ b/internal/api/truenas_handlers.go@@ -99,6 +99,10 @@ func (h *TrueNASHandlers) HandleList(w http.ResponseWriter, r *http.Request) {if !h.featureEnabled(w) {return}+ if mock.IsMockEnabled() {+ writeJSON(w, http.StatusOK, mockTrueNASConnectionResponses())+ return+ }persistence := h.persistenceForRequest(w, r.Context())if persistence == nil {diff --git a/internal/api/truenas_handlers_test.go b/internal/api/truenas_handlers_test.goindex d4d381631e..55b9dbe0b8 100644--- a/internal/api/truenas_handlers_test.go+++ b/internal/api/truenas_handlers_test.go@@ -221,6 +221,38 @@ func TestTrueNASHandlers_HandleList_RedactsSensitiveFields(t *testing.T) {}}+func TestTrueNASHandlers_HandleList_ReturnsMockConnectionsInMockMode(t *testing.T) {+ setTrueNASFeatureForTest(t, true)+ setMockModeForTrueNASTest(t, true)++ handler, _, _ := newTrueNASHandlersForTest(t, nil)++ req := httptest.NewRequest(http.MethodGet, "/api/truenas/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 listed []trueNASConnectionResponse+ if err := json.NewDecoder(rec.Body).Decode(&listed); err != nil {+ t.Fatalf("decode list response: %v", err)+ }+ if len(listed) != 1 {+ t.Fatalf("expected 1 mock TrueNAS connection, got %d", len(listed))+ }+ if listed[0].Host != "truenas-main" {+ t.Fatalf("expected mock TrueNAS host truenas-main, got %q", listed[0].Host)+ }+ if listed[0].Poll == nil || listed[0].Poll.LastSuccessAt == nil {+ t.Fatalf("expected mock poll summary, got %+v", listed[0].Poll)+ }+ if listed[0].Observed == nil || listed[0].Observed.Systems != 1 || listed[0].Observed.StoragePools == 0 {+ t.Fatalf("expected populated mock observed summary, got %+v", listed[0].Observed)+ }+}+func TestTrueNASHandlers_HandleList_IncludesPollAndObservedSummary(t *testing.T) {setTrueNASFeatureForTest(t, true)diff --git a/internal/api/vmware_handlers.go b/internal/api/vmware_handlers.goindex 718a3ad87f..72a7c28397 100644--- a/internal/api/vmware_handlers.go+++ b/internal/api/vmware_handlers.go@@ -100,6 +100,10 @@ func (h *VMwareHandlers) HandleList(w http.ResponseWriter, r *http.Request) {if !h.featureEnabled(w) {return}+ if mock.IsMockEnabled() {+ writeJSON(w, http.StatusOK, mockVMwareConnectionResponses())+ return+ }persistence := h.persistenceForRequest(w, r.Context())if persistence == nil {diff --git a/internal/api/vmware_handlers_test.go b/internal/api/vmware_handlers_test.goindex 6df8fabc25..2e3d95ff04 100644--- a/internal/api/vmware_handlers_test.go+++ b/internal/api/vmware_handlers_test.go@@ -179,6 +179,41 @@ func TestVMwareHandlers_HandleList_RedactsSensitiveFieldsAndIncludesRuntimeSumma}}+func TestVMwareHandlers_HandleList_ReturnsMockConnectionsInMockMode(t *testing.T) {+ setVMwareFeatureForTest(t, true)+ setMockModeForVMwareTest(t, true)++ handler, _ := newVMwareHandlersForTest(t)++ 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 listed []vmwareConnectionResponse+ if err := json.NewDecoder(rec.Body).Decode(&listed); err != nil {+ t.Fatalf("decode list response: %v", err)+ }+ if len(listed) != 1 {+ t.Fatalf("expected 1 mock VMware connection, got %d", len(listed))+ }+ if listed[0].Host != "vcsa.lab.local" {+ t.Fatalf("expected mock VMware host vcsa.lab.local, got %q", listed[0].Host)+ }+ if listed[0].Password != "********" {+ t.Fatalf("expected redacted mock VMware password, got %q", listed[0].Password)+ }+ if listed[0].Poll == nil || listed[0].Poll.LastSuccessAt == nil {+ t.Fatalf("expected mock VMware poll summary, got %+v", listed[0].Poll)+ }+ if listed[0].Observed == nil || listed[0].Observed.Hosts == 0 || listed[0].Observed.VMs == 0 {+ t.Fatalf("expected populated mock VMware observed summary, got %+v", listed[0].Observed)+ }+}+func TestVMwareHandlers_HandleDelete_RemovesAndClearsRuntimeSummary(t *testing.T) {setVMwareFeatureForTest(t, true)setMockModeForVMwareTest(t, false)diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.goindex 2fa6d1c54c..3d22421838 100644--- a/internal/monitoring/canonical_guardrails_test.go+++ b/internal/monitoring/canonical_guardrails_test.go@@ -25,6 +25,16 @@ var bannedSnapshotResourceAccessPatterns = []struct {},}+type guardrailSupplementalProvider struct {+ records []unifiedresources.IngestRecord+}++func (p guardrailSupplementalProvider) SupplementalRecords(*Monitor, string) []unifiedresources.IngestRecord {+ out := make([]unifiedresources.IngestRecord, len(p.records))+ copy(out, p.records)+ return out+}+func readMonitoringRuntimeFiles(t *testing.T) map[string]string {t.Helper()@@ -437,6 +447,48 @@ func TestAlertLifecycleCanonicalChangesRemainWritable(t *testing.T) {}}+func TestSupplementalProviderChangesRefreshCanonicalReadState(t *testing.T) {+ now := time.Now().UTC()+ state := models.NewState()+ state.UpsertHost(models.Host{+ ID: "host-1",+ Hostname: "seed-host",+ Status: "online",+ LastSeen: now,+ })++ store := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(nil))+ monitor := &Monitor{state: state}+ monitor.SetResourceStore(store)+ monitor.SetSupplementalRecordsProvider(unifiedresources.SourceVMware, guardrailSupplementalProvider{+ records: []unifiedresources.IngestRecord{+ {+ SourceID: "vmware:esxi-01",+ Resource: unifiedresources.Resource{+ Type: unifiedresources.ResourceTypeAgent,+ Name: "esxi-01.lab.local",+ Status: unifiedresources.StatusOnline,+ LastSeen: now,+ UpdatedAt: now,+ },+ Identity: unifiedresources.ResourceIdentity{+ Hostnames: []string{"esxi-01.lab.local"},+ },+ },+ },+ })++ resources := store.GetAll()+ for _, resource := range resources {+ for _, source := range resource.Sources {+ if source == unifiedresources.SourceVMware {+ return+ }+ }+ }+ t.Fatalf("expected resource store refresh to surface vmware supplemental records, got %#v", resources)+}+func TestTelemetrySnapshotAggregationUsesProvisionedTenantSet(t *testing.T) {baseDir := t.TempDir()persistence := config.NewMultiTenantPersistence(baseDir)diff --git a/internal/monitoring/mock_metrics_history.go b/internal/monitoring/mock_metrics_history.goindex 458da5b63f..806909d72a 100644--- a/internal/monitoring/mock_metrics_history.go+++ b/internal/monitoring/mock_metrics_history.go@@ -12,6 +12,7 @@ import ("github.com/rcourtman/pulse-go-rewrite/internal/mock""github.com/rcourtman/pulse-go-rewrite/internal/models""github.com/rcourtman/pulse-go-rewrite/internal/truenas"+ "github.com/rcourtman/pulse-go-rewrite/internal/vmware""github.com/rcourtman/pulse-go-rewrite/pkg/metrics""github.com/rs/zerolog/log")@@ -927,6 +928,78 @@ func seedMockMetricsHistory(mh *MetricsHistory, ms *metrics.Store, state models.queueMetric("dataset", dataset.Name, "disk", diskPercent, now)}+ vmwareFixtures := vmware.DefaultFixtures()+ vmwareDatastoreUsage := vmwareDatastoreUsageByID(vmwareFixtures.Datastores)+ log.Debug().+ Int("hosts", len(vmwareFixtures.Hosts)).+ Int("vms", len(vmwareFixtures.VMs)).+ Int("datastores", len(vmwareFixtures.Datastores)).+ Msg("mock seeding: processing VMware fixtures")++ for _, host := range vmwareFixtures.Hosts {+ sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "host", host.Host)+ if sourceID == "" {+ continue+ }+ recordGuest(+ "agent:"+sourceID,+ "agent",+ sourceID,+ vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }),+ vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }),+ vmwareAverageDatastoreUsage(vmwareDatastoreUsage, host.DatastoreIDs),+ vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }),+ vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }),+ vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }),+ vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }),+ true,+ true,+ true,+ )+ }++ for _, guest := range vmwareFixtures.VMs {+ sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "vm", guest.VM)+ if sourceID == "" {+ continue+ }+ recordGuest(+ sourceID,+ "vm",+ sourceID,+ vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }),+ vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }),+ vmwareAverageDatastoreUsage(vmwareDatastoreUsage, guest.DatastoreIDs),+ vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }),+ vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }),+ vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }),+ vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }),+ true,+ true,+ true,+ )+ }++ for _, datastore := range vmwareFixtures.Datastores {+ usage := vmwareDatastoreUsagePercent(datastore)+ if usage <= 0 {+ continue+ }+ sourceID := vmware.SourceID(vmwareFixtures.ConnectionID, "datastore", datastore.Datastore)+ if sourceID == "" {+ continue+ }+ numPoints := len(seedTimestamps)+ usageSeries := GenerateSeededSeries(usage, numPoints, HashSeed("vmware-datastore", sourceID, "usage"), 0, 100, styleFlat)+ for i := 0; i < numPoints; i++ {+ ts := seedTimestamps[i]+ mh.AddStorageMetric(sourceID, "usage", usageSeries[i], ts)+ queueMetric("storage", sourceID, "usage", usageSeries[i], ts)+ }+ mh.AddStorageMetric(sourceID, "usage", usage, now)+ queueMetric("storage", sourceID, "usage", usage, now)+ }+if ms != nil && len(seedBatch) > 0 {ms.WriteBatchSync(seedBatch)}@@ -975,6 +1048,123 @@ func recordTrueNASFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, ts time}}+func recordVMwareFixturesMetrics(mh *MetricsHistory, ms *metrics.Store, ts time.Time) {+ snapshot := vmware.DefaultFixtures()+ datastoreUsage := vmwareDatastoreUsageByID(snapshot.Datastores)++ for _, host := range snapshot.Hosts {+ sourceID := vmware.SourceID(snapshot.ConnectionID, "host", host.Host)+ if sourceID == "" {+ continue+ }+ mh.AddGuestMetric("agent:"+sourceID, "cpu", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)+ mh.AddGuestMetric("agent:"+sourceID, "memory", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)+ mh.AddGuestMetric("agent:"+sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, host.DatastoreIDs), ts)+ mh.AddGuestMetric("agent:"+sourceID, "diskread", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)+ mh.AddGuestMetric("agent:"+sourceID, "diskwrite", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)+ mh.AddGuestMetric("agent:"+sourceID, "netin", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)+ mh.AddGuestMetric("agent:"+sourceID, "netout", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)+ if ms != nil {+ ms.Write("agent", sourceID, "cpu", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)+ ms.Write("agent", sourceID, "memory", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)+ ms.Write("agent", sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, host.DatastoreIDs), ts)+ ms.Write("agent", sourceID, "diskread", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)+ ms.Write("agent", sourceID, "diskwrite", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)+ ms.Write("agent", sourceID, "netin", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)+ ms.Write("agent", sourceID, "netout", vmwareFloat64Metric(host.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)+ }+ }++ for _, guest := range snapshot.VMs {+ sourceID := vmware.SourceID(snapshot.ConnectionID, "vm", guest.VM)+ if sourceID == "" {+ continue+ }+ mh.AddGuestMetric(sourceID, "cpu", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)+ mh.AddGuestMetric(sourceID, "memory", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)+ mh.AddGuestMetric(sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, guest.DatastoreIDs), ts)+ mh.AddGuestMetric(sourceID, "diskread", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)+ mh.AddGuestMetric(sourceID, "diskwrite", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)+ mh.AddGuestMetric(sourceID, "netin", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)+ mh.AddGuestMetric(sourceID, "netout", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)+ if ms != nil {+ ms.Write("vm", sourceID, "cpu", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.CPUPercent }), ts)+ ms.Write("vm", sourceID, "memory", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.MemoryPercent }), ts)+ ms.Write("vm", sourceID, "disk", vmwareAverageDatastoreUsage(datastoreUsage, guest.DatastoreIDs), ts)+ ms.Write("vm", sourceID, "diskread", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskReadBytesPerSecond }), ts)+ ms.Write("vm", sourceID, "diskwrite", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.DiskWriteBytesPerSecond }), ts)+ ms.Write("vm", sourceID, "netin", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetInBytesPerSecond }), ts)+ ms.Write("vm", sourceID, "netout", vmwareFloat64Metric(guest.Metrics, func(m *vmware.InventoryMetrics) *float64 { return m.NetOutBytesPerSecond }), ts)+ }+ }++ for _, datastore := range snapshot.Datastores {+ sourceID := vmware.SourceID(snapshot.ConnectionID, "datastore", datastore.Datastore)+ if sourceID == "" {+ continue+ }+ usage := vmwareDatastoreUsagePercent(datastore)+ mh.AddStorageMetric(sourceID, "usage", usage, ts)+ if ms != nil {+ ms.Write("storage", sourceID, "usage", usage, ts)+ }+ }+}++func vmwareFloat64Metric(metrics *vmware.InventoryMetrics, pick func(*vmware.InventoryMetrics) *float64) float64 {+ if metrics == nil || pick == nil {+ return 0+ }+ value := pick(metrics)+ if value == nil {+ return 0+ }+ return *value+}++func vmwareDatastoreUsageByID(datastores []vmware.InventoryDatastore) map[string]float64 {+ out := make(map[string]float64, len(datastores))+ for _, datastore := range datastores {+ id := strings.TrimSpace(datastore.Datastore)+ if id == "" {+ continue+ }+ out[id] = vmwareDatastoreUsagePercent(datastore)+ }+ return out+}++func vmwareAverageDatastoreUsage(byID map[string]float64, ids []string) float64 {+ if len(ids) == 0 || len(byID) == 0 {+ return 0+ }+ var total float64+ var count int+ for _, id := range ids {+ usage, ok := byID[strings.TrimSpace(id)]+ if !ok {+ continue+ }+ total += usage+ count+++ }+ if count == 0 {+ return 0+ }+ return total / float64(count)+}++func vmwareDatastoreUsagePercent(datastore vmware.InventoryDatastore) float64 {+ if datastore.Capacity <= 0 {+ return 0+ }+ used := datastore.Capacity - datastore.FreeSpace+ if used < 0 {+ used = 0+ }+ return clampFloat((float64(used)/float64(datastore.Capacity))*100, 0, 100)+}+type guestMetricSource interface {GetID() stringGetStatus() string@@ -1265,6 +1455,7 @@ func recordMockStateToMetricsHistory(mh *MetricsHistory, ms *metrics.Store, stat// Record TrueNAS pool/dataset disk-usage live ticksrecordTrueNASFixturesMetrics(mh, ms, ts)+ recordVMwareFixturesMetrics(mh, ms, ts)}func diskMetricsResourceID(disk models.PhysicalDisk) string {diff --git a/internal/monitoring/mock_metrics_history_test.go b/internal/monitoring/mock_metrics_history_test.goindex f9bbe29bc1..bc5f7db96e 100644--- a/internal/monitoring/mock_metrics_history_test.go+++ b/internal/monitoring/mock_metrics_history_test.go@@ -265,6 +265,51 @@ func TestSeedMockMetricsHistory_SeedsDiskTemperatureMetricsStore(t *testing.T) {}}+func TestSeedMockMetricsHistory_SeedsVMwareMetricsStore(t *testing.T) {+ now := time.Now()+ state := models.StateSnapshot{}++ cfg := metrics.DefaultConfig(t.TempDir())+ cfg.RetentionRaw = 90 * 24 * time.Hour+ cfg.RetentionMinute = 90 * 24 * time.Hour+ cfg.RetentionHourly = 90 * 24 * time.Hour+ cfg.RetentionDaily = 90 * 24 * time.Hour+ cfg.WriteBufferSize = 500++ store, err := metrics.NewStore(cfg)+ if err != nil {+ t.Fatalf("failed to create metrics store: %v", err)+ }+ defer store.Close()++ mh := NewMetricsHistory(1000, 7*24*time.Hour)+ seedMockMetricsHistory(mh, store, state, now, 7*24*time.Hour, time.Minute)++ hostPoints, err := store.Query("agent", "vc-mock-1:host:host-101", "cpu", now.Add(-7*24*time.Hour), now, 3600)+ if err != nil {+ t.Fatalf("failed to query VMware host cpu metrics: %v", err)+ }+ if len(hostPoints) == 0 {+ t.Fatal("expected metrics store to have seeded VMware host cpu points")+ }++ vmPoints, err := store.Query("vm", "vc-mock-1:vm:vm-201", "cpu", now.Add(-7*24*time.Hour), now, 3600)+ if err != nil {+ t.Fatalf("failed to query VMware VM cpu metrics: %v", err)+ }+ if len(vmPoints) == 0 {+ t.Fatal("expected metrics store to have seeded VMware VM cpu points")+ }++ storagePoints, err := store.Query("storage", "vc-mock-1:datastore:datastore-201", "usage", now.Add(-7*24*time.Hour), now, 3600)+ if err != nil {+ t.Fatalf("failed to query VMware datastore usage metrics: %v", err)+ }+ if len(storagePoints) == 0 {+ t.Fatal("expected metrics store to have seeded VMware datastore usage points")+ }+}+func TestStartMockMetricsSampler_DoesNotClearExistingMetricsStoreData(t *testing.T) {t.Setenv("PULSE_MOCK_NODES", "1")t.Setenv("PULSE_MOCK_VMS_PER_NODE", "0")diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex f681e9fc98..708a083aba 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -3916,6 +3916,8 @@ func (m *Monitor) SetSupplementalRecordsProvider(source unifiedresources.DataSoum.supplementalProviders[normalized] = provider}m.mu.Unlock()++ m.updateResourceStore(m.GetState())}// SetRecoveryManager wires the recovery store manager for best-effort ingestion ofdiff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.goindex 06a912da3c..202a0b9853 100644--- a/internal/unifiedresources/code_standards_test.go+++ b/internal/unifiedresources/code_standards_test.go@@ -218,6 +218,25 @@ func TestNoDirectStateAccessForMigratedResources(t *testing.T) {}}+func TestAPIResourcesKeepsOwnedSupplementalGapFillAndVMwareAlias(t *testing.T) {+ data, err := os.ReadFile(filepath.Join("..", "api", "resources.go"))+ if err != nil {+ t.Fatalf("failed to read ../api/resources.go: %v", err)+ }+ source := string(data)++ requiredSnippets := []string{+ "seedSources := unifiedSeedSources(seed.resources)",+ "!sourceOwnedBySupplementalProvider(source, ownedSources) || unifiedSeedIncludesSource(seedSources, source)",+ `case "vmware", "vmware-vsphere":`,+ }+ for _, snippet := range requiredSnippets {+ if !strings.Contains(source, snippet) {+ t.Fatalf("../api/resources.go must contain %q", snippet)+ }+ }+}+func TestResourceAPIUsesCanonicalTenantUnifiedSeed(t *testing.T) {data, err := os.ReadFile(filepath.Join("..", "api", "resources.go"))if err != nil {diff --git a/internal/vmware/fixtures.go b/internal/vmware/fixtures.gonew file mode 100644index 0000000000..e67b9378ca--- /dev/null+++ b/internal/vmware/fixtures.go@@ -0,0 +1,266 @@+package vmware++import "time"++func DefaultFixtures() InventorySnapshot {+ collectedAt := time.Date(2026, time.March, 31, 9, 45, 0, 0, time.UTC)++ accessible := true+ multipleHostAccess := true++ return InventorySnapshot{+ ConnectionID: "vc-mock-1",+ ConnectionName: "Lab vCenter",+ VCenterHost: "vcsa.lab.local",+ VIRelease: "8.0.3",+ CollectedAt: collectedAt,+ Hosts: []InventoryHost{+ {+ Host: "host-101",+ Name: "esxi-01.lab.local",+ ConnectionState: "CONNECTED",+ PowerState: "POWERED_ON",+ HostUUID: "uuid-host-101",+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ ComputeResourceID: "domain-c101",+ ComputeResourceName: "Production Cluster",+ ClusterID: "domain-c101",+ ClusterName: "Production Cluster",+ FolderID: "group-h4",+ FolderName: "Cluster Hosts",+ DatastoreIDs: []string{"datastore-201", "datastore-202"},+ DatastoreNames: []string{"nvme-primary", "archive-tier"},+ OverallStatus: "green",+ Metrics: &InventoryMetrics{+ CPUPercent: float64Ptr(27.4),+ MemoryPercent: float64Ptr(58.1),+ MemoryUsedBytes: int64Ptr(49_902_682_112),+ MemoryTotalBytes: int64Ptr(85_899_345_920),+ NetInBytesPerSecond: float64Ptr(1_240_000),+ NetOutBytesPerSecond: float64Ptr(980_000),+ DiskReadBytesPerSecond: float64Ptr(2_280_000),+ DiskWriteBytesPerSecond: float64Ptr(1_920_000),+ },+ RecentTasks: []InventoryTask{{+ Task: "task-301",+ Name: "Apply host profile remediation",+ State: "success",+ StartedAt: collectedAt.Add(-28 * time.Minute),+ }},+ },+ {+ Host: "host-102",+ Name: "esxi-02.lab.local",+ ConnectionState: "CONNECTED",+ PowerState: "POWERED_ON",+ HostUUID: "uuid-host-102",+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ ComputeResourceID: "domain-c101",+ ComputeResourceName: "Production Cluster",+ ClusterID: "domain-c101",+ ClusterName: "Production Cluster",+ FolderID: "group-h4",+ FolderName: "Cluster Hosts",+ DatastoreIDs: []string{"datastore-201"},+ DatastoreNames: []string{"nvme-primary"},+ OverallStatus: "yellow",+ Metrics: &InventoryMetrics{+ CPUPercent: float64Ptr(43.6),+ MemoryPercent: float64Ptr(71.5),+ MemoryUsedBytes: int64Ptr(61_419_929_600),+ MemoryTotalBytes: int64Ptr(85_899_345_920),+ NetInBytesPerSecond: float64Ptr(1_960_000),+ NetOutBytesPerSecond: float64Ptr(1_420_000),+ DiskReadBytesPerSecond: float64Ptr(3_180_000),+ DiskWriteBytesPerSecond: float64Ptr(2_540_000),+ },+ TriggeredAlarms: []InventoryAlarm{{+ Alarm: "alarm-401",+ Name: "Host memory contention",+ OverallStatus: "yellow",+ TriggeredAt: collectedAt.Add(-11 * time.Minute),+ }},+ RecentTasks: []InventoryTask{{+ Task: "task-302",+ Name: "vMotion virtual machine",+ State: "running",+ StartedAt: collectedAt.Add(-3 * time.Minute),+ }},+ },+ },+ VMs: []InventoryVM{+ {+ VM: "vm-201",+ Name: "orders-api-01",+ PowerState: "POWERED_ON",+ CPUCount: 4,+ MemorySizeMiB: 16 * 1024,+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ ComputeResourceID: "domain-c101",+ ComputeResourceName: "Production Cluster",+ ClusterID: "domain-c101",+ ClusterName: "Production Cluster",+ FolderID: "group-v7",+ FolderName: "Production VMs",+ ResourcePoolID: "resgroup-22",+ ResourcePoolName: "Tier 1",+ RuntimeHostID: "host-101",+ RuntimeHostName: "esxi-01.lab.local",+ DatastoreIDs: []string{"datastore-201"},+ DatastoreNames: []string{"nvme-primary"},+ InstanceUUID: "vm-instance-201",+ BIOSUUID: "vm-bios-201",+ GuestOSFamily: "LINUX",+ GuestHostname: "orders-api-01.internal",+ GuestIPAddresses: []string{"10.42.10.21"},+ OverallStatus: "green",+ SnapshotCount: 1,+ Metrics: &InventoryMetrics{+ CPUPercent: float64Ptr(36.2),+ MemoryPercent: float64Ptr(64.4),+ MemoryUsedBytes: int64Ptr(11_058_069_504),+ MemoryTotalBytes: int64Ptr(17_179_869_184),+ NetInBytesPerSecond: float64Ptr(620_000),+ NetOutBytesPerSecond: float64Ptr(710_000),+ DiskReadBytesPerSecond: float64Ptr(1_180_000),+ DiskWriteBytesPerSecond: float64Ptr(940_000),+ },+ RecentEvents: []InventoryEvent{{+ Event: "event-501",+ Type: "VmMessageEvent",+ Message: "Snapshot completed successfully",+ User: "svc-pulse",+ CreatedAt: collectedAt.Add(-46 * time.Minute),+ }},+ },+ {+ VM: "vm-202",+ Name: "postgres-ha-01",+ PowerState: "POWERED_ON",+ CPUCount: 8,+ MemorySizeMiB: 32 * 1024,+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ ComputeResourceID: "domain-c101",+ ComputeResourceName: "Production Cluster",+ ClusterID: "domain-c101",+ ClusterName: "Production Cluster",+ FolderID: "group-v7",+ FolderName: "Production VMs",+ ResourcePoolID: "resgroup-23",+ ResourcePoolName: "Stateful",+ RuntimeHostID: "host-102",+ RuntimeHostName: "esxi-02.lab.local",+ DatastoreIDs: []string{"datastore-201", "datastore-202"},+ DatastoreNames: []string{"nvme-primary", "archive-tier"},+ InstanceUUID: "vm-instance-202",+ BIOSUUID: "vm-bios-202",+ GuestOSFamily: "LINUX",+ GuestHostname: "postgres-ha-01.internal",+ GuestIPAddresses: []string{"10.42.10.32"},+ OverallStatus: "yellow",+ SnapshotCount: 3,+ Metrics: &InventoryMetrics{+ CPUPercent: float64Ptr(58.8),+ MemoryPercent: float64Ptr(82.1),+ MemoryUsedBytes: int64Ptr(28_215_830_528),+ MemoryTotalBytes: int64Ptr(34_359_738_368),+ NetInBytesPerSecond: float64Ptr(880_000),+ NetOutBytesPerSecond: float64Ptr(930_000),+ DiskReadBytesPerSecond: float64Ptr(2_940_000),+ DiskWriteBytesPerSecond: float64Ptr(3_220_000),+ },+ TriggeredAlarms: []InventoryAlarm{{+ Alarm: "alarm-402",+ Name: "Virtual machine memory usage",+ OverallStatus: "yellow",+ TriggeredAt: collectedAt.Add(-17 * time.Minute),+ }},+ RecentTasks: []InventoryTask{{+ Task: "task-303",+ Name: "Consolidate virtual machine disks",+ State: "queued",+ StartedAt: collectedAt.Add(-2 * time.Minute),+ }},+ },+ {+ VM: "vm-203",+ Name: "batch-worker-01",+ PowerState: "POWERED_OFF",+ CPUCount: 4,+ MemorySizeMiB: 8 * 1024,+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ ComputeResourceID: "domain-c101",+ ComputeResourceName: "Production Cluster",+ ClusterID: "domain-c101",+ ClusterName: "Production Cluster",+ FolderID: "group-v8",+ FolderName: "Batch VMs",+ ResourcePoolID: "resgroup-24",+ ResourcePoolName: "Workers",+ RuntimeHostID: "host-101",+ RuntimeHostName: "esxi-01.lab.local",+ DatastoreIDs: []string{"datastore-202"},+ DatastoreNames: []string{"archive-tier"},+ InstanceUUID: "vm-instance-203",+ BIOSUUID: "vm-bios-203",+ GuestOSFamily: "LINUX",+ GuestHostname: "batch-worker-01.internal",+ GuestIPAddresses: []string{},+ OverallStatus: "gray",+ },+ },+ Datastores: []InventoryDatastore{+ {+ Datastore: "datastore-201",+ Name: "nvme-primary",+ Type: "VMFS",+ FreeSpace: 3_800_000_000_000,+ Capacity: 8_000_000_000_000,+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ FolderID: "group-s4",+ FolderName: "Datastores",+ HostIDs: []string{"host-101", "host-102"},+ HostNames: []string{"esxi-01.lab.local", "esxi-02.lab.local"},+ VMIDs: []string{"vm-201", "vm-202"},+ VMNames: []string{"orders-api-01", "postgres-ha-01"},+ Accessible: &accessible,+ MultipleHostAccess: &multipleHostAccess,+ MaintenanceMode: "normal",+ URL: "ds:///vmfs/volumes/datastore-201/",+ OverallStatus: "green",+ },+ {+ Datastore: "datastore-202",+ Name: "archive-tier",+ Type: "NFS41",+ FreeSpace: 11_000_000_000_000,+ Capacity: 16_000_000_000_000,+ DatacenterID: "datacenter-1",+ DatacenterName: "Primary DC",+ FolderID: "group-s4",+ FolderName: "Datastores",+ HostIDs: []string{"host-101"},+ HostNames: []string{"esxi-01.lab.local"},+ VMIDs: []string{"vm-202", "vm-203"},+ VMNames: []string{"postgres-ha-01", "batch-worker-01"},+ Accessible: &accessible,+ MultipleHostAccess: &multipleHostAccess,+ MaintenanceMode: "normal",+ URL: "ds:///nfs/archive-tier/",+ OverallStatus: "yellow",+ RecentTasks: []InventoryTask{{+ Task: "task-304",+ Name: "Rescan datastore",+ State: "success",+ StartedAt: collectedAt.Add(-14 * time.Minute),+ }},+ },+ },+ }+}diff --git a/internal/vmware/provider.go b/internal/vmware/provider.goindex 0c30460f36..8ccedcbb73 100644--- a/internal/vmware/provider.go+++ b/internal/vmware/provider.go@@ -260,6 +260,11 @@ func NewProvider(snapshot InventorySnapshot) *Provider {return provider}+// NewDefaultProvider returns a provider loaded with the default VMware fixtures.+func NewDefaultProvider() *Provider {+ return NewProvider(DefaultFixtures())+}+// Refresh fetches and caches the latest snapshot.func (p *Provider) Refresh(ctx context.Context) error {if p == nil {@@ -693,6 +698,12 @@ func vmwareSourceID(connectionID, entityType, managedObjectID string) string {return strings.Join(parts, ":")}+// SourceID returns the canonical VMware source identifier used for projected+// records, metrics targets, and mock/runtime history.+func SourceID(connectionID, entityType, managedObjectID string) string {+ return vmwareSourceID(connectionID, entityType, managedObjectID)+}+func hostStatus(host InventoryHost) unifiedresources.ResourceStatus {switch strings.ToUpper(strings.TrimSpace(host.ConnectionState)) {case "CONNECTED":diff --git a/tests/integration/tests/43-platform-mock-runtime.spec.ts b/tests/integration/tests/43-platform-mock-runtime.spec.tsnew file mode 100644index 0000000000..9e650d4cd9--- /dev/null+++ b/tests/integration/tests/43-platform-mock-runtime.spec.ts@@ -0,0 +1,128 @@+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, getMockMode, setMockMode } from './helpers';++const __dirname = path.dirname(fileURLToPath(import.meta.url));++type WorkerFixtures = {+ authStorageStatePath: string;+};++const TRUENAS_SCREENSHOT_PATH = path.resolve(+ __dirname,+ '..',+ '..',+ 'tmp',+ 'platform-mock-runtime-truenas.png',+);+const VMWARE_SCREENSHOT_PATH = path.resolve(+ __dirname,+ '..',+ '..',+ 'tmp',+ 'platform-mock-runtime-vmware.png',+);++let mockModeWasEnabled: boolean | null = null;++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',+ `platform-mock-runtime-${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' }],+});++async function ensureMockModeEnabled(page: import('@playwright/test').Page): Promise<void> {+ const state = await getMockMode(page);+ if (mockModeWasEnabled === null) {+ mockModeWasEnabled = state.enabled;+ }+ if (!state.enabled) {+ await setMockMode(page, true);+ }+}++test.describe.serial('Platform mock runtime', () => {+ test.setTimeout(180_000);++ test.afterAll(async ({ browser }) => {+ if (mockModeWasEnabled === null) {+ return;+ }++ const context = await browser.newContext();+ const page = await context.newPage();+ try {+ const current = await getMockMode(page);+ if (current.enabled !== mockModeWasEnabled) {+ await setMockMode(page, mockModeWasEnabled);+ }+ } finally {+ await context.close();+ }+ });++ test('renders TrueNAS and VMware mock data from the live runtime', async ({ page }, testInfo) => {+ test.skip(testInfo.project.name.startsWith('mobile-'), 'Desktop runtime proof');++ await ensureMockModeEnabled(page);++ await page.goto('/settings/infrastructure/platforms/truenas', {+ waitUntil: 'domcontentloaded',+ });+ await page.waitForURL(/\/settings\/infrastructure\/platforms\/truenas/, {+ timeout: 15_000,+ });+ await expect(page.getByText('Archive NAS')).toBeVisible();+ await expect(page.getByText('3 pools')).toBeVisible();+ await expect(page.getByText('5 datasets')).toBeVisible();+ fs.mkdirSync(path.dirname(TRUENAS_SCREENSHOT_PATH), { recursive: true });+ await page.screenshot({ path: TRUENAS_SCREENSHOT_PATH, fullPage: true });++ await page.goto('/infrastructure?source=truenas', {+ waitUntil: 'domcontentloaded',+ });+ await expect(page.getByTestId('infrastructure-page')).toBeVisible();+ await expect(page.locator('#infra-source-filter')).toHaveValue('truenas');+ await expect(page.getByText('truenas-main').first()).toBeVisible();++ await page.goto('/settings/infrastructure/platforms/vmware', {+ waitUntil: 'domcontentloaded',+ });+ await page.waitForURL(/\/settings\/infrastructure\/platforms\/vmware/, {+ timeout: 15_000,+ });+ await expect(page.getByText('Lab vCenter')).toBeVisible();+ await expect(page.getByText('2 hosts')).toBeVisible();+ await expect(page.getByText('3 vms')).toBeVisible();+ await expect(page.getByText('2 datastores')).toBeVisible();+ fs.mkdirSync(path.dirname(VMWARE_SCREENSHOT_PATH), { recursive: true });+ await page.screenshot({ path: VMWARE_SCREENSHOT_PATH, fullPage: true });++ await page.goto('/infrastructure?source=vmware-vsphere', {+ waitUntil: 'domcontentloaded',+ });+ await expect(page.getByTestId('infrastructure-page')).toBeVisible();+ await expect(page.locator('#infra-source-filter')).toHaveValue('vmware-vsphere');+ await expect(page.getByText('esxi-01.lab.local').first()).toBeVisible();+ });+});