Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add container processes tab (#4187)
Kyle Mendellbbc70f7d6007
diff --git a/backend/internal/bootstrap/logger_bootstrap.go b/backend/internal/bootstrap/logger_bootstrap.goindex 1fee15e37..1342fdf30 100644--- a/backend/internal/bootstrap/logger_bootstrap.go+++ b/backend/internal/bootstrap/logger_bootstrap.go@@ -25,6 +25,18 @@ type attrFilterHandler struct {dropKeys map[string]struct{}}+// gormLogger drops traces for queries interrupted by a canceled request context.+type gormLogger struct {+ logger.Interface+}++func (l gormLogger) Trace(ctx context.Context, begin time.Time, fc func() (string, int64), err error) {+ if errors.Is(err, context.Canceled) {+ return+ }+ l.Interface.Trace(ctx, begin, fc, err)+}+type stackAttrHandler struct {handler slog.Handlerattrs []slog.Attr@@ -274,5 +286,5 @@ func BuildGormLogger(cfg *config.Config) logger.Interface {slogGorm.SetLogLevel(slogGorm.SlowQueryLogType, slog.LevelWarn),)- return slogGorm.New(opts...)+ return gormLogger{Interface: slogGorm.New(opts...)}}diff --git a/backend/internal/container/handler.go b/backend/internal/container/handler.goindex f2bc0f2e1..d4fd0840d 100644--- a/backend/internal/container/handler.go+++ b/backend/internal/container/handler.go@@ -184,6 +184,16 @@ func RegisterContainers(api huma.API, containerSvc *ContainerService, dockerSvcSecurity: handlerutil.DefaultOperationSecurity(),}, authz.PermContainersRead, h.GetContainer)+ middleware.RegisterWithPermission(api, huma.Operation{+ OperationID: "get-container-processes",+ Method: http.MethodGet,+ Path: "/environments/{id}/containers/{containerId}/processes",+ Summary: "Get container processes",+ Description: "Snapshot of the processes running inside the container, as reported by Docker",+ Tags: []string{"Containers"},+ Security: handlerutil.DefaultOperationSecurity(),+ }, authz.PermContainersRead, h.GetContainerProcesses)+middleware.RegisterWithPermission(api, huma.Operation{OperationID: "start-container",Method: http.MethodPost,@@ -658,6 +668,30 @@ func (h *ContainerHandler) GetContainer(ctx context.Context, input *GetContainer}, nil}+func (h *ContainerHandler) GetContainerProcesses(ctx context.Context, input *GetContainerInput) (*handlerutil.Out[containertypes.Processes], error) {+ processes, err := h.containerService.GetContainerProcesses(ctx, input.ContainerID)+ if err != nil {+ message := errors.WithMessage(err, "Failed to retrieve container processes").Error()+ switch {+ case errdefs.IsNotFound(err):+ return nil, huma.Error404NotFound(message)+ case errdefs.IsConflict(err):+ return nil, huma.Error409Conflict(message)+ case errors.Is(err, context.DeadlineExceeded):+ return nil, huma.Error504GatewayTimeout(message)+ default:+ return nil, huma.Error500InternalServerError(message)+ }+ }++ return &handlerutil.Out[containertypes.Processes]{+ Body: base.ApiResponse[containertypes.Processes]{+ Success: true,+ Data: processes,+ },+ }, nil+}+func (h *ContainerHandler) DownloadContainerLogs(ctx context.Context, input *GetContainerInput) (*huma.StreamResponse, error) {reader, filename, err := h.containerService.DownloadLogs(ctx, input.ContainerID)if err != nil {diff --git a/backend/internal/container/service.go b/backend/internal/container/service.goindex 405304cc8..f02d5978a 100644--- a/backend/internal/container/service.go+++ b/backend/internal/container/service.go@@ -1194,6 +1194,38 @@ func (s *ContainerService) GetContainerDetails(ctx context.Context, id string) (}// GetContainerNameByReference resolves a container's clean name from a Docker ID or name.++// containerProcessesPsArgs asks ps for per-process CPU and memory; Windows daemons ignore it.+var containerProcessesPsArgs = []string{"-eo", "pid,user,%cpu,%mem,etime,cmd"}++// GetContainerProcesses returns Docker's `top` snapshot for a container.+func (s *ContainerService) GetContainerProcesses(ctx context.Context, containerID string) (containertypes.Processes, error) {+ dockerClient, err := s.dockerService.GetClient(ctx)+ if err != nil {+ return containertypes.Processes{}, errors.WrapIf(err, "failed to connect to Docker")+ }++ timeout := timeouts.DefaultDockerAPI+ if s.settingsService != nil {+ timeout = timeouts.GetDuration(s.settingsService.GetSettingsConfig().DockerAPITimeout.AsInt(), timeouts.DefaultDockerAPI)+ }+ topCtx, cancel := context.WithTimeout(ctx, timeout)+ defer cancel()++ result, err := dockerClient.ContainerTop(topCtx, containerID, client.ContainerTopOptions{Arguments: containerProcessesPsArgs})+ if err != nil {+ return containertypes.Processes{}, errors.WrapIf(err, "failed to list container processes")+ }+ processes := containertypes.Processes{Titles: result.Titles, Processes: result.Processes}+ if processes.Titles == nil {+ processes.Titles = []string{}+ }+ if processes.Processes == nil {+ processes.Processes = [][]string{}+ }+ return processes, nil+}+func (s *ContainerService) GetContainerNameByReference(ctx context.Context, ref string) (string, error) {info, err := s.GetContainerByReference(ctx, ref)if err != nil {diff --git a/backend/internal/container/service_test.go b/backend/internal/container/service_test.goindex 52963d15c..2a4b033fd 100644--- a/backend/internal/container/service_test.go+++ b/backend/internal/container/service_test.go@@ -11,12 +11,17 @@ import ("context""encoding/json"+ "io""net/http""net/http/httptest""net/netip"+ "net/url""regexp"+ "strings""testing"+ "time"+ "github.com/containerd/errdefs""github.com/getarcaneapp/arcane/backend/v2/internal/database""github.com/getarcaneapp/arcane/backend/v2/internal/docker""github.com/getarcaneapp/arcane/backend/v2/internal/event"@@ -625,3 +630,74 @@ func TestBuildSummariesUsesContainerTagPolicyUpdates(t *testing.T) {require.Contains(t, string(encoded), `"autoUpdateEnabled":false`, "false status must stay serialized")}++func TestContainerServiceGetContainerProcessesInternal(t *testing.T) {+ tests := []struct {+ name string+ status int+ body string+ wantTitles []string+ wantRows [][]string+ wantErr func(error) bool+ }{+ {+ name: "docker snapshot",+ status: http.StatusOK,+ body: `{"Titles":["PID","USER","%CPU","%MEM","ELAPSED","CMD"],"Processes":[["1","root","0.0","0.1","01:02:03","nginx: master process nginx -g daemon off;"],["29","nginx","0.0","0.1","01:02:03","nginx: worker process"]]}`,+ wantTitles: []string{"PID", "USER", "%CPU", "%MEM", "ELAPSED", "CMD"},+ wantRows: [][]string{{"1", "root", "0.0", "0.1", "01:02:03", "nginx: master process nginx -g daemon off;"}, {"29", "nginx", "0.0", "0.1", "01:02:03", "nginx: worker process"}},+ },+ {name: "empty", status: http.StatusOK, body: `{}`, wantTitles: []string{}, wantRows: [][]string{}},+ {name: "not found", status: http.StatusNotFound, body: `{"message":"No such container: container-1"}`, wantErr: errdefs.IsNotFound},+ {name: "not running", status: http.StatusConflict, body: `{"message":"container container-1 is not running"}`, wantErr: errdefs.IsConflict},+ }+ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ var gotQuery url.Values+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || dockerTestPathInternal(r.URL.Path) != "/containers/container-1/top" {+ http.NotFound(w, r)+ return+ }+ gotQuery = r.URL.Query()+ w.Header().Set("Content-Type", "application/json")+ w.WriteHeader(tt.status)+ if _, err := io.WriteString(w, tt.body); err != nil {+ t.Error(err)+ }+ }))+ t.Cleanup(server.Close)+ svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil)++ processes, err := svc.GetContainerProcesses(context.Background(), "container-1")+ require.Equal(t, strings.Join(containerProcessesPsArgs, " "), gotQuery.Get("ps_args"))+ if tt.wantErr != nil {+ require.True(t, tt.wantErr(err), "unexpected error: %v", err)+ return+ }+ require.NoError(t, err)+ require.Equal(t, tt.wantTitles, processes.Titles)+ require.Equal(t, tt.wantRows, processes.Processes)+ })+ }+}++func TestContainerServiceGetContainerProcessesPropagatesContextInternal(t *testing.T) {+ requestDone := make(chan struct{})+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ <-r.Context().Done()+ close(requestDone)+ }))+ t.Cleanup(server.Close)+ svc := NewContainerService(nil, docker.NewDockerClientService(t.Context(), nil, nil, nil).WithClient(newTestDockerClientInternal(t, server)), nil, nil, nil)++ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)+ defer cancel()+ _, err := svc.GetContainerProcesses(ctx, "container-1")+ require.ErrorIs(t, err, context.DeadlineExceeded)+ select {+ case <-requestDone:+ case <-time.After(5 * time.Second):+ t.Fatal("Docker request was not cancelled")+ }+}diff --git a/backend/internal/environment/environment.go b/backend/internal/environment/environment.goindex e7dd5bcdd..49a12158a 100644--- a/backend/internal/environment/environment.go+++ b/backend/internal/environment/environment.go@@ -167,7 +167,9 @@ func (s *EnvironmentService) ResolveEnvironmentName(ctx context.Context, environ}env, err := s.GetEnvironmentByID(ctx, environmentID)if err != nil || env == nil {- slog.WarnContext(ctx, "failed to resolve environment name", "environmentID", environmentID, "error", err)+ if !errors.Is(err, context.Canceled) {+ slog.WarnContext(ctx, "failed to resolve environment name", "environmentID", environmentID, "error", err)+ }return DisplayName(environmentID, "")}return DisplayName(env.ID, env.Name)diff --git a/frontend/messages/en.json b/frontend/messages/en.jsonindex 87b2bdbe9..6c43fa81e 100644--- a/frontend/messages/en.json+++ b/frontend/messages/en.json@@ -3738,5 +3738,9 @@"minutes": "minutes","commits_files_to": "Commits {count} file(s) to","create_new_project": "Create a new project",- "link_existing_project_description": "Link an existing project instead of creating one. Its files are replaced from the repository; local .env values are kept."+ "link_existing_project_description": "Link an existing project instead of creating one. Its files are replaced from the repository; local .env values are kept.",+ "containers_processes_title": "Processes",+ "containers_processes_description": "Processes running inside the container, as reported by Docker. Refreshes every few seconds.",+ "containers_processes_unavailable": "Container is not running. Processes unavailable.",+ "containers_processes_empty": "No processes reported"}diff --git a/frontend/src/lib/query/query-keys.ts b/frontend/src/lib/query/query-keys.tsindex 2802b981c..1b93f6af5 100644--- a/frontend/src/lib/query/query-keys.ts+++ b/frontend/src/lib/query/query-keys.ts@@ -111,7 +111,8 @@ export const queryKeys = {create: (environmentId: string) => ['containers', 'create', environmentId] as const,statusCounts: (environmentId: string) => ['containers', 'status-counts', environmentId] as const,detail: (environmentId: string, containerId: string) => ['container', environmentId, containerId] as const,- editConfig: (environmentId: string, containerId: string) => ['container', environmentId, containerId, 'edit-config'] as const+ editConfig: (environmentId: string, containerId: string) => ['container', environmentId, containerId, 'edit-config'] as const,+ processes: (environmentId: string, containerId: string) => ['container', environmentId, containerId, 'processes'] as const},images: {all: ['images'] as const,diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.tsindex bf6643ab6..1ac40a572 100644--- a/frontend/src/lib/services/container-service.ts+++ b/frontend/src/lib/services/container-service.ts@@ -9,7 +9,8 @@ import type {ContainerCommitRequest,ContainerCommitResult,ContainerEditConfigDto,- ContainerEditRequest+ ContainerEditRequest,+ ContainerProcessesDto} from '#lib/types/docker.js';import type { SearchPaginationSortRequest, Paginated } from '#lib/types/shared.js';import type { Activity } from '#lib/types/activity.type.js';@@ -66,6 +67,11 @@ class ContainerService extends BaseAPIService {return this.handleResponse(this.api.get(`/environments/${environmentId}/containers/${containerId}`));}+ async getContainerProcesses(containerId: string, signal?: AbortSignal): Promise<ContainerProcessesDto> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}/processes`, { signal }));+ }+async startContainer(containerId: string): Promise<any> {const envId = await environmentStore.getCurrentEnvironmentId();return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));diff --git a/frontend/src/lib/types/docker.ts b/frontend/src/lib/types/docker.tsindex 934fea9b0..8694ebcfa 100644--- a/frontend/src/lib/types/docker.ts+++ b/frontend/src/lib/types/docker.ts@@ -1065,3 +1065,8 @@ export interface ContainerRegistryPullUsage {checkedAt: string;error?: string;}++export interface ContainerProcessesDto {+ titles: string[];+ processes: string[][];+}diff --git a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte b/frontend/src/routes/(app)/containers/[containerId]/+page.svelteindex 559fb4b99..7e52a6c65 100644--- a/frontend/src/routes/(app)/containers/[containerId]/+page.svelte+++ b/frontend/src/routes/(app)/containers/[containerId]/+page.svelte@@ -24,6 +24,7 @@import ContainerShell from '../components/ContainerShell.svelte';import ContainerComposePanel from '../components/ContainerComposePanel.svelte';import ContainerInspect from '../components/ContainerInspect.svelte';+ import ContainerProcesses from '../components/ContainerProcesses.svelte';import ContainerDetailStatsSync from '../components/container-detail-stats-sync.svelte';import ContainerHealthcheck from '../components/ContainerHealthcheck.svelte';import ContainerCommitDialog from '../components/container-commit-dialog.svelte';@@ -41,7 +42,8 @@StatsIcon,CodeIcon,InspectIcon,- HealthIcon+ HealthIcon,+ LayoutListIcon} from '#lib/icons/index.js';import { parse as parseYaml } from 'yaml';import type { IncludeFile } from '#lib/types/swarm.js';@@ -349,6 +351,7 @@const tabItems = $derived<TabItem[]>([{ value: 'overview', label: m.common_overview(), icon: ContainersIcon },...(showStats ? [{ value: 'stats', label: m.containers_nav_metrics(), icon: StatsIcon }] : []),+ { value: 'processes', label: m.containers_processes_title(), icon: LayoutListIcon },...(canViewLogs ? [{ value: 'logs', label: m.common_logs(), icon: FileTextIcon }] : []),...(showShell ? [{ value: 'shell', label: m.common_shell(), icon: TerminalIcon }] : []),...(hasHealthcheck ? [{ value: 'healthcheck', label: m.containers_nav_healthcheck(), icon: HealthIcon }] : []),@@ -587,6 +590,12 @@</Tabs.Content>{/if}+ <Tabs.Content value="processes" class="h-full">+ {#if activeTab === 'processes'}+ <ContainerProcesses containerId={container.id} status={containerStatus} />+ {/if}+ </Tabs.Content>+<Tabs.Content value="logs" class="h-full">{#if activeTab === 'logs'}{#key container?.id}diff --git a/frontend/src/routes/(app)/containers/components/ContainerProcesses.svelte b/frontend/src/routes/(app)/containers/components/ContainerProcesses.sveltenew file mode 100644index 000000000..15b4c18bc--- /dev/null+++ b/frontend/src/routes/(app)/containers/components/ContainerProcesses.svelte@@ -0,0 +1,93 @@+<script lang="ts">+ import * as Card from '#lib/components/ui/card/index.js';+ import * as Table from '#lib/components/ui/table/index.js';+ import { ArcaneButton } from '#lib/components/arcane-button/index.js';+ import EmptyState from '#lib/components/states/empty-state.svelte';+ import Spinner from '#lib/components/ui/spinner/spinner.svelte';+ import { m } from '#lib/paraglide/messages.js';+ import { LayoutListIcon } from '#lib/icons/index.js';+ import { createQuery } from '@tanstack/svelte-query';+ import { queryKeys } from '#lib/query/query-keys.js';+ import { containerService } from '#lib/services/container-service.js';+ import { environmentStore } from '#lib/stores/environment.store.svelte.js';+ import { extractApiErrorMessage } from '#lib/utils/api.js';++ interface Props {+ containerId: string;+ status: string;+ }++ let { containerId, status }: Props = $props();++ const canFetch = $derived(status === 'running' || status === 'paused');++ const processesQuery = createQuery(() => ({+ queryKey: queryKeys.containers.processes(environmentStore.selected?.id ?? '', containerId),+ queryFn: ({ signal }) => containerService.getContainerProcesses(containerId, signal),+ enabled: canFetch,+ gcTime: 0,+ retry: false,+ refetchOnWindowFocus: false,+ refetchOnReconnect: false,+ refetchInterval: 5000+ }));++ const titles = $derived(processesQuery.data?.titles ?? []);+ const processes = $derived(processesQuery.data?.processes ?? []);+ const pidIndex = $derived(titles.findIndex((title) => title.toUpperCase() === 'PID'));+</script>++<Card.Root>+ <Card.Header icon={LayoutListIcon}>+ <div class="flex flex-col space-y-1.5">+ <Card.Title>+ <h2>{m.containers_processes_title()}</h2>+ </Card.Title>+ <Card.Description>{m.containers_processes_description()}</Card.Description>+ </div>+ {#if canFetch}+ <div class="ml-auto">+ <ArcaneButton action="refresh" size="sm" disabled={processesQuery.isFetching} onclick={() => processesQuery.refetch()} />+ </div>+ {/if}+ </Card.Header>+ {#if !canFetch}+ <EmptyState icon={LayoutListIcon} title={m.common_unavailable()} description={m.containers_processes_unavailable()} />+ {:else if processesQuery.isError}+ <EmptyState+ icon={LayoutListIcon}+ title={m.common_load_failed({ resource: m.containers_processes_title() })}+ description={extractApiErrorMessage(processesQuery.error)}+ actionLabel={m.common_retry()}+ onAction={() => processesQuery.refetch()}+ />+ {:else if processesQuery.isPending}+ <div class="flex items-center justify-center gap-2 py-12 text-sm text-muted-foreground" role="status" aria-live="polite">+ <Spinner tone="muted" />+ <span>{m.common_loading()}</span>+ </div>+ {:else if processes.length === 0}+ <EmptyState icon={LayoutListIcon} title={m.containers_processes_empty()} />+ {:else}+ <div class="overflow-x-auto rounded-b-lg">+ <Table.Root aria-label={m.containers_processes_title()}>+ <Table.Header>+ <Table.Row>+ {#each titles as title}+ <Table.Head scope="col">{title}</Table.Head>+ {/each}+ </Table.Row>+ </Table.Header>+ <Table.Body>+ {#each processes as cells (pidIndex >= 0 ? cells[pidIndex] : cells)}+ <Table.Row>+ {#each cells as cell}+ <Table.Cell class="font-mono text-xs">{cell}</Table.Cell>+ {/each}+ </Table.Row>+ {/each}+ </Table.Body>+ </Table.Root>+ </div>+ {/if}+</Card.Root>diff --git a/types/container/container.go b/types/container/container.goindex d8597cb09..23976928a 100644--- a/types/container/container.go+++ b/types/container/container.go@@ -1866,3 +1866,16 @@ func mapEditNetworks(c *container.InspectResponse) map[string]EditConfigNetworkreturn out}++// Processes is the process snapshot Docker reports for a running container.+type Processes struct {+ // Titles are the column headers Docker returned, in order.+ //+ // Required: true+ Titles []string `json:"titles"`++ // Processes are the rows Docker returned; each row is positional to Titles.+ //+ // Required: true+ Processes [][]string `json:"processes"`+}