Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: add container resource card
Kyle Mendell37ec736c4bb0
diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.tsindex 662600eb3..bb6d93992 100644--- a/src/lib/services/docker/container-service.ts+++ b/src/lib/services/docker/container-service.ts@@ -2,7 +2,8 @@ import { getDockerClient, dockerHost } from './core';import type { ContainerConfig, ContainerCreate } from '$lib/types/docker';import type { ServiceContainer } from '$lib/types/docker/container.type';// Import custom errors-import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors';+import { NotFoundError, ConflictError, DockerApiError, ContainerStateError } from '$lib/types/errors';+import type Docker from 'dockerode';/*** This TypeScript function lists Docker containers and returns an array of ServiceContainer objects.@@ -337,3 +338,61 @@ export async function createContainer(config: ContainerConfig) {throw new Error(`Failed to create container with image "${config.image}": ${error.message}`);}}++/**+ * Retrieves a single snapshot of resource usage statistics for a given container.+ * @param {string} containerId - The ID of the container.+ * @returns {Promise<Docker.ContainerStats | null>} A promise that resolves with the stats object, or null if the container is not running or not found.+ * @throws {NotFoundError} If the container does not exist.+ * @throws {DockerApiError} For other errors during the Docker API interaction.+ */+export async function getContainerStats(containerId: string): Promise<Docker.ContainerStats | null> {+ try {+ const docker = getDockerClient();+ const container = docker.getContainer(containerId);++ // Check if container exists first (inspect is a good way)+ try {+ await container.inspect();+ } catch (inspectError: any) {+ if (inspectError.statusCode === 404) {+ throw new NotFoundError(`Container ${containerId} not found when trying to get stats.`);+ }+ // Rethrow other inspect errors+ throw inspectError;+ }++ // Get a single stats reading+ // Note: This might throw an error or return empty/zero data if the container is not running.+ const stats = await container.stats({ stream: false });++ // The stats stream might return an empty object {} if the container just stopped.+ // Check for essential properties before returning.+ if (!stats || !stats.memory_stats || !stats.cpu_stats) {+ console.warn(`Docker Service: Received incomplete stats for container ${containerId}. It might not be running.`);+ return null;+ }++ return stats as Docker.ContainerStats;+ } catch (error: any) {+ // Handle cases where stats fails because the container isn't running (often a 404 or 500 from Docker API)+ if (error.statusCode === 404) {+ // Could be container not found OR container not running (Docker API might return 404 for stats on stopped container)+ console.warn(`Docker Service: Container ${containerId} not found or not running when fetching stats.`);+ return null; // Return null if not running or not found+ }+ if (error.statusCode === 500 && error.message?.includes('is not running')) {+ console.warn(`Docker Service: Container ${containerId} is not running when fetching stats.`);+ return null; // Return null if not running+ }++ // Handle specific NotFoundError from the inspect check+ if (error instanceof NotFoundError) {+ throw error;+ }++ console.error(`Docker Service: Error getting stats for container ${containerId}:`, error);+ // Throw a DockerApiError for unexpected issues+ throw new DockerApiError(`Failed to get stats for container ${containerId}: ${error.message || 'Unknown Docker error'}`, error.statusCode);+ }+}diff --git a/src/routes/containers/[id]/+page.server.ts b/src/routes/containers/[id]/+page.server.tsindex 52e2e3caa..e587a715f 100644--- a/src/routes/containers/[id]/+page.server.ts+++ b/src/routes/containers/[id]/+page.server.ts@@ -1,16 +1,25 @@import type { PageServerLoad, Actions } from './$types';-import { getContainer, startContainer, stopContainer, restartContainer, removeContainer, getContainerLogs } from '$lib/services/docker/container-service';+// Import getContainerStats+import { getContainer, startContainer, stopContainer, restartContainer, removeContainer, getContainerLogs, getContainerStats } from '$lib/services/docker/container-service';import { error, fail, redirect } from '@sveltejs/kit';+import type Docker from 'dockerode'; // Import Docker type for statsexport const load: PageServerLoad = async ({ params }) => {const containerId = params.id;try {- const [container, logs] = await Promise.all([+ // Fetch container, logs, and stats in parallel+ const [container, logs, stats] = await Promise.all([getContainer(containerId),getContainerLogs(containerId, { tail: 100 }).catch((err) => {console.error(`Failed to retrieve logs for ${containerId}:`, err);- return "Failed to load logs. This could be because the container hasn't been started yet.";+ return 'Failed to load logs. Container might not be running or logs are unavailable.'; // Updated message+ }),+ getContainerStats(containerId).catch((err) => {+ // Fetch stats+ console.error(`Failed to retrieve stats for ${containerId}:`, err);+ // Don't fail the page load for stats errors, just return null+ return null;})]);@@ -22,17 +31,24 @@ export const load: PageServerLoad = async ({ params }) => {return {container,- logs+ logs,+ stats};} catch (err: any) {console.error(`Failed to load container ${containerId}:`, err);- error(500, {- message: err.message || `Failed to load container details for "${containerId}".`- });+ // If the error is NotFoundError from getContainerStats, it should have been caught above.+ // This handles errors from getContainer primarily.+ if (err.name === 'NotFoundError') {+ error(404, { message: err.message });+ } else {+ error(500, {+ message: err.message || `Failed to load container details for "${containerId}".`+ });+ }}};-// Define Form Actions+// Actions remain the sameexport const actions: Actions = {start: async ({ params }) => {const containerId = params.id;@@ -61,18 +77,20 @@ export const actions: Actions = {return fail(500, { error: err.message });}},- remove: async ({ params }) => {+ remove: async ({ params, url }) => {+ // Read 'force' from URLconst containerId = params.id;+ const force = url.searchParams.get('force') === 'true'; // Get force paramtry {- // Consider adding a 'force' option from form data if needed- // const formData = await request.formData();- // const force = formData.get('force') === 'true';- await removeContainer(containerId /*, force */);- // Redirect to the containers list after successful removal+ await removeContainer(containerId, force); // Pass force paramredirect(303, '/containers');- // Note: Redirect prevents returning a success message directly here} catch (err: any) {- return fail(500, { error: err.message });+ // Handle specific errors from removeContainer+ if (err.name === 'NotFoundError' || err.name === 'ConflictError' || err.name === 'DockerApiError') {+ return fail(err.status || 500, { error: err.message });+ }+ // Fallback for unexpected errors+ return fail(500, { error: err.message || 'An unexpected error occurred during removal.' });}}};diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelteindex 4896d0e73..1748b494e 100644--- a/src/routes/containers/[id]/+page.svelte+++ b/src/routes/containers/[id]/+page.svelte@@ -2,7 +2,7 @@import type { PageData, ActionData } from './$types';import * as Card from '$lib/components/ui/card/index.js';import { Button } from '$lib/components/ui/button/index.js';- import { ArrowLeft, AlertCircle, RefreshCw, HardDrive, Clock, Network, Terminal } from '@lucide/svelte';+ import { ArrowLeft, AlertCircle, RefreshCw, HardDrive, Clock, Network, Terminal, Cpu, MemoryStick } from '@lucide/svelte';import * as Breadcrumb from '$lib/components/ui/breadcrumb/index.js';import { enhance } from '$app/forms';import { invalidateAll } from '$app/navigation';@@ -10,10 +10,11 @@import { Separator } from '$lib/components/ui/separator/index.js';import { Badge } from '$lib/components/ui/badge/index.js';import ActionButtons from '$lib/components/action-buttons.svelte';- import { formatDate, formatLogLine } from '$lib/utils';+ import { formatDate, formatLogLine, formatBytes } from '$lib/utils';+ import type Docker from 'dockerode';let { data, form }: { data: PageData; form: ActionData } = $props();- let { container, logs } = $derived(data);+ let { container, logs, stats } = $derived(data);let starting = $state(false);let stopping = $state(false);@@ -23,9 +24,33 @@let formattedLogs = $derived(logs ? logs.split('\n').map(formatLogLine).join('\n') : '');- // Set up auto-scroll for logslet logsContainer = $state<HTMLDivElement | undefined>(undefined);+ // --- Stats Calculation ---+ const calculateCPUPercent = (statsData: Docker.ContainerStats | null): number => {+ if (!statsData || !statsData.cpu_stats || !statsData.precpu_stats) {+ return 0;+ }++ const cpuDelta = statsData.cpu_stats.cpu_usage.total_usage - (statsData.precpu_stats.cpu_usage?.total_usage || 0);+ const systemDelta = statsData.cpu_stats.system_cpu_usage - (statsData.precpu_stats.system_cpu_usage || 0);+ const numberCPUs = statsData.cpu_stats.online_cpus || statsData.cpu_stats.cpu_usage?.percpu_usage?.length || 1;++ if (systemDelta > 0 && cpuDelta > 0) {+ const cpuPercent = (cpuDelta / systemDelta) * numberCPUs * 100.0;+ return Math.min(Math.max(cpuPercent, 0), 100 * numberCPUs);+ }+ return 0;+ };++ const cpuUsagePercent = $derived(calculateCPUPercent(stats));+ const memoryUsageBytes = $derived(stats?.memory_stats?.usage || 0);+ const memoryLimitBytes = $derived(stats?.memory_stats?.limit || 0);+ const memoryUsageFormatted = $derived(formatBytes(memoryUsageBytes));+ const memoryLimitFormatted = $derived(formatBytes(memoryLimitBytes));+ const memoryUsagePercent = $derived(memoryLimitBytes > 0 ? (memoryUsageBytes / memoryLimitBytes) * 100 : 0);+ // --- End Stats Calculation ---+$effect(() => {starting = false;stopping = false;@@ -34,7 +59,6 @@});$effect(() => {- // Scroll to bottom whenever logs changeif (logsContainer && logs) {logsContainer.scrollTop = logsContainer.scrollHeight;}@@ -73,6 +97,11 @@<h1 class="text-2xl font-bold tracking-tight">{container?.name || 'Container Details'}</h1>+ {#if container?.state}+ <Badge variant={container.state.Running ? 'default' : 'destructive'} class="capitalize">+ {container.state.Status}+ </Badge>+ {/if}</div></div>@@ -294,37 +323,59 @@<!-- Stats Card --><Card.Root class="lg:col-span-4 border shadow-sm"><Card.Header>- <Card.Title class="text-lg font-semibold">Resource Usage</Card.Title>- <Card.Description>Container performance metrics</Card.Description>+ <div class="flex justify-between items-center">+ <div>+ <Card.Title class="text-lg font-semibold">Resource Usage</Card.Title>+ <Card.Description>Live container metrics</Card.Description>+ </div>+ <Button variant="ghost" size="icon" onclick={refreshData} disabled={isRefreshing} title="Refresh Stats & Logs">+ <RefreshCw class={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />+ </Button>+ </div></Card.Header><Card.Content>- <div class="space-y-4">- <div>- <div class="flex justify-between mb-1">- <span class="text-sm font-medium">CPU Usage</span>- <span class="text-sm text-muted-foreground">0%</span>- </div>- <div class="w-full bg-secondary rounded-full h-2">- <div class="bg-primary h-2 rounded-full" style="width: 0%"></div>+ {#if stats && container.state?.Running}+ <div class="space-y-4">+ <!-- CPU Usage -->+ <div>+ <div class="flex justify-between items-center mb-1">+ <span class="text-sm font-medium flex items-center gap-2"><Cpu class="h-4 w-4 text-muted-foreground" /> CPU Usage</span>+ <span class="text-sm font-semibold">{cpuUsagePercent.toFixed(2)}%</span>+ </div>+ <div class="w-full bg-secondary rounded-full h-2 overflow-hidden">+ <div class="bg-primary h-2 rounded-full transition-all duration-300" style="width: {Math.min(cpuUsagePercent, 100)}%"></div>+ </div></div>- </div>- <div>- <div class="flex justify-between mb-1">- <span class="text-sm font-medium">Memory Usage</span>- <span class="text-sm text-muted-foreground">0 / 0 MB</span>+ <!-- Memory Usage -->+ <div>+ <div class="flex justify-between items-center mb-1">+ <span class="text-sm font-medium flex items-center gap-2"><MemoryStick class="h-4 w-4 text-muted-foreground" /> Memory Usage</span>+ <span class="text-sm font-semibold">{memoryUsageFormatted} / {memoryLimitFormatted}</span>+ </div>+ <div class="w-full bg-secondary rounded-full h-2 overflow-hidden">+ <div class="bg-primary h-2 rounded-full transition-all duration-300" style="width: {memoryUsagePercent.toFixed(2)}%"></div>+ </div></div>- <div class="w-full bg-secondary rounded-full h-2">- <div class="bg-primary h-2 rounded-full" style="width: 0%"></div>- </div>- </div>- <div class="bg-muted/50 p-4 rounded-md text-center mt-4">- <p class="text-sm text-muted-foreground mb-2">Stats fetching not implemented yet.</p>- <Button variant="outline" size="sm" href="/containers/{container.id}/stats" class="text-sm w-full">View detailed stats</Button>+ <!-- Network I/O -->+ <div class="text-xs text-muted-foreground space-y-1 pt-2 border-t">+ <div class="flex justify-between">+ <span>Network RX:</span>+ <span>{formatBytes(stats.networks?.eth0?.rx_bytes || 0)}</span>+ </div>+ <div class="flex justify-between">+ <span>Network TX:</span>+ <span>{formatBytes(stats.networks?.eth0?.tx_bytes || 0)}</span>+ </div>+ </div></div>- </div>+ {:else if !container.state?.Running}+ <div class="text-center text-sm text-muted-foreground italic py-8">Container is not running. Stats unavailable.</div>+ {:else}+ <div class="text-center text-sm text-muted-foreground italic py-8">Could not load stats.</div>+ {/if}</Card.Content></Card.Root></div>