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.

Stop monitoring linking a node to an agent the operator split off

rcourtman7d02f9f04e9e
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 725dcd7dfe..a089e0f234 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -8915,7 +8915,9 @@ reassociation even when a subsequent report matches. An explicit link can select
a replacement ID.
Only known automatic associations are re-evaluated destructively against provider
-names and network evidence. Obsolete reverse links are removed with host updates.
+names and network evidence, and an operator's split of the node and the agent in
+the resource store (resources API unlink or report-merge) clears the link in
+state whatever its provenance. Obsolete reverse links are removed with host updates.
An unmarked persisted link is not assumed automatic: report ingestion retains it,
so this is deliberately **not** a blanket repair of existing v6.4.1 associations.
Legacy provider reconciliation otherwise retains its previous behaviour.
@@ -9356,9 +9358,10 @@ identity and continuity are unchanged.
`internal/api/resourceapi/resources.go` changed only so report-merge on a
resource an operator linked an agent into (a VM, a node or a Docker host)
replaces that link, splitting the agent back out as unlink does. Agent
-registration, enrolment, install, update, removal, report identity and
-continuity are unchanged, and an agent's own declared node link still
-ignores exclusions.
+registration, enrolment, install, update, removal and report identity are
+unchanged. An agent's own node link honours the split too, and a manual
+link's persisted intent can end with it ("Agent node links honour operator
+splits" below).
A report-merge that names sources now picks links by the member that carries
the source instead of by the sources a link's folded side took in with it
@@ -9414,3 +9417,31 @@ revision and link list hold (monitoring contract, "Mock-mode metrics-target
lookups ride the fixture structure revision"). Agent registration, enrolment,
install, update, removal, report identity and continuity are unchanged, and
real-mode resolution still goes through the live registry.
+
+### Agent node links honour operator splits
+
+Report ingest (`monitor_agents.go`) no longer links an agent to a node the
+operator split it from in the resource store (resources API unlink or
+report-merge). The agent's `LinkedNodeID` stays off that node (empty, or
+another node the report infers for it), so its LXC filesystems and node alert
+correlation stay off that node, and when the report finds the link split, or
+ends a split manual intent, the container filesystem readings the agent
+already cached for the node's containers are cleared. A cached reading is
+also not shown for a node the operator split from the agent that cached it,
+whether or not a report cleared it. A report uses the link the state stored, so a split the state
+sees between the report's own check and its store does not reach the
+node, the container readings, the agent's alert coverage or its persisted
+continuity. A split recorded
+after the agents API's manual link ends that manual intent: the agent's next
+report that finds the split confirmed in the resource store records its
+link source as automatic in host continuity, so the node is no longer
+reserved for the agent. Until then a report keeps the manual intent's node
+in host continuity. `Monitor.LinkHostAgent` (`/api/agents/agent/link`)
+removes from the resource store the exclusions that split the pair before it
+records manual intent, because the link is the operator's newer decision and
+both the registry and monitoring read the split from the store. If the
+intent fails to persist, the exclusions are recorded again, except for a
+pair the operator has decided about since. The agents API's unlink is
+unchanged. Registration, enrolment, install, update,
+removal, token binding and report identity are unchanged. The
+unified-resources contract records the split's rules.
diff --git a/docs/release-control/v6/internal/subsystems/monitoring.md b/docs/release-control/v6/internal/subsystems/monitoring.md
index 6178dec032..df749fdb7f 100644
--- a/docs/release-control/v6/internal/subsystems/monitoring.md
+++ b/docs/release-control/v6/internal/subsystems/monitoring.md
@@ -1519,7 +1519,9 @@ merged from an already-linked agent. Known automatic associations may be
re-evaluated and cleared; provenance-bearing host updates remove obsolete
reverse links without clearing another agent's link. Unmarked legacy forward
links are retained during report ingestion, and unmarked one-way reverse links
-must survive host updates because SMART fallback also consumes them. Legacy
+must survive host updates because SMART fallback also consumes them, except
+that a link the operator split in the resource store (unlink or report-merge
+in the resources API) is cleared on both sides whatever its provenance. Legacy
provider reconciliation otherwise keeps its existing behaviour. This deliberately
does not claim to repair every persisted v6.4.1 association or resolve #1930.
@@ -6869,3 +6871,41 @@ malformed records, both client/collector paths, canonical and served state,
original age/expiry, History, breach continuity and complete removal/recovery.
These are synthetic source controls, not native thaw, the cause of #2619/#2439,
or installed/released acceptance.
+
+### Node and agent links honour operator splits
+
+An operator's split of a Proxmox node and its pulse-agent (resources API
+unlink or report-merge) split the registry's rows but left the monitor's
+own link (`Node.LinkedAgentID`, `Host.LinkedNodeID`) standing. What reads
+that link kept treating the two machines as one: the physical disk poll
+took the agent's SMART inventory as the node's disk fallback and applied the
+agent's `--disk-exclude` patterns to the node's disks, `linkedHostForNode`
+fed the node's disk sources, guests inherited the agent for discovery and
+commands, deployment reported the node as already running an agent, service
+discovery routed through it, and alert correlation tied the node to it.
+`models.State` now holds such a link back on both sides through a
+`models.NodeAgentSplitDecider` that `Monitor.SetResourceStore` installs from
+the resource store's adapter. `resetStateLocked` installs it again when mock
+mode replaces the state. Every link write applies it: `UpdateNodesForInstance`
+before the merge key reads a node's link and again after the manual-intent
+reconcile, `UpsertHost`, `LinkNodeToHostAgent`, and report ingest before it
+applies the agent's LXC filesystems. A report that finds an agent's link
+split, or ends its split manual intent, clears that agent's cached container
+filesystem readings. A cached reading is also not shown for a node the
+operator split from the agent that cached it
+(`enrichContainerWithAgentLXCFilesystems`), whether or not a report cleared
+it. A report uses the link `UpsertHost` kept when a split lands between
+the report's own check and the state's store. The split's rules and its one record,
+the resource store, are in the unified-resources contract.
+`Monitor.LinkHostAgent` first removes an older split of that pair from the
+store, and records it again if the intent fails to persist, without replacing
+a decision the operator recorded in between. A split recorded
+after a manual link ends that manual intent on the agent's next report that
+finds the split confirmed in the store. The alert manager's node coverage
+for the agent changes on that agent's next checked report or offline
+transition. Mock mode's fixture graph keeps its own links. Polling cadence,
+link inference and the broadcast payload are unchanged. `TestOperatorSplitStopsMonitoringTreatingNodeAndAgentAsLinked`
+checks each of those readers after a report-merge, against a control
+exclusion that splits nothing, and `TestManualNodeLinkReplacesAnOperatorSplit`
+covers the agents API's link after a split, a split after it, and a
+resources API relink.
diff --git a/docs/release-control/v6/internal/subsystems/unified-resources.md b/docs/release-control/v6/internal/subsystems/unified-resources.md
index 017c5c024a..38864408e1 100644
--- a/docs/release-control/v6/internal/subsystems/unified-resources.md
+++ b/docs/release-control/v6/internal/subsystems/unified-resources.md
@@ -7437,15 +7437,124 @@ agent's pin while another agent it was split from declares it, and
`TestOperatorSplitHoldsWhenTheAgentStopsReportingItsMachineID` keeps a split
whose agent comes back without its machine ID.
-What the split does not reach: the agents API's node link
-(`/api/agents/agent/link`) records a monitor-side link intent, not a store
-decision, so it does not override a resource split; rejoin through
-`POST /api/resources/{id}/link`. The monitor's own node record keeps its
-link where it has one, so what reads it still follows the agent: the
-agent's SMART inventory as the node's disk fallback when the Proxmox disk
-query fails, the agent's disk-exclude patterns on the node's disks, and the
-node's linked agent that guest discovery, agent deployment and service
-discovery act on.
+Monitoring's own link honours the split as well, at each place it reads the
+link as evidence: besides the readers below, the temperature read for a
+polled node skips a split agent in its exact-hostname fallback (the held-back
+link would otherwise leave the agent "unlinked" and matchable by name), while
+the check that drops a carried reading once its agent's lease lapses still
+finds a split agent whose hostname is the node's name, so a reading it
+supplied earlier does not outlive that lease. An agent the link tied to the
+node by address (an FQDN, say) is no longer found once split, and a reading it
+supplied earlier stays until the ordinary carry window ends: readings carry
+no source to find it by. `UpdateNodesForInstance` holds the link back before the
+merge key reads it, for the polled instance's nodes and for the retained
+nodes of the other instances, so an agent the operator split from a node
+never proves two connections' views of that node to be one machine. The node's
+`LinkedAgentID` and the agent's `LinkedNodeID` in `models.State` are what
+the agent's SMART inventory as the node's disk fallback, its disk-exclude
+patterns on the node's disks, guest discovery and commands (guests inherit
+the node's linked agent), agent deployment (`already_agent`), service
+discovery, the agent's LXC filesystems and the node and agent's shared
+alert correlation read, so leaving that link standing kept treating the
+two machines as one. The resource store holds the one record of the
+split. `MonitorAdapter.ProxmoxNodeAgentSplit` implements
+`models.NodeAgentSplitDecider` with `splitProxmoxNodeLink`'s rule over the
+two records, and the state holds back both sides of every link it splits
+wherever a link is written (the node poll's link before its merge key reads
+it, the reconcile after manual intent, an agent report). The decider reads
+the adapter's current generation and confirms a split it finds against the
+store's latest decisions. Monitoring writes links before the rebuild that
+loads a newer decision, so without that check a relink would stay held back
+for one more poll, and that rebuild would join the rows by the manual link
+alone, under the link's primary ID (for an agent reporting no machine key, a
+different ID from the one the node's link joins them under). A split
+monitoring misses for the poll before that rebuild is applied by the
+registry to the node's link on that rebuild, as above. With the link held
+back, the registry ingests a node naming no agent and an agent naming no
+node. Every server-side view keeps them apart, within the presentation limit
+this section records for a third same-host row, and the browser's realtime
+coalesce is the limit recorded below. A relink joins them again once
+monitoring infers the link on its next poll.
+
+The decider reads the agent under the ID the registry holds it under too,
+so an agent that stops reporting its machine key, whose pin keeps its
+machine-derived ID, stays split from the node in monitoring as in the
+registry. The agents API's node link (`Monitor.LinkHostAgent`) is the
+operator's newest decision about the pair, so before it records manual
+intent it removes from the store the exclusions that split that node from
+that agent (`LiftProxmoxNodeAgentSplit`, across the same ID sets). If the
+intent then fails to persist, it records them again with their original
+times (`RestoreProxmoxNodeAgentSplit`), and a removal that fails part way
+restores the ones already removed. A restore only fills a pair the operator
+has not decided about since: `ResourceStore.RestoreExclusion` declines a pair
+that has an exclusion in either order or a link recorded at or after the
+exclusion's time, checking and inserting in one transaction, so it does not
+replace a newer decision (it compares the records' times, so a decision
+written with an earlier clock reading looks older), while a link row older
+than the exclusion, left beside it by older data or canonical-ID succession,
+is superseded by it as it was before the take. The pair joins in
+monitoring at once and
+in the registry on its next rebuild. Report-merge's exclusion of the agent's
+own candidate from the machine-derived ID stays, because it never split the
+node. A split recorded after a manual link ends that intent on the agent's
+next report that finds the split confirmed in the store
+(`ProxmoxNodeAgentSplitConfirmed`), which records the agent's link as
+automatic in host continuity. The node is then no longer reserved for that
+agent, and the split holds back the inferred link. Until then, and while
+the store cannot be read, the persisted intent keeps its node. The agents
+API's unlink records no store decision: it clears monitoring's link, so the
+registry stops joining the pair through it, but a resources API link
+between their rows still joins them in the registry, and so can identity
+matching where a node completes a joined-era pin's machine key.
+`TestMonitorStateHoldsBackAnOperatorSplitNodeAgentLink` (`store_test.go`)
+runs the six requests above over four link shapes (unclustered, clustered,
+an agent hostname in another form, an agent reporting no machine key)
+through a `models.State` holding the adapter's decisions, over three
+poll-and-rebuild cycles per step in every view. It checks the state's links
+from the second cycle, checks that a report alone keeps a split pair apart,
+then a relink, an agent-first rebuild that persists its pins, and the
+request again. `TestMonitorStateHoldsBackSplitLinksItStartsWith` holds back
+the links a state already has when the decider is installed, and a manual
+link restored from host continuity once the reconcile writes it.
+`TestOperatorSplitStopsMonitoringTreatingNodeAndAgentAsLinked`
+follows a report-merge through the monitor's readers of the link and keeps
+them all linked under an unrelated exclusion.
+`TestManualNodeLinkReplacesAnOperatorSplit` covers the agents API's link
+after a split (and that a link to another node lifts nothing), a split after
+it, and a resources API relink.
+
+What the split does not reach: a relink through
+`POST /api/resources/{id}/link` joins the registry's rows, but monitoring
+links the pair again only where it infers the link or the agents API sets
+it, so a pair that only that link joins is one row that monitoring does not
+link, as for any manual link. The alert manager's record of which node an
+agent's usage alerts cover (`hostAgentNodeLinks`) changes when it checks the
+agent's next report, or when the agent goes offline, so the node's CPU,
+memory and disk alerts stay with the agent until then. Mock mode's
+consumers read the fixture graph, whose links ignore operator decisions,
+as the mock-mode view does. A rebuild that cannot read the store's
+decisions loads none, so for that generation the registry and the decider
+both treat the pair as undecided, as they do for every operator decision,
+and the next readable rebuild applies the split again. An exclusion that
+names the node by its source-specific ID stops naming it if the node's
+source ID changes, like every exclusion keyed by a canonical ID. A report
+reads the split before it stores the agent and the state reads it again
+when it does (for the agent's own link, then for each node linked to it),
+and the report uses the link the state kept, so a split the decider sees
+between those checks does not reach the node's back link, the agent's
+container filesystem readings, its alert coverage or its persisted
+continuity. The decider answers from the adapter's generation and confirms a
+split it finds against the store, so a split recorded since the last
+rebuild takes effect from the rebuild that loads it, and is applied to the
+link the next report finds. When that report drops the agent's link, or ends
+its manual intent, it also clears the container filesystem readings the
+agent had cached for the node's containers. Those readings are also checked
+when they are shown: a cached reading is not shown for a node the operator
+split from the agent that cached it (`State.NodeSplitFromAgent`), whether or
+not a report ever cleared it, so a report that infers no node for the agent
+(its name no longer matches, or matches several) and clears nothing does not
+leave it on show. The check is the split only: a reading whose link ended
+for another reason is used until it expires, as before.
Physical disks inside one host join through `resolveLinkedPhysicalDisk`,
which now honours their operator exclusions ("Operator split separates disks
inside a linked host" above, upstream #2748). A node split also puts the two
diff --git a/internal/models/models.go b/internal/models/models.go
index b1ee9cd09e..ceee0c30f3 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -61,6 +61,90 @@ type State struct {
// are discarded as decisive evidence. Internal evidence only: never
// serialized and never part of snapshots.
pbsGuestConfirmations map[string]map[PBSGuestConfirmation]struct{}
+
+ // nodeAgentSplits holds back node<->agent links the operator split
+ // (SetNodeAgentSplitDecider); nil holds none back.
+ nodeAgentSplits NodeAgentSplitDecider
+}
+
+// NodeAgentSplitDecider reports whether the operator split a Proxmox node
+// from a host agent's machine (unlink or report-merge in the resources API,
+// recorded in the resource store and decided by
+// unifiedresources.MonitorAdapter). State holds such a link back on both
+// sides, so nothing that reads a node's linked agent or an agent's linked
+// node treats the pair as one machine: the agent's SMART inventory as the
+// node's disk fallback, its disk-exclude patterns on the node, guest
+// discovery, agent deployment, service discovery and the node and agent's
+// alert correlation.
+// State calls it with its lock held, so it must not call State.
+type NodeAgentSplitDecider interface {
+ ProxmoxNodeAgentSplit(node Node, host Host) bool
+}
+
+// SetNodeAgentSplitDecider installs the operator's split decisions and
+// holds back the links they split now; every later link write reads them
+// too. A held-back link returns when monitoring next infers it after the
+// decider stops splitting the pair. A manual link (the agents API's node
+// link) split afterwards ends on the agent's next report that finds the
+// split confirmed in the resource store, which records the agent's link as
+// automatic again.
+func (s *State) SetNodeAgentSplitDecider(d NodeAgentSplitDecider) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ s.nodeAgentSplits = d
+ holdBackSplitNodeLinks(d, s.Hosts, s.Nodes)
+}
+
+// NodeAgentLinkSplit reports whether the operator split the node with
+// nodeID from host's agent, so a link between them is held back.
+func (s *State) NodeAgentLinkSplit(nodeID string, host Host) bool {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ return nodeAgentLinkSplitLocked(s.nodeAgentSplits, s.Nodes, nodeID, host)
+}
+
+func nodeAgentLinkSplitLocked(d NodeAgentSplitDecider, nodes []Node, nodeID string, host Host) bool {
+ nodeID = strings.TrimSpace(nodeID)
+ if d == nil || nodeID == "" || strings.TrimSpace(host.ID) == "" {
+ return false
+ }
+ for i := range nodes {
+ if nodes[i].ID == nodeID {
+ return d.ProxmoxNodeAgentSplit(nodes[i], host)
+ }
+ }
+ return false
+}
+
+// holdBackSplitNodeLinks clears both sides of every node<->agent link the
+// operator split.
+func holdBackSplitNodeLinks(d NodeAgentSplitDecider, hosts []Host, nodes []Node) {
+ if d == nil {
+ return
+ }
+ hostByID := make(map[string]Host, len(hosts))
+ for _, host := range hosts {
+ hostByID[host.ID] = host
+ }
+ for i := range nodes {
+ holdBackSplitNodeLink(d, &nodes[i], hostByID)
+ }
+ for i := range hosts {
+ if nodeAgentLinkSplitLocked(d, nodes, hosts[i].LinkedNodeID, hosts[i]) {
+ hosts[i].LinkedNodeID = ""
+ }
+ }
+}
+
+// holdBackSplitNodeLink clears node's linked agent if the operator split
+// the node from it.
+func holdBackSplitNodeLink(d NodeAgentSplitDecider, node *Node, hostByID map[string]Host) {
+ if d == nil || node.LinkedAgentID == "" {
+ return
+ }
+ if host, ok := hostByID[node.LinkedAgentID]; ok && d.ProxmoxNodeAgentSplit(*node, host) {
+ node.LinkedAgentID = ""
+ }
}
// PBSGuestConfirmation identifies one PBS snapshot as seen through a PVE
@@ -3968,7 +4052,7 @@ func preferNodeForMerge(existing Node, candidate Node) Node {
return existing
}
-func reconcileHostNodeLinksLocked(hosts []Host, nodes []Node) {
+func reconcileHostNodeLinksLocked(hosts []Host, nodes []Node, splits NodeAgentSplitDecider) {
// Explicit operator intent is pinned to the selected provider ID, never
// transferred by hostname to a replacement provider identity.
for _, host := range hosts {
@@ -3984,6 +4068,9 @@ func reconcileHostNodeLinksLocked(hosts []Host, nodes []Node) {
}
}
}
+ // A split recorded after a manual link is the newer decision (the
+ // agents API's link removes an older split before it records intent).
+ holdBackSplitNodeLinks(splits, hosts, nodes)
linkedNodeByHostID := make(map[string]string)
multipleNodeLinksByHostID := make(map[string]struct{})
for _, node := range nodes {
@@ -4082,10 +4169,20 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
}
linkedHostToKey[hostID] = key
}
+ // A split recorded since another instance's poll is read here, before that
+ // instance's retained link can steer where this poll's nodes fold.
+ var retainedHostByID map[string]Host
+ if s.nodeAgentSplits != nil && len(s.Hosts) > 0 {
+ retainedHostByID = make(map[string]Host, len(s.Hosts))
+ for _, host := range s.Hosts {
+ retainedHostByID[host.ID] = host
+ }
+ }
for _, node := range s.Nodes {
if node.Instance == instanceName {
continue
}
+ holdBackSplitNodeLink(s.nodeAgentSplits, &node, retainedHostByID)
key := nodeLogicalKey(node)
if key == "" {
@@ -4332,6 +4429,9 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
}
}
+ // A split agent is no evidence of this node's identity either, so
+ // hold the link back before the merge key reads it.
+ holdBackSplitNodeLink(s.nodeAgentSplits, &node, hostByID)
primaryKey := nodeLogicalKey(node)
targetKey := resolveNodeMergeKey(primaryKey, node, nodeMap, nodeAliasToKey, ambiguousNodeAliases)
if node.LinkedAgentID != "" {
@@ -4359,6 +4459,7 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
if existing, ok := nodeMap[targetKey]; ok {
if validHostAgentIDs[existing.LinkedAgentID] {
node.LinkedAgentID = existing.LinkedAgentID
+ holdBackSplitNodeLink(s.nodeAgentSplits, &node, hostByID)
}
}
}
@@ -4383,7 +4484,7 @@ func (s *State) UpdateNodesForInstance(instanceName string, nodes []Node) {
return newNodes[i].Name < newNodes[j].Name
})
- reconcileHostNodeLinksLocked(s.Hosts, newNodes)
+ reconcileHostNodeLinksLocked(s.Hosts, newNodes, s.nodeAgentSplits)
s.Nodes = newNodes
s.LastUpdate = time.Now()
@@ -5471,10 +5572,22 @@ func (s *State) UpsertHost(host Host) {
defer s.mu.Unlock()
host = cloneHost(host)
+ if nodeAgentLinkSplitLocked(s.nodeAgentSplits, s.Nodes, host.LinkedNodeID, host) {
+ host.LinkedNodeID = ""
+ }
for i, node := range s.Nodes {
+ if host.ID == "" || node.LinkedAgentID != host.ID {
+ continue
+ }
+ // An operator split holds the link back on both sides, whatever the
+ // host's intent.
+ split := nodeAgentLinkSplitLocked(s.nodeAgentSplits, s.Nodes, node.ID, host)
+ if split && node.ID == host.LinkedNodeID {
+ host.LinkedNodeID = ""
+ }
// Legacy one-way links have unknown intent; an unmarked host update
// cannot authorise their removal (SMART fallback also uses these links).
- if host.NodeLinkSource != "" && host.ID != "" && node.LinkedAgentID == host.ID && node.ID != host.LinkedNodeID {
+ if split || (host.NodeLinkSource != "" && node.ID != host.LinkedNodeID) {
s.Nodes[i].LinkedAgentID = ""
}
}
@@ -5513,6 +5626,51 @@ func (s *State) GetHost(hostID string) (Host, bool) {
return Host{}, false
}
+// NodeSplitFromAgent reports whether the operator split the node with this
+// connection and name from the host agent with this ID. It reads the state in
+// place, so readers that ask once per container do not copy the records. A
+// node or agent not in state is not split.
+func (s *State) NodeSplitFromAgent(instance, name, agentID string) bool {
+ instance = strings.ToLower(strings.TrimSpace(instance))
+ name = strings.ToLower(strings.TrimSpace(name))
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+ if s.nodeAgentSplits == nil {
+ return false
+ }
+ var host *Host
+ for i := range s.Hosts {
+ if s.Hosts[i].ID == agentID {
+ host = &s.Hosts[i]
+ break
+ }
+ }
+ if host == nil {
+ return false
+ }
+ for i := range s.Nodes {
+ node := &s.Nodes[i]
+ if strings.ToLower(strings.TrimSpace(node.Instance)) == instance &&
+ strings.ToLower(strings.TrimSpace(node.Name)) == name {
+ return s.nodeAgentSplits.ProxmoxNodeAgentSplit(*node, *host)
+ }
+ }
+ return false
+}
+
+// GetNode returns one detached Proxmox node record.
+func (s *State) GetNode(nodeID string) (Node, bool) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ for _, node := range s.Nodes {
+ if node.ID == nodeID {
+ return cloneNode(node), true
+ }
+ }
+ return Node{}, false
+}
+
// GetHosts returns a copy of all generic hosts.
func (s *State) GetHosts() []Host {
s.mu.RLock()
@@ -5552,12 +5710,18 @@ func (s *State) ClearAllHosts() int {
// LinkNodeToHostAgent updates a PVE node to link to its host agent.
// This is called when a host agent registers and matches a known PVE node by hostname.
+// A node the operator split from the agent keeps no link to it.
func (s *State) LinkNodeToHostAgent(nodeID, hostAgentID string) bool {
s.mu.Lock()
defer s.mu.Unlock()
for i, node := range s.Nodes {
if node.ID == nodeID {
+ for _, host := range s.Hosts {
+ if host.ID == hostAgentID && nodeAgentLinkSplitLocked(s.nodeAgentSplits, s.Nodes, nodeID, host) {
+ return true
+ }
+ }
s.Nodes[i].LinkedAgentID = hostAgentID
s.LastUpdate = time.Now()
return true
diff --git a/internal/models/state_host_test.go b/internal/models/state_host_test.go
index 7593919690..da263e1431 100644
--- a/internal/models/state_host_test.go
+++ b/internal/models/state_host_test.go
@@ -2168,3 +2168,100 @@ func TestUpdateNodesForInstanceStandaloneViewStillFoldsIntoClusterNode(t *testin
t.Fatalf("agent link: nodes = %#v, want 1 (fingerprint-proven view folds via shared agent)", byAgent.Nodes)
}
}
+
+// splitNodeDecider reports the pairs an operator split, by node and agent ID.
+type splitNodeDecider map[[2]string]bool
+
+func (d splitNodeDecider) ProxmoxNodeAgentSplit(node Node, host Host) bool {
+ return d[[2]string{node.ID, host.ID}]
+}
+
+// A split recorded after one connection's poll is applied to that connection's
+// retained node before its link can fold the next connection's view into it.
+func TestUpdateNodesForInstanceReadsASplitOfARetainedNodeBeforeItFolds(t *testing.T) {
+ agent := Host{ID: "agent-1", Hostname: "pve1.lan", ReportIP: "10.0.0.5", Status: "online"}
+ nodeA := Node{ID: "a-pve1", Name: "pve1", Instance: "a", Host: "https://10.0.0.5:8006", Status: "online"}
+ nodeB := Node{ID: "b-pve1", Name: "pve1", Instance: "b", Host: "https://pve1.lan:8006", Status: "online"}
+
+ decider := splitNodeDecider{}
+ state := NewState()
+ state.UpsertHost(agent)
+ state.SetNodeAgentSplitDecider(decider)
+ state.UpdateNodesForInstance("a", []Node{nodeA})
+ if linked := state.GetSnapshot().Nodes; len(linked) != 1 || linked[0].LinkedAgentID != agent.ID {
+ t.Fatalf("fixture: the first poll should link its node to the agent: %+v", linked)
+ }
+
+ // The operator splits the first node from the agent; nothing has written
+ // a link since, so the retained node still names the agent.
+ decider[[2]string{nodeA.ID, agent.ID}] = true
+ state.UpdateNodesForInstance("b", []Node{nodeB})
+
+ nodes := state.GetSnapshot().Nodes
+ if len(nodes) != 2 {
+ t.Fatalf("a retained node's split link still folded the next view into its slot: %+v", nodes)
+ }
+ for _, node := range nodes {
+ switch node.ID {
+ case nodeA.ID:
+ if node.LinkedAgentID != "" {
+ t.Fatalf("node %s kept the agent %q the operator split it from", node.ID, node.LinkedAgentID)
+ }
+ case nodeB.ID:
+ if node.LinkedAgentID != agent.ID {
+ t.Fatalf("node %s lost an agent link nobody split: %q", node.ID, node.LinkedAgentID)
+ }
+ default:
+ t.Fatalf("unexpected node %+v", node)
+ }
+ }
+}
+
+// One agent corroborates two standalone connections' nodes through the node's
+// IP address and its full hostname, which is the proof that folds the second
+// view into the first node's slot. When the operator has split the second
+// node from that agent, the agent is no evidence for it, so the view is not
+// folded, and neither a node nor the agent keeps a link the operator split.
+func TestUpdateNodesForInstanceHoldsASplitAgentBackBeforeItFoldsNodeViews(t *testing.T) {
+ agent := Host{
+ ID: "agent-1",
+ Hostname: "pve1.lan",
+ ReportIP: "10.0.0.5",
+ Status: "online",
+ }
+ nodeA := Node{ID: "a-pve1", Name: "pve1", Instance: "a", Host: "https://10.0.0.5:8006", Status: "online"}
+ nodeB := Node{ID: "b-pve1", Name: "pve1", Instance: "b", Host: "https://pve1.lan:8006", Status: "online"}
+
+ poll := func(decider NodeAgentSplitDecider) []Node {
+ state := NewState()
+ state.UpsertHost(agent)
+ state.SetNodeAgentSplitDecider(decider)
+ state.UpdateNodesForInstance("a", []Node{nodeA})
+ state.UpdateNodesForInstance("b", []Node{nodeB})
+ return state.GetSnapshot().Nodes
+ }
+
+ folded := poll(nil)
+ if len(folded) != 1 || folded[0].LinkedAgentID != agent.ID {
+ t.Fatalf("fixture: the agent should fold both views into one linked node, got %+v", folded)
+ }
+
+ apart := poll(splitNodeDecider{{nodeB.ID, agent.ID}: true})
+ if len(apart) != 2 {
+ t.Fatalf("a node split from the agent folded into its slot anyway: %+v", apart)
+ }
+ for _, node := range apart {
+ switch node.ID {
+ case nodeA.ID:
+ if node.LinkedAgentID != agent.ID {
+ t.Fatalf("the split of the other node unlinked %s from the agent", node.ID)
+ }
+ case nodeB.ID:
+ if node.LinkedAgentID != "" {
+ t.Fatalf("node %s kept the agent %q the operator split it from", node.ID, node.LinkedAgentID)
+ }
+ default:
+ t.Fatalf("unexpected node %+v", node)
+ }
+ }
+}
diff --git a/internal/monitoring/host_agent_temps.go b/internal/monitoring/host_agent_temps.go
index 83ae970aac..8165ce0036 100644
--- a/internal/monitoring/host_agent_temps.go
+++ b/internal/monitoring/host_agent_temps.go
@@ -91,7 +91,7 @@ func (m *Monitor) getHostAgentTemperatureForNode(node models.Node) *models.Tempe
nodes := readState.Nodes()
slot := m.polledNodeSlot(hosts, nodes, node)
- matchedHost := hostAgentForNode(hosts, nodes, slot, node.Name)
+ matchedHost := hostAgentForNode(hosts, nodes, slot, node.Name, m.nodeAgentSplitFilter(node))
if matchedHost == nil {
// No directly-linked host agent found — check cluster sensor cache
return m.getClusterSensorTemperature(hosts, nodes, node, slot)
@@ -140,7 +140,10 @@ func (m *Monitor) carriedTemperatureOutlivesAgentLease(node models.Node, temp *m
}
hosts := readState.Hosts()
nodes := readState.Nodes()
- matchedHost := hostAgentForNode(hosts, nodes, m.polledNodeSlot(hosts, nodes, node), node.Name)
+ // A split agent still counts here: the check asks whether a carried
+ // reading may have been the agent's, and one it supplied before the split
+ // must not outlive the agent's lease.
+ matchedHost := hostAgentForNode(hosts, nodes, m.polledNodeSlot(hosts, nodes, node), node.Name, nil)
if matchedHost == nil {
return false
}
@@ -272,8 +275,11 @@ func (m *Monitor) stateNodeFromView(view *unifiedresources.NodeView) models.Node
// another node or to a guest, and finds nothing when a Proxmox node outside the
// slot or a second unlinked agent has the name. Every link source (automatic,
// manual, restored from continuity) stores the Proxmox source node ID, so slot
-// IDs compare with LinkedNodeID directly.
-func hostAgentForNode(hosts []*unifiedresources.HostView, nodes []*unifiedresources.NodeView, slot nodeSlot, nodeName string) *unifiedresources.HostView {
+// IDs compare with LinkedNodeID directly. The hostname fallback also
+// skips an agent the operator split from the node (split, which may be nil):
+// the split holds the link back, which would otherwise leave the agent
+// "unlinked" and let its name hand the node the machine's sensors.
+func hostAgentForNode(hosts []*unifiedresources.HostView, nodes []*unifiedresources.NodeView, slot nodeSlot, nodeName string, split func(*unifiedresources.HostView) bool) *unifiedresources.HostView {
for _, host := range hosts {
if slot.hasID(host.LinkedNodeID()) {
log.Debug().
@@ -298,6 +304,9 @@ func hostAgentForNode(hosts []*unifiedresources.HostView, nodes []*unifiedresour
if strings.ToLower(strings.TrimSpace(host.Hostname())) != name {
continue
}
+ if split != nil && split(host) {
+ continue
+ }
if match != nil {
return nil
}
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 5fe35958a8..0f732f9327 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -4830,6 +4830,33 @@ func (m *Monitor) resetStateLocked() {
StartTime: m.startTime,
Version: "2.0.0-go",
}
+ m.installNodeAgentSplitDeciderLocked()
+}
+
+// installNodeAgentSplitDeciderLocked makes the state hold back node<->agent
+// links the operator split in the resource store, so the monitor's own link
+// agrees with the registry's rows. Callers hold m.mu.
+func (m *Monitor) installNodeAgentSplitDeciderLocked() {
+ if m.state == nil {
+ return
+ }
+ decider, _ := m.resourceStore.(models.NodeAgentSplitDecider)
+ m.state.SetNodeAgentSplitDecider(decider)
+}
+
+// nodeAgentSplitFilter reports, for a polled node, whether a read-state host
+// is an agent the operator split from it. Nil when no resource store holds
+// operator decisions.
+func (m *Monitor) nodeAgentSplitFilter(node models.Node) func(*unifiedresources.HostView) bool {
+ m.mu.RLock()
+ decider, _ := m.resourceStore.(models.NodeAgentSplitDecider)
+ m.mu.RUnlock()
+ if decider == nil {
+ return nil
+ }
+ return func(host *unifiedresources.HostView) bool {
+ return decider.ProxmoxNodeAgentSplit(node, hostFromReadStateView(host))
+ }
}
// GetStartTime returns the monitor start time
@@ -4906,6 +4933,7 @@ func (m *Monitor) SetResourceStore(store ResourceStoreInterface) {
m.mu.Lock()
m.resourceStore = store
incidentStore := m.incidentStore
+ m.installNodeAgentSplitDeciderLocked()
m.mu.Unlock()
m.installOperatorIntentResolver(store)
log.Info().Msg("resource store set for polling optimization")
diff --git a/internal/monitoring/monitor_agent_lxc_filesystems.go b/internal/monitoring/monitor_agent_lxc_filesystems.go
index 02d44a73ad..b8079a5555 100644
--- a/internal/monitoring/monitor_agent_lxc_filesystems.go
+++ b/internal/monitoring/monitor_agent_lxc_filesystems.go
@@ -222,6 +222,12 @@ func (m *Monitor) enrichContainerWithAgentLXCFilesystems(
if strings.TrimSpace(container.Name) != entry.name {
return
}
+ // Admission required the agent to be linked to this node. A reading cached
+ // before the operator split the node from the agent is not shown once they
+ // are split, whether or not a later report cleared it or even named a node.
+ if m.state.NodeSplitFromAgent(instance, node, entry.agentID) {
+ return
+ }
container.Disks = append([]models.Disk(nil), entry.disks...)
for _, disk := range container.Disks {
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index 764e307315..0d93930105 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -980,7 +980,17 @@ func (m *Monitor) LinkHostAgent(hostID, nodeID string) error {
return fmt.Errorf("node id is required")
}
+ restoreSplit, err := m.liftNodeAgentSplit(hostID, nodeID)
+ if err != nil {
+ return fmt.Errorf("link host agent %q to node %q: %w", hostID, nodeID, err)
+ }
if err := m.state.SetHostNodeLinkIntent(hostID, nodeID, m.persistNodeLinkIntents); err != nil {
+ if restoreErr := restoreSplit(); restoreErr != nil {
+ log.Error().Err(restoreErr).
+ Str("hostID", hostID).
+ Str("nodeID", nodeID).
+ Msg("Failed to restore the operator's split after the manual node link failed")
+ }
return fmt.Errorf("link host agent %q to node %q: %w", hostID, nodeID, err)
}
@@ -992,6 +1002,76 @@ func (m *Monitor) LinkHostAgent(hostID, nodeID string) error {
return nil
}
+// nodeAgentSplitStore is the resource store holding the operator's
+// node<->agent splits (unifiedresources.MonitorAdapter).
+type nodeAgentSplitStore interface {
+ ProxmoxNodeAgentSplitConfirmed(node models.Node, host models.Host) (bool, error)
+ LiftProxmoxNodeAgentSplit(node models.Node, host models.Host) ([]unifiedresources.ResourceExclusion, error)
+ RestoreProxmoxNodeAgentSplit(removed []unifiedresources.ResourceExclusion) error
+}
+
+func (m *Monitor) nodeAgentSplitStore() nodeAgentSplitStore {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ store, _ := m.resourceStore.(nodeAgentSplitStore)
+ return store
+}
+
+// liftNodeAgentSplit removes an operator split between the node and the
+// agent (resources API unlink or report-merge) before a manual link is
+// recorded. The link is the newer decision, and the registry's rows and the
+// state's hold-back both read the split from the resource store, so leaving
+// it would keep the pair apart in both despite the link. The returned
+// restore records the split again, for a link that then fails to persist.
+func (m *Monitor) liftNodeAgentSplit(hostID, nodeID string) (restore func() error, err error) {
+ restore = func() error { return nil }
+ store := m.nodeAgentSplitStore()
+ if store == nil {
+ return restore, nil
+ }
+ host, hostFound := m.state.GetHost(hostID)
+ node, nodeFound := m.state.GetNode(nodeID)
+ if !hostFound || !nodeFound {
+ // SetHostNodeLinkIntent reports the missing record.
+ return restore, nil
+ }
+ removed, err := store.LiftProxmoxNodeAgentSplit(node, host)
+ if err != nil {
+ return restore, fmt.Errorf("lift the operator's split: %w", err)
+ }
+ if len(removed) > 0 {
+ log.Info().
+ Str("hostID", hostID).
+ Str("nodeID", nodeID).
+ Int("exclusionsRemoved", len(removed)).
+ Msg("Manual node link replaced the operator's split of the node and agent")
+ }
+ return func() error { return store.RestoreProxmoxNodeAgentSplit(removed) }, nil
+}
+
+// nodeAgentSplitConfirmed reports whether the resource store's latest
+// decisions split the node from host's agent; an unreadable store confirms
+// nothing.
+func (m *Monitor) nodeAgentSplitConfirmed(nodeID string, host models.Host) bool {
+ store := m.nodeAgentSplitStore()
+ if store == nil {
+ return false
+ }
+ node, ok := m.state.GetNode(nodeID)
+ if !ok {
+ return false
+ }
+ split, err := store.ProxmoxNodeAgentSplitConfirmed(node, host)
+ if err != nil {
+ log.Warn().Err(err).
+ Str("hostID", host.ID).
+ Str("nodeID", nodeID).
+ Msg("Could not read the operator's node and agent split; keeping the manual node link")
+ return false
+ }
+ return split
+}
+
// UnlinkHostAgent removes the link between a host agent and its PVE node.
// The agent will continue to report but will appear in the Managed Agents table
// instead of being merged with the PVE node in the Dashboard.
@@ -1644,6 +1724,19 @@ func (m *Monitor) MatchHostConfigContinuity(agentID, tokenID string) (models.Hos
return models.Host{}, false
}
+// persistedNodeLinkTarget is the node a report persists as the agent's link.
+// A manual link an operator split holds back in state keeps its node in the
+// persisted intent: only a split the store confirms ends it (ApplyHostReport).
+func persistedNodeLinkTarget(store *config.HostContinuityStore, host models.Host) string {
+ linkedNodeID := strings.TrimSpace(host.LinkedNodeID)
+ if linkedNodeID == "" && host.NodeLinkSource == "manual" && store != nil {
+ if prior, ok := store.Get(host.ID); ok && prior.NodeLinkSource == "manual" {
+ return prior.LinkedNodeID
+ }
+ }
+ return linkedNodeID
+}
+
func (m *Monitor) persistHostContinuity(host models.Host, report agentshost.Report, order hostReportOrder) {
if m == nil || m.hostContinuityStore == nil {
return
@@ -1660,7 +1753,7 @@ func (m *Monitor) persistHostContinuity(host models.Host, report agentshost.Repo
AgentVersion: strings.TrimSpace(host.AgentVersion),
Platform: strings.TrimSpace(host.Platform),
NodeLinkSource: host.NodeLinkSource,
- LinkedNodeID: strings.TrimSpace(host.LinkedNodeID),
+ LinkedNodeID: persistedNodeLinkTarget(m.hostContinuityStore, host),
LinkedVMID: strings.TrimSpace(host.LinkedVMID),
LinkedContainerID: strings.TrimSpace(host.LinkedContainerID),
IsLegacy: host.IsLegacy,
@@ -3579,6 +3672,7 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
prior = hostFromContinuityEntry(entry)
}
}
+ inferredNodeID, inferredVMID, inferredContainerID := linkedNodeID, linkedVMID, linkedContainerID
host.NodeLinkSource = "automatic"
if prior.NodeLinkSource == "manual" || prior.NodeLinkSource == "unlinked" ||
(prior.NodeLinkSource == "" && prior.LinkedNodeID != "") {
@@ -3586,10 +3680,37 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
linkedNodeID = prior.LinkedNodeID
linkedVMID, linkedContainerID = "", ""
}
+ // An operator split of the node a manual link names is the newer
+ // decision (the agents API's link removes an older split first), so it
+ // ends the manual intent, which persists with this report: the agent
+ // links as Pulse infers again, and the split holds that link back below.
+ // Kept, the intent would also reserve the node against other agents.
+ // The state may already hold the link back, so the node comes from the
+ // persisted intent, and only a split the store confirms ends it.
+ if host.NodeLinkSource == "manual" {
+ if linkedNodeID == "" && m.hostContinuityStore != nil {
+ if entry, ok := m.hostContinuityStore.Get(host.ID); ok && entry.NodeLinkSource == "manual" {
+ linkedNodeID = entry.LinkedNodeID
+ }
+ }
+ if linkedNodeID != "" && m.nodeAgentSplitConfirmed(linkedNodeID, host) {
+ host.NodeLinkSource = "automatic"
+ linkedNodeID, linkedVMID, linkedContainerID = inferredNodeID, inferredVMID, inferredContainerID
+ m.clearAgentLXCFilesystems(host.ID)
+ }
+ }
if linkedNodeID != "" && host.NodeLinkSource != "manual" && m.hostContinuityStore != nil &&
m.hostContinuityStore.NodeLinkReservedByOther(host.ID, linkedNodeID) {
linkedNodeID = ""
}
+ // The operator split this node from the agent (resources API unlink or
+ // report-merge): the agent's LXC filesystems and everything else that
+ // follows the link stay off the node, and what the agent already
+ // contributed to its containers goes with the link.
+ if linkedNodeID != "" && m.state.NodeAgentLinkSplit(linkedNodeID, host) {
+ linkedNodeID = ""
+ m.clearAgentLXCFilesystems(host.ID)
+ }
if linkedNodeID != "" {
host.LinkedNodeID = linkedNodeID
log.Debug().
@@ -3659,6 +3780,16 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
}
m.state.UpsertHost(host)
+ // A split recorded since the check above is applied by the state under
+ // its own lock; what follows (the node's back link, the agent's LXC
+ // filesystems, its alert coverage and the persisted continuity) uses the
+ // link the state kept.
+ if host.LinkedNodeID != "" {
+ if stored, ok := m.state.GetHost(host.ID); ok && stored.LinkedNodeID != host.LinkedNodeID {
+ host.LinkedNodeID = stored.LinkedNodeID
+ m.clearAgentLXCFilesystems(host.ID)
+ }
+ }
m.state.SetConnectionHealth(hostConnectionPrefix+host.ID, true)
m.supersedeStaleHostAgentDuplicates(host, tokenRecord, existingHostModels)
diff --git a/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go b/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
index d3daad925f..65daf1fca5 100644
--- a/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
+++ b/internal/monitoring/monitor_host_agent_removal_lifecycle_test.go
@@ -1,10 +1,13 @@
package monitoring
import (
+ "errors"
+ "fmt"
"os"
"path/filepath"
"slices"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -956,3 +959,615 @@ func TestLeavingMockModeReleasesFixtureAgentNodeLinksOnEveryRunningMonitor(t *te
}
t.Fatalf("org-b's node %s raised no memory alert: its fixture agent's node link outlived a switch made through the default monitor", linked.ID)
}
+
+// nodeAgentSplitMonitor is a Proxmox node with a guest and the pulse-agent
+// on the same machine, monitored through a store-backed resource adapter.
+type nodeAgentSplitMonitor struct {
+ t *testing.T
+ monitor *Monitor
+ store unifiedresources.ResourceStore
+ adapter *unifiedresources.MonitorAdapter
+ nodes []models.Node
+ vm models.VM
+ report agentshost.Report
+ host models.Host
+}
+
+func newNodeAgentSplitMonitor(t *testing.T) *nodeAgentSplitMonitor {
+ return newNodeAgentSplitMonitorWithStore(t, nil)
+}
+
+// flakyDecisionStore fails reads of the operator's manual decisions while
+// fail is set, as a store that cannot be read for a moment does.
+type flakyDecisionStore struct {
+ unifiedresources.ResourceStore
+ fail atomic.Bool
+}
+
+func (s *flakyDecisionStore) GetLinks() ([]unifiedresources.ResourceLink, error) {
+ if s.fail.Load() {
+ return nil, errors.New("decisions unreadable")
+ }
+ return s.ResourceStore.GetLinks()
+}
+
+func (s *flakyDecisionStore) GetExclusions() ([]unifiedresources.ResourceExclusion, error) {
+ if s.fail.Load() {
+ return nil, errors.New("decisions unreadable")
+ }
+ return s.ResourceStore.GetExclusions()
+}
+
+func newNodeAgentSplitMonitorWithStore(t *testing.T, wrap func(unifiedresources.ResourceStore) unifiedresources.ResourceStore) *nodeAgentSplitMonitor {
+ t.Helper()
+ sqliteStore, err := unifiedresources.NewSQLiteResourceStore(t.TempDir(), "default")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = sqliteStore.Close() })
+ var store unifiedresources.ResourceStore = sqliteStore
+ if wrap != nil {
+ store = wrap(store)
+ }
+ now := time.Now().UTC()
+ f := &nodeAgentSplitMonitor{
+ t: t,
+ monitor: issue1654Monitor(),
+ store: store,
+ adapter: unifiedresources.NewMonitorAdapter(unifiedresources.NewRegistry(store)),
+ nodes: []models.Node{
+ {ID: "lab-pve1", Name: "pve1", Instance: "lab", Host: "https://10.0.0.5:8006", Status: "online", LastSeen: now},
+ {ID: "lab-pve2", Name: "pve2", Instance: "lab", Host: "https://10.0.0.6:8006", Status: "online", LastSeen: now},
+ },
+ vm: models.VM{ID: "lab-pve1-100", VMID: 100, Name: "web", Node: "pve1", Instance: "lab", Type: "qemu", Status: "running", LastSeen: now},
+ report: agentshost.Report{
+ Agent: agentshost.AgentInfo{ID: "agent-pve1", Version: "6.2.0", IntervalSeconds: 30, DiskExclude: []string{"/dev/sdz"}},
+ Host: agentshost.HostInfo{
+ ID: "pve1-host", MachineID: "0123456789abcdef", Hostname: "pve1", Platform: "linux", ReportIP: "10.0.0.5",
+ },
+ Timestamp: now,
+ },
+ }
+ f.monitor.hostContinuityStore = config.NewHostContinuityStore(t.TempDir(), nil)
+ f.monitor.SetResourceStore(f.adapter)
+ return f
+}
+
+// cycle polls the nodes, rebuilds the adapter, takes one agent report and
+// rebuilds again, as the poll loop and report ingest interleave.
+func (f *nodeAgentSplitMonitor) cycle() {
+ f.t.Helper()
+ f.monitor.state.UpdateNodesForInstance("lab", f.nodes)
+ f.monitor.state.UpdateVMsForInstance("lab", []models.VM{f.vm})
+ f.adapter.PopulateFromSnapshot(f.monitor.state.GetSnapshot())
+ f.report.Timestamp = f.report.Timestamp.Add(time.Second)
+ host, err := f.monitor.ApplyHostReport(f.report, nil)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ f.host = host
+ f.adapter.PopulateFromSnapshot(f.monitor.state.GetSnapshot())
+}
+
+// recordReportMerge records what POST /api/resources/{id}/report-merge
+// records for the joined node and agent row, read from a registry rebuilt
+// from the monitor's snapshot as the resources API builds one.
+func (f *nodeAgentSplitMonitor) recordReportMerge() {
+ f.t.Helper()
+ registry := unifiedresources.NewRegistry(f.store)
+ registry.IngestSnapshot(f.monitor.state.GetSnapshot())
+ merged := ""
+ for _, resource := range registry.List() {
+ if resource.Proxmox != nil && resource.Agent != nil {
+ merged = resource.ID
+ }
+ }
+ if merged == "" {
+ f.t.Fatal("no joined node and agent row to report")
+ }
+ for _, target := range registry.SourceTargets(merged) {
+ if target.CandidateID == "" || target.CandidateID == merged {
+ continue
+ }
+ if err := f.store.AddExclusion(unifiedresources.ResourceExclusion{ResourceA: merged, ResourceB: target.CandidateID, CreatedAt: time.Now().UTC()}); err != nil {
+ f.t.Fatal(err)
+ }
+ }
+}
+
+// seedLXCFilesystems caches one container filesystem reading from the agent,
+// as an earlier report with a Proxmox LXC inventory would have.
+func (f *nodeAgentSplitMonitor) seedLXCFilesystems() {
+ f.t.Helper()
+ f.monitor.proxmoxLXCFilesystemsMu.Lock()
+ defer f.monitor.proxmoxLXCFilesystemsMu.Unlock()
+ f.monitor.proxmoxLXCFilesystemsCache = map[string]agentLXCFilesystemCacheEntry{
+ agentLXCFilesystemCacheKey("lab", "pve1", 200): {
+ agentID: f.host.ID,
+ name: "ct200",
+ disks: []models.Disk{{Mountpoint: "/", Total: 10 << 30, Used: 1 << 30}},
+ expiresAt: time.Now().Add(10 * time.Minute),
+ },
+ }
+}
+
+func (f *nodeAgentSplitMonitor) lxcFilesystemEntries() int {
+ f.monitor.proxmoxLXCFilesystemsMu.RLock()
+ defer f.monitor.proxmoxLXCFilesystemsMu.RUnlock()
+ return len(f.monitor.proxmoxLXCFilesystemsCache)
+}
+
+// reportOnly takes one agent report with no poll or rebuild before it.
+func (f *nodeAgentSplitMonitor) reportOnly() models.Host {
+ f.t.Helper()
+ f.report.Timestamp = f.report.Timestamp.Add(time.Second)
+ host, err := f.monitor.ApplyHostReport(f.report, nil)
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ f.host = host
+ return host
+}
+
+// exclusions lists the store's exclusions as "a|b", and how many name the
+// node's own source-specific ID.
+func (f *nodeAgentSplitMonitor) exclusions() (all []string, namingNode int) {
+ f.t.Helper()
+ exclusions, err := f.store.GetExclusions()
+ if err != nil {
+ f.t.Fatal(err)
+ }
+ nodeCandidate := unifiedresources.SourceSpecificID(unifiedresources.ResourceTypeAgent, unifiedresources.SourceProxmox, f.nodes[0].ID)
+ for _, exclusion := range exclusions {
+ all = append(all, exclusion.ResourceA+"|"+exclusion.ResourceB)
+ if exclusion.ResourceA == nodeCandidate || exclusion.ResourceB == nodeCandidate {
+ namingNode++
+ }
+ }
+ slices.Sort(all)
+ return all, namingNode
+}
+
+// assertLinked checks every reader of the node<->agent link: the state's
+// two sides, report ingest's result, the node's linked agent in the read
+// state (agent deployment, service discovery and the physical disk poll's
+// SMART fallback and --disk-exclude patterns read it), the node's disk
+// source host, the guest's inherited agent (guest discovery and commands)
+// and the shared-system alert correlation, and whether the registry lists
+// the pair as one row.
+func (f *nodeAgentSplitMonitor) assertLinked(step string, want bool) {
+ f.t.Helper()
+ node, agent := f.nodes[0].ID, f.host.ID
+ wantAgent, wantNode := "", ""
+ if want {
+ wantAgent, wantNode = agent, node
+ }
+ snapshot := f.monitor.state.GetSnapshot()
+ for _, n := range snapshot.Nodes {
+ if n.ID == node && n.LinkedAgentID != wantAgent {
+ f.t.Fatalf("%s: state node links agent %q, want %q", step, n.LinkedAgentID, wantAgent)
+ }
+ }
+ for _, h := range snapshot.Hosts {
+ if h.ID == agent && h.LinkedNodeID != wantNode {
+ f.t.Fatalf("%s: state agent links node %q, want %q", step, h.LinkedNodeID, wantNode)
+ }
+ }
+ if f.host.LinkedNodeID != wantNode {
+ f.t.Fatalf("%s: report ingest linked node %q, want %q", step, f.host.LinkedNodeID, wantNode)
+ }
+ readState := f.monitor.GetUnifiedReadStateOrSnapshot()
+ for _, view := range readState.Nodes() {
+ if view.SourceID() == node && view.LinkedAgentID() != wantAgent {
+ f.t.Fatalf("%s: read-state node links agent %q, want %q", step, view.LinkedAgentID(), wantAgent)
+ }
+ }
+ diskHost := f.monitor.linkedHostForNode("lab", node, f.nodes[0].Name)
+ if (diskHost != nil) != want || (diskHost != nil && diskHost.ID != agent) {
+ f.t.Fatalf("%s: node disk source host %+v, want linked=%v", step, diskHost, want)
+ }
+ joined := false
+ for _, resource := range f.adapter.GetAll() {
+ if resource.Type == unifiedresources.ResourceTypeVM && resource.Proxmox != nil && resource.Proxmox.LinkedAgentID != wantAgent {
+ f.t.Fatalf("%s: guest inherits agent %q, want %q", step, resource.Proxmox.LinkedAgentID, wantAgent)
+ }
+ if resource.Proxmox != nil && resource.Agent != nil {
+ joined = true
+ }
+ }
+ if joined != want {
+ f.t.Fatalf("%s: registry lists the pair joined=%v, want %v", step, joined, want)
+ }
+ if correlated := sharedSystemAlertCorrelationForHost(f.host, snapshot.Nodes) != nil; correlated != want {
+ f.t.Fatalf("%s: shared-system alert correlation=%v, want %v", step, correlated, want)
+ }
+}
+
+// An operator's split of a Proxmox node and its pulse-agent (report-merge
+// or unlink in the resources API) stops monitoring treating them as one
+// machine: the agent's SMART inventory, --disk-exclude patterns, guest
+// discovery target, deployment status and alert correlation no longer
+// reach the node. An exclusion that splits neither leaves all of it alone.
+func TestOperatorSplitStopsMonitoringTreatingNodeAndAgentAsLinked(t *testing.T) {
+ t.Run("unrelated exclusion keeps the link", func(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ f.assertLinked("before", true)
+ joined := ""
+ for _, resource := range f.adapter.GetAll() {
+ if resource.Proxmox != nil && resource.Agent != nil {
+ joined = resource.ID
+ }
+ }
+ f.seedLXCFilesystems()
+ if err := f.store.AddExclusion(unifiedresources.ResourceExclusion{ResourceA: joined, ResourceB: "agent-00000000deadbeef", CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after an unrelated exclusion", true)
+ if got := f.lxcFilesystemEntries(); got != 1 {
+ t.Fatalf("an unrelated exclusion changed the agent's container filesystem readings to %d", got)
+ }
+ })
+
+ t.Run("report-merge splits the link", func(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ f.assertLinked("before", true)
+ f.seedLXCFilesystems()
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after report-merge", false)
+ if got := f.lxcFilesystemEntries(); got != 0 {
+ t.Fatalf("the split left %d of the agent's container filesystem readings on the node's containers", got)
+ }
+ })
+}
+
+// The agents API's node link is the operator's newer decision about the
+// pair, so it replaces an earlier split in the resource store, which both
+// the registry and monitoring read, instead of leaving monitoring linked
+// and the registry split. A link to another node lifts nothing. A split
+// recorded after a manual link wins in turn and ends the manual intent, so
+// the node is no longer reserved for the agent, and a later relink of the
+// rows in the resources API joins them again through the link monitoring
+// infers.
+func TestManualNodeLinkReplacesAnOperatorSplit(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after report-merge", false)
+ split, namingNode := f.exclusions()
+ if namingNode != 1 {
+ t.Fatalf("report-merge recorded %v, want one exclusion naming the node's candidate", split)
+ }
+
+ if err := f.monitor.LinkHostAgent(f.host.ID, f.nodes[1].ID); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := f.exclusions(); !slices.Equal(got, split) {
+ t.Fatalf("linking the agent to another node changed the exclusions from %v to %v", split, got)
+ }
+ // The node's split goes. Report-merge's exclusion of the agent's own
+ // candidate from the machine-derived ID it merged under stays: it never
+ // split the node (nodeAgentSplit), and it is also what splitting another
+ // source off the agent records.
+ if err := f.monitor.LinkHostAgent(f.host.ID, f.nodes[0].ID); err != nil {
+ t.Fatal(err)
+ }
+ if got, namingNode := f.exclusions(); namingNode != 0 || len(got) != len(split)-1 {
+ t.Fatalf("manual link left exclusions %v of %v", got, split)
+ }
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after the manual link", true)
+
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after a split of the manual link", false)
+ entry, ok := f.monitor.hostContinuityStore.Get(f.host.ID)
+ if !ok || entry.NodeLinkSource != "automatic" || entry.LinkedNodeID != "" {
+ t.Fatalf("split left the manual intent persisted: %+v", entry)
+ }
+ if reserved := f.monitor.hostContinuityStore.NodeLinkReservedByOther("another-agent", f.nodes[0].ID); reserved {
+ t.Fatal("the ended manual intent still reserves the node against other agents")
+ }
+
+ var nodeRow, agentRow string
+ for _, resource := range f.adapter.GetAll() {
+ switch {
+ case resource.Proxmox != nil && resource.Agent == nil && resource.Proxmox.SourceID == f.nodes[0].ID:
+ nodeRow = resource.ID
+ case resource.Agent != nil && resource.Proxmox == nil:
+ agentRow = resource.ID
+ }
+ }
+ if err := f.store.AddLink(unifiedresources.ResourceLink{ResourceA: nodeRow, ResourceB: agentRow, PrimaryID: nodeRow, CreatedAt: time.Now().UTC()}); err != nil {
+ t.Fatal(err)
+ }
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after a resources API relink", true)
+}
+
+// A manual node link that cannot persist its intent leaves the operator's
+// split as it was: the exclusions it removed are recorded again, with their
+// original times, and the pair stays apart.
+func TestManualNodeLinkKeepsTheSplitWhenItsIntentCannotPersist(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ before, err := f.store.GetExclusions()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ continuity := f.monitor.hostContinuityStore
+ f.monitor.hostContinuityStore = nil
+ if err := f.monitor.LinkHostAgent(f.host.ID, f.nodes[0].ID); err == nil {
+ t.Fatal("manual link without intent storage succeeded")
+ }
+ f.monitor.hostContinuityStore = continuity
+ after, err := f.store.GetExclusions()
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := func(exclusions []unifiedresources.ResourceExclusion) []string {
+ out := make([]string, 0, len(exclusions))
+ for _, exclusion := range exclusions {
+ out = append(out, exclusion.ResourceA+"|"+exclusion.ResourceB+"|"+exclusion.CreatedAt.UTC().Format(time.RFC3339Nano))
+ }
+ slices.Sort(out)
+ return out
+ }
+ if !slices.Equal(key(before), key(after)) {
+ t.Fatalf("failed manual link changed the split from %v to %v", key(before), key(after))
+ }
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after the failed manual link", false)
+}
+
+// A manual node link the state holds back only because the split cannot be
+// confirmed (the store is unreadable just after the link removed it) keeps
+// its persisted intent, and links once the store reads again. Only a split
+// the store confirms ends a manual intent.
+func TestManualNodeLinkSurvivesAnUnreadableSplitStore(t *testing.T) {
+ var flaky *flakyDecisionStore
+ f := newNodeAgentSplitMonitorWithStore(t, func(store unifiedresources.ResourceStore) unifiedresources.ResourceStore {
+ flaky = &flakyDecisionStore{ResourceStore: store}
+ return flaky
+ })
+ f.cycle()
+ f.cycle()
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after report-merge", false)
+ if err := f.monitor.LinkHostAgent(f.host.ID, f.nodes[0].ID); err != nil {
+ t.Fatal(err)
+ }
+
+ // A report before the adapter rebuilds: its generation still holds the
+ // split the link removed, which the unreadable store cannot confirm gone,
+ // so the state holds the link back while the persisted intent keeps its
+ // node. (Without the persisted fallback the entry would lose the node.)
+ flaky.fail.Store(true)
+ held := f.reportOnly()
+ if held.LinkedNodeID != "" {
+ t.Fatalf("the report linked node %q although the split could not be confirmed gone", held.LinkedNodeID)
+ }
+ snapshot := f.monitor.state.GetSnapshot()
+ for _, n := range snapshot.Nodes {
+ if n.LinkedAgentID != "" {
+ t.Fatalf("state links node %s to agent %q", n.ID, n.LinkedAgentID)
+ }
+ }
+ entry, ok := f.monitor.hostContinuityStore.Get(f.host.ID)
+ if !ok || entry.NodeLinkSource != "manual" || entry.LinkedNodeID != f.nodes[0].ID {
+ t.Fatalf("a held-back manual link lost its persisted intent: %+v", entry)
+ }
+
+ // A rebuild that cannot read the decisions loads none, so the link
+ // returns for now and the intent is unchanged.
+ f.cycle()
+ entry, ok = f.monitor.hostContinuityStore.Get(f.host.ID)
+ if !ok || entry.NodeLinkSource != "manual" || entry.LinkedNodeID != f.nodes[0].ID {
+ t.Fatalf("an unreadable split store ended the manual intent: %+v", entry)
+ }
+ flaky.fail.Store(false)
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after the store reads again", true)
+ if entry, _ := f.monitor.hostContinuityStore.Get(f.host.ID); entry.NodeLinkSource != "manual" {
+ t.Fatalf("manual intent became %q", entry.NodeLinkSource)
+ }
+}
+
+// sequencedSplitDecider answers "not split" for its first calls and "split"
+// from then on, as an operator's split recorded while a report is in flight
+// does.
+type sequencedSplitDecider struct {
+ calls atomic.Int32
+ splitFrom atomic.Int32
+}
+
+func (d *sequencedSplitDecider) ProxmoxNodeAgentSplit(models.Node, models.Host) bool {
+ return d.calls.Add(1) > d.splitFrom.Load()
+}
+
+// A split recorded after a report's own check but before the state stores
+// the agent is applied by the state; the report then neither returns, links
+// nor persists the node the state refused.
+func TestReportUsesTheLinkTheStateKeptWhenASplitLandsMidReport(t *testing.T) {
+ // The split is first seen by the state's own check of the agent's link
+ // (call 2), or only by its check of each node linked to the agent (call 3).
+ for _, seenAtCall := range []int32{1, 2} {
+ t.Run(fmt.Sprintf("seen after %d checks", seenAtCall), func(t *testing.T) {
+ testReportUsesTheLinkTheStateKept(t, seenAtCall)
+ })
+ }
+}
+
+func testReportUsesTheLinkTheStateKept(t *testing.T, splitFrom int32) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ f.assertLinked("before", true)
+ f.seedLXCFilesystems()
+
+ decider := &sequencedSplitDecider{}
+ decider.splitFrom.Store(1 << 30)
+ f.monitor.state.SetNodeAgentSplitDecider(decider)
+ f.monitor.state.UpdateNodesForInstance("lab", f.nodes)
+ f.monitor.state.UpsertHost(f.host)
+ // The report's own check (its first call) finds no split; the state's
+ // store of the agent (the next) does.
+ decider.calls.Store(0)
+ decider.splitFrom.Store(splitFrom)
+
+ held := f.reportOnly()
+ if held.LinkedNodeID != "" {
+ t.Fatalf("the report returned node %q that the state refused", held.LinkedNodeID)
+ }
+ snapshot := f.monitor.state.GetSnapshot()
+ for _, n := range snapshot.Nodes {
+ if n.LinkedAgentID != "" {
+ t.Fatalf("state links node %s to agent %q", n.ID, n.LinkedAgentID)
+ }
+ }
+ for _, h := range snapshot.Hosts {
+ if h.LinkedNodeID != "" {
+ t.Fatalf("state links agent %s to node %q", h.ID, h.LinkedNodeID)
+ }
+ }
+ entry, ok := f.monitor.hostContinuityStore.Get(f.host.ID)
+ if !ok || entry.LinkedNodeID != "" {
+ t.Fatalf("the report persisted node %q that the state refused: %+v", entry.LinkedNodeID, entry)
+ }
+ if got := f.lxcFilesystemEntries(); got != 0 {
+ t.Fatalf("%d container filesystem readings from the agent outlived the split", got)
+ }
+}
+
+// A confirmed split of a manual link ends the intent and clears what the
+// agent cached for the node's containers even where nothing infers another
+// node for the agent (inference has no node to substitute, so no later branch
+// would clear it).
+func TestConfirmedSplitOfAManualLinkClearsTheAgentsContainerReadings(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ if err := f.monitor.LinkHostAgent(f.host.ID, f.nodes[0].ID); err != nil {
+ t.Fatal(err)
+ }
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after the manual link", true)
+
+ // The agent no longer looks like the node to inference, and nothing but
+ // the manual intent ties it to the node.
+ f.report.Host.Hostname = "elsewhere"
+ f.report.Host.ReportIP = ""
+ f.seedLXCFilesystems()
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+
+ entry, ok := f.monitor.hostContinuityStore.Get(f.host.ID)
+ if !ok || entry.NodeLinkSource != "automatic" || entry.LinkedNodeID != "" {
+ t.Fatalf("a confirmed split left the manual intent: %+v", entry)
+ }
+ if got := f.lxcFilesystemEntries(); got != 0 {
+ t.Fatalf("%d container filesystem readings from the split agent outlived its manual link", got)
+ }
+}
+
+// A split agent whose name is its node's name must not hand the node its
+// sensors through the unlinked-agent hostname fallback.
+func TestSplitAgentSensorsDoNotReachTheNodeThroughItsName(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.report.Sensors.TemperatureCelsius = map[string]float64{"cpu_package": 61}
+ f.cycle()
+ f.cycle()
+ node := f.nodes[0]
+ if temp := f.monitor.getHostAgentTemperatureForNode(node); temp == nil || temp.CPUPackage != 61 {
+ t.Fatalf("a linked agent's temperature did not reach its node: %+v", temp)
+ }
+
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after report-merge", false)
+ if temp := f.monitor.getHostAgentTemperatureForNode(node); temp != nil {
+ t.Fatalf("the split agent's temperature reached the node through its name: %+v", temp)
+ }
+
+ // A reading the agent supplied before the split must not outlive the
+ // agent's lease because the split took it out of the node's slot.
+ carried := &models.Temperature{Available: true, CPUPackage: 61, LastUpdate: f.host.LastSeen}
+ if !f.monitor.carriedTemperatureOutlivesAgentLease(node, carried, time.Now().Add(time.Hour)) {
+ t.Fatal("a split agent's carried reading would outlive the agent's lapsed lease")
+ }
+}
+
+// Container filesystem readings an agent cached are not shown for a node the
+// operator split from that agent. Seeded after the split, so no cleanup has
+// run, they are ignored; a linked pair's reading is shown.
+func TestAgentContainerReadingsAreNotShownForANodeSplitFromTheAgent(t *testing.T) {
+ f := newNodeAgentSplitMonitor(t)
+ f.cycle()
+ f.cycle()
+ f.recordReportMerge()
+ f.cycle()
+ f.cycle()
+ f.assertLinked("after report-merge", false)
+
+ // The agent's reports name no node (as when its name matches none), so
+ // nothing on the report path clears what is cached.
+ f.seedLXCFilesystems()
+ container := models.Container{VMID: 200, Name: "ct200", Status: "running"}
+ f.monitor.enrichContainerWithAgentLXCFilesystems("lab", "pve1", &container, time.Now())
+ if len(container.Disks) != 0 {
+ t.Fatalf("the split agent's readings were shown for the node's container: %+v", container.Disks)
+ }
+
+ // A node that is not in state under this connection (a proven duplicate
+ // connection folded it into another's) is not split from the agent.
+ f.monitor.proxmoxLXCFilesystemsMu.Lock()
+ f.monitor.proxmoxLXCFilesystemsCache[agentLXCFilesystemCacheKey("ghost", "pve9", 300)] = agentLXCFilesystemCacheEntry{
+ agentID: f.host.ID,
+ name: "ct300",
+ disks: []models.Disk{{Mountpoint: "/", Total: 10 << 30, Used: 1 << 30}},
+ expiresAt: time.Now().Add(10 * time.Minute),
+ }
+ f.monitor.proxmoxLXCFilesystemsMu.Unlock()
+ ghost := models.Container{VMID: 300, Name: "ct300", Status: "running"}
+ f.monitor.enrichContainerWithAgentLXCFilesystems("ghost", "pve9", &ghost, time.Now())
+ if len(ghost.Disks) != 1 {
+ t.Fatalf("a reading for a node that left this connection's slot was hidden: %+v", ghost.Disks)
+ }
+
+ // The control: with the agent linked the same reading is shown.
+ linked := newNodeAgentSplitMonitor(t)
+ linked.cycle()
+ linked.cycle()
+ linked.assertLinked("control", true)
+ linked.seedLXCFilesystems()
+ control := models.Container{VMID: 200, Name: "ct200", Status: "running"}
+ linked.monitor.enrichContainerWithAgentLXCFilesystems("lab", "pve1", &control, time.Now())
+ if len(control.Disks) != 1 {
+ t.Fatalf("a linked agent's reading was not shown: %+v", control.Disks)
+ }
+}
diff --git a/internal/unifiedresources/proxmox_node_links.go b/internal/unifiedresources/proxmox_node_links.go
index 72cb6bbe72..30912a5376 100644
--- a/internal/unifiedresources/proxmox_node_links.go
+++ b/internal/unifiedresources/proxmox_node_links.go
@@ -1,6 +1,7 @@
package unifiedresources
import (
+ "errors"
"net"
"slices"
"strings"
@@ -284,21 +285,207 @@ func (rr *ResourceRegistry) splitProxmoxNodeLink(node models.Node, host *models.
if host == nil || len(rr.exclusions) == 0 {
return node, host
}
- _, nodeIdentity := resourceFromProxmoxNode(node, nil)
- _, hostIdentity := resourceFromHost(*host)
- if !rr.proxmoxNodeAgentSplitLocked(
- nodeAgentLinkSide{sourceID: nodeID, identity: nodeIdentity},
- nodeAgentLinkSide{sourceID: normalizeSourceID(host.ID), identity: hostIdentity},
- ) {
+ nodeSide, agentSide := proxmoxNodeAgentLinkSides(node, *host)
+ if !rr.proxmoxNodeAgentSplitLocked(nodeSide, agentSide) {
return node, host
}
if rr.splitAgents == nil {
rr.splitAgents = make(map[string]nodeAgentLinkSide)
}
- rr.splitAgents[nodeID] = nodeAgentLinkSide{sourceID: normalizeSourceID(host.ID), identity: hostIdentity}
+ rr.splitAgents[nodeID] = agentSide
return node, nil
}
+// proxmoxNodeAgentLinkSides returns the two sides of a monitored node and
+// agent pair as snapshot ingest reads them: each record's source ID and the
+// identity it derives on its own.
+func proxmoxNodeAgentLinkSides(node models.Node, host models.Host) (nodeAgentLinkSide, nodeAgentLinkSide) {
+ _, nodeIdentity := resourceFromProxmoxNode(node, nil)
+ _, hostIdentity := resourceFromHost(host)
+ return nodeAgentLinkSide{sourceID: normalizeSourceID(node.ID), identity: nodeIdentity},
+ nodeAgentLinkSide{sourceID: normalizeSourceID(host.ID), identity: hostIdentity}
+}
+
+// Monitoring keeps its own node<->agent link (models.Node.LinkedAgentID and
+// models.Host.LinkedNodeID), and that link, not the registry's rows, is what
+// the agent's SMART fallback and disk-exclude patterns on the node, guest
+// discovery, agent deployment, service discovery and the node and agent's
+// alert correlation read. It reads the operator's split from here
+// (models.NodeAgentSplitDecider) so it never treats a pair the registry
+// keeps apart as one machine, and the agents API's node link, an operator
+// decision newer than any split it overrides, removes that split here
+// first. The resource store therefore holds the one record of whether an
+// operator split a node from an agent.
+
+// ProxmoxNodeAgentSplit reports whether the operator split node from host's
+// agent, by the rule snapshot ingest applies to a node's link
+// (splitProxmoxNodeLink), also reading the agent under the ID the registry
+// holds it under (a pin can keep a machine-derived ID for an agent that no
+// longer reports its machine key). A registry without a store carries no
+// operator decisions. It takes no lock monitoring holds, so monitoring
+// calls it while holding its state lock.
+func (a *MonitorAdapter) ProxmoxNodeAgentSplit(node models.Node, host models.Host) bool {
+ registry := a.currentRegistry()
+ if registry == nil || registry.store == nil {
+ return false
+ }
+ return registry.proxmoxNodeAgentSplit(node, host)
+}
+
+// ProxmoxNodeAgentSplitConfirmed reports whether the store's latest
+// decisions split node from host's agent. Unlike ProxmoxNodeAgentSplit,
+// which keeps a split it cannot confirm, it reports an unreadable store as
+// an error, for decisions that must not rest on an unconfirmed split.
+func (a *MonitorAdapter) ProxmoxNodeAgentSplitConfirmed(node models.Node, host models.Host) (bool, error) {
+ registry := a.currentRegistry()
+ if registry == nil || registry.store == nil || strings.TrimSpace(node.ID) == "" || strings.TrimSpace(host.ID) == "" {
+ return false, nil
+ }
+ latest, err := storedOperatorPairDecisions(registry.store)
+ if err != nil {
+ return false, err
+ }
+ nodeSide, agentSide := registry.proxmoxNodeAgentLinkSidesHeld(node, host)
+ return registry.nodeAgentSplit(latest, nodeSide, agentSide), nil
+}
+
+// proxmoxNodeAgentLinkSidesHeld returns the pair's sides with the ID this
+// registry holds the agent under.
+func (rr *ResourceRegistry) proxmoxNodeAgentLinkSidesHeld(node models.Node, host models.Host) (nodeAgentLinkSide, nodeAgentLinkSide) {
+ nodeSide, agentSide := proxmoxNodeAgentLinkSides(node, host)
+ rr.mu.RLock()
+ agentSide.heldID = rr.bySource[SourceAgent][agentSide.sourceID]
+ rr.mu.RUnlock()
+ return nodeSide, agentSide
+}
+
+// proxmoxNodeAgentSplit decides by this generation's decisions, and a split
+// it finds is confirmed against the store's latest. Monitoring updates its
+// links before the rebuild that loads a newer decision, so by the
+// generation alone it would hold a relinked pair apart for one more poll,
+// and that rebuild would join the rows by the manual link alone, under the
+// link's primary ID rather than the ID the node's link joins them under.
+// Only a split is confirmed: splits are few, and a split monitoring misses
+// for a poll is applied by the registry to the node's link on that rebuild.
+// A split it cannot confirm, the store being unreadable, stands.
+func (rr *ResourceRegistry) proxmoxNodeAgentSplit(node models.Node, host models.Host) bool {
+ rr.mu.RLock()
+ none := len(rr.exclusions) == 0
+ rr.mu.RUnlock()
+ if none || strings.TrimSpace(node.ID) == "" || strings.TrimSpace(host.ID) == "" {
+ return false
+ }
+ nodeSide, agentSide := rr.proxmoxNodeAgentLinkSidesHeld(node, host)
+ rr.mu.RLock()
+ split := rr.proxmoxNodeAgentSplitLocked(nodeSide, agentSide)
+ rr.mu.RUnlock()
+ if !split {
+ return false
+ }
+ latest, err := storedOperatorPairDecisions(rr.store)
+ if err != nil {
+ return true
+ }
+ return rr.nodeAgentSplit(latest, nodeSide, agentSide)
+}
+
+// storedOperatorPairDecisions reads the store's current manual decisions as
+// loadOverrides does.
+func storedOperatorPairDecisions(store ResourceStore) (operatorPairDecisions, error) {
+ links, err := store.GetLinks()
+ if err != nil {
+ return operatorPairDecisions{}, err
+ }
+ exclusions, err := store.GetExclusions()
+ if err != nil {
+ return operatorPairDecisions{}, err
+ }
+ links, exclusions = effectiveManualPairDecisions(links, exclusions)
+ decisions := operatorPairDecisions{
+ exclusions: make(map[string]time.Time, len(exclusions)),
+ linksByID: indexLinksByID(links),
+ }
+ for _, exclusion := range exclusions {
+ key := exclusionKey(CanonicalResourceID(exclusion.ResourceA), CanonicalResourceID(exclusion.ResourceB))
+ if at, ok := decisions.exclusions[key]; !ok || exclusion.CreatedAt.After(at) {
+ decisions.exclusions[key] = exclusion.CreatedAt
+ }
+ }
+ return decisions, nil
+}
+
+// LiftProxmoxNodeAgentSplit removes from the store every exclusion that
+// splits node from host's agent (nodeAgentSplit reads them across the IDs
+// each side can hold, and the ID the registry holds the agent under), so
+// the agents API's node link, made after the split, joins the pair: at
+// once in monitoring, whose decider confirms a split against the store, and
+// in the registry on its next rebuild. It returns the exclusions it removed,
+// for RestoreProxmoxNodeAgentSplit should recording the link fail; if a
+// removal fails it restores the ones already removed and returns the error.
+// Exclusions between other IDs stay, among them report-merge's exclusion of
+// the agent's own candidate, which also records splitting another source
+// off the agent.
+func (a *MonitorAdapter) LiftProxmoxNodeAgentSplit(node models.Node, host models.Host) ([]ResourceExclusion, error) {
+ registry := a.currentRegistry()
+ if registry == nil || registry.store == nil {
+ return nil, nil
+ }
+ return registry.liftProxmoxNodeAgentSplit(node, host)
+}
+
+// RestoreProxmoxNodeAgentSplit records again exclusions a lift removed, with
+// their original times, reasons and authors. A pair the operator decided
+// about since (a link or a new exclusion) keeps that newer decision.
+func (a *MonitorAdapter) RestoreProxmoxNodeAgentSplit(removed []ResourceExclusion) error {
+ registry := a.currentRegistry()
+ if registry == nil || registry.store == nil {
+ return nil
+ }
+ return restoreExclusions(registry.store, removed)
+}
+
+func restoreExclusions(store ResourceStore, removed []ResourceExclusion) error {
+ var errs []error
+ for _, exclusion := range removed {
+ if _, err := store.RestoreExclusion(exclusion); err != nil {
+ errs = append(errs, err)
+ }
+ }
+ return errors.Join(errs...)
+}
+
+func (rr *ResourceRegistry) liftProxmoxNodeAgentSplit(node models.Node, host models.Host) ([]ResourceExclusion, error) {
+ if strings.TrimSpace(node.ID) == "" || strings.TrimSpace(host.ID) == "" {
+ return nil, nil
+ }
+ // The store's decisions, not the generation's: a split recorded since
+ // the last rebuild is older than this link too.
+ stored, err := rr.store.GetExclusions()
+ if err != nil {
+ return nil, err
+ }
+ nodeSide, agentSide := rr.proxmoxNodeAgentLinkSidesHeld(node, host)
+ nodeIDs, agentIDs := rr.nodeAgentPairIDs(nodeSide, agentSide)
+ var removed []ResourceExclusion
+ for _, exclusion := range stored {
+ left, right := CanonicalResourceID(exclusion.ResourceA), CanonicalResourceID(exclusion.ResourceB)
+ if left == right || !((slices.Contains(nodeIDs, left) && slices.Contains(agentIDs, right)) ||
+ (slices.Contains(nodeIDs, right) && slices.Contains(agentIDs, left))) {
+ continue
+ }
+ // The row taken is the one removed, whatever the operator recorded
+ // for the pair since the listing above.
+ taken, found, err := rr.store.TakeExclusion(left, right)
+ if err != nil {
+ return nil, errors.Join(err, restoreExclusions(rr.store, removed))
+ }
+ if found {
+ removed = append(removed, taken)
+ }
+ }
+ return removed, nil
+}
+
func inferLinkedHostsForProxmoxNodes(nodes []models.Node, hostByID map[string]*models.Host) map[string]*models.Host {
if len(nodes) == 0 || len(hostByID) == 0 {
return nil
diff --git a/internal/unifiedresources/store.go b/internal/unifiedresources/store.go
index 8f5d7fa85c..7751f99853 100644
--- a/internal/unifiedresources/store.go
+++ b/internal/unifiedresources/store.go
@@ -25,6 +25,18 @@ import (
type ResourceStore interface {
AddLink(link ResourceLink) error
AddExclusion(exclusion ResourceExclusion) error
+ // TakeExclusion deletes the pair's exclusion, either way round, and
+ // returns the row it deleted (false when the pair has none), so a newer
+ // operator decision recorded outside this store (the agents API's node
+ // link) replaces it, and the caller holds exactly what it replaced.
+ TakeExclusion(resourceA, resourceB string) (ResourceExclusion, bool, error)
+ // RestoreExclusion records an exclusion that TakeExclusion took away,
+ // unless the pair has been decided since: it declines a pair that has an
+ // exclusion in either order or a link at or after this exclusion's time, and
+ // reports whether it recorded it. An older link row left alongside the
+ // exclusion (older data, canonical-ID succession) is superseded by it, as
+ // it was before the take.
+ RestoreExclusion(exclusion ResourceExclusion) (bool, error)
GetLinks() ([]ResourceLink, error)
GetExclusions() ([]ResourceExclusion, error)
// Identity pins keep canonical IDs for merged-source hosts stable across
@@ -1305,6 +1317,121 @@ func (s *SQLiteResourceStore) GetLinks() ([]ResourceLink, error) {
return links, nil
}
+// TakeExclusion deletes the pair's exclusion in either order and returns the
+// row it deleted. The read and the delete share one transaction.
+func (s *SQLiteResourceStore) TakeExclusion(resourceA, resourceB string) (ResourceExclusion, bool, error) {
+ a, b := normalizePair(resourceA, resourceB)
+ if a == "" || b == "" {
+ return ResourceExclusion{}, false, fmt.Errorf("resource IDs required")
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ tx, err := s.db.Begin()
+ if err != nil {
+ return ResourceExclusion{}, false, fmt.Errorf("begin take of resource exclusion %q<->%q: %w", a, b, err)
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback()
+ }
+ }()
+ var taken ResourceExclusion
+ err = tx.QueryRow(`SELECT resource_a, resource_b, reason, created_by, created_at FROM resource_exclusions
+ WHERE (resource_a = ? AND resource_b = ?) OR (resource_a = ? AND resource_b = ?)
+ ORDER BY created_at DESC LIMIT 1`, a, b, b, a).
+ Scan(&taken.ResourceA, &taken.ResourceB, &taken.Reason, &taken.CreatedBy, &taken.CreatedAt)
+ if errors.Is(err, sql.ErrNoRows) {
+ return ResourceExclusion{}, false, nil
+ }
+ if err != nil {
+ return ResourceExclusion{}, false, fmt.Errorf("read resource exclusion %q<->%q: %w", a, b, err)
+ }
+ if _, err := tx.Exec(`DELETE FROM resource_exclusions
+ WHERE (resource_a = ? AND resource_b = ?) OR (resource_a = ? AND resource_b = ?)`, a, b, b, a); err != nil {
+ return ResourceExclusion{}, false, fmt.Errorf("remove resource exclusion %q<->%q: %w", a, b, err)
+ }
+ if err := tx.Commit(); err != nil {
+ return ResourceExclusion{}, false, fmt.Errorf("commit take of resource exclusion %q<->%q: %w", a, b, err)
+ }
+ committed = true
+ taken.ResourceA = CanonicalResourceID(taken.ResourceA)
+ taken.ResourceB = CanonicalResourceID(taken.ResourceB)
+ return taken, true, nil
+}
+
+// RestoreExclusion records the exclusion, with its original time, reason and
+// author, unless the pair has an exclusion in either order or a link recorded
+// at or after the exclusion's time (an older link row is superseded by it).
+// The check and the insert share one transaction.
+func (s *SQLiteResourceStore) RestoreExclusion(exclusion ResourceExclusion) (bool, error) {
+ if exclusion.ResourceA == "" || exclusion.ResourceB == "" {
+ return false, fmt.Errorf("resource IDs required")
+ }
+ a, b := normalizePair(exclusion.ResourceA, exclusion.ResourceB)
+ if exclusion.CreatedAt.IsZero() {
+ exclusion.CreatedAt = time.Now().UTC()
+ }
+ s.mu.Lock()
+ defer s.mu.Unlock()
+ tx, err := s.db.Begin()
+ if err != nil {
+ return false, fmt.Errorf("begin restore of resource exclusion %q<->%q: %w", a, b, err)
+ }
+ committed := false
+ defer func() {
+ if !committed {
+ _ = tx.Rollback()
+ }
+ }()
+ var exclusions int
+ if err := tx.QueryRow(`SELECT COUNT(*) FROM resource_exclusions
+ WHERE (resource_a = ? AND resource_b = ?) OR (resource_a = ? AND resource_b = ?)`,
+ a, b, b, a).Scan(&exclusions); err != nil {
+ return false, fmt.Errorf("read exclusions of resource pair %q<->%q: %w", a, b, err)
+ }
+ if exclusions > 0 {
+ return false, nil
+ }
+ linkTimes, err := tx.Query(`SELECT created_at FROM resource_links
+ WHERE (resource_a = ? AND resource_b = ?) OR (resource_a = ? AND resource_b = ?)`, a, b, b, a)
+ if err != nil {
+ return false, fmt.Errorf("read links of resource pair %q<->%q: %w", a, b, err)
+ }
+ newerLink := false
+ for linkTimes.Next() {
+ var linkedAt time.Time
+ if err := linkTimes.Scan(&linkedAt); err != nil {
+ _ = linkTimes.Close()
+ return false, fmt.Errorf("scan link time of resource pair %q<->%q: %w", a, b, err)
+ }
+ if !linkedAt.Before(exclusion.CreatedAt) {
+ newerLink = true
+ }
+ }
+ if err := linkTimes.Err(); err != nil {
+ _ = linkTimes.Close()
+ return false, fmt.Errorf("iterate links of resource pair %q<->%q: %w", a, b, err)
+ }
+ if err := linkTimes.Close(); err != nil {
+ return false, fmt.Errorf("close links of resource pair %q<->%q: %w", a, b, err)
+ }
+ if newerLink {
+ return false, nil
+ }
+ if _, err := tx.Exec(`
+ INSERT INTO resource_exclusions (resource_a, resource_b, reason, created_by, created_at)
+ VALUES (?, ?, ?, ?, ?)
+ `, a, b, exclusion.Reason, exclusion.CreatedBy, exclusion.CreatedAt); err != nil {
+ return false, fmt.Errorf("restore resource exclusion %q<->%q: %w", a, b, err)
+ }
+ if err := tx.Commit(); err != nil {
+ return false, fmt.Errorf("commit restore of resource exclusion %q<->%q: %w", a, b, err)
+ }
+ committed = true
+ return true, nil
+}
+
// GetExclusions returns the exclusions that are their pair's latest operator
// decision.
func (s *SQLiteResourceStore) GetExclusions() ([]ResourceExclusion, error) {
@@ -3633,6 +3760,46 @@ func (m *MemoryStore) AddExclusion(exclusion ResourceExclusion) error {
return nil
}
+func (m *MemoryStore) TakeExclusion(resourceA, resourceB string) (ResourceExclusion, bool, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ var taken ResourceExclusion
+ found := false
+ m.exclusions = slices.DeleteFunc(m.exclusions, func(existing ResourceExclusion) bool {
+ if !sameManualPair(existing.ResourceA, existing.ResourceB, resourceA, resourceB) {
+ return false
+ }
+ if !found || existing.CreatedAt.After(taken.CreatedAt) {
+ taken, found = existing, true
+ }
+ return true
+ })
+ return taken, found, nil
+}
+
+func (m *MemoryStore) RestoreExclusion(exclusion ResourceExclusion) (bool, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ exclusion.ResourceA = CanonicalResourceID(exclusion.ResourceA)
+ exclusion.ResourceB = CanonicalResourceID(exclusion.ResourceB)
+ if exclusion.ResourceA == "" || exclusion.ResourceB == "" {
+ return false, fmt.Errorf("resource IDs required")
+ }
+ if exclusion.CreatedAt.IsZero() {
+ exclusion.CreatedAt = time.Now().UTC()
+ }
+ if slices.ContainsFunc(m.links, func(link ResourceLink) bool {
+ return sameManualPair(link.ResourceA, link.ResourceB, exclusion.ResourceA, exclusion.ResourceB) &&
+ !link.CreatedAt.Before(exclusion.CreatedAt)
+ }) || slices.ContainsFunc(m.exclusions, func(existing ResourceExclusion) bool {
+ return sameManualPair(existing.ResourceA, existing.ResourceB, exclusion.ResourceA, exclusion.ResourceB)
+ }) {
+ return false, nil
+ }
+ m.exclusions = append(m.exclusions, exclusion)
+ return true, nil
+}
+
func (m *MemoryStore) GetLinks() ([]ResourceLink, error) {
m.mu.RLock()
defer m.mu.RUnlock()
diff --git a/internal/unifiedresources/store_test.go b/internal/unifiedresources/store_test.go
index 9641df9ff6..73d28d348a 100644
--- a/internal/unifiedresources/store_test.go
+++ b/internal/unifiedresources/store_test.go
@@ -8,6 +8,7 @@ import (
"os"
"path/filepath"
"reflect"
+ "sort"
"strings"
"testing"
"time"
@@ -3660,3 +3661,607 @@ func TestProxmoxDiskTemperatureAlertRowsFollowRecordedHardwareIdentity(t *testin
require.ElementsMatch(t, []string{"temperature"}, pveDiskHistoryIDs(byRef))
require.Equal(t, ref, OwnedAlertReference(byRef["temperature"]))
}
+
+// TakeExclusion deletes the pair's exclusion whichever way round it was
+// recorded, returns the row it deleted, and touches nothing else.
+func TestTakeExclusionDeletesThePairEitherWayRound(t *testing.T) {
+ sqliteStore, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, sqliteStore.Close()) })
+ for name, store := range map[string]ResourceStore{"sqlite": sqliteStore, "memory": NewMemoryStore()} {
+ t.Run(name, func(t *testing.T) {
+ now := time.Now().UTC()
+ require.NoError(t, store.AddExclusion(ResourceExclusion{ResourceA: "agent-b", ResourceB: "agent-a", CreatedAt: now}))
+ require.NoError(t, store.AddExclusion(ResourceExclusion{ResourceA: "agent-a", ResourceB: "agent-c", CreatedAt: now}))
+ taken, found, err := store.TakeExclusion("agent-a", "agent-b")
+ require.NoError(t, err)
+ require.True(t, found)
+ require.True(t, taken.CreatedAt.Equal(now), "took %v", taken.CreatedAt)
+ require.ElementsMatch(t, []string{"agent-a", "agent-b"}, []string{taken.ResourceA, taken.ResourceB})
+ _, found, err = store.TakeExclusion("agent-a", "agent-b")
+ require.NoError(t, err)
+ require.False(t, found, "a second take found a row")
+ exclusions, err := store.GetExclusions()
+ require.NoError(t, err)
+ require.Len(t, exclusions, 1)
+ require.Equal(t, [2]string{"agent-a", "agent-c"}, [2]string{exclusions[0].ResourceA, exclusions[0].ResourceB})
+ })
+ }
+}
+
+// monitorSplitFixture is a Proxmox node and the pulse-agent on the same
+// machine as monitoring sees them: a models.State holding the operator's
+// split decisions from a store-backed adapter, fed an agent report naming
+// the node and a node poll each cycle.
+type monitorSplitFixture struct {
+ t *testing.T
+ store ResourceStore
+ adapter *MonitorAdapter
+ state *models.State
+ node models.Node
+ host models.Host
+}
+
+func newMonitorSplitFixture(t *testing.T, cluster, agentHostname, machineID string) *monitorSplitFixture {
+ return newMonitorSplitFixtureWithStore(t, cluster, agentHostname, machineID, nil)
+}
+
+func newMonitorSplitFixtureWithStore(t *testing.T, cluster, agentHostname, machineID string, wrap func(ResourceStore) ResourceStore) *monitorSplitFixture {
+ t.Helper()
+ sqliteStore, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = sqliteStore.Close() })
+ var store ResourceStore = sqliteStore
+ if wrap != nil {
+ store = wrap(store)
+ }
+ now := time.Now().UTC()
+ f := &monitorSplitFixture{
+ t: t,
+ store: store,
+ adapter: NewMonitorAdapter(NewRegistry(store)),
+ state: models.NewState(),
+ node: models.Node{ID: "lab-pve1", Name: "pve1", Instance: "lab", ClusterName: cluster, Host: "https://10.0.0.5:8006", Status: "online", LastSeen: now},
+ host: models.Host{
+ ID: "host-pve1",
+ Hostname: agentHostname,
+ MachineID: machineID,
+ Status: "online",
+ LastSeen: now,
+ NetworkInterfaces: []models.HostNetworkInterface{{Name: "vmbr0", MAC: "aa:bb:cc:dd:ee:01", Addresses: []string{"10.0.0.5/24"}}},
+ },
+ }
+ f.state.SetNodeAgentSplitDecider(f.adapter)
+ return f
+}
+
+// cycle runs one agent report and one node poll through the state, then
+// rebuilds the adapter from the state's snapshot, as a monitor poll does.
+func (f *monitorSplitFixture) cycle() models.StateSnapshot {
+ report := f.host
+ report.NodeLinkSource = "automatic"
+ report.LinkedNodeID = f.node.ID
+ f.state.UpsertHost(report)
+ f.state.UpdateNodesForInstance(f.node.Instance, []models.Node{f.node})
+ snapshot := f.state.GetSnapshot()
+ f.adapter.PopulateFromSnapshot(snapshot)
+ return snapshot
+}
+
+// links returns the node's linked agent and the agent's linked node in the
+// state.
+func (f *monitorSplitFixture) links() (nodeLinksAgent, agentLinksNode string) {
+ f.t.Helper()
+ snapshot := f.state.GetSnapshot()
+ require.Len(f.t, snapshot.Nodes, 1)
+ require.Len(f.t, snapshot.Hosts, 1)
+ return snapshot.Nodes[0].LinkedAgentID, snapshot.Hosts[0].LinkedNodeID
+}
+
+// A state that starts with links an operator split holds them back before
+// any report: links it already holds when the decisions are installed, and
+// a manual link restored from host continuity, which the reconcile writes
+// for the node once its poll arrives.
+func TestMonitorStateHoldsBackSplitLinksItStartsWith(t *testing.T) {
+ f := newMonitorSplitFixture(t, "lab", "pve1", "0123456789abcdef")
+ f.cycle()
+ joined := hostRowsByFacet(t, f.adapter.GetAll()).joined
+ require.NotEmpty(t, joined)
+ nodeCandidate := SourceSpecificID(ResourceTypeAgent, SourceProxmox, f.node.ID)
+ require.NoError(t, f.store.AddExclusion(ResourceExclusion{ResourceA: joined, ResourceB: nodeCandidate, CreatedAt: time.Now().UTC()}))
+ f.adapter.PopulateFromSnapshot(f.state.GetSnapshot())
+
+ linked := f.state.GetSnapshot()
+ installed := models.NewState()
+ manual := f.host
+ manual.NodeLinkSource, manual.LinkedNodeID = "manual", f.node.ID
+ installed.UpsertHost(manual)
+ installed.UpdateNodesForInstance(f.node.Instance, linked.Nodes)
+ require.Equal(t, f.host.ID, installed.GetSnapshot().Nodes[0].LinkedAgentID, "fixture state without decisions links the pair")
+ installed.SetNodeAgentSplitDecider(f.adapter)
+ snapshot := installed.GetSnapshot()
+ require.Empty(t, snapshot.Nodes[0].LinkedAgentID, "installing the decisions held no node link back")
+ require.Empty(t, snapshot.Hosts[0].LinkedNodeID, "installing the decisions held no agent link back")
+
+ restarted := models.NewState()
+ restarted.SetNodeAgentSplitDecider(f.adapter)
+ restarted.UpsertHost(manual)
+ restarted.UpdateNodesForInstance(f.node.Instance, []models.Node{f.node})
+ snapshot = restarted.GetSnapshot()
+ require.Empty(t, snapshot.Nodes[0].LinkedAgentID, "the reconcile linked the node to its split manual agent")
+ require.Empty(t, snapshot.Hosts[0].LinkedNodeID, "the reconcile kept the split manual agent's link")
+ require.Equal(t, "manual", snapshot.Hosts[0].NodeLinkSource, "the state rewrote the manual intent before a report")
+ require.True(t, restarted.LinkNodeToHostAgent(f.node.ID, f.host.ID))
+ require.Empty(t, restarted.GetSnapshot().Nodes[0].LinkedAgentID, "LinkNodeToHostAgent linked a split pair")
+}
+
+// RestoreExclusion records an exclusion only for a pair nothing has decided
+// since, whichever way round the earlier decision was recorded.
+func TestRestoreExclusionKeepsANewerDecision(t *testing.T) {
+ sqliteStore, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, sqliteStore.Close()) })
+ for name, store := range map[string]ResourceStore{"sqlite": sqliteStore, "memory": NewMemoryStore()} {
+ t.Run(name, func(t *testing.T) {
+ at := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
+ original := ResourceExclusion{ResourceA: "agent-a", ResourceB: "agent-b", Reason: "operator", CreatedBy: "richard", CreatedAt: at}
+
+ restored, err := store.RestoreExclusion(original)
+ require.NoError(t, err)
+ require.True(t, restored, "an undecided pair takes the exclusion back")
+ exclusions, err := store.GetExclusions()
+ require.NoError(t, err)
+ require.Len(t, exclusions, 1)
+ require.Equal(t, "operator", exclusions[0].Reason)
+ require.Equal(t, "richard", exclusions[0].CreatedBy)
+ require.True(t, exclusions[0].CreatedAt.Equal(at), "restore kept the original time, got %v", exclusions[0].CreatedAt)
+
+ // A newer exclusion, recorded the other way round, stays.
+ _, found, err := store.TakeExclusion("agent-a", "agent-b")
+ require.NoError(t, err)
+ require.True(t, found)
+ require.NoError(t, store.AddExclusion(ResourceExclusion{ResourceA: "agent-b", ResourceB: "agent-a", Reason: "newer", CreatedAt: time.Now().UTC()}))
+ restored, err = store.RestoreExclusion(original)
+ require.NoError(t, err)
+ require.False(t, restored, "an exclusion recorded since was replaced")
+ exclusions, err = store.GetExclusions()
+ require.NoError(t, err)
+ require.Len(t, exclusions, 1)
+ require.Equal(t, "newer", exclusions[0].Reason)
+
+ // A newer link replaces the exclusion for the pair, and a restore
+ // must not take that link away.
+ require.NoError(t, store.AddLink(ResourceLink{ResourceA: "agent-a", ResourceB: "agent-b", PrimaryID: "agent-a", CreatedAt: time.Now().UTC()}))
+ restored, err = store.RestoreExclusion(original)
+ require.NoError(t, err)
+ require.False(t, restored, "a link recorded since was replaced")
+ links, err := store.GetLinks()
+ require.NoError(t, err)
+ require.Len(t, links, 1)
+ exclusions, err = store.GetExclusions()
+ require.NoError(t, err)
+ require.Empty(t, exclusions)
+ })
+ }
+}
+
+// An older link row left beside an exclusion (older data, canonical-ID
+// succession) is superseded by it, so taking the exclusion and restoring it
+// after a failed operation brings the split back, while a link newer than the
+// exclusion still blocks the restore.
+func TestRestoreExclusionIgnoresALinkOlderThanIt(t *testing.T) {
+ sqliteStore, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, sqliteStore.Close()) })
+ memoryStore := NewMemoryStore()
+ seedLink := map[string]func(link ResourceLink){
+ "sqlite": func(link ResourceLink) {
+ _, err := sqliteStore.db.Exec(`INSERT INTO resource_links (resource_a, resource_b, primary_id, reason, created_by, created_at)
+ VALUES (?, ?, ?, 'raw', 'test', ?)`, link.ResourceA, link.ResourceB, link.PrimaryID, link.CreatedAt)
+ require.NoError(t, err)
+ },
+ "memory": func(link ResourceLink) { memoryStore.links = append(memoryStore.links, link) },
+ }
+ for name, store := range map[string]ResourceStore{"sqlite": sqliteStore, "memory": memoryStore} {
+ t.Run(name, func(t *testing.T) {
+ now := time.Now().UTC().Truncate(time.Second)
+ exclusion := ResourceExclusion{ResourceA: "agent-a", ResourceB: "agent-b", Reason: "split", CreatedAt: now}
+
+ // The stale link is older than the exclusion that superseded it.
+ seedLink[name](ResourceLink{ResourceA: "agent-a", ResourceB: "agent-b", PrimaryID: "agent-a", CreatedAt: now.Add(-time.Hour)})
+ restored, err := store.RestoreExclusion(exclusion)
+ require.NoError(t, err)
+ require.True(t, restored, "an older link row blocked restoring the split")
+ exclusions, err := store.GetExclusions()
+ require.NoError(t, err)
+ require.Len(t, exclusions, 1)
+ links, err := store.GetLinks()
+ require.NoError(t, err)
+ require.Empty(t, links, "the restored split did not supersede the older link")
+
+ // A link newer than the exclusion blocks the restore.
+ _, found, err := store.TakeExclusion("agent-a", "agent-b")
+ require.NoError(t, err)
+ require.True(t, found)
+ seedLink[name](ResourceLink{ResourceA: "agent-b", ResourceB: "agent-a", PrimaryID: "agent-b", CreatedAt: now.Add(time.Hour)})
+ restored, err = store.RestoreExclusion(exclusion)
+ require.NoError(t, err)
+ require.False(t, restored, "a newer link was ignored")
+ })
+ }
+}
+
+// A SQLite row stored in the reversed order, as older data can be, counts as
+// the pair's decision: a restore declines it and a take finds it.
+func TestSQLiteExclusionRowsInEitherOrderAreOneDecision(t *testing.T) {
+ store, err := NewSQLiteResourceStore(t.TempDir(), "default")
+ require.NoError(t, err)
+ t.Cleanup(func() { require.NoError(t, store.Close()) })
+ insert := func(table, a, b string) {
+ t.Helper()
+ columns := "resource_a, resource_b, reason, created_by, created_at"
+ values := "?, ?, 'raw', 'test', ?"
+ args := []any{a, b, time.Now().UTC()}
+ if table == "resource_links" {
+ columns, values = "resource_a, resource_b, primary_id, reason, created_by, created_at", "?, ?, ?, 'raw', 'test', ?"
+ args = []any{a, b, a, time.Now().UTC()}
+ }
+ _, err := store.db.Exec(`INSERT INTO `+table+` (`+columns+`) VALUES (`+values+`)`, args...)
+ require.NoError(t, err)
+ }
+ original := ResourceExclusion{ResourceA: "agent-a", ResourceB: "agent-b", CreatedAt: time.Now().UTC()}
+
+ // The rows are stored a > b, against the normalised order.
+ insert("resource_exclusions", "agent-b", "agent-a")
+ restored, err := store.RestoreExclusion(original)
+ require.NoError(t, err)
+ require.False(t, restored, "a reversed exclusion row was not seen")
+ taken, found, err := store.TakeExclusion("agent-a", "agent-b")
+ require.NoError(t, err)
+ require.True(t, found, "a reversed exclusion row was not taken")
+ require.Equal(t, "raw", taken.Reason)
+ left, err := store.GetExclusions()
+ require.NoError(t, err)
+ require.Empty(t, left, "taking a reversed exclusion row left it behind")
+
+ insert("resource_links", "agent-b", "agent-a")
+ restored, err = store.RestoreExclusion(original)
+ require.NoError(t, err)
+ require.False(t, restored, "a reversed link row was not seen")
+}
+
+// failingRemoveStore fails the nth TakeExclusion call.
+type failingRemoveStore struct {
+ ResourceStore
+ failOn int
+ calls int
+ // before runs once, ahead of the next take.
+ before func()
+}
+
+func (s *failingRemoveStore) TakeExclusion(resourceA, resourceB string) (ResourceExclusion, bool, error) {
+ if hook := s.before; hook != nil {
+ s.before = nil
+ hook()
+ }
+ s.calls++
+ if s.calls == s.failOn {
+ return ResourceExclusion{}, false, errors.New("remove failed")
+ }
+ return s.ResourceStore.TakeExclusion(resourceA, resourceB)
+}
+
+// Lifting a node's split from its agent restores what it removed when it
+// cannot finish, and what a caller restores later never replaces a decision
+// the operator recorded in between.
+func TestLiftedNodeAgentSplitRestoresOnlyWhatIsStillUndecided(t *testing.T) {
+ var failing *failingRemoveStore
+ f := newMonitorSplitFixtureWithStore(t, "lab", "pve1", "0123456789abcdef", func(store ResourceStore) ResourceStore {
+ failing = &failingRemoveStore{ResourceStore: store}
+ return failing
+ })
+ f.cycle()
+ f.cycle()
+ merged := hostRowsByFacet(t, f.adapter.GetAll()).joined
+ require.NotEmpty(t, merged)
+ var nodeCandidate, agentCandidate string
+ for _, target := range f.adapter.currentRegistry().SourceTargets(merged) {
+ switch target.Source {
+ case SourceProxmox:
+ nodeCandidate = target.CandidateID
+ case SourceAgent:
+ agentCandidate = target.CandidateID
+ }
+ }
+ require.NotEmpty(t, nodeCandidate)
+ require.NotEmpty(t, agentCandidate)
+ at := time.Now().UTC().Add(-time.Minute).Truncate(time.Second)
+ first := ResourceExclusion{ResourceA: merged, ResourceB: nodeCandidate, Reason: "first", CreatedAt: at}
+ second := ResourceExclusion{ResourceA: agentCandidate, ResourceB: nodeCandidate, Reason: "second", CreatedAt: at.Add(time.Second)}
+ require.NoError(t, f.store.AddExclusion(first))
+ require.NoError(t, f.store.AddExclusion(second))
+ f.cycle()
+ snapshot := f.state.GetSnapshot()
+ node, host := snapshot.Nodes[0], snapshot.Hosts[0]
+
+ reasons := func() []string {
+ exclusions, err := f.store.GetExclusions()
+ require.NoError(t, err)
+ out := make([]string, 0, len(exclusions))
+ for _, exclusion := range exclusions {
+ out = append(out, exclusion.Reason+"@"+exclusion.CreatedAt.UTC().Format(time.RFC3339))
+ }
+ sort.Strings(out)
+ return out
+ }
+ before := reasons()
+ require.Len(t, before, 2)
+
+ // The second removal fails: the first is put back, with its time.
+ failing.calls, failing.failOn = 0, 2
+ removed, err := f.adapter.LiftProxmoxNodeAgentSplit(node, host)
+ require.Error(t, err)
+ require.Empty(t, removed)
+ require.Equal(t, before, reasons(), "a failed lift changed the split")
+
+ // A lift that finishes returns what it removed.
+ failing.failOn = 0
+ removed, err = f.adapter.LiftProxmoxNodeAgentSplit(node, host)
+ require.NoError(t, err)
+ require.Len(t, removed, 2)
+ require.Empty(t, reasons())
+
+ // The operator decides one pair again before the restore: a link for the
+ // first, a new exclusion for the second.
+ require.NoError(t, f.store.AddLink(ResourceLink{ResourceA: merged, ResourceB: nodeCandidate, PrimaryID: merged, CreatedAt: time.Now().UTC()}))
+ require.NoError(t, f.store.AddExclusion(ResourceExclusion{ResourceA: agentCandidate, ResourceB: nodeCandidate, Reason: "newer", CreatedAt: time.Now().UTC()}))
+ require.NoError(t, f.adapter.RestoreProxmoxNodeAgentSplit(removed))
+ links, err := f.store.GetLinks()
+ require.NoError(t, err)
+ require.Len(t, links, 1, "the restore took a newer link away")
+ exclusions, err := f.store.GetExclusions()
+ require.NoError(t, err)
+ require.Len(t, exclusions, 1)
+ require.Equal(t, "newer", exclusions[0].Reason, "the restore replaced a newer exclusion")
+}
+
+// A lift returns the row it actually removed: an operator who replaces the
+// pair's exclusion between the lift's listing and its removal has that newer
+// row taken and, if the caller restores, put back, never the older one read
+// from the listing.
+func TestLiftedNodeAgentSplitReturnsTheRowItRemoved(t *testing.T) {
+ var racing *failingRemoveStore
+ f := newMonitorSplitFixtureWithStore(t, "lab", "pve1", "0123456789abcdef", func(store ResourceStore) ResourceStore {
+ racing = &failingRemoveStore{ResourceStore: store}
+ return racing
+ })
+ f.cycle()
+ f.cycle()
+ merged := hostRowsByFacet(t, f.adapter.GetAll()).joined
+ require.NotEmpty(t, merged)
+ nodeCandidate := SourceSpecificID(ResourceTypeAgent, SourceProxmox, f.node.ID)
+ require.NoError(t, f.store.AddExclusion(ResourceExclusion{ResourceA: merged, ResourceB: nodeCandidate, Reason: "first", CreatedAt: time.Now().UTC().Add(-time.Minute)}))
+ f.cycle()
+ snapshot := f.state.GetSnapshot()
+
+ racing.before = func() {
+ require.NoError(t, f.store.AddExclusion(ResourceExclusion{ResourceA: nodeCandidate, ResourceB: merged, Reason: "newer", CreatedAt: time.Now().UTC()}))
+ }
+ removed, err := f.adapter.LiftProxmoxNodeAgentSplit(snapshot.Nodes[0], snapshot.Hosts[0])
+ require.NoError(t, err)
+ require.Len(t, removed, 1)
+ require.Equal(t, "newer", removed[0].Reason, "the lift returned the row it listed, not the one it removed")
+ remaining, err := f.store.GetExclusions()
+ require.NoError(t, err)
+ require.Empty(t, remaining)
+
+ require.NoError(t, f.adapter.RestoreProxmoxNodeAgentSplit(removed))
+ remaining, err = f.store.GetExclusions()
+ require.NoError(t, err)
+ require.Len(t, remaining, 1)
+ require.Equal(t, "newer", remaining[0].Reason)
+}
+
+// An agent that stops reporting its machine key after an unlink naming the
+// ID the pair merged under (its machine-derived ID) keeps that ID through
+// its pin, and stays split from the node in monitoring as in the registry.
+func TestMonitorStateKeepsASplitWhenTheAgentStopsReportingItsMachineID(t *testing.T) {
+ f := newMonitorSplitFixture(t, "", "pve1", "0123456789abcdef")
+ f.cycle()
+ f.cycle()
+ merged := hostRowsByFacet(t, f.adapter.GetAll()).joined
+ require.NotEmpty(t, merged)
+ nodeCandidate := SourceSpecificID(ResourceTypeAgent, SourceProxmox, f.node.ID)
+ require.NoError(t, f.store.AddExclusion(ResourceExclusion{ResourceA: merged, ResourceB: nodeCandidate, CreatedAt: time.Now().UTC()}))
+ for i := 0; i < 3; i++ {
+ f.cycle()
+ }
+ nodeLink, agentLink := f.links()
+ require.Empty(t, nodeLink+agentLink, "split did not reach the state")
+
+ f.host.MachineID = ""
+ for cycle := 1; cycle <= 3; cycle++ {
+ f.cycle()
+ rows := hostRowsByFacet(t, f.adapter.GetAll())
+ require.Empty(t, rows.joined, "cycle %d: registry joined the pair", cycle)
+ require.Equal(t, merged, rows.agent, "cycle %d: the agent left the ID its pin holds", cycle)
+ nodeLink, agentLink := f.links()
+ require.Empty(t, nodeLink+agentLink, "cycle %d: state relinked the split pair", cycle)
+ }
+}
+
+// An operator split of a node and its agent reaches monitoring's own link:
+// once the adapter's registry generation carries the split, the state names
+// neither side on the other, and every view of the registry still keeps the
+// pair apart although no record links them any more (the node's joined-era
+// identity pin included). A relink of the rows joins them in both again,
+// and the same request after it splits them again.
+func TestMonitorStateHoldsBackAnOperatorSplitNodeAgentLink(t *testing.T) {
+ for _, link := range []struct {
+ name string
+ cluster string
+ agentHostname string
+ machineID string
+ }{
+ {"unclustered", "", "pve1", "0123456789abcdef"},
+ {"clustered", "lab", "pve1", "0123456789abcdef"},
+ {"clustered-agent-fqdn", "lab", "pve1.example", "0123456789abcdef"},
+ {"clustered-machine-keyless-agent", "lab", "pve1", ""},
+ } {
+ for _, request := range []struct {
+ name string
+ exclusions func(ids splitRequestIDs) [][2]string
+ split func(ids splitRequestIDs) bool
+ }{
+ {"report-merge", func(ids splitRequestIDs) [][2]string {
+ return [][2]string{{ids.merged, ids.nodeCandidate}, {ids.merged, ids.agentCandidate}}
+ }, splitAlways},
+ {"unlink-naming-node", func(ids splitRequestIDs) [][2]string {
+ return [][2]string{{ids.merged, ids.nodeCandidate}}
+ }, splitAlways},
+ {"unlink-naming-node-row", func(ids splitRequestIDs) [][2]string {
+ return [][2]string{{ids.nodeOwn, ids.agentOwn}}
+ }, func(ids splitRequestIDs) bool { return ids.nodeOwn != ids.agentOwn }},
+ {"unlink-naming-both-candidates", func(ids splitRequestIDs) [][2]string {
+ return [][2]string{{ids.agentCandidate, ids.nodeCandidate}}
+ }, splitAlways},
+ {"exclusion-naming-only-the-agent", func(ids splitRequestIDs) [][2]string {
+ return [][2]string{{ids.merged, ids.agentCandidate}}
+ }, func(ids splitRequestIDs) bool { return ids.merged == ids.nodeOwn }},
+ {"unrelated-exclusion", func(ids splitRequestIDs) [][2]string {
+ return [][2]string{{ids.merged, "agent-00000000deadbeef"}}
+ }, func(splitRequestIDs) bool { return false }},
+ } {
+ t.Run(link.name+"/"+request.name, func(t *testing.T) {
+ f := newMonitorSplitFixture(t, link.cluster, link.agentHostname, link.machineID)
+ now := time.Now().UTC()
+ alone := NewRegistry(nil)
+ alone.IngestSnapshot(models.StateSnapshot{LastUpdate: now, Nodes: []models.Node{f.node}})
+ nodeAlone := hostRowsByFacet(t, alone.List()).node
+ alone = NewRegistry(nil)
+ alone.IngestSnapshot(models.StateSnapshot{LastUpdate: now, Hosts: []models.Host{f.host}})
+ agentAlone := hostRowsByFacet(t, alone.List()).agent
+
+ f.cycle()
+ merged := hostRowsByFacet(t, f.adapter.GetAll())
+ nodeLink, agentLink := f.links()
+ if merged.joined == "" || nodeLink != f.host.ID || agentLink != f.node.ID {
+ t.Fatalf("fixture did not link the node and the agent: rows %+v, node->%q agent->%q", merged, nodeLink, agentLink)
+ }
+ reportMerge := func() splitRequestIDs {
+ t.Helper()
+ ids := splitRequestIDs{merged: merged.joined, nodeOwn: nodeAlone, agentOwn: agentAlone}
+ for _, target := range f.adapter.currentRegistry().SourceTargets(merged.joined) {
+ switch target.Source {
+ case SourceProxmox:
+ ids.nodeCandidate = target.CandidateID
+ case SourceAgent:
+ ids.agentCandidate = target.CandidateID
+ }
+ }
+ if ids.nodeCandidate == "" || ids.agentCandidate == "" {
+ t.Fatalf("merged %s lists candidates %+v", merged.joined, ids)
+ }
+ return ids
+ }
+ record := func(ids splitRequestIDs) {
+ t.Helper()
+ for _, pair := range request.exclusions(ids) {
+ require.NoError(t, f.store.AddExclusion(ResourceExclusion{ResourceA: pair[0], ResourceB: pair[1], CreatedAt: time.Now().UTC()}))
+ }
+ }
+ ids := reportMerge()
+ record(ids)
+ split := request.split(ids)
+ want := nodeAgentRows{joined: merged.joined}
+ if split {
+ want = nodeAgentRows{node: nodeAlone, agent: agentAlone}
+ }
+
+ // The first cycle after a request still reads the decisions
+ // of the generation before it (the rebuild ending that cycle
+ // loads the request), so the state's links are checked from
+ // the second cycle on. Every view is checked every cycle.
+ assertCycles := func(step string, cycles int, want nodeAgentRows, linked bool) {
+ t.Helper()
+ for cycle := 1; cycle <= cycles; cycle++ {
+ snapshot := f.cycle()
+ listed := f.adapter.GetAll()
+ broadcast, ok := f.adapter.CoalesceForPresentation(listed, nil)
+ require.True(t, ok)
+ rest := NewRegistry(f.store)
+ rest.IngestResources(listed)
+ restFromSnapshot := NewRegistry(f.store)
+ restFromSnapshot.IngestSnapshot(snapshot)
+ for view, resources := range map[string][]Resource{
+ "monitor": listed,
+ "broadcast": broadcast,
+ "rest": rest.List(),
+ "rest presentation": rest.ListForPresentation(),
+ "rest from snapshot": restFromSnapshot.List(),
+ "rest presentation snapshot": restFromSnapshot.ListForPresentation(),
+ } {
+ if got := hostRowsByFacet(t, resources); got != want {
+ t.Fatalf("%s cycle %d %s: got %+v, want %+v", step, cycle, view, got, want)
+ }
+ }
+ if cycle == 1 {
+ continue
+ }
+ nodeLink, agentLink := f.links()
+ if gotLinked := nodeLink != "" || agentLink != ""; gotLinked != linked || (linked && (nodeLink != f.host.ID || agentLink != f.node.ID)) {
+ t.Fatalf("%s cycle %d: state links node->%q agent->%q, want linked=%v", step, cycle, nodeLink, agentLink, linked)
+ }
+ // A report naming the node, before any poll, keeps a
+ // split pair apart on its own.
+ if !linked {
+ report := f.host
+ report.NodeLinkSource = "automatic"
+ report.LinkedNodeID = f.node.ID
+ f.state.UpsertHost(report)
+ if nodeLink, agentLink := f.links(); nodeLink != "" || agentLink != "" {
+ t.Fatalf("%s cycle %d: a report linked node->%q agent->%q", step, cycle, nodeLink, agentLink)
+ }
+ }
+ for _, resource := range listed {
+ if resource.Proxmox != nil && resource.Agent == nil && resource.Proxmox.LinkedAgentID != "" {
+ t.Fatalf("%s cycle %d: split node row names agent %q", step, cycle, resource.Proxmox.LinkedAgentID)
+ }
+ }
+ }
+ }
+ assertCycles("after the request", 3, want, !split)
+ if !split {
+ return
+ }
+ // A registry meeting the agent first, which holds its
+ // machine-derived ID, with the node naming no agent and the
+ // joined-era pins still in the store.
+ held := f.state.GetSnapshot()
+ withoutHost := held
+ withoutHost.Hosts = nil
+ for name, snapshot := range map[string]models.StateSnapshot{"with host": held, "without host": withoutHost} {
+ agentFirst := NewRegistry(f.store)
+ agentFirst.IngestRecords(SourceAgent, []IngestRecord{HostIngestRecord(f.host)})
+ agentFirst.IngestSnapshot(snapshot)
+ for view, resources := range map[string][]Resource{"list": agentFirst.List(), "presentation": agentFirst.ListForPresentation()} {
+ if got := hostRowsByFacet(t, resources); got != want {
+ t.Fatalf("agent ingested first, snapshot %s, %s: got %+v, want %+v", name, view, got, want)
+ }
+ }
+ }
+
+ require.NoError(t, f.store.AddLink(ResourceLink{ResourceA: want.agent, ResourceB: want.node, PrimaryID: want.agent, CreatedAt: time.Now().UTC()}))
+ assertCycles("after relink", 3, nodeAgentRows{joined: merged.joined}, true)
+ reordered := NewRegistry(f.store)
+ reordered.IngestRecords(SourceAgent, []IngestRecord{HostIngestRecord(f.host)})
+ reordered.IngestSnapshot(f.state.GetSnapshot())
+ reordered.PersistIdentityPins()
+ assertCycles("after an agent-first rebuild persisted its pins", 2, nodeAgentRows{joined: merged.joined}, true)
+
+ record(reportMerge())
+ assertCycles("after splitting again", 3, want, false)
+ })
+ }
+ }
+}