Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: pull/remove images (#33)
Kyle Mendell5cf58833fb7f
diff --git a/src/lib/services/docker-service.ts b/src/lib/services/docker-service.tsindex 2f329431e..51b9f8927 100644--- a/src/lib/services/docker-service.ts+++ b/src/lib/services/docker-service.ts@@ -429,6 +429,35 @@ export async function listImages(): Promise<ServiceImage[]> {}}+/**+ * Removes a Docker image.+ * @param imageId - The ID or name of the image to remove.+ * @param force - Whether to force removal (default: false).+ */+export async function removeImage(+ imageId: string,+ force: boolean = false+): Promise<void> {+ try {+ const docker = getDockerClient();+ const image = docker.getImage(imageId);+ await image.remove({ force });+ console.log(`Docker Service: Image "${imageId}" removed successfully.`);+ } catch (error: any) {+ console.error(`Docker Service: Error removing image "${imageId}":`, error);+ if (error.statusCode === 409) {+ throw new Error(+ `Image "${imageId}" is being used by a container. Use force option to remove.`+ );+ }+ throw new Error(+ `Failed to remove image "${imageId}" using host "${dockerHost}". ${+ error.message || error.reason || ""+ }`+ );+ }+}+// Define and export the type returned by listNetworksexport type ServiceNetwork = {id: string;@@ -570,4 +599,54 @@ export async function removeVolume(}}+/**+ * Pulls a Docker image from a registry.+ * @param imageRef - The image reference to pull (e.g., 'nginx:latest')+ * @param platform - Optional platform specification (e.g., 'linux/amd64')+ */+export async function pullImage(+ imageRef: string,+ platform?: string+): Promise<void> {+ try {+ const docker = getDockerClient();++ const pullOptions: any = {};+ if (platform) {+ pullOptions.platform = platform;+ }++ console.log(`Docker Service: Pulling image "${imageRef}"...`);++ // Pull the image - this returns a stream+ const stream = await docker.pull(imageRef, pullOptions);++ // Wait for the pull to complete by consuming the stream+ await new Promise((resolve, reject) => {+ docker.modem.followProgress(stream, (err: any, output: any) => {+ if (err) {+ reject(err);+ } else {+ resolve(output);+ }+ });+ });++ console.log(`Docker Service: Image "${imageRef}" pulled successfully.`);+ } catch (error: any) {+ console.error(`Docker Service: Error pulling image "${imageRef}":`, error);++ // Handle specific error cases+ if (error.statusCode === 404) {+ throw new Error(`Image "${imageRef}" not found in registry.`);+ }++ throw new Error(+ `Failed to pull image "${imageRef}". ${+ error.message || error.reason || ""+ }`+ );+ }+}+export default getDockerClient;diff --git a/src/routes/api/images/[id]/+server.ts b/src/routes/api/images/[id]/+server.tsnew file mode 100644index 000000000..f2e34dc93--- /dev/null+++ b/src/routes/api/images/[id]/+server.ts@@ -0,0 +1,19 @@+import { json } from "@sveltejs/kit";+import type { RequestHandler } from "./$types";+import { removeImage } from "$lib/services/docker-service";++export const DELETE: RequestHandler = async ({ params, url }) => {+ const { id } = params;+ const force = url.searchParams.get("force") === "true";++ try {+ await removeImage(id, force);+ return json({ success: true });+ } catch (error: any) {+ console.error("API Error removing image:", error);+ return json(+ { error: `Failed to remove image: ${error.message || "Unknown error"}` },+ { status: 500 }+ );+ }+};diff --git a/src/routes/api/images/pull-stream/[...name]/+server.ts b/src/routes/api/images/pull-stream/[...name]/+server.tsnew file mode 100644index 000000000..f7abf31c9--- /dev/null+++ b/src/routes/api/images/pull-stream/[...name]/+server.ts@@ -0,0 +1,92 @@+import type { RequestHandler } from "./$types";+import { getDockerClient } from "$lib/services/docker-service";++export const GET: RequestHandler = async ({ params, request }) => {+ const imageRef = params.name;++ // Set up SSE headers+ const headers = new Headers({+ "Content-Type": "text/event-stream",+ "Cache-Control": "no-cache",+ Connection: "keep-alive",+ });++ const stream = new ReadableStream({+ async start(controller) {+ try {+ const docker = getDockerClient();++ function send(data: any) {+ controller.enqueue(+ new TextEncoder().encode(`data: ${JSON.stringify(data)}\n\n`)+ );+ }++ const pullStream = await docker.pull(imageRef);++ let layers: Record<string, any> = {};+ let totalProgress = 0;++ docker.modem.followProgress(+ pullStream,+ (err: Error | null, output: any[]) => {+ // Pull complete+ if (err) {+ send({ error: err.message });+ } else {+ send({ complete: true, progress: 100 });+ }+ controller.close();+ },+ (event: any) => {+ if (event.id && event.status) {+ if (!layers[event.id]) {+ layers[event.id] = { current: 0, total: 0 };+ }++ if (+ event.progressDetail &&+ event.progressDetail.current &&+ event.progressDetail.total+ ) {+ layers[event.id].current = event.progressDetail.current;+ layers[event.id].total = event.progressDetail.total;+ }++ let totalSize = 0;+ let currentProgress = 0;++ Object.values(layers).forEach((layer: any) => {+ if (layer.total > 0) {+ totalSize += layer.total;+ currentProgress += layer.current;+ }+ });++ if (totalSize > 0) {+ totalProgress = Math.min(+ 99,+ Math.floor((currentProgress / totalSize) * 100)+ );+ send({ progress: totalProgress, status: event.status });+ } else {+ send({ progress: 5, status: event.status });+ }+ }+ }+ );+ } catch (error: any) {+ controller.enqueue(+ new TextEncoder().encode(+ `data: ${JSON.stringify({+ error: error.message || "Unknown error pulling image",+ })}\n\n`+ )+ );+ controller.close();+ }+ },+ });++ return new Response(stream, { headers });+};diff --git a/src/routes/api/images/pull/[...name]/+server.ts b/src/routes/api/images/pull/[...name]/+server.tsnew file mode 100644index 000000000..a6cccc0d0--- /dev/null+++ b/src/routes/api/images/pull/[...name]/+server.ts@@ -0,0 +1,36 @@+import { json } from "@sveltejs/kit";+import type { RequestHandler } from "@sveltejs/kit";+import { pullImage } from "$lib/services/docker-service";++export const POST: RequestHandler = async ({ params, request }) => {+ try {+ const fullPath = params.name;++ if (!fullPath) {+ return json({ error: "Image reference is required." }, { status: 400 });+ }++ const body = await request.json();+ const platform = body?.platform;+ const tag = body?.tag || "latest";++ let imageRef = fullPath.includes(":") ? fullPath : `${fullPath}:${tag}`;++ console.log(`API: Pulling image "${imageRef}"...`);+ await pullImage(imageRef, platform);++ return json(+ {+ success: true,+ message: `Image "${imageRef}" pulled successfully.`,+ },+ { status: 200 }+ );+ } catch (error: any) {+ console.error("API Error pulling image:", error);+ return json(+ { error: `Failed to pull image: ${error.message || "Unknown error"}` },+ { status: 500 }+ );+ }+};diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelteindex b6440983d..9755838aa 100644--- a/src/routes/images/+page.svelte+++ b/src/routes/images/+page.svelte@@ -15,23 +15,76 @@import * as Card from "$lib/components/ui/card/index.js";import { Badge } from "$lib/components/ui/badge/index.js";import { invalidateAll } from "$app/navigation";+ import { toast } from "svelte-sonner";+ import PullImageDialog from "./pull-image-dialog.svelte";let { data }: { data: PageData } = $props();const { images, error } = data;let isRefreshing = $state(false);+ let isPullDialogOpen = $state(false);+ let isPullingImage = $state(false);+ let pullProgress = $state(0);- // Calculate total imagesconst totalImages = $derived(images?.length || 0);- // Calculate total size of all imagesconst totalSize = $derived(images?.reduce((acc, img) => acc + (img.size || 0), 0) || 0);- function pullImage() {- // TODO: Implement pull image modal/logic- alert("Implement pull image functionality");+ async function handlePullImageSubmit(event: {+ imageRef: string;+ tag?: string;+ platform?: string;+ }) {+ const { imageRef, tag = "latest", platform } = event;++ isPullingImage = true;+ let currentPullProgress = $state(0);++ try {+ const encodedImageRef = encodeURIComponent(imageRef);+ const eventSource = new EventSource(+ `/api/images/pull-stream/${encodedImageRef}?tag=${tag}${platform ? `&platform=${platform}` : ""}`+ );++ eventSource.onmessage = (event) => {+ const data = JSON.parse(event.data);++ if (data.error) {+ eventSource.close();+ toast.error(`Pull failed: ${data.error}`);+ isPullingImage = false;+ return;+ }++ if (data.progress !== undefined) {+ console.log("Progress update:", data.progress);+ currentPullProgress = data.progress;+ pullProgress = data.progress;+ }++ if (data.complete) {+ eventSource.close();+ const fullImageRef = `${imageRef}:${tag}`;+ toast.success(`Image "${fullImageRef}" pulled successfully.`);+ isPullDialogOpen = false;++ window.location.href = `${window.location.pathname}?t=${Date.now()}`;+ }+ };++ eventSource.onerror = (err) => {+ console.error("EventSource error:", err);+ eventSource.close();+ toast.error("Connection to server lost while pulling image");+ isPullingImage = false;+ };+ } catch (err: any) {+ console.error("Failed to pull image:", err);+ toast.error(`Failed to pull image: ${err.message}`);+ isPullingImage = false;+ }}async function refreshData() {@@ -42,7 +95,10 @@}, 500);}- // Helper to format bytes+ function openPullDialog() {+ isPullDialogOpen = true;+ }+function formatBytes(bytes: number | undefined | null, decimals = 1): string {if (!bytes || !+bytes) return "0 Bytes";const k = 1024;@@ -72,7 +128,7 @@<RefreshCw class={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />Refresh</Button>- <Button variant="outline" size="sm" onclick={pullImage}>+ <Button variant="outline" size="sm" onclick={openPullDialog}><Download class="w-4 h-4" />Pull Image</Button>@@ -159,11 +215,18 @@<RefreshCw class="h-4 w-4" />Refresh</Button>- <Button variant="outline" size="sm" onclick={pullImage}>+ <Button variant="outline" size="sm" onclick={openPullDialog}><Download class="h-4 w-4" />Pull Image</Button></div></div>{/if}++ <PullImageDialog+ bind:open={isPullDialogOpen}+ isPulling={isPullingImage}+ {pullProgress}+ onSubmit={handlePullImageSubmit}+ /></div>diff --git a/src/routes/images/ImageActions.svelte b/src/routes/images/ImageActions.svelteindex 0f353d092..b2b68269f 100644--- a/src/routes/images/ImageActions.svelte+++ b/src/routes/images/ImageActions.svelte@@ -1,16 +1,83 @@<script lang="ts">- import Ellipsis from "@lucide/svelte/icons/ellipsis";import { Button } from "$lib/components/ui/button/index.js";+ import * as Dialog from "$lib/components/ui/dialog/index.js";import * as DropdownMenu from "$lib/components/ui/dropdown-menu/index.js";- import { Trash2 } from "@lucide/svelte"; // Import Trash icon+ import { Trash2, Download, Ellipsis, Loader2 } from "@lucide/svelte";+ import { toast } from "svelte-sonner";- // Accept image ID and potentially other relevant infolet { id, repoTag }: { id: string; repoTag?: string } = $props();+ let isPulling = $state(false);+ let isDeleting = $state(false);+ let isConfirmDialogOpen = $state(false);- function removeImage() {- // TODO: Implement API call to remove image- console.log("Attempting to remove image:", id, repoTag);- alert(`Implement remove action for image ID: ${id.substring(0, 12)}`);+ async function removeImage() {+ isDeleting = true;+ try {+ const response = await fetch(`/api/images/${encodeURIComponent(id)}`, {+ method: "DELETE",+ });++ const result = await response.json();++ if (!response.ok) {+ throw new Error(+ result.error || `HTTP error! status: ${response.status}`+ );+ }++ toast.success(+ `Image ${repoTag || id.substring(0, 12)} deleted successfully.`+ );+ isConfirmDialogOpen = false;++ window.location.href = `${window.location.pathname}?t=${Date.now()}`;+ } catch (err: any) {+ console.error(`Failed to delete image:`, err);+ toast.error(`Failed to delete image: ${err.message}`);+ } finally {+ isDeleting = false;+ }+ }++ async function pullImage() {+ if (!repoTag) {+ toast.error("Cannot pull image without a repository tag");+ return;+ }++ isPulling = true;+ try {+ let [imageRef, tag] = repoTag.split(":");+ tag = tag || "latest";++ const encodedImageRef = encodeURIComponent(imageRef);++ const response = await fetch(`/api/images/pull/${encodedImageRef}`, {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ tag,+ }),+ });++ if (!response.ok) {+ const result = await response.json();+ throw new Error(+ result.error || `HTTP error! status: ${response.status}`+ );+ }++ toast.success(`Image "${repoTag}" pulled successfully.`);++ window.location.href = `${window.location.pathname}?t=${Date.now()}`;+ } catch (err: any) {+ console.error(`Failed to pull image "${repoTag}":`, err);+ toast.error(`Failed to pull image: ${err.message}`);+ } finally {+ isPulling = false;+ }}</script>@@ -30,16 +97,51 @@</DropdownMenu.Trigger><DropdownMenu.Content><DropdownMenu.Group>- <DropdownMenu.Label>Actions</DropdownMenu.Label>- <DropdownMenu.Separator />+ <DropdownMenu.Item onclick={pullImage} disabled={isPulling || !repoTag}>+ {#if isPulling}+ <Loader2 class="h-4 w-4 animate-spin" />+ Pulling...+ {:else}+ <Download class="mr-2 h-4 w-4" />+ Pull+ {/if}+ </DropdownMenu.Item><DropdownMenu.Item- onclick={removeImage}- class="text-destructive focus:text-destructive"+ class="text-red-500 focus:!text-red-700"+ onclick={() => (isConfirmDialogOpen = true)}><Trash2 class="mr-2 h-4 w-4" />- Remove Image+ Remove</DropdownMenu.Item>- <!-- Add other actions if needed --></DropdownMenu.Group></DropdownMenu.Content></DropdownMenu.Root>++<Dialog.Root+ open={isConfirmDialogOpen}+ onOpenChange={(open) => (isConfirmDialogOpen = open)}+>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>Confirm Deletion</Dialog.Title>+ <Dialog.Description>+ Are you sure you want to delete the image <span class="font-bold"+ >{repoTag || id.substring(0, 12)}</span+ >? This action cannot be undone.+ </Dialog.Description>+ </Dialog.Header>+ <Dialog.Footer>+ <Button variant="ghost" onclick={() => (isConfirmDialogOpen = false)}>+ Cancel+ </Button>+ <Button variant="destructive" onclick={removeImage} disabled={isDeleting}>+ {#if isDeleting}+ <Loader2 class="h-4 w-4 animate-spin" />+ Deleting...+ {:else}+ Delete+ {/if}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+</Dialog.Root>diff --git a/src/routes/images/columns.ts b/src/routes/images/columns.tsindex 7fa534627..e2e43685e 100644--- a/src/routes/images/columns.ts+++ b/src/routes/images/columns.ts@@ -3,7 +3,6 @@ import type { ColumnDef } from "@tanstack/table-core";import { renderComponent } from "$lib/components/ui/data-table/index.js";import ImageActions from "./ImageActions.svelte";-// Helper to format bytes (keep as is)function formatBytes(bytes: number, decimals = 2): string {if (!+bytes) return "0 Bytes";const k = 1024;@@ -18,9 +17,7 @@ export const columns: ColumnDef<ServiceImage>[] = [accessorKey: "repo",header: "Repository",cell: ({ row }) => {- // Return the plain repository name stringreturn row.original.repo;- // Note: Styling for '<none>' will be lost without a component},},{@@ -29,19 +26,16 @@ export const columns: ColumnDef<ServiceImage>[] = [cell: ({ row }) => {// Return the plain tag stringreturn row.original.tag;- // Note: Styling for '<none>' will be lost without a component},},{accessorKey: "id",header: "Image ID",cell: ({ row }) => {- // Calculate and return the short ID stringconst shortId =row.original.id.split(":")[1]?.substring(0, 12) ||row.original.id.substring(0, 12);return shortId;- // Note: Monospace font styling will be lost without a component},enableSorting: false,},@@ -49,7 +43,6 @@ export const columns: ColumnDef<ServiceImage>[] = [accessorKey: "size",header: "Size",cell: ({ row }) => {- // formatBytes already returns a stringreturn formatBytes(row.original.size);},},@@ -57,7 +50,6 @@ export const columns: ColumnDef<ServiceImage>[] = [id: "actions",header: "Actions",cell: ({ row }) => {- // Keep using renderComponent for the actions dropdownreturn renderComponent(ImageActions, {id: row.original.id,repoTag: row.original.repoTags?.[0],diff --git a/src/routes/images/pull-image-dialog.svelte b/src/routes/images/pull-image-dialog.sveltenew file mode 100644index 000000000..7007ad681--- /dev/null+++ b/src/routes/images/pull-image-dialog.svelte@@ -0,0 +1,213 @@+<script lang="ts">+ import { Button } from "$lib/components/ui/button/index.js";+ import * as Dialog from "$lib/components/ui/dialog/index.js";+ import { Input } from "$lib/components/ui/input/index.js";+ import { Label } from "$lib/components/ui/label/index.js";+ import { Loader2 } from "@lucide/svelte";+ import * as Accordion from "$lib/components/ui/accordion/index.js";+ import * as Select from "$lib/components/ui/select/index.js";++ function preventDefault(handler: (event: SubmitEvent) => void) {+ return (event: SubmitEvent) => {+ event.preventDefault();+ handler(event);+ };+ }++ export function onClose() {+ open = false;+ }++ interface Props {+ open?: boolean;+ isPulling?: boolean;+ pullProgress?: number;+ onSubmit?: any;+ }++ let {+ open = $bindable(false),+ isPulling = false,+ pullProgress = 0,+ onSubmit = (data: {+ imageRef: string;+ tag?: string;+ platform?: string;+ }) => {},+ }: Props = $props();++ let imageRef = $state("");+ let tag = $state("latest");+ let platform = $state("");++ // Available platforms+ const platforms = [+ { label: "Default", value: "" },+ { label: "linux/amd64", value: "linux/amd64" },+ { label: "linux/arm64", value: "linux/arm64" },+ { label: "linux/arm/v7", value: "linux/arm/v7" },+ { label: "windows/amd64", value: "windows/amd64" },+ ];++ function handleSubmit() {+ if (!imageRef.trim()) return;++ let urlPath = imageRef.trim();+ let imageTag = tag || "latest";++ if (urlPath.includes(":")) {+ const parts = urlPath.split(":");+ urlPath = parts[0];+ imageTag = parts[1];+ }++ onSubmit({+ imageRef: urlPath,+ tag: imageTag,+ platform: platform || undefined,+ });+ }+</script>++<Dialog.Root bind:open>+ <Dialog.Content class="sm:max-w-[500px]">+ <Dialog.Header>+ <Dialog.Title>Pull Docker Image</Dialog.Title>+ <Dialog.Description>+ Enter the image reference you want to pull from a registry.+ </Dialog.Description>+ </Dialog.Header>++ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">+ <!-- Basic image settings -->+ <div class="flex flex-col gap-2">+ <Label for="image-ref">Image</Label>+ <div class="flex items-center gap-2">+ <div class="flex-1">+ <Input+ id="image-ref"+ bind:value={imageRef}+ placeholder="e.g., nginx or ubuntu"+ required+ disabled={isPulling}+ />+ </div>+ <div class="flex items-center">+ <span class="text-lg font-medium text-muted-foreground">:</span>+ </div>+ <div class="w-1/3">+ <Input+ id="image-tag"+ bind:value={tag}+ placeholder="latest"+ disabled={isPulling}+ />+ </div>+ </div>+ </div>++ <!-- Advanced settings -->+ <Accordion.Root type="single">+ <Accordion.Item value="advanced">+ <Accordion.Trigger>Advanced Settings</Accordion.Trigger>+ <Accordion.Content>+ <div class="grid gap-4 pt-2">+ <div class="flex flex-col gap-2">+ <Label for="platform">Platform</Label>+ <Select.Root+ type="single"+ bind:value={platform}+ disabled={isPulling}+ >+ <Select.Trigger class="w-full" id="platform">+ <span>+ {platforms.find((p) => p.value === platform)?.label ||+ "Select platform"}+ </span>+ </Select.Trigger>+ <Select.Content>+ {#each platforms as platformOption}+ <Select.Item value={platformOption.value}>+ {platformOption.label}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>++ <p class="text-xs text-muted-foreground mt-1">+ Platform specifies the architecture and OS for+ multi-architecture images. Leave empty to use your system's+ default platform.+ </p>+ </div>+ </div>+ </Accordion.Content>+ </Accordion.Item>+ </Accordion.Root>+ </form>++ {#if isPulling}+ <div class="mt-4">+ <div class="flex justify-between text-xs mb-1">+ <span>Pulling image...</span>+ <span>{Math.round(pullProgress)}%</span>+ </div>+ <div class="w-full bg-secondary h-2 rounded-full overflow-hidden">+ <div+ class="bg-primary h-full transition-all duration-300 ease-in-out"+ style="width: {pullProgress}%"+ ></div>+ </div>+ <p class="text-xs text-muted-foreground mt-1">+ This may take a while depending on the image size and your internet+ connection.+ </p>+ </div>+ {/if}++ <Dialog.Footer>+ <Button variant="outline" onclick={onClose} disabled={isPulling}>+ Cancel+ </Button>+ <Button+ type="submit"+ onclick={handleSubmit}+ disabled={isPulling || !imageRef.trim()}+ class="relative"+ >+ {#if isPulling}+ <div class="absolute inset-0 flex items-center justify-center">+ <svg class="absolute w-full h-full" viewBox="0 0 100 100">+ <circle+ class="text-primary-400/20"+ cx="50"+ cy="50"+ r="45"+ fill="none"+ stroke="currentColor"+ stroke-width="8"+ />+ <circle+ class="text-primary-500"+ cx="50"+ cy="50"+ r="45"+ fill="none"+ stroke="currentColor"+ stroke-width="8"+ stroke-linecap="round"+ stroke-dasharray={283}+ stroke-dashoffset={283 * (1 - pullProgress / 100)}+ transform="rotate(-90 50 50)"+ />+ </svg>+ <Loader2 class="h-4 w-4 animate-spin" />+ </div>+ <span class="opacity-0">Pull Image</span>+ {:else}+ Pull Image+ {/if}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+</Dialog.Root>