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.

fix(hostagent): prevent data mixing when multiple nodes share hostname

rcourtman9cd79daa68b8
diff --git a/internal/api/host_agents.go b/internal/api/host_agents.go
index ce2477be09..e842fe144d 100644
--- a/internal/api/host_agents.go
+++ b/internal/api/host_agents.go
@@ -374,6 +374,55 @@ func (h *HostAgentHandlers) HandleUninstall(w http.ResponseWriter, r *http.Reque
}
}
+// HandleLink manually links a host agent to a specific PVE node.
+// This is used when auto-linking can't disambiguate (e.g., multiple nodes with hostname "pve").
+func (h *HostAgentHandlers) HandleLink(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost {
+ writeErrorResponse(w, http.StatusMethodNotAllowed, "method_not_allowed", "Only POST is allowed", nil)
+ return
+ }
+
+ r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
+ defer r.Body.Close()
+
+ var req struct {
+ HostID string `json:"hostId"`
+ NodeID string `json:"nodeId"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "invalid_json", "Failed to decode request body", map[string]string{"error": err.Error()})
+ return
+ }
+
+ hostID := strings.TrimSpace(req.HostID)
+ if hostID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_host_id", "Host ID is required", nil)
+ return
+ }
+
+ nodeID := strings.TrimSpace(req.NodeID)
+ if nodeID == "" {
+ writeErrorResponse(w, http.StatusBadRequest, "missing_node_id", "Node ID is required", nil)
+ return
+ }
+
+ if err := h.monitor.LinkHostAgent(hostID, nodeID); err != nil {
+ writeErrorResponse(w, http.StatusBadRequest, "link_failed", err.Error(), nil)
+ return
+ }
+
+ go h.wsHub.BroadcastState(h.monitor.GetState().ToFrontend())
+
+ if err := utils.WriteJSONResponse(w, map[string]any{
+ "success": true,
+ "hostId": hostID,
+ "nodeId": nodeID,
+ "message": "Host agent linked to PVE node",
+ }); err != nil {
+ log.Error().Err(err).Msg("Failed to serialize host link response")
+ }
+}
+
// HandleUnlink removes the link between a host agent and its PVE node.
// The agent continues to report but appears in the Managed Agents table.
func (h *HostAgentHandlers) HandleUnlink(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/api/router.go b/internal/api/router.go
index f1efbe3b54..e22677b9a7 100644
--- a/internal/api/router.go
+++ b/internal/api/router.go
@@ -220,6 +220,7 @@ func (r *Router) setupRoutes() {
r.mux.HandleFunc("/api/agents/host/lookup", RequireAuth(r.config, RequireScope(config.ScopeHostReport, r.hostAgentHandlers.HandleLookup)))
r.mux.HandleFunc("/api/agents/host/uninstall", RequireAuth(r.config, RequireScope(config.ScopeHostReport, r.hostAgentHandlers.HandleUninstall)))
r.mux.HandleFunc("/api/agents/host/unlink", RequireAdmin(r.config, RequireScope(config.ScopeHostManage, r.hostAgentHandlers.HandleUnlink)))
+ r.mux.HandleFunc("/api/agents/host/link", RequireAdmin(r.config, RequireScope(config.ScopeHostManage, r.hostAgentHandlers.HandleLink)))
// Host agent management routes - config endpoint is accessible by agents (GET) and admins (PATCH)
r.mux.HandleFunc("/api/agents/host/", RequireAuth(r.config, func(w http.ResponseWriter, req *http.Request) {
// Route /api/agents/host/{id}/config to HandleConfig
diff --git a/internal/models/models.go b/internal/models/models.go
index 2102e2c7c9..f642941c67 100644
--- a/internal/models/models.go
+++ b/internal/models/models.go
@@ -1,6 +1,7 @@
package models
import (
+ "fmt"
"sort"
"strconv"
"strings"
@@ -2067,6 +2068,66 @@ func (s *State) UnlinkNodesFromHostAgent(hostAgentID string) int {
return count
}
+// LinkHostAgentToNode creates a bidirectional link between a host agent and a PVE node.
+// This is used for manual linking when auto-linking can't disambiguate (e.g., multiple nodes
+// with the same hostname). Sets LinkedNodeID on the host and LinkedHostAgentID on the node.
+// Returns an error if either the host or node is not found.
+func (s *State) LinkHostAgentToNode(hostID, nodeID string) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // Find the host
+ var hostIdx int = -1
+ for i, host := range s.Hosts {
+ if host.ID == hostID {
+ hostIdx = i
+ break
+ }
+ }
+ if hostIdx < 0 {
+ return fmt.Errorf("host agent not found: %s", hostID)
+ }
+
+ // Find the node
+ var nodeIdx int = -1
+ for i, node := range s.Nodes {
+ if node.ID == nodeID {
+ nodeIdx = i
+ break
+ }
+ }
+ if nodeIdx < 0 {
+ return fmt.Errorf("node not found: %s", nodeID)
+ }
+
+ // Clear any existing links from this host
+ oldNodeID := s.Hosts[hostIdx].LinkedNodeID
+ if oldNodeID != "" {
+ for i, node := range s.Nodes {
+ if node.ID == oldNodeID {
+ s.Nodes[i].LinkedHostAgentID = ""
+ break
+ }
+ }
+ }
+
+ // Clear any existing links to the target node (from other hosts)
+ for i, host := range s.Hosts {
+ if host.LinkedNodeID == nodeID && i != hostIdx {
+ s.Hosts[i].LinkedNodeID = ""
+ }
+ }
+
+ // Create the bidirectional link
+ s.Hosts[hostIdx].LinkedNodeID = nodeID
+ s.Hosts[hostIdx].LinkedVMID = "" // Clear VM/container links if setting node link
+ s.Hosts[hostIdx].LinkedContainerID = ""
+ s.Nodes[nodeIdx].LinkedHostAgentID = hostID
+
+ s.LastUpdate = time.Now()
+ return nil
+}
+
// UnlinkHostAgent removes the bidirectional link between a host agent and its PVE node.
// Clears LinkedNodeID on the host and LinkedHostAgentID on the node.
// Returns true if the host was found and unlinked.
diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.go
index 74884577af..8dc3dc351b 100644
--- a/internal/monitoring/monitor.go
+++ b/internal/monitoring/monitor.go
@@ -1346,6 +1346,31 @@ func (m *Monitor) RemoveHostAgent(hostID string) (models.Host, error) {
return host, nil
}
+// LinkHostAgent manually links a host agent to a specific PVE node.
+// This is used when auto-linking can't disambiguate (e.g., multiple nodes with hostname "pve").
+// After linking, the host agent's temperature/sensor data will appear on the correct node.
+func (m *Monitor) LinkHostAgent(hostID, nodeID string) error {
+ hostID = strings.TrimSpace(hostID)
+ nodeID = strings.TrimSpace(nodeID)
+ if hostID == "" {
+ return fmt.Errorf("host id is required")
+ }
+ if nodeID == "" {
+ return fmt.Errorf("node id is required")
+ }
+
+ if err := m.state.LinkHostAgentToNode(hostID, nodeID); err != nil {
+ return err
+ }
+
+ log.Info().
+ Str("hostID", hostID).
+ Str("nodeID", nodeID).
+ Msg("Manually linked host agent to PVE node")
+
+ return nil
+}
+
// 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.
@@ -2544,6 +2569,9 @@ func (m *Monitor) ApplyHostReport(report agentshost.Report, tokenRecord *config.
// findLinkedProxmoxEntity searches for a PVE node, VM, or container with a matching hostname.
// Returns the IDs of matched entities (empty string if no match).
+// When multiple entities match the same hostname (e.g., two PVE instances both have a node
+// named "pve"), this function returns empty strings to avoid incorrect linking. Users should
+// manually link agents to nodes via the UI in such cases.
func (m *Monitor) findLinkedProxmoxEntity(hostname string) (nodeID, vmID, containerID string) {
if hostname == "" {
return "", "", ""
@@ -2572,26 +2600,67 @@ func (m *Monitor) findLinkedProxmoxEntity(hostname string) (nodeID, vmID, contai
state := m.GetState()
- // Check PVE nodes first
+ // Check PVE nodes first - but detect ambiguity when multiple nodes match
+ var matchingNodes []models.Node
for _, node := range state.Nodes {
if matchHostname(node.Name) {
- return node.ID, "", ""
+ matchingNodes = append(matchingNodes, node)
}
}
+ if len(matchingNodes) == 1 {
+ return matchingNodes[0].ID, "", ""
+ }
+ if len(matchingNodes) > 1 {
+ // Multiple nodes with the same hostname - can't auto-link, would cause data mixing
+ log.Warn().
+ Str("hostname", hostname).
+ Int("matchCount", len(matchingNodes)).
+ Strs("instances", func() []string {
+ instances := make([]string, len(matchingNodes))
+ for i, n := range matchingNodes {
+ instances[i] = n.Instance
+ }
+ return instances
+ }()).
+ Msg("Multiple PVE nodes match hostname - cannot auto-link host agent. Manual linking required via UI.")
+ return "", "", ""
+ }
- // Check VMs
+ // Check VMs - same pattern for ambiguity detection
+ var matchingVMs []models.VM
for _, vm := range state.VMs {
if matchHostname(vm.Name) {
- return "", vm.ID, ""
+ matchingVMs = append(matchingVMs, vm)
}
}
+ if len(matchingVMs) == 1 {
+ return "", matchingVMs[0].ID, ""
+ }
+ if len(matchingVMs) > 1 {
+ log.Warn().
+ Str("hostname", hostname).
+ Int("matchCount", len(matchingVMs)).
+ Msg("Multiple VMs match hostname - cannot auto-link host agent. Manual linking required via UI.")
+ return "", "", ""
+ }
- // Check containers
+ // Check containers - same pattern
+ var matchingCTs []models.Container
for _, ct := range state.Containers {
if matchHostname(ct.Name) {
- return "", "", ct.ID
+ matchingCTs = append(matchingCTs, ct)
}
}
+ if len(matchingCTs) == 1 {
+ return "", "", matchingCTs[0].ID
+ }
+ if len(matchingCTs) > 1 {
+ log.Warn().
+ Str("hostname", hostname).
+ Int("matchCount", len(matchingCTs)).
+ Msg("Multiple containers match hostname - cannot auto-link host agent. Manual linking required via UI.")
+ return "", "", ""
+ }
return "", "", ""
}