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.

Heal forked host identities after a hostname rename

rcourtmanfbf1da43e428
diff --git a/internal/monitoring/issue1667_host_rename_heal_test.go b/internal/monitoring/issue1667_host_rename_heal_test.go
new file mode 100644
index 0000000000..b40eb77005
--- /dev/null
+++ b/internal/monitoring/issue1667_host_rename_heal_test.go
@@ -0,0 +1,158 @@
+package monitoring
+
+import (
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+ agentshost "github.com/rcourtman/pulse-go-rewrite/pkg/agents/host"
+)
+
+func issue1667Report(hostname string, at time.Time) agentshost.Report {
+ return agentshost.Report{
+ Agent: agentshost.AgentInfo{
+ ID: "mac-02d9aee1c3a1",
+ Type: "unified",
+ Version: "6.1.2",
+ IntervalSeconds: 30,
+ },
+ Host: agentshost.HostInfo{
+ ID: "mac-02d9aee1c3a1",
+ Hostname: hostname,
+ Platform: "linux",
+ MachineID: "machine-issue1667",
+ },
+ Timestamp: at,
+ }
+}
+
+func issue1667AgeHost(t *testing.T, m *Monitor, hostID string, lastSeen time.Time) {
+ t.Helper()
+ for _, h := range m.state.GetHosts() {
+ if h.ID == hostID {
+ h.LastSeen = lastSeen
+ m.state.UpsertHost(h)
+ return
+ }
+ }
+ t.Fatalf("host %q not found in state", hostID)
+}
+
+// Issue #1667: a hostname change on the same machine and token (e.g. the Home
+// Assistant add-on gaining agent_hostname after first boot) forked the host
+// module onto a suffixed identity while workload modules kept the base agent
+// ID, permanently splitting one machine into two agent identities. Once the
+// pre-rename record has clearly stopped reporting, the fork must heal back to
+// the base identity.
+func TestApplyHostReportRenameHealsForkedIdentity(t *testing.T) {
+ monitor := newTestMonitor(t)
+ monitor.hostTokenBindings = make(map[string]string)
+ token := &config.APITokenRecord{ID: "token-issue1667", Name: "HA"}
+
+ now := time.Now().UTC()
+ original, err := monitor.ApplyHostReport(issue1667Report("3ec0269c-pulse-docker-agent", now), token)
+ if err != nil {
+ t.Fatalf("first report: %v", err)
+ }
+
+ // Rename while the old record is still fresh: this is indistinguishable
+ // from a cloned VM sharing a machine ID (#1584), so it must still fork.
+ forked, err := monitor.ApplyHostReport(issue1667Report("homeassistant", now.Add(30*time.Second)), token)
+ if err != nil {
+ t.Fatalf("renamed report: %v", err)
+ }
+ if forked.ID == original.ID {
+ t.Fatalf("expected fork while the old hostname record is fresh, both got %q", forked.ID)
+ }
+
+ // The machine only reports under the new hostname, so the pre-rename
+ // record goes quiet. Once it is stale the fork is proven to be a rename.
+ issue1667AgeHost(t, monitor, original.ID, now.Add(-24*time.Hour))
+
+ healed, err := monitor.ApplyHostReport(issue1667Report("homeassistant", now.Add(60*time.Second)), token)
+ if err != nil {
+ t.Fatalf("healing report: %v", err)
+ }
+ if healed.ID != original.ID {
+ t.Fatalf("expected heal back to base identity %q, got %q", original.ID, healed.ID)
+ }
+
+ hosts := monitor.state.GetHosts()
+ if len(hosts) != 1 {
+ t.Fatalf("expected exactly one host after heal, got %d", len(hosts))
+ }
+ if hosts[0].ID != original.ID || hosts[0].Hostname != "homeassistant" {
+ t.Fatalf("expected base identity with new hostname, got ID %q hostname %q", hosts[0].ID, hosts[0].Hostname)
+ }
+}
+
+// A rename discovered only after the old record already went stale (agent was
+// stopped, hostname changed, agent restarted later) must adopt the base
+// identity directly instead of forking at all.
+func TestApplyHostReportRenameAdoptsBaseWhenOldRecordStale(t *testing.T) {
+ monitor := newTestMonitor(t)
+ monitor.hostTokenBindings = make(map[string]string)
+ token := &config.APITokenRecord{ID: "token-issue1667b", Name: "HA"}
+
+ now := time.Now().UTC()
+ original, err := monitor.ApplyHostReport(issue1667Report("old-name", now), token)
+ if err != nil {
+ t.Fatalf("first report: %v", err)
+ }
+
+ issue1667AgeHost(t, monitor, original.ID, now.Add(-24*time.Hour))
+
+ renamed, err := monitor.ApplyHostReport(issue1667Report("new-name", now.Add(30*time.Second)), token)
+ if err != nil {
+ t.Fatalf("renamed report: %v", err)
+ }
+ if renamed.ID != original.ID {
+ t.Fatalf("expected stale rename to keep base identity %q, got %q", original.ID, renamed.ID)
+ }
+
+ hosts := monitor.state.GetHosts()
+ if len(hosts) != 1 {
+ t.Fatalf("expected exactly one host after stale rename, got %d", len(hosts))
+ }
+ if hosts[0].Hostname != "new-name" {
+ t.Fatalf("expected hostname to follow the rename, got %q", hosts[0].Hostname)
+ }
+}
+
+// Two live machines flapping on one machine ID (cloned VMs, #1584) must keep
+// their forked identities: the heal only fires when the colliding record has
+// stopped reporting.
+func TestApplyHostReportCloneKeepsForkedIdentity(t *testing.T) {
+ monitor := newTestMonitor(t)
+ monitor.hostTokenBindings = make(map[string]string)
+ token := &config.APITokenRecord{ID: "token-issue1667c", Name: "HA"}
+
+ now := time.Now().UTC()
+ cloneA, err := monitor.ApplyHostReport(issue1667Report("clone-a", now), token)
+ if err != nil {
+ t.Fatalf("clone-a report: %v", err)
+ }
+ cloneB, err := monitor.ApplyHostReport(issue1667Report("clone-b", now.Add(15*time.Second)), token)
+ if err != nil {
+ t.Fatalf("clone-b report: %v", err)
+ }
+ if cloneB.ID == cloneA.ID {
+ t.Fatalf("expected clones to fork, both got %q", cloneB.ID)
+ }
+
+ // Both keep reporting: no heal, identities stay split.
+ againA, err := monitor.ApplyHostReport(issue1667Report("clone-a", now.Add(30*time.Second)), token)
+ if err != nil {
+ t.Fatalf("clone-a second report: %v", err)
+ }
+ againB, err := monitor.ApplyHostReport(issue1667Report("clone-b", now.Add(45*time.Second)), token)
+ if err != nil {
+ t.Fatalf("clone-b second report: %v", err)
+ }
+ if againA.ID != cloneA.ID || againB.ID != cloneB.ID {
+ t.Fatalf("expected stable forked identities, got %q/%q then %q/%q", cloneA.ID, cloneB.ID, againA.ID, againB.ID)
+ }
+ if len(monitor.state.GetHosts()) != 2 {
+ t.Fatalf("expected two host records for live clones, got %d", len(monitor.state.GetHosts()))
+ }
+}
diff --git a/internal/monitoring/monitor_agents.go b/internal/monitoring/monitor_agents.go
index a24f4cf701..417b5737ad 100644
--- a/internal/monitoring/monitor_agents.go
+++ b/internal/monitoring/monitor_agents.go
@@ -2272,6 +2272,85 @@ func staleHostIdentityForReenrollment(report agentshost.Report, tokenRecord *con
return bestID
}
+// hostRenameHealSource returns the host record that keeps a renamed machine's
+// identity forked: same host ID, same reporting token, same machine ID, a
+// different hostname, and no report for several health windows. A cloned VM
+// sharing a machine ID (#1584) keeps reporting under the old hostname, so it
+// never matches; only a machine that stopped reporting under its previous
+// hostname does (#1667).
+func hostRenameHealSource(hosts []models.Host, id, tokenID, machineID, hostname string, now time.Time) (models.Host, bool) {
+ id = strings.TrimSpace(id)
+ tokenID = strings.TrimSpace(tokenID)
+ machineID = strings.TrimSpace(machineID)
+ if id == "" || tokenID == "" || machineID == "" {
+ return models.Host{}, false
+ }
+ for _, candidate := range hosts {
+ if strings.TrimSpace(candidate.ID) != id {
+ continue
+ }
+ if strings.TrimSpace(candidate.TokenID) != tokenID ||
+ strings.TrimSpace(candidate.MachineID) != machineID ||
+ hostAgentHostnamesMatch(candidate.Hostname, hostname) {
+ return models.Host{}, false
+ }
+ if candidate.LastSeen.IsZero() ||
+ now.Sub(candidate.LastSeen) > 3*hostAgentHealthWindow(candidate.IntervalSeconds) {
+ return candidate, true
+ }
+ return models.Host{}, false
+ }
+ return models.Host{}, false
+}
+
+// removeSupersededHostRecord removes a host record that a live identity has
+// superseded, along with its bindings, continuity, and tracking state. This is
+// an internal supersession, not a user removal: no tombstone, no token
+// revocation.
+func (m *Monitor) removeSupersededHostRecord(staleID, replacementID, reason string) bool {
+ staleID = strings.TrimSpace(staleID)
+ if staleID == "" {
+ return false
+ }
+ removed, ok := m.state.RemoveHost(staleID)
+ if !ok {
+ return false
+ }
+ m.state.RemoveConnectionHealth(hostConnectionPrefix + staleID)
+ m.state.UnlinkNodesFromHostAgent(staleID)
+ m.clearAgentLXCFilesystems(staleID)
+
+ m.mu.Lock()
+ for key, boundID := range m.hostTokenBindings {
+ if strings.TrimSpace(boundID) == staleID {
+ delete(m.hostTokenBindings, key)
+ }
+ }
+ m.clearHostAgentIdentityTrackingLocked(staleID)
+ m.mu.Unlock()
+
+ m.hostReportOrderMu.Lock()
+ delete(m.hostReportOrders, staleID)
+ m.hostReportOrderMu.Unlock()
+
+ if m.hostContinuityStore != nil {
+ if err := m.hostContinuityStore.Delete(staleID); err != nil {
+ log.Warn().Err(err).Str("staleHostID", staleID).Msg("Failed to remove superseded host continuity entry")
+ }
+ }
+ if m.alertManager != nil {
+ m.alertManager.HandleHostRemoved(removed)
+ m.SyncAlertState()
+ }
+
+ log.Info().
+ Str("host", removed.Hostname).
+ Str("staleHostID", staleID).
+ Str("replacementHostID", replacementID).
+ Msg(reason)
+ return true
+}
+
// supersedeStaleHostAgentDuplicates removes older generations left behind by
// installs completed before this cleanup existed. This is an internal
// supersession, not a user removal: it deliberately creates no tombstone and
@@ -2314,42 +2393,7 @@ func (m *Monitor) supersedeStaleHostAgentDuplicates(current models.Host, tokenRe
continue
}
- removed, ok := m.state.RemoveHost(staleID)
- if !ok {
- continue
- }
- m.state.RemoveConnectionHealth(hostConnectionPrefix + staleID)
- m.state.UnlinkNodesFromHostAgent(staleID)
- m.clearAgentLXCFilesystems(staleID)
-
- m.mu.Lock()
- for key, boundID := range m.hostTokenBindings {
- if strings.TrimSpace(boundID) == staleID {
- delete(m.hostTokenBindings, key)
- }
- }
- m.clearHostAgentIdentityTrackingLocked(staleID)
- m.mu.Unlock()
-
- m.hostReportOrderMu.Lock()
- delete(m.hostReportOrders, staleID)
- m.hostReportOrderMu.Unlock()
-
- if m.hostContinuityStore != nil {
- if err := m.hostContinuityStore.Delete(staleID); err != nil {
- log.Warn().Err(err).Str("staleHostID", staleID).Msg("Failed to remove superseded host continuity entry")
- }
- }
- if m.alertManager != nil {
- m.alertManager.HandleHostRemoved(removed)
- m.SyncAlertState()
- }
-
- log.Info().
- Str("host", removed.Hostname).
- Str("staleHostID", staleID).
- Str("replacementHostID", current.ID).
- Msg("Superseded stale host agent record after re-enrollment")
+ m.removeSupersededHostRecord(staleID, current.ID, "Superseded stale host agent record after re-enrollment")
}
}
@@ -2435,6 +2479,22 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// even if another colliding host disappears later.
if boundID != "" {
identifier = boundID
+ // A machine renamed while its old record still existed was forked
+ // onto a suffixed identity to stay safe against cloned VMs
+ // sharing a machine ID (#1584). Once the pre-rename record has
+ // clearly stopped reporting, the collision is proven to be a
+ // rename, not a clone, so heal back to the base identity that
+ // workload modules still report under (#1667).
+ if boundID != baseIdentifier {
+ if stale, ok := hostRenameHealSource(existingHostModels, baseIdentifier, tokenID, strings.TrimSpace(report.Host.MachineID), hostname, receivedAt); ok {
+ m.removeSupersededHostRecord(stale.ID, baseIdentifier, "Superseded stale pre-rename host record to heal forked identity")
+ m.removeSupersededHostRecord(boundID, baseIdentifier, "Retired forked host identity after rename heal")
+ m.mu.Lock()
+ m.hostTokenBindings[bindingKey] = baseIdentifier
+ m.mu.Unlock()
+ identifier = baseIdentifier
+ }
+ }
} else {
bindingID := baseIdentifier
reusedStaleID := staleHostIdentityForReenrollment(report, tokenRecord, existingHostModels)
@@ -2452,6 +2512,14 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
break
}
+ // A colliding record that stopped reporting under its old
+ // hostname is a rename, not a clone: supersede it and keep
+ // the base identity instead of forking (#1667).
+ if stale, ok := hostRenameHealSource(existingHostModels, bindingID, tokenID, strings.TrimSpace(report.Host.MachineID), hostname, receivedAt); ok {
+ m.removeSupersededHostRecord(stale.ID, bindingID, "Superseded stale pre-rename host record instead of forking identity")
+ break
+ }
+
seed := strings.Join([]string{tokenID, hostname, bindingID}, "|")
sum := sha1.Sum([]byte(seed))
suffix := hex.EncodeToString(sum[:4])