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.

Skip monitor reload on no-op auto-register

rcourtman6ce593f474e0
diff --git a/internal/api/config_handlers_canonical_auto_register_test.go b/internal/api/config_handlers_canonical_auto_register_test.go
index 6937a883cf..7fa2778943 100644
--- a/internal/api/config_handlers_canonical_auto_register_test.go
+++ b/internal/api/config_handlers_canonical_auto_register_test.go
@@ -6,6 +6,7 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
"github.com/rcourtman/pulse-go-rewrite/pkg/tlsutil"
@@ -577,6 +578,150 @@ func TestHandleCanonicalAutoRegisterConsolidatesStandaloneOverlapIntoClusterInMe
}
}
+func TestHandleCanonicalAutoRegisterNoOpReRegistrationSkipsMonitorReload(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ server := newIPv4TLSServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ // Start with a cluster that already has minipc as an endpoint; the first
+ // auto-register call below promotes the caller's token onto the cluster
+ // and is a legitimate state change. The second identical call simulates
+ // the periodic agent heartbeat that was producing the UI flicker, and
+ // must short-circuit before SaveNodesConfig + monitor reload.
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ PVEInstances: []config.PVEInstance{
+ {
+ Name: "delly",
+ ClusterName: "delly",
+ IsCluster: true,
+ ClusterEndpoints: []config.ClusterEndpoint{
+ {NodeName: "minipc", Host: server.URL},
+ },
+ },
+ },
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+ reloadCalls := 0
+ handler.reloadFunc = func() error {
+ reloadCalls++
+ return nil
+ }
+
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: server.URL,
+ ServerName: "minipc",
+ TokenID: "pulse-monitor@pve!pulse-cluster-node",
+ TokenValue: "cluster-token",
+ Source: "agent",
+ }
+
+ // First call: warms up the cluster's host/token/source/etc. from the
+ // caller's payload. This is a real state change so a reload IS expected.
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", nil)
+ rec := httptest.NewRecorder()
+ handler.handleCanonicalAutoRegister(rec, req, &reqBody, "127.0.0.1")
+ if rec.Code != http.StatusOK {
+ t.Fatalf("warm-up call status = %d, want 200: %s", rec.Code, rec.Body.String())
+ }
+ // Allow the warm-up reload goroutine to run before resetting the counter.
+ time.Sleep(50 * time.Millisecond)
+ if reloadCalls == 0 {
+ t.Fatalf("expected the first state-changing auto-register to call reloadFunc, got %d", reloadCalls)
+ }
+ reloadCalls = 0
+
+ // Second call with the identical payload: this is the no-op scenario
+ // the fix targets. No persisted-config delta → no save → no reload.
+ req2 := httptest.NewRequest(http.MethodPost, "/api/auto-register", nil)
+ rec2 := httptest.NewRecorder()
+ handler.handleCanonicalAutoRegister(rec2, req2, &reqBody, "127.0.0.1")
+ if rec2.Code != http.StatusOK {
+ t.Fatalf("no-op call status = %d, want 200: %s", rec2.Code, rec2.Body.String())
+ }
+
+ // Wait long enough for a scheduled reload goroutine to surface if one
+ // was queued. Reload is fired via `go func()` so a tight assert race is
+ // unsafe; this gives it a generous slice of wall time to fail loudly.
+ time.Sleep(150 * time.Millisecond)
+
+ if reloadCalls != 0 {
+ t.Fatalf("no-op auto-register triggered %d monitor reload(s); expected zero so the WebSocket-visible resource store is not wiped", reloadCalls)
+ }
+}
+
+func TestHandleCanonicalAutoRegisterStateChangingRegistrationStillReloads(t *testing.T) {
+ tempDir := t.TempDir()
+ t.Setenv("PULSE_DATA_DIR", tempDir)
+
+ server := newIPv4TLSServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ // Initial state: a cluster with a stale token. The auto-register payload
+ // carries a fresh token that must be persisted, so SaveNodesConfig and the
+ // monitor reload should still fire.
+ cfg := &config.Config{
+ DataPath: tempDir,
+ ConfigPath: tempDir,
+ PVEInstances: []config.PVEInstance{
+ {
+ Name: "delly",
+ ClusterName: "delly",
+ IsCluster: true,
+ TokenName: "pulse-monitor@pve!pulse-cluster-node",
+ TokenValue: "stale-token",
+ Source: "script",
+ ClusterEndpoints: []config.ClusterEndpoint{
+ {NodeName: "minipc", Host: server.URL},
+ },
+ },
+ },
+ }
+
+ handler := newTestConfigHandlers(t, cfg)
+ reloadCalls := make(chan struct{}, 1)
+ handler.reloadFunc = func() error {
+ select {
+ case reloadCalls <- struct{}{}:
+ default:
+ }
+ return nil
+ }
+
+ reqBody := AutoRegisterRequest{
+ Type: "pve",
+ Host: server.URL,
+ ServerName: "minipc",
+ TokenID: "pulse-monitor@pve!pulse-cluster-node",
+ TokenValue: "fresh-token",
+ Source: "agent",
+ }
+
+ req := httptest.NewRequest(http.MethodPost, "/api/auto-register", nil)
+ rec := httptest.NewRecorder()
+
+ handler.handleCanonicalAutoRegister(rec, req, &reqBody, "127.0.0.1")
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: %s", rec.Code, rec.Body.String())
+ }
+
+ select {
+ case <-reloadCalls:
+ case <-time.After(time.Second):
+ t.Fatal("expected a monitor reload after a real token rotation, none observed")
+ }
+}
+
func TestHandleCanonicalAutoRegister_PVEPreservesExistingHostnameWhenRequestUsesSameIP(t *testing.T) {
tempDir := t.TempDir()
t.Setenv("PULSE_DATA_DIR", tempDir)
diff --git a/internal/api/config_setup_handlers.go b/internal/api/config_setup_handlers.go
index 267c36ac10..9cc08e86cb 100644
--- a/internal/api/config_setup_handlers.go
+++ b/internal/api/config_setup_handlers.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/ed25519"
"crypto/rand"
+ "crypto/sha256"
"encoding/hex"
"encoding/json"
"encoding/pem"
@@ -951,6 +952,31 @@ func (h *ConfigHandlers) handleAutoUnregister(w http.ResponseWriter, r *http.Req
}
}
+// nodesConfigFingerprint computes a deterministic SHA-256 fingerprint of the
+// PVE / PBS / PMG instance lists that would be persisted by SaveNodesConfig.
+// Used by handleCanonicalAutoRegister to detect no-op re-registrations: when
+// an already-known agent re-announces itself the auto-register handler still
+// runs the full add-then-consolidate path, which produces the exact same
+// persisted state. Writing+reloading on those no-ops triggers a full monitor
+// rebuild that briefly empties the resource store, producing a visible
+// flicker for every connected WebSocket client. Comparing fingerprints lets
+// us short-circuit and skip both the save and the reload.
+func nodesConfigFingerprint(pve []config.PVEInstance, pbs []config.PBSInstance, pmg []config.PMGInstance) string {
+ payload := struct {
+ PVE []config.PVEInstance `json:"pve"`
+ PBS []config.PBSInstance `json:"pbs"`
+ PMG []config.PMGInstance `json:"pmg"`
+ }{pve, pbs, pmg}
+ data, err := json.Marshal(payload)
+ if err != nil {
+ // Fall back to a non-comparable sentinel so callers treat this as
+ // "changed" and persist+reload defensively.
+ return fmt.Sprintf("fingerprint-error:%d:%d:%d:%v", len(pve), len(pbs), len(pmg), err)
+ }
+ sum := sha256.Sum256(data)
+ return hex.EncodeToString(sum[:])
+}
+
// HandleAutoRegister receives token details from the setup script and auto-configures the node
func (h *ConfigHandlers) handleAutoRegister(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
@@ -1211,6 +1237,14 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
Str("tokenID", fullTokenID).
Str("source", registrationSource).
Msg("Using caller-supplied token for canonical /api/auto-register completion")
+
+ // Snapshot the pre-mutation persisted-state fingerprint so we can detect
+ // no-op auto-registrations and skip the SaveNodesConfig + monitor reload
+ // that would otherwise wipe the live resource store for every connected
+ // client. See nodesConfigFingerprint for the full rationale.
+ preCfg := h.getConfig(r.Context())
+ beforeFingerprint := nodesConfigFingerprint(preCfg.PVEInstances, preCfg.PBSInstances, preCfg.PMGInstances)
+
// Add the node to configuration
created := false
if req.Type == "pve" {
@@ -1369,10 +1403,21 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
// Save configuration
h.normalizePVEConfigState(r.Context())
- if err := h.getPersistence(r.Context()).SaveNodesConfig(h.getConfig(r.Context()).PVEInstances, h.getConfig(r.Context()).PBSInstances, h.getConfig(r.Context()).PMGInstances); err != nil {
- log.Error().Err(err).Msg("Failed to save auto-registered node")
- http.Error(w, "Failed to save configuration", http.StatusInternalServerError)
- return
+ postCfg := h.getConfig(r.Context())
+ afterFingerprint := nodesConfigFingerprint(postCfg.PVEInstances, postCfg.PBSInstances, postCfg.PMGInstances)
+ configChanged := beforeFingerprint != afterFingerprint
+
+ if configChanged {
+ if err := h.getPersistence(r.Context()).SaveNodesConfig(postCfg.PVEInstances, postCfg.PBSInstances, postCfg.PMGInstances); err != nil {
+ log.Error().Err(err).Msg("Failed to save auto-registered node")
+ http.Error(w, "Failed to save configuration", http.StatusInternalServerError)
+ return
+ }
+ } else {
+ log.Debug().
+ Str("host", host).
+ Str("type", req.Type).
+ Msg("Auto-register resulted in no persisted-config change; skipping SaveNodesConfig and monitor reload")
}
actualName := h.findInstanceNameByHost(r.Context(), req.Type, host)
@@ -1381,8 +1426,11 @@ func (h *ConfigHandlers) handleCanonicalAutoRegister(w http.ResponseWriter, r *h
}
h.markAutoRegistered(req.Type, actualName)
- // Reload monitor
- if h.reloadFunc != nil {
+ // Reload monitor only when the persisted state actually changed. A full
+ // reload stops the multi-tenant monitor and rebuilds it from scratch,
+ // which momentarily empties the WebSocket-visible resource store; for
+ // no-op re-registrations there is nothing for the monitor to pick up.
+ if configChanged && h.reloadFunc != nil {
go func() {
if err := h.reloadFunc(); err != nil {
log.Error().Err(err).Msg("Failed to reload monitor after auto-registration")