Skip to content

Modern Docker Management, Designed for Everyone

feat: initial stakc implementation

Kyle Mendell924b3f1483d7
diff --git a/package-lock.json b/package-lock.json
index 8bae14d7b..731f44a9a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,9 +9,11 @@
"version": "0.1.0",
"dependencies": {
"@tanstack/table-core": "^8.21.3",
- "@types/dockerode": "^3.3.38",
"dockerode": "^4.0.5",
- "mode-watcher": "^1.0.2"
+ "dockerode-compose": "^1.4.0",
+ "js-yaml": "^4.1.0",
+ "mode-watcher": "^1.0.2",
+ "nanoid": "^5.1.5"
},
"devDependencies": {
"@eslint/compat": "^1.2.5",
@@ -21,6 +23,9 @@
"@sveltejs/kit": "^2.16.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@tailwindcss/vite": "^4.0.0",
+ "@types/dockerode": "^3.3.38",
+ "@types/dockerode-compose": "^1.4.1",
+ "@types/js-yaml": "^4.0.9",
"bits-ui": "^1.3.19",
"clsx": "^2.1.1",
"eslint": "^9.18.0",
@@ -1880,6 +1885,7 @@
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/@types/docker-modem/-/docker-modem-3.0.6.tgz",
"integrity": "sha512-yKpAGEuKRSS8wwx0joknWxsmLha78wNMe9R2S3UNsVOkZded8UqOrV8KoeDXoXsjndxwyF3eIhyClGbO1SEhEg==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "*",
@@ -1890,6 +1896,7 @@
"version": "3.3.38",
"resolved": "https://registry.npmjs.org/@types/dockerode/-/dockerode-3.3.38.tgz",
"integrity": "sha512-nnrcfUe2iR+RyOuz0B4bZgQwD9djQa9ADEjp7OAgBs10pYT0KSCtplJjcmBDJz0qaReX5T7GbE5i4VplvzUHvA==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/docker-modem": "*",
@@ -1897,12 +1904,29 @@
"@types/ssh2": "*"
}
},
+ "node_modules/@types/dockerode-compose": {
+ "version": "1.4.1",
+ "resolved": "https://registry.npmjs.org/@types/dockerode-compose/-/dockerode-compose-1.4.1.tgz",
+ "integrity": "sha512-AouE5+t2bghPrCxWGabBGqvXQDF1Hym0NCuCVDzI3vI5KbucWyLBPUIwZK+a9qb3v2Wr9VvBJzHrHLS5r1VM/w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/dockerode": "*"
+ }
+ },
"node_modules/@types/estree": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.7.tgz",
"integrity": "sha512-w28IoSUCJpidD/TGviZwwMJckNESJZXFu7NBZ5YJ4mEUnNraUn9Pm8HSZm/jDF1pDWYKspWE7oVphigUPRakIQ==",
"license": "MIT"
},
+ "node_modules/@types/js-yaml": {
+ "version": "4.0.9",
+ "resolved": "https://registry.npmjs.org/@types/js-yaml/-/js-yaml-4.0.9.tgz",
+ "integrity": "sha512-k4MGaQl5TGo/iipqb2UDG2UwjXziSWkh0uysQelTlJpX1qGlpUZYm8PnO4DxG1qBomtJUdYJ6qR6xdIah10JLg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -1930,6 +1954,7 @@
"version": "1.15.5",
"resolved": "https://registry.npmjs.org/@types/ssh2/-/ssh2-1.15.5.tgz",
"integrity": "sha512-N1ASjp/nXH3ovBHddRJpli4ozpk6UdDYIX4RJWFa9L1YKnzdhTlVmiGHm4DZnj/jLbqZpes4aeR30EFGQtvhQQ==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"@types/node": "^18.11.18"
@@ -1939,6 +1964,7 @@
"version": "18.19.86",
"resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.86.tgz",
"integrity": "sha512-fifKayi175wLyKyc5qUfyENhQ1dCNI1UNjp653d8kuYcPQN5JhX3dGuP/XmvPTg/xRBn1VTLpbmi+H/Mr7tLfQ==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~5.26.4"
@@ -1948,6 +1974,7 @@
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
+ "dev": true,
"license": "MIT"
},
"node_modules/@types/validator": {
@@ -2298,7 +2325,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
- "dev": true,
"license": "Python-2.0"
},
"node_modules/aria-query": {
@@ -2777,6 +2803,17 @@
"node": ">= 8.0"
}
},
+ "node_modules/dockerode-compose": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/dockerode-compose/-/dockerode-compose-1.4.0.tgz",
+ "integrity": "sha512-6x5ZlK06H+cgoTR4ffucqN5kWVvxNvxwTLcHQUZcegCJBEDGrdzXMOEGDMsxbHwiLtLo2dNwG0eZK7B2RfEWSw==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "dockerode": "^4.0.0",
+ "js-yaml": "^4.0.0",
+ "tar-fs": "^2.1.1"
+ }
+ },
"node_modules/effect": {
"version": "3.14.11",
"resolved": "https://registry.npmjs.org/effect/-/effect-3.14.11.tgz",
@@ -3616,7 +3653,6 @@
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz",
"integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==",
- "dev": true,
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -4119,10 +4155,9 @@
"optional": true
},
"node_modules/nanoid": {
- "version": "3.3.11",
- "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
- "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
- "dev": true,
+ "version": "5.1.5",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-5.1.5.tgz",
+ "integrity": "sha512-Ir/+ZpE9fDsNH0hQ3C68uyThDXzYcim2EqcZ8zn8Chtt1iylPT9xXJB0kPCnqzgcEGikO9RxSrh63MsmVCU7Fw==",
"funding": [
{
"type": "github",
@@ -4131,10 +4166,10 @@
],
"license": "MIT",
"bin": {
- "nanoid": "bin/nanoid.cjs"
+ "nanoid": "bin/nanoid.js"
},
"engines": {
- "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ "node": "^18 || >=20"
}
},
"node_modules/natural-compare": {
@@ -4414,6 +4449,25 @@
"node": ">=4"
}
},
+ "node_modules/postcss/node_modules/nanoid": {
+ "version": "3.3.11",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz",
+ "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
"node_modules/prelude-ls": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz",
diff --git a/package.json b/package.json
index c85e9edc1..5fabf6a95 100644
--- a/package.json
+++ b/package.json
@@ -20,6 +20,9 @@
"@sveltejs/kit": "^2.16.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@tailwindcss/vite": "^4.0.0",
+ "@types/dockerode": "^3.3.38",
+ "@types/dockerode-compose": "^1.4.1",
+ "@types/js-yaml": "^4.0.9",
"bits-ui": "^1.3.19",
"clsx": "^2.1.1",
"eslint": "^9.18.0",
@@ -40,8 +43,10 @@
},
"dependencies": {
"@tanstack/table-core": "^8.21.3",
- "@types/dockerode": "^3.3.38",
"dockerode": "^4.0.5",
- "mode-watcher": "^1.0.2"
+ "dockerode-compose": "^1.4.0",
+ "js-yaml": "^4.1.0",
+ "mode-watcher": "^1.0.2",
+ "nanoid": "^5.1.5"
}
}
diff --git a/src/lib/components/navbar.svelte b/src/lib/components/navbar.svelte
index 2af806309..1f1f48a85 100644
--- a/src/lib/components/navbar.svelte
+++ b/src/lib/components/navbar.svelte
@@ -10,6 +10,7 @@
X,
ChevronRight,
ChevronLeft,
+ FileStack,
type Icon as IconType,
} from "@lucide/svelte";
import { page } from "$app/stores";
@@ -53,6 +54,7 @@
items = [
{ href: "/", label: "Dashboard", icon: Home },
{ href: "/containers", label: "Containers", icon: Box },
+ { href: "/stacks", label: "Stacks", icon: FileStack },
{ href: "/images", label: "Images", icon: Image },
{ href: "/networks", label: "Networks", icon: Network },
{ href: "/volumes", label: "Volumes", icon: HardDrive },
diff --git a/src/lib/components/ui/textarea/index.ts b/src/lib/components/ui/textarea/index.ts
new file mode 100644
index 000000000..ace797a89
--- /dev/null
+++ b/src/lib/components/ui/textarea/index.ts
@@ -0,0 +1,7 @@
+import Root from "./textarea.svelte";
+
+export {
+ Root,
+ //
+ Root as Textarea,
+};
diff --git a/src/lib/components/ui/textarea/textarea.svelte b/src/lib/components/ui/textarea/textarea.svelte
new file mode 100644
index 000000000..2616c2c1b
--- /dev/null
+++ b/src/lib/components/ui/textarea/textarea.svelte
@@ -0,0 +1,22 @@
+<script lang="ts">
+ import type { WithElementRef, WithoutChildren } from "bits-ui";
+ import type { HTMLTextareaAttributes } from "svelte/elements";
+ import { cn } from "$lib/utils.js";
+
+ let {
+ ref = $bindable(null),
+ value = $bindable(),
+ class: className,
+ ...restProps
+ }: WithoutChildren<WithElementRef<HTMLTextareaAttributes>> = $props();
+</script>
+
+<textarea
+ bind:this={ref}
+ class={cn(
+ "border-input bg-background ring-offset-background placeholder:text-muted-foreground focus-visible:ring-ring flex min-h-[80px] w-full rounded-md border px-3 py-2 text-base focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
+ className
+ )}
+ bind:value
+ {...restProps}
+></textarea>
diff --git a/src/lib/services/compose.ts b/src/lib/services/compose.ts
new file mode 100644
index 000000000..043f10dd2
--- /dev/null
+++ b/src/lib/services/compose.ts
@@ -0,0 +1,439 @@
+import { promises as fs } from "fs";
+import { join } from "path";
+import DockerodeCompose from "dockerode-compose";
+import { getDockerClient } from "./docker-service";
+import { nanoid } from "nanoid";
+import type {
+ Stack,
+ StackMeta,
+ StackService,
+ StackUpdate,
+} from "$lib/types/stack";
+import yaml from "js-yaml";
+
+const STACKS_DIR =
+ process.env.STACKS_DIR || join(process.cwd(), ".arcane", "stacks");
+
+/**
+ * Ensure stacks directory exists
+ */
+async function ensureStacksDir(): Promise<void> {
+ try {
+ await fs.mkdir(STACKS_DIR, { recursive: true });
+ } catch (err) {
+ console.error("Error creating stacks directory:", err);
+ throw new Error("Failed to create stacks storage directory");
+ }
+}
+
+/**
+ * Get stack directory path
+ * @param {string} stackId
+ */
+function getStackDir(stackId: string): string {
+ return join(STACKS_DIR, stackId);
+}
+
+/**
+ * Get compose file path
+ * @param {string} stackId
+ */
+function getComposeFilePath(stackId: string): string {
+ return join(getStackDir(stackId), "docker-compose.yml");
+}
+
+/**
+ * Get stack metadata file path
+ * @param {string} stackId
+ */
+function getStackMetaPath(stackId: string): string {
+ return join(getStackDir(stackId), "meta.json");
+}
+
+/**
+ * Initialize a DockerodeCompose instance for a stack
+ * @param {string} stackId
+ */
+async function getComposeInstance(stackId: string): Promise<DockerodeCompose> {
+ const docker = getDockerClient();
+ const composePath = getComposeFilePath(stackId);
+ // The third parameter is the project name, used as namespace for containers
+ return new DockerodeCompose(docker, composePath, stackId);
+}
+
+/**
+ * Get the services and their status for a specific stack
+ * @param {string} stackId Stack ID
+ * @param {string} composeContent Compose file content
+ */
+async function getStackServices(
+ stackId: string,
+ composeContent: string
+): Promise<StackService[]> {
+ const docker = getDockerClient();
+
+ try {
+ // Parse the compose file to get service names
+ const composeData = yaml.load(composeContent) as any;
+ if (!composeData || !composeData.services) {
+ return [];
+ }
+
+ const serviceNames = Object.keys(composeData.services);
+
+ // First, list all containers
+ const containers = await docker.listContainers({ all: true });
+
+ // Filter containers related to this stack based on naming convention
+ // DockerodeCompose prepends the project name to container names
+ const stackPrefix = `${stackId}_`;
+ const stackContainers = containers.filter((container) => {
+ const names = container.Names || [];
+ return names.some((name) => name.startsWith(`/${stackPrefix}`));
+ });
+
+ // Map containerData to our StackService format
+ const services: StackService[] = [];
+
+ for (const containerData of stackContainers) {
+ // Extract service name by removing stack prefix from container name
+ let containerName = containerData.Names?.[0] || "";
+ // Remove the leading slash and the stack prefix
+ containerName = containerName.substring(1); // Remove the leading slash
+
+ // Find the service name by removing prefix
+ let serviceName = "";
+ for (const name of serviceNames) {
+ if (
+ containerName.startsWith(`${stackId}_${name}_`) ||
+ containerName === `${stackId}_${name}`
+ ) {
+ serviceName = name;
+ break;
+ }
+ }
+
+ if (!serviceName) {
+ // In case we can't determine the service name, use the container name
+ serviceName = containerName;
+ }
+
+ const service: StackService = {
+ id: containerData.Id,
+ name: serviceName,
+ state: {
+ Running: containerData.State === "running",
+ Status: containerData.State,
+ ExitCode: 0, // Would need to get container inspect data for this
+ },
+ };
+
+ services.push(service);
+ }
+
+ // Add services from compose file that don't have containers yet
+ for (const name of serviceNames) {
+ if (!services.some((s) => s.name === name)) {
+ services.push({
+ id: "",
+ name: name,
+ state: {
+ Running: false,
+ Status: "not created",
+ ExitCode: 0,
+ },
+ });
+ }
+ }
+
+ return services;
+ } catch (err) {
+ console.error(`Error getting services for stack ${stackId}:`, err);
+ return [];
+ }
+}
+
+/**
+ * Load all compose stacks
+ * @returns {Promise<Array<Stack>>} List of stacks
+ */
+export async function loadComposeStacks(): Promise<Stack[]> {
+ await ensureStacksDir();
+
+ try {
+ const stackDirs = await fs.readdir(STACKS_DIR);
+ const stacks: Stack[] = [];
+
+ for (const dir of stackDirs) {
+ try {
+ const metaPath = getStackMetaPath(dir);
+ const composePath = getComposeFilePath(dir);
+
+ const [metaContent, composeContent] = await Promise.all([
+ fs.readFile(metaPath, "utf8"),
+ fs.readFile(composePath, "utf8"),
+ ]);
+
+ const meta = JSON.parse(metaContent) as StackMeta;
+
+ // Get services and their status
+ const services = await getStackServices(dir, composeContent);
+
+ const serviceCount = services.length;
+ const runningCount = services.filter((s) => s.state?.Running).length;
+
+ let status: Stack["status"] = "stopped";
+ if (runningCount === serviceCount && serviceCount > 0) {
+ status = "running";
+ } else if (runningCount > 0) {
+ status = "partially running";
+ }
+
+ stacks.push({
+ id: dir,
+ name: meta.name,
+ serviceCount,
+ runningCount,
+ status,
+ createdAt: meta.createdAt,
+ updatedAt: meta.updatedAt,
+ });
+ } catch (err) {
+ console.warn(`Error loading stack ${dir}:`, err);
+ // Skip this stack if we can't load it
+ }
+ }
+
+ return stacks;
+ } catch (err) {
+ console.error("Error loading stacks:", err);
+ throw new Error("Failed to load compose stacks");
+ }
+}
+
+/**
+ * Get stack by ID
+ * @param {string} stackId
+ */
+export async function getStack(stackId: string): Promise<Stack> {
+ try {
+ const metaPath = getStackMetaPath(stackId);
+ const composePath = getComposeFilePath(stackId);
+
+ const [metaContent, composeContent] = await Promise.all([
+ fs.readFile(metaPath, "utf8"),
+ fs.readFile(composePath, "utf8"),
+ ]);
+
+ const meta = JSON.parse(metaContent) as StackMeta;
+
+ // Get services status
+ const services = await getStackServices(stackId, composeContent);
+ const compose = await getComposeInstance(stackId);
+
+ const serviceCount = services.length;
+ const runningCount = services.filter((s) => s.state?.Running).length;
+
+ let status: Stack["status"] = "stopped";
+ if (runningCount === serviceCount && serviceCount > 0) {
+ status = "running";
+ } else if (runningCount > 0) {
+ status = "partially running";
+ }
+
+ return {
+ id: stackId,
+ name: meta.name,
+ services,
+ serviceCount,
+ runningCount,
+ status,
+ createdAt: meta.createdAt,
+ updatedAt: meta.updatedAt,
+ composeContent,
+ // We don't include the compose instance directly in the returned object
+ // as it may not serialize properly and isn't needed in the UI
+ };
+ } catch (err) {
+ console.error(`Error getting stack ${stackId}:`, err);
+ throw new Error(`Stack not found or cannot be accessed`);
+ }
+}
+
+/**
+ * Create a new stack
+ * @param {string} name Stack name
+ * @param {string} composeContent Compose file content
+ */
+export async function createStack(
+ name: string,
+ composeContent: string
+): Promise<Stack> {
+ await ensureStacksDir();
+
+ const id = nanoid();
+ const stackDir = getStackDir(id);
+ const composePath = getComposeFilePath(id);
+ const metaPath = getStackMetaPath(id);
+
+ const meta: StackMeta = {
+ name,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ };
+
+ try {
+ await fs.mkdir(stackDir, { recursive: true });
+ await Promise.all([
+ fs.writeFile(composePath, composeContent, "utf8"),
+ fs.writeFile(metaPath, JSON.stringify(meta, null, 2), "utf8"),
+ ]);
+
+ return {
+ id,
+ name: meta.name,
+ serviceCount: 0,
+ runningCount: 0,
+ status: "stopped",
+ createdAt: meta.createdAt,
+ updatedAt: meta.updatedAt,
+ };
+ } catch (err) {
+ console.error("Error creating stack:", err);
+ throw new Error("Failed to create stack");
+ }
+}
+
+/**
+ * Update an existing stack
+ * @param {string} stackId Stack ID
+ * @param {StackUpdate} updates Updates to apply
+ */
+export async function updateStack(
+ stackId: string,
+ updates: StackUpdate
+): Promise<Stack> {
+ const metaPath = getStackMetaPath(stackId);
+ const composePath = getComposeFilePath(stackId);
+
+ try {
+ // Read existing meta
+ const metaContent = await fs.readFile(metaPath, "utf8");
+ const meta = JSON.parse(metaContent) as StackMeta;
+
+ // Update meta
+ const updatedMeta: StackMeta = {
+ ...meta,
+ name: updates.name || meta.name,
+ updatedAt: new Date().toISOString(),
+ };
+
+ // Write updated files
+ const promises = [
+ fs.writeFile(metaPath, JSON.stringify(updatedMeta, null, 2), "utf8"),
+ ];
+
+ if (updates.composeContent) {
+ promises.push(fs.writeFile(composePath, updates.composeContent, "utf8"));
+ }
+
+ await Promise.all(promises);
+
+ // Now get the updated stack status
+ const composeContent =
+ updates.composeContent || (await fs.readFile(composePath, "utf8"));
+ const services = await getStackServices(stackId, composeContent);
+
+ const serviceCount = services.length;
+ const runningCount = services.filter((s) => s.state?.Running).length;
+
+ let status: Stack["status"] = "stopped";
+ if (runningCount === serviceCount && serviceCount > 0) {
+ status = "running";
+ } else if (runningCount > 0) {
+ status = "partially running";
+ }
+
+ return {
+ id: stackId,
+ name: updatedMeta.name,
+ serviceCount,
+ runningCount,
+ status,
+ createdAt: updatedMeta.createdAt,
+ updatedAt: updatedMeta.updatedAt,
+ };
+ } catch (err) {
+ console.error(`Error updating stack ${stackId}:`, err);
+ throw new Error("Failed to update stack");
+ }
+}
+
+/**
+ * Start a stack
+ * @param {string} stackId Stack ID
+ */
+export async function startStack(stackId: string): Promise<boolean> {
+ try {
+ const compose = await getComposeInstance(stackId);
+ await compose.up();
+ return true;
+ } catch (err) {
+ console.error(`Error starting stack ${stackId}:`, err);
+ throw new Error(`Failed to start stack: ${err.message}`);
+ }
+}
+
+/**
+ * Stop a stack
+ * @param {string} stackId Stack ID
+ */
+export async function stopStack(stackId: string): Promise<boolean> {
+ try {
+ const compose = await getComposeInstance(stackId);
+ await compose.down();
+ return true;
+ } catch (err) {
+ console.error(`Error stopping stack ${stackId}:`, err);
+ throw new Error(`Failed to stop stack: ${err.message}`);
+ }
+}
+
+/**
+ * Restart a stack
+ * @param {string} stackId Stack ID
+ */
+export async function restartStack(stackId: string): Promise<boolean> {
+ try {
+ // DockerodeCompose doesn't have a restart method, so we'll implement it
+ // by stopping and starting the stack
+ const compose = await getComposeInstance(stackId);
+ await compose.down();
+ await compose.up();
+ return true;
+ } catch (err) {
+ console.error(`Error restarting stack ${stackId}:`, err);
+ throw new Error(`Failed to restart stack: ${err.message}`);
+ }
+}
+
+/**
+ * Remove a stack
+ * @param {string} stackId Stack ID
+ */
+export async function removeStack(stackId: string): Promise<boolean> {
+ try {
+ // First stop all services
+ const compose = await getComposeInstance(stackId);
+ await compose.down();
+
+ // Then delete the stack files
+ const stackDir = getStackDir(stackId);
+ await fs.rm(stackDir, { recursive: true, force: true });
+
+ return true;
+ } catch (err) {
+ console.error(`Error removing stack ${stackId}:`, err);
+ throw new Error(`Failed to remove stack: ${err.message}`);
+ }
+}
diff --git a/src/lib/services/docker-service.ts b/src/lib/services/docker-service.ts
index 2b4c1c5a0..be24351e9 100644
--- a/src/lib/services/docker-service.ts
+++ b/src/lib/services/docker-service.ts
@@ -1,6 +1,7 @@
import Docker from "dockerode";
import fs from "fs"; // Use synchronous fs for initial load
import path from "path";
+import type { DockerConnectionOptions } from "$lib/types/docker";
// Define Settings Type (can be shared with +page.server.ts if moved to a types file)
type SettingsData = {
@@ -40,98 +41,73 @@ function loadInitialSettings(): SettingsData {
const initialSettings = loadInitialSettings();
// --- End Load Initial Settings ---
+let dockerClient: Docker | null = null;
+
/**
- * Creates Dockerode options from a host string.
+ * Initialize Docker connection with the given options
+ * @param options Docker connection options
*/
-function getDockerOpts(host?: string): Docker.DockerOptions {
- const targetHost = host || initialSettings.dockerHost; // Use provided host or loaded setting
- const options: Docker.DockerOptions = {};
-
- if (targetHost.startsWith("unix://")) {
- options.socketPath = targetHost.substring(7);
- } else if (
- targetHost.startsWith("tcp://") ||
- targetHost.startsWith("http://") ||
- targetHost.startsWith("https://")
- ) {
- try {
- const url = new URL(targetHost);
- options.host = url.hostname;
- options.port = url.port || (url.protocol === "https:" ? "2376" : "2375");
- options.protocol = url.protocol.slice(0, -1) as "https" | "http";
- // TODO: Add TLS options if needed based on protocol or settings
- } catch (e) {
- console.error("Invalid Docker host URL format:", targetHost, e);
- // Return options that will likely fail connection, signaling an issue
- return { host: "invalid-host-format" };
+export function initializeDocker(options: DockerConnectionOptions): Docker {
+ let connectionOpts: any = {};
+
+ // Handle different connection types (socket, tcp, etc.)
+ if (options.socketPath) {
+ connectionOpts.socketPath = options.socketPath;
+ } else if (options.host && options.port) {
+ connectionOpts.host = options.host;
+ connectionOpts.port = options.port;
+
+ if (options.ca || options.cert || options.key) {
+ connectionOpts.ca = options.ca;
+ connectionOpts.cert = options.cert;
+ connectionOpts.key = options.key;
}
- } else {
- // Assume it's a socket path if no protocol
- options.socketPath = targetHost;
}
- return options;
-}
-// --- Initialize the shared defaultDocker instance ---
-// Use let so it can be reassigned by updateDefaultDockerInstance
-let defaultDocker = new Docker(getDockerOpts());
-console.log(
- `Docker Service: Initialized defaultDocker with options:`,
- getDockerOpts()
-);
-// --- End Initialization ---
+ dockerClient = new Docker(connectionOpts);
+ return dockerClient;
+}
/**
- * Updates the shared default Docker instance used by the service.
- * @param host - The new Docker host string.
+ * Get the Docker client instance. Initialize with default options if not already initialized.
*/
-export function updateDefaultDockerInstance(host: string) {
- try {
- const newOptions = getDockerOpts(host);
- // Re-assign the module-level defaultDocker variable
- defaultDocker = new Docker(newOptions);
- // Update the settings object in memory (optional, but keeps it consistent)
- initialSettings.dockerHost = host;
- console.log(
- "Docker Service: Updated defaultDocker instance for host:",
- host
- );
- console.log("Docker Service: New options:", newOptions);
- } catch (e) {
- console.error(
- `Docker Service: Failed to update default Docker instance for host: ${host}`,
- e
- );
- // Optionally revert to a known good state or throw
+export function getDockerClient(): Docker {
+ if (!dockerClient) {
+ // Default to socket path for local development
+ const socketPath =
+ process.platform === "win32"
+ ? "//./pipe/docker_engine"
+ : "/var/run/docker.sock";
+
+ dockerClient = new Docker({ socketPath });
}
+
+ return dockerClient;
}
/**
- * Gets Docker system information.
- * Uses the *shared* defaultDocker instance unless a specific host is passed for testing.
- * @param host - Optional Docker host URL to connect to for *testing*. If not provided, uses the default shared instance.
+ * Test Docker connection
+ * @returns Promise resolving to true if connection is successful
*/
-export async function getDockerInfo(host?: string): Promise<Docker.Info> {
- // Use a temporary instance ONLY if a specific host is provided for testing
- const dockerInstance = host ? new Docker(getDockerOpts(host)) : defaultDocker;
- const targetHost = host || initialSettings.dockerHost; // For logging
-
+export async function testDockerConnection(): Promise<boolean> {
try {
- const info = await dockerInstance.info();
- return info;
- } catch (error: any) {
- console.error(
- `Docker Service: Error getting Docker info for host "${targetHost}":`,
- error.message || error
- );
- throw new Error(
- `Failed to connect to Docker Engine at "${targetHost}". ${
- error.message || ""
- }`
- );
+ const docker = getDockerClient();
+ const info = await docker.info();
+ return !!info;
+ } catch (err) {
+ console.error("Docker connection test failed:", err);
+ return false;
}
}
+/**
+ * Get Docker system information
+ */
+export async function getDockerInfo() {
+ const docker = getDockerClient();
+ return await docker.info();
+}
+
// Define and export the type returned by listContainers
export type ServiceContainer = {
id: string;
@@ -148,13 +124,11 @@ export type ServiceContainer = {
/**
* Lists Docker containers.
- * Uses the shared defaultDocker instance.
*/
export async function listContainers(all = true): Promise<ServiceContainer[]> {
try {
- // Uses the potentially updated defaultDocker
- const containers = await defaultDocker.listContainers({ all });
- // Ensure the mapping matches the ServiceContainer type
+ const docker = getDockerClient();
+ const containers = await docker.listContainers({ all });
return containers.map(
(c): ServiceContainer => ({
id: c.Id,
@@ -179,26 +153,23 @@ export async function listContainers(all = true): Promise<ServiceContainer[]> {
/**
* Gets details for a specific container.
- * Uses the shared defaultDocker instance.
*/
export async function getContainer(containerId: string) {
try {
- // Uses the potentially updated defaultDocker
- const container = defaultDocker.getContainer(containerId);
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
const inspectData = await container.inspect();
- // Return relevant details
return {
id: inspectData.Id,
name: inspectData.Name.substring(1),
created: inspectData.Created,
path: inspectData.Path,
args: inspectData.Args,
- state: inspectData.State, // More detailed state object
+ state: inspectData.State,
image: inspectData.Image,
config: inspectData.Config,
networkSettings: inspectData.NetworkSettings,
mounts: inspectData.Mounts,
- // Add more fields as needed
};
} catch (error: any) {
console.error(
@@ -206,7 +177,7 @@ export async function getContainer(containerId: string) {
error
);
if (error.statusCode === 404) {
- return null; // Container not found
+ return null;
}
throw new Error(
`Failed to get container details for ${containerId} using host "${initialSettings.dockerHost}".`
@@ -220,7 +191,8 @@ export async function getContainer(containerId: string) {
*/
export async function startContainer(containerId: string): Promise<void> {
try {
- const container = defaultDocker.getContainer(containerId);
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
await container.start();
} catch (error: any) {
console.error(
@@ -241,7 +213,8 @@ export async function startContainer(containerId: string): Promise<void> {
*/
export async function stopContainer(containerId: string): Promise<void> {
try {
- const container = defaultDocker.getContainer(containerId);
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
await container.stop();
} catch (error: any) {
console.error(
@@ -262,7 +235,8 @@ export async function stopContainer(containerId: string): Promise<void> {
*/
export async function restartContainer(containerId: string): Promise<void> {
try {
- const container = defaultDocker.getContainer(containerId);
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
await container.restart();
} catch (error: any) {
console.error(
@@ -287,7 +261,8 @@ export async function removeContainer(
force = false
): Promise<void> {
try {
- const container = defaultDocker.getContainer(containerId);
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
await container.remove({ force });
} catch (error: any) {
console.error(
@@ -318,16 +293,17 @@ export async function removeContainer(
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
+ tail?: number | "all";
+ since?: number;
+ until?: number;
+ follow?: boolean;
+ stdout?: boolean;
+ stderr?: boolean;
} = {}
): Promise<string> {
try {
- const container = defaultDocker.getContainer(containerId);
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
const logOptions = {
tail: options.tail === "all" ? undefined : options.tail || 100,
@@ -389,7 +365,8 @@ export type ServiceImage = {
*/
export async function listImages(): Promise<ServiceImage[]> {
try {
- const images = await defaultDocker.listImages({ all: false });
+ const docker = getDockerClient();
+ const images = await docker.listImages({ all: false });
const parseRepoTag = (
tag: string | undefined
@@ -444,7 +421,8 @@ export type ServiceNetwork = {
*/
export async function listNetworks(): Promise<ServiceNetwork[]> {
try {
- const networks = await defaultDocker.listNetworks();
+ const docker = getDockerClient();
+ const networks = await docker.listNetworks();
return networks.map(
(net): ServiceNetwork => ({
id: net.Id,
@@ -478,7 +456,8 @@ export type ServiceVolume = {
*/
export async function listVolumes(): Promise<ServiceVolume[]> {
try {
- const volumeResponse = await defaultDocker.listVolumes();
+ const docker = getDockerClient();
+ const volumeResponse = await docker.listVolumes();
const volumes = volumeResponse.Volumes || [];
return volumes.map(
@@ -498,4 +477,4 @@ export async function listVolumes(): Promise<ServiceVolume[]> {
}
}
-export default defaultDocker;
+export default getDockerClient;
diff --git a/src/lib/types/docker.ts b/src/lib/types/docker.ts
new file mode 100644
index 000000000..06fe0b7b4
--- /dev/null
+++ b/src/lib/types/docker.ts
@@ -0,0 +1,8 @@
+export interface DockerConnectionOptions {
+ socketPath?: string;
+ host?: string;
+ port?: number;
+ ca?: string;
+ cert?: string;
+ key?: string;
+}
diff --git a/src/lib/types/stack.ts b/src/lib/types/stack.ts
new file mode 100644
index 000000000..d2a7c8a75
--- /dev/null
+++ b/src/lib/types/stack.ts
@@ -0,0 +1,34 @@
+export interface StackMeta {
+ name: string;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface StackService {
+ id: string;
+ name: string;
+ state?: {
+ Running: boolean;
+ Status: string;
+ ExitCode: number;
+ };
+ ports?: string[];
+}
+
+export interface Stack {
+ id: string;
+ name: string;
+ services?: StackService[];
+ serviceCount: number;
+ runningCount: number;
+ status: "running" | "partially running" | "stopped";
+ createdAt: string;
+ updatedAt: string;
+ composeContent?: string;
+ compose?: any; // Don't include this in serialized responses
+}
+
+export interface StackUpdate {
+ name?: string;
+ composeContent?: string;
+}
diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.ts
index 1cc932fa7..9707787a8 100644
--- a/src/routes/settings/+page.server.ts
+++ b/src/routes/settings/+page.server.ts
@@ -1,6 +1,6 @@
import type { PageServerLoad, Actions } from "./$types";
import { fail } from "@sveltejs/kit";
-import { updateDefaultDockerInstance } from "$lib/services/docker-service";
+import updateDefaultDockerInstance from "$lib/services/docker-service";
// Define a type for settings
type SettingsData = {
diff --git a/src/routes/stacks/+page.server.ts b/src/routes/stacks/+page.server.ts
index 613f24a2d..241f181f2 100644
--- a/src/routes/stacks/+page.server.ts
+++ b/src/routes/stacks/+page.server.ts
@@ -1,5 +1,18 @@
-import type { PageServerLoad } from "./$types";
+import { error } from "@sveltejs/kit";
+import { loadComposeStacks } from "$lib/services/compose";
-export const load = (async () => {
- return {};
-}) satisfies PageServerLoad;
+/** @type {import('./$types').PageServerLoad} */
+export async function load() {
+ try {
+ const stacks = await loadComposeStacks();
+ return {
+ stacks,
+ };
+ } catch (err) {
+ console.error("Failed to load stacks:", err);
+ return {
+ stacks: [],
+ error: "Failed to load Docker Compose stacks: " + err.message,
+ };
+ }
+}
diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelte
index d4be1cba1..94e0655bd 100644
--- a/src/routes/stacks/+page.svelte
+++ b/src/routes/stacks/+page.svelte
@@ -1,5 +1,185 @@
<script lang="ts">
import type { PageData } from "./$types";
+ import * as Card from "$lib/components/ui/card/index.js";
+ import { Button } from "$lib/components/ui/button/index.js";
+ import {
+ Plus,
+ AlertCircle,
+ Layers,
+ RefreshCw,
+ Filter,
+ ArrowUpDown,
+ Upload,
+ FileStack,
+ } from "@lucide/svelte";
+ import DataTable from "$lib/components/data-table.svelte";
+ import { columns } from "./columns";
+ import * as Alert from "$lib/components/ui/alert/index.js";
+ import { Badge } from "$lib/components/ui/badge/index.js";
+ import { invalidateAll } from "$app/navigation";
let { data }: { data: PageData } = $props();
+ const { stacks, error } = data;
+
+ let isRefreshing = $state(false);
+
+ // Calculate stack stats
+ const totalStacks = $derived(stacks?.length || 0);
+ const runningStacks = $derived(
+ stacks?.filter((s) => s.status === "running").length || 0
+ );
+ const partialStacks = $derived(
+ stacks?.filter((s) => s.status === "partially running").length || 0
+ );
+
+ function createStack() {
+ window.location.href = "/stacks/new";
+ }
+
+ async function importStack() {
+ // TODO: Implement import stack modal functionality
+ alert("Implement import stack functionality");
+ }
+
+ async function refreshData() {
+ isRefreshing = true;
+ await invalidateAll();
+ setTimeout(() => {
+ isRefreshing = false;
+ }, 500);
+ }
</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">Stacks</h1>
+ <p class="text-sm text-muted-foreground mt-1">
+ Manage Docker Compose stacks
+ </p>
+ </div>
+ <div class="flex gap-2">
+ <Button
+ variant="outline"
+ size="sm"
+ class="h-9"
+ onclick={refreshData}
+ disabled={isRefreshing}
+ >
+ <RefreshCw
+ class={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`}
+ />
+ Refresh
+ </Button>
+ <Button variant="outline" size="sm" class="h-9" onclick={importStack}>
+ <Upload class="w-4 h-4 mr-2" />
+ Import
+ </Button>
+ <Button variant="default" onclick={createStack}>
+ <Plus class="w-4 h-4 mr-2" />
+ Create Stack
+ </Button>
+ </div>
+ </div>
+
+ {#if error}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="h-4 w-4 mr-2" />
+ <Alert.Title>Error Loading Stacks</Alert.Title>
+ <Alert.Description>{error}</Alert.Description>
+ </Alert.Root>
+ {/if}
+
+ <!-- Stack stats summary -->
+ <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Total Stacks</p>
+ <p class="text-2xl font-bold">{totalStacks}</p>
+ </div>
+ <div class="bg-primary/10 p-2 rounded-full">
+ <FileStack class="h-5 w-5 text-primary" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Running</p>
+ <p class="text-2xl font-bold">{runningStacks}</p>
+ </div>
+ <div class="bg-green-500/10 p-2 rounded-full">
+ <Layers class="h-5 w-5 text-green-500" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">
+ Partially Running
+ </p>
+ <p class="text-2xl font-bold">{partialStacks}</p>
+ </div>
+ <div class="bg-amber-500/10 p-2 rounded-full">
+ <Layers class="h-5 w-5 text-amber-500" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <!-- Main stacks table -->
+ <Card.Root class="border shadow-sm">
+ <Card.Header class="px-6">
+ <div class="flex items-center justify-between">
+ <div>
+ <Card.Title>
+ Stack List
+ <Badge variant="secondary" class="ml-2">{totalStacks}</Badge>
+ </Card.Title>
+ <Card.Description>Manage Docker Compose stacks</Card.Description>
+ </div>
+ <div class="flex items-center gap-2">
+ <Button variant="outline" size="sm" class="hidden sm:flex">
+ <Filter class="h-4 w-4 mr-2" />
+ Filter
+ </Button>
+ <Button variant="outline" size="sm" class="hidden sm:flex">
+ <ArrowUpDown class="h-4 w-4 mr-2" />
+ Sort
+ </Button>
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ {#if stacks && stacks.length > 0}
+ <DataTable data={stacks} {columns} />
+ {:else if !error}
+ <div
+ class="flex flex-col items-center justify-center py-12 px-6 text-center"
+ >
+ <FileStack class="h-12 w-12 text-muted-foreground mb-4 opacity-40" />
+ <p class="text-lg font-medium">No stacks found</p>
+ <p class="text-sm text-muted-foreground mt-1 max-w-md">
+ Create a new stack using the "Create Stack" button above or import
+ an existing compose file
+ </p>
+ <div class="flex gap-3 mt-4">
+ <Button variant="outline" onclick={refreshData}>
+ <RefreshCw class="h-4 w-4 mr-2" />
+ Refresh
+ </Button>
+ <Button variant="default" onclick={createStack}>
+ <Plus class="h-4 w-4 mr-2" />
+ Create Stack
+ </Button>
+ </div>
+ </div>
+ {/if}
+ </Card.Content>
+ </Card.Root>
+</div>
diff --git a/src/routes/stacks/StackActions.svelte b/src/routes/stacks/StackActions.svelte
new file mode 100644
index 000000000..05b8bde12
--- /dev/null
+++ b/src/routes/stacks/StackActions.svelte
@@ -0,0 +1,65 @@
+<script lang="ts">
+ import { enhance } from "$app/forms";
+ import { Button } from "$lib/components/ui/button/index.js";
+ import {
+ Play,
+ CircleStop,
+ Trash2,
+ Settings,
+ RefreshCw,
+ } from "@lucide/svelte";
+
+ interface Props {
+ id: string;
+ status: string;
+ }
+
+ let { id, status }: Props = $props();
+
+ const isRunning = status === "running" || status === "partially running";
+</script>
+
+<div class="flex items-center gap-2 justify-end">
+ {#if isRunning}
+ <form method="POST" action="/stacks/{id}?/stop" use:enhance>
+ <Button type="submit" size="icon" variant="outline" title="Stop Stack">
+ <CircleStop class="h-4 w-4" />
+ </Button>
+ </form>
+ {:else}
+ <form method="POST" action="/stacks/{id}?/start" use:enhance>
+ <Button type="submit" size="icon" variant="outline" title="Start Stack">
+ <Play class="h-4 w-4" />
+ </Button>
+ </form>
+ {/if}
+
+ <form method="POST" action="/stacks/{id}?/restart" use:enhance>
+ <Button
+ type="submit"
+ size="icon"
+ variant="outline"
+ disabled={!isRunning}
+ title="Restart Stack"
+ >
+ <RefreshCw class="h-4 w-4" />
+ </Button>
+ </form>
+
+ <a href="/stacks/{id}">
+ <Button size="icon" variant="outline" title="Edit Stack">
+ <Settings class="h-4 w-4" />
+ </Button>
+ </a>
+
+ <form method="POST" action="/stacks/{id}?/remove" use:enhance>
+ <Button
+ type="submit"
+ size="icon"
+ variant="destructive"
+ title="Remove Stack"
+ >
+ <Trash2 class="h-4 w-4" />
+ </Button>
+ </form>
+</div>
diff --git a/src/routes/stacks/StackDateCell.svelte b/src/routes/stacks/StackDateCell.svelte
new file mode 100644
index 000000000..923049b8c
--- /dev/null
+++ b/src/routes/stacks/StackDateCell.svelte
@@ -0,0 +1,32 @@
+<script lang="ts">
+ interface Props {
+ date: string;
+ }
+
+ let { date }: Props = $props();
+
+ // Format the date with a nice relative format
+ function formatDate(date: string): string {
+ const dateObj = new Date(date);
+ const now = new Date();
+ const diff = now.getTime() - dateObj.getTime();
+ const diffDays = Math.floor(diff / (1000 * 3600 * 24));
+
+ if (diffDays === 0) {
+ return (
+ "Today, " +
+ dateObj.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })
+ );
+ } else if (diffDays === 1) {
+ return "Yesterday";
+ } else if (diffDays < 7) {
+ return `${diffDays} days ago`;
+ } else {
+ return dateObj.toLocaleDateString();
+ }
+ }
+</script>
+
+<span title={new Date(date).toLocaleString()}>
+ {formatDate(date)}
+</span>
diff --git a/src/routes/stacks/StackNameCell.svelte b/src/routes/stacks/StackNameCell.svelte
new file mode 100644
index 000000000..5c2c566cc
--- /dev/null
+++ b/src/routes/stacks/StackNameCell.svelte
@@ -0,0 +1,12 @@
+<script lang="ts">
+ interface Props {
+ id: string;
+ name: string;
+ }
+
+ let { id, name }: Props = $props();
+</script>
+
+<a href="/stacks/{id}" class="font-medium hover:underline">
+ {name}
+</a>
diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.ts
new file mode 100644
index 000000000..9442d9124
--- /dev/null
+++ b/src/routes/stacks/[stackId]/+page.server.ts
@@ -0,0 +1,117 @@
+import { error, redirect } from "@sveltejs/kit";
+import {
+ getStack,
+ updateStack,
+ startStack,
+ stopStack,
+ restartStack,
+ removeStack,
+} from "$lib/services/compose";
+
+/** @type {import('./$types').PageServerLoad} */
+export async function load({ params }) {
+ const { stackId } = params;
+
+ try {
+ const stack = await getStack(stackId);
+ return { stack };
+ } catch (err) {
+ throw error(404, `Stack not found: ${err.message}`);
+ }
+}
+
+/** @type {import('./$types').Actions} */
+export const actions = {
+ update: async ({ params, request }) => {
+ const { stackId } = params;
+ const formData = await request.formData();
+
+ const name = formData.get("name")?.toString() || "";
+ const composeContent = formData.get("composeContent")?.toString() || "";
+
+ try {
+ await updateStack(stackId, { name, composeContent });
+ return {
+ success: true,
+ message: "Stack updated successfully",
+ };
+ } catch (err) {
+ console.error("Error updating stack:", err);
+ return {
+ success: false,
+ error: err.message || "Failed to update stack",
+ };
+ }
+ },
+
+ start: async ({ params }) => {
+ const { stackId } = params;
+
+ try {
+ await startStack(stackId);
+ return {
+ success: true,
+ message: "Stack started successfully",
+ };
+ } catch (err) {
+ console.error("Error starting stack:", err);
+ return {
+ success: false,
+ error: err.message || "Failed to start stack",
+ };
+ }
+ },
+
+ stop: async ({ params }) => {
+ const { stackId } = params;
+
+ try {
+ await stopStack(stackId);
+ return {
+ success: true,
+ message: "Stack stopped successfully",
+ };
+ } catch (err) {
+ console.error("Error stopping stack:", err);
+ return {
+ success: false,
+ error: err.message || "Failed to stop stack",
+ };
+ }
+ },
+
+ restart: async ({ params }) => {
+ const { stackId } = params;
+
+ try {
+ await restartStack(stackId);
+ return {
+ success: true,
+ message: "Stack restarted successfully",
+ };
+ } catch (err) {
+ console.error("Error restarting stack:", err);
+ return {
+ success: false,
+ error: err.message || "Failed to restart stack",
+ };
+ }
+ },
+
+ remove: async ({ params }) => {
+ const { stackId } = params;
+
+ try {
+ await removeStack(stackId);
+ throw redirect(303, "/stacks");
+ } catch (err) {
+ if (err instanceof Response) throw err; // Rethrow the redirect
+
+ console.error("Error removing stack:", err);
+ return {
+ success: false,
+ error: err.message || "Failed to remove stack",
+ };
+ }
+ },
+};
diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelte
new file mode 100644
index 000000000..4c1ccb137
--- /dev/null
+++ b/src/routes/stacks/[stackId]/+page.svelte
@@ -0,0 +1,415 @@
+<script lang="ts">
+ 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,
+ Loader2,
+ AlertCircle,
+ RefreshCw,
+ PlayCircle,
+ StopCircle,
+ RotateCw,
+ Trash2,
+ Save,
+ FileStack,
+ Layers,
+ } 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";
+ import { Badge } from "$lib/components/ui/badge/index.js";
+ import { Textarea } from "$lib/components/ui/textarea/index.js";
+ import { Input } from "$lib/components/ui/input/index.js";
+ import { Label } from "$lib/components/ui/label/index.js";
+ import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
+
+ let { data, form }: { data: PageData; form: ActionData } = $props();
+ let { stack } = $derived(data);
+
+ let starting = $state(false);
+ let stopping = $state(false);
+ let restarting = $state(false);
+ let removing = $state(false);
+ let saving = $state(false);
+ let isRefreshing = $state(false);
+
+ let name = $state(stack?.name || "");
+ let composeContent = $state(stack?.composeContent || "");
+
+ $effect(() => {
+ if (stack) {
+ name = stack.name;
+ composeContent = stack.composeContent;
+ }
+ });
+
+ $effect(() => {
+ starting = false;
+ stopping = false;
+ restarting = false;
+ removing = false;
+ saving = false;
+ });
+
+ async function refreshData() {
+ isRefreshing = true;
+ await invalidateAll();
+ setTimeout(() => {
+ isRefreshing = false;
+ }, 500);
+ }
+</script>
+
+<div class="space-y-6 pb-8">
+ <!-- Breadcrumb Navigation -->
+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
+ <div>
+ <Breadcrumb.Root>
+ <Breadcrumb.List>
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/">Dashboard</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/stacks">Stacks</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Page>{stack?.name || "Loading..."}</Breadcrumb.Page>
+ </Breadcrumb.Item>
+ </Breadcrumb.List>
+ </Breadcrumb.Root>
+
+ <div class="mt-2 flex items-center gap-2">
+ <h1 class="text-2xl font-bold tracking-tight">
+ {stack?.name || "Stack Details"}
+ </h1>
+ {#if stack}
+ <Badge
+ variant={stack.status === "running"
+ ? "success"
+ : stack.status === "partially running"
+ ? "warning"
+ : "destructive"}
+ >
+ {stack.status}
+ </Badge>
+ {/if}
+ </div>
+ </div>
+
+ {#if stack}
+ <div class="flex gap-2 flex-wrap">
+ <Button
+ variant="outline"
+ size="sm"
+ on:click={refreshData}
+ disabled={isRefreshing}
+ class="h-9"
+ >
+ <RefreshCw
+ class={`h-4 w-4 mr-2 ${isRefreshing ? "animate-spin" : ""}`}
+ />
+ Refresh
+ </Button>
+
+ {#if stack.status === "running" || stack.status === "partially 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 h-9"
+ >
+ {#if stopping}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <StopCircle class="w-4 h-4 mr-2" />
+ {/if}
+ Stop
+ </Button>
+ </form>
+ <form
+ method="POST"
+ action="?/restart"
+ use:enhance={() => {
+ restarting = true;
+ return async ({ update }) => {
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ variant="outline"
+ disabled={restarting}
+ size="sm"
+ class="font-medium h-9"
+ >
+ {#if restarting}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <RotateCw class="w-4 h-4 mr-2" />
+ {/if}
+ Restart
+ </Button>
+ </form>
+ {:else}
+ <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 h-9"
+ >
+ {#if starting}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <PlayCircle class="w-4 h-4 mr-2" />
+ {/if}
+ Start
+ </Button>
+ </form>
+ {/if}
+ <form
+ method="POST"
+ action="?/remove"
+ use:enhance={() => {
+ if (
+ !confirm(
+ `Are you sure you want to remove stack "${stack?.name}"?`
+ )
+ ) {
+ return { action: false };
+ }
+ removing = true;
+ return async ({ update }) => {
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Button
+ type="submit"
+ variant="destructive"
+ disabled={removing}
+ size="sm"
+ class="font-medium h-9"
+ >
+ {#if removing}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Trash2 class="w-4 h-4 mr-2" />
+ {/if}
+ Remove
+ </Button>
+ </form>
+ </div>
+ {/if}
+ </div>
+
+ <!-- Error Alert -->
+ {#if form?.error}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="h-4 w-4 mr-2" />
+ <Alert.Title>Action Failed</Alert.Title>
+ <Alert.Description>{form.error}</Alert.Description>
+ </Alert.Root>
+ {/if}
+
+ {#if stack}
+ <!-- Stack Details Section -->
+ <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Services</p>
+ <p class="text-2xl font-bold">{stack.serviceCount}</p>
+ </div>
+ <div class="bg-primary/10 p-2 rounded-full">
+ <Layers class="h-5 w-5 text-primary" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">
+ Running Services
+ </p>
+ <p class="text-2xl font-bold">{stack.runningCount}</p>
+ </div>
+ <div class="bg-green-500/10 p-2 rounded-full">
+ <Layers class="h-5 w-5 text-green-500" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+
+ <Card.Root>
+ <Card.Content class="p-4 flex items-center justify-between">
+ <div>
+ <p class="text-sm font-medium text-muted-foreground">Created</p>
+ <p class="text-lg font-medium">
+ {new Date(stack.createdAt).toLocaleString()}
+ </p>
+ </div>
+ <div class="bg-blue-500/10 p-2 rounded-full">
+ <FileStack class="h-5 w-5 text-blue-500" />
+ </div>
+ </Card.Content>
+ </Card.Root>
+ </div>
+
+ <!-- Stack Editor -->
+ <form
+ method="POST"
+ action="?/update"
+ class="space-y-6"
+ use:enhance={() => {
+ saving = true;
+ return async ({ update }) => {
+ saving = false;
+ await update({ reset: false });
+ };
+ }}
+ >
+ <Card.Root class="border shadow-sm">
+ <Card.Header>
+ <Card.Title>Stack Configuration</Card.Title>
+ <Card.Description
+ >Edit stack settings and compose file</Card.Description
+ >
+ </Card.Header>
+ <Card.Content>
+ <div class="space-y-4">
+ <div class="grid w-full max-w-sm items-center gap-1.5">
+ <Label for="name">Stack Name</Label>
+ <Input
+ type="text"
+ id="name"
+ name="name"
+ bind:value={name}
+ required
+ />
+ </div>
+
+ <div class="grid w-full items-center gap-1.5">
+ <Label for="compose-editor">Docker Compose File</Label>
+ <Textarea
+ id="compose-editor"
+ name="composeContent"
+ bind:value={composeContent}
+ rows={20}
+ class="font-mono text-sm"
+ />
+ <p class="text-xs text-muted-foreground">
+ Edit your docker-compose.yml file directly. Be careful with
+ syntax.
+ </p>
+ </div>
+ </div>
+ </Card.Content>
+ <Card.Footer class="flex justify-between">
+ <Button
+ variant="outline"
+ type="button"
+ on:click={() => window.history.back()}
+ >
+ <ArrowLeft class="w-4 h-4 mr-2" />
+ Back
+ </Button>
+ <Button type="submit" variant="default" disabled={saving}>
+ {#if saving}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Save class="w-4 h-4 mr-2" />
+ {/if}
+ Save Changes
+ </Button>
+ </Card.Footer>
+ </Card.Root>
+ </form>
+
+ <!-- Service List -->
+ <Card.Root class="border shadow-sm">
+ <Card.Header>
+ <Card.Title>Services</Card.Title>
+ <Card.Description>Containers in this stack</Card.Description>
+ </Card.Header>
+ <Card.Content>
+ <div class="space-y-2">
+ {#if stack.services && stack.services.length > 0}
+ {#each stack.services as service}
+ <div
+ class="flex items-center justify-between p-3 border rounded-md"
+ >
+ <div class="flex items-center gap-3">
+ <div class="bg-muted rounded-md p-1">
+ <Layers class="h-4 w-4" />
+ </div>
+ <div>
+ <p class="font-medium">{service.name}</p>
+ <p class="text-xs text-muted-foreground">
+ {service.container?.Id?.substring(0, 12) || "Not created"}
+ </p>
+ </div>
+ </div>
+ <StatusBadge state={service.state?.Status || "unknown"} />
+ </div>
+ {/each}
+ {:else}
+ <div class="text-center py-6 text-muted-foreground">
+ <p>No services defined in this stack</p>
+ </div>
+ {/if}
+ </div>
+ </Card.Content>
+ </Card.Root>
+ {:else}
+ <div
+ class="flex flex-col items-center justify-center py-12 border rounded-lg shadow-sm bg-card"
+ >
+ <div class="rounded-full bg-muted/50 p-4 mb-4">
+ <AlertCircle class="h-8 w-8 text-muted-foreground" />
+ </div>
+ <h2 class="text-lg font-medium mb-2">Stack Not Found</h2>
+ <p class="text-center text-muted-foreground max-w-md">
+ Could not load stack data. It may have been removed or the Docker engine
+ is not accessible.
+ </p>
+ <div class="flex gap-3 mt-6">
+ <Button variant="outline" href="/stacks">
+ <ArrowLeft class="h-4 w-4 mr-2" />
+ Back to Stacks
+ </Button>
+ <Button variant="default" on:click={refreshData}>
+ <RefreshCw class="h-4 w-4 mr-2" />
+ Retry
+ </Button>
+ </div>
+ </div>
+ {/if}
+</div>
diff --git a/src/routes/stacks/columns.ts b/src/routes/stacks/columns.ts
new file mode 100644
index 000000000..c00173e7b
--- /dev/null
+++ b/src/routes/stacks/columns.ts
@@ -0,0 +1,51 @@
+import type { Stack } from "$lib/types/stack";
+import type { ColumnDef } from "@tanstack/table-core";
+import { renderComponent } from "$lib/components/ui/data-table/index.js";
+import StackActions from "./StackActions.svelte";
+import StatusBadge from "$lib/components/docker/StatusBadge.svelte";
+import StackNameCell from "./StackNameCell.svelte";
+import StackDateCell from "./StackDateCell.svelte";
+
+export const columns: ColumnDef<Stack>[] = [
+ {
+ accessorKey: "name",
+ header: "Name",
+ cell: ({ row }) => {
+ return renderComponent(StackNameCell, {
+ id: row.original.id,
+ name: row.original.name,
+ });
+ },
+ },
+ {
+ accessorKey: "serviceCount",
+ header: "Services",
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ cell: ({ row }) => {
+ return renderComponent(StatusBadge, { state: row.original.status });
+ },
+ },
+ {
+ accessorKey: "createdAt",
+ header: "Created",
+ cell: ({ row }) => {
+ return renderComponent(StackDateCell, {
+ date: row.original.createdAt,
+ });
+ },
+ },
+ {
+ id: "actions",
+ header: "Actions",
+ cell: ({ row }) => {
+ return renderComponent(StackActions, {
+ id: row.original.id,
+ status: row.original.status,
+ });
+ },
+ enableSorting: false,
+ },
+];
diff --git a/src/routes/stacks/new/+page.server.ts b/src/routes/stacks/new/+page.server.ts
new file mode 100644
index 000000000..dad9d3b72
--- /dev/null
+++ b/src/routes/stacks/new/+page.server.ts
@@ -0,0 +1,39 @@
+import { redirect } from "@sveltejs/kit";
+import { createStack } from "$lib/services/compose";
+
+/** @type {import('./$types').Actions} */
+export const actions = {
+ default: async ({ request }) => {
+ const formData = await request.formData();
+
+ const name = formData.get("name")?.toString() || "";
+ const composeContent = formData.get("composeContent")?.toString() || "";
+
+ if (!name) {
+ return {
+ success: false,
+ error: "Stack name is required",
+ };
+ }
+
+ if (!composeContent) {
+ return {
+ success: false,
+ error: "Compose file content is required",
+ };
+ }
+
+ try {
+ const stack = await createStack(name, composeContent);
+ throw redirect(303, `/stacks/${stack.id}`);
+ } catch (err) {
+ if (err instanceof Response) throw err; // Rethrow the redirect
+
+ console.error("Error creating stack:", err);
+ return {
+ success: false,
+ error: err.message || "Failed to create stack",
+ };
+ }
+ },
+};
diff --git a/src/routes/stacks/new/+page.svelte b/src/routes/stacks/new/+page.svelte
new file mode 100644
index 000000000..267883570
--- /dev/null
+++ b/src/routes/stacks/new/+page.svelte
@@ -0,0 +1,151 @@
+<script lang="ts">
+ import type { ActionData } from "./$types";
+ import * as Card from "$lib/components/ui/card/index.js";
+ import { Button } from "$lib/components/ui/button/index.js";
+ import {
+ ArrowLeft,
+ Loader2,
+ AlertCircle,
+ Save,
+ FileStack,
+ } from "@lucide/svelte";
+ import * as Breadcrumb from "$lib/components/ui/breadcrumb/index.js";
+ import { enhance } from "$app/forms";
+ import * as Alert from "$lib/components/ui/alert/index.js";
+ import { Textarea } from "$lib/components/ui/textarea/index.js";
+ import { Input } from "$lib/components/ui/input/index.js";
+ import { Label } from "$lib/components/ui/label/index.js";
+
+ let { form }: { form: ActionData } = $props();
+
+ let saving = $state(false);
+
+ // Default compose file template
+ const defaultComposeTemplate = `version: '3'
+
+services:
+ web:
+ image: nginx:latest
+ ports:
+ - "8080:80"
+ volumes:
+ - ./html:/usr/share/nginx/html
+ restart: unless-stopped
+`;
+
+ let name = $state("");
+ let composeContent = $state(defaultComposeTemplate);
+</script>
+
+<div class="space-y-6 pb-8">
+ <!-- Breadcrumb Navigation -->
+ <div class="flex flex-col sm:flex-row justify-between sm:items-center gap-4">
+ <div>
+ <Breadcrumb.Root>
+ <Breadcrumb.List>
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/">Dashboard</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Link href="/stacks">Stacks</Breadcrumb.Link>
+ </Breadcrumb.Item>
+ <Breadcrumb.Separator />
+ <Breadcrumb.Item>
+ <Breadcrumb.Page>New Stack</Breadcrumb.Page>
+ </Breadcrumb.Item>
+ </Breadcrumb.List>
+ </Breadcrumb.Root>
+
+ <h1 class="text-2xl font-bold tracking-tight mt-2">Create New Stack</h1>
+ </div>
+ </div>
+
+ <!-- Error Alert -->
+ {#if form?.error}
+ <Alert.Root variant="destructive">
+ <AlertCircle class="h-4 w-4 mr-2" />
+ <Alert.Title>Failed to Create Stack</Alert.Title>
+ <Alert.Description>{form.error}</Alert.Description>
+ </Alert.Root>
+ {/if}
+
+ <!-- Stack Editor -->
+ <form
+ method="POST"
+ class="space-y-6"
+ use:enhance={() => {
+ saving = true;
+ return async ({ update }) => {
+ saving = false;
+ await update();
+ };
+ }}
+ >
+ <Card.Root class="border shadow-sm">
+ <Card.Header>
+ <div class="flex items-center gap-3">
+ <div class="bg-primary/10 p-2 rounded-full">
+ <FileStack class="h-5 w-5 text-primary" />
+ </div>
+ <div>
+ <Card.Title>Stack Configuration</Card.Title>
+ <Card.Description
+ >Create a new Docker Compose stack</Card.Description
+ >
+ </div>
+ </div>
+ </Card.Header>
+ <Card.Content>
+ <div class="space-y-4">
+ <div class="grid w-full max-w-sm items-center gap-1.5">
+ <Label for="name">Stack Name</Label>
+ <Input
+ type="text"
+ id="name"
+ name="name"
+ bind:value={name}
+ required
+ placeholder="e.g., my-web-app"
+ />
+ </div>
+
+ <div class="grid w-full items-center gap-1.5">
+ <Label for="compose-editor">Docker Compose File</Label>
+ <Textarea
+ id="compose-editor"
+ name="composeContent"
+ bind:value={composeContent}
+ rows={20}
+ class="font-mono text-sm"
+ required
+ placeholder="Paste your docker-compose.yml content here"
+ />
+ <p class="text-xs text-muted-foreground">
+ Enter a valid docker-compose.yml file. Be sure to check your
+ syntax.
+ </p>
+ </div>
+ </div>
+ </Card.Content>
+ <Card.Footer class="flex justify-between">
+ <Button
+ variant="outline"
+ type="button"
+ onclick={() => window.history.back()}
+ >
+ <ArrowLeft class="w-4 h-4 mr-2" />
+ Cancel
+ </Button>
+ <Button type="submit" variant="default" disabled={saving}>
+ {#if saving}
+ <Loader2 class="w-4 h-4 mr-2 animate-spin" />
+ {:else}
+ <Save class="w-4 h-4 mr-2" />
+ {/if}
+ Create Stack
+ </Button>
+ </Card.Footer>
+ </Card.Root>
+ </form>
+</div>