Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
fix: container exec sessions not being cleaned up after websockets close (#1614)
Kyle Mendell87e517d78139
diff --git a/backend/internal/api/ws_handler.go b/backend/internal/api/ws_handler.goindex d7330f1dd..424d86461 100644--- a/backend/internal/api/ws_handler.go+++ b/backend/internal/api/ws_handler.go@@ -6,6 +6,7 @@ import ("encoding/csv""encoding/json""fmt"+ "io""log/slog""net/http""os"@@ -439,67 +440,101 @@ func (h *WebSocketHandler) ContainerExec(c *gin.Context) {ctx, cancel := context.WithCancel(c.Request.Context())defer cancel()+ h.runContainerExecInternal(ctx, cancel, conn, containerID, shell)+}++func (h *WebSocketHandler) runContainerExecInternal(ctx context.Context, cancel context.CancelFunc, conn *websocket.Conn, containerID, shell string) {// Create exec instanceexecID, err := h.containerService.CreateExec(ctx, containerID, []string{shell})if err != nil {- _ = conn.WriteMessage(websocket.TextMessage, []byte((&common.ExecCreationError{Err: err}).Error()+"\r\n"))+ h.writeExecErrorInternal(conn, &common.ExecCreationError{Err: err})return}// Attach to exec- stdin, stdout, err := h.containerService.AttachExec(ctx, execID)+ execSession, err := h.containerService.AttachExec(ctx, containerID, execID)if err != nil {- _ = conn.WriteMessage(websocket.TextMessage, []byte((&common.ExecAttachError{Err: err}).Error()+"\r\n"))+ h.writeExecErrorInternal(conn, &common.ExecAttachError{Err: err})return}- defer stdin.Close()+ cleanup := h.execCleanupFuncInternal(ctx, execSession, execID, containerID)+ defer cleanup()+ h.watchExecContextInternal(ctx, execID, containerID, cleanup)done := make(chan struct{})+ go h.pipeExecOutputInternal(ctx, conn, execSession.Stdout(), execID, containerID, done)+ go h.pipeExecInputInternal(ctx, cancel, conn, execSession.Stdin(), execID, containerID)- // Read from container, write to websocket- go func() {- defer close(done)- buf := make([]byte, 4096)- for {- select {- case <-ctx.Done():- return- default:- }+ <-done+}- n, err := stdout.Read(buf)- if err != nil {- return- }- if n > 0 {- if err := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {- return- }- }+func (h *WebSocketHandler) writeExecErrorInternal(conn *websocket.Conn, err error) {+ _ = conn.WriteMessage(websocket.TextMessage, []byte(err.Error()+"\r\n"))+}++func (h *WebSocketHandler) execCleanupFuncInternal(ctx context.Context, execSession *services.ExecSession, execID, containerID string) func() {+ return func() {+ slog.Debug("Cleaning up exec session", "execID", execID, "containerID", containerID, "contextErr", ctx.Err())+ // Cleanup must proceed even if parent ctx is canceled.+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second) //nolint:contextcheck+ defer cleanupCancel()+ if err := execSession.Close(cleanupCtx); err != nil { //nolint:contextcheck+ slog.Warn("Failed to clean up exec session", "execID", execID, "error", err)}- }()+ }+}- // Read from websocket, write to container+func (h *WebSocketHandler) watchExecContextInternal(ctx context.Context, execID, containerID string, cleanup func()) {go func() {- for {- select {- case <-ctx.Done():- return- default:- }+ <-ctx.Done()+ slog.Debug("Exec context cancelled", "execID", execID, "containerID", containerID)+ cleanup()+ }()+}- _, data, err := conn.ReadMessage()- if err != nil {- cancel()- return- }- if _, err := stdin.Write(data); err != nil {+func (h *WebSocketHandler) pipeExecOutputInternal(ctx context.Context, conn *websocket.Conn, stdout io.Reader, execID, containerID string, done chan<- struct{}) {+ defer close(done)+ buf := make([]byte, 4096)+ for {+ select {+ case <-ctx.Done():+ return+ default:+ }++ n, err := stdout.Read(buf)+ if err != nil {+ slog.Debug("Exec stdout read error", "execID", execID, "containerID", containerID, "error", err)+ return+ }+ if n > 0 {+ if err := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); err != nil {+ slog.Debug("Exec websocket write error", "execID", execID, "containerID", containerID, "error", err)return}}- }()+ }+}- <-done+func (h *WebSocketHandler) pipeExecInputInternal(ctx context.Context, cancel context.CancelFunc, conn *websocket.Conn, stdin io.Writer, execID, containerID string) {+ for {+ select {+ case <-ctx.Done():+ return+ default:+ }++ _, data, err := conn.ReadMessage()+ if err != nil {+ slog.Debug("Exec websocket read error", "execID", execID, "containerID", containerID, "error", err)+ cancel()+ return+ }+ if _, err := stdin.Write(data); err != nil {+ slog.Debug("Exec stdin write error", "execID", execID, "containerID", containerID, "error", err)+ return+ }+ }}// ============================================================================diff --git a/backend/internal/services/container_service.go b/backend/internal/services/container_service.goindex 2d9332c1a..f89bfa34d 100644--- a/backend/internal/services/container_service.go+++ b/backend/internal/services/container_service.go@@ -9,10 +9,14 @@ import ("io""log/slog""strings"+ "sync"+ "time"+ "github.com/docker/docker/api/types""github.com/docker/docker/api/types/container""github.com/docker/docker/api/types/image""github.com/docker/docker/api/types/network"+ "github.com/docker/docker/client""github.com/docker/docker/pkg/stdcopy""github.com/getarcaneapp/arcane/backend/internal/database""github.com/getarcaneapp/arcane/backend/internal/models"@@ -624,19 +628,54 @@ func (s *ContainerService) CreateExec(ctx context.Context, containerID string, creturn execResp.ID, nil}-// AttachExec attaches to an exec instance and returns stdin, stdout/stderr streams-func (s *ContainerService) AttachExec(ctx context.Context, execID string) (io.WriteCloser, io.Reader, error) {+// ExecSession manages the lifecycle of a Docker exec session.+type ExecSession struct {+ execID string+ containerID string+ hijackedResp types.HijackedResponse+ dockerClient *client.Client+ closeOnce sync.Once+}++func (e *ExecSession) Stdin() io.WriteCloser { return e.hijackedResp.Conn }+func (e *ExecSession) Stdout() io.Reader { return e.hijackedResp.Reader }++// Close terminates the exec session and kills the process if still running.+func (e *ExecSession) Close(ctx context.Context) error {+ var closeErr error+ e.closeOnce.Do(func() {+ slog.Debug("Closing exec session", "execID", e.execID, "containerID", e.containerID)++ // Send EOF (Ctrl-D) then exit to terminate the shell gracefully.+ _, _ = e.hijackedResp.Conn.Write([]byte{0x04})+ time.Sleep(50 * time.Millisecond)+ _, _ = e.hijackedResp.Conn.Write([]byte("exit\n"))+ time.Sleep(100 * time.Millisecond)++ e.hijackedResp.Close()+ })++ return closeErr+}++// AttachExec attaches to an exec instance and returns an ExecSession for lifecycle management.+func (s *ContainerService) AttachExec(ctx context.Context, containerID, execID string) (*ExecSession, error) {dockerClient, err := s.dockerService.GetClient()if err != nil {- return nil, nil, fmt.Errorf("failed to connect to Docker: %w", err)+ return nil, fmt.Errorf("failed to connect to Docker: %w", err)}execAttach, err := dockerClient.ContainerExecAttach(ctx, execID, container.ExecAttachOptions{Tty: true,})if err != nil {- return nil, nil, fmt.Errorf("failed to attach to exec: %w", err)+ return nil, fmt.Errorf("failed to attach to exec: %w", err)}- return execAttach.Conn, execAttach.Reader, nil+ return &ExecSession{+ execID: execID,+ containerID: containerID,+ hijackedResp: execAttach,+ dockerClient: dockerClient,+ }, nil}diff --git a/frontend/src/lib/components/terminal/terminal.svelte b/frontend/src/lib/components/terminal/terminal.svelteindex d5c56045c..bae6f68df 100644--- a/frontend/src/lib/components/terminal/terminal.svelte+++ b/frontend/src/lib/components/terminal/terminal.svelte@@ -1,5 +1,5 @@<script lang="ts">- import { onMount, onDestroy } from 'svelte';+ import { onMount } from 'svelte';import { Terminal } from '@xterm/xterm';import { FitAddon } from '@xterm/addon-fit';import '@xterm/xterm/css/xterm.css';@@ -24,6 +24,7 @@let ws: WebSocket | null = null;let isReconnecting = false;let resizeObserver: ResizeObserver | null = null;+ let isReady = $state(false);const darkTheme = {background: '#09090b',@@ -165,8 +166,8 @@onMount(() => {initializeTerminal();- connectWebSocket();window.addEventListener('resize', handleResize);+ isReady = true;return () => {window.removeEventListener('resize', handleResize);@@ -178,7 +179,7 @@});$effect(() => {- if (websocketUrl && terminal) {+ if (isReady && websocketUrl && terminal) {terminal.clear();connectWebSocket();}@@ -190,12 +191,6 @@}});- onDestroy(() => {- resizeObserver?.disconnect();- isReconnecting = true;- ws?.close();- terminal?.dispose();- });</script><div bind:this={container} class="terminal-container h-full w-full" style="height: {height}"></div>