Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: memory leak in websocket connections (#664)
Kyle Mendell2700c52d4a13
diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.goindex 65508cec4..513d061df 100644--- a/backend/internal/api/container_handler.go+++ b/backend/internal/api/container_handler.go@@ -84,6 +84,13 @@ func (h *ContainerHandler) getOrStartContainerLogHub(containerID, format string,ls.once.Do(func() {ctx, cancel := context.WithCancel(context.Background())ls.cancel = cancel++ ls.hub.SetOnEmpty(func() {+ slog.Debug("all clients disconnected, cleaning up log hub", "containerID", containerID, "format", format)+ cancel()+ h.logStreams.Delete(key)+ })+go ls.hub.Run(ctx)slog.Debug("starting log stream pipeline", "containerID", containerID, "format", format, "batched", batched)@@ -572,6 +579,13 @@ func (h *ContainerHandler) getOrStartContainerStatsHub(containerID string) *ws.Hss.once.Do(func() {ctx, cancel := context.WithCancel(context.Background())ss.cancel = cancel++ ss.hub.SetOnEmpty(func() {+ slog.Debug("all clients disconnected, cleaning up stats hub", "containerID", containerID)+ cancel()+ h.logStreams.Delete(key)+ })+go ss.hub.Run(ctx)slog.Debug("starting stats stream pipeline", "containerID", containerID)diff --git a/backend/internal/api/project_handler.go b/backend/internal/api/project_handler.goindex add870c33..e85221dcc 100644--- a/backend/internal/api/project_handler.go+++ b/backend/internal/api/project_handler.go@@ -4,6 +4,7 @@ import ("context""errors""fmt"+ "log/slog""net/http""strings""sync"@@ -324,6 +325,13 @@ func (h *ProjectHandler) getOrStartProjectLogHub(projectID, format string, batchls.once.Do(func() {ctx, cancel := context.WithCancel(context.Background())ls.cancel = cancel++ ls.hub.SetOnEmpty(func() {+ slog.Debug("all clients disconnected, cleaning up project log hub", "projectID", projectID, "format", format)+ cancel()+ h.logStreams.Delete(key)+ })+go ls.hub.Run(ctx)lines := make(chan string, 256)diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.goindex 07795797b..16122b1f6 100644--- a/backend/internal/api/system_handler.go+++ b/backend/internal/api/system_handler.go@@ -5,6 +5,8 @@ import ("log/slog""net/http""runtime"+ "sync"+ "sync/atomic""time""github.com/docker/docker/api/types/container"@@ -24,9 +26,20 @@ import ()type SystemHandler struct {- dockerService *services.DockerClientService- systemService *services.SystemService- sysWsUpgrader websocket.Upgrader+ dockerService *services.DockerClientService+ systemService *services.SystemService+ sysWsUpgrader websocket.Upgrader+ activeConnections sync.Map+ cpuCache struct {+ sync.RWMutex+ value float64+ timestamp time.Time+ }+ diskUsagePathCache struct {+ sync.RWMutex+ value string+ timestamp time.Time+ }}func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, systemService *services.SystemService, authMiddleware *middleware.AuthMiddleware, cfg *config.Config) {@@ -230,10 +243,24 @@ func (h *SystemHandler) StartAllStoppedContainers(c *gin.Context) {}func (h *SystemHandler) getDiskUsagePath(ctx context.Context) string {+ h.diskUsagePathCache.RLock()+ if h.diskUsagePathCache.value != "" && time.Since(h.diskUsagePathCache.timestamp) < 30*time.Second {+ path := h.diskUsagePathCache.value+ h.diskUsagePathCache.RUnlock()+ return path+ }+ h.diskUsagePathCache.RUnlock()+diskUsagePath := h.systemService.GetDiskUsagePath(ctx)if diskUsagePath == "" {diskUsagePath = "/"}++ h.diskUsagePathCache.Lock()+ h.diskUsagePathCache.value = diskUsagePath+ h.diskUsagePathCache.timestamp = time.Now()+ h.diskUsagePathCache.Unlock()+return diskUsagePath}@@ -256,6 +283,28 @@ func (h *SystemHandler) StopAllContainers(c *gin.Context) {//nolint:gocognitfunc (h *SystemHandler) Stats(c *gin.Context) {+ clientIP := c.ClientIP()++ connCount, _ := h.activeConnections.LoadOrStore(clientIP, new(int32))+ count := connCount.(*int32)++ currentCount := atomic.AddInt32(count, 1)+ if currentCount > 5 {+ atomic.AddInt32(count, -1)+ c.JSON(http.StatusTooManyRequests, gin.H{+ "success": false,+ "error": "Too many concurrent stats connections from this IP",+ })+ return+ }++ defer func() {+ newCount := atomic.AddInt32(count, -1)+ if newCount <= 0 {+ h.activeConnections.Delete(clientIP)+ }+ }()+conn, err := h.sysWsUpgrader.Upgrade(c.Writer, c.Request, nil)if err != nil {return@@ -265,20 +314,32 @@ func (h *SystemHandler) Stats(c *gin.Context) {ticker := time.NewTicker(2 * time.Second)defer ticker.Stop()- var lastCPU float64+ cpuUpdateTicker := time.NewTicker(1 * time.Second)+ defer cpuUpdateTicker.Stop()- send := func(block bool) error {- var cpuUsage float64- if block {- if vals, err := cpu.Percent(time.Second, false); err == nil && len(vals) > 0 {- cpuUsage = vals[0]- lastCPU = cpuUsage- } else {- cpuUsage = lastCPU+ ctx, cancel := context.WithCancel(c.Request.Context())+ defer cancel()++ go func(ctx context.Context) {+ for {+ select {+ case <-ctx.Done():+ return+ case <-cpuUpdateTicker.C:+ if vals, err := cpu.Percent(0, false); err == nil && len(vals) > 0 {+ h.cpuCache.Lock()+ h.cpuCache.value = vals[0]+ h.cpuCache.timestamp = time.Now()+ h.cpuCache.Unlock()+ }}- } else {- cpuUsage = lastCPU}+ }(ctx)++ send := func() error {+ h.cpuCache.RLock()+ cpuUsage := h.cpuCache.value+ h.cpuCache.RUnlock()cpuCount, err := cpu.Counts(true)if err != nil {@@ -322,7 +383,14 @@ func (h *SystemHandler) Stats(c *gin.Context) {return conn.WriteJSON(stats)}- if err := send(true); err != nil {+ if vals, err := cpu.Percent(time.Second, false); err == nil && len(vals) > 0 {+ h.cpuCache.Lock()+ h.cpuCache.value = vals[0]+ h.cpuCache.timestamp = time.Now()+ h.cpuCache.Unlock()+ }++ if err := send(); err != nil {return}@@ -331,7 +399,7 @@ func (h *SystemHandler) Stats(c *gin.Context) {case <-c.Request.Context().Done():returncase <-ticker.C:- if err := send(true); err != nil {+ if err := send(); err != nil {return}}diff --git a/backend/internal/utils/ws/hub.go b/backend/internal/utils/ws/hub.goindex d187e7984..1b7ff47f8 100644--- a/backend/internal/utils/ws/hub.go+++ b/backend/internal/utils/ws/hub.go@@ -3,6 +3,7 @@ package wsimport ("context""log/slog"+ "runtime""sync")@@ -12,6 +13,7 @@ type Hub struct {register chan *Clientunregister chan *Clientbroadcast chan []byte+ onEmpty func()}func NewHub(buffer int) *Hub {@@ -23,6 +25,18 @@ func NewHub(buffer int) *Hub {}}+func (h *Hub) ClientCount() int {+ h.mu.RLock()+ defer h.mu.RUnlock()+ return len(h.clients)+}++func (h *Hub) SetOnEmpty(fn func()) {+ h.mu.Lock()+ h.onEmpty = fn+ h.mu.Unlock()+}+func (h *Hub) Run(ctx context.Context) {for {select {@@ -35,6 +49,18 @@ func (h *Hub) Run(ctx context.Context) {h.mu.Unlock()case c := <-h.unregister:h.remove(c)+ if h.ClientCount() == 0 {+ go func() {+ runtime.Gosched()+ h.mu.RLock()+ empty := len(h.clients) == 0+ onEmpty := h.onEmpty+ h.mu.RUnlock()+ if empty && onEmpty != nil {+ onEmpty()+ }+ }()+ }case msg := <-h.broadcast:h.mu.RLock()for c := range h.clients {diff --git a/frontend/src/lib/components/disk-meter.svelte b/frontend/src/lib/components/disk-meter.svelteindex 787be55ff..4d8f5638a 100644--- a/frontend/src/lib/components/disk-meter.svelte+++ b/frontend/src/lib/components/disk-meter.svelte@@ -46,7 +46,7 @@async function saveDiskUsagePath() {const trimmedPath = diskUsagePath.trim();const result = pathSchema.safeParse(trimmedPath);-+if (!result.success) {const firstError = result.error.issues[0];toast.error(firstError.message);@@ -54,6 +54,7 @@}isSaving = true;+try {await settingsService.updateSettings({ diskUsagePath: trimmedPath });settingsStore.set({ ...$settingsStore, diskUsagePath: trimmedPath });@@ -79,7 +80,7 @@<div class="min-w-0 flex-1"><div class="text-foreground text-sm font-semibold">{m.dashboard_meter_disk()}</div><div class="text-muted-foreground text-xs">{m.dashboard_meter_disk_desc()}</div>- <div class="text-muted-foreground/70 mt-0.5 text-[10px] font-mono">+ <div class="text-muted-foreground/70 mt-0.5 font-mono text-[10px]">{m.dashboard_meter_disk_monitoring({ path: $settingsStore.diskUsagePath })}</div></div>diff --git a/frontend/src/lib/components/logs/log-viewer.svelte b/frontend/src/lib/components/logs/log-viewer.svelteindex a2b0ac0a9..c6f4adc04 100644--- a/frontend/src/lib/components/logs/log-viewer.svelte+++ b/frontend/src/lib/components/logs/log-viewer.svelte@@ -155,12 +155,18 @@if (!targetId) return;+ // Prevent starting if already streaming+ if (shouldBeStreaming && wsClient) {+ return;+ }+try {shouldBeStreaming = true;- isStreaming = true;error = null;- onStart?.();await startWebSocketStream();+ // Only notify after successful start+ isStreaming = true;+ onStart?.();return;} catch (err) {console.error('Failed to start log stream:', err);@@ -171,6 +177,14 @@}async function startWebSocketStream() {+ // Close existing connection if any+ if (wsClient) {+ try {+ wsClient.close();+ } catch {}+ wsClient = null;+ }+wsClient = new ReconnectingWebSocket<string>({buildUrl: async () => {return await buildLogWsEndpoint();@@ -226,7 +240,7 @@});}- export function stopLogStream(notifyCallback = true) {+ export function stopLogStream(notifyCallback = true) {shouldBeStreaming = false;if (eventSource) {@@ -296,12 +310,29 @@$effect(() => {const key = streamKey();- if (!key) return;- if (key === currentStreamKey && isStreaming) return;- if (currentStreamKey) stopLogStream(false); // Don't notify callback on internal stop- logs = [];- currentStreamKey = key;- startLogStream();+ if (!key) {+ if (currentStreamKey && shouldBeStreaming) {+ stopLogStream(false);+ }+ currentStreamKey = null;+ return;+ }++ // If key changed while streaming, restart with new key+ if (currentStreamKey && currentStreamKey !== key) {+ const wasStreaming = shouldBeStreaming;+ if (wasStreaming) {+ stopLogStream(false);+ }+ logs = [];+ currentStreamKey = key;+ if (wasStreaming) {+ startLogStream();+ }+ } else if (!currentStreamKey) {+ // First time - just set the key, don't auto-start+ currentStreamKey = key;+ }});</script>diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.tsindex f8d25e904..219f35c25 100644--- a/frontend/src/lib/utils/ws.ts+++ b/frontend/src/lib/utils/ws.ts@@ -28,6 +28,9 @@ export class ReconnectingWebSocket<T = unknown> {}async connect() {+ if (this.ws && !this.closed) {+ this.close();+ }this.closed = false;this.attempt = 0;await this.connectOnce();@@ -35,6 +38,14 @@ export class ReconnectingWebSocket<T = unknown> {async connectOnce() {if (this.closed || this.connecting) return;++ if (this.ws) {+ try {+ this.ws.close();+ } catch {}+ this.ws = null;+ }+this.connecting = true;let url: string;try {@@ -46,8 +57,9 @@ export class ReconnectingWebSocket<T = unknown> {return;}+ let socket: WebSocket;try {- this.ws = new WebSocket(url);+ socket = new WebSocket(url);} catch (err) {this.connecting = false;this.scheduleReconnect();@@ -55,13 +67,17 @@ export class ReconnectingWebSocket<T = unknown> {return;}- this.ws.onopen = () => {+ this.ws = socket;++ socket.onopen = () => {+ if (socket !== this.ws) return;this.attempt = 0;this.connecting = false;this.opts.onOpen?.();};- this.ws.onmessage = (evt) => {+ socket.onmessage = (evt) => {+ if (socket !== this.ws) return;try {const parser =this.opts.parseMessage ??@@ -76,15 +92,20 @@ export class ReconnectingWebSocket<T = unknown> {}};- this.ws.onerror = (e) => {+ socket.onerror = (e) => {+ if (socket !== this.ws) return;this.opts.onError?.(e);};- this.ws.onclose = () => {+ socket.onclose = () => {+ if (socket !== this.ws) return;this.opts.onClose?.();this.ws = null;+ this.connecting = false;if (!this.closed) this.scheduleReconnect();};++ return;}private scheduleReconnect() {@@ -131,8 +152,6 @@ export class ReconnectingWebSocket<T = unknown> {try {this.ws?.close();} catch {}-- this.ws = null;this.connecting = false;}diff --git a/frontend/src/routes/containers/[containerId]/+page.svelte b/frontend/src/routes/containers/[containerId]/+page.svelteindex b0c7b489c..d3e1f6d94 100644--- a/frontend/src/routes/containers/[containerId]/+page.svelte+++ b/frontend/src/routes/containers/[containerId]/+page.svelte@@ -15,7 +15,7 @@import StatusBadge from '$lib/components/badges/status-badge.svelte';import { format } from 'date-fns';import bytes from 'bytes';- import { onDestroy } from 'svelte';+ import { onDestroy, untrack } from 'svelte';import type {ContainerDetailsDto,ContainerNetworkSettings,@@ -52,6 +52,7 @@let statsWebSocket: ReconnectingWebSocket<any> | null = $state(null);let isConnecting = $state(false);let hasInitialStatsLoaded = $state(false);+ let statsStreamEnabled = $state(false);const cleanContainerName = (name: string | undefined): string => {if (!name) return m.containers_not_found_title();@@ -61,9 +62,12 @@const containerDisplayName = $derived(cleanContainerName(container?.name));async function startStatsStream() {- if (statsWebSocket || isConnecting || !container?.id || !container.state?.running) return;+ if (isConnecting || statsWebSocket || !container?.id || !container.state?.running) {+ return;+ }isConnecting = true;+ statsStreamEnabled = true;try {const envId = await environmentStore.getCurrentEnvironmentId();@@ -89,7 +93,9 @@isConnecting = false;},maxBackoff: 5000,- shouldReconnect: () => selectedTab === 'stats' && container?.state?.running === true+ shouldReconnect: () => {+ return statsStreamEnabled && container?.state?.running === true;+ }});ws.connect();@@ -101,6 +107,7 @@}function closeStatsStream() {+ statsStreamEnabled = false;if (statsWebSocket) {statsWebSocket.close();statsWebSocket = null;@@ -110,11 +117,18 @@}$effect(() => {- if (selectedTab === 'stats' && container?.state?.running) {- void startStatsStream();- } else if (statsWebSocket) {- closeStatsStream();- }+ const isStatsTab = selectedTab === 'stats';++ untrack(() => {+ const containerRunning = container?.state?.running;+ const hasWebSocket = !!statsWebSocket;++ if (isStatsTab && containerRunning && !hasWebSocket) {+ void startStatsStream();+ } else if (!isStatsTab && hasWebSocket) {+ closeStatsStream();+ }+ });});onDestroy(() => {@@ -279,32 +293,38 @@{#if showStats}<Tabs.Content value="stats" class="h-full">- <ContainerStats- {container}- {stats}- {cpuUsagePercent}- {memoryUsageFormatted}- {memoryLimitFormatted}- {memoryUsagePercent}- loading={!hasInitialStatsLoaded}- />+ {#if selectedTab === 'stats'}+ <ContainerStats+ {container}+ {stats}+ {cpuUsagePercent}+ {memoryUsageFormatted}+ {memoryLimitFormatted}+ {memoryUsagePercent}+ loading={!hasInitialStatsLoaded}+ />+ {/if}</Tabs.Content>{/if}<Tabs.Content value="logs" class="h-full">- <ContainerLogsPanel- containerId={container?.id}- bind:autoScroll={autoScrollLogs}- onStart={handleLogStart}- onStop={handleLogStop}- onClear={handleLogClear}- onToggleAutoScroll={handleToggleAutoScroll}- />+ {#if selectedTab === 'logs'}+ <ContainerLogsPanel+ containerId={container?.id}+ bind:autoScroll={autoScrollLogs}+ onStart={handleLogStart}+ onStop={handleLogStop}+ onClear={handleLogClear}+ onToggleAutoScroll={handleToggleAutoScroll}+ />+ {/if}</Tabs.Content>{#if showShell}<Tabs.Content value="shell" class="h-full">- <ContainerShell containerId={container?.id} />+ {#if selectedTab === 'shell'}+ <ContainerShell containerId={container?.id} />+ {/if}</Tabs.Content>{/if}diff --git a/frontend/src/routes/containers/components/ContainerLogsPanel.svelte b/frontend/src/routes/containers/components/ContainerLogsPanel.svelteindex b30dd59d6..39ebf1df2 100644--- a/frontend/src/routes/containers/components/ContainerLogsPanel.svelte+++ b/frontend/src/routes/containers/components/ContainerLogsPanel.svelte@@ -25,13 +25,10 @@let viewer = $state<LogViewer>();function handleStart() {- isStreaming = true;viewer?.startLogStream();- onStart();}function handleStop() {- isStreaming = false;viewer?.stopLogStream();}@@ -42,7 +39,20 @@function handleRefresh() {viewer?.stopLogStream();- viewer?.startLogStream();+ setTimeout(() => {+ viewer?.startLogStream();+ }, 100);+ }++ // Sync isStreaming from viewer callbacks+ function handleStreamStart() {+ isStreaming = true;+ onStart();+ }++ function handleStreamStop() {+ isStreaming = false;+ onStop();}</script>@@ -86,9 +96,9 @@maxLines={500}showTimestamps={true}height="calc(100vh - 320px)"- onStart={handleStart}- onStop={handleStop}- onClear={handleClear}+ onStart={handleStreamStart}+ onStop={handleStreamStop}+ {onClear}/></div></Card.Content>diff --git a/frontend/src/routes/containers/components/ContainerShell.svelte b/frontend/src/routes/containers/components/ContainerShell.svelteindex 92cad2c0c..e6b85a505 100644--- a/frontend/src/routes/containers/components/ContainerShell.svelte+++ b/frontend/src/routes/containers/components/ContainerShell.svelte@@ -17,8 +17,21 @@let websocketUrl = $state('');let selectedShell = $state($settingsStore.defaultShell || '/bin/sh');let reconnectKey = $state(0);+ let lastContainerId = $state<string | undefined>(undefined);+ let lastShell = $state<string | undefined>(undefined);$effect(() => {+ // Only update if container or shell actually changed+ const currentContainer = containerId;+ const currentShell = $settingsStore.defaultShell || selectedShell;++ if (lastContainerId === currentContainer && lastShell === currentShell) {+ return; // No change, skip update+ }++ lastContainerId = currentContainer;+ lastShell = currentShell;+if ($settingsStore.defaultShell) {selectedShell = $settingsStore.defaultShell;}diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelteindex 2bf071868..59edd33e3 100644--- a/frontend/src/routes/dashboard/+page.svelte+++ b/frontend/src/routes/dashboard/+page.svelte@@ -142,6 +142,11 @@}function setupStatsWS() {+ if (statsWSClient) {+ statsWSClient.close();+ statsWSClient = null;+ }+const getEnvId = () => {const env = get(environmentStore.selected);return env ? env.id : '0';