Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat(volumes): create and delete volumes (#29)
Kyle Mendell6054fc8abc89
diff --git a/src/lib/components/ui/accordion/accordion-content.svelte b/src/lib/components/ui/accordion/accordion-content.sveltenew file mode 100644index 000000000..4cc5989eb--- /dev/null+++ b/src/lib/components/ui/accordion/accordion-content.svelte@@ -0,0 +1,24 @@+<script lang="ts">+ import { Accordion as AccordionPrimitive, type WithoutChild } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ children,+ ...restProps+ }: WithoutChild<AccordionPrimitive.ContentProps> = $props();+</script>++<AccordionPrimitive.Content+ bind:ref+ class={cn(+ "data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down overflow-hidden text-sm transition-all",+ className+ )}+ {...restProps}+>+ <div class="pb-4 pt-0">+ {@render children?.()}+ </div>+</AccordionPrimitive.Content>diff --git a/src/lib/components/ui/accordion/accordion-item.svelte b/src/lib/components/ui/accordion/accordion-item.sveltenew file mode 100644index 000000000..852bcf3e5--- /dev/null+++ b/src/lib/components/ui/accordion/accordion-item.svelte@@ -0,0 +1,12 @@+<script lang="ts">+ import { Accordion as AccordionPrimitive } from "bits-ui";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ ...restProps+ }: AccordionPrimitive.ItemProps = $props();+</script>++<AccordionPrimitive.Item bind:ref class={cn("border-b", className)} {...restProps} />diff --git a/src/lib/components/ui/accordion/accordion-trigger.svelte b/src/lib/components/ui/accordion/accordion-trigger.sveltenew file mode 100644index 000000000..54209f210--- /dev/null+++ b/src/lib/components/ui/accordion/accordion-trigger.svelte@@ -0,0 +1,29 @@+<script lang="ts">+ import { Accordion as AccordionPrimitive, type WithoutChild } from "bits-ui";+ import ChevronDown from "@lucide/svelte/icons/chevron-down";+ import { cn } from "$lib/utils.js";++ let {+ ref = $bindable(null),+ class: className,+ level = 3,+ children,+ ...restProps+ }: WithoutChild<AccordionPrimitive.TriggerProps> & {+ level?: AccordionPrimitive.HeaderProps["level"];+ } = $props();+</script>++<AccordionPrimitive.Header {level} class="flex">+ <AccordionPrimitive.Trigger+ bind:ref+ class={cn(+ "flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",+ className+ )}+ {...restProps}+ >+ {@render children?.()}+ <ChevronDown class="size-4 shrink-0 transition-transform duration-200" />+ </AccordionPrimitive.Trigger>+</AccordionPrimitive.Header>diff --git a/src/lib/components/ui/accordion/index.ts b/src/lib/components/ui/accordion/index.tsnew file mode 100644index 000000000..ed4921386--- /dev/null+++ b/src/lib/components/ui/accordion/index.ts@@ -0,0 +1,17 @@+import { Accordion as AccordionPrimitive } from "bits-ui";+import Content from "./accordion-content.svelte";+import Item from "./accordion-item.svelte";+import Trigger from "./accordion-trigger.svelte";+const Root = AccordionPrimitive.Root;++export {+ Root,+ Content,+ Item,+ Trigger,+ //+ Root as Accordion,+ Content as AccordionContent,+ Item as AccordionItem,+ Trigger as AccordionTrigger,+};diff --git a/src/lib/services/docker-service.ts b/src/lib/services/docker-service.tsindex 81df6efbd..2f329431e 100644--- a/src/lib/services/docker-service.ts+++ b/src/lib/services/docker-service.ts@@ -1,4 +1,5 @@import Docker from "dockerode";+import type { VolumeInspectInfo, VolumeCreateOptions, Volume } from "dockerode"; // Import Volume typeimport { getSettings } from "$lib/services/settings-service";import type { DockerConnectionOptions } from "$lib/types/docker";@@ -500,4 +501,73 @@ export async function listVolumes(): Promise<ServiceVolume[]> {}}+/**+ * Creates a Docker volume.+ * @param options - Options for creating the volume (e.g., Name, Driver, Labels).+ */+export async function createVolume(options: VolumeCreateOptions): Promise<any> {+ try {+ const docker = getDockerClient();+ // createVolume returns the volume data directly - no need to inspect+ const volume = await docker.createVolume(options);++ console.log(+ `Docker Service: Volume "${options.Name}" created successfully.`+ );++ // Return the creation response which contains basic info+ return {+ Name: volume.Name,+ Driver: volume.Driver,+ Mountpoint: volume.Mountpoint,+ Labels: volume.Labels || {},+ Scope: volume.Scope || "local",+ CreatedAt: new Date().toISOString(), // Since inspect would give us this+ };+ } catch (error: any) {+ console.error(+ `Docker Service: Error creating volume "${options.Name}":`,+ error+ );+ // Check for specific Docker errors, like volume already exists (often 409)+ if (error.statusCode === 409) {+ throw new Error(`Volume "${options.Name}" already exists.`);+ }+ throw new Error(+ `Failed to create volume "${options.Name}" using host "${dockerHost}". ${+ error.message || error.reason || "" // Include reason if available+ }`+ );+ }+}++/**+ * Removes a Docker volume.+ * @param name - The name of the volume to remove.+ * @param force - Whether to force removal if the volume is in use.+ */+export async function removeVolume(+ name: string,+ force: boolean = false+): Promise<void> {+ try {+ const docker = getDockerClient();+ const volume = docker.getVolume(name);+ await volume.remove({ force });+ console.log(`Docker Service: Volume "${name}" removed successfully.`);+ } catch (error: any) {+ console.error(`Docker Service: Error removing volume "${name}":`, error);+ if (error.statusCode === 409) {+ throw new Error(+ `Volume "${name}" is in use by a container. Use force option to remove.`+ );+ }+ throw new Error(+ `Failed to remove volume "${name}" using host "${dockerHost}". ${+ error.message || error.reason || ""+ }`+ );+ }+}+export default getDockerClient;diff --git a/src/routes/api/volumes/+server.ts b/src/routes/api/volumes/+server.tsnew file mode 100644index 000000000..41dc11d30--- /dev/null+++ b/src/routes/api/volumes/+server.ts@@ -0,0 +1,44 @@+import { json } from "@sveltejs/kit";+import type { RequestHandler } from "./$types";+import { createVolume } from "$lib/services/docker-service";+import type { VolumeCreateOptions } from "dockerode";++export const POST: RequestHandler = async ({ request }) => {+ try {+ const body = await request.json();++ if (+ !body.name ||+ typeof body.name !== "string" ||+ body.name.trim() === ""+ ) {+ return json({ error: "Volume name is required." }, { status: 400 });+ }++ const options: VolumeCreateOptions = {+ Name: body.name.trim(),+ Driver: body.driver || "local",+ Labels: body.labels || {},+ DriverOpts: body.driverOpts || {},+ };++ const volumeInfo = await createVolume(options);++ return json(+ {+ success: true,+ volume: {+ ...volumeInfo,+ Name: body.name.trim(), // Ensure Name is set correctly+ },+ },+ { status: 201 }+ );+ } catch (error: any) {+ console.error("API Error creating volume:", error);+ return json(+ { error: `Failed to create volume: ${error.message || "Unknown error"}` },+ { status: 500 }+ );+ }+};diff --git a/src/routes/api/volumes/[name]/+server.ts b/src/routes/api/volumes/[name]/+server.tsnew file mode 100644index 000000000..41bc9b375--- /dev/null+++ b/src/routes/api/volumes/[name]/+server.ts@@ -0,0 +1,19 @@+import { json } from "@sveltejs/kit";+import type { RequestHandler } from "./$types";+import { removeVolume } from "$lib/services/docker-service";++export const DELETE: RequestHandler = async ({ params, url }) => {+ const { name } = params;+ const force = url.searchParams.get("force") === "true";++ try {+ await removeVolume(name, force);+ return json({ success: true });+ } catch (error: any) {+ console.error("API Error removing volume:", error);+ return json(+ { error: `Failed to remove volume: ${error.message || "Unknown error"}` },+ { status: 500 }+ );+ }+};diff --git a/src/routes/volumes/+page.svelte b/src/routes/volumes/+page.svelteindex 347743286..cd1947f7a 100644--- a/src/routes/volumes/+page.svelte+++ b/src/routes/volumes/+page.svelte@@ -1,6 +1,7 @@<script lang="ts">import * as Card from "$lib/components/ui/card/index.js";import { Button } from "$lib/components/ui/button/index.js";+ import { toast } from "svelte-sonner";import {Plus,AlertCircle,@@ -9,6 +10,7 @@Filter,ArrowUpDown,Database,+ Loader2,} from "@lucide/svelte";import DataTable from "$lib/components/data-table.svelte";import { columns } from "./columns";@@ -16,31 +18,82 @@import * as Alert from "$lib/components/ui/alert/index.js";import { Badge } from "$lib/components/ui/badge/index.js";import { invalidateAll } from "$app/navigation";+ import CreateVolumeDialog from "./create-volume-dialog.svelte";let { data }: { data: PageData } = $props();- const { volumes, error } = data;+ let { error } = data;+ let volumes = $state(data.volumes);let isRefreshing = $state(false);+ let isCreateDialogOpen = $state(false);+ let isCreatingVolume = $state(false);- // Calculate total volumesconst totalVolumes = $derived(volumes?.length || 0);- function createVolume() {- // TODO: Implement create volume functionality- alert("Implement create volume functionality");+ async function handleCreateVolumeSubmit(event: {+ name: string;+ driver?: string;+ driverOpts?: Record<string, string>;+ labels?: Record<string, string>;+ }) {+ const { name, driver, driverOpts, labels } = event;++ isCreatingVolume = true;+ try {+ const response = await fetch("/api/volumes", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ name,+ driver,+ driverOpts,+ labels,+ }),+ });++ const result = await response.json();++ if (!response.ok) {+ throw new Error(+ result.error || `HTTP error! status: ${response.status}`+ );+ }++ toast.success(`Volume "${result.volume.Name}" created successfully.`);+ isCreateDialogOpen = false;++ // Force a refresh with a short timeout to ensure Docker API has time to register the volume+ setTimeout(async () => {+ await refreshData();+ }, 500);+ } catch (err: any) {+ console.error("Failed to create volume:", err);+ toast.error(`Failed to create volume: ${err.message}`);+ } finally {+ isCreatingVolume = false;+ }}async function refreshData() {isRefreshing = true;- await invalidateAll();- setTimeout(() => {- isRefreshing = false;- }, 500);+ try {+ await invalidateAll();+ volumes = data.volumes;+ } finally {+ setTimeout(() => {+ isRefreshing = false;+ }, 300);+ }+ }++ function openCreateDialog() {+ isCreateDialogOpen = true;}</script><div class="space-y-6">- <!-- Header with refresh and create buttons --><div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4"><div><h1 class="text-3xl font-bold tracking-tight">Volumes</h1>@@ -53,12 +106,16 @@variant="outline"size="sm"onclick={refreshData}- disabled={isRefreshing}+ disabled={isRefreshing || isCreatingVolume}>- <RefreshCw class={`h-4 w-4 ${isRefreshing ? "animate-spin" : ""}`} />+ {#if isRefreshing}+ <Loader2 class="h-4 w-4 animate-spin" />+ {:else}+ <RefreshCw class="h-4 w-4" />+ {/if}Refresh</Button>- <Button variant="outline" size="sm" onclick={createVolume}>+ <Button variant="outline" size="sm" onclick={openCreateDialog}><Plus class="w-4 h-4" />Create Volume</Button>@@ -73,7 +130,6 @@</Alert.Root>{/if}- <!-- Volume stats summary --><div class="grid grid-cols-1 sm:grid-cols-2 gap-4"><Card.Root><Card.Content class="p-4 flex items-center justify-between">@@ -100,7 +156,6 @@</Card.Root></div>- <!-- Main volumes table --><Card.Root class="border shadow-sm"><Card.Header class="px-6"><div class="flex items-center justify-between">@@ -141,7 +196,7 @@<RefreshCw class="h-4 w-4 mr-2" />Refresh</Button>- <Button variant="default" size="default" onclick={createVolume}>+ <Button variant="default" size="default" onclick={openCreateDialog}><Plus class="h-4 w-4 mr-2" />Create Volume</Button>@@ -150,4 +205,10 @@{/if}</Card.Content></Card.Root>++ <CreateVolumeDialog+ bind:open={isCreateDialogOpen}+ isCreating={isCreatingVolume}+ onSubmit={handleCreateVolumeSubmit}+ /></div>diff --git a/src/routes/volumes/VolumeActions.svelte b/src/routes/volumes/VolumeActions.svelteindex 36a58cb8e..1dd13e2bc 100644--- a/src/routes/volumes/VolumeActions.svelte+++ b/src/routes/volumes/VolumeActions.svelte@@ -1,22 +1,83 @@-<!-- filepath: /Users/kylemendell/dev/ofkm/arcane/src/routes/volumes/VolumeActions.svelte --><script lang="ts">import { Button } from "$lib/components/ui/button/index.js";- import { Trash2 } from "@lucide/svelte";+ import * as Dialog from "$lib/components/ui/dialog/index.js";+ import { Trash2, AlertCircle, Loader2 } from "@lucide/svelte";+ import { toast } from "svelte-sonner";- export let name: string;+ const { name } = $props<{ name: string }>();- function deleteVolume() {- // TODO: Implement volume deletion logic- alert(`Implement deletion for volume: ${name}`);+ let isConfirmDialogOpen = $state(false);+ let isDeleting = $state(false);++ async function deleteVolume() {+ isDeleting = true;+ try {+ const response = await fetch(`/api/volumes/${name}`, {+ method: "DELETE",+ });++ const result = await response.json();++ if (!response.ok) {+ throw new Error(+ result.error || `HTTP error! status: ${response.status}`+ );+ }++ toast.success(`Volume "${name}" deleted successfully.`);+ isConfirmDialogOpen = false;++ window.location.href = `${window.location.pathname}?t=${Date.now()}`;+ } catch (err: any) {+ console.error(`Failed to delete volume "${name}":`, err);+ toast.error(`Failed to delete volume: ${err.message}`);+ } finally {+ isDeleting = false;+ }}</script>-<Button- variant="destructive"- size="sm"- onclick={deleteVolume}- title="Delete Volume"->- <Trash2 class="w-4 h-4" />-</Button>-<!-- Add other actions like inspect if needed -->+<div class="flex gap-2">+ <Button+ variant="destructive"+ size="sm"+ title="Delete Volume"+ onclick={() => (isConfirmDialogOpen = true)}+ >+ <Trash2 class="w-4 h-4" />+ </Button>++ <Dialog.Root bind:open={isConfirmDialogOpen}>+ <Dialog.Content>+ <Dialog.Header>+ <Dialog.Title>Delete Volume</Dialog.Title>+ <Dialog.Description>+ Are you sure you want to delete volume "{name}"? This action cannot be+ undone.+ </Dialog.Description>+ </Dialog.Header>++ <div class="flex justify-end gap-3 pt-6">+ <Button+ variant="outline"+ onclick={() => (isConfirmDialogOpen = false)}+ disabled={isDeleting}+ >+ Cancel+ </Button>+ <Button+ variant="destructive"+ onclick={deleteVolume}+ disabled={isDeleting}+ >+ {#if isDeleting}+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />+ Deleting...+ {:else}+ Delete+ {/if}+ </Button>+ </div>+ </Dialog.Content>+ </Dialog.Root>+</div>diff --git a/src/routes/volumes/columns.ts b/src/routes/volumes/columns.tsindex 37314ff03..4d03af8da 100644--- a/src/routes/volumes/columns.ts+++ b/src/routes/volumes/columns.ts@@ -1,8 +1,7 @@-// filepath: /Users/kylemendell/dev/ofkm/arcane/src/routes/volumes/columns.tsimport type { ColumnDef } from "@tanstack/table-core";import { renderComponent } from "$lib/components/ui/data-table/index.js";import VolumeActions from "./VolumeActions.svelte";-import MountpointCell from "./MountpointCell.svelte"; // Import the new component+import MountpointCell from "./MountpointCell.svelte";import type { ServiceVolume } from "$lib/services/docker-service";export type VolumeInfo = ServiceVolume;diff --git a/src/routes/volumes/create-volume-dialog.svelte b/src/routes/volumes/create-volume-dialog.sveltenew file mode 100644index 000000000..6edfd4ace--- /dev/null+++ b/src/routes/volumes/create-volume-dialog.svelte@@ -0,0 +1,186 @@+<script lang="ts">+ import { preventDefault } from "svelte/legacy";++ 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 { Textarea } from "$lib/components/ui/textarea/index.js";+ import * as Accordion from "$lib/components/ui/accordion/index.js";+ import * as Select from "$lib/components/ui/select/index.js";++ // Functions for events+ export function onClose() {+ open = false;+ }++ interface Props {+ // Simple boolean prop for open state+ open?: boolean;+ isCreating?: boolean;+ onSubmit?: any;+ }++ let {+ open = $bindable(false),+ isCreating = false,+ onSubmit = (data: {+ name: string;+ driver?: string;+ driverOpts?: Record<string, string>;+ labels?: Record<string, string>;+ }) => {},+ }: Props = $props();++ // Internal state+ let volumeName = $state("");+ let driver = $state("local");+ let showAdvanced = $state(false);++ let driverOptsText = $state("");+ let labelsText = $state("");++ // Available volume drivers+ const drivers = [+ { label: "Local", value: "local" },+ { label: "NFS", value: "nfs" },+ { label: "AWS EBS", value: "awsElasticBlockStore" },+ { label: "Azure Disk", value: "azure_disk" },+ { label: "GCE Persistent Disk", value: "gcePersistentDisk" },+ ];++ function parseKeyValuePairs(text: string): Record<string, string> {+ if (!text.trim()) return {};++ const result: Record<string, string> = {};+ const lines = text.split("\n");++ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed || !trimmed.includes("=")) continue;++ const [key, ...valueParts] = trimmed.split("=");+ const value = valueParts.join("="); // Handle values that might contain =++ if (key.trim()) {+ result[key.trim()] = value.trim();+ }+ }++ return result;+ }++ function handleSubmit() {+ if (!volumeName.trim()) return;++ const driverOpts = parseKeyValuePairs(driverOptsText);+ const labels = parseKeyValuePairs(labelsText);++ onSubmit({+ name: volumeName.trim(),+ driver,+ driverOpts: Object.keys(driverOpts).length ? driverOpts : undefined,+ labels: Object.keys(labels).length ? labels : undefined,+ });+ }+</script>++<Dialog.Root bind:open>+ <Dialog.Content class="sm:max-w-[500px]">+ <Dialog.Header>+ <Dialog.Title>Create New Volume</Dialog.Title>+ <Dialog.Description>+ Enter the details for the new Docker volume.+ </Dialog.Description>+ </Dialog.Header>++ <form onsubmit={preventDefault(handleSubmit)} class="grid gap-4 py-4">+ <!-- Basic volume settings -->+ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="volume-name" class="text-right">Name</Label>+ <Input+ id="volume-name"+ bind:value={volumeName}+ class="col-span-3"+ placeholder="e.g., my-app-data"+ required+ disabled={isCreating}+ />+ </div>++ <div class="grid grid-cols-4 items-center gap-4">+ <Label for="volume-driver" class="text-right">Driver</Label>+ <div class="col-span-3">+ <Select.Root type="single" bind:value={driver} disabled={isCreating}>+ <Select.Trigger class="w-full">+ <span+ >{drivers.find((d) => d.value === driver)?.label ||+ "Select a driver"}</span+ >+ </Select.Trigger>+ <Select.Content>+ {#each drivers as driverOption}+ <Select.Item value={driverOption.value}>+ {driverOption.label}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </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>+ <Label for="driver-opts">Driver Options</Label>+ <Textarea+ id="driver-opts"+ bind:value={driverOptsText}+ placeholder="key=value key2=value2"+ disabled={isCreating}+ />+ <p class="text-xs text-muted-foreground mt-1">+ Enter driver-specific options as key=value pairs, one per line+ </p>+ </div>+ <div>+ <Label for="labels">Labels</Label>+ <Textarea+ id="labels"+ bind:value={labelsText}+ placeholder="com.example.description=Production data com.example.department=Finance"+ disabled={isCreating}+ />+ <p class="text-xs text-muted-foreground mt-1">+ Enter metadata labels as key=value pairs, one per line+ </p>+ </div>+ </div>+ </Accordion.Content>+ </Accordion.Item>+ </Accordion.Root>+ </form>++ <Dialog.Footer>+ <Button variant="outline" onclick={onClose} disabled={isCreating}>+ Cancel+ </Button>+ <Button+ type="submit"+ onclick={handleSubmit}+ disabled={isCreating || !volumeName.trim()}+ >+ {#if isCreating}+ <Loader2 class="h-4 w-4 mr-2 animate-spin" /> Creating...+ {:else}+ Create Volume+ {/if}+ </Button>+ </Dialog.Footer>+ </Dialog.Content>+</Dialog.Root>