Skip to content

Modern Docker Management, Designed for Everyone

feat: add container logs

Kyle Mendell213dc2f8bdef
diff --git a/src/lib/services/docker-service.ts b/src/lib/services/docker-service.ts
index a87ddb174..308ada5b7 100644
--- a/src/lib/services/docker-service.ts
+++ b/src/lib/services/docker-service.ts
@@ -143,6 +143,151 @@ export async function getContainer(containerId: string) {
}
}
+/**
+ * Starts a specific container.
+ * @param containerId - The ID of the container.
+ */
+export async function startContainer(containerId: string): Promise<void> {
+ try {
+ const container = defaultDocker.getContainer(containerId);
+ await container.start();
+ } catch (error: any) {
+ console.error(`Error starting container ${containerId}:`, error);
+ // Provide more context if possible (e.g., container already started)
+ throw new Error(
+ `Failed to start container ${containerId}. ${error.message || ""}`
+ );
+ }
+}
+
+/**
+ * Stops a specific container.
+ * @param containerId - The ID of the container.
+ */
+export async function stopContainer(containerId: string): Promise<void> {
+ try {
+ const container = defaultDocker.getContainer(containerId);
+ await container.stop();
+ } catch (error: any) {
+ console.error(`Error stopping container ${containerId}:`, error);
+ // Provide more context (e.g., container not running)
+ throw new Error(
+ `Failed to stop container ${containerId}. ${error.message || ""}`
+ );
+ }
+}
+
+/**
+ * Restarts a specific container.
+ * @param containerId - The ID of the container.
+ */
+export async function restartContainer(containerId: string): Promise<void> {
+ try {
+ const container = defaultDocker.getContainer(containerId);
+ await container.restart();
+ } catch (error: any) {
+ console.error(`Error restarting container ${containerId}:`, error);
+ throw new Error(
+ `Failed to restart container ${containerId}. ${error.message || ""}`
+ );
+ }
+}
+
+/**
+ * Removes a specific container.
+ * @param containerId - The ID of the container.
+ * @param force - Force removal even if running (default: false).
+ */
+export async function removeContainer(
+ containerId: string,
+ force = false
+): Promise<void> {
+ try {
+ const container = defaultDocker.getContainer(containerId);
+ await container.remove({ force });
+ } catch (error: any) {
+ console.error(`Error removing container ${containerId}:`, error);
+ // Provide more context (e.g., conflict, container not found)
+ if (error.statusCode === 404) {
+ throw new Error(`Container ${containerId} not found.`);
+ }
+ if (error.statusCode === 409) {
+ throw new Error(
+ `Cannot remove running container ${containerId}. Stop it first or use force.`
+ );
+ }
+ throw new Error(
+ `Failed to remove container ${containerId}. ${error.message || ""}`
+ );
+ }
+}
+
+/**
+ * Gets logs for a specific container.
+ * @param containerId - The ID of the container.
+ * @param options - Optional parameters for log retrieval
+ */
+export async function getContainerLogs(
+ containerId: string,
+ options: {
+ tail?: number | "all"; // Number of lines to show from the end of logs (use undefined for all logs)
+ since?: number; // Timestamp (in seconds) to filter logs since
+ until?: number; // Timestamp (in seconds) to filter logs until
+ follow?: boolean; // Stream logs (not typically used in SSR)
+ stdout?: boolean; // Include stdout
+ stderr?: boolean; // Include stderr
+ } = {}
+): Promise<string> {
+ try {
+ const container = defaultDocker.getContainer(containerId);
+
+ // Set default options if not provided
+ const logOptions = {
+ tail: options.tail === "all" ? undefined : options.tail || 100, // Default to last 100 lines, undefined for 'all'
+ stdout: options.stdout !== false, // Include stdout by default
+ stderr: options.stderr !== false, // Include stderr by default
+ follow: false, // Don't stream by default (won't work well with SSR)
+ timestamps: true, // Include timestamps
+ since: options.since || 0, // Get all logs by default
+ until: options.until || undefined,
+ };
+
+ // Get the logs as a Buffer
+ const logsBuffer = await container.logs(logOptions);
+
+ // Convert the Buffer to a string and handle the format
+ let logString = logsBuffer.toString();
+
+ // Process the log string to handle Docker log format
+ // Docker prefixes each line with 8 bytes: first byte is 01 (stdout) or 02 (stderr),
+ // followed by 3 bytes of 0s, then 4 bytes for the size
+ if (logOptions.stdout || logOptions.stderr) {
+ // This is a simple approach - split by lines and remove Docker headers
+ const lines = logString.split("\n");
+ const processedLines = lines
+ .map((line) => {
+ // Skip empty lines
+ if (!line) return "";
+ // Remove the 8-byte header if present (check line length)
+ if (line.length > 8) {
+ return line.substring(8);
+ }
+ return line;
+ })
+ .filter(Boolean); // Remove empty lines
+
+ logString = processedLines.join("\n");
+ }
+
+ return logString;
+ } catch (error: any) {
+ console.error(`Error getting logs for container ${containerId}:`, error);
+ throw new Error(
+ `Failed to get logs for container ${containerId}. ${error.message || ""}`
+ );
+ }
+}
+
// Define and export the type returned by listImages
export type ServiceImage = {
id: string;
diff --git a/src/routes/containers/[id]/+page.server.ts b/src/routes/containers/[id]/+page.server.ts
index d7b97acb7..81c379700 100644
--- a/src/routes/containers/[id]/+page.server.ts
+++ b/src/routes/containers/[id]/+page.server.ts
@@ -1,12 +1,28 @@
-import type { PageServerLoad } from "./$types";
-import { getContainer } from "$lib/services/docker-service";
-import { error } from "@sveltejs/kit";
+import type { PageServerLoad, Actions } from "./$types";
+import {
+ getContainer,
+ startContainer,
+ stopContainer,
+ restartContainer,
+ removeContainer,
+ getContainerLogs, // Add this import
+} from "$lib/services/docker-service";
+import { error, fail, redirect } from "@sveltejs/kit";
+import { invalidateAll } from "$app/navigation"; // Used client-side, but good practice to know
export const load: PageServerLoad = async ({ params }) => {
const containerId = params.id;
try {
- const container = await getContainer(containerId);
+ // Fetch container details and logs concurrently for better performance
+ const [container, logs] = await Promise.all([
+ getContainer(containerId),
+ getContainerLogs(containerId, { tail: 100 }).catch((err) => {
+ // Handle log retrieval errors gracefully
+ 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.";
+ }),
+ ]);
if (!container) {
error(404, {
@@ -16,12 +32,60 @@ export const load: PageServerLoad = async ({ params }) => {
return {
container,
+ logs,
};
} catch (err: any) {
console.error(`Failed to load container ${containerId}:`, err);
+ // Use the error helper for consistency
error(500, {
message:
err.message || `Failed to load container details for "${containerId}".`,
});
}
};
+
+// Define Form Actions
+export const actions: Actions = {
+ start: async ({ params }) => {
+ const containerId = params.id;
+ try {
+ await startContainer(containerId);
+ // No redirect needed, page data will refresh via invalidateAll on client
+ return { success: true, message: "Container started." };
+ } catch (err: any) {
+ return fail(500, { error: err.message });
+ }
+ },
+ stop: async ({ params }) => {
+ const containerId = params.id;
+ try {
+ await stopContainer(containerId);
+ return { success: true, message: "Container stopped." };
+ } catch (err: any) {
+ return fail(500, { error: err.message });
+ }
+ },
+ restart: async ({ params }) => {
+ const containerId = params.id;
+ try {
+ await restartContainer(containerId);
+ return { success: true, message: "Container restarted." };
+ } catch (err: any) {
+ return fail(500, { error: err.message });
+ }
+ },
+ remove: async ({ params }) => {
+ const containerId = params.id;
+ try {
+ // 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
+ redirect(303, "/containers");
+ // Note: Redirect prevents returning a success message directly here
+ } catch (err: any) {
+ return fail(500, { error: err.message });
+ }
+ },
+};
diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelte
index 38106c94c..890448f32 100644
--- a/src/routes/containers/[id]/+page.svelte
+++ b/src/routes/containers/[id]/+page.svelte
@@ -1,13 +1,22 @@
<script lang="ts">
- import type { PageData } from "./$types";
+ 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 StatusBadge from "$lib/components/docker/StatusBadge.svelte";
- import { ArrowLeft } from "@lucide/svelte";
+ import { ArrowLeft, Loader2, AlertCircle, RefreshCw } from "@lucide/svelte";
import * as Breadcrumb from "$lib/components/ui/breadcrumb/index.js";
+ import { enhance } from "$app/forms";
+ import { invalidateAll } from "$app/navigation";
+ import * as Alert from "$lib/components/ui/alert/index.js";
+ import { Separator } from "$lib/components/ui/separator/index.js";
- let { data }: { data: PageData } = $props();
- const { container } = data;
+ let { data, form }: { data: PageData; form: ActionData } = $props();
+ let { container, logs } = $derived(data);
+
+ let starting = $state(false);
+ let stopping = $state(false);
+ let restarting = $state(false);
+ let removing = $state(false);
function formatDate(dateString: string | undefined | null): string {
if (!dateString) return "Unknown";
@@ -17,154 +26,343 @@
return "Invalid Date";
}
}
+
+ // Function to format logs with some basic highlighting
+ function formatLogLine(line: string): string {
+ if (
+ line.includes("ERROR") ||
+ line.includes("FATAL") ||
+ line.includes("WARN")
+ ) {
+ return `<span class="text-red-400">${line}</span>`;
+ }
+ if (line.includes("INFO")) {
+ return `<span class="text-blue-400">${line}</span>`;
+ }
+ return line;
+ }
+
+ // Format all logs
+ let formattedLogs = $derived(
+ logs ? logs.split("\n").map(formatLogLine).join("\n") : ""
+ );
+
+ // Set up auto-scroll for logs
+ let logsContainer = $state<HTMLDivElement | undefined>(undefined);
+
+ $effect(() => {
+ starting = false;
+ stopping = false;
+ restarting = false;
+ removing = false;
+ });
+
+ $effect(() => {
+ // Scroll to bottom whenever logs change
+ if (logsContainer && logs) {
+ logsContainer.scrollTop = logsContainer.scrollHeight;
+ }
+ });
</script>
-<div
- class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4"
->
- <Breadcrumb.Root>
- <Breadcrumb.List>
- <Breadcrumb.Item>
- <Breadcrumb.Link href="/">Dashboard</Breadcrumb.Link>
- </Breadcrumb.Item>
- <Breadcrumb.Separator />
- <Breadcrumb.Item>
- <Breadcrumb.Link href="/containers">Containers</Breadcrumb.Link>
- </Breadcrumb.Item>
- <Breadcrumb.Separator />
- <Breadcrumb.Item>
- <Breadcrumb.Page>{container.name}</Breadcrumb.Page>
- </Breadcrumb.Item>
- </Breadcrumb.List>
- </Breadcrumb.Root>
+<div class="container mx-auto pb-8">
+ <!-- Breadcrumb Navigation -->
+ <div
+ class="flex flex-col sm:flex-row justify-between items-start sm:items-center mt-4 mb-6 gap-4"
+ >
+ <Breadcrumb.Root>
+ <Breadcrumb.List>
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/">Dashboard</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/containers">Containers</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Page>{container?.name || "Loading..."}</Breadcrumb.Page>
+ </Breadcrumb.Item>
+ </Breadcrumb.List>
+ </Breadcrumb.Root>
+
+ {#if container}
+ <div class="flex gap-2 flex-wrap">
+ {#if container.state?.Running}
+ <form
+ method="POST"
+ action="?/stop"
+ use:enhance={() => {
+ stopping = true;
+ return async ({ update }) => {
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ variant="secondary"
+ disabled={stopping}
+ size="sm"
+ class="font-medium"
+ >
+ {#if stopping}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {/if}
+ Stop
+ </Button>
+ </form>
+ <form
+ method="POST"
+ action="?/restart"
+ use:enhance={() => {
+ restarting = true;
+ return async ({ update }) => {
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ variant="secondary"
+ disabled={restarting}
+ size="sm"
+ class="font-medium"
+ >
+ {#if restarting}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {/if}
+ Restart
+ </Button>
+ </form>
+ {:else if container.state?.Status === "exited" || container.state?.Status === "created"}
+ <form
+ method="POST"
+ action="?/start"
+ use:enhance={() => {
+ starting = true;
+ return async ({ update }) => {
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ variant="default"
+ disabled={starting}
+ size="sm"
+ class="font-medium"
+ >
+ {#if starting}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {/if}
+ Start
+ </Button>
+ </form>
+ {/if}
+ <form
+ method="POST"
+ action="?/remove"
+ use:enhance={() => {
+ if (
+ !confirm(
+ `Are you sure you want to remove container "${container?.name}"?`
+ )
+ ) {
+ return;
+ }
+ removing = true;
+ return async ({ update }) => {
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ variant="destructive"
+ disabled={removing}
+ size="sm"
+ class="font-medium"
+ >
+ {#if removing}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {/if}
+ Remove
+ </Button>
+ </form>
+ </div>
+ {/if}
+ </div>
+
+ <!-- Error Alert -->
+ {#if form?.error}
+ <Alert.Root variant="destructive" class="mb-6">
+ <AlertCircle class="h-4 w-4 mr-2" />
+ <Alert.Title>Action Failed</Alert.Title>
+ <Alert.Description>{form.error}</Alert.Description>
+ </Alert.Root>
+ {/if}
{#if container}
- <div class="flex gap-2 flex-wrap">
- {#if container.state?.Running}
- <Button variant="secondary">Stop</Button>
- <Button variant="secondary">Restart</Button>
- {:else if container.state?.Status === "exited" || container.state?.Status === "created"}
- <Button variant="default">Start</Button>
- {/if}
- <Button variant="destructive">Remove</Button>
+ <!-- Container Details Section -->
+ <div class="mb-6">
+ <h2 class="text-xl font-bold mb-4">Container Details</h2>
+ <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="pb-2 bg-muted/40">
+ <Card.Title class="text-sm font-medium">State</Card.Title>
+ </Card.Header>
+ <Card.Content class="pt-4">
+ <StatusBadge state={container.state?.Status ?? "unknown"} />
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="pb-2 bg-muted/40">
+ <Card.Title class="text-sm font-medium">Image</Card.Title>
+ </Card.Header>
+ <Card.Content class="pt-4 text-sm font-medium break-all">
+ <div class="truncate" title={container.config?.Image || "N/A"}>
+ {container.config?.Image || "N/A"}
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="pb-2 bg-muted/40">
+ <Card.Title class="text-sm font-medium">Created</Card.Title>
+ </Card.Header>
+ <Card.Content class="pt-4 text-sm font-medium">
+ {formatDate(container.created)}
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root class="overflow-hidden">
+ <Card.Header class="pb-2 bg-muted/40">
+ <Card.Title class="text-sm font-medium">IP Address</Card.Title>
+ </Card.Header>
+ <Card.Content class="pt-4 text-sm font-medium">
+ {container.networkSettings?.IPAddress || "N/A"}
+ </Card.Content>
+ </Card.Root>
+ </div>
</div>
- {/if}
-</div>
-{#if container}
- <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4 mb-6">
- <Card.Root>
- <Card.Header class="pb-2">
- <Card.Title class="text-sm font-medium text-muted-foreground"
- >State</Card.Title
- >
- </Card.Header>
- <Card.Content>
- <StatusBadge state={container.state?.Status || "unknown"} />
- </Card.Content>
- </Card.Root>
-
- <Card.Root>
- <Card.Header class="pb-2">
- <Card.Title class="text-sm font-medium text-muted-foreground"
- >Image</Card.Title
- >
- </Card.Header>
- <Card.Content class="text-sm font-medium break-all">
- {container.config?.Image || "N/A"}
- </Card.Content>
- </Card.Root>
-
- <Card.Root>
- <Card.Header class="pb-2">
- <Card.Title class="text-sm font-medium text-muted-foreground"
- >Created</Card.Title
- >
- </Card.Header>
- <Card.Content class="text-sm font-medium">
- {formatDate(container.created)}
- </Card.Content>
- </Card.Root>
-
- <Card.Root>
- <Card.Header class="pb-2">
- <Card.Title class="text-sm font-medium text-muted-foreground"
- >IP Address</Card.Title
- >
- </Card.Header>
- <Card.Content class="text-sm font-medium">
- {container.networkSettings?.IPAddress || "N/A"}
- </Card.Content>
- </Card.Root>
- </div>
+ <Separator class="my-6" />
- <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
- <Card.Root class="lg:col-span-8">
- <Card.Header>
- <Card.Title>Logs</Card.Title>
- <Card.Description>Recent container output</Card.Description>
- </Card.Header>
- <Card.Content>
- <div
- class="bg-muted text-muted-foreground p-4 rounded font-mono text-xs h-64 overflow-y-auto"
- >
- <p>Log fetching not implemented yet.</p>
- </div>
- </Card.Content>
- <Card.Footer>
- <Button
- variant="link"
- class="p-0 h-auto"
- href="/containers/{container.id}/logs"
- >
- View full logs
- </Button>
- </Card.Footer>
- </Card.Root>
-
- <Card.Root class="lg:col-span-4">
- <Card.Header>
- <Card.Title>Stats</Card.Title>
- <Card.Description>Resource usage</Card.Description>
- </Card.Header>
- <Card.Content>
- <p class="text-sm text-muted-foreground">
- Stats fetching not implemented yet.
- </p>
- <ul>
- <li class="mb-2">
- <div class="text-muted-foreground text-sm">CPU</div>
- <div class="w-full bg-secondary rounded-full h-2.5 mt-1">
- <div
- class="bg-primary h-2.5 rounded-full"
- style="width: 0%"
- ></div>
+ <!-- Logs and Stats Section -->
+ <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">
+ <!-- Logs Card -->
+ <Card.Root class="lg:col-span-8 border shadow-sm">
+ <Card.Header>
+ <div
+ class="flex flex-col sm:flex-row justify-between items-start sm:items-center w-full gap-4"
+ >
+ <div>
+ <Card.Title class="text-lg font-semibold"
+ >Container Logs</Card.Title
+ >
+ <Card.Description
+ >Recent output from the container</Card.Description
+ >
</div>
- </li>
- <li class="mb-2">
- <div class="text-muted-foreground text-sm">Memory</div>
- <div class="w-full bg-secondary rounded-full h-2.5 mt-1">
- <div
- class="bg-primary h-2.5 rounded-full"
- style="width: 0%"
- ></div>
+ </div>
+ </Card.Header>
+
+ <Card.Content>
+ <div
+ class="bg-muted/50 text-foreground p-4 rounded-md font-mono text-xs h-80 overflow-y-auto whitespace-pre-wrap border"
+ bind:this={logsContainer}
+ id="logs-container"
+ >
+ {#if logs}
+ {@html formattedLogs}
+ {:else}
+ <p class="text-muted-foreground italic">
+ No logs available. The container may not have started yet.
+ </p>
+ {/if}
+ </div>
+ </Card.Content>
+
+ <Card.Footer class="flex justify-between border-t pt-4">
+ <Button
+ variant="outline"
+ size="sm"
+ href="/containers/{container.id}/logs"
+ class="text-xs"
+ >
+ View full logs
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ onclick={() => invalidateAll()}
+ class="text-xs"
+ >
+ <RefreshCw class="w-3.5 h-3.5 mr-1" /> Refresh
+ </Button>
+ </Card.Footer>
+ </Card.Root>
+
+ <!-- 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>
+ </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>
+ </div>
</div>
- </li>
- </ul>
- </Card.Content>
- <Card.Footer>
- <Button
- variant="link"
- class="p-0 h-auto"
- href="/containers/{container.id}/stats"
- >
- View detailed stats
- </Button>
- </Card.Footer>
- </Card.Root>
- </div>
-{:else}
- <p class="text-center text-muted-foreground">
- Could not load container data.
- </p>
-{/if}
+
+ <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>
+ </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="pt-2 text-xs italic text-muted-foreground">
+ Stats fetching not implemented yet.
+ </div>
+ </div>
+ </Card.Content>
+
+ <Card.Footer class="border-t pt-4">
+ <Button
+ variant="outline"
+ size="sm"
+ href="/containers/{container.id}/stats"
+ class="w-full text-xs"
+ >
+ View detailed stats
+ </Button>
+ </Card.Footer>
+ </Card.Root>
+ </div>
+ {:else}
+ <div class="flex items-center justify-center h-48 border rounded-lg">
+ <p class="text-center text-muted-foreground">
+ Could not load container data.
+ </p>
+ </div>
+ {/if}
+</div>