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.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Fix websocket state broadcast retention
rcourtmanc47560ad6948
diff --git a/internal/api/agent_handlers_base.go b/internal/api/agent_handlers_base.goindex b0f9337ed1..66595e093e 100644--- a/internal/api/agent_handlers_base.go+++ b/internal/api/agent_handlers_base.go@@ -82,8 +82,16 @@ func (b *baseAgentHandlers) broadcastState(ctx context.Context) {return}- state := monitor.BuildFrontendState()orgID := GetOrgID(ctx)+ if orgID != "" {+ if b.wsHub.GetTenantClientCount(orgID) == 0 {+ return+ }+ } else if b.wsHub.GetClientCount() == 0 {+ return+ }++ state := monitor.BuildFrontendState()if orgID != "" {go b.wsHub.BroadcastStateToTenant(orgID, state)returndiff --git a/internal/api/alerts.go b/internal/api/alerts.goindex 8bad45a1df..9e93e474e7 100644--- a/internal/api/alerts.go+++ b/internal/api/alerts.go@@ -119,6 +119,14 @@ func (h *AlertHandlers) broadcastStateForContext(ctx context.Context) {}orgID := GetOrgID(ctx)+ if orgID != "" {+ if h.wsHub.GetTenantClientCount(orgID) == 0 {+ return+ }+ } else if h.wsHub.GetClientCount() == 0 {+ return+ }+frontendState := h.getMonitor(ctx).BuildFrontendState()if orgID != "" {h.wsHub.BroadcastStateToTenant(orgID, frontendState)diff --git a/internal/monitoring/monitor.go b/internal/monitoring/monitor.goindex 93136ee454..ec61fb19f0 100644--- a/internal/monitoring/monitor.go+++ b/internal/monitoring/monitor.go@@ -1907,6 +1907,9 @@ func (m *Monitor) Start(ctx context.Context, wsHub *websocket.Hub) {Int("pbsBackups", len(state.Backups.PBS)).Int("physicalDisks", len(state.PhysicalDisks)).Msg("Broadcasting state update (ticker)")+ if !stateBroadcasterHasSubscribers(wsHub, m.GetOrgID()) {+ continue+ }frontendState := m.buildBroadcastFrontendStateFromSnapshot(state)// Use tenant-aware broadcast methodm.broadcastState(wsHub, frontendState)@@ -3859,6 +3862,28 @@ type stateBroadcaster interface {BroadcastStateToTenant(orgID string, state interface{})}+type stateSubscriberCounter interface {+ GetClientCount() int+ GetTenantClientCount(orgID string) int+}++func stateBroadcasterHasSubscribers(hub stateBroadcaster, orgID string) bool {+ if isNilStateBroadcaster(hub) {+ return false+ }++ counter, ok := hub.(stateSubscriberCounter)+ if !ok {+ return true+ }++ orgID = strings.TrimSpace(orgID)+ if orgID != "" {+ return counter.GetTenantClientCount(orgID) > 0+ }+ return counter.GetClientCount() > 0+}+// broadcastState broadcasts state to WebSocket clients.// Monitors with an explicit org ID (including "default") are tenant-scoped.// Legacy monitors without an org ID broadcast globally.@@ -3868,6 +3893,9 @@ func (m *Monitor) broadcastState(hub stateBroadcaster, frontendState interface{}}orgID := strings.TrimSpace(m.GetOrgID())+ if !stateBroadcasterHasSubscribers(hub, orgID) {+ return+ }if orgID != "" {hub.BroadcastStateToTenant(orgID, frontendState)} else {@@ -3941,7 +3969,7 @@ func (m *Monitor) SetMockMode(enable bool) error {hub := m.wsHubm.mu.RUnlock()- if hub != nil {+ if hub != nil && stateBroadcasterHasSubscribers(hub, m.GetOrgID()) {frontendState := m.buildBroadcastFrontendStateFromSnapshot(m.GetState())// Use tenant-aware broadcast methodm.broadcastState(hub, frontendState)diff --git a/internal/monitoring/monitor_alerts.go b/internal/monitoring/monitor_alerts.goindex d7f95b6936..e642caa699 100644--- a/internal/monitoring/monitor_alerts.go+++ b/internal/monitoring/monitor_alerts.go@@ -278,6 +278,9 @@ func (m *Monitor) broadcastStateUpdate() {if hub == nil {return}+ if !stateBroadcasterHasSubscribers(hub, m.GetOrgID()) {+ return+ }frontendState := m.BuildBroadcastFrontendState()// Use tenant-aware broadcast methoddiff --git a/internal/websocket/hub.go b/internal/websocket/hub.goindex 14892f5229..c03bdd7531 100644--- a/internal/websocket/hub.go+++ b/internal/websocket/hub.go@@ -618,18 +618,7 @@ func (h *Hub) Run() {case client := <-h.unregister:h.mu.Lock()- if _, ok := h.clients[client]; ok {- delete(h.clients, client)- // Also remove from tenant map- if client.orgID != "" && h.clientsByTenant[client.orgID] != nil {- delete(h.clientsByTenant[client.orgID], client)- // Clean up empty tenant maps- if len(h.clientsByTenant[client.orgID]) == 0 {- delete(h.clientsByTenant, client.orgID)- }- }- client.closed.Store(true) // Mark closed before closing channel to prevent sends- close(client.send)+ if h.removeClientLocked(client) {h.mu.Unlock()log.Info().Str("client", client.id).Str("org_id", client.orgID).Msg("webSocket client disconnected")} else {@@ -637,25 +626,7 @@ func (h *Hub) Run() {}case message := <-h.broadcast:- h.mu.RLock()- clients := make([]*Client, 0, len(h.clients))- for client := range h.clients {- clients = append(clients, client)- }- h.mu.RUnlock()-- for _, client := range clients {- if !client.safeSend(message) {- // Client closed or buffer full - remove if still registered- h.mu.Lock()- if _, stillPresent := h.clients[client]; stillPresent {- delete(h.clients, client)- client.closed.Store(true)- close(client.send)- }- h.mu.Unlock()- }- }+ h.dispatchToClients(message, "Client send channel full, dropping broadcast message and closing connection")case <-pingTicker.C:h.sendPing()@@ -665,10 +636,19 @@ func (h *Hub) Run() {// Close all client connectionsh.mu.Lock()for client := range h.clients {- client.closed.Store(true)- close(client.send)+ if !client.closed.Swap(true) {+ close(client.send)+ }+ }+ for _, tenantClients := range h.clientsByTenant {+ for client := range tenantClients {+ if !client.closed.Swap(true) {+ close(client.send)+ }+ }}h.clients = make(map[*Client]bool)+ h.clientsByTenant = make(map[string]map[*Client]bool)h.mu.Unlock()return}@@ -865,6 +845,48 @@ func normalizeOrgID(orgID string) string {return orgID}+// removeClientLocked removes a client from every hub index and closes the send+// channel once. h.mu must be held by the caller.+func (h *Hub) removeClientLocked(client *Client) bool {+ if client == nil {+ return false+ }++ removed := false+ if _, ok := h.clients[client]; ok {+ delete(h.clients, client)+ removed = true+ }++ if client.orgID != "" {+ if tenantClients := h.clientsByTenant[client.orgID]; tenantClients != nil {+ if _, ok := tenantClients[client]; ok {+ delete(tenantClients, client)+ removed = true+ if len(tenantClients) == 0 {+ delete(h.clientsByTenant, client.orgID)+ }+ }+ }+ } else {+ for orgID, tenantClients := range h.clientsByTenant {+ if _, ok := tenantClients[client]; ok {+ delete(tenantClients, client)+ removed = true+ if len(tenantClients) == 0 {+ delete(h.clientsByTenant, orgID)+ }+ }+ }+ }++ if removed && !client.closed.Swap(true) {+ close(client.send)+ }++ return removed+}+// dispatchToClients fan-outs a marshaled payload to all clients, dropping any that// cannot keep up to prevent unbounded buffering.func (h *Hub) dispatchToClients(data []byte, dropLog string) {@@ -877,12 +899,8 @@ func (h *Hub) dispatchToClients(data []byte, dropLog string) {for _, client := range clients {if !client.safeSend(data) {- // Client closed or buffer full - remove if still registeredh.mu.Lock()- if _, stillPresent := h.clients[client]; stillPresent {- delete(h.clients, client)- client.closed.Store(true)- close(client.send)+ if h.removeClientLocked(client) {log.Warn().Str("client", client.id).Msg(dropLog)}h.mu.Unlock()@@ -1080,15 +1098,8 @@ func (h *Hub) dispatchToTenantClients(orgID string, data []byte, dropLog string)for _, client := range clients {if !client.safeSend(data) {- // Client closed or buffer full - remove if still registeredh.mu.Lock()- if _, stillPresent := h.clients[client]; stillPresent {- delete(h.clients, client)- if h.clientsByTenant[client.orgID] != nil {- delete(h.clientsByTenant[client.orgID], client)- }- client.closed.Store(true)- close(client.send)+ if h.removeClientLocked(client) {log.Warn().Str("client", client.id).Str("org_id", client.orgID).Msg(dropLog)}h.mu.Unlock()diff --git a/internal/websocket/hub_tenant_test.go b/internal/websocket/hub_tenant_test.goindex 8493a8298d..c0f3a6b687 100644--- a/internal/websocket/hub_tenant_test.go+++ b/internal/websocket/hub_tenant_test.go@@ -120,3 +120,61 @@ func TestHub_DispatchToTenantClients(t *testing.T) {// Success}}++func TestHub_GlobalDropRemovesClientFromTenantIndex(t *testing.T) {+ hub := NewHub(nil)+ go hub.Run()+ t.Cleanup(hub.Stop)++ client := registerTenantTestClient(t, hub, "client-full", "org1")+ for i := 0; i < cap(client.send); i++ {+ client.send <- []byte("queued")+ }++ hub.dispatchToClients([]byte("drop"), "Dropping full client")++ hub.mu.RLock()+ _, inClients := hub.clients[client]+ tenantClients := hub.clientsByTenant["org1"]+ _, inTenant := tenantClients[client]+ hub.mu.RUnlock()++ if inClients {+ t.Fatal("full client remained in flat registry after global drop")+ }+ if inTenant || len(tenantClients) != 0 {+ t.Fatal("full client remained in tenant registry after global drop")+ }+ if !client.closed.Load() {+ t.Fatal("full client was not marked closed after global drop")+ }+}++func TestHub_TenantDropClearsStaleTenantOnlyClient(t *testing.T) {+ hub := NewHub(nil)+ client := &Client{+ hub: hub,+ id: "tenant-only-full",+ orgID: "org1",+ send: make(chan []byte, 1),+ }+ client.send <- []byte("queued")++ hub.mu.Lock()+ hub.clientsByTenant["org1"] = map[*Client]bool{client: true}+ hub.mu.Unlock()++ hub.dispatchToTenantClients("org1", []byte("drop"), "Dropping stale tenant client")++ hub.mu.RLock()+ tenantClients := hub.clientsByTenant["org1"]+ _, inTenant := tenantClients[client]+ hub.mu.RUnlock()++ if inTenant || len(tenantClients) != 0 {+ t.Fatal("stale tenant-only client remained in tenant registry after tenant drop")+ }+ if !client.closed.Load() {+ t.Fatal("stale tenant-only client was not marked closed after tenant drop")+ }+}