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.

Canonicalize top-level infrastructure counting

rcourtmana2b9723db9d5
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 455bc0a4ba..4fa2721420 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -30,7 +30,8 @@ truth for live infrastructure data.
6. `internal/unifiedresources/read_state.go`
7. `internal/unifiedresources/monitor_adapter.go`
8. `internal/unifiedresources/views.go`
-9. `docker-entrypoint.sh`
+9. `internal/monitoring/connected_infrastructure.go`
+10. `docker-entrypoint.sh`
## Shared Boundaries
@@ -152,6 +153,12 @@ versus `pve-a`.
Connected infrastructure and monitored-system projections now also use the
shared unified-resource display-name fallback, so the monitoring layer does
not rebuild its own canonical name-or-hostname selection for those surfaces.
+Connected infrastructure now also consumes the shared top-level system
+resolver from unified resources instead of maintaining an independent
+machine/hostname grouping heuristic. Monitoring-owned inventory surfaces must
+therefore stay aligned with the monitored-system ledger on one canonical
+top-level system identity contract, and that contract must not count friendly
+display names as identity.
Storage-backup preservation now also derives node-to-storage membership from
canonical `ReadState.StoragePools()` instead of from snapshot-owned storage
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index db82a3c1b8..8139dc6e5c 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -38,42 +38,43 @@ cross-source deduplication.
16. `internal/unifiedresources/kubernetes_capabilities.go`
17. `internal/unifiedresources/pbs_rollups.go`
18. `internal/unifiedresources/monitored_systems.go`
-19. `internal/unifiedresources/capabilities.go`
-20. `internal/unifiedresources/changes.go`
-21. `internal/unifiedresources/relationships.go`
-22. `internal/unifiedresources/privacy.go`
-23. `internal/unifiedresources/actions.go`
-24. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`
-25. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`
-26. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`
-27. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerSupportDisclosure.tsx`
-28. `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`
-29. `frontend-modern/src/components/Infrastructure/UnifiedResourceHostTableCard.tsx`
-30. `frontend-modern/src/components/Infrastructure/UnifiedResourcePBSTableSection.tsx`
-31. `frontend-modern/src/components/Infrastructure/UnifiedResourcePMGTableSection.tsx`
-32. `frontend-modern/src/components/Infrastructure/UnifiedResourceServiceInfrastructureCard.tsx`
-33. `frontend-modern/src/components/Infrastructure/unifiedResourceTableModel.ts`
-34. `frontend-modern/src/components/Infrastructure/unifiedResourceTableStateModel.ts`
-35. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts`
-36. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerServiceModel.ts`
-37. `frontend-modern/src/components/Infrastructure/resourceDetailDiscoveryModel.ts`
-38. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerOperationalModel.ts`
-39. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerHistoryState.ts`
-40. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDockerActionsState.ts`
-41. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`
-42. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts`
-43. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableViewportSync.ts`
-44. `frontend-modern/src/components/Discovery/DiscoveryTab.tsx`
-45. `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts`
-46. `frontend-modern/src/features/infrastructure/InfrastructurePageSurface.tsx`
-47. `frontend-modern/src/features/infrastructure/useInfrastructurePageRouteState.ts`
-48. `frontend-modern/src/features/infrastructure/useInfrastructurePageState.ts`
-49. `frontend-modern/src/features/infrastructure/infrastructurePageModel.ts`
-50. `frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx`
-51. `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`
-52. `frontend-modern/src/components/Infrastructure/infrastructureSummaryModel.ts`
-53. `frontend-modern/src/utils/resourceIdentity.ts`
-54. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerIdentityModel.ts`
+19. `internal/unifiedresources/top_level_systems.go`
+20. `internal/unifiedresources/capabilities.go`
+21. `internal/unifiedresources/changes.go`
+22. `internal/unifiedresources/relationships.go`
+23. `internal/unifiedresources/privacy.go`
+24. `internal/unifiedresources/actions.go`
+25. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawer.tsx`
+26. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerOverviewTab.tsx`
+27. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerDebugTab.tsx`
+28. `frontend-modern/src/components/Infrastructure/ResourceDetailDrawerSupportDisclosure.tsx`
+29. `frontend-modern/src/components/Infrastructure/ResourceFacetSummary.tsx`
+30. `frontend-modern/src/components/Infrastructure/UnifiedResourceHostTableCard.tsx`
+31. `frontend-modern/src/components/Infrastructure/UnifiedResourcePBSTableSection.tsx`
+32. `frontend-modern/src/components/Infrastructure/UnifiedResourcePMGTableSection.tsx`
+33. `frontend-modern/src/components/Infrastructure/UnifiedResourceServiceInfrastructureCard.tsx`
+34. `frontend-modern/src/components/Infrastructure/unifiedResourceTableModel.ts`
+35. `frontend-modern/src/components/Infrastructure/unifiedResourceTableStateModel.ts`
+36. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDerivedState.ts`
+37. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerServiceModel.ts`
+38. `frontend-modern/src/components/Infrastructure/resourceDetailDiscoveryModel.ts`
+39. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerOperationalModel.ts`
+40. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerHistoryState.ts`
+41. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerDockerActionsState.ts`
+42. `frontend-modern/src/components/Infrastructure/useResourceDetailDrawerState.ts`
+43. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableState.ts`
+44. `frontend-modern/src/components/Infrastructure/useUnifiedResourceTableViewportSync.ts`
+45. `frontend-modern/src/components/Discovery/DiscoveryTab.tsx`
+46. `frontend-modern/src/components/Discovery/useDiscoveryTabState.ts`
+47. `frontend-modern/src/features/infrastructure/InfrastructurePageSurface.tsx`
+48. `frontend-modern/src/features/infrastructure/useInfrastructurePageRouteState.ts`
+49. `frontend-modern/src/features/infrastructure/useInfrastructurePageState.ts`
+50. `frontend-modern/src/features/infrastructure/infrastructurePageModel.ts`
+51. `frontend-modern/src/components/Infrastructure/InfrastructureSummary.tsx`
+52. `frontend-modern/src/components/Infrastructure/useInfrastructureSummaryState.ts`
+53. `frontend-modern/src/components/Infrastructure/infrastructureSummaryModel.ts`
+54. `frontend-modern/src/utils/resourceIdentity.ts`
+55. `frontend-modern/src/components/Infrastructure/resourceDetailDrawerIdentityModel.ts`
## Shared Boundaries
@@ -149,6 +150,13 @@ the API cannot supply machine-level identity signals; the code may borrow
machine-id and MAC evidence from a uniquely matched host agent, but duplicate
short hostnames across domains or clusters stay an unresolved ambiguity rather
than being force-merged into a stronger canonical identity.
+The canonical monitored-system and connected-infrastructure grouping contract
+now lives in `internal/unifiedresources/top_level_systems.go`. Top-level
+system identity may merge on strong runtime identity such as machine IDs,
+agent IDs, connector-stable primary IDs, or the existing high-confidence
+identity matcher, and it may use exact-host attachment only as a bounded
+fallback onto a uniquely better existing surface. Friendly display names are
+presentation-only and must not participate in monitored-system counting.
The unified-resource runtime now also owns the durable change timeline for the
canonical resource view. `internal/unifiedresources/monitor_adapter.go` feeds
diff --git a/internal/monitoring/canonical_guardrails_test.go b/internal/monitoring/canonical_guardrails_test.go
index 7fde95c879..b67addb1c1 100644
--- a/internal/monitoring/canonical_guardrails_test.go
+++ b/internal/monitoring/canonical_guardrails_test.go
@@ -60,6 +60,23 @@ func TestNoGetStateResourceArrayRegression(t *testing.T) {
}
}
+func TestConnectedInfrastructureUsesSharedTopLevelSystemResolver(t *testing.T) {
+ data, err := os.ReadFile("connected_infrastructure.go")
+ if err != nil {
+ t.Fatalf("failed to read connected_infrastructure.go: %v", err)
+ }
+ source := string(data)
+ requiredSnippets := []string{
+ "resolver := unifiedresources.ResolveTopLevelSystems(resources)",
+ "key := resolver.GroupIDForResource(resource)",
+ }
+ for _, snippet := range requiredSnippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("connected_infrastructure.go must contain %q", snippet)
+ }
+ }
+}
+
func TestLegacyMemorySourceAliasesRemainCanonicalized(t *testing.T) {
t.Parallel()
diff --git a/internal/monitoring/connected_infrastructure.go b/internal/monitoring/connected_infrastructure.go
index 7bea7cd857..aa1334963e 100644
--- a/internal/monitoring/connected_infrastructure.go
+++ b/internal/monitoring/connected_infrastructure.go
@@ -33,9 +33,10 @@ func buildConnectedInfrastructure(
snapshot models.StateSnapshot,
) []models.ConnectedInfrastructureItemFrontend {
groups := make(map[string]*connectedInfrastructureGroup)
+ resolver := unifiedresources.ResolveTopLevelSystems(resources)
for _, resource := range resources {
- appendConnectedInfrastructureSurfaces(groups, resource)
+ appendConnectedInfrastructureSurfaces(groups, resource, resolver)
}
applyConnectedInfrastructureIgnoreState(groups, snapshot)
@@ -204,24 +205,25 @@ func applyConnectedInfrastructureIgnoreState(
func appendConnectedInfrastructureSurfaces(
groups map[string]*connectedInfrastructureGroup,
resource unifiedresources.Resource,
+ resolver unifiedresources.TopLevelSystemResolver,
) {
if surface, ok := connectedInfrastructureAgentSurface(resource); ok {
- addConnectedInfrastructureSurface(groups, resource, surface)
+ addConnectedInfrastructureSurface(groups, resource, surface, resolver)
}
if surface, ok := connectedInfrastructureDockerSurface(resource); ok {
- addConnectedInfrastructureSurface(groups, resource, surface)
+ addConnectedInfrastructureSurface(groups, resource, surface, resolver)
}
if surface, ok := connectedInfrastructureKubernetesSurface(resource); ok {
- addConnectedInfrastructureSurface(groups, resource, surface)
+ addConnectedInfrastructureSurface(groups, resource, surface, resolver)
}
if surface, ok := connectedInfrastructureProxmoxSurface(resource); ok {
- addConnectedInfrastructureSurface(groups, resource, surface)
+ addConnectedInfrastructureSurface(groups, resource, surface, resolver)
}
if surface, ok := connectedInfrastructurePBSSurface(resource); ok {
- addConnectedInfrastructureSurface(groups, resource, surface)
+ addConnectedInfrastructureSurface(groups, resource, surface, resolver)
}
if surface, ok := connectedInfrastructurePMGSurface(resource); ok {
- addConnectedInfrastructureSurface(groups, resource, surface)
+ addConnectedInfrastructureSurface(groups, resource, surface, resolver)
}
}
@@ -229,8 +231,12 @@ func addConnectedInfrastructureSurface(
groups map[string]*connectedInfrastructureGroup,
resource unifiedresources.Resource,
surface models.ConnectedInfrastructureSurfaceFrontend,
+ resolver unifiedresources.TopLevelSystemResolver,
) {
- key := connectedInfrastructureGroupKey(resource, surface.Kind)
+ key := resolver.GroupIDForResource(resource)
+ if strings.TrimSpace(key) == "" {
+ key = connectedInfrastructureGroupKey(resource, surface.Kind)
+ }
group, exists := groups[key]
if !exists {
group = &connectedInfrastructureGroup{
diff --git a/internal/monitoring/connected_infrastructure_test.go b/internal/monitoring/connected_infrastructure_test.go
index 25970979ad..2e759971b8 100644
--- a/internal/monitoring/connected_infrastructure_test.go
+++ b/internal/monitoring/connected_infrastructure_test.go
@@ -110,3 +110,47 @@ func TestBuildConnectedInfrastructure_UsesSharedDisplayNameFallback(t *testing.T
t.Fatalf("expected canonical display name to drive displayName, got %q", item.DisplayName)
}
}
+
+func TestBuildConnectedInfrastructure_UsesSharedTopLevelSystemGrouping(t *testing.T) {
+ now := time.Unix(1_700_000_000, 0)
+ items := buildConnectedInfrastructure([]unifiedresources.Resource{
+ {
+ ID: "tower-agent",
+ Name: "Tower Agent",
+ LastSeen: now,
+ Status: unifiedresources.StatusOnline,
+ Agent: &unifiedresources.AgentData{
+ AgentID: "tower-agent",
+ AgentVersion: "1.2.3",
+ Hostname: "tower.local",
+ },
+ Identity: unifiedresources.ResourceIdentity{
+ Hostnames: []string{"tower.local"},
+ },
+ },
+ {
+ ID: "tower-pbs",
+ Name: "Tower PBS",
+ LastSeen: now,
+ Status: unifiedresources.StatusOnline,
+ PBS: &unifiedresources.PBSData{
+ InstanceID: "pbs-1",
+ Hostname: "tower.local",
+ HostURL: "https://tower.local:8007",
+ Version: "3.4.1",
+ },
+ },
+ }, models.StateSnapshot{})
+
+ if len(items) != 1 {
+ t.Fatalf("expected one connected infrastructure item after shared grouping, got %d", len(items))
+ }
+
+ item := items[0]
+ if len(item.Surfaces) != 2 {
+ t.Fatalf("expected host telemetry and PBS surfaces on one item, got %#v", item.Surfaces)
+ }
+ if item.ID == "resource:tower-pbs" {
+ t.Fatalf("expected PBS surface to attach to the shared top-level system group, got %q", item.ID)
+ }
+}
diff --git a/internal/unifiedresources/code_standards_test.go b/internal/unifiedresources/code_standards_test.go
index 21a380c20e..22b722020d 100644
--- a/internal/unifiedresources/code_standards_test.go
+++ b/internal/unifiedresources/code_standards_test.go
@@ -589,6 +589,32 @@ func TestResourceDisplayNameUsedByInfrastructureConsumers(t *testing.T) {
}
}
+func TestTopLevelSystemResolverPinsCanonicalInfrastructureCounting(t *testing.T) {
+ requiredSnippets := map[string][]string{
+ filepath.Join(".", "monitored_systems.go"): {
+ "resolveMonitoredSystemTopLevelSystems(rs).Count()",
+ "ResolveTopLevelSystems(resources)",
+ },
+ filepath.Join(".", "top_level_systems.go"): {
+ "ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver",
+ "match.Confidence < HighConfidenceThreshold",
+ "monitoredSystemCandidateAllowsHostAttachment(candidate)",
+ },
+ }
+ for name, snippets := range requiredSnippets {
+ data, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatalf("failed to read %s: %v", name, err)
+ }
+ source := string(data)
+ for _, snippet := range snippets {
+ if !strings.Contains(source, snippet) {
+ t.Fatalf("%s must contain %q", name, snippet)
+ }
+ }
+ }
+}
+
func TestResourceTimelineStoreIndexesSupportFilteredReads(t *testing.T) {
data, err := os.ReadFile(filepath.Join("store.go"))
if err != nil {
diff --git a/internal/unifiedresources/monitored_systems.go b/internal/unifiedresources/monitored_systems.go
index 2258f1fae9..673a9f536b 100644
--- a/internal/unifiedresources/monitored_systems.go
+++ b/internal/unifiedresources/monitored_systems.go
@@ -1,7 +1,6 @@
package unifiedresources
import (
- "net"
"sort"
"strings"
"time"
@@ -33,17 +32,13 @@ type MonitoredSystemRecord struct {
// canonical cross-view deduplication. Child resources are intentionally
// excluded.
func MonitoredSystemCount(rs ReadState) int {
- return len(monitoredSystemGroups(rs))
+ return resolveMonitoredSystemTopLevelSystems(rs).Count()
}
// MonitoredSystems returns the canonical counted monitored systems after
// deduping overlapping top-level roots across collection paths.
func MonitoredSystems(rs ReadState) []MonitoredSystemRecord {
- groups := monitoredSystemGroups(rs)
- records := make([]MonitoredSystemRecord, 0, len(groups))
- for _, group := range groups {
- records = append(records, monitoredSystemRecord(group))
- }
+ records := resolveMonitoredSystemTopLevelSystems(rs).records()
sort.Slice(records, func(i, j int) bool {
if records[i].Name != records[j].Name {
return records[i].Name < records[j].Name
@@ -62,20 +57,7 @@ func MonitoredSystems(rs ReadState) []MonitoredSystemRecord {
// HasMatchingMonitoredSystem reports whether a prospective monitored system
// would dedupe onto an already-counted top-level monitored system.
func HasMatchingMonitoredSystem(rs ReadState, candidate MonitoredSystemCandidate) bool {
- candidateKeys := monitoredSystemCandidateKeys(candidate)
- if len(candidateKeys) == 0 {
- return false
- }
-
- for _, group := range monitoredSystemGroups(rs) {
- for key := range candidateKeys {
- if _, ok := group.keys[key]; ok {
- return true
- }
- }
- }
-
- return false
+ return resolveMonitoredSystemTopLevelSystems(rs).HasMatchingCandidate(candidate)
}
type monitoredSystemGroup struct {
@@ -84,46 +66,14 @@ type monitoredSystemGroup struct {
}
func monitoredSystemGroups(rs ReadState) []monitoredSystemGroup {
- roots := monitoredSystemRoots(rs)
- groups := make([]monitoredSystemGroup, 0, len(roots))
-
- for _, resource := range roots {
- keys := monitoredSystemResourceKeys(resource)
- matched := -1
- for i := range groups {
- if monitoredSystemKeySetsOverlap(groups[i].keys, keys) {
- matched = i
- break
- }
- }
-
- if matched == -1 {
- groups = append(groups, monitoredSystemGroup{
- keys: cloneStringSet(keys),
- resources: []*Resource{resource},
- })
- continue
- }
-
- for key := range keys {
- groups[matched].keys[key] = struct{}{}
- }
- groups[matched].resources = append(groups[matched].resources, resource)
-
- // Collapse any later groups that now overlap transitively.
- for i := matched + 1; i < len(groups); {
- if !monitoredSystemKeySetsOverlap(groups[matched].keys, groups[i].keys) {
- i++
- continue
- }
- for key := range groups[i].keys {
- groups[matched].keys[key] = struct{}{}
- }
- groups[matched].resources = append(groups[matched].resources, groups[i].resources...)
- groups = append(groups[:i], groups[i+1:]...)
- }
+ resolver := resolveMonitoredSystemTopLevelSystems(rs)
+ groups := make([]monitoredSystemGroup, 0, len(resolver.groups))
+ for _, group := range resolver.groups {
+ groups = append(groups, monitoredSystemGroup{
+ keys: cloneStringSet(group.strongIDs),
+ resources: group.resources,
+ })
}
-
return groups
}
@@ -161,6 +111,18 @@ func monitoredSystemRoots(rs ReadState) []*Resource {
return roots
}
+func resolveMonitoredSystemTopLevelSystems(rs ReadState) TopLevelSystemResolver {
+ roots := monitoredSystemRoots(rs)
+ resources := make([]Resource, 0, len(roots))
+ for _, resource := range roots {
+ if resource == nil {
+ continue
+ }
+ resources = append(resources, *resource)
+ }
+ return ResolveTopLevelSystems(resources)
+}
+
func monitoredSystemRecord(group monitoredSystemGroup) MonitoredSystemRecord {
resource := preferredMonitoredSystemResource(group.resources)
record := MonitoredSystemRecord{
@@ -378,139 +340,6 @@ func monitoredSystemPrimarySource(resource *Resource) string {
return ""
}
-func monitoredSystemResourceKeys(resource *Resource) map[string]struct{} {
- keys := make(map[string]struct{})
- if resource == nil {
- return keys
- }
-
- addMonitoredSystemCanonicalKeys(keys, resource.Canonical)
-
- switch CanonicalResourceType(resource.Type) {
- case ResourceTypeAgent:
- addMonitoredSystemTokens(keys, "host", resource.Name)
- addMonitoredSystemTokens(keys, "host", resource.Identity.Hostnames...)
- addMonitoredSystemTokens(keys, "ip", resource.Identity.IPAddresses...)
- addMonitoredSystemTokens(keys, "machine", resource.Identity.MachineID)
- addMonitoredSystemTokens(keys, "resource", resource.ID)
- if resource.Agent != nil {
- addMonitoredSystemTokens(keys, "host", resource.Agent.Hostname)
- addMonitoredSystemTokens(keys, "machine", resource.Agent.MachineID)
- addMonitoredSystemTokens(keys, "agent", resource.Agent.AgentID)
- }
- if resource.Proxmox != nil {
- addMonitoredSystemTokens(keys, "host", resource.Proxmox.NodeName)
- addMonitoredSystemTokens(keys, "proxmox", resource.Proxmox.SourceID)
- addMonitoredSystemHostURL(keys, resource.Proxmox.HostURL)
- }
- if resource.Docker != nil {
- addMonitoredSystemTokens(keys, "host", resource.Docker.Hostname)
- addMonitoredSystemTokens(keys, "docker", resource.Docker.HostSourceID)
- }
- if resource.TrueNAS != nil {
- addMonitoredSystemTokens(keys, "host", resource.TrueNAS.Hostname)
- }
- case ResourceTypePBS:
- if resource.PBS != nil {
- addMonitoredSystemTokens(keys, "pbs", resource.PBS.InstanceID)
- addMonitoredSystemTokens(keys, "host", resource.PBS.Hostname)
- addMonitoredSystemHostURL(keys, resource.PBS.HostURL)
- }
- case ResourceTypePMG:
- if resource.PMG != nil {
- addMonitoredSystemTokens(keys, "pmg", resource.PMG.InstanceID)
- addMonitoredSystemTokens(keys, "host", resource.PMG.Hostname)
- }
- case ResourceTypeK8sCluster:
- if resource.Kubernetes != nil {
- addMonitoredSystemTokens(keys, "k8s", resource.Kubernetes.ClusterID)
- addMonitoredSystemTokens(keys, "agent", resource.Kubernetes.AgentID)
- addMonitoredSystemHostURL(keys, resource.Kubernetes.Server)
- }
- }
-
- if len(keys) == 0 {
- addMonitoredSystemTokens(keys, "fallback", string(resource.Type)+":"+resource.ID)
- }
-
- return keys
-}
-
-func monitoredSystemCandidateKeys(candidate MonitoredSystemCandidate) map[string]struct{} {
- keys := make(map[string]struct{})
- addMonitoredSystemTokens(keys, "resource", candidate.ResourceID)
- addMonitoredSystemTokens(keys, "host", candidate.Name, candidate.Hostname)
- addMonitoredSystemTokens(keys, "machine", candidate.MachineID)
- addMonitoredSystemTokens(keys, "agent", candidate.AgentID)
- addMonitoredSystemHostURL(keys, candidate.HostURL)
- if len(keys) == 0 {
- addMonitoredSystemTokens(keys, "fallback", string(candidate.Type))
- }
- return keys
-}
-
-func addMonitoredSystemCanonicalKeys(keys map[string]struct{}, canonical *CanonicalIdentity) {
- if canonical == nil {
- return
- }
- addMonitoredSystemTokens(keys, "canonical-primary", canonical.PrimaryID)
- addMonitoredSystemTokens(keys, "host", canonical.Hostname)
- addMonitoredSystemTokens(keys, "canonical-platform", canonical.PlatformID)
- for _, alias := range canonical.Aliases {
- addMonitoredSystemTokens(keys, "canonical-alias", alias)
- }
-}
-
-func addMonitoredSystemHostURL(keys map[string]struct{}, raw string) {
- host := extractHostname(raw)
- if ip := normalizeIPToken(host); ip != "" {
- keys["ip:"+ip] = struct{}{}
- return
- }
- addMonitoredSystemTokens(keys, "host", host)
-}
-
-func addMonitoredSystemTokens(keys map[string]struct{}, namespace string, values ...string) {
- for _, value := range values {
- if normalized := normalizeMonitoredSystemToken(value); normalized != "" {
- keys[namespace+":"+normalized] = struct{}{}
- }
- }
-}
-
-func normalizeMonitoredSystemToken(value string) string {
- trimmed := strings.ToLower(strings.TrimSpace(value))
- if trimmed == "" {
- return ""
- }
- if ip := normalizeIPToken(trimmed); ip != "" {
- return ip
- }
- return trimmed
-}
-
-func normalizeIPToken(value string) string {
- if parsed := net.ParseIP(strings.TrimSpace(value)); parsed != nil {
- return parsed.String()
- }
- return ""
-}
-
-func monitoredSystemKeySetsOverlap(left, right map[string]struct{}) bool {
- if len(left) == 0 || len(right) == 0 {
- return false
- }
- if len(left) > len(right) {
- left, right = right, left
- }
- for key := range left {
- if _, ok := right[key]; ok {
- return true
- }
- }
- return false
-}
-
func cloneStringSet(in map[string]struct{}) map[string]struct{} {
out := make(map[string]struct{}, len(in))
for key := range in {
diff --git a/internal/unifiedresources/monitored_systems_test.go b/internal/unifiedresources/monitored_systems_test.go
index ec6fc4ed65..705cb4963c 100644
--- a/internal/unifiedresources/monitored_systems_test.go
+++ b/internal/unifiedresources/monitored_systems_test.go
@@ -113,3 +113,102 @@ func TestHasMatchingMonitoredSystemMatchesByCanonicalHostIdentity(t *testing.T)
t.Fatal("expected unrelated candidate not to match existing counted system")
}
}
+
+func TestMonitoredSystemCountDoesNotMergeFriendlyNameCollisions(t *testing.T) {
+ registry := NewRegistry(nil)
+ registry.IngestRecords(SourceAgent, []IngestRecord{
+ {
+ SourceID: "host-1",
+ Resource: Resource{
+ ID: "host-1",
+ Type: ResourceTypeAgent,
+ Name: "Production",
+ Status: StatusOnline,
+ Agent: &AgentData{
+ AgentID: "agent-1",
+ Hostname: "alpha.local",
+ MachineID: "machine-1",
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"alpha.local"},
+ },
+ },
+ },
+ {
+ SourceID: "host-2",
+ Resource: Resource{
+ ID: "host-2",
+ Type: ResourceTypeAgent,
+ Name: "Production",
+ Status: StatusOnline,
+ Agent: &AgentData{
+ AgentID: "agent-2",
+ Hostname: "beta.local",
+ MachineID: "machine-2",
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-2",
+ Hostnames: []string{"beta.local"},
+ },
+ },
+ },
+ })
+
+ if got := MonitoredSystemCount(registry); got != 2 {
+ t.Fatalf("MonitoredSystemCount() = %d, want 2", got)
+ }
+
+ if HasMatchingMonitoredSystem(registry, MonitoredSystemCandidate{
+ Type: ResourceTypeAgent,
+ Name: "Production",
+ }) {
+ t.Fatal("expected friendly name alone not to match an existing counted system")
+ }
+}
+
+func TestMonitoredSystemCountExactHostnameFallbackDoesNotMergeEqualPriorityHosts(t *testing.T) {
+ registry := NewRegistry(nil)
+ registry.IngestRecords(SourceAgent, []IngestRecord{
+ {
+ SourceID: "host-1",
+ Resource: Resource{
+ ID: "host-1",
+ Type: ResourceTypeAgent,
+ Name: "one",
+ Status: StatusOnline,
+ Agent: &AgentData{
+ AgentID: "agent-1",
+ Hostname: "shared.local",
+ MachineID: "machine-1",
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-1",
+ Hostnames: []string{"shared.local"},
+ },
+ },
+ },
+ {
+ SourceID: "host-2",
+ Resource: Resource{
+ ID: "host-2",
+ Type: ResourceTypeAgent,
+ Name: "two",
+ Status: StatusOnline,
+ Agent: &AgentData{
+ AgentID: "agent-2",
+ Hostname: "shared.local",
+ MachineID: "machine-2",
+ },
+ Identity: ResourceIdentity{
+ MachineID: "machine-2",
+ Hostnames: []string{"shared.local"},
+ },
+ },
+ },
+ })
+
+ if got := MonitoredSystemCount(registry); got != 2 {
+ t.Fatalf("MonitoredSystemCount() = %d, want 2", got)
+ }
+}
diff --git a/internal/unifiedresources/top_level_systems.go b/internal/unifiedresources/top_level_systems.go
new file mode 100644
index 0000000000..1025e0b594
--- /dev/null
+++ b/internal/unifiedresources/top_level_systems.go
@@ -0,0 +1,686 @@
+package unifiedresources
+
+import (
+ "sort"
+ "strconv"
+ "strings"
+)
+
+// TopLevelSystemResolver groups infrastructure resources into canonical
+// top-level monitored systems using one shared identity contract.
+type TopLevelSystemResolver struct {
+ groups []topLevelSystemResolvedGroup
+ resourceToGroup map[string]string
+}
+
+type topLevelSystemResolvedGroup struct {
+ id string
+ resources []*Resource
+ exactHosts map[string]struct{}
+ exactIPs map[string]struct{}
+ strongIDs map[string]struct{}
+ priority int
+ attachByHost bool
+}
+
+type topLevelSystemNode struct {
+ resource *Resource
+ identity ResourceIdentity
+ strongIDs map[string]struct{}
+ exactHosts map[string]struct{}
+ exactIPs map[string]struct{}
+ priority int
+ attachByHost bool
+}
+
+// ResolveTopLevelSystems builds the shared top-level system grouping used by
+// monitored-system counting and connected-infrastructure inventory surfaces.
+func ResolveTopLevelSystems(resources []Resource) TopLevelSystemResolver {
+ if len(resources) == 0 {
+ return TopLevelSystemResolver{
+ groups: nil,
+ resourceToGroup: map[string]string{},
+ }
+ }
+
+ nodes := make([]topLevelSystemNode, 0, len(resources))
+ for i := range resources {
+ node := buildTopLevelSystemNode(&resources[i])
+ if node.resource == nil {
+ continue
+ }
+ nodes = append(nodes, node)
+ }
+ if len(nodes) == 0 {
+ return TopLevelSystemResolver{
+ groups: nil,
+ resourceToGroup: map[string]string{},
+ }
+ }
+
+ parent := make([]int, len(nodes))
+ for i := range parent {
+ parent[i] = i
+ }
+
+ find := func(id int) int {
+ for parent[id] != id {
+ parent[id] = parent[parent[id]]
+ id = parent[id]
+ }
+ return id
+ }
+
+ union := func(left, right int) {
+ leftRoot := find(left)
+ rightRoot := find(right)
+ if leftRoot == rightRoot {
+ return
+ }
+ parent[leftRoot] = rightRoot
+ }
+
+ strongIDOwners := make(map[string]int)
+ for i := range nodes {
+ for strongID := range nodes[i].strongIDs {
+ if existing, ok := strongIDOwners[strongID]; ok {
+ union(i, existing)
+ continue
+ }
+ strongIDOwners[strongID] = i
+ }
+ }
+
+ matcher := NewIdentityMatcher()
+ nodeIDByMatcherID := make(map[string]int, len(nodes))
+ for i := range nodes {
+ matcherID := topLevelSystemMatcherID(i)
+ nodeIDByMatcherID[matcherID] = i
+ matcher.Add(matcherID, nodes[i].identity)
+ }
+ for i := range nodes {
+ matches := matcher.FindCandidates(nodes[i].identity)
+ for _, match := range matches {
+ if match.Confidence < HighConfidenceThreshold {
+ continue
+ }
+ existingIndex, ok := nodeIDByMatcherID[match.ID]
+ if !ok || existingIndex == i {
+ continue
+ }
+ union(i, existingIndex)
+ }
+ }
+
+ for {
+ initialGroups := buildTopLevelSystemResolvedGroups(nodes, parent)
+ hostOwners, ipOwners := buildTopLevelSystemFallbackOwners(initialGroups)
+ attached := false
+
+ for groupRoot, group := range initialGroups {
+ if !group.attachByHost {
+ continue
+ }
+ targetRoot, ok := uniqueBetterTopLevelSystemTarget(groupRoot, group, hostOwners, ipOwners, initialGroups)
+ if !ok {
+ continue
+ }
+ union(groupRoot, targetRoot)
+ attached = true
+ }
+
+ if !attached {
+ finalGroups := buildTopLevelSystemResolvedGroups(nodes, parent)
+ orderedGroups := make([]topLevelSystemResolvedGroup, 0, len(finalGroups))
+ for _, group := range finalGroups {
+ orderedGroups = append(orderedGroups, group)
+ }
+ sort.Slice(orderedGroups, func(i, j int) bool {
+ if orderedGroups[i].priority != orderedGroups[j].priority {
+ return orderedGroups[i].priority < orderedGroups[j].priority
+ }
+ if len(orderedGroups[i].resources) == 0 || len(orderedGroups[j].resources) == 0 {
+ return orderedGroups[i].id < orderedGroups[j].id
+ }
+ left := monitoredSystemDisplayName(orderedGroups[i].resources, preferredMonitoredSystemResource(orderedGroups[i].resources))
+ right := monitoredSystemDisplayName(orderedGroups[j].resources, preferredMonitoredSystemResource(orderedGroups[j].resources))
+ if left == right {
+ return orderedGroups[i].id < orderedGroups[j].id
+ }
+ return left < right
+ })
+
+ resourceToGroup := make(map[string]string, len(nodes))
+ for _, group := range orderedGroups {
+ for _, resource := range group.resources {
+ if resource == nil || strings.TrimSpace(resource.ID) == "" {
+ continue
+ }
+ resourceToGroup[strings.TrimSpace(resource.ID)] = group.id
+ }
+ }
+
+ return TopLevelSystemResolver{
+ groups: orderedGroups,
+ resourceToGroup: resourceToGroup,
+ }
+ }
+ }
+}
+
+// GroupIDForResource returns the canonical top-level system group id for a
+// resource, or empty when the resource was not part of this resolver.
+func (r TopLevelSystemResolver) GroupIDForResource(resource Resource) string {
+ return r.resourceToGroup[strings.TrimSpace(resource.ID)]
+}
+
+// Count returns the number of grouped top-level monitored systems.
+func (r TopLevelSystemResolver) Count() int {
+ return len(r.groups)
+}
+
+func (r TopLevelSystemResolver) records() []MonitoredSystemRecord {
+ records := make([]MonitoredSystemRecord, 0, len(r.groups))
+ for _, group := range r.groups {
+ records = append(records, monitoredSystemRecord(monitoredSystemGroup{
+ keys: cloneStringSet(group.strongIDs),
+ resources: group.resources,
+ }))
+ }
+ return records
+}
+
+func (r TopLevelSystemResolver) HasMatchingCandidate(candidate MonitoredSystemCandidate) bool {
+ strongIDs := monitoredSystemCandidateStrongIDs(candidate)
+ for _, group := range r.groups {
+ if topLevelSystemSetsOverlap(group.strongIDs, strongIDs) {
+ return true
+ }
+ }
+
+ if !monitoredSystemCandidateAllowsHostAttachment(candidate) {
+ return false
+ }
+
+ groupByID := make(map[string]topLevelSystemResolvedGroup, len(r.groups))
+ hostOwners := make(map[string]map[string]struct{})
+ ipOwners := make(map[string]map[string]struct{})
+ for _, group := range r.groups {
+ groupByID[group.id] = group
+ for host := range group.exactHosts {
+ addTopLevelSystemOwner(hostOwners, host, group.id)
+ }
+ for ip := range group.exactIPs {
+ addTopLevelSystemOwner(ipOwners, ip, group.id)
+ }
+ }
+
+ targetIDs := candidateExactTargetGroups(candidate, hostOwners, ipOwners, groupByID, monitoredSystemCandidatePriority(candidate))
+ return len(targetIDs) == 1
+}
+
+func buildTopLevelSystemResolvedGroups(
+ nodes []topLevelSystemNode,
+ parent []int,
+) map[int]topLevelSystemResolvedGroup {
+ find := func(id int) int {
+ for parent[id] != id {
+ parent[id] = parent[parent[id]]
+ id = parent[id]
+ }
+ return id
+ }
+
+ groupIndex := make(map[int]*topLevelSystemResolvedGroup)
+ for i := range nodes {
+ root := find(i)
+ group := groupIndex[root]
+ if group == nil {
+ group = &topLevelSystemResolvedGroup{
+ exactHosts: make(map[string]struct{}),
+ exactIPs: make(map[string]struct{}),
+ strongIDs: make(map[string]struct{}),
+ priority: nodes[i].priority,
+ }
+ groupIndex[root] = group
+ }
+ group.resources = append(group.resources, nodes[i].resource)
+ if nodes[i].priority < group.priority {
+ group.priority = nodes[i].priority
+ }
+ if nodes[i].attachByHost {
+ group.attachByHost = true
+ }
+ for host := range nodes[i].exactHosts {
+ group.exactHosts[host] = struct{}{}
+ }
+ for ip := range nodes[i].exactIPs {
+ group.exactIPs[ip] = struct{}{}
+ }
+ for strongID := range nodes[i].strongIDs {
+ group.strongIDs[strongID] = struct{}{}
+ }
+ }
+
+ groups := make(map[int]topLevelSystemResolvedGroup, len(groupIndex))
+ for root, group := range groupIndex {
+ group.id = topLevelSystemGroupID(*group)
+ groups[root] = *group
+ }
+
+ return groups
+}
+
+func buildTopLevelSystemNode(resource *Resource) topLevelSystemNode {
+ if resource == nil {
+ return topLevelSystemNode{}
+ }
+
+ exactHosts := topLevelSystemExactHosts(*resource)
+ exactIPs := topLevelSystemExactIPs(*resource)
+ identity := cloneResourceIdentity(resource.Identity)
+ identity.Hostnames = uniqueStrings(append(cloneStringSlice(identity.Hostnames), topLevelSystemSortedSet(exactHosts)...))
+ identity.IPAddresses = uniqueStrings(append(cloneStringSlice(identity.IPAddresses), topLevelSystemSortedSet(exactIPs)...))
+
+ return topLevelSystemNode{
+ resource: resource,
+ identity: identity,
+ strongIDs: topLevelSystemStrongIDs(*resource),
+ exactHosts: exactHosts,
+ exactIPs: exactIPs,
+ priority: monitoredSystemResourcePriority(resource),
+ attachByHost: monitoredSystemResourceAllowsHostAttachment(resource),
+ }
+}
+
+func topLevelSystemStrongIDs(resource Resource) map[string]struct{} {
+ ids := make(map[string]struct{})
+
+ if canonical := resource.Canonical; canonical != nil {
+ if primaryID := strings.TrimSpace(canonical.PrimaryID); primaryID != "" {
+ ids["primary:"+primaryID] = struct{}{}
+ }
+ }
+
+ if resourceID := strings.TrimSpace(resource.ID); resourceID != "" {
+ ids["resource:"+resourceID] = struct{}{}
+ }
+ if machineID := strings.TrimSpace(resource.Identity.MachineID); machineID != "" {
+ ids["machine:"+machineID] = struct{}{}
+ }
+ if resource.Agent != nil {
+ if agentID := strings.TrimSpace(resource.Agent.AgentID); agentID != "" {
+ ids["agent:"+agentID] = struct{}{}
+ }
+ }
+ if resource.Docker != nil {
+ if hostSourceID := strings.TrimSpace(resource.Docker.HostSourceID); hostSourceID != "" {
+ ids["docker:"+hostSourceID] = struct{}{}
+ }
+ if agentID := strings.TrimSpace(resource.Docker.AgentID); agentID != "" {
+ ids["agent:"+agentID] = struct{}{}
+ }
+ }
+ if resource.Proxmox != nil {
+ if sourceID := strings.TrimSpace(resource.Proxmox.SourceID); sourceID != "" {
+ ids["proxmox:"+sourceID] = struct{}{}
+ }
+ }
+ if resource.PBS != nil {
+ if instanceID := strings.TrimSpace(resource.PBS.InstanceID); instanceID != "" {
+ ids["pbs:"+instanceID] = struct{}{}
+ }
+ }
+ if resource.PMG != nil {
+ if instanceID := strings.TrimSpace(resource.PMG.InstanceID); instanceID != "" {
+ ids["pmg:"+instanceID] = struct{}{}
+ }
+ }
+ if resource.Kubernetes != nil {
+ if clusterID := strings.TrimSpace(resource.Kubernetes.ClusterID); clusterID != "" {
+ ids["k8s:"+clusterID] = struct{}{}
+ }
+ if agentID := strings.TrimSpace(resource.Kubernetes.AgentID); agentID != "" {
+ ids["agent:"+agentID] = struct{}{}
+ }
+ }
+
+ return ids
+}
+
+func topLevelSystemExactHosts(resource Resource) map[string]struct{} {
+ hosts := make(map[string]struct{})
+ for _, candidate := range []string{
+ canonicalAgentHostname(resource),
+ canonicalDockerHostname(resource),
+ canonicalPBSHostname(resource),
+ canonicalPMGHostname(resource),
+ canonicalTrueNASHostname(resource),
+ canonicalProxmoxNodeName(resource),
+ firstTrimmed(topLevelSystemProxmoxHostURL(resource)),
+ firstTrimmed(topLevelSystemPBSHostURL(resource)),
+ firstTrimmed(topLevelSystemKubernetesServer(resource)),
+ firstTrimmed(topLevelSystemCanonicalHostname(resource)),
+ } {
+ if normalized := topLevelSystemNormalizeHost(candidate); normalized != "" {
+ hosts[normalized] = struct{}{}
+ }
+ }
+ return hosts
+}
+
+func topLevelSystemExactIPs(resource Resource) map[string]struct{} {
+ ips := make(map[string]struct{})
+ for _, candidate := range resource.Identity.IPAddresses {
+ if normalized := NormalizeIP(candidate); normalized != "" && !isNonUniqueIP(normalized) {
+ ips[normalized] = struct{}{}
+ }
+ }
+ for _, raw := range []string{
+ firstTrimmed(topLevelSystemProxmoxHostURL(resource)),
+ firstTrimmed(topLevelSystemPBSHostURL(resource)),
+ firstTrimmed(topLevelSystemKubernetesServer(resource)),
+ } {
+ host := extractHostname(raw)
+ if normalized := NormalizeIP(host); normalized != "" && !isNonUniqueIP(normalized) {
+ ips[normalized] = struct{}{}
+ }
+ }
+ return ips
+}
+
+func topLevelSystemMatcherID(index int) string {
+ return "top-level-system:" + strconv.Itoa(index)
+}
+
+func buildTopLevelSystemFallbackOwners(
+ groups map[int]topLevelSystemResolvedGroup,
+) (map[string]map[int]struct{}, map[string]map[int]struct{}) {
+ hostOwners := make(map[string]map[int]struct{})
+ ipOwners := make(map[string]map[int]struct{})
+ for groupRoot, group := range groups {
+ for host := range group.exactHosts {
+ bucket := hostOwners[host]
+ if bucket == nil {
+ bucket = make(map[int]struct{})
+ hostOwners[host] = bucket
+ }
+ bucket[groupRoot] = struct{}{}
+ }
+ for ip := range group.exactIPs {
+ bucket := ipOwners[ip]
+ if bucket == nil {
+ bucket = make(map[int]struct{})
+ ipOwners[ip] = bucket
+ }
+ bucket[groupRoot] = struct{}{}
+ }
+ }
+ return hostOwners, ipOwners
+}
+
+func uniqueBetterTopLevelSystemTarget(
+ groupRoot int,
+ group topLevelSystemResolvedGroup,
+ hostOwners map[string]map[int]struct{},
+ ipOwners map[string]map[int]struct{},
+ groups map[int]topLevelSystemResolvedGroup,
+) (int, bool) {
+ targets := make(map[int]struct{})
+
+ for host := range group.exactHosts {
+ for targetRoot := range hostOwners[host] {
+ if targetRoot == groupRoot {
+ continue
+ }
+ if groups[targetRoot].priority >= group.priority {
+ continue
+ }
+ targets[targetRoot] = struct{}{}
+ }
+ }
+ for ip := range group.exactIPs {
+ for targetRoot := range ipOwners[ip] {
+ if targetRoot == groupRoot {
+ continue
+ }
+ if groups[targetRoot].priority >= group.priority {
+ continue
+ }
+ targets[targetRoot] = struct{}{}
+ }
+ }
+
+ if len(targets) != 1 {
+ return 0, false
+ }
+ for targetRoot := range targets {
+ return targetRoot, true
+ }
+ return 0, false
+}
+
+func candidateExactTargetGroups(
+ candidate MonitoredSystemCandidate,
+ hostOwners map[string]map[string]struct{},
+ ipOwners map[string]map[string]struct{},
+ groups map[string]topLevelSystemResolvedGroup,
+ priority int,
+) map[string]struct{} {
+ targets := make(map[string]struct{})
+ for host := range monitoredSystemCandidateExactHosts(candidate) {
+ for groupID := range hostOwners[host] {
+ if groups[groupID].priority >= priority {
+ continue
+ }
+ targets[groupID] = struct{}{}
+ }
+ }
+ for ip := range monitoredSystemCandidateExactIPs(candidate) {
+ for groupID := range ipOwners[ip] {
+ if groups[groupID].priority >= priority {
+ continue
+ }
+ targets[groupID] = struct{}{}
+ }
+ }
+ return targets
+}
+
+func monitoredSystemCandidateStrongIDs(candidate MonitoredSystemCandidate) map[string]struct{} {
+ ids := make(map[string]struct{})
+ if resourceID := strings.TrimSpace(candidate.ResourceID); resourceID != "" {
+ ids["resource:"+resourceID] = struct{}{}
+ }
+ if machineID := strings.TrimSpace(candidate.MachineID); machineID != "" {
+ ids["machine:"+machineID] = struct{}{}
+ }
+ if agentID := strings.TrimSpace(candidate.AgentID); agentID != "" {
+ ids["agent:"+agentID] = struct{}{}
+ }
+ return ids
+}
+
+func monitoredSystemCandidateExactHosts(candidate MonitoredSystemCandidate) map[string]struct{} {
+ hosts := make(map[string]struct{})
+ for _, value := range []string{candidate.Hostname, extractHostname(candidate.HostURL)} {
+ if normalized := topLevelSystemNormalizeHost(value); normalized != "" {
+ hosts[normalized] = struct{}{}
+ }
+ }
+ return hosts
+}
+
+func monitoredSystemCandidateExactIPs(candidate MonitoredSystemCandidate) map[string]struct{} {
+ ips := make(map[string]struct{})
+ for _, value := range []string{candidate.Hostname, extractHostname(candidate.HostURL)} {
+ if normalized := NormalizeIP(value); normalized != "" && !isNonUniqueIP(normalized) {
+ ips[normalized] = struct{}{}
+ }
+ }
+ return ips
+}
+
+func monitoredSystemCandidatePriority(candidate MonitoredSystemCandidate) int {
+ switch candidate.Type {
+ case ResourceTypePBS:
+ return 10
+ case ResourceTypePMG:
+ return 11
+ case ResourceTypeK8sCluster:
+ return 12
+ default:
+ return 3
+ }
+}
+
+func monitoredSystemCandidateAllowsHostAttachment(candidate MonitoredSystemCandidate) bool {
+ if candidate.Type == ResourceTypeK8sCluster {
+ return false
+ }
+ return len(monitoredSystemCandidateExactHosts(candidate)) > 0 || len(monitoredSystemCandidateExactIPs(candidate)) > 0
+}
+
+func monitoredSystemResourceAllowsHostAttachment(resource *Resource) bool {
+ if resource == nil || CanonicalResourceType(resource.Type) == ResourceTypeK8sCluster {
+ return false
+ }
+ return len(topLevelSystemExactHosts(*resource)) > 0 || len(topLevelSystemExactIPs(*resource)) > 0
+}
+
+func topLevelSystemGroupID(group topLevelSystemResolvedGroup) string {
+ orderedStrongIDs := topLevelSystemSortedSet(group.strongIDs)
+ sort.SliceStable(orderedStrongIDs, func(i, j int) bool {
+ leftPrefix, leftValue := topLevelSystemSplitStrongID(orderedStrongIDs[i])
+ rightPrefix, rightValue := topLevelSystemSplitStrongID(orderedStrongIDs[j])
+ if topLevelSystemStrongIDPriority(leftPrefix) != topLevelSystemStrongIDPriority(rightPrefix) {
+ return topLevelSystemStrongIDPriority(leftPrefix) < topLevelSystemStrongIDPriority(rightPrefix)
+ }
+ return leftValue < rightValue
+ })
+ if len(orderedStrongIDs) > 0 {
+ return orderedStrongIDs[0]
+ }
+
+ orderedHosts := topLevelSystemSortedSet(group.exactHosts)
+ if len(orderedHosts) > 0 {
+ return "host:" + orderedHosts[0]
+ }
+ orderedIPs := topLevelSystemSortedSet(group.exactIPs)
+ if len(orderedIPs) > 0 {
+ return "ip:" + orderedIPs[0]
+ }
+
+ preferred := preferredMonitoredSystemResource(group.resources)
+ if preferred != nil {
+ if resourceID := strings.TrimSpace(preferred.ID); resourceID != "" {
+ return "resource:" + resourceID
+ }
+ }
+ return "resource:unknown"
+}
+
+func topLevelSystemStrongIDPriority(prefix string) int {
+ switch prefix {
+ case "machine":
+ return 0
+ case "agent":
+ return 1
+ case "primary":
+ return 2
+ case "proxmox":
+ return 3
+ case "docker":
+ return 4
+ case "pbs":
+ return 5
+ case "pmg":
+ return 6
+ case "k8s":
+ return 7
+ case "resource":
+ return 8
+ default:
+ return 99
+ }
+}
+
+func topLevelSystemSplitStrongID(value string) (string, string) {
+ parts := strings.SplitN(value, ":", 2)
+ if len(parts) != 2 {
+ return value, ""
+ }
+ return parts[0], parts[1]
+}
+
+func topLevelSystemSortedSet(values map[string]struct{}) []string {
+ out := make([]string, 0, len(values))
+ for value := range values {
+ out = append(out, value)
+ }
+ sort.Strings(out)
+ return out
+}
+
+func topLevelSystemSetsOverlap(left, right map[string]struct{}) bool {
+ if len(left) == 0 || len(right) == 0 {
+ return false
+ }
+ if len(left) > len(right) {
+ left, right = right, left
+ }
+ for value := range left {
+ if _, ok := right[value]; ok {
+ return true
+ }
+ }
+ return false
+}
+
+func addTopLevelSystemOwner(index map[string]map[string]struct{}, key, owner string) {
+ bucket := index[key]
+ if bucket == nil {
+ bucket = make(map[string]struct{})
+ index[key] = bucket
+ }
+ bucket[owner] = struct{}{}
+}
+
+func topLevelSystemNormalizeHost(value string) string {
+ trimmed := strings.TrimSpace(strings.ToLower(value))
+ if trimmed == "" {
+ return ""
+ }
+ if NormalizeIP(trimmed) != "" {
+ return ""
+ }
+ return trimmed
+}
+
+func topLevelSystemProxmoxHostURL(resource Resource) string {
+ if resource.Proxmox == nil {
+ return ""
+ }
+ return strings.TrimSpace(resource.Proxmox.HostURL)
+}
+
+func topLevelSystemPBSHostURL(resource Resource) string {
+ if resource.PBS == nil {
+ return ""
+ }
+ return strings.TrimSpace(resource.PBS.HostURL)
+}
+
+func topLevelSystemKubernetesServer(resource Resource) string {
+ if resource.Kubernetes == nil {
+ return ""
+ }
+ return strings.TrimSpace(resource.Kubernetes.Server)
+}
+
+func topLevelSystemCanonicalHostname(resource Resource) string {
+ if resource.Canonical == nil {
+ return ""
+ }
+ return strings.TrimSpace(resource.Canonical.Hostname)
+}