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.

Build the mock linked view at the rebuild's link boundary

rcourtman55443c709530
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index d7ee52daa5..3e6892eeec 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -3610,7 +3610,7 @@ the mock-mode fence above): it stays a plain projection of current state for
the window before a rebuild in the new epoch, after which the registry applies
the links again. `TestMockUnifiedViewAppliesOperatorManualLinks` in
`internal/monitoring/monitor_host_agents_test.go` pins the broadcast, the
-freshness advance and the cache, `TestFixtureGraphAppliesManualLinksAtEachIngestStage`
+freshness advance and the cache, `TestFixtureGraphAppliesManualLinksAtTheRebuildsBoundary`
and `TestUnifiedResourceSnapshotWithLinksLeavesTheSharedSnapshotUnlinked` in
`internal/mock/platform_fixtures_test.go` pin the linked fixture build, and
`TestMockUnifiedStateViewUsesCanonicalMockFixtureGraph` in
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 a7372f932d..2b94604873 100644
--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md
@@ -3723,6 +3723,22 @@ nonempty machine and agent IDs and canonical identity across fixture rebuilds.
This changes fixture generation only, without relaxing production identity
resolution or adding work to the recurring update path.
+### Mock linked fixture builds use the rebuild's link boundary
+
+The mock fixture build holds the operator-link pass back until the snapshot and
+every supplemental source but availability are ingested, then runs one deferred
+pass before availability (`DeferManualLinks`, `ApplyDeferredManualLinks`), as
+the monitor's rebuild does; the availability ingest runs its own pass after it,
+as in the rebuild. The shared memoized snapshot has no links, so it defers
+nothing and builds as before (about 52 ms and 65 MB on the default fixture
+estate, with or without the change). A linked build, which runs only when the
+fixture data version or the link list changes, pays one extra refresh round
+after the deferred pass: about 3 ms and 5 MB more on that estate, the same
+round the rebuild runs.
+`TestFixtureGraphAppliesManualLinksAtTheRebuildsBoundary` in
+`internal/mock/platform_fixtures_test.go` pins the result a pass per source
+does not reach.
+
### Alert passes resolve metrics targets without materializing the estate
An alert pass makes one `Monitor.MetricsTargetForResource` call per resource
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 0b330163c0..080eebde01 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -6989,10 +6989,12 @@ links" below).
its chain carries, so identical records leave the pair set and every
folded ID as they were. The resources API's snapshot-seeded fallback,
used only while the monitor has published no unified listing, still
- ingests the snapshot and each supplemental source with a pass per call,
- and so does the mock-mode fixture build (`internal/mock`): a chain whose
- answer depends on the order its members' sources arrive in can settle
- differently there than in the monitor's rebuild.
+ ingests the snapshot and each supplemental source with a pass per call.
+ The mock-mode fixture build (`internal/mock`) draws the rebuild's boundary
+ (`DeferManualLinks`, `ApplyDeferredManualLinks`; see "Mock-mode unified
+ view applies operator links"), so a chain whose answer depends on the
+ order its members' sources arrive in settles there as it does in the
+ monitor's rebuild.
- Rows fold along the chain's links, deepest first, so each fold record
names a stored link's pair. The links form a spanning tree from the root
that follows the fold records the rows already carry before any other
@@ -7223,13 +7225,24 @@ identity pins, canonical-ID successions or change records, and the view's read
state forwards no history to the operator's store, so fixture data stays out
of durable state through it.
-- The links apply at each ingest stage, as in the live rebuild: the snapshot,
- then the TrueNAS and vSphere records, then availability. An availability
- check that names the folded resource by source reference resolves through
- the fold and projects onto the primary. Folding the finished list instead
- dropped the check with the folded row. A check that names the folded
- resource by canonical ID still loses its target, as live (fold history
- above).
+- The links apply at the live rebuild's boundary (the monitor's rebuild
+ holds the link pass back, above): the build holds the pass back
+ (`DeferManualLinks`), ingests the snapshot and the TrueNAS and vSphere
+ records, runs it once over that estate (`ApplyDeferredManualLinks`, which
+ takes the stale thresholds the ingests were given, nil for the registry's
+ own), and only then ingests availability. A chain of links is judged over
+ every member's source at once, as the rebuild judges it, so the row that
+ survives does not depend on which source arrives first: a Proxmox storage,
+ a TrueNAS VM and a vSphere VM linked in a cycle keep the TrueNAS VM whose
+ link is the oldest, where a pass after the TrueNAS records had already
+ folded it into the storage and kept the vSphere VM. A registry with no
+ links defers nothing, so the shared memoized snapshot is built exactly as
+ before. An availability check that names the folded resource by source
+ reference resolves through the fold and projects onto the primary, and so
+ does one that names it by canonical ID, which the registry resolves through
+ the fold history (`TestAvailabilityLinkToALinkFoldedResourceFollowsItsPrimary`
+ in `internal/unifiedresources/availability_link_test.go`). Folding the
+ finished list instead dropped the check with the folded row.
- A link reaches the view when the adapter's next rebuild loads it, the same
point at which the live broadcast picks it up. The view's cache is keyed on
the fixture data version and on the links' resource pairs and primaries, so
@@ -7260,10 +7273,17 @@ the rebuild and freshness advance on a link change with the fixture data
version held, the cached build afterwards, the same rows as a store-backed
registry seeded through resource ingest the way the resources API seeds, and
no change rows reaching the store through the view.
-`TestFixtureGraphAppliesManualLinksAtEachIngestStage` and
+`TestFixtureGraphAppliesManualLinksAtTheRebuildsBoundary` and
`TestUnifiedResourceSnapshotWithLinksLeavesTheSharedSnapshotUnlinked` in
-`internal/mock/platform_fixtures_test.go` pin the staged availability
-projection and the untouched shared snapshot, and
+`internal/mock/platform_fixtures_test.go` pin the rebuild's boundary (the
+cycle above settling on the row the monitor's rebuild keeps, which a pass per
+source does not, and the availability projection after the pass) and the
+untouched shared snapshot,
+`TestRegistryHoldsManualLinksBackUntilTheDeferredPass` and
+`TestRegistryDeferredLinkPassJudgesFreshnessByTheCallersThresholds` in
+`internal/unifiedresources/registry_merge_policy_test.go` pin the exported
+pair (the snapshot and record ingests wait, the pass runs once, and it judges
+freshness by the thresholds it is given), and
`TestRegistryWithManualLinksFoldsLikeTheStoreBackedRegistry` in
`internal/unifiedresources/registry_test.go` pins the store-less registry
against the store-backed one and the per-generation `ManualLinks` snapshot.
diff --git a/internal/mock/platform_fixtures.go b/internal/mock/platform_fixtures.go
index e479469b65..240222852c 100644
--- a/internal/mock/platform_fixtures.go
+++ b/internal/mock/platform_fixtures.go
@@ -190,14 +190,16 @@ func UnifiedResourceSnapshot() ([]unifiedresources.Resource, time.Time) {
}
// UnifiedResourceSnapshotWithLinks returns the current mock world as unified
-// resources with the operator's manual links applied at each ingest stage, as
-// the live monitor's registry rebuild applies them: a link whose side arrives
-// as a supplemental record, or whose folded side an availability check names
-// by source, folds as it would live. Folding the finished list instead loses
-// both. The registry has no store, so nothing the fixtures ingest is
-// persisted. Without links this is UnifiedResourceSnapshot; with links it
-// builds afresh on every call, so callers cache it per fixture data version
-// and link set, and its result is the caller's own.
+// resources with the operator's manual links applied where the live monitor's
+// registry rebuild applies them: once the snapshot and every supplemental
+// record source are in, and before availability. A chain whose members arrive
+// as supplemental records is judged over the whole estate, so it settles on the
+// row the live view keeps, and an availability check that names the folded
+// resource by source resolves through the fold onto the primary. Folding the
+// finished list instead loses both. The registry has no store, so nothing the
+// fixtures ingest is persisted. Without links this is UnifiedResourceSnapshot;
+// with links it builds afresh on every call, so callers cache it per fixture
+// data version and link set, and its result is the caller's own.
func UnifiedResourceSnapshotWithLinks(links []unifiedresources.ResourceLink) ([]unifiedresources.Resource, time.Time) {
if len(links) == 0 {
return UnifiedResourceSnapshot()
@@ -213,15 +215,26 @@ func (g FixtureGraph) UnifiedResourceSnapshot() ([]unifiedresources.Resource, ti
}
func (g FixtureGraph) unifiedResourceSnapshot(registry *unifiedresources.ResourceRegistry) ([]unifiedresources.Resource, time.Time) {
+ // The links apply at the monitor rebuild's boundary
+ // (MonitorAdapter.replaceRegistryLocked): after the snapshot and every
+ // source but availability, so a chain is judged over the assembled estate
+ // instead of folded as its members' sources arrive, and before
+ // availability, so a check linked to a folded resource projects onto its
+ // primary.
+ registry.DeferManualLinks()
registry.IngestSnapshot(unifiedresources.SnapshotWithoutSources(g.State, SupplementalOwnedSources()))
for _, source := range SupplementalOwnedSources() {
+ if source == unifiedresources.SourceAvailability {
+ registry.ApplyDeferredManualLinks(nil)
+ }
records := g.SupplementalRecords(source)
if len(records) == 0 {
continue
}
registry.IngestRecords(source, records)
}
+ registry.ApplyDeferredManualLinks(nil)
freshness := g.State.LastUpdate
for _, candidate := range []time.Time{
diff --git a/internal/mock/platform_fixtures_test.go b/internal/mock/platform_fixtures_test.go
index bf5db89b7f..5c49e4f015 100644
--- a/internal/mock/platform_fixtures_test.go
+++ b/internal/mock/platform_fixtures_test.go
@@ -466,54 +466,152 @@ func TestFixtureGraphAttachesServiceAvailabilityFixturesToServiceResources(t *te
}
}
-// TestFixtureGraphAppliesManualLinksAtEachIngestStage pins the linked build
-// behind the mock-mode unified view. Folding the curated Docker service into a
-// VM must move its availability check onto the VM, as the live rebuild's
-// availability ingest resolves the check's source reference through the fold;
-// folding the finished list dropped the facet with the folded row.
-func TestFixtureGraphAppliesManualLinksAtEachIngestStage(t *testing.T) {
+// TestFixtureGraphAppliesManualLinksAtTheRebuildsBoundary pins the linked
+// build behind the mock-mode unified view to the live rebuild's link boundary
+// (MonitorAdapter.replaceRegistryLocked): the links apply once the snapshot
+// and every supplemental source but availability are in, and before
+// availability. Two things hang on it. Availability goes in after the pass, so
+// folding the curated Docker service into a VM moves its availability check
+// onto the VM, as the live rebuild's availability ingest resolves the check's
+// source reference through the fold; folding the finished list dropped the
+// facet with the folded row. And a chain of links is judged over the assembled
+// estate, so mock mode keeps the row the live rebuild keeps instead of the one
+// a pass per source happens to leave.
+func TestFixtureGraphAppliesManualLinksAtTheRebuildsBoundary(t *testing.T) {
now := time.Date(2026, time.May, 6, 12, 0, 0, 0, time.UTC)
graph := buildFixtureGraph(DefaultConfig, now)
unlinked, _ := graph.UnifiedResourceSnapshot()
- const checkID = "mock-availability-docker-frontend-service"
- var serviceID, vmID string
- for _, resource := range unlinked {
- switch {
- case resource.Type == unifiedresources.ResourceTypeDockerService && resource.Availability != nil &&
- resource.Availability.TargetID == checkID:
- serviceID = resource.ID
- case vmID == "" && resource.Type == unifiedresources.ResourceTypeVM && resource.Proxmox != nil:
- vmID = resource.ID
+ t.Run("an availability check follows the fold onto the primary", func(t *testing.T) {
+ const checkID = "mock-availability-docker-frontend-service"
+ var serviceID, vmID string
+ for _, resource := range unlinked {
+ switch {
+ case resource.Type == unifiedresources.ResourceTypeDockerService && resource.Availability != nil &&
+ resource.Availability.TargetID == checkID:
+ serviceID = resource.ID
+ case vmID == "" && resource.Type == unifiedresources.ResourceTypeVM && resource.Proxmox != nil:
+ vmID = resource.ID
+ }
+ }
+ if serviceID == "" || vmID == "" {
+ t.Fatalf("fixture graph needs the checked Docker service and a Proxmox VM, got service=%q vm=%q", serviceID, vmID)
}
- }
- if serviceID == "" || vmID == "" {
- t.Fatalf("fixture graph needs the checked Docker service and a Proxmox VM, got service=%q vm=%q", serviceID, vmID)
- }
- links := []unifiedresources.ResourceLink{{ResourceA: vmID, ResourceB: serviceID, PrimaryID: vmID}}
- linked, _ := graph.unifiedResourceSnapshot(unifiedresources.NewRegistryWithManualLinks(links))
- var vm, endpoint *unifiedresources.Resource
- for i := range linked {
- switch {
- case linked[i].ID == serviceID:
- t.Fatalf("linked build still lists the folded Docker service %s", serviceID)
- case linked[i].ID == vmID:
- vm = &linked[i]
- case linked[i].Type == unifiedresources.ResourceTypeNetworkEndpoint && linked[i].Availability != nil &&
- linked[i].Availability.TargetID == checkID:
- endpoint = &linked[i]
+ links := []unifiedresources.ResourceLink{{ResourceA: vmID, ResourceB: serviceID, PrimaryID: vmID}}
+ linked, _ := graph.unifiedResourceSnapshot(unifiedresources.NewRegistryWithManualLinks(links))
+ var vm, endpoint *unifiedresources.Resource
+ for i := range linked {
+ switch {
+ case linked[i].ID == serviceID:
+ t.Fatalf("linked build still lists the folded Docker service %s", serviceID)
+ case linked[i].ID == vmID:
+ vm = &linked[i]
+ case linked[i].Type == unifiedresources.ResourceTypeNetworkEndpoint && linked[i].Availability != nil &&
+ linked[i].Availability.TargetID == checkID:
+ endpoint = &linked[i]
+ }
}
- }
- if vm == nil || vm.Docker == nil {
- t.Fatalf("linked VM %s = %+v, want it to carry the folded service's Docker facet", vmID, vm)
- }
- if vm.Availability == nil || vm.Availability.TargetID != checkID {
- t.Fatalf("linked VM availability = %+v, want the folded service's check projected onto it", vm.Availability)
- }
- if !hasChecksEdgeTo(endpoint, vmID) {
- t.Fatalf("check relationships = %+v, want the checks edge to follow the fold to %s", endpoint, vmID)
- }
+ if vm == nil || vm.Docker == nil {
+ t.Fatalf("linked VM %s = %+v, want it to carry the folded service's Docker facet", vmID, vm)
+ }
+ if vm.Availability == nil || vm.Availability.TargetID != checkID {
+ t.Fatalf("linked VM availability = %+v, want the folded service's check projected onto it", vm.Availability)
+ }
+ if !hasChecksEdgeTo(endpoint, vmID) {
+ t.Fatalf("check relationships = %+v, want the checks edge to follow the fold to %s", endpoint, vmID)
+ }
+ })
+
+ // A Proxmox storage, a TrueNAS VM and a vSphere VM linked in a cycle keep
+ // the TrueNAS VM, whose link is the oldest. A pass after the TrueNAS
+ // records has already folded that VM into the storage when the vSphere
+ // records bring a guest that outranks the storage, so folding as the
+ // sources arrive keeps the vSphere VM instead.
+ t.Run("a chain of links is judged over the assembled estate", func(t *testing.T) {
+ soleSource := func(resource unifiedresources.Resource, source unifiedresources.DataSource) bool {
+ return len(resource.Sources) == 1 && resource.Sources[0] == source
+ }
+ var storageID, nasVMID, guestID string
+ for _, resource := range unlinked {
+ switch {
+ case storageID == "" && resource.Type == unifiedresources.ResourceTypeStorage &&
+ soleSource(resource, unifiedresources.SourceProxmox):
+ storageID = resource.ID
+ case nasVMID == "" && resource.Type == unifiedresources.ResourceTypeVM &&
+ soleSource(resource, unifiedresources.SourceTrueNAS):
+ nasVMID = resource.ID
+ case guestID == "" && resource.Type == unifiedresources.ResourceTypeVM &&
+ soleSource(resource, unifiedresources.SourceVMware):
+ guestID = resource.ID
+ }
+ }
+ if storageID == "" || nasVMID == "" || guestID == "" {
+ t.Fatalf("fixture graph needs a Proxmox storage, a TrueNAS VM and a vSphere VM, got storage=%q nas=%q guest=%q",
+ storageID, nasVMID, guestID)
+ }
+ created := time.Date(2026, time.October, 1, 9, 0, 0, 0, time.UTC)
+ links := []unifiedresources.ResourceLink{
+ {ResourceA: nasVMID, ResourceB: storageID, PrimaryID: storageID, CreatedAt: created.Add(time.Minute)},
+ {ResourceA: storageID, ResourceB: guestID, PrimaryID: guestID, CreatedAt: created.Add(2 * time.Minute)},
+ {ResourceA: guestID, ResourceB: nasVMID, PrimaryID: nasVMID, CreatedAt: created},
+ }
+ // cycleRows is what is left of the three members: type, ID and sources.
+ cycleRows := func(resources []unifiedresources.Resource) []string {
+ var rows []string
+ for _, resource := range resources {
+ if resource.ID != storageID && resource.ID != nasVMID && resource.ID != guestID {
+ continue
+ }
+ sources := make([]string, 0, len(resource.Sources))
+ for _, source := range resource.Sources {
+ sources = append(sources, string(source))
+ }
+ slices.Sort(sources)
+ rows = append(rows, fmt.Sprintf("%s %s %v", resource.Type, resource.ID, sources))
+ }
+ return rows
+ }
+ owned := SupplementalOwnedSources()
+ snapshot := unifiedresources.SnapshotWithoutSources(graph.State, owned)
+ records := make(map[unifiedresources.DataSource][]unifiedresources.IngestRecord, len(owned))
+ for _, source := range owned {
+ records[source] = graph.SupplementalRecords(source)
+ }
+
+ // The monitor's rebuild is the reference the mock build must match.
+ store := unifiedresources.NewMemoryStore()
+ for _, link := range links {
+ if err := store.AddLink(link); err != nil {
+ t.Fatalf("add link: %v", err)
+ }
+ }
+ adapter := unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store))
+ adapter.PopulateSnapshotAndSupplemental(snapshot, records)
+ live := cycleRows(adapter.GetAll())
+ if len(live) != 1 || !strings.HasPrefix(live[0], "vm "+nasVMID+" ") {
+ t.Fatalf("live rebuild kept %v, want the TrueNAS VM %s alone", live, nasVMID)
+ }
+
+ // A registry that ingests the same sources one call at a time judges
+ // the chain at each call. It must settle elsewhere, or this fixture no
+ // longer separates the boundary from per-call passes.
+ perCall := unifiedresources.NewRegistryWithManualLinks(links)
+ perCall.IngestSnapshot(snapshot)
+ for _, source := range owned {
+ if len(records[source]) > 0 {
+ perCall.IngestRecords(source, records[source])
+ }
+ }
+ if got := cycleRows(perCall.List()); slices.Equal(got, live) {
+ t.Fatalf("a pass per source also kept %v, so this fixture no longer separates the rebuild's boundary from per-call passes", got)
+ }
+
+ linked, _ := graph.unifiedResourceSnapshot(unifiedresources.NewRegistryWithManualLinks(links))
+ if got := cycleRows(linked); !slices.Equal(got, live) {
+ t.Fatalf("mock build kept %v, want what the live rebuild keeps: %v", got, live)
+ }
+ })
}
// TestUnifiedResourceSnapshotWithLinksLeavesTheSharedSnapshotUnlinked pins the
diff --git a/internal/unifiedresources/manual_links.go b/internal/unifiedresources/manual_links.go
index 0d4de9097c..00a06e678c 100644
--- a/internal/unifiedresources/manual_links.go
+++ b/internal/unifiedresources/manual_links.go
@@ -1,6 +1,9 @@
package unifiedresources
-import "slices"
+import (
+ "slices"
+ "time"
+)
// NewRegistryWithManualLinks creates a registry that applies the given
// operator links on every ingest but has no store behind it. Read views built
@@ -8,13 +11,45 @@ import "slices"
// fixture graph, use it to show the operator's links the way the store-backed
// registry does, while nothing they ingest can persist identity pins,
// canonical-ID successions or change records. It carries no exclusions, so
-// its identity matching and ListForPresentation see none.
+// its identity matching and ListForPresentation see none. A builder that
+// ingests the snapshot and several record sources in turn calls
+// DeferManualLinks first, so the links are judged once over the whole estate
+// as the monitor's rebuild does.
func NewRegistryWithManualLinks(links []ResourceLink) *ResourceRegistry {
rr := NewRegistry(nil)
rr.links = slices.Clone(links)
return rr
}
+// DeferManualLinks holds the link pass back from this registry's snapshot and
+// record ingests until ApplyDeferredManualLinks, the boundary the monitor's
+// rebuild draws (MonitorAdapter.replaceRegistryLocked): a chain of links is
+// judged over every member's source at once, because a fold cannot be undone
+// when a later source brings a member that outranks the earlier choice. The
+// caller ingests availability checks after ApplyDeferredManualLinks, so a
+// check linked to a folded resource projects onto its primary. A registry with
+// no links has no pass to hold back and ingests as it always did.
+func (rr *ResourceRegistry) DeferManualLinks() {
+ rr.mu.Lock()
+ defer rr.mu.Unlock()
+ if len(rr.links) == 0 {
+ return
+ }
+ rr.deferManualLinks = true
+}
+
+// ApplyDeferredManualLinks runs the link pass DeferManualLinks held back, then
+// refreshes what folding changes. Freshness is judged by thresholds, which the
+// caller passes as it passed them to the ingests (nil takes the registry's own,
+// as IngestSnapshot and IngestRecords do): a source whose reading is stale
+// under one set can be current under the other, and the merge keeps the
+// current one. It does nothing once the pass has run, or on a registry that
+// was not deferring, so a builder may call it at every boundary without
+// tracking whether the pass already ran.
+func (rr *ResourceRegistry) ApplyDeferredManualLinks(thresholds map[DataSource]time.Duration) {
+ rr.applyDeferredManualLinks(rr.thresholdsOrOwn(thresholds))
+}
+
// ManualLinks returns the operator's manual links that the adapter's current
// registry generation applied, as loaded from its store when that generation
// was built. A link added to the store since then appears after the next
diff --git a/internal/unifiedresources/registry_merge_policy_test.go b/internal/unifiedresources/registry_merge_policy_test.go
index b10e66d7d8..7eae5da870 100644
--- a/internal/unifiedresources/registry_merge_policy_test.go
+++ b/internal/unifiedresources/registry_merge_policy_test.go
@@ -4579,3 +4579,167 @@ func linkedDiskRowsOn(t *testing.T, resources []Resource) linkedDiskRows {
}
return rows
}
+
+// TestRegistryHoldsManualLinksBackUntilTheDeferredPass pins the exported
+// boundary a builder outside the monitor draws (the mock fixture build): once
+// DeferManualLinks is called the snapshot and record ingests leave every
+// member standing, ApplyDeferredManualLinks folds them in one pass, and a
+// second call changes nothing. A registry with no links has no pass to hold
+// back, so the call leaves it ingesting as before.
+func TestRegistryHoldsManualLinksBackUntilTheDeferredPass(t *testing.T) {
+ now := time.Now().UTC()
+ nas := IngestRecord{
+ SourceID: "system:tn-1:vm:nas-vm",
+ Resource: Resource{Type: ResourceTypeVM, Name: "nas-vm", Status: StatusOnline, LastSeen: now},
+ }
+ guest := IngestRecord{
+ SourceID: "vc-1:vm:vm-42",
+ Resource: Resource{
+ Type: ResourceTypeVM, Technology: "vmware", Name: "app-guest", Status: StatusOnline, LastSeen: now,
+ VMware: &VMwareData{ConnectionID: "vc-1", ManagedObjectID: "vm-42", EntityType: "vm"},
+ },
+ Identity: ResourceIdentity{Hostnames: []string{"app-guest"}},
+ }
+ snapshot := models.StateSnapshot{
+ LastUpdate: now,
+ VMs: []models.VM{
+ {ID: "lab:pve1:101", VMID: 101, Name: "web", Node: "pve1", Instance: "lab", Status: "running", Type: "qemu", LastSeen: now},
+ },
+ Hosts: []models.Host{
+ {ID: "host-app", Hostname: "app-agent", MachineID: "0123456789abcdef", Status: "online", LastSeen: now},
+ },
+ }
+ // The snapshot brings a Proxmox VM and an agent, the records bring a
+ // TrueNAS VM and a vSphere VM; one link joins each pair.
+ ingest := func(rr *ResourceRegistry, afterSnapshot func()) {
+ rr.IngestSnapshot(snapshot)
+ if afterSnapshot != nil {
+ afterSnapshot()
+ }
+ rr.IngestRecords(SourceTrueNAS, []IngestRecord{nas})
+ rr.IngestRecords(SourceVMware, []IngestRecord{guest})
+ }
+
+ unlinked := NewRegistry(nil)
+ ingest(unlinked, nil)
+ ids := map[string]string{}
+ for _, resource := range unlinked.List() {
+ ids[resource.Name] = resource.ID
+ }
+ if len(ids) != 4 || ids["web"] == "" || ids["app-agent"] == "" || ids["nas-vm"] == "" || ids["app-guest"] == "" {
+ t.Fatalf("unlinked estate = %v, want the VM, the agent, the TrueNAS VM and the vSphere VM", ids)
+ }
+ links := []ResourceLink{
+ {ResourceA: ids["app-agent"], ResourceB: ids["web"], PrimaryID: ids["web"]},
+ {ResourceA: ids["nas-vm"], ResourceB: ids["app-guest"], PrimaryID: ids["app-guest"]},
+ }
+ wantAfter := []string{ids["app-guest"], ids["web"]}
+ slices.Sort(wantAfter)
+ listed := func(rr *ResourceRegistry) []string {
+ got := resourceIDs(rr.List())
+ slices.Sort(got)
+ return got
+ }
+
+ eager := NewRegistryWithManualLinks(links)
+ ingest(eager, nil)
+ if got := listed(eager); !slices.Equal(got, wantAfter) {
+ t.Fatalf("a registry that was not deferred listed %v, want %v", got, wantAfter)
+ }
+
+ deferred := NewRegistryWithManualLinks(links)
+ deferred.DeferManualLinks()
+ ingest(deferred, func() {
+ // The link between the snapshot's own members waits too.
+ if got := listed(deferred); len(got) != 2 {
+ t.Fatalf("a deferred registry listed %v after the snapshot, want both snapshot members standing", got)
+ }
+ })
+ if got := listed(deferred); len(got) != 4 {
+ t.Fatalf("a deferred registry listed %v before the pass, want every member standing", got)
+ }
+ deferred.ApplyDeferredManualLinks(nil)
+ if got := listed(deferred); !slices.Equal(got, wantAfter) {
+ t.Fatalf("a deferred registry listed %v after the pass, want %v", got, wantAfter)
+ }
+ folded, _ := deferred.Get(ids["app-guest"])
+ for _, source := range []DataSource{SourceTrueNAS, SourceVMware} {
+ if !slices.Contains(folded.Sources, source) {
+ t.Fatalf("folded row sources = %v, want %s among them", folded.Sources, source)
+ }
+ }
+ deferred.ApplyDeferredManualLinks(nil)
+ if got := listed(deferred); !slices.Equal(got, wantAfter) {
+ t.Fatalf("a second deferred pass listed %v, want the same rows %v", got, wantAfter)
+ }
+
+ plain := NewRegistry(nil)
+ plain.DeferManualLinks()
+ if plain.deferManualLinks {
+ t.Fatal("a registry with no links holds a pass back that has nothing to fold")
+ }
+ plain.ApplyDeferredManualLinks(nil)
+}
+
+// TestRegistryDeferredLinkPassJudgesFreshnessByTheCallersThresholds pins the
+// thresholds ApplyDeferredManualLinks takes: a vSphere disk reading three
+// minutes old is current under the five minutes the ingests were given, so the
+// guest keeps it over the agent's, and stale under the two-minute default,
+// where the fresh agent's reading replaces it.
+func TestRegistryDeferredLinkPassJudgesFreshnessByTheCallersThresholds(t *testing.T) {
+ now := time.Now().UTC()
+ total, used := int64(8<<30), int64(3<<30)
+ guest := IngestRecord{
+ SourceID: "vc-1:vm:vm-42",
+ Resource: Resource{
+ Type: ResourceTypeVM, Technology: "vmware", Name: "app-guest", Status: StatusOnline,
+ LastSeen: now.Add(-3 * time.Minute),
+ VMware: &VMwareData{ConnectionID: "vc-1", ManagedObjectID: "vm-42", EntityType: "vm"},
+ Metrics: &ResourceMetrics{
+ Disk: &MetricValue{Value: 20, Percent: 20, Used: &used, Total: &total, Source: SourceVMware},
+ },
+ },
+ Identity: ResourceIdentity{Hostnames: []string{"app-guest"}},
+ }
+ snapshot := models.StateSnapshot{
+ LastUpdate: now,
+ Hosts: []models.Host{{
+ ID: "host-app", Hostname: "app-agent", MachineID: "0123456789abcdef", Status: "online", LastSeen: now,
+ Disks: []models.Disk{{Total: 100 << 30, Used: 80 << 30, Free: 20 << 30, Usage: 80, Mountpoint: "/"}},
+ }},
+ }
+ thresholds := map[DataSource]time.Duration{SourceVMware: 5 * time.Minute, SourceAgent: 5 * time.Minute}
+ ingest := func(rr *ResourceRegistry) {
+ rr.IngestSnapshotWithStaleThresholds(snapshot, thresholds)
+ rr.IngestRecordsWithStaleThresholds(SourceVMware, []IngestRecord{guest}, thresholds)
+ }
+
+ unlinked := NewRegistry(nil)
+ ingest(unlinked)
+ ids := map[string]string{}
+ for _, resource := range unlinked.List() {
+ ids[resource.Name] = resource.ID
+ }
+ if len(ids) != 2 || ids["app-agent"] == "" || ids["app-guest"] == "" {
+ t.Fatalf("unlinked estate = %v, want the agent and the vSphere VM", ids)
+ }
+ links := []ResourceLink{{ResourceA: ids["app-agent"], ResourceB: ids["app-guest"], PrimaryID: ids["app-guest"]}}
+
+ diskSource := func(applyWith map[DataSource]time.Duration) DataSource {
+ rr := NewRegistryWithManualLinks(links)
+ rr.DeferManualLinks()
+ ingest(rr)
+ rr.ApplyDeferredManualLinks(applyWith)
+ row, ok := rr.Get(ids["app-guest"])
+ if !ok || row.Metrics == nil || row.Metrics.Disk == nil {
+ t.Fatalf("merged guest = %+v, want it listed with a disk reading", row)
+ }
+ return row.Metrics.Disk.Source
+ }
+ if got := diskSource(thresholds); got != SourceVMware {
+ t.Fatalf("deferred pass with the ingests' thresholds took the disk reading from %q, want the current vSphere one", got)
+ }
+ if got := diskSource(nil); got != SourceAgent {
+ t.Fatalf("deferred pass with default thresholds took the disk reading from %q, want the fresh agent's (this scenario no longer separates the thresholds)", got)
+ }
+}