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.

Self-heal stale Proxmox auto-register markers

rcourtman8de5c60b4685
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f1994216af..677c6a9f9c 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -91,6 +91,7 @@ management, and fleet control surfaces.
67. `frontend-modern/src/components/Settings/useTrueNASSettingsPanelState.ts`
68. `frontend-modern/src/components/Settings/VMwareSettingsPanel.tsx`
69. `frontend-modern/src/components/Settings/useVMwareSettingsPanelState.ts`
+70. `internal/hostagent/proxmox_setup.go`
## Shared Boundaries
@@ -124,6 +125,7 @@ management, and fleet control surfaces.
1. Add or change install-command generation, canonical /api/auto-register behavior, or installer download behavior through the owned `internal/api/` files above.
2. Add or change update continuity and persisted-version handoff through `internal/agentupdate/`.
3. Add or change runtime-side Unified Agent startup, first-report assembly, and enroll/runtime continuity through `internal/hostagent/`.
+ Proxmox host-agent setup must treat local `proxmox-registered` markers as a cache, not authority: before skipping token setup or node repair, `internal/hostagent/proxmox_setup.go` must revalidate the current type and candidate hosts against Pulse through the canonical auto-register contract.
That runtime-side ownership includes local disk telemetry collection in
`internal/hostagent/smartctl.go`. Linux SMART discovery must prefer
`smartctl --scan-open` typed targets before generic block-device fallback so
@@ -159,6 +161,7 @@ management, and fleet control surfaces.
2. Keep shared API proof routing aligned whenever install, register, or profile payloads change.
3. Update runtime and settings tests in the same slice when lifecycle behavior changes.
4. Preserve canonical /api/auto-register node identity continuity when canonical hosts shift between hostname and IP forms for the same node.
+5. Keep Proxmox registration continuity self-healing: stale local registration markers must be verified against Pulse before the host agent skips setup, and a missing matching node on the Pulse side must drive canonical re-registration instead of asking operators to delete marker files manually.
5. Keep first-session lifecycle handoff explicit: the live setup completion
surface in `frontend-modern/src/components/SetupWizard/SetupCompletionPanel.tsx`
must route the primary CTA into `/settings/infrastructure/install`, frame
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index bf532a5d58..9c39035fe8 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -73,6 +73,7 @@ Own canonical runtime payload shapes between backend and frontend.
49. `internal/cloudcp/portal/frontend/tsconfig.json`
50. `internal/cloudcp/portal/frontend_sync_test.go`
51. `internal/api/recovery_handlers.go`
+52. `internal/api/config_setup_handlers.go`
## Shared Boundaries
@@ -114,6 +115,7 @@ Own canonical runtime payload shapes between backend and frontend.
36. `internal/api/config_setup_handlers.go` shared with `agent-lifecycle`: auto-register and setup handlers are both an agent lifecycle control surface and a canonical API payload contract boundary.
That same shared boundary also owns reachable-host selection truth for canonical Proxmox registration: runtime callers may propose ordered `candidateHosts`, but the API contract must persist and echo the first candidate Pulse can actually reach instead of freezing the caller's rejected first preference into the stored node endpoint.
That same canonical payload contract also owns strict-TLS truth for that selected host: `/api/auto-register` may only persist `VerifySSL=true` when Pulse actually captured a certificate fingerprint for the selected candidate, and it must not pretend public-CA verification is safe after every candidate fingerprint probe failed.
+ That same contract now owns stale-marker verification as well: setup-token-authenticated `checkRegistration` requests may omit token completion fields and must answer `{registered:boolean}` from canonical candidate-host matching so runtime repair can distinguish real registrations from stale local marker files without rotating tokens first.
37. `internal/api/enterprise_extension_rbac_admin.go` shared with `organization-settings`: RBAC admin extension endpoints are both an organization settings control surface and a canonical API payload contract boundary.
38. `internal/api/licensing_bridge.go` shared with `cloud-paid`: commercial licensing bridge handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
39. `internal/api/licensing_handlers.go` shared with `cloud-paid`: commercial licensing handlers carry both API payload contract and cloud-paid entitlement boundary ownership.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 66a0b30b7c..513d9fd775 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -89,6 +89,12 @@ querying, and the operator-facing storage health presentation layer.
that host's certificate fingerprint, so adjacent setup and recovery-linked
transport flows do not inherit a false strict-TLS claim for self-signed
nodes that never completed fingerprint capture.
+ That same shared dependency now also owns stale-marker repair truth:
+ setup-token-authenticated `checkRegistration` calls may omit token
+ completion fields and answer only `{registered:boolean}`, so adjacent
+ transport flows must not reintroduce local marker trust or token rotation
+ when the canonical auto-register helper can verify whether Pulse still has
+ a matching node.
15. Preserve the governed root-or-sudo Unix wrapper in shared backend install-command helpers so storage- and recovery-adjacent transport surfaces do not inherit a stale raw `| bash -s --` install payload shape from the canonical agent-install-command API and hosted Proxmox install responses.
16. Preserve optional-auth tokenless behavior in those same shared backend install-command helpers so adjacent transport surfaces do not implicitly persist API tokens and flip auth-configured state when an operator only requested a Proxmox install command on a token-optional Pulse instance.
17. Preserve backend-owned Pulse Mobile relay runtime credential minting in those same shared `internal/api/` auth/security helpers so storage- and recovery-adjacent transport surfaces do not inherit browser-authored wildcard token bundles when they depend on the canonical security helper layer.
@@ -185,12 +191,18 @@ querying, and the operator-facing storage health presentation layer.
chart highlighting so pool-only cards demote cleanly during disk focus and
disk-temperature cards demote cleanly during pool focus, instead of
leaving stale row-local IDs or storage-local hover branches on the page.
-14. Keep cross-surface workload handoffs on canonical IDs too. Shared workload
+14. Keep storage summary remount caches versioned with the chart contract.
+ `frontend-modern/src/components/Storage/StorageSummary.tsx` may keep a
+ bounded in-memory cache for same-tab remounts, but its cache key must carry
+ an explicit summary contract version so long-lived demo sessions do not
+ rehydrate stale pool or disk sparkline shapes after the storage summary
+ chart model changes.
+15. Keep cross-surface workload handoffs on canonical IDs too. Shared workload
chart transport may look up provider-backed VM history through unified
metrics targets, but infrastructure/workloads/storage/recovery navigation
and focus handoffs must stay on canonical workload IDs instead of
provider-native metric keys.
-15. Keep storage row emphasis on the shared frontend primitive contract. Pool
+16. Keep storage row emphasis on the shared frontend primitive contract. Pool
rows and physical-disk rows that mirror the active summary entity must
expose that state through `data-summary-row-active` and let the shared row
presentation owned by `frontend-modern/src/index.css` render the emphasis,
diff --git a/internal/api/config_handlers_auto_register_test.go b/internal/api/config_handlers_auto_register_test.go
index a7ea48bf12..6b3c0e052d 100644
--- a/internal/api/config_handlers_auto_register_test.go
+++ b/internal/api/config_handlers_auto_register_test.go
@@ -162,6 +162,122 @@ func TestHandleAutoRegisterAcceptsWithSetupToken(t *testing.T) {
}
}
+func TestHandleAutoRegisterCheckRegistrationUsesCanonicalCandidateHosts(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ PVEInstances: []config.PVEInstance{
+ {
+ Name: "pve-node-1",
+ Host: "https://10.0.0.5:8006",
+ Source: "agent",
+ },
+ },
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ const tokenValue = "TEMP-TOKEN-CHECK"
+ tokenHash := internalauth.HashAPIToken(tokenValue)
+ handler.codeMutex.Lock()
+ handler.setupTokens[tokenHash] = &SetupTokenRecord{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ }
+ handler.codeMutex.Unlock()
+
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ CandidateHosts: []string{"https://pve.local:8006", "https://10.0.0.5:8006"},
+ ServerName: "pve-node-1",
+ AuthToken: tokenValue,
+ Source: "agent",
+ CheckRegistration: true,
+ }
+
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ 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("expected status 200, got %d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ var response struct {
+ Registered bool `json:"registered"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if !response.Registered {
+ t.Fatalf("expected registered=true, got %#v", response)
+ }
+}
+
+func TestHandleAutoRegisterCheckRegistrationReturnsFalseForMissingNode(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+
+ const tokenValue = "TEMP-TOKEN-CHECK-MISSING"
+ tokenHash := internalauth.HashAPIToken(tokenValue)
+ handler.codeMutex.Lock()
+ handler.setupTokens[tokenHash] = &SetupTokenRecord{
+ ExpiresAt: time.Now().Add(5 * time.Minute),
+ NodeType: "pve",
+ }
+ handler.codeMutex.Unlock()
+
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ ServerName: "pve-node-1",
+ AuthToken: tokenValue,
+ Source: "agent",
+ CheckRegistration: true,
+ }
+
+ body, err := json.Marshal(reqBody)
+ if err != nil {
+ t.Fatalf("failed to marshal request: %v", err)
+ }
+
+ 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("expected status 200, got %d, body=%s", rec.Code, rec.Body.String())
+ }
+
+ var response struct {
+ Registered bool `json:"registered"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+ if response.Registered {
+ t.Fatalf("expected registered=false, got %#v", response)
+ }
+}
+
func TestHandleAutoRegisterRejectsMissingSource(t *testing.T) {
stubAutoRegisterNetworkDeps(t)
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index c8122a2ce9..98b9aabe19 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -252,14 +252,15 @@ func (h *ConfigHandlers) handleSetupScriptURL(w http.ResponseWriter, r *http.Req
// AutoRegisterRequest represents a request from the setup script or agent to auto-register a node
type AutoRegisterRequest struct {
- Type string `json:"type"` // "pve" or "pbs"
- Host string `json:"host"` // The preferred host URL
- CandidateHosts []string `json:"candidateHosts,omitempty"` // Alternate host URLs the server can try from its own network view
- TokenID string `json:"tokenId"` // Full token ID like pulse-monitor@pve!pulse-token
- TokenValue string `json:"tokenValue,omitempty"` // The token value for the node
- ServerName string `json:"serverName,omitempty"` // Hostname or IP
- AuthToken string `json:"authToken,omitempty"` // One-time setup token from setup/install flows
- Source string `json:"source,omitempty"` // "agent" or "script" - indicates how the node was registered
+ Type string `json:"type"` // "pve" or "pbs"
+ Host string `json:"host"` // The preferred host URL
+ CandidateHosts []string `json:"candidateHosts,omitempty"` // Alternate host URLs the server can try from its own network view
+ TokenID string `json:"tokenId,omitempty"` // Full token ID like pulse-monitor@pve!pulse-token
+ TokenValue string `json:"tokenValue,omitempty"` // The token value for the node
+ ServerName string `json:"serverName,omitempty"` // Hostname or IP
+ AuthToken string `json:"authToken,omitempty"` // One-time setup token from setup/install flows
+ Source string `json:"source,omitempty"` // "agent" or "script" - indicates how the node was registered
+ CheckRegistration bool `json:"checkRegistration,omitempty"` // Check whether a matching registered node already exists without completing registration
}
// AutoRegisterResponse is the canonical success shape for /api/auto-register.
@@ -383,6 +384,23 @@ func canonicalAutoRegisterCompletionPayloadMessage() string {
return "Incomplete canonical auto-register token completion payload"
}
+func canonicalAutoRegisterCheckMissingFieldsMessage(typeValue string, host string, serverName string) string {
+ missing := make([]string, 0, 3)
+ if strings.TrimSpace(typeValue) == "" {
+ missing = append(missing, "type")
+ }
+ if strings.TrimSpace(host) == "" {
+ missing = append(missing, "host")
+ }
+ if strings.TrimSpace(serverName) == "" {
+ missing = append(missing, "serverName")
+ }
+ if len(missing) == 0 {
+ return "Missing required canonical auto-register check fields"
+ }
+ return "Missing required canonical auto-register check fields: " + strings.Join(missing, ", ")
+}
+
func canonicalAutoRegisterMissingFieldsMessage(typeValue string, host string, hasTokenID bool, serverName string) string {
missing := make([]string, 0, 4)
if strings.TrimSpace(typeValue) == "" {
@@ -426,6 +444,50 @@ func canonicalAutoRegisterSuccessMessage(nodeName string, host string) string {
return fmt.Sprintf("Node %s registered successfully at %s", trimmedNodeName, trimmedHost)
}
+type autoRegisterCheckResponse struct {
+ Registered bool `json:"registered"`
+}
+
+func autoRegisterHostMatchesCandidates(existingHost string, candidates []string) bool {
+ trimmedExisting := strings.TrimSpace(existingHost)
+ if trimmedExisting == "" {
+ return false
+ }
+ for _, candidate := range candidates {
+ trimmedCandidate := strings.TrimSpace(candidate)
+ if trimmedCandidate == "" {
+ continue
+ }
+ if trimmedExisting == trimmedCandidate || hostsShareResolvedIdentity(trimmedExisting, trimmedCandidate) {
+ return true
+ }
+ }
+ return false
+}
+
+func (h *ConfigHandlers) autoRegisteredNodeExists(ctx context.Context, req *AutoRegisterRequest, candidates []string) bool {
+ if req == nil {
+ return false
+ }
+
+ switch req.Type {
+ case "pve":
+ for _, node := range h.getConfig(ctx).PVEInstances {
+ if autoRegisterHostMatchesCandidates(node.Host, candidates) {
+ return true
+ }
+ }
+ case "pbs":
+ for _, node := range h.getConfig(ctx).PBSInstances {
+ if autoRegisterHostMatchesCandidates(node.Host, candidates) {
+ return true
+ }
+ }
+ }
+
+ return false
+}
+
func buildCanonicalAutoRegisterResponse(req *AutoRegisterRequest, host string, actualName string, tokenID string, tokenValue string) AutoRegisterResponse {
nodeName := canonicalAutoRegisterNodeIdentity(req, actualName, host)
return AutoRegisterResponse{
@@ -638,6 +700,53 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
hasTokenID := tokenID != ""
hasTokenValue := tokenValue != ""
+ if registrationSource == "" {
+ http.Error(w, "source is required", http.StatusBadRequest)
+ return
+ }
+ if !isCanonicalAutoRegisterSource(registrationSource) {
+ http.Error(w, "source must be 'agent' or 'script'", http.StatusBadRequest)
+ return
+ }
+ if !isCanonicalAutoRegisterType(typeValue) {
+ http.Error(w, "type must be 'pve' or 'pbs'", http.StatusBadRequest)
+ return
+ }
+
+ req.Type = typeValue
+ req.Host = hostValue
+ req.TokenID = tokenID
+ req.TokenValue = tokenValue
+ req.ServerName = serverName
+ req.Source = registrationSource
+
+ if req.CheckRegistration {
+ if typeValue == "" || hostValue == "" || serverName == "" {
+ missingMessage := canonicalAutoRegisterCheckMissingFieldsMessage(typeValue, hostValue, serverName)
+ log.Error().
+ Str("type", req.Type).
+ Str("host", req.Host).
+ Str("serverName", req.ServerName).
+ Msg(missingMessage)
+ http.Error(w, missingMessage, http.StatusBadRequest)
+ return
+ }
+
+ normalizedCandidates, err := normalizeAutoRegisterHostCandidates(req.Type, req.Host, req.CandidateHosts)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusBadRequest)
+ return
+ }
+
+ w.Header().Set("Content-Type", "application/json")
+ if err := json.NewEncoder(w).Encode(autoRegisterCheckResponse{
+ Registered: h.autoRegisteredNodeExists(r.Context(), req, normalizedCandidates),
+ }); err != nil {
+ log.Error().Err(err).Msg("Failed to encode auto-register registration check response")
+ }
+ return
+ }
+
if hasTokenID != hasTokenValue {
log.Error().
Bool("hasTokenID", hasTokenID).
@@ -658,30 +767,11 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
http.Error(w, missingMessage, http.StatusBadRequest)
return
}
- if registrationSource == "" {
- http.Error(w, "source is required", http.StatusBadRequest)
- return
- }
- if !isCanonicalAutoRegisterSource(registrationSource) {
- http.Error(w, "source must be 'agent' or 'script'", http.StatusBadRequest)
- return
- }
- if !isCanonicalAutoRegisterType(typeValue) {
- http.Error(w, "type must be 'pve' or 'pbs'", http.StatusBadRequest)
- return
- }
if !isCanonicalAutoRegisterTokenID(typeValue, tokenID) {
http.Error(w, "tokenId must be a canonical Pulse-managed token id", http.StatusBadRequest)
return
}
- req.Type = typeValue
- req.Host = hostValue
- req.TokenID = tokenID
- req.TokenValue = tokenValue
- req.ServerName = serverName
- req.Source = registrationSource
-
host, fingerprint, verifySSL, candidateHosts, err := selectAutoRegisterHost(req.Type, req.Host, req.CandidateHosts)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 15c6e46723..7355f92ac5 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -4952,6 +4952,35 @@ func TestContract_AutoRegisterScriptRequestJSONSnapshot(t *testing.T) {
assertJSONSnapshot(t, got, want)
}
+func TestContract_AutoRegisterCheckRequestJSONSnapshot(t *testing.T) {
+ payload := AutoRegisterRequest{
+ Type: "pve",
+ Host: "https://pve.local:8006",
+ CandidateHosts: []string{"https://pve.local:8006", "https://10.0.0.5:8006"},
+ ServerName: "pve-node-1",
+ AuthToken: "setup-token-123",
+ Source: "agent",
+ CheckRegistration: true,
+ }
+
+ got, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatalf("marshal auto-register check request: %v", err)
+ }
+
+ const want = `{
+ "type":"pve",
+ "host":"https://pve.local:8006",
+ "candidateHosts":["https://pve.local:8006","https://10.0.0.5:8006"],
+ "serverName":"pve-node-1",
+ "authToken":"setup-token-123",
+ "source":"agent",
+ "checkRegistration":true
+ }`
+
+ assertJSONSnapshot(t, got, want)
+}
+
func TestContract_AutoRegisterScriptRequestRequiresExplicitSourceMarker(t *testing.T) {
payload := AutoRegisterRequest{
Type: "pve",
diff --git a/internal/hostagent/proxmox_setup.go b/internal/hostagent/proxmox_setup.go
index b39fc7e27d..bfc37dbf15 100644
--- a/internal/hostagent/proxmox_setup.go
+++ b/internal/hostagent/proxmox_setup.go
@@ -56,14 +56,15 @@ type autoRegisterSource string
const autoRegisterSourceAgent autoRegisterSource = "agent"
type autoRegisterRequest struct {
- Type proxmoxProductType `json:"type"`
- Host string `json:"host"`
- CandidateHosts []string `json:"candidateHosts,omitempty"`
- ServerName string `json:"serverName"`
- AuthToken string `json:"authToken,omitempty"`
- TokenID string `json:"tokenId"`
- TokenValue string `json:"tokenValue"`
- Source autoRegisterSource `json:"source"`
+ Type proxmoxProductType `json:"type"`
+ Host string `json:"host"`
+ CandidateHosts []string `json:"candidateHosts,omitempty"`
+ ServerName string `json:"serverName"`
+ AuthToken string `json:"authToken,omitempty"`
+ TokenID string `json:"tokenId,omitempty"`
+ TokenValue string `json:"tokenValue,omitempty"`
+ Source autoRegisterSource `json:"source"`
+ CheckRegistration bool `json:"checkRegistration,omitempty"`
}
type autoRegisterResponse struct {
@@ -79,6 +80,12 @@ type autoRegisterResponse struct {
TokenValue string `json:"tokenValue"`
}
+type autoRegisterCheckResponse struct {
+ Registered bool `json:"registered"`
+}
+
+const maxRegistrationCheckResponseBytes = 8 * 1024
+
type setupScriptURLRequest struct {
Type string `json:"type"`
Host string `json:"host"`
@@ -347,12 +354,6 @@ func (p *ProxmoxSetup) Run(ctx context.Context) (*ProxmoxSetupResult, error) {
}
ptype := proxmoxProductType(ptypeStr)
- // Check if already registered (idempotency)
- if p.isAlreadyRegistered() {
- p.logger.Info().Msg("Proxmox node already registered, skipping setup")
- return nil, nil
- }
-
// Detect Proxmox type
if ptype == proxmoxProductUnknown {
detected := p.detectProxmoxType()
@@ -363,6 +364,22 @@ func (p *ProxmoxSetup) Run(ctx context.Context) (*ProxmoxSetupResult, error) {
p.logger.Info().Str("type", string(ptype)).Msg("Auto-detected Proxmox type")
}
+ hostURL := p.getHostURL(ctx, ptype)
+
+ // Check if already registered (idempotency)
+ if p.isAlreadyRegistered() {
+ registered, err := p.checkRegistrationWithPulse(ctx, ptype, hostURL)
+ if err != nil {
+ p.logger.Warn().Err(err).Msg("Failed to verify Proxmox registration state with Pulse; keeping local marker behavior")
+ return nil, nil
+ }
+ if registered {
+ p.logger.Info().Msg("Proxmox node already registered, skipping setup")
+ return nil, nil
+ }
+ p.logger.Info().Str("type", string(ptype)).Str("host", hostURL).Msg("Local Proxmox registration marker exists but Pulse has no matching node; re-registering")
+ }
+
// Create monitoring user and token
tokenID, tokenValue, err := p.setupToken(ctx, ptype)
if err != nil {
@@ -371,9 +388,6 @@ func (p *ProxmoxSetup) Run(ctx context.Context) (*ProxmoxSetupResult, error) {
p.logger.Info().Str("token_id", tokenID).Msg("Created Proxmox API token")
- // Get the host URL for registration
- hostURL := p.getHostURL(ctx, ptype)
-
// Register with Pulse
registered := false
registerResp, err := p.registerWithPulse(ctx, ptype, hostURL, tokenID, tokenValue)
@@ -460,11 +474,26 @@ func (p *ProxmoxSetup) runForType(ctx context.Context, ptype proxmoxProductType)
return nil, fmt.Errorf("invalid proxmox type %q: must be pve or pbs", ptype)
}
ptype = proxmoxProductType(normalizedTypeStr)
+ hostURL := p.getHostURL(ctx, ptype)
// Check if this type is already registered
if p.isTypeRegistered(ptype) {
- p.logger.Info().Str("type", string(ptype)).Msg("Proxmox type already registered, skipping")
- return nil, nil
+ registered, err := p.checkRegistrationWithPulse(ctx, ptype, hostURL)
+ if err != nil {
+ p.logger.Warn().
+ Err(err).
+ Str("type", string(ptype)).
+ Msg("Failed to verify Proxmox registration state with Pulse; keeping local marker behavior")
+ return nil, nil
+ }
+ if registered {
+ p.logger.Info().Str("type", string(ptype)).Msg("Proxmox type already registered, skipping")
+ return nil, nil
+ }
+ p.logger.Info().
+ Str("type", string(ptype)).
+ Str("host", hostURL).
+ Msg("Local Proxmox registration marker exists but Pulse has no matching node; re-registering")
}
p.logger.Info().Str("type", string(ptype)).Msg("Setting up Proxmox type")
@@ -477,9 +506,6 @@ func (p *ProxmoxSetup) runForType(ctx context.Context, ptype proxmoxProductType)
p.logger.Info().Str("type", string(ptype)).Str("token_id", tokenID).Msg("Created Proxmox API token")
- // Get the host URL for registration
- hostURL := p.getHostURL(ctx, ptype)
-
// Register with Pulse
registered := false
registerResp, err := p.registerWithPulse(ctx, ptype, hostURL, tokenID, tokenValue)
@@ -504,6 +530,72 @@ func (p *ProxmoxSetup) runForType(ctx context.Context, ptype proxmoxProductType)
}, nil
}
+func (p *ProxmoxSetup) orderedCandidateHosts(ctx context.Context, ptype proxmoxProductType, hostURL string) []string {
+ candidateHosts := p.candidateHostURLs(ctx, ptype)
+ if len(candidateHosts) == 0 || strings.TrimSpace(candidateHosts[0]) != strings.TrimSpace(hostURL) {
+ seen := make(map[string]struct{}, len(candidateHosts)+1)
+ reordered := make([]string, 0, len(candidateHosts)+1)
+ reordered = appendUniqueHostCandidate(reordered, seen, hostURL)
+ for _, candidate := range candidateHosts {
+ reordered = appendUniqueHostCandidate(reordered, seen, candidate)
+ }
+ candidateHosts = reordered
+ }
+ return candidateHosts
+}
+
+func (p *ProxmoxSetup) checkRegistrationWithPulse(ctx context.Context, ptype proxmoxProductType, hostURL string) (bool, error) {
+ setupToken, err := p.fetchSetupToken(ctx, ptype, hostURL)
+ if err != nil {
+ return false, fmt.Errorf("fetch setup token: %w", err)
+ }
+
+ payload := autoRegisterRequest{
+ Type: ptype,
+ Host: hostURL,
+ CandidateHosts: p.orderedCandidateHosts(ctx, ptype, hostURL),
+ ServerName: p.hostname,
+ AuthToken: setupToken,
+ Source: autoRegisterSourceAgent,
+ CheckRegistration: true,
+ }
+
+ body, err := json.Marshal(payload)
+ if err != nil {
+ return false, fmt.Errorf("marshal registration-check payload: %w", err)
+ }
+
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.pulseURL+"/api/auto-register", bytes.NewReader(body))
+ if err != nil {
+ return false, fmt.Errorf("create registration-check request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+
+ resp, err := p.httpClient.Do(req)
+ if err != nil {
+ return false, fmt.Errorf("registration-check request failed: %w", err)
+ }
+ defer func() {
+ if closeErr := resp.Body.Close(); closeErr != nil {
+ p.logger.Debug().Err(closeErr).Msg("Failed to close registration-check response body")
+ }
+ }()
+
+ bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxRegistrationCheckResponseBytes))
+ if err != nil {
+ return false, fmt.Errorf("read registration-check response: %w", err)
+ }
+ if resp.StatusCode >= http.StatusBadRequest {
+ return false, fmt.Errorf("registration-check returned HTTP %d: %s", resp.StatusCode, strings.TrimSpace(string(bodyBytes)))
+ }
+
+ var parsed autoRegisterCheckResponse
+ if err := json.Unmarshal(bodyBytes, &parsed); err != nil {
+ return false, fmt.Errorf("decode registration-check response: %w", err)
+ }
+ return parsed.Registered, nil
+}
+
// detectProxmoxType checks for pvesh (PVE) or proxmox-backup-manager (PBS).
// For backward compatibility, returns the first detected type.
// Use detectProxmoxTypes() to get all detected types.
@@ -1208,16 +1300,7 @@ func (p *ProxmoxSetup) fetchSetupToken(ctx context.Context, ptype proxmoxProduct
// registerWithPulse calls the auto-register endpoint to add the node.
func (p *ProxmoxSetup) registerWithPulse(ctx context.Context, ptype proxmoxProductType, hostURL, tokenID, tokenValue string) (autoRegisterResponse, error) {
- candidateHosts := p.candidateHostURLs(ctx, ptype)
- if len(candidateHosts) == 0 || strings.TrimSpace(candidateHosts[0]) != strings.TrimSpace(hostURL) {
- seen := make(map[string]struct{}, len(candidateHosts)+1)
- reordered := make([]string, 0, len(candidateHosts)+1)
- reordered = appendUniqueHostCandidate(reordered, seen, hostURL)
- for _, candidate := range candidateHosts {
- reordered = appendUniqueHostCandidate(reordered, seen, candidate)
- }
- candidateHosts = reordered
- }
+ candidateHosts := p.orderedCandidateHosts(ctx, ptype, hostURL)
backoffs := p.retryBackoffs
if backoffs == nil {
diff --git a/internal/hostagent/proxmox_setup_test.go b/internal/hostagent/proxmox_setup_test.go
index 0a70009ced..f2acf44825 100644
--- a/internal/hostagent/proxmox_setup_test.go
+++ b/internal/hostagent/proxmox_setup_test.go
@@ -504,6 +504,15 @@ func TestProxmoxSetup_RunForType(t *testing.T) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, "pve", "https://10.0.0.1:8006", "setup-token-run-for-type")))
case "/api/auto-register":
+ var payload map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode auto-register payload: %v", err)
+ }
+ if check, _ := payload["checkRegistration"].(bool); check {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"registered":true}`))
+ return
+ }
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(fmt.Sprintf(`{"status":"success","message":"Node node-1 registered successfully at https://10.0.0.1:8006","action":"use_token","type":"pve","source":"agent","host":"https://10.0.0.1:8006","nodeId":"node-1","nodeName":"node-1","tokenId":"%s","tokenValue":"my-token"}`, expectedTokenID)))
@@ -519,6 +528,9 @@ func TestProxmoxSetup_RunForType(t *testing.T) {
t.Run("skips if already registered", func(t *testing.T) {
mc.statFn = func(name string) (os.FileInfo, error) { return nil, nil } // exists
+ mc.dialTimeoutFn = func(n, a string, d time.Duration) (net.Conn, error) {
+ return &mockConn{localAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1")}}, nil
+ }
res, err := p.runForType(context.Background(), "pve")
if err != nil || res != nil {
t.Errorf("expected skip")
@@ -759,6 +771,172 @@ func TestProxmoxSetup_RunAll(t *testing.T) {
}
})
+ t.Run("re-registers when Pulse has no matching node for a stale local marker", func(t *testing.T) {
+ mc := &mockCollector{}
+ requestKinds := make([]string, 0, 2)
+ var expectedPVETokenID string
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/setup-script-url":
+ var payload map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode setup token payload: %v", err)
+ }
+ publicURL := "http://" + r.Host
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, payload["type"].(string), payload["host"].(string), "setup-token-check")))
+ case "/api/auto-register":
+ var payload map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode auto-register payload: %v", err)
+ }
+ if check, _ := payload["checkRegistration"].(bool); check {
+ requestKinds = append(requestKinds, "check")
+ if _, ok := payload["tokenId"]; ok {
+ t.Fatalf("expected registration check payload to omit tokenId, got %#v", payload["tokenId"])
+ }
+ if _, ok := payload["tokenValue"]; ok {
+ t.Fatalf("expected registration check payload to omit tokenValue, got %#v", payload["tokenValue"])
+ }
+ if payload["source"] != "agent" {
+ t.Fatalf("source = %#v, want agent", payload["source"])
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"registered":false}`))
+ return
+ }
+ requestKinds = append(requestKinds, "register")
+ if payload["tokenId"] != expectedPVETokenID {
+ t.Fatalf("tokenId = %#v, want %q", payload["tokenId"], expectedPVETokenID)
+ }
+ if payload["tokenValue"] != "v1" {
+ t.Fatalf("tokenValue = %#v, want v1", payload["tokenValue"])
+ }
+ host := payload["host"].(string)
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(fmt.Sprintf(`{"status":"success","message":"Node node-1 registered successfully at %s","action":"use_token","type":"pve","source":"agent","host":"%s","nodeId":"node-1","nodeName":"node-1","tokenId":"%s","tokenValue":"v1"}`, host, host, expectedPVETokenID)))
+ default:
+ t.Fatalf("unexpected path %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+
+ stateDir := t.TempDir()
+ p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, server.URL, "token", "", "host", "", stateDir, false)
+ p.retryBackoffs = []time.Duration{}
+ expectedPVETokenID = fmt.Sprintf("%s!%s", proxmoxUserPVE, p.monitorTokenName())
+
+ pveStateFile := p.pveStateFilePath()
+ mc.lookPathFn = func(file string) (string, error) {
+ if file == "pvesh" {
+ return "/bin/pvesh", nil
+ }
+ return "", os.ErrNotExist
+ }
+ mc.statFn = func(name string) (os.FileInfo, error) {
+ if name == pveStateFile {
+ return nil, nil
+ }
+ return nil, os.ErrNotExist
+ }
+ mc.commandCombinedOutputFn = func(ctx context.Context, name string, arg ...string) (string, error) {
+ if name == "pveum" && len(arg) > 2 && arg[1] == "token" && arg[2] == "add" {
+ return "│ value │ v1 │", nil
+ }
+ return "", nil
+ }
+ mc.dialTimeoutFn = func(network, address string, timeout time.Duration) (net.Conn, error) {
+ return &mockConn{localAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1")}}, nil
+ }
+ mc.mkdirAllFn = func(path string, perm os.FileMode) error { return nil }
+ mc.chmodFn = func(name string, mode os.FileMode) error { return nil }
+ mc.writeFileFn = func(filename string, data []byte, perm os.FileMode) error { return nil }
+
+ results, err := p.RunAll(context.Background())
+ if err != nil {
+ t.Fatalf("RunAll: %v", err)
+ }
+ if len(results) != 1 || !results[0].Registered || results[0].ProxmoxType != "pve" {
+ t.Fatalf("expected one re-registered pve result, got %#v", results)
+ }
+ if strings.Join(requestKinds, ",") != "check,register" {
+ t.Fatalf("unexpected request sequence: %v", requestKinds)
+ }
+ })
+
+ t.Run("skips when Pulse confirms the local marker still matches a registered node", func(t *testing.T) {
+ mc := &mockCollector{}
+ requestKinds := make([]string, 0, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/setup-script-url":
+ var payload map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode setup token payload: %v", err)
+ }
+ publicURL := "http://" + r.Host
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(canonicalSetupScriptURLResponseJSON(publicURL, payload["type"].(string), payload["host"].(string), "setup-token-check")))
+ case "/api/auto-register":
+ var payload map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&payload); err != nil {
+ t.Fatalf("decode auto-register payload: %v", err)
+ }
+ if check, _ := payload["checkRegistration"].(bool); !check {
+ t.Fatalf("expected only registration-check request, got %#v", payload)
+ }
+ requestKinds = append(requestKinds, "check")
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"registered":true}`))
+ default:
+ t.Fatalf("unexpected path %s", r.URL.Path)
+ }
+ }))
+ defer server.Close()
+
+ stateDir := t.TempDir()
+ p := NewProxmoxSetup(zerolog.Nop(), server.Client(), mc, server.URL, "token", "", "host", "", stateDir, false)
+ p.retryBackoffs = []time.Duration{}
+
+ pveStateFile := p.pveStateFilePath()
+ mc.lookPathFn = func(file string) (string, error) {
+ if file == "pvesh" {
+ return "/bin/pvesh", nil
+ }
+ return "", os.ErrNotExist
+ }
+ mc.statFn = func(name string) (os.FileInfo, error) {
+ if name == pveStateFile {
+ return nil, nil
+ }
+ return nil, os.ErrNotExist
+ }
+ mc.commandCombinedOutputFn = func(ctx context.Context, name string, arg ...string) (string, error) {
+ if name == "hostname" && len(arg) == 1 && arg[0] == "-I" {
+ return "", nil
+ }
+ t.Fatalf("did not expect token setup command %q %v", name, arg)
+ return "", nil
+ }
+ mc.dialTimeoutFn = func(network, address string, timeout time.Duration) (net.Conn, error) {
+ return &mockConn{localAddr: &net.UDPAddr{IP: net.ParseIP("10.0.0.1")}}, nil
+ }
+
+ results, err := p.RunAll(context.Background())
+ if err != nil {
+ t.Fatalf("RunAll: %v", err)
+ }
+ if len(results) != 0 {
+ t.Fatalf("expected no setup results when registration already exists, got %#v", results)
+ }
+ if strings.Join(requestKinds, ",") != "check" {
+ t.Fatalf("unexpected request sequence: %v", requestKinds)
+ }
+ })
+
t.Run("invalid forced type returns error", func(t *testing.T) {
p := NewProxmoxSetup(zerolog.Nop(), http.DefaultClient, mc, "https://pulse", "token", "invalid", "host", "", "", false)
if _, err := p.RunAll(context.Background()); err == nil || !strings.Contains(err.Error(), "invalid proxmox type") {
diff --git a/scripts/release_control/subsystem_lookup_test.py b/scripts/release_control/subsystem_lookup_test.py
index 6a8e980f29..b095d821f9 100644
--- a/scripts/release_control/subsystem_lookup_test.py
+++ b/scripts/release_control/subsystem_lookup_test.py
@@ -3709,8 +3709,8 @@ class SubsystemLookupTest(unittest.TestCase):
{
"heading": "## Shared Boundaries",
"path": "internal/api/access_control_handlers.go",
- "line": 109,
- "heading_line": 77,
+ "line": 110,
+ "heading_line": 78,
}
],
)