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(agent): prevent duplicate PVE entries on agent re-registration (#1245)

rcourtman1d07c1cd30ad
diff --git a/internal/api/config_handlers.go b/internal/api/config_handlers.go
index 47e7549e68..33ae5f61cf 100644
--- a/internal/api/config_handlers.go
+++ b/internal/api/config_handlers.go
@@ -1379,6 +1379,14 @@ func normalizeNodeHost(rawHost, nodeType string) (string, error) {
// extractHostIP extracts the IP address from a host URL if it's an IP-based URL.
// Returns empty string if the URL uses a hostname instead of an IP.
+// isPulseAgentToken returns true if the token ID was created by the Pulse agent.
+// Agent tokens follow the pattern "pulse-monitor@pam!pulse-<timestamp>" (PVE)
+// or "pulse-monitor@pbs!pulse-<timestamp>" (PBS).
+func isPulseAgentToken(tokenID string) bool {
+ return strings.HasPrefix(tokenID, "pulse-monitor@pam!pulse-") ||
+ strings.HasPrefix(tokenID, "pulse-monitor@pbs!pulse-")
+}
+
func extractHostIP(hostURL string) string {
parsed, err := url.Parse(hostURL)
if err != nil {
@@ -5241,6 +5249,24 @@ func (h *ConfigHandlers) HandleAutoRegister(w http.ResponseWriter, r *http.Reque
Msg("Detected IP change for existing node - updating host")
break
}
+ // Agent re-registration: same server name + both tokens created by Pulse agent.
+ // On reinstall/update the agent creates a new token (different timestamp), so the
+ // exact token match above fails. Match by server name when both entries are
+ // agent-created Pulse tokens to prevent duplicates. (#1245)
+ if req.Source == "agent" && node.Source == "agent" && req.ServerName != "" &&
+ strings.EqualFold(node.Name, req.ServerName) &&
+ isPulseAgentToken(node.TokenName) && isPulseAgentToken(req.TokenID) {
+ existingIndex = i
+ preserveHost = true
+ log.Info().
+ Str("oldHost", node.Host).
+ Str("newHost", host).
+ Str("node", req.ServerName).
+ Str("oldToken", node.TokenName).
+ Str("newToken", req.TokenID).
+ Msg("Agent re-registration detected by server name + Pulse token pattern - merging")
+ break
+ }
// Agent registration: check if existing hostname resolves to the new IP
// This catches the case where a node was manually added by hostname and
// then the agent registers using the IP address. (Issue #924)
@@ -5280,6 +5306,21 @@ func (h *ConfigHandlers) HandleAutoRegister(w http.ResponseWriter, r *http.Reque
Msg("Detected IP change for existing node - updating host")
break
}
+ // Agent re-registration: same server name + both Pulse agent tokens (#1245)
+ if req.Source == "agent" && node.Source == "agent" && req.ServerName != "" &&
+ strings.EqualFold(node.Name, req.ServerName) &&
+ isPulseAgentToken(node.TokenName) && isPulseAgentToken(req.TokenID) {
+ existingIndex = i
+ preserveHost = true
+ log.Info().
+ Str("oldHost", node.Host).
+ Str("newHost", host).
+ Str("node", req.ServerName).
+ Str("oldToken", node.TokenName).
+ Str("newToken", req.TokenID).
+ Msg("Agent re-registration detected by server name + Pulse token pattern - merging")
+ break
+ }
// Agent registration: check if existing hostname resolves to the new IP
// We preserve the user's configured hostname instead of overwriting with IP. (Issue #940)
if req.Source == "agent" && newHostIP != "" {
diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.go
index 63b72f238d..5e41adc8da 100644
--- a/internal/api/config_handlers_auto_register_test.go
+++ b/internal/api/config_handlers_auto_register_test.go
@@ -318,3 +318,158 @@ func TestExtractHostIP(t *testing.T) {
})
}
}
+
+func TestIsPulseAgentToken(t *testing.T) {
+ tests := []struct {
+ token string
+ want bool
+ }{
+ {"pulse-monitor@pam!pulse-1234567890", true},
+ {"pulse-monitor@pbs!pulse-1234567890", true},
+ {"pulse-monitor@pam!pulse-", true},
+ {"pulse-monitor@pam!token1", false},
+ {"root@pam!mytoken", false},
+ {"", false},
+ }
+ for _, tt := range tests {
+ if got := isPulseAgentToken(tt.token); got != tt.want {
+ t.Errorf("isPulseAgentToken(%q) = %v, want %v", tt.token, got, tt.want)
+ }
+ }
+}
+
+// TestAutoRegisterAgentReRegistrationMerges verifies that an agent re-registering
+// with a new Pulse token (e.g., after an update) merges with the existing entry
+// instead of creating a duplicate. Regression test for Issue #1245.
+func TestAutoRegisterAgentReRegistrationMerges(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ originalDetectPVECluster := detectPVECluster
+ detectPVECluster = func(clientConfig proxmox.ClientConfig, nodeName string, existingEndpoints []config.ClusterEndpoint) (bool, string, []config.ClusterEndpoint) {
+ return false, "", nil
+ }
+ defer func() { detectPVECluster = originalDetectPVECluster }()
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ // Pre-existing agent-registered node with an old Pulse token
+ PVEInstances: []config.PVEInstance{
+ {
+ Name: "pve",
+ Host: "https://10.0.1.100:8006",
+ TokenName: "pulse-monitor@pam!pulse-1700000000",
+ TokenValue: "old-secret",
+ Source: "agent",
+ },
+ },
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ const tokenValue = "TEMP-TOKEN"
+ tokenHash := internalauth.HashAPIToken(tokenValue)
+ handler.codeMutex.Lock()
+ handler.setupCodes[tokenHash] = &SetupCode{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ }
+ handler.codeMutex.Unlock()
+
+ // Agent re-registers with a NEW Pulse token (different timestamp) and possibly different IP
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://10.0.1.200:8006", // IP may have changed
+ TokenID: "pulse-monitor@pam!pulse-1700099999",
+ TokenValue: "new-secret",
+ ServerName: "pve",
+ Source: "agent",
+ AuthToken: tokenValue,
+ }
+
+ body, _ := json.Marshal(reqBody)
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAutoRegister(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("re-registration failed: status=%d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ // Should still be exactly 1 node (merged, not duplicated)
+ if len(cfg.PVEInstances) != 1 {
+ t.Fatalf("expected 1 PVE instance after re-registration, got %d (duplicate created!)", len(cfg.PVEInstances))
+ }
+
+ // Token should be updated to the new one
+ node := cfg.PVEInstances[0]
+ if node.TokenName != "pulse-monitor@pam!pulse-1700099999" {
+ t.Errorf("token not updated: got %q, want %q", node.TokenName, "pulse-monitor@pam!pulse-1700099999")
+ }
+}
+
+// TestAutoRegisterAgentDifferentHostsSameNameStaySeparate verifies that two
+// genuinely different hosts with the same name but non-Pulse tokens (e.g.,
+// manually created tokens) are NOT merged. Regression test for Issue #891.
+func TestAutoRegisterAgentDifferentHostsSameNameStaySeparate(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ originalDetectPVECluster := detectPVECluster
+ detectPVECluster = func(clientConfig proxmox.ClientConfig, nodeName string, existingEndpoints []config.ClusterEndpoint) (bool, string, []config.ClusterEndpoint) {
+ return false, "", nil
+ }
+ defer func() { detectPVECluster = originalDetectPVECluster }()
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ // Existing node with a manually-created (non-Pulse) token
+ PVEInstances: []config.PVEInstance{
+ {
+ Name: "pve",
+ Host: "https://10.0.1.100:8006",
+ TokenName: "root@pam!my-manual-token",
+ TokenValue: "manual-secret",
+ Source: "agent",
+ },
+ },
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ const tokenValue = "TEMP-TOKEN"
+ tokenHash := internalauth.HashAPIToken(tokenValue)
+ handler.codeMutex.Lock()
+ handler.setupCodes[tokenHash] = &SetupCode{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ }
+ handler.codeMutex.Unlock()
+
+ // Different physical host registers with same name but Pulse agent token
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://10.0.2.200:8006",
+ TokenID: "pulse-monitor@pam!pulse-1700099999",
+ TokenValue: "new-secret",
+ ServerName: "pve",
+ Source: "agent",
+ AuthToken: tokenValue,
+ }
+
+ body, _ := json.Marshal(reqBody)
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", bytes.NewReader(body))
+ rec := httptest.NewRecorder()
+ handler.HandleAutoRegister(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("registration failed: status=%d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ // Should be 2 separate nodes (one has manual token, other has Pulse token)
+ if len(cfg.PVEInstances) != 2 {
+ t.Fatalf("expected 2 PVE instances (different hosts), got %d", len(cfg.PVEInstances))
+ }
+}
diff --git a/scripts/install.sh b/scripts/install.sh
index 44bd02361b..58111f8342 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -826,9 +826,9 @@ fi
# --- Service Installation ---
-# If Proxmox mode is enabled, clear the state files to ensure fresh registration
-# This allows re-installation to re-create the Proxmox API tokens
-if [[ "$ENABLE_PROXMOX" == "true" ]]; then
+# If Proxmox mode is enabled on a FRESH install, clear state files for fresh registration.
+# On upgrades, preserve state to avoid creating duplicate PVE entries (#1245).
+if [[ "$ENABLE_PROXMOX" == "true" && "$UPGRADE_MODE" != "true" ]]; then
log_info "Clearing Proxmox state for fresh registration..."
rm -f /var/lib/pulse-agent/proxmox-registered 2>/dev/null || true
rm -f /var/lib/pulse-agent/proxmox-pve-registered 2>/dev/null || true