Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: custom stack implementation (#208)
Kyle Mendell5391c9d4bd3a
diff --git a/src/lib/components/action-buttons.svelte b/src/lib/components/action-buttons.svelteindex dfcb592f6..c512ea778 100644--- a/src/lib/components/action-buttons.svelte+++ b/src/lib/components/action-buttons.svelte@@ -52,15 +52,23 @@if (action === 'remove') {openConfirmDialog({title: `Confirm ${type === 'stack' ? 'Destroy' : 'Removal'}`,- message: `Are you sure you want to ${type === 'stack' ? 'destroy' : 'remove'} this ${type}? This action cannot be undone.`,+ message: `Are you sure you want to ${type === 'stack' ? 'destroy' : 'remove'} this ${type}? This action is DESTRUCTIVE and cannot be undone.`,confirm: {label: type === 'stack' ? 'Destroy' : 'Remove',destructive: true,- action: async () => {+ action: async (checkboxStates) => {+ console.log('Debug - received checkbox states:', checkboxStates);++ // Ensure these are proper booleans+ const removeFiles = checkboxStates['removeFiles'] === true;+ const removeVolumes = checkboxStates['removeVolumes'] === true;++ console.log('Debug - removeFiles:', removeFiles, 'removeVolumes:', removeVolumes);+isLoading.remove = true;handleApiResultWithCallbacks({- result: await tryCatch(type === 'container' ? containerApi.remove(id) : stackApi.destroy(id)),- message: `Failed to ${type === 'stack' ? 'Destroy' : 'Removal'} ${type}`,+ result: await tryCatch(type === 'container' ? containerApi.remove(id) : stackApi.destroy(id, removeVolumes, removeFiles)),+ message: `Failed to ${type === 'stack' ? 'Destroy' : 'Remove'} ${type}`,setLoadingState: (value) => (isLoading.remove = value),onSuccess: async () => {toast.success(`${type.charAt(0).toUpperCase() + type.slice(1)} ${type === 'stack' ? 'Destroyed' : 'Removed'} Successfully`);@@ -69,12 +77,16 @@}});}- }+ },+ checkboxes: [+ { id: 'removeFiles', label: 'Remove stack files', initialState: false },+ { id: 'removeVolumes', label: 'Remove volumes (Warning: Data will be lost)', initialState: false }+ ]});} else if (action === 'redeploy') {openConfirmDialog({title: `Confirm Redeploy`,- message: `Are you sure you want to redeploy this ${type}?`,+ message: `Are you sure you want to redeploy this stack? This will STOP, PULL, and START the Stack.`,confirm: {label: 'Redeploy',action: async () => {@@ -97,7 +109,7 @@async function handleStart() {isLoading.start = true;handleApiResultWithCallbacks({- result: await tryCatch(type === 'container' ? containerApi.start(id) : stackApi.start(id)),+ result: await tryCatch(type === 'container' ? containerApi.start(id) : stackApi.deploy(id)),message: `Failed to Start ${type}`,setLoadingState: (value) => (isLoading.start = value),onSuccess: async () => {diff --git a/src/lib/components/confirm-dialog/confirm-dialog.svelte b/src/lib/components/confirm-dialog/confirm-dialog.svelteindex 0f4c1c2bd..79651dd5a 100644--- a/src/lib/components/confirm-dialog/confirm-dialog.svelte+++ b/src/lib/components/confirm-dialog/confirm-dialog.svelte@@ -3,6 +3,28 @@import { AlertTriangle } from '@lucide/svelte';import { confirmDialogStore } from '.';import Button from '../ui/button/button.svelte';+ import { Label } from '$lib/components/ui/label';+ import Checkbox from '../ui/checkbox/checkbox.svelte';++ let checkboxStates = $state<Record<string, boolean>>({});++ $effect(() => {+ if ($confirmDialogStore.open && $confirmDialogStore.checkboxes) {+ const newStates: Record<string, boolean> = {};++ for (const checkbox of $confirmDialogStore.checkboxes) {+ newStates[checkbox.id] = Boolean(checkbox.initialState);+ }++ checkboxStates = newStates;+ }+ });++ function handleConfirm() {+ console.log('Final checkbox states before confirm:', checkboxStates);+ $confirmDialogStore.confirm.action(checkboxStates);+ $confirmDialogStore.open = false;+ }</script><Dialog.Root bind:open={$confirmDialogStore.open}>@@ -18,24 +40,28 @@{$confirmDialogStore.message}</div>- <!-- {#if showForceRemoveCheckbox}- <div class="flex items-center space-x-2 pt-4 pb-2 mt-4 border-t border-border">- <Checkbox id="force-remove" bind:checked={forceRemoveChecked} />- <Label for="force-remove" class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Force remove running container</Label>+ <!-- Checkboxes -->+ {#if $confirmDialogStore.checkboxes && $confirmDialogStore.checkboxes.length > 0}+ <div class="flex flex-col gap-3 pt-4 pb-2 mt-4 border-t border-border">+ {#each $confirmDialogStore.checkboxes as checkbox (checkbox.id)}+ <div class="flex items-center space-x-2">+ {#if checkboxStates[checkbox.id] !== undefined}+ <Checkbox id={checkbox.id} bind:checked={checkboxStates[checkbox.id]} aria-labelledby={`${checkbox.id}-label`} />+ {:else}+ <Checkbox id={checkbox.id} checked={false} onchange={(e) => (checkboxStates[checkbox.id] = true)} aria-labelledby={`${checkbox.id}-label`} />+ {/if}+ <Label id={`${checkbox.id}-label`} for={checkbox.id} class="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70">+ {checkbox.label}+ </Label>+ </div>+ {/each}</div>- {/if} -->+ {/if}<Dialog.Footer class="mt-6"><div class="flex justify-end gap-2"><Button class="arcane-button-cancel" variant="outline" onclick={() => ($confirmDialogStore.open = false)}>Cancel</Button>- <Button- class="arcane-button-create"- variant={$confirmDialogStore.confirm.destructive ? 'destructive' : 'default'}- onclick={() => {- $confirmDialogStore.confirm.action();- $confirmDialogStore.open = false;- }}- >+ <Button class="arcane-button-create" variant={$confirmDialogStore.confirm.destructive ? 'destructive' : 'default'} onclick={handleConfirm}>{$confirmDialogStore.confirm.label}</Button></div>diff --git a/src/lib/components/confirm-dialog/index.ts b/src/lib/components/confirm-dialog/index.tsindex 8812a6096..963242c34 100644--- a/src/lib/components/confirm-dialog/index.ts+++ b/src/lib/components/confirm-dialog/index.ts@@ -1,7 +1,23 @@import { writable } from 'svelte/store';import ConfirmDialog from './confirm-dialog.svelte';-export const confirmDialogStore = writable({+interface ConfirmDialogStore {+ open: boolean;+ title: string;+ message: string;+ confirm: {+ label?: string;+ destructive?: boolean;+ action: (checkboxStates: Record<string, boolean>) => void;+ };+ checkboxes?: Array<{+ id: string;+ label: string;+ initialState?: boolean;+ }>;+}++export const confirmDialogStore = writable<ConfirmDialogStore>({open: false,title: '',message: '',@@ -15,15 +31,21 @@ export const confirmDialogStore = writable({function openConfirmDialog({title,message,- confirm+ confirm,+ checkboxes}: {title: string;message: string;confirm: {label?: string;destructive?: boolean;- action: () => void;+ action: (checkboxStates: Record<string, boolean>) => void;};+ checkboxes?: Array<{+ id: string;+ label: string;+ initialState?: boolean;+ }>;}) {confirmDialogStore.update((val) => ({open: true,@@ -32,7 +54,8 @@ function openConfirmDialog({confirm: {...val.confirm,...confirm- }+ },+ checkboxes}));}diff --git a/src/lib/services/api/stack-api-service.ts b/src/lib/services/api/stack-api-service.tsindex 2afef8806..519709690 100644--- a/src/lib/services/api/stack-api-service.ts+++ b/src/lib/services/api/stack-api-service.ts@@ -1,13 +1,13 @@import BaseAPIService from './api-service';export default class StackAPIService extends BaseAPIService {- async start(id: string) {- const res = await this.api.post(`/stacks/${id}/start`);+ async deploy(id: string) {+ const res = await this.api.post(`/stacks/${id}/deploy`);return res.data;}async down(id: string) {- const res = await this.api.post(`/stacks/${id}/stop`);+ const res = await this.api.post(`/stacks/${id}/down`);return res.data;}@@ -16,8 +16,19 @@ export default class StackAPIService extends BaseAPIService {return res.data;}- async destroy(id: string) {- const res = await this.api.delete(`/stacks/${id}/remove`);+ async destroy(id: string, removeVolumes = false, removeFiles = false) {+ console.log('API service - removeVolumes:', removeVolumes, 'removeFiles:', removeFiles);++ const queryParams = {+ removeVolumes: removeVolumes ? 'true' : 'false',+ removeFiles: removeFiles ? 'true' : 'false'+ };++ console.log('Query params:', queryParams);++ const res = await this.api.delete(`/stacks/${id}/destroy`, {+ params: queryParams+ });return res.data;}diff --git a/src/lib/services/docker/auto-update-service.ts b/src/lib/services/docker/auto-update-service.tsindex 9659c5c56..185fb0c9e 100644--- a/src/lib/services/docker/auto-update-service.ts+++ b/src/lib/services/docker/auto-update-service.ts@@ -1,5 +1,6 @@import { listContainers, getContainer, recreateContainer } from './container-service';-import { listStacks, getStack, fullyRedeployStack } from './stack-service';+import { listStacks, getStack } from './stack-service';+import { redeployStack } from './stack-custom-service';import { pullImage, getImage } from './image-service';import { getSettings } from '../settings-service';import yaml from 'js-yaml';@@ -148,7 +149,7 @@ export async function checkAndUpdateStacks(): Promise<{if (updateAvailable) {updatingStacks.add(stackToUpdate.id);console.log(`Auto-update: Redeploying stack ${stackToUpdate.name} (${stackToUpdate.id})`);- await fullyRedeployStack(stackToUpdate.id);+ await redeployStack(stackToUpdate.id);console.log(`Auto-update: Stack ${stackToUpdate.name} redeployed successfully`);results.updated++;updatingStacks.delete(stackToUpdate.id);diff --git a/src/lib/services/docker/stack-custom-service.ts b/src/lib/services/docker/stack-custom-service.tsnew file mode 100644index 000000000..781ec3872--- /dev/null+++ b/src/lib/services/docker/stack-custom-service.ts@@ -0,0 +1,1018 @@+import { promises as fs } from 'node:fs';+import * as path from 'node:path';+import Dockerode from 'dockerode';+import { getComposeFilePath, getStackDir, loadEnvFile, parseYamlContent, normalizeHealthcheckTest } from './stack-service';+import { getDockerClient } from './core';+import { removeVolume } from './volume-service';++const stackCache = new Map();++// Helper function to parse environment file content+export function parseEnvContent(envContent: string | null): Record<string, string> {+ const envVars: Record<string, string> = {};+ if (envContent) {+ envContent.split('\n').forEach((line) => {+ const trimmedLine = line.trim();+ if (trimmedLine && !trimmedLine.startsWith('#')) {+ const [key, ...valueParts] = trimmedLine.split('=');+ const value = valueParts.join('=');+ if (key) {+ envVars[key.trim()] = value?.trim() || '';+ }+ }+ });+ }+ return envVars;+}++/**+ * Custom stack deployment function using dockerode directly+ */+export async function deployStack(stackId: string): Promise<boolean> {+ const stackDir = await getStackDir(stackId);+ const originalCwd = process.cwd();+ let deploymentStarted = false;++ try {+ // Load and normalize compose file+ const composePath = await getComposeFilePath(stackId);+ if (!composePath) {+ throw new Error(`Compose file not found for stack ${stackId}`);+ }++ const composeContent = await fs.readFile(composePath, 'utf8');+ const envContent = await loadEnvFile(stackId);++ // Parse env variables and create getter+ const envVars = parseEnvContent(envContent);+ const getEnvVar = (key: string): string | undefined => envVars[key] || process.env[key];++ // Normalize content for healthchecks but don't write it back to the file+ const normalizedContent = normalizeHealthcheckTest(composeContent, getEnvVar);++ // Only write back if it's specifically a healthcheck normalization issue+ // Don't write back the env var interpolations+ if (normalizedContent !== composeContent && normalizedContent.includes('healthcheck') && composeContent.includes('healthcheck')) {+ await fs.writeFile(composePath, normalizedContent, 'utf8');+ }++ // Parse normalized content+ const composeData = parseYamlContent(normalizedContent, getEnvVar);+ if (!composeData) {+ throw new Error(`Failed to parse compose file for stack ${stackId}`);+ }++ // Store environment variables in compose data for later use+ composeData._envVars = envVars;++ // Change directory for relative paths+ process.chdir(stackDir);+ console.log(`Temporarily changed CWD to: ${stackDir} for stack operations`);++ // Get docker client+ const docker = await getDockerClient();+ deploymentStarted = true;++ // Deploy in sequence:+ // 1. Create networks+ await createStackNetworks(docker, stackId, composeData.networks || {});++ // 2. Pull images+ await pullStackImages(docker, composeData.services || {});++ // 3. Create volumes (if needed)+ await createStackVolumes(docker, stackId, composeData.volumes || {});++ // 4. Create and start containers with proper network config+ await createAndStartContainers(docker, stackId, composeData, stackDir);++ // If everything succeeds, invalidate cache+ stackCache.delete('compose-stacks');+ return true;+ } catch (err) {+ if (deploymentStarted) {+ try {+ await cleanupFailedDeployment(stackId);+ } catch (cleanupErr) {+ console.error(`Error cleaning up failed deployment for stack ${stackId}:`, cleanupErr);+ }+ }++ console.error(`Error deploying stack ${stackId}:`, err);+ const errorMessage = err instanceof Error ? err.message : String(err);+ throw new Error(`Failed to deploy stack: ${errorMessage}`);+ } finally {+ process.chdir(originalCwd);+ console.log(`Restored CWD to: ${originalCwd}`);+ }+}++/**+ * Creates all networks defined in the compose file+ */+async function createStackNetworks(docker: Dockerode, stackId: string, networks: Record<string, any>): Promise<void> {+ // Always create a default network if no networks are defined+ if (Object.keys(networks).length === 0) {+ const defaultNetworkName = `${stackId}_default`;+ console.log(`No networks defined, creating default network: ${defaultNetworkName}`);++ try {+ await docker.createNetwork({+ Name: defaultNetworkName,+ Driver: 'bridge',+ Labels: {+ 'com.docker.compose.project': stackId,+ 'com.docker.compose.network': 'default'+ }+ });+ } catch (err: any) {+ if (err.statusCode === 409) {+ console.log(`Default network ${defaultNetworkName} already exists, reusing it.`);+ } else {+ throw err;+ }+ }+ return;+ }++ // Process defined networks+ for (const [networkName, networkConfig] of Object.entries(networks)) {+ // Skip external networks+ if (networkConfig.external) {+ console.log(`Using external network: ${networkName}`);+ continue;+ }++ // Network creation logic+ const networkToCreate = {+ Name: networkConfig.name || `${stackId}_${networkName}`,+ Driver: networkConfig.driver || 'bridge',+ Labels: {+ 'com.docker.compose.project': stackId,+ 'com.docker.compose.network': networkName+ },+ Options: networkConfig.driver_opts || {}+ };++ try {+ console.log(`Creating network: ${networkToCreate.Name}`);+ await docker.createNetwork(networkToCreate);+ } catch (err: any) {+ if (err.statusCode === 409) {+ console.log(`Network ${networkToCreate.Name} already exists, reusing it.`);+ } else {+ throw err;+ }+ }+ }+}++/**+ * Pulls all images defined in the compose file+ */+async function pullStackImages(docker: Dockerode, services: Record<string, any>): Promise<void> {+ const pullPromises = Object.entries(services)+ .filter(([_, serviceConfig]) => serviceConfig.image)+ .map(async ([serviceName, serviceConfig]) => {+ const serviceImage = serviceConfig.image;+ console.log(`Pulling image for service ${serviceName}: ${serviceImage}`);++ try {+ await new Promise((resolve, reject) => {+ docker.pull(serviceImage, {}, (pullError, stream) => {+ if (pullError) {+ reject(pullError);+ return;+ }+ if (!stream) {+ reject(new Error(`Docker pull did not return a stream.`));+ return;+ }++ docker.modem.followProgress(+ stream,+ (progressError, output) => {+ if (progressError) {+ reject(progressError);+ } else {+ resolve(output);+ }+ },+ (event) => {+ if (event.progress) {+ console.log(`${serviceImage}: ${event.status} ${event.progress}`);+ } else if (event.status) {+ console.log(`${serviceImage}: ${event.status}`);+ }+ }+ );+ });+ });+ } catch (err) {+ console.warn(`Warning: Failed to pull image ${serviceImage}:`, err);+ }+ });++ await Promise.all(pullPromises);+}++/**+ * Pulls all images for a stack without deploying+ */+export async function pullImagesForStack(stackId: string): Promise<boolean> {+ console.log(`Pulling images for stack ${stackId}...`);++ try {+ // Load and normalize compose file+ const composePath = await getComposeFilePath(stackId);+ if (!composePath) {+ throw new Error(`Compose file not found for stack ${stackId}`);+ }++ const composeContent = await fs.readFile(composePath, 'utf8');+ const envContent = await loadEnvFile(stackId);++ // Parse env variables and create getter+ const envVars = parseEnvContent(envContent);+ const getEnvVar = (key: string): string | undefined => envVars[key] || process.env[key];++ // Normalize and parse compose content+ const normalizedContent = normalizeHealthcheckTest(composeContent, getEnvVar);+ const composeData = parseYamlContent(normalizedContent, getEnvVar);++ if (!composeData) {+ throw new Error(`Failed to parse compose file for stack ${stackId}`);+ }++ // Get docker client+ const docker = await getDockerClient();++ // Call the internal pullStackImages function with correct arguments+ await pullStackImages(docker, composeData.services || {});++ return true;+ } catch (err) {+ console.error(`Error pulling images for stack ${stackId}:`, err);+ throw new Error(`Failed to pull images: ${err instanceof Error ? err.message : String(err)}`);+ }+}++/**+ * Creates volumes defined in the compose file+ */+async function createStackVolumes(docker: Dockerode, stackId: string, volumes: Record<string, any>): Promise<void> {+ for (const [volumeName, volumeConfig] of Object.entries(volumes)) {+ if (volumeConfig?.external) {+ console.log(`Using external volume: ${volumeName}`);+ continue;+ }++ const volumeToCreate = {+ Name: volumeConfig?.name || `${stackId}_${volumeName}`,+ Driver: volumeConfig?.driver || 'local',+ DriverOpts: volumeConfig?.driver_opts || {},+ Labels: {+ 'com.docker.compose.project': stackId,+ 'com.docker.compose.volume': volumeName,+ ...volumeConfig?.labels+ }+ };++ try {+ console.log(`Creating volume: ${volumeToCreate.Name}`);+ await docker.createVolume(volumeToCreate);+ } catch (err: any) {+ if (err.statusCode === 409) {+ console.log(`Volume ${volumeToCreate.Name} already exists, reusing it.`);+ } else {+ throw err;+ }+ }+ }+}++/**+ * Creates and starts all containers with proper network configuration+ */+async function createAndStartContainers(docker: Dockerode, stackId: string, composeData: any, stackDir: string): Promise<void> {+ const services = composeData.services || {};++ // Build dependency order - services with depends_on should start after their dependencies+ const serviceList = buildServiceStartOrder(services);++ for (const serviceName of serviceList) {+ const serviceConfig = services[serviceName];+ console.log(`Creating container for service: ${serviceName}`);++ // Generate container name+ const containerName = serviceConfig.container_name || `${stackId}_${serviceName}`;++ // Check if container already exists+ const existingContainers = await docker.listContainers({+ all: true,+ filters: { name: [containerName] }+ });++ if (existingContainers.length > 0) {+ console.log(`Container ${containerName} already exists. Removing it.`);+ const container = docker.getContainer(existingContainers[0].Id);+ if (existingContainers[0].State === 'running') {+ await container.stop();+ }+ await container.remove();+ }++ // Build container creation options+ const createOptions = await buildContainerOptions(docker, stackId, serviceName, serviceConfig, stackDir, composeData);++ // Create the container+ const container = await docker.createContainer(createOptions);+ console.log(`Created container ${containerName} with ID: ${container.id}`);++ // Connect to additional networks if specified+ if (serviceConfig.networks && !serviceConfig.network_mode) {+ for (const [networkName, networkConfig] of Object.entries(serviceConfig.networks)) {+ // Skip the default network which is already connected+ if (networkName === 'default') continue;++ // Get actual network name+ const actualNetworkName = composeData.networks?.[networkName]?.name || (composeData.networks?.[networkName]?.external ? networkName : `${stackId}_${networkName}`);++ try {+ // Verify network exists before connecting+ const networks = await docker.listNetworks({+ filters: JSON.stringify({ name: [actualNetworkName] })+ });++ if (networks.length === 0) {+ console.warn(`Network ${actualNetworkName} not found, creating it now...`);+ await docker.createNetwork({+ Name: actualNetworkName,+ Driver: 'bridge',+ Labels: {+ 'com.docker.compose.project': stackId,+ 'com.docker.compose.network': networkName+ }+ });+ }++ console.log(`Connecting container ${containerName} to network: ${actualNetworkName}`);+ const network = docker.getNetwork(actualNetworkName);+ await network.connect({+ Container: container.id,+ EndpointConfig: buildEndpointConfig(networkConfig)+ });+ } catch (err) {+ console.error(`Failed to connect container to network ${actualNetworkName}:`, err);+ throw err;+ }+ }+ }++ // Start the container+ console.log(`Starting container: ${containerName}`);+ await container.start();+ }+}++/**+ * Build endpoint configuration for network connection+ */+function buildEndpointConfig(networkConfig: any): any {+ if (!networkConfig) return {};++ const config: any = {};++ // IPv4 address configuration - this is the part that needs fixing+ if (networkConfig.ipv4_address) {+ // Create IPAMConfig structure as required by Docker API+ config.IPAMConfig = config.IPAMConfig || {};+ config.IPAMConfig.IPv4Address = networkConfig.ipv4_address;+ console.log(`Setting static IPv4 address: ${networkConfig.ipv4_address}`);+ }++ // IPv6 address configuration+ if (networkConfig.ipv6_address) {+ config.IPAMConfig = config.IPAMConfig || {};+ config.IPAMConfig.IPv6Address = networkConfig.ipv6_address;+ }++ // DNS aliases - crucial for service discovery+ if (networkConfig.aliases && Array.isArray(networkConfig.aliases)) {+ config.Aliases = networkConfig.aliases;+ }++ // Link-local IPs+ if (networkConfig.link_local_ips && Array.isArray(networkConfig.link_local_ips)) {+ config.IPAMConfig = config.IPAMConfig || {};+ config.IPAMConfig.LinkLocalIPs = networkConfig.link_local_ips;+ }++ return config;+}++/**+ * Builds the optimal service start order based on dependencies+ */+function buildServiceStartOrder(services: Record<string, any>): string[] {+ const visited = new Set<string>();+ const result: string[] = [];++ // DFS function to process services+ function visit(serviceName: string) {+ if (visited.has(serviceName)) return;+ visited.add(serviceName);++ // Process dependencies first+ const deps = services[serviceName]?.depends_on || {};+ if (typeof deps === 'object') {+ // Handle both array format and object format of depends_on+ const depNames = Array.isArray(deps) ? deps : Object.keys(deps);+ for (const dep of depNames) {+ visit(dep);+ }+ }++ result.push(serviceName);+ }++ // Visit all services+ Object.keys(services).forEach(visit);++ return result;+}++/**+ * Builds container creation options from service configuration+ */+async function buildContainerOptions(docker: Dockerode, stackId: string, serviceName: string, serviceConfig: any, stackDir: string, composeData: any): Promise<any> {+ const options: any = {+ name: serviceConfig.container_name || `${stackId}_${serviceName}`,+ Image: serviceConfig.image,+ Tty: serviceConfig.tty || false,+ OpenStdin: serviceConfig.stdin_open || false,+ StopSignal: serviceConfig.stop_signal,+ StopTimeout: serviceConfig.stop_grace_period ? parseInt(serviceConfig.stop_grace_period.replace(/s$/, '')) : undefined,+ Hostname: serviceConfig.hostname || serviceName,+ Domainname: serviceConfig.domainname,+ User: serviceConfig.user,+ WorkingDir: serviceConfig.working_dir,+ Labels: {+ 'com.docker.compose.project': stackId,+ 'com.docker.compose.service': serviceName,+ ...serviceConfig.labels+ }+ };++ // Handle command+ if (serviceConfig.command) {+ if (typeof serviceConfig.command === 'string') {+ options.Cmd = serviceConfig.command.split(/\s+/);+ } else {+ options.Cmd = serviceConfig.command;+ }+ }++ // Handle entrypoint+ if (serviceConfig.entrypoint) {+ if (typeof serviceConfig.entrypoint === 'string') {+ options.Entrypoint = serviceConfig.entrypoint.split(/\s+/);+ } else {+ options.Entrypoint = serviceConfig.entrypoint;+ }+ }++ // Handle environment variables+ if (serviceConfig.environment) {+ options.Env = [];+ if (Array.isArray(serviceConfig.environment)) {+ options.Env = serviceConfig.environment;+ } else {+ for (const [key, value] of Object.entries(serviceConfig.environment)) {+ options.Env.push(`${key}=${value}`);+ }+ }+ }++ // Add .env file variables to container environment+ const envVars = composeData._envVars || {};+ for (const [key, value] of Object.entries(envVars)) {+ // Only add if not already set by service config+ if (!options.Env || !options.Env.some((env: string) => env.startsWith(`${key}=`))) {+ options.Env = options.Env || [];+ options.Env.push(`${key}=${value}`);+ }+ }++ // Handle ports+ if (serviceConfig.ports) {+ options.ExposedPorts = {};+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.PortBindings = {};++ for (const portMapping of serviceConfig.ports) {+ let hostPort, containerPort, protocol;++ if (typeof portMapping === 'string') {+ const parts = portMapping.split(':');+ if (parts.length === 1) {+ containerPort = parts[0];+ hostPort = parts[0];+ } else {+ hostPort = parts[0];+ containerPort = parts[1];+ }++ // Handle protocol specification+ const protocolParts = containerPort.split('/');+ if (protocolParts.length > 1) {+ containerPort = protocolParts[0];+ protocol = protocolParts[1];+ } else {+ protocol = 'tcp';+ }+ } else {+ hostPort = portMapping.published;+ containerPort = portMapping.target;+ protocol = portMapping.protocol || 'tcp';+ }++ const containerPortWithProtocol = `${containerPort}/${protocol}`;+ options.ExposedPorts[containerPortWithProtocol] = {};+ options.HostConfig.PortBindings[containerPortWithProtocol] = [{ HostPort: hostPort.toString() }];+ }+ }++ // Handle volumes+ if (serviceConfig.volumes) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.Binds = [];++ for (const volume of serviceConfig.volumes) {+ let source, target, mode;++ if (typeof volume === 'string') {+ const parts = volume.split(':');+ if (parts.length === 1) {+ // Anonymous volume+ target = parts[0];+ options.Volumes = options.Volumes || {};+ options.Volumes[target] = {};+ continue;+ } else {+ source = parts[0];+ target = parts[1];+ mode = parts[2] || 'rw';+ }+ } else {+ source = volume.source;+ target = volume.target;+ mode = volume.read_only ? 'ro' : 'rw';+ }++ // Handle named volumes vs bind mounts+ if (source.startsWith('.') || source.startsWith('/')) {+ // It's a bind mount - resolve relative paths+ if (source.startsWith('.')) {+ source = path.resolve(stackDir, source);+ }+ } else {+ // It's a named volume+ if (composeData.volumes && composeData.volumes[source]) {+ // Use the full volume name from the volumes section+ const volumeConfig = composeData.volumes[source];+ if (volumeConfig && !volumeConfig.external) {+ source = volumeConfig.name || `${stackId}_${source}`;+ }+ } else {+ // Fallback to default Docker volume naming+ source = `${stackId}_${source}`;+ }+ }++ options.HostConfig.Binds.push(`${source}:${target}:${mode}`);+ }+ }++ // Handle restart policy+ if (serviceConfig.restart) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.RestartPolicy = parseRestartPolicy(serviceConfig.restart);+ }++ // Handle network mode+ if (serviceConfig.network_mode) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.NetworkMode = serviceConfig.network_mode;+ } else if (serviceConfig.networks && Object.keys(serviceConfig.networks).length > 0) {+ // For containers with explicit network configurations+ const defaultNetwork = Object.keys(serviceConfig.networks)[0];+ const networkConfig = composeData.networks?.[defaultNetwork];++ // Get the primary network name+ const networkName = networkConfig?.name || (networkConfig?.external ? defaultNetwork : `${stackId}_${defaultNetwork}`);++ // Set the primary network+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.NetworkMode = networkName;++ // Add advanced network settings for the default network+ if (serviceConfig.networks[defaultNetwork]) {+ const endpointConfig = buildEndpointConfig(serviceConfig.networks[defaultNetwork]);++ // If we have DNS settings for the primary network, add them to NetworkingConfig+ if (Object.keys(endpointConfig).length > 0) {+ options.NetworkingConfig = {+ EndpointsConfig: {+ [networkName]: endpointConfig+ }+ };+ console.log(`Adding network config for primary network ${networkName}:`, endpointConfig);+ }+ }+ } else {+ // No networks specified, use the default network+ const networkName = `${stackId}_default`;+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.NetworkMode = networkName;+ }++ // Handle devices+ if (serviceConfig.devices) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.Devices = serviceConfig.devices.map((device: string) => {+ const parts = device.split(':');+ if (parts.length === 1) {+ return { PathOnHost: parts[0], PathInContainer: parts[0], CgroupPermissions: 'rwm' };+ } else if (parts.length === 2) {+ return { PathOnHost: parts[0], PathInContainer: parts[1], CgroupPermissions: 'rwm' };+ } else {+ return { PathOnHost: parts[0], PathInContainer: parts[1], CgroupPermissions: parts[2] };+ }+ });+ }++ // Handle capabilities+ if (serviceConfig.cap_add || serviceConfig.cap_drop) {+ options.HostConfig = options.HostConfig || {};+ if (serviceConfig.cap_add) {+ options.HostConfig.CapAdd = serviceConfig.cap_add;+ }+ if (serviceConfig.cap_drop) {+ options.HostConfig.CapDrop = serviceConfig.cap_drop;+ }+ }++ // Handle privileged mode+ if (serviceConfig.privileged) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.Privileged = true;+ }++ // Handle healthcheck+ if (serviceConfig.healthcheck) {+ options.Healthcheck = {+ Test: serviceConfig.healthcheck.test,+ Interval: parseTimeString(serviceConfig.healthcheck.interval, 30000000000), // 30s default+ Timeout: parseTimeString(serviceConfig.healthcheck.timeout, 30000000000), // 30s default+ Retries: serviceConfig.healthcheck.retries || 3,+ StartPeriod: parseTimeString(serviceConfig.healthcheck.start_period, 0) // 0 default+ };++ if (serviceConfig.healthcheck.disable === true) {+ options.Healthcheck = { Test: ['NONE'] };+ }+ }++ // Handle logging+ if (serviceConfig.logging) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.LogConfig = {+ Type: serviceConfig.logging.driver || 'json-file',+ Config: serviceConfig.logging.options || {}+ };+ }++ // Handle DNS settings+ if (serviceConfig.dns || serviceConfig.dns_search || serviceConfig.dns_opt) {+ options.HostConfig = options.HostConfig || {};++ // Configure DNS servers+ if (serviceConfig.dns) {+ options.HostConfig.Dns = Array.isArray(serviceConfig.dns) ? serviceConfig.dns : [serviceConfig.dns];+ console.log(`Setting DNS servers for ${serviceName}:`, options.HostConfig.Dns);+ }++ // Configure DNS search domains+ if (serviceConfig.dns_search) {+ options.HostConfig.DnsSearch = Array.isArray(serviceConfig.dns_search) ? serviceConfig.dns_search : [serviceConfig.dns_search];+ console.log(`Setting DNS search domains for ${serviceName}:`, options.HostConfig.DnsSearch);+ }++ // Configure DNS options+ if (serviceConfig.dns_opt) {+ options.HostConfig.DnsOptions = Array.isArray(serviceConfig.dns_opt) ? serviceConfig.dns_opt : [serviceConfig.dns_opt];+ console.log(`Setting DNS options for ${serviceName}:`, options.HostConfig.DnsOptions);+ }+ }++ // Handle extra_hosts (add entries to /etc/hosts)+ if (serviceConfig.extra_hosts) {+ options.HostConfig = options.HostConfig || {};+ options.HostConfig.ExtraHosts = Array.isArray(serviceConfig.extra_hosts) ? serviceConfig.extra_hosts : [serviceConfig.extra_hosts];+ console.log(`Setting extra hosts for ${serviceName}:`, options.HostConfig.ExtraHosts);+ }++ return options;+}++/**+ * Parses a time string to nanoseconds (Docker API format)+ */+function parseTimeString(timeStr: string | undefined, defaultValue: number): number {+ if (!timeStr) return defaultValue;++ const match = timeStr.match(/^(\d+)(ms|s|m|h)$/);+ if (!match) return defaultValue;++ const value = parseInt(match[1]);+ const unit = match[2];++ const multipliers: Record<string, number> = {+ ms: 1000000, // milliseconds to nanoseconds+ s: 1000000000, // seconds to nanoseconds+ m: 60000000000, // minutes to nanoseconds+ h: 3600000000000 // hours to nanoseconds+ };++ return value * multipliers[unit];+}++/**+ * Parses restart policy string to Docker format+ */+function parseRestartPolicy(policy: string): any {+ if (policy === 'no' || policy === 'none') {+ return { Name: 'no' };+ } else if (policy === 'always') {+ return { Name: 'always' };+ } else if (policy === 'unless-stopped') {+ return { Name: 'unless-stopped' };+ } else if (policy.startsWith('on-failure')) {+ const parts = policy.split(':');+ if (parts.length > 1) {+ return { Name: 'on-failure', MaximumRetryCount: parseInt(parts[1]) };+ } else {+ return { Name: 'on-failure' };+ }+ }++ // Default+ return { Name: 'no' };+}++/**+ * Cleans up containers from a failed stack deployment+ */+async function cleanupFailedDeployment(stackId: string): Promise<void> {+ console.log(`Cleaning up containers for failed deployment of stack ${stackId}...`);+ const docker = await getDockerClient();+ const composeProjectLabel = 'com.docker.compose.project';++ try {+ // Find containers belonging to this stack+ const containers = await docker.listContainers({+ all: true,+ filters: JSON.stringify({+ label: [`${composeProjectLabel}=${stackId}`]+ })+ });++ // Also find by name convention as fallback+ const containersByName = await docker.listContainers({+ all: true,+ filters: JSON.stringify({+ name: [`${stackId}_`]+ })+ });++ // Combine the results (removing duplicates)+ const allContainerIds = new Set([...containers.map((c) => c.Id), ...containersByName.map((c) => c.Id)]);++ // Stop and remove all containers+ for (const containerId of allContainerIds) {+ const container = docker.getContainer(containerId);++ try {+ const containerInfo = await container.inspect();+ if (containerInfo.State.Running) {+ console.log(`Stopping container ${containerInfo.Name}...`);+ await container.stop();+ }++ console.log(`Removing container ${containerInfo.Name}...`);+ await container.remove();+ } catch (err) {+ console.warn(`Error cleaning up container ${containerId}:`, err);+ }+ }++ console.log(`Cleanup completed for stack ${stackId}.`);+ } catch (err) {+ console.error(`Error during cleanup of stack ${stackId}:`, err);+ throw err;+ }+}++/**+ * Stops a stack by stopping and removing all containers+ */+export async function stopStack(stackId: string): Promise<boolean> {+ console.log(`Stopping stack ${stackId}...`);+ try {+ await cleanupFailedDeployment(stackId);+ stackCache.delete('compose-stacks');+ return true;+ } catch (err) {+ console.error(`Error stopping stack ${stackId}:`, err);+ throw new Error(`Failed to stop stack: ${err instanceof Error ? err.message : String(err)}`);+ }+}++/**+ * Redeploys a stack by stopping it, pulling images, and redeploying+ */+export async function redeployStack(stackId: string): Promise<boolean> {+ console.log(`Redeploying stack ${stackId}...`);++ try {+ // First stop the stack+ console.log(`Stopping existing stack ${stackId}...`);+ await stopStack(stackId);++ // Pull fresh images+ console.log(`Pulling fresh images for stack ${stackId}...`);+ await pullImagesForStack(stackId);++ // Deploy the stack with fresh images+ console.log(`Deploying stack ${stackId}...`);+ const result = await deployStack(stackId);++ console.log(`Stack ${stackId} has been successfully redeployed`);+ return result;+ } catch (err) {+ console.error(`Error redeploying stack ${stackId}:`, err);+ throw new Error(`Failed to redeploy stack: ${err instanceof Error ? err.message : String(err)}`);+ }+}++/**+ * Restarts all containers in a stack without redeploying+ */+export async function restartStack(stackId: string): Promise<boolean> {+ console.log(`Restarting stack ${stackId}...`);+ const docker = await getDockerClient();+ const composeProjectLabel = 'com.docker.compose.project';++ try {+ // Find containers belonging to this stack+ const containers = await docker.listContainers({+ all: true,+ filters: JSON.stringify({+ label: [`${composeProjectLabel}=${stackId}`]+ })+ });++ // Also find by name convention as fallback+ const containersByName = await docker.listContainers({+ all: true,+ filters: JSON.stringify({+ name: [`${stackId}_`]+ })+ });++ // Combine the results (removing duplicates)+ const allContainerIds = new Set([...containers.map((c) => c.Id), ...containersByName.map((c) => c.Id)]);++ if (allContainerIds.size === 0) {+ console.log(`No containers found for stack ${stackId}, nothing to restart`);+ return false;+ }++ // Restart all containers+ for (const containerId of allContainerIds) {+ const container = docker.getContainer(containerId);++ try {+ const containerInfo = await container.inspect();+ console.log(`Restarting container ${containerInfo.Name}...`);+ await container.restart({ t: 10 }); // 10 second timeout for restart+ } catch (err) {+ console.warn(`Error restarting container ${containerId}:`, err);+ throw err;+ }+ }++ console.log(`Successfully restarted all containers in stack ${stackId}`);+ return true;+ } catch (err) {+ console.error(`Error restarting stack ${stackId}:`, err);+ throw new Error(`Failed to restart stack: ${err instanceof Error ? err.message : String(err)}`);+ }+}++/**+ * Completely destroys a stack, removing containers, networks, and optionally volumes and files+ */+export async function destroyStack(stackId: string, removeVolumes: boolean = false, removeFiles: boolean = false): Promise<boolean> {+ console.log(`Destroying stack ${stackId}${removeVolumes ? ' including volumes' : ''}...`);+ const docker = await getDockerClient();+ const composeProjectLabel = 'com.docker.compose.project';++ try {+ // First stop and remove all containers+ console.log(`Stopping and removing containers for stack ${stackId}...`);+ await cleanupFailedDeployment(stackId);++ // Remove networks+ console.log(`Removing networks for stack ${stackId}...`);+ const networks = await docker.listNetworks({+ filters: JSON.stringify({+ label: [`${composeProjectLabel}=${stackId}`]+ })+ });++ // Also find networks by name convention+ const networksByName = await docker.listNetworks({+ filters: JSON.stringify({+ name: [`${stackId}_`]+ })+ });++ // Combine network results (removing duplicates)+ const allNetworkIds = new Set([...networks.map((n) => n.Id), ...networksByName.map((n) => n.Id)]);++ for (const networkId of allNetworkIds) {+ try {+ const network = docker.getNetwork(networkId);+ const networkInfo = await network.inspect();+ console.log(`Removing network ${networkInfo.Name}...`);+ await network.remove();+ } catch (err) {+ console.warn(`Error removing network ${networkId}:`, err);+ }+ }++ // Remove volumes if requested+ if (removeVolumes) {+ console.log(`Removing volumes for stack ${stackId}...`);+ const volumes = await docker.listVolumes({+ filters: JSON.stringify({+ label: [`${composeProjectLabel}=${stackId}`]+ })+ });++ // Also find volumes by name convention+ const volumesByName =+ (+ await docker.listVolumes({+ filters: JSON.stringify({+ name: [`${stackId}_`]+ })+ })+ ).Volumes || [];++ const allVolumeNames = new Set([...(volumes.Volumes || []).map((v) => v.Name), ...volumesByName.map((v) => v.Name)]);++ for (const volumeName of allVolumeNames) {+ try {+ console.log(`Removing volume ${volumeName}...`);+ await removeVolume(volumeName);+ } catch (err) {+ console.warn(`Error removing volume ${volumeName}:`, err);+ }+ }+ }++ // Remove stack files if requested+ if (removeFiles) {+ console.log(`Removing stack files for ${stackId}...`);+ const stackDir = await getStackDir(stackId);+ try {+ await fs.rm(stackDir, { recursive: true, force: true });+ console.log(`Successfully removed stack directory: ${stackDir}`);+ } catch (err) {+ console.warn(`Error removing stack files at ${stackDir}:`, err);+ // Continue execution - don't fail if files can't be removed+ }+ }++ // Clear cache+ stackCache.delete('compose-stacks');+ console.log(`Stack ${stackId} has been successfully destroyed`);+ return true;+ } catch (err) {+ console.error(`Error destroying stack ${stackId}:`, err);+ throw new Error(`Failed to destroy stack: ${err instanceof Error ? err.message : String(err)}`);+ }+}diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.tsindex de3857479..7ec23b4e2 100644--- a/src/lib/services/docker/stack-service.ts+++ b/src/lib/services/docker/stack-service.ts@@ -91,7 +91,7 @@ export async function ensureStacksDir(): Promise<string> {/*** Returns the stack directory for a given stackId (unchanged)*/-async function getStackDir(stackId: string): Promise<string> {+export async function getStackDir(stackId: string): Promise<string> {const stacksDirAbs = await ensureStacksDir(); // This now returns an absolute pathconst safeId = path.basename(stackId); // Use path.basename for safetyif (safeId !== stackId) {@@ -108,7 +108,7 @@ async function getStackDir(stackId: string): Promise<string> {* Returns the path to the compose file, prioritizing compose.yaml, fallback to docker-compose.yml.* Returns null if neither is found.*/-async function getComposeFilePath(stackId: string): Promise<string | null> {+export async function getComposeFilePath(stackId: string): Promise<string | null> {const stackDirAbs = await getStackDir(stackId); // Will be absoluteconst newPath = path.join(stackDirAbs, 'compose.yaml');const oldPath = path.join(stackDirAbs, 'docker-compose.yml');@@ -153,7 +153,7 @@ async function saveEnvFile(stackId: string, content?: string): Promise<void> {* Loads environment variables from a .env file in the stack directory* Returns empty string if the file doesn't exist*/-async function loadEnvFile(stackId: string): Promise<string> {+export async function loadEnvFile(stackId: string): Promise<string> {const envPath = await getEnvFilePath(stackId);try {@@ -1262,194 +1262,6 @@ export async function stopStack(stackId: string): Promise<boolean> {}}-/**- * The `restartStack` function asynchronously restarts a Docker stack identified by its ID, handling- * errors and returning a boolean indicating success.- * @param {string} stackId - The `stackId` parameter is a string that represents the identifier of the- * stack that you want to restart.- * @returns The `restartStack` function returns a `Promise<boolean>`.- */-export async function restartStack(stackId: string): Promise<boolean> {- const stackDir = await getStackDir(stackId);- const originalCwd = process.cwd();- console.log(`Attempting to restart stack ${stackId}...`);-- try {- const stopped = await stopStack(stackId);- if (!stopped) {- console.error(`Restart failed because stop step failed for stack ${stackId}.`);- return false;- }-- // ---- START: Ensure compose file is normalized before use ----- const composePath = await getComposeFilePath(stackId);- if (!composePath) {- throw new Error(`Compose file not found for stack ${stackId} during restart.`);- }- const currentComposeContent = await fs.readFile(composePath, 'utf8');- const normalizedComposeContent = normalizeHealthcheckTest(currentComposeContent);- if (currentComposeContent !== normalizedComposeContent) {- console.log(`Normalizing healthcheck.test in compose file for stack ${stackId} before restart.`);- await fs.writeFile(composePath, normalizedComposeContent, 'utf8');- }- // ---- END: Ensure compose file is normalized ------ process.chdir(stackDir);- console.log(`Temporarily changed CWD to: ${stackDir} for restarting stack ${stackId}.`);-- console.log(`Starting stack ${stackId} after stopping...`);- const compose = await getComposeInstance(stackId);- await compose.up();- console.log(`Stack ${stackId} started.`);-- // Invalidate the cache after restarting- stackCache.delete('compose-stacks');-- return true;- } catch (err: unknown) {- console.error(`Error restarting stack ${stackId} from directory ${stackDir}:`, err);- const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to restart stack: ${errorMessage}`);- } finally {- process.chdir(originalCwd);- console.log(`Restored CWD to: ${originalCwd}.`);- }-}--/**- * The function `fullyRedployStack` asynchronously stops, pulls latest images, and restarts a- * specified stack, returning true if successful.- * @param {string} stackId - The `stackId` parameter in the `fullyRedeployStack` function is a string- * that represents the identifier of the stack that you want to fully redeploy. This function stops the- * stack, pulls the latest images, and then starts the stack again to ensure a full redeployment of the- * specified- * @returns The `fullyRedeployStack` function returns a `Promise<boolean>`. The function attempts to- * fully redeploy a stack by stopping it, pulling the latest images, and then starting it again. If all- * commands succeed, the function resolves the promise with a value of `true`. If an error occurs- * during the process, the function catches the error, logs it, and then throws a new `- */-export async function fullyRedeployStack(stackId: string): Promise<boolean> {- const stackDir = await getStackDir(stackId);- const originalCwd = process.cwd();- console.log(`Attempting to fully redeploy stack ${stackId}...`);-- try {- const stopped = await stopStack(stackId);- if (!stopped) {- console.error(`Redeploy failed because stop step failed for stack ${stackId}.`);- return false;- }-- // ---- START: Ensure compose file is normalized before use ----- const composePath = await getComposeFilePath(stackId);- if (!composePath) {- throw new Error(`Compose file not found for stack ${stackId} during redeploy.`);- }- const currentComposeContent = await fs.readFile(composePath, 'utf8');- // The normalizeHealthcheckTest function is defined at the end of your file- const normalizedComposeContent = normalizeHealthcheckTest(currentComposeContent);-- // Only write back to disk if the normalization actually changed the content- // This avoids unnecessary file modifications and mtime updates.- if (currentComposeContent !== normalizedComposeContent) {- console.log(`Normalizing healthcheck.test in compose file for stack ${stackId} before redeploy.`);- await fs.writeFile(composePath, normalizedComposeContent, 'utf8');- }- // ---- END: Ensure compose file is normalized ------ process.chdir(stackDir);- console.log(`Temporarily changed CWD to: ${stackDir} for redeploying stack ${stackId}.`);-- console.log(`Pulling images for stack ${stackId}...`);- // getComposeInstance will now read the potentially corrected (normalized) file from disk- const compose = await getComposeInstance(stackId);- await compose.pull();- console.log(`Images pulled for stack ${stackId}.`);-- console.log(`Starting stack ${stackId} after pull...`);- await compose.up(); // This should now use the corrected compose configuration- console.log(`Stack ${stackId} started.`);-- return true;- } catch (err: unknown) {- console.error(`Error fully redeploying stack ${stackId} from directory ${stackDir}:`, err);- const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to fully redeploy stack: ${errorMessage}`);- } finally {- process.chdir(originalCwd);- console.log(`Restored CWD to: ${originalCwd}.`);- }-}--/**- * The function `destroyStack` completely removes a Docker stack by stopping its services,- * removing containers, networks, and deleting all stack files.- * @param {string} stackId - The unique identifier of the stack to destroy- * @returns {Promise<boolean>} - True if the stack was successfully destroyed- */-export async function destroyStack(stackId: string): Promise<boolean> {- console.log(`Attempting to destroy stack ${stackId} (containers and files)...`);- try {- // First stop and remove all containers- const stopped = await stopStack(stackId);- if (!stopped) {- console.error(`Destruction step 1 failed: stop/remove containers failed for stack ${stackId}.`);- // We'll continue anyway to try to remove files- } else {- console.log(`Containers for stack ${stackId} stopped and removed.`);- }-- // Now remove the stack directory- const stackDir = await getStackDir(stackId);- console.log(`Removing stack directory ${stackDir}...`);- try {- await fs.rm(stackDir, { recursive: true, force: true });- console.log(`Stack directory ${stackDir} removed.`);- } catch (rmErr) {- console.error(`Failed to remove stack directory ${stackDir}:`, rmErr);- throw new Error(`Failed to remove stack directory: ${rmErr instanceof Error ? rmErr.message : String(rmErr)}`);- }-- // Invalidate the cache after removing a stack- stackCache.delete('compose-stacks');-- return true;- } catch (err: unknown) {- console.error(`Error destroying stack ${stackId}:`, err);- const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to destroy stack ${stackId}: ${errorMessage}`);- }-}--/**- * The function `removeStack` stops and removes all containers and networks for a stack- * but preserves the stack files for potential redeployment.- * @param {string} stackId - The unique identifier of the stack to remove containers from- * @returns {Promise<boolean>} - True if the stack's containers were successfully removed- */-export async function removeStack(stackId: string): Promise<boolean> {- console.log(`Attempting to remove containers for stack ${stackId} (preserving files)...`);- try {- // Stop and remove all containers- const stopped = await stopStack(stackId);- if (!stopped) {- console.error(`Remove operation failed: stop/remove containers failed for stack ${stackId}.`);- throw new Error(`Failed to stop/remove containers for stack ${stackId}`);- }-- console.log(`Stack ${stackId} containers successfully removed. Stack files preserved.`);-- // Invalidate the cache after container removal- stackCache.delete('compose-stacks');-- return true;- } catch (err: unknown) {- console.error(`Error removing containers for stack ${stackId}:`, err);- const errorMessage = err instanceof Error ? err.message : String(err);- throw new Error(`Failed to remove containers for stack ${stackId}: ${errorMessage}`);- }-}-export async function renameStack(currentStackId: string, newName: string): Promise<Stack> {if (!currentStackId || !newName) {throw new Error('Current stack ID and new name must be provided.');@@ -1815,7 +1627,7 @@ export async function isStackRunning(stackId: string): Promise<boolean> {* @param {function} envGetter - Optional function to get environment variable values.* @returns {string} - The normalized and substituted YAML content.*/-function normalizeHealthcheckTest(composeContent: string, envGetter?: (key: string) => string | undefined): string {+export function normalizeHealthcheckTest(composeContent: string, envGetter?: (key: string) => string | undefined): string {let doc: any; // Use 'any' for easier manipulation, will be validated by yamlLoadtry {doc = yamlLoad(composeContent);@@ -1881,7 +1693,7 @@ function normalizeHealthcheckTest(composeContent: string, envGetter?: (key: stri* @param envGetter Optional function to get environment variable values* @returns Parsed object or null if parsing fails*/-function parseYamlContent(content: string, envGetter?: (key: string) => string | undefined): Record<string, any> | null {+export function parseYamlContent(content: string, envGetter?: (key: string) => string | undefined): Record<string, any> | null {try {// Use js-yaml directly without any potential CommonJS dependenciesconst parsedYaml = yamlLoad(content);diff --git a/src/routes/api/containers/[containerId]/logs/stream/+server.ts b/src/routes/api/containers/[containerId]/logs/stream/+server.tsindex 1e3167d3e..bb285f9d8 100644--- a/src/routes/api/containers/[containerId]/logs/stream/+server.ts+++ b/src/routes/api/containers/[containerId]/logs/stream/+server.ts@@ -1,78 +1,94 @@import { getDockerClient } from '$lib/services/docker/core';-import { json } from '@sveltejs/kit';-import type { RequestHandler } from './$types';-import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';-import { extractDockerErrorMessage } from '$lib/utils/errors.util';-import { tryCatch } from '$lib/utils/try-catch';+import type { RequestHandler } from '@sveltejs/kit';+import type { Readable } from 'stream';++// Define a custom interface for our stream source+interface LogStreamSource extends UnderlyingDefaultSource<Uint8Array> {+ logStream?: Readable;+}export const GET: RequestHandler = async ({ params }) => {- const { containerId } = params;+ if (!params.containerId) {+ return new Response('Container ID is required', { status: 400 });+ }+const docker = await getDockerClient();+ const container = docker.getContainer(params.containerId);- const result = await tryCatch(- (async () => {- const container = docker.getContainer(containerId);+ // Create a ReadableStream with our custom source type+ const stream = new ReadableStream<Uint8Array>({+ async start(controller) {+ try {+ // Get logs stream from Docker+ const logStream = (await container.logs({+ follow: true,+ stdout: true,+ stderr: true,+ timestamps: true+ })) as Readable;- // Check if container exists- const containerInfo = await container.inspect();- const hasTty = containerInfo.Config.Tty === true;+ // Track controller state+ let isControllerClosed = false;- // Create a stream for Server-Sent Events (SSE)- const encoder = new TextEncoder();- const stream = new ReadableStream({- async start(controller) {- try {- const logStream = await container.logs({- follow: true,- stdout: true,- stderr: true,- timestamps: false,- tail: 0- });+ // Set up cleanup for client disconnection+ const cleanup = () => {+ isControllerClosed = true;+ if (logStream && logStream.destroy) {+ logStream.destroy();+ }+ };- logStream.on('data', (chunk) => {- let log;- if (!hasTty) {- log = chunk.slice(8).toString('utf8');- } else {- log = chunk.toString('utf8');- }- controller.enqueue(encoder.encode(`data: ${log}\n\n`));- });+ // Handle Docker stream events+ logStream.on('data', (chunk) => {+ try {+ // Only enqueue if controller is still open+ if (!isControllerClosed) {+ controller.enqueue(chunk);+ }+ } catch (error: any) {+ // Handle "controller closed" errors gracefully+ if (error.code === 'ERR_INVALID_STATE') {+ cleanup();+ } else {+ console.error('Error streaming logs:', error);+ }+ }+ });- logStream.on('end', () => {- controller.close();- });+ logStream.on('end', () => {+ if (!isControllerClosed) {+ controller.close();+ isControllerClosed = true;+ }+ });- logStream.on('error', (err) => {- console.error('Log stream error:', err);- controller.error(err);- });- } catch (err) {- console.error('Error setting up log stream:', err);+ logStream.on('error', (err) => {+ console.error('Docker logs stream error:', err);+ if (!isControllerClosed) {controller.error(err);+ isControllerClosed = true;}- }- });-- return stream;- })()- );+ });- if (result.error) {- console.error('Error streaming container logs:', result.error);+ // Store for cleanup in cancel+ (this as LogStreamSource).logStream = logStream;+ } catch (error) {+ console.error('Error starting logs stream:', error);+ controller.error(error);+ }+ },- const response: ApiErrorResponse = {- success: false,- error: extractDockerErrorMessage(result.error),- code: ApiErrorCode.DOCKER_API_ERROR,- details: result.error- };-- return json(response, { status: 500 });- }+ cancel() {+ // Called when client disconnects+ console.log('Client disconnected from logs stream');+ const self = this as LogStreamSource;+ if (self.logStream && self.logStream.destroy) {+ self.logStream.destroy();+ }+ }+ } as LogStreamSource);- return new Response(result.data, {+ return new Response(stream, {headers: {'Content-Type': 'text/event-stream','Cache-Control': 'no-cache',diff --git a/src/routes/api/stacks/[stackId]/deploy/+server.ts b/src/routes/api/stacks/[stackId]/deploy/+server.tsnew file mode 100644index 000000000..5c6a69a4c--- /dev/null+++ b/src/routes/api/stacks/[stackId]/deploy/+server.ts@@ -0,0 +1,27 @@+import { deployStack } from '$lib/services/docker/stack-custom-service';+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';+import { tryCatch } from '$lib/utils/try-catch';++export const POST: RequestHandler = async ({ params }) => {+ const id = params.stackId;++ const result = await tryCatch(deployStack(id));++ if (result.error) {+ console.error(`API Error starting stack ${id}:`, result.error);+ const response: ApiErrorResponse = {+ success: false,+ error: result.error.message || 'Failed to start stack',+ code: ApiErrorCode.INTERNAL_SERVER_ERROR,+ details: result.error+ };+ return json(response, { status: 500 });+ }++ return json({+ success: true,+ message: `Stack started successfully`+ });+};diff --git a/src/routes/api/stacks/[stackId]/remove/+server.ts b/src/routes/api/stacks/[stackId]/destroy/+server.tssimilarity index 58%rename from src/routes/api/stacks/[stackId]/remove/+server.tsrename to src/routes/api/stacks/[stackId]/destroy/+server.tsindex acfb893b1..7b9015c30 100644--- a/src/routes/api/stacks/[stackId]/remove/+server.ts+++ b/src/routes/api/stacks/[stackId]/destroy/+server.ts@@ -1,11 +1,13 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';-import { removeStack } from '$lib/services/docker/stack-service';+import { destroyStack } from '$lib/services/docker/stack-custom-service';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';-export const DELETE: RequestHandler = async ({ params }) => {+export const DELETE: RequestHandler = async ({ params, url }) => {const id = params.stackId;+ const removeFiles = url.searchParams.get('removeFiles') === 'true';+ const removeVolumes = url.searchParams.get('removeVolumes') === 'true';if (!id) {const response: ApiErrorResponse = {@@ -16,13 +18,14 @@ export const DELETE: RequestHandler = async ({ params }) => {return json(response, { status: 400 });}- const result = await tryCatch(removeStack(id));+ // Pass removeFiles parameter to destroyStack function+ const result = await tryCatch(destroyStack(id, removeVolumes, removeFiles));if (result.error) {- console.error(`API Error removing stack ${id}:`, result.error);+ console.error(`API Error destroying stack ${id}:`, result.error);const response: ApiErrorResponse = {success: false,- error: result.error.message || 'Failed to remove stack',+ error: result.error.message || 'Failed to destroy stack',code: ApiErrorCode.INTERNAL_SERVER_ERROR,details: result.error};@@ -32,7 +35,7 @@ export const DELETE: RequestHandler = async ({ params }) => {if (result.data) {return json({success: true,- message: `Stack removed successfully`+ message: `Stack Destroyed Successfully${removeFiles ? ' (including files)' : ''}`});} else {const response: ApiErrorResponse = {diff --git a/src/routes/api/stacks/[stackId]/start/+server.ts b/src/routes/api/stacks/[stackId]/down/+server.tssimilarity index 85%rename from src/routes/api/stacks/[stackId]/start/+server.tsrename to src/routes/api/stacks/[stackId]/down/+server.tsindex 30a3a5dfc..cfbf623e5 100644--- a/src/routes/api/stacks/[stackId]/start/+server.ts+++ b/src/routes/api/stacks/[stackId]/down/+server.ts@@ -1,4 +1,4 @@-import { startStack } from '$lib/services/docker/stack-service';+import { stopStack } from '$lib/services/docker/stack-custom-service';import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';@@ -7,7 +7,7 @@ import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;- const result = await tryCatch(startStack(id));+ const result = await tryCatch(stopStack(id));if (result.error) {console.error(`API Error starting stack ${id}:`, result.error);diff --git a/src/routes/api/stacks/[stackId]/pull/+server.ts b/src/routes/api/stacks/[stackId]/pull/+server.tsindex caa0efe6c..dd53a9a2c 100644--- a/src/routes/api/stacks/[stackId]/pull/+server.ts+++ b/src/routes/api/stacks/[stackId]/pull/+server.ts@@ -9,7 +9,6 @@ import { getSettings } from '$lib/services/settings-service';import { areRegistriesEquivalent, parseImageNameForRegistry } from '$lib/utils/registry.utils';import { json } from '@sveltejs/kit';-// Define AuthConfig interface (as used by dockerode)interface AuthConfig {username: string;password?: string;diff --git a/src/routes/api/stacks/[stackId]/redeploy/+server.ts b/src/routes/api/stacks/[stackId]/redeploy/+server.tsindex 12628a5d6..c82bfe80a 100644--- a/src/routes/api/stacks/[stackId]/redeploy/+server.ts+++ b/src/routes/api/stacks/[stackId]/redeploy/+server.ts@@ -1,13 +1,13 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';-import { fullyRedeployStack } from '$lib/services/docker/stack-service';+import { redeployStack } from '$lib/services/docker/stack-custom-service';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';export const POST: RequestHandler = async ({ params }) => {const id = params.stackId;- const result = await tryCatch(fullyRedeployStack(id));+ const result = await tryCatch(redeployStack(id));if (result.error) {console.error(`API Error redeploying stack ${id}:`, result.error);diff --git a/src/routes/api/stacks/[stackId]/restart/+server.ts b/src/routes/api/stacks/[stackId]/restart/+server.tsindex dadde257b..891396f41 100644--- a/src/routes/api/stacks/[stackId]/restart/+server.ts+++ b/src/routes/api/stacks/[stackId]/restart/+server.ts@@ -1,6 +1,6 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';-import { restartStack } from '$lib/services/docker/stack-service';+import { restartStack } from '$lib/services/docker/stack-custom-service';import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';import { tryCatch } from '$lib/utils/try-catch';diff --git a/src/routes/api/stacks/[stackId]/stop/+server.ts b/src/routes/api/stacks/[stackId]/stop/+server.tsdeleted file mode 100644index ce4354a68..000000000--- a/src/routes/api/stacks/[stackId]/stop/+server.ts+++ /dev/null@@ -1,36 +0,0 @@-import type { RequestHandler } from './$types';-import { json } from '@sveltejs/kit';-import { stopStack } from '$lib/services/docker/stack-service';-import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';-import { tryCatch } from '$lib/utils/try-catch';--export const POST: RequestHandler = async ({ params }) => {- const id = params.stackId;-- const result = await tryCatch(stopStack(id));-- if (result.error) {- console.error(`API Error stopping stack ${id}:`, result.error);- const response: ApiErrorResponse = {- success: false,- error: result.error.message || 'Failed to stop stack',- code: ApiErrorCode.INTERNAL_SERVER_ERROR,- details: result.error- };- return json(response, { status: 500 });- }-- if (result.data) {- return json({- success: true,- message: `Stack stopped successfully`- });- } else {- const response: ApiErrorResponse = {- success: false,- error: 'Failed to stop stack',- code: ApiErrorCode.INTERNAL_SERVER_ERROR- };- return json(response, { status: 500 });- }-};diff --git a/src/routes/stacks/+page.svelte b/src/routes/stacks/+page.svelteindex a2851e715..d60b25972 100644--- a/src/routes/stacks/+page.svelte+++ b/src/routes/stacks/+page.svelte@@ -47,7 +47,7 @@if (action === 'start') {handleApiResultWithCallbacks({- result: await tryCatch(stackApi.start(id)),+ result: await tryCatch(stackApi.deploy(id)),message: 'Failed to Start Stack',setLoadingState: (value) => (isLoading.start = value),onSuccess: async () => {@@ -216,7 +216,7 @@<UniversalTabledata={stacks}columns={[- { accessorKey: 'name', header: 'Name' },+ { accessorKey: 'Name', header: 'Name' },{ accessorKey: 'serviceCount', header: 'Services' },{ accessorKey: 'status', header: 'Status' },{ accessorKey: 'source', header: 'Source' },diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex ff9423b6f..303c981bc 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -1,7 +1,7 @@-import { getStack, updateStack, startStack, stopStack, restartStack, removeStack, fullyRedeployStack } from '$lib/services/docker/stack-service';+import { getStack } from '$lib/services/docker/stack-service';import { getSettings } from '$lib/services/settings-service';import { getContainer } from '$lib/services/docker/container-service';-import type { PageServerLoad, Actions } from './$types';+import type { PageServerLoad } from './$types';import { tryCatch } from '$lib/utils/try-catch';import type { PortBinding, ContainerInspectInfo } from 'dockerode';@@ -81,92 +81,27 @@ export const load: PageServerLoad = async ({ params }) => {};};-export const actions: 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() || '';- const autoUpdate = formData.get('autoUpdate') === 'on';-- const result = await tryCatch(updateStack(stackId, { name, composeContent, autoUpdate }));- if (!result.error) {- return {- success: true,- message: 'Stack updated successfully'- };- } else {- console.error('Error updating stack:', result.error);- return {- success: false,- error: result.error instanceof Error ? result.error.message : 'Failed to update stack'- };- }- },-- start: async ({ params }) => {- const result = await tryCatch(startStack(params.stackId));- if (!result.error) {- return { success: true };- } else {- console.error('Error starting stack:', result.error);- return {- success: false,- error: result.error instanceof Error ? result.error.message : 'Failed to start stack'- };- }- },-- stop: async ({ params }) => {- const result = await tryCatch(stopStack(params.stackId));- if (!result.error) {- return { success: true };- } else {- console.error('Error stopping stack:', result.error);- return {- success: false,- error: result.error instanceof Error ? result.error.message : 'Failed to stop stack'- };- }- },-- restart: async ({ params }) => {- const result = await tryCatch(restartStack(params.stackId));- if (!result.error) {- return { success: true };- } else {- console.error('Error restarting stack:', result.error);- return {- success: false,- error: result.error instanceof Error ? result.error.message : 'Failed to restart stack'- };- }- },-- remove: async ({ params }) => {- const result = await tryCatch(removeStack(params.stackId));- if (!result.error && result.data) {- return { success: true, message: 'Stack removal initiated' };- } else {- console.error('Error removing stack:', result.error);- return {- success: false,- error: result.error instanceof Error ? result.error.message : 'Failed to remove stack'- };- }- },-- redeploy: async ({ params }) => {- const result = await tryCatch(fullyRedeployStack(params.stackId));- if (!result.error) {- return { success: true, message: 'Stack redeployment initiated' };- } else {- console.error('Error redeploying stack:', result.error);- return {- success: false,- error: result.error instanceof Error ? result.error.message : 'Failed to redeploy stack'- };- }- }-};+// export const actions: 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() || '';+// const autoUpdate = formData.get('autoUpdate') === 'on';++// const result = await tryCatch(updateStack(stackId, { name, composeContent, autoUpdate }));+// if (!result.error) {+// return {+// success: true,+// message: 'Stack updated successfully'+// };+// } else {+// console.error('Error updating stack:', result.error);+// return {+// success: false,+// error: result.error instanceof Error ? result.error.message : 'Failed to update stack'+// };+// }+// }+// };