Skip to content

Modern Docker Management, Designed for Everyone

refactor: reorganize services and types (#71)

Kyle Mendell7079dc1bb28d
diff --git a/.prettierrc b/.prettierrc
index 3862a8e6b..3f31090b2 100644
--- a/.prettierrc
+++ b/.prettierrc
@@ -2,7 +2,7 @@
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
- "printWidth": 600,
+ "printWidth": 450,
"plugins": ["prettier-plugin-svelte"],
"overrides": [
{
diff --git a/src/hooks.server.ts b/src/hooks.server.ts
index ad2bc4ea5..adbb104ed 100644
--- a/src/hooks.server.ts
+++ b/src/hooks.server.ts
@@ -1,4 +1,4 @@
-import { initComposeService } from '$lib/services/compose';
+import { initComposeService } from '$lib/services/docker/stack-service';
// Initialize needed services
initComposeService().catch((err) => {
diff --git a/src/lib/services/docker-service.ts b/src/lib/services/docker-service.ts
deleted file mode 100644
index e4323fc0e..000000000
--- a/src/lib/services/docker-service.ts
+++ /dev/null
@@ -1,810 +0,0 @@
-import Docker from 'dockerode';
-import type { VolumeCreateOptions } from 'dockerode';
-import type { NetworkInspectInfo, NetworkCreateOptions } from 'dockerode';
-import type { DockerConnectionOptions, ContainerConfig, ContainerCreate } from '$lib/types/docker';
-
-let dockerClient: Docker | null = null;
-let dockerHost: string = 'unix:///var/run/docker.sock';
-
-/**
- * Initialize Docker connection with the given options
- * @param options Docker connection options
- */
-export function initializeDocker(options: DockerConnectionOptions): Docker {
- let connectionOpts: any = {};
-
- // Handle different connection types (socket, tcp, etc.)
- if (options.socketPath) {
- connectionOpts.socketPath = options.socketPath;
- dockerHost = options.socketPath;
- } else if (options.host && options.port) {
- connectionOpts.host = options.host;
- connectionOpts.port = options.port;
- dockerHost = `${options.host}:${options.port}`;
-
- if (options.ca || options.cert || options.key) {
- connectionOpts.ca = options.ca;
- connectionOpts.cert = options.cert;
- connectionOpts.key = options.key;
- }
- }
-
- dockerClient = new Docker(connectionOpts);
- return dockerClient;
-}
-
-/**
- * Update the Docker connection with a new host string
- * @param host Docker host connection string
- */
-export function updateDockerConnection(host: string): void {
- try {
- // Only create a new connection if we have a valid host
- if (!host) {
- console.warn('No Docker host specified, connection not established');
- return;
- }
-
- console.log(`Connecting to Docker at ${host}`);
- let connectionOpts: any = {};
-
- // Parse the host string to determine connection type
- if (host.startsWith('unix://')) {
- // Unix socket connection - remove the unix:// prefix
- connectionOpts.socketPath = host.replace('unix://', '');
- } else if (host.startsWith('tcp://')) {
- // TCP connection (no TLS)
- const url = new URL(host);
- connectionOpts.host = url.hostname;
- connectionOpts.port = parseInt(url.port || '2375', 10);
- } else if (host.startsWith('https://')) {
- // HTTPS connection (TLS)
- const url = new URL(host);
- connectionOpts.host = url.hostname;
- connectionOpts.port = parseInt(url.port || '2376', 10);
- connectionOpts.protocol = 'https';
- } else {
- // If it doesn't have a prefix, assume it's a direct socket path
- connectionOpts.socketPath = host;
- }
-
- dockerClient = new Docker(connectionOpts);
- dockerHost = host;
- console.log('Docker connection updated with options:', connectionOpts);
- } catch (error) {
- console.error('Error connecting to Docker:', error);
- }
-}
-
-/**
- * Get the Docker client instance. Initialize with default options if not already initialized.
- */
-export function getDockerClient(): Docker {
- if (!dockerClient) {
- let connectionOpts: any = {};
-
- // Parse the dockerHost to get the proper connection options
- if (dockerHost.startsWith('unix://')) {
- connectionOpts.socketPath = dockerHost.replace('unix://', '');
- } else if (dockerHost.startsWith('tcp://')) {
- const url = new URL(dockerHost);
- connectionOpts.host = url.hostname;
- connectionOpts.port = parseInt(url.port || '2375', 10);
- } else if (dockerHost.startsWith('https://')) {
- const url = new URL(dockerHost);
- connectionOpts.host = url.hostname;
- connectionOpts.port = parseInt(url.port || '2376', 10);
- connectionOpts.protocol = 'https';
- } else {
- // If it doesn't have a prefix, assume it's a direct socket path
- connectionOpts.socketPath = dockerHost;
- }
-
- dockerClient = new Docker(connectionOpts);
- console.log(`Initialized Docker client with host: ${dockerHost}`, connectionOpts);
- }
- return dockerClient;
-}
-
-/**
- * Test Docker connection
- * @returns Promise resolving to true if connection is successful
- */
-export async function testDockerConnection(): Promise<boolean> {
- try {
- 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;
- names: string[];
- name: string; // Your derived name
- image: string;
- imageId: string;
- command: string;
- created: number;
- state: string; // 'created', 'running', 'paused', 'restarting', 'removing', 'exited', 'dead'
- status: string; // e.g., "Up 2 hours"
- ports: Docker.Port[];
-};
-
-/**
- * Lists Docker containers.
- */
-export async function listContainers(all = true): Promise<ServiceContainer[]> {
- try {
- const docker = getDockerClient();
- const containers = await docker.listContainers({ all });
- return containers.map(
- (c): ServiceContainer => ({
- id: c.Id,
- names: c.Names,
- name: c.Names[0]?.substring(1) || c.Id.substring(0, 12),
- image: c.Image,
- imageId: c.ImageID,
- command: c.Command,
- created: c.Created,
- state: c.State,
- status: c.Status,
- ports: c.Ports
- })
- );
- } catch (error: any) {
- console.error('Docker Service: Error listing containers:', error);
- throw new Error(`Failed to list Docker containers using host "${dockerHost}".`);
- }
-}
-
-/**
- * Gets details for a specific container.
- */
-export async function getContainer(containerId: string) {
- try {
- const docker = getDockerClient();
- const container = docker.getContainer(containerId);
- const inspectData = await container.inspect();
- return {
- id: inspectData.Id,
- name: inspectData.Name.substring(1),
- created: inspectData.Created,
- path: inspectData.Path,
- args: inspectData.Args,
- state: inspectData.State,
- image: inspectData.Image,
- config: inspectData.Config,
- networkSettings: inspectData.NetworkSettings,
- mounts: inspectData.Mounts
- };
- } catch (error: any) {
- console.error(`Docker Service: Error getting container ${containerId}:`, error);
- if (error.statusCode === 404) {
- return null;
- }
- throw new Error(`Failed to get container details for ${containerId} using host "${dockerHost}".`);
- }
-}
-
-/**
- * Starts a specific container.
- * @param containerId - The ID of the container.
- */
-export async function startContainer(containerId: string): Promise<void> {
- try {
- const docker = getDockerClient();
- const container = docker.getContainer(containerId);
- await container.start();
- } catch (error: any) {
- console.error(`Docker Service: Error starting container ${containerId}:`, error);
- throw new Error(`Failed to start container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
- }
-}
-
-/**
- * Stops a specific container.
- * @param containerId - The ID of the container.
- */
-export async function stopContainer(containerId: string): Promise<void> {
- try {
- const docker = getDockerClient();
- const container = docker.getContainer(containerId);
- await container.stop();
- } catch (error: any) {
- console.error(`Docker Service: Error stopping container ${containerId}:`, error);
- throw new Error(`Failed to stop container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
- }
-}
-
-/**
- * Restarts a specific container.
- * @param containerId - The ID of the container.
- */
-export async function restartContainer(containerId: string): Promise<void> {
- try {
- const docker = getDockerClient();
- const container = docker.getContainer(containerId);
- await container.restart();
- } catch (error: any) {
- console.error(`Docker Service: Error restarting container ${containerId}:`, error);
- throw new Error(`Failed to restart container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
- }
-}
-
-/**
- * Removes a specific container.
- * @param containerId - The ID of the container.
- * @param force - Force removal even if running (default: false).
- */
-export async function removeContainer(containerId: string, force = false): Promise<void> {
- try {
- const docker = getDockerClient();
- const container = docker.getContainer(containerId);
- await container.remove({ force });
- } catch (error: any) {
- console.error(`Docker Service: Error removing container ${containerId}:`, error);
- if (error.statusCode === 404) {
- throw new Error(`Container ${containerId} not found.`);
- }
- if (error.statusCode === 409) {
- throw new Error(`Cannot remove running container ${containerId}. Stop it first or use force.`);
- }
- throw new Error(`Failed to remove container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
- }
-}
-
-/**
- * Retrieves logs from a specific Docker container.
- *
- * @param containerId - The ID of the container to fetch logs from.
- * @param options - Optional log retrieval settings, including tail count, time range, streaming, and output selection.
- * @returns The container logs as a string, with Docker stream headers removed.
- *
- * @throws {Error} If log retrieval fails for the specified container.
- */
-export async function getContainerLogs(
- containerId: string,
- options: {
- tail?: number | 'all';
- since?: number;
- until?: number;
- follow?: boolean;
- stdout?: boolean;
- stderr?: boolean;
- } = {}
-): Promise<string> {
- try {
- const docker = getDockerClient();
- const container = docker.getContainer(containerId);
-
- const logOptions = {
- tail: options.tail === 'all' ? undefined : options.tail || 100,
- stdout: options.stdout !== false,
- stderr: options.stderr !== false,
- timestamps: true,
- since: options.since || 0,
- until: options.until || undefined
- };
-
- const logsBuffer = options.follow === true ? await container.logs({ ...logOptions, follow: true }) : await container.logs({ ...logOptions, follow: false });
- let logString = logsBuffer.toString();
-
- if (logOptions.stdout || logOptions.stderr) {
- const lines = logString.split('\n');
- const processedLines = lines
- .map((line) => {
- if (!line) return '';
- if (line.length > 8) {
- return line.substring(8);
- }
- return line;
- })
- .filter(Boolean);
-
- logString = processedLines.join('\n');
- }
-
- return logString;
- } catch (error: any) {
- console.error(`Docker Service: Error getting logs for container ${containerId}:`, error);
- throw new Error(`Failed to get logs for container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
- }
-}
-
-/**
- * Creates and starts a new Docker container using the specified configuration.
- *
- * @param config - The container configuration, including image, environment variables, ports, volumes, restart policy, and network.
- * @returns An object containing the created container's ID, name, state, status, and creation timestamp.
- *
- * @throws {Error} If the container cannot be created or started.
- */
-export async function createContainer(config: ContainerConfig) {
- try {
- const docker = getDockerClient();
-
- const containerOptions: ContainerCreate = {
- name: config.name,
- Image: config.image,
- Env: config.envVars?.map((env) => `${env.key}=${env.value}`) || [],
- Labels: config.labels || {},
- Cmd: config.command,
- User: config.user,
- Healthcheck: config.healthcheck
- ? {
- Test: config.healthcheck.Test,
- Interval: config.healthcheck.Interval,
- Timeout: config.healthcheck.Timeout,
- Retries: config.healthcheck.Retries,
- StartPeriod: config.healthcheck.StartPeriod
- }
- : undefined,
- HostConfig: {
- RestartPolicy: {
- Name: config.restart || 'no'
- },
- Memory: config.memoryLimit,
- NanoCpus: config.cpuLimit ? Math.round(config.cpuLimit * 1_000_000_000) : undefined
- }
- };
-
- // Set up port bindings if provided
- if (config.ports && config.ports.length > 0) {
- containerOptions.ExposedPorts = {};
- containerOptions.HostConfig = containerOptions.HostConfig || {};
- containerOptions.HostConfig.PortBindings = {};
-
- config.ports.forEach((port) => {
- const containerPort = `${port.containerPort}/tcp`;
- containerOptions.ExposedPorts![containerPort] = {};
- containerOptions.HostConfig!.PortBindings![containerPort] = [{ HostPort: port.hostPort }];
- });
- }
-
- // Set up volume mounts if provided
- if (config.volumes && config.volumes.length > 0) {
- containerOptions.HostConfig = containerOptions.HostConfig || {};
- containerOptions.HostConfig.Binds = config.volumes.map((vol) => `${vol.source}:${vol.target}${vol.readOnly ? ':ro' : ''}`);
- }
-
- // Set up network if provided
- if (config.network) {
- containerOptions.HostConfig = containerOptions.HostConfig || {};
- if (!containerOptions.NetworkingConfig) {
- containerOptions.HostConfig.NetworkMode = config.network;
- }
-
- if (config.networkConfig && config.network !== 'host' && config.network !== 'none' && config.network !== 'bridge') {
- containerOptions.NetworkingConfig = {
- EndpointsConfig: {
- [config.network]: {
- IPAMConfig: {
- IPv4Address: config.networkConfig.ipv4Address || undefined,
- IPv6Address: config.networkConfig.ipv6Address || undefined
- }
- }
- }
- };
- delete containerOptions.HostConfig.NetworkMode;
- }
- }
-
- // Create and start the container
- const container = await docker.createContainer(containerOptions);
- await container.start();
-
- // Get the container details
- const containerInfo = await container.inspect();
-
- return {
- id: containerInfo.Id,
- name: containerInfo.Name.substring(1),
- state: containerInfo.State.Status,
- status: containerInfo.State.Running ? 'running' : 'stopped',
- created: containerInfo.Created
- };
- } catch (error: any) {
- console.error('Error creating container:', error);
- if (error.message && error.message.includes('IPAMConfig')) {
- throw new Error(`Failed to create container: Invalid IP address configuration for network "${config.network}". ${error.message}`);
- }
- // Add more specific error handling for resource limits if needed
- if (error.message && error.message.includes('NanoCpus')) {
- throw new Error(`Invalid CPU limit specified: ${error.message}`);
- }
- if (error.message && error.message.includes('Memory')) {
- throw new Error(`Invalid Memory limit specified: ${error.message}`);
- }
- throw new Error(`Failed to create container with image "${config.image}": ${error.message}`);
- }
-}
-
-// Define and export the type returned by listImages
-export type ServiceImage = {
- id: string;
- repoTags: string[] | undefined;
- repoDigests: string[] | undefined;
- created: number;
- size: number;
- virtualSize: number;
- labels: { [label: string]: string } | undefined;
- repo: string;
- tag: string;
-};
-
-/**
- * Lists Docker images.
- */
-export async function listImages(): Promise<ServiceImage[]> {
- try {
- const docker = getDockerClient();
- const images = await docker.listImages({ all: false });
-
- const parseRepoTag = (tag: string | undefined): { repo: string; tag: string } => {
- if (!tag || tag === '<none>:<none>') {
- return { repo: '<none>', tag: '<none>' };
- }
- const parts = tag.split(':');
- if (parts.length === 1) {
- return { repo: parts[0], tag: 'latest' };
- }
- const tagPart = parts.pop() || 'latest';
- const repoPart = parts.join(':');
- return { repo: repoPart, tag: tagPart };
- };
-
- return images.map((img): ServiceImage => {
- const { repo, tag } = parseRepoTag(img.RepoTags?.[0]);
- return {
- id: img.Id,
- repoTags: img.RepoTags,
- repoDigests: img.RepoDigests,
- created: img.Created,
- size: img.Size,
- virtualSize: img.VirtualSize,
- labels: img.Labels,
- repo: repo,
- tag: tag
- };
- });
- } catch (error: any) {
- console.error('Docker Service: Error listing images:', error);
- throw new Error(`Failed to list Docker images using host "${dockerHost}".`);
- }
-}
-
-/**
- * Removes a Docker image.
- * @param imageId - The ID or name of the image to remove.
- * @param force - Whether to force removal (default: false).
- */
-export async function removeImage(imageId: string, force: boolean = false): Promise<void> {
- try {
- const docker = getDockerClient();
- const image = docker.getImage(imageId);
- await image.remove({ force });
- console.log(`Docker Service: Image "${imageId}" removed successfully.`);
- } catch (error: any) {
- console.error(`Docker Service: Error removing image "${imageId}":`, error);
- if (error.statusCode === 409) {
- throw new Error(`Image "${imageId}" is being used by a container. Use force option to remove.`);
- }
- throw new Error(`Failed to remove image "${imageId}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
- }
-}
-
-/**
- * Check if an image is used by any container
- * @param imageId The image ID or reference to check
- * @returns Boolean indicating if the image is in use
- */
-export async function isImageInUse(imageId: string): Promise<boolean> {
- try {
- const docker = getDockerClient();
- const containers = await docker.listContainers({ all: true });
-
- // Look for containers using this image
- return containers.some((container) => container.ImageID === imageId || container.Image === imageId);
- } catch (error) {
- console.error(`Error checking if image ${imageId} is in use:`, error);
- // Default to assuming it's in use for safety
- return true;
- }
-}
-
-/**
- * Prunes unused Docker images.
- * @param mode - Mode of pruning ('all' or 'dangling').
- * @returns Information about reclaimed space.
- */
-export async function pruneImages(mode: 'all' | 'dangling' = 'all'): Promise<{
- ImagesDeleted: Docker.ImageRemoveInfo[] | null;
- SpaceReclaimed: number;
-}> {
- try {
- const docker = getDockerClient();
- const filterValue = mode === 'all' ? 'false' : 'true';
- const logMessage = mode === 'all' ? 'Pruning all unused images (docker image prune -a)...' : 'Pruning dangling images (docker image prune)...';
-
- console.log(`Docker Service: ${logMessage}`);
-
- const pruneOptions = {
- filters: { dangling: [filterValue] }
- };
-
- const result = await docker.pruneImages(pruneOptions); // Use the options object
-
- console.log(`Docker Service: Image prune complete. Space reclaimed: ${result.SpaceReclaimed}`);
- return result;
- } catch (error: any) {
- console.error('Docker Service: Error pruning images:', error);
- throw new Error(`Failed to prune images using host "${dockerHost}". ${error.message || error.reason || ''}`);
- }
-}
-
-// Define and export the type returned by listNetworks
-export type ServiceNetwork = {
- id: string;
- name: string;
- driver: string;
- scope: string;
- subnet: string | null;
- gateway: string | null;
- created: string;
-};
-
-/**
- * Lists Docker networks.
- */
-export async function listNetworks(): Promise<ServiceNetwork[]> {
- try {
- const docker = getDockerClient();
- const networks = await docker.listNetworks();
- return networks.map(
- (net): ServiceNetwork => ({
- id: net.Id,
- name: net.Name,
- driver: net.Driver,
- scope: net.Scope,
- subnet: net.IPAM?.Config?.[0]?.Subnet ?? null,
- gateway: net.IPAM?.Config?.[0]?.Gateway ?? null,
- created: net.Created
- })
- );
- } catch (error: any) {
- console.error('Docker Service: Error listing networks:', error);
- throw new Error(`Failed to list Docker networks using host "${dockerHost}".`);
- }
-}
-
-/**
- * Removes a Docker network.
- * @param networkId - The ID or name of the network to remove.
- */
-export async function removeNetwork(networkId: string): Promise<void> {
- try {
- const DEFAULT_NETWORKS = new Set(['host', 'bridge', 'none', 'ingress']);
- if (DEFAULT_NETWORKS.has(networkId)) {
- throw new Error(`Network "${networkId}" is managed by Docker and cannot be removed.`);
- }
- const docker = getDockerClient();
- const network = docker.getNetwork(networkId);
- await network.remove();
- console.log(`Docker Service: Network "${networkId}" removed successfully.`);
- } catch (error: any) {
- console.error(`Docker Service: Error removing network "${networkId}":`, error);
- if (error.statusCode === 404) {
- throw new Error(`Network "${networkId}" not found.`);
- }
- if (error.statusCode === 409) {
- // 409 Conflict usually means it's in use or predefined
- throw new Error(`Network "${networkId}" cannot be removed (possibly in use or predefined).`);
- }
- throw new Error(`Failed to remove network "${networkId}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
- }
-}
-
-/**
- * Creates a Docker network.
- * @param options - Options for creating the network (e.g., Name, Driver, Labels, CheckDuplicate, Internal, IPAM).
- */
-export async function createNetwork(options: NetworkCreateOptions): Promise<NetworkInspectInfo> {
- try {
- const docker = getDockerClient();
- console.log(`Docker Service: Creating network "${options.Name}"...`, options);
-
- // Dockerode's createNetwork returns the Network object, we need to inspect it after creation
- const network = await docker.createNetwork(options);
-
- // Inspect the newly created network to get full details
- const inspectInfo = await network.inspect();
-
- console.log(`Docker Service: Network "${options.Name}" (ID: ${inspectInfo.Id}) created successfully.`);
- return inspectInfo; // Return the detailed inspect info
- } catch (error: any) {
- console.error(`Docker Service: Error creating network "${options.Name}":`, error);
- // Check for specific Docker errors
- if (error.statusCode === 409) {
- // Could be duplicate name if CheckDuplicate was true, or other conflicts
- throw new Error(`Network "${options.Name}" may already exist or conflict with an existing configuration.`);
- }
- throw new Error(`Failed to create network "${options.Name}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
- }
-}
-
-// Define and export the type returned by listVolumes
-export type ServiceVolume = {
- name: string;
- driver: string;
- scope: string;
- mountpoint: string;
- labels: { [label: string]: string } | null;
-};
-
-/**
- * Lists Docker volumes.
- */
-export async function listVolumes(): Promise<ServiceVolume[]> {
- try {
- const docker = getDockerClient();
- const volumeResponse = await docker.listVolumes();
- const volumes = volumeResponse.Volumes || [];
-
- return volumes.map(
- (vol): ServiceVolume => ({
- name: vol.Name,
- driver: vol.Driver,
- scope: vol.Scope,
- mountpoint: vol.Mountpoint,
- labels: vol.Labels
- })
- );
- } catch (error: any) {
- console.error('Docker Service: Error listing volumes:', error);
- throw new Error(`Failed to list Docker volumes using host "${dockerHost}".`);
- }
-}
-
-/**
- * Check if a volume is in use by any container
- * @param volumeName The name of the volume to check
- * @returns Boolean indicating if the volume is in use
- */
-export async function isVolumeInUse(volumeName: string): Promise<boolean> {
- try {
- const docker = getDockerClient();
- const containers = await docker.listContainers({ all: true });
-
- // Inspect each container to check its mounts
- for (const containerInfo of containers) {
- const container = docker.getContainer(containerInfo.Id);
- const details = await container.inspect();
-
- // Check if any mount points to our volume
- const volumeMounts = details.Mounts.filter((mount) => mount.Type === 'volume' && mount.Name === volumeName);
-
- if (volumeMounts.length > 0) {
- return true;
- }
- }
-
- return false;
- } catch (error) {
- console.error(`Error checking if volume ${volumeName} is in use:`, error);
- // Default to assuming it's in use for safety
- return true;
- }
-}
-
-/**
- * Creates a Docker volume.
- * @param options - Options for creating the volume (e.g., Name, Driver, Labels).
- */
-export async function createVolume(options: VolumeCreateOptions): Promise<any> {
- try {
- const docker = getDockerClient();
- // createVolume returns the volume data directly - no need to inspect
- const volume = await docker.createVolume(options);
-
- console.log(`Docker Service: Volume "${options.Name}" created successfully.`);
-
- // Return the creation response which contains basic info
- return {
- Name: volume.Name,
- Driver: volume.Driver,
- Mountpoint: volume.Mountpoint,
- Labels: volume.Labels || {},
- Scope: volume.Scope || 'local',
- CreatedAt: new Date().toISOString() // Since inspect would give us this
- };
- } catch (error: any) {
- console.error(`Docker Service: Error creating volume "${options.Name}":`, error);
- // Check for specific Docker errors, like volume already exists (often 409)
- if (error.statusCode === 409) {
- throw new Error(`Volume "${options.Name}" already exists.`);
- }
- throw new Error(
- `Failed to create volume "${options.Name}" using host "${dockerHost}". ${
- error.message || error.reason || '' // Include reason if available
- }`
- );
- }
-}
-
-/**
- * Removes a Docker volume.
- * @param name - The name of the volume to remove.
- * @param force - Whether to force removal if the volume is in use.
- */
-export async function removeVolume(name: string, force: boolean = false): Promise<void> {
- try {
- const docker = getDockerClient();
- const volume = docker.getVolume(name);
- await volume.remove({ force });
- console.log(`Docker Service: Volume "${name}" removed successfully.`);
- } catch (error: any) {
- console.error(`Docker Service: Error removing volume "${name}":`, error);
- if (error.statusCode === 409) {
- throw new Error(`Volume "${name}" is in use by a container. Use force option to remove.`);
- }
- throw new Error(`Failed to remove volume "${name}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
- }
-}
-
-/**
- * Pulls a Docker image from a registry.
- * @param imageRef - The image reference to pull (e.g., 'nginx:latest')
- * @param platform - Optional platform specification (e.g., 'linux/amd64')
- */
-export async function pullImage(imageRef: string, platform?: string): Promise<void> {
- try {
- const docker = getDockerClient();
-
- const pullOptions: any = {};
- if (platform) {
- pullOptions.platform = platform;
- }
-
- console.log(`Docker Service: Pulling image "${imageRef}"...`);
-
- // Pull the image - this returns a stream
- const stream = await docker.pull(imageRef, pullOptions);
-
- // Wait for the pull to complete by consuming the stream
- await new Promise((resolve, reject) => {
- docker.modem.followProgress(stream, (err: any, output: any) => {
- if (err) {
- reject(err);
- } else {
- resolve(output);
- }
- });
- });
-
- console.log(`Docker Service: Image "${imageRef}" pulled successfully.`);
- } catch (error: any) {
- console.error(`Docker Service: Error pulling image "${imageRef}":`, error);
-
- // Handle specific error cases
- if (error.statusCode === 404) {
- throw new Error(`Image "${imageRef}" not found in registry.`);
- }
-
- throw new Error(`Failed to pull image "${imageRef}". ${error.message || error.reason || ''}`);
- }
-}
-
-export default getDockerClient;
diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.ts
new file mode 100644
index 000000000..b1068584e
--- /dev/null
+++ b/src/lib/services/docker/container-service.ts
@@ -0,0 +1,326 @@
+import { getDockerClient, dockerHost } from './core';
+import type { ContainerConfig, ContainerCreate } from '$lib/types/docker';
+import type { ServiceContainer } from '$lib/types/docker/container.type';
+
+/**
+ * This TypeScript function lists Docker containers and returns an array of ServiceContainer objects.
+ * @param [all=true] - The `all` parameter in the `listContainers` function is a boolean parameter that
+ * determines whether to list all containers or only running containers. When `all` is set to `true`,
+ * all containers (including stopped containers) will be listed. If `all` is set to `false`, only
+ * @returns The `listContainers` function returns a Promise that resolves to an array of
+ * `ServiceContainer` objects. Each `ServiceContainer` object contains properties such as `id`,
+ * `names`, `name`, `image`, `imageId`, `command`, `created`, `state`, `status`, and `ports`, which are
+ * extracted from the Docker containers retrieved using the Docker client.
+ */
+export async function listContainers(all = true): Promise<ServiceContainer[]> {
+ try {
+ const docker = getDockerClient();
+ const containers = await docker.listContainers({ all });
+ return containers.map(
+ (c): ServiceContainer => ({
+ id: c.Id,
+ names: c.Names,
+ name: c.Names[0]?.substring(1) || c.Id.substring(0, 12),
+ image: c.Image,
+ imageId: c.ImageID,
+ command: c.Command,
+ created: c.Created,
+ state: c.State,
+ status: c.Status,
+ ports: c.Ports
+ })
+ );
+ } catch (error: any) {
+ console.error('Docker Service: Error listing containers:', error);
+ throw new Error(`Failed to list Docker containers using host "${dockerHost}".`);
+ }
+}
+
+/**
+ * This TypeScript function retrieves details of a Docker container by its ID and handles errors
+ * appropriately.
+ * @param {string} containerId - The `getContainer` function you provided is an asynchronous function
+ * that retrieves information about a Docker container based on the `containerId` provided as a
+ * parameter. The function uses the Docker API to inspect the container and return relevant details.
+ * @returns The function `getContainer` returns an object containing various details of the Docker
+ * container with the specified `containerId`. The object includes properties such as `id`, `name`,
+ * `created`, `path`, `args`, `state`, `image`, `config`, `networkSettings`, and `mounts`. If an error
+ * occurs during the process, it will be caught and handled accordingly. If the
+ */
+export async function getContainer(containerId: string) {
+ try {
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
+ const inspectData = await container.inspect();
+ return {
+ id: inspectData.Id,
+ name: inspectData.Name.substring(1),
+ created: inspectData.Created,
+ path: inspectData.Path,
+ args: inspectData.Args,
+ state: inspectData.State,
+ image: inspectData.Image,
+ config: inspectData.Config,
+ networkSettings: inspectData.NetworkSettings,
+ mounts: inspectData.Mounts
+ };
+ } catch (error: any) {
+ console.error(`Docker Service: Error getting container ${containerId}:`, error);
+ if (error.statusCode === 404) {
+ return null;
+ }
+ throw new Error(`Failed to get container details for ${containerId} using host "${dockerHost}".`);
+ }
+}
+
+/**
+ * The function `startContainer` asynchronously starts a Docker container using its ID and handles any
+ * errors that may occur.
+ * @param {string} containerId - The `containerId` parameter is a string that represents the unique
+ * identifier of the Docker container that you want to start.
+ */
+export async function startContainer(containerId: string): Promise<void> {
+ try {
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
+ await container.start();
+ } catch (error: any) {
+ console.error(`Docker Service: Error starting container ${containerId}:`, error);
+ throw new Error(`Failed to start container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
+ }
+}
+
+/**
+ * The function `stopContainer` stops a Docker container using its ID and handles any errors that may
+ * occur.
+ * @param {string} containerId - The `containerId` parameter is a string that represents the unique
+ * identifier of the Docker container that you want to stop.
+ */
+export async function stopContainer(containerId: string): Promise<void> {
+ try {
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
+ await container.stop();
+ } catch (error: any) {
+ console.error(`Docker Service: Error stopping container ${containerId}:`, error);
+ throw new Error(`Failed to stop container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
+ }
+}
+
+/**
+ * The function restarts a Docker container using its ID.
+ * @param {string} containerId - The `containerId` parameter is a string that represents the unique
+ * identifier of the Docker container that you want to restart.
+ */
+export async function restartContainer(containerId: string): Promise<void> {
+ try {
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
+ await container.restart();
+ } catch (error: any) {
+ console.error(`Docker Service: Error restarting container ${containerId}:`, error);
+ throw new Error(`Failed to restart container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
+ }
+}
+
+/**
+ * The function `removeContainer` asynchronously removes a Docker container by its ID, with an option
+ * to force removal if necessary.
+ * @param {string} containerId - The `containerId` parameter is a string that represents the unique
+ * identifier of the container that you want to remove. It is used to identify the specific container
+ * within the Docker environment.
+ * @param [force=false] - The `force` parameter in the `removeContainer` function is a boolean
+ * parameter that determines whether to forcefully remove the container if it is currently running. If
+ * `force` is set to `true`, the container will be removed even if it is running. If `force` is set to
+ * `false
+ */
+export async function removeContainer(containerId: string, force = false): Promise<void> {
+ try {
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
+ await container.remove({ force });
+ } catch (error: any) {
+ console.error(`Docker Service: Error removing container ${containerId}:`, error);
+ if (error.statusCode === 404) {
+ throw new Error(`Container ${containerId} not found.`);
+ }
+ if (error.statusCode === 409) {
+ throw new Error(`Cannot remove running container ${containerId}. Stop it first or use force.`);
+ }
+ throw new Error(`Failed to remove container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
+ }
+}
+
+/**
+ * This TypeScript function retrieves logs from a Docker container based on specified options.
+ * @param {string} containerId - The `containerId` parameter is a string that represents the unique
+ * identifier of the container for which you want to retrieve logs.
+ * @param options - - `tail`: Number of lines to show from the end of the logs, or 'all' to show all
+ * logs.
+ * @returns The function `getContainerLogs` returns a Promise that resolves to a string containing the
+ * logs of the specified Docker container based on the provided options.
+ */
+export async function getContainerLogs(
+ containerId: string,
+ options: {
+ tail?: number | 'all';
+ since?: number;
+ until?: number;
+ follow?: boolean;
+ stdout?: boolean;
+ stderr?: boolean;
+ } = {}
+): Promise<string> {
+ try {
+ const docker = getDockerClient();
+ const container = docker.getContainer(containerId);
+
+ const logOptions = {
+ tail: options.tail === 'all' ? undefined : options.tail || 100,
+ stdout: options.stdout !== false,
+ stderr: options.stderr !== false,
+ timestamps: true,
+ since: options.since || 0,
+ until: options.until || undefined
+ };
+
+ const logsBuffer = options.follow === true ? await container.logs({ ...logOptions, follow: true }) : await container.logs({ ...logOptions, follow: false });
+ let logString = logsBuffer.toString();
+
+ if (logOptions.stdout || logOptions.stderr) {
+ const lines = logString.split('\n');
+ const processedLines = lines
+ .map((line) => {
+ if (!line) return '';
+ if (line.length > 8) {
+ return line.substring(8);
+ }
+ return line;
+ })
+ .filter(Boolean);
+
+ logString = processedLines.join('\n');
+ }
+
+ return logString;
+ } catch (error: any) {
+ console.error(`Docker Service: Error getting logs for container ${containerId}:`, error);
+ throw new Error(`Failed to get logs for container ${containerId} using host "${dockerHost}". ${error.message || ''}`);
+ }
+}
+
+/**
+ * The function `createContainer` in TypeScript creates a Docker container based on the provided
+ * configuration and returns information about the created container.
+ * @param {ContainerConfig} config - The `config` parameter in the `createContainer` function is an
+ * object that contains various properties used to configure and create a Docker container. Here are
+ * the properties that can be included in the `config` object:
+ * @returns The `createContainer` function returns an object with the following properties:
+ * - `id`: The ID of the created container
+ * - `name`: The name of the container
+ * - `state`: The status of the container (e.g., "running", "stopped")
+ * - `status`: Indicates whether the container is running or stopped
+ * - `created`: The timestamp indicating when the container was created
+ */
+export async function createContainer(config: ContainerConfig) {
+ try {
+ const docker = getDockerClient();
+
+ const containerOptions: ContainerCreate = {
+ name: config.name,
+ Image: config.image,
+ Env: config.envVars?.map((env) => `${env.key}=${env.value}`) || [],
+ Labels: config.labels || {},
+ Cmd: config.command,
+ User: config.user,
+ Healthcheck: config.healthcheck
+ ? {
+ Test: config.healthcheck.Test,
+ Interval: config.healthcheck.Interval,
+ Timeout: config.healthcheck.Timeout,
+ Retries: config.healthcheck.Retries,
+ StartPeriod: config.healthcheck.StartPeriod
+ }
+ : undefined,
+ HostConfig: {
+ RestartPolicy: {
+ Name: config.restart || 'no'
+ },
+ Memory: config.memoryLimit,
+ NanoCpus: config.cpuLimit ? Math.round(config.cpuLimit * 1_000_000_000) : undefined
+ }
+ };
+
+ // Set up port bindings if provided
+ if (config.ports?.length) {
+ const exposedPorts: Record<string, {}> = {};
+ const portBindings: Record<string, Array<{ HostPort: string }>> = {};
+ for (const p of config.ports) {
+ const key = `${p.containerPort}/tcp`;
+ exposedPorts[key] = {};
+ portBindings[key] = [{ HostPort: p.hostPort }];
+ }
+ containerOptions.ExposedPorts = exposedPorts;
+ containerOptions.HostConfig = {
+ ...(containerOptions.HostConfig ?? {}),
+ PortBindings: portBindings
+ };
+ }
+
+ // Set up volume mounts if provided
+ if (config.volumes && config.volumes.length > 0) {
+ containerOptions.HostConfig = containerOptions.HostConfig || {};
+ containerOptions.HostConfig.Binds = config.volumes.map((vol) => `${vol.source}:${vol.target}${vol.readOnly ? ':ro' : ''}`);
+ }
+
+ // Set up network if provided
+ if (config.network) {
+ containerOptions.HostConfig = containerOptions.HostConfig || {};
+ if (!containerOptions.NetworkingConfig) {
+ containerOptions.HostConfig.NetworkMode = config.network;
+ }
+
+ if (config.networkConfig && config.network !== 'host' && config.network !== 'none' && config.network !== 'bridge') {
+ containerOptions.NetworkingConfig = {
+ EndpointsConfig: {
+ [config.network]: {
+ IPAMConfig: {
+ IPv4Address: config.networkConfig.ipv4Address || undefined,
+ IPv6Address: config.networkConfig.ipv6Address || undefined
+ }
+ }
+ }
+ };
+ containerOptions.HostConfig.NetworkMode = undefined;
+ }
+ }
+
+ // Create and start the container
+ const container = await docker.createContainer(containerOptions);
+ await container.start();
+
+ // Get the container details
+ const containerInfo = await container.inspect();
+
+ return {
+ id: containerInfo.Id,
+ name: containerInfo.Name.substring(1),
+ state: containerInfo.State.Status,
+ status: containerInfo.State.Running ? 'running' : 'stopped',
+ created: containerInfo.Created
+ };
+ } catch (error: any) {
+ console.error('Error creating container:', error);
+ if (error.message && error.message.includes('IPAMConfig')) {
+ throw new Error(`Failed to create container: Invalid IP address configuration for network "${config.network}". ${error.message}`);
+ }
+ // Add more specific error handling for resource limits if needed
+ if (error.message && error.message.includes('NanoCpus')) {
+ throw new Error(`Invalid CPU limit specified: ${error.message}`);
+ }
+ if (error.message && error.message.includes('Memory')) {
+ throw new Error(`Invalid Memory limit specified: ${error.message}`);
+ }
+ throw new Error(`Failed to create container with image "${config.image}": ${error.message}`);
+ }
+}
diff --git a/src/lib/services/docker/core.ts b/src/lib/services/docker/core.ts
new file mode 100644
index 000000000..18e384087
--- /dev/null
+++ b/src/lib/services/docker/core.ts
@@ -0,0 +1,146 @@
+import Docker from 'dockerode';
+import type { DockerConnectionOptions } from '$lib/types/docker';
+
+let dockerClient: Docker | null = null;
+export let dockerHost = 'unix:///var/run/docker.sock';
+
+/**
+ * The function `getDockerInfo` asynchronously retrieves information about the Docker environment using
+ * a Docker client.
+ * @returns The `getDockerInfo` function is returning information about the Docker engine, such as its
+ * version, number of containers, images, and other relevant details.
+ */
+export async function getDockerInfo() {
+ const docker = getDockerClient();
+ return await docker.info();
+}
+
+/**
+ * The function `getDockerClient` initializes and returns a Docker client based on the provided
+ * `dockerHost` connection options.
+ * @returns The function `getDockerClient()` returns the Docker client instance that is either newly
+ * created or already existing based on the condition check for `dockerClient`.
+ */
+export function getDockerClient(): Docker {
+ if (!dockerClient) {
+ const connectionOpts = createConnectionOptions(dockerHost);
+
+ dockerClient = new Docker(connectionOpts);
+ console.log(`Initialized Docker client with host: ${dockerHost}`, connectionOpts);
+ }
+ return dockerClient;
+}
+
+/**
+ * The function initializes a Docker connection based on the provided options, supporting different
+ * connection types such as socket and TCP.
+ * @param {DockerConnectionOptions} options - The `options` parameter in the `initializeDocker`
+ * function is of type `DockerConnectionOptions`. This parameter is an object that can contain the
+ * following properties:
+ * @returns The function `initializeDocker` is returning an instance of the Docker client that is
+ * initialized with the connection options provided in the `options` parameter.
+ */
+export function initializeDocker(options: DockerConnectionOptions): Docker {
+ const connectionOpts: Record<string, any> = {};
+
+ // Handle different connection types (socket, tcp, etc.)
+ if (options.socketPath) {
+ connectionOpts.socketPath = options.socketPath;
+ dockerHost = options.socketPath;
+ } else if (options.host && options.port) {
+ connectionOpts.host = options.host;
+ connectionOpts.port = options.port;
+ dockerHost = `${options.host}:${options.port}`;
+
+ if (options.ca || options.cert || options.key) {
+ connectionOpts.ca = options.ca;
+ connectionOpts.cert = options.cert;
+ connectionOpts.key = options.key;
+ }
+ }
+
+ dockerClient = new Docker(connectionOpts);
+ return dockerClient;
+}
+
+/**
+ * The function `updateDockerConnection` establishes a connection to a Docker host based on the
+ * provided host string.
+ * @param {string} host - The `host` parameter in the `updateDockerConnection` function is a string
+ * that represents the connection endpoint for Docker. It can be in one of the following formats:
+ * @returns If the `host` parameter is empty or falsy, a warning message is logged and the function
+ * returns early without establishing a new Docker connection.
+ */
+export function updateDockerConnection(host: string): void {
+ try {
+ // Only create a new connection if we have a valid host
+ if (!host) {
+ console.warn('No Docker host specified, connection not established');
+ return;
+ }
+
+ console.log(`Connecting to Docker at ${host}`);
+ const connectionOpts = createConnectionOptions(host);
+
+ dockerClient = new Docker(connectionOpts);
+ dockerHost = host;
+ console.log('Docker connection updated with options:', connectionOpts);
+ } catch (error) {
+ console.error('Error connecting to Docker:', error);
+ }
+}
+
+/**
+ * The function `testDockerConnection` checks if a connection to Docker can be established and returns
+ * a boolean indicating the success of the connection test.
+ * @returns The `testDockerConnection` function returns a Promise that resolves to a boolean value. If
+ * the Docker connection test is successful, it will return `true`. If the test fails, it will return
+ * `false`.
+ */
+export async function testDockerConnection(): Promise<boolean> {
+ try {
+ const docker = getDockerClient();
+ const info = await docker.info();
+ return !!info;
+ } catch (err) {
+ console.error('Docker connection test failed:', err);
+ return false;
+ }
+}
+
+/**
+ * The function `createConnectionOptions` parses a host string to create connection options for
+ * different types of connections such as Unix socket, TCP, and HTTPS.
+ * @param {string} host - The `createConnectionOptions` function takes a `host` parameter as input and
+ * based on the format of the host, it constructs connection options for different types of connections
+ * like Unix socket, TCP, or HTTPS.
+ * @returns The `createConnectionOptions` function returns a record object containing connection
+ * options based on the provided `host` parameter. The connection options include `socketPath`, `host`,
+ * `port`, and `protocol` properties depending on the format of the `host` string.
+ */
+function createConnectionOptions(host: string): Record<string, any> {
+ const connectionOpts: Record<string, any> = {};
+
+ if (host.startsWith('unix://')) {
+ connectionOpts.socketPath = host.replace('unix://', '');
+ } else if (host.startsWith('tcp://')) {
+ const url = new URL(host);
+ connectionOpts.host = url.hostname;
+ connectionOpts.port = Number.parseInt(url.port || '2375', 10);
+ } else if (host.startsWith('https://')) {
+ const url = new URL(host);
+ connectionOpts.host = url.hostname;
+ connectionOpts.port = Number.parseInt(url.port || '2376', 10);
+ connectionOpts.protocol = 'https';
+ } else {
+ connectionOpts.socketPath = host;
+ }
+
+ return connectionOpts;
+}
+
+/* The statement `export default getDockerClient;` is exporting the `getDockerClient` function as the
+default export of the module. This means that when another module imports from this module without
+specifying a particular named export, it will receive the `getDockerClient` function as the default
+export. */
+export default getDockerClient;
diff --git a/src/lib/services/docker/image-service.ts b/src/lib/services/docker/image-service.ts
new file mode 100644
index 000000000..2343bc7fd
--- /dev/null
+++ b/src/lib/services/docker/image-service.ts
@@ -0,0 +1,177 @@
+import { getDockerClient, dockerHost } from './core';
+import type { ServiceImage } from '$lib/types/docker/image.type';
+import type Docker from 'dockerode';
+
+/**
+ * The function `listImages` retrieves a list of Docker images and parses their information into a
+ * structured format.
+ * @returns The `listImages` function returns an array of `ServiceImage` objects. Each `ServiceImage`
+ * object contains properties such as `id`, `repoTags`, `repoDigests`, `created`, `size`,
+ * `virtualSize`, `labels`, `repo`, and `tag`. These properties are extracted from the images obtained
+ * from the Docker client and processed using the `parseRepoTag` function
+ */
+export async function listImages(): Promise<ServiceImage[]> {
+ try {
+ const docker = getDockerClient();
+ const images = await docker.listImages({ all: false });
+
+ const parseRepoTag = (tag: string | undefined): { repo: string; tag: string } => {
+ if (!tag || tag === '<none>:<none>') {
+ return { repo: '<none>', tag: '<none>' };
+ }
+ const withoutDigest = tag.split('@')[0];
+ const lastSlash = withoutDigest.lastIndexOf('/');
+ const lastColon = withoutDigest.lastIndexOf(':');
+ if (lastColon === -1 || lastColon < lastSlash) {
+ return { repo: withoutDigest, tag: 'latest' };
+ }
+ return {
+ repo: withoutDigest.substring(0, lastColon),
+ tag: withoutDigest.substring(lastColon + 1)
+ };
+ };
+
+ return images.map((img): ServiceImage => {
+ const { repo, tag } = parseRepoTag(img.RepoTags?.[0]);
+ return {
+ id: img.Id,
+ repoTags: img.RepoTags,
+ repoDigests: img.RepoDigests,
+ created: img.Created,
+ size: img.Size,
+ virtualSize: img.VirtualSize,
+ labels: img.Labels,
+ repo: repo,
+ tag: tag
+ };
+ });
+ } catch (error: any) {
+ console.error('Docker Service: Error listing images:', error);
+ throw new Error(`Failed to list Docker images using host "${dockerHost}".`);
+ }
+}
+
+/**
+ * This TypeScript function removes a Docker image by its ID, with an option to force removal if the
+ * image is in use.
+ * @param {string} imageId - The `imageId` parameter is a string that represents the unique identifier
+ * of the Docker image that you want to remove.
+ * @param {boolean} [force=false] - The `force` parameter in the `removeImage` function is a boolean
+ * parameter that determines whether to forcefully remove the image even if it is being used by a
+ * container. If `force` is set to `true`, the image will be removed regardless of whether it is in use
+ * by a container.
+ */
+export async function removeImage(imageId: string, force: boolean = false): Promise<void> {
+ try {
+ const docker = getDockerClient();
+ const image = docker.getImage(imageId);
+ await image.remove({ force });
+ console.log(`Docker Service: Image "${imageId}" removed successfully.`);
+ } catch (error: any) {
+ console.error(`Docker Service: Error removing image "${imageId}":`, error);
+ if (error.statusCode === 409) {
+ throw new Error(`Image "${imageId}" is being used by a container. Use force option to remove.`);
+ }
+ throw new Error(`Failed to remove image "${imageId}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
+ }
+}
+
+/**
+ * The function `isImageInUse` checks if a Docker image is being used by any containers.
+ * @param {string} imageId - The `imageId` parameter in the `isImageInUse` function is a string that
+ * represents the ID of the image that you want to check if it is being used by any Docker containers.
+ * @returns The function `isImageInUse` returns a Promise that resolves to a boolean value indicating
+ * whether the image with the provided `imageId` is in use by any Docker containers. If an error occurs
+ * during the process of checking for container usage, the function will log the error and default to
+ * assuming that the image is in use for safety reasons.
+ */
+export async function isImageInUse(imageId: string): Promise<boolean> {
+ try {
+ const docker = getDockerClient();
+ const containers = await docker.listContainers({ all: true });
+
+ // Look for containers using this image
+ return containers.some((container) => container.ImageID === imageId || container.Image === imageId);
+ } catch (error) {
+ console.error(`Error checking if image ${imageId} is in use:`, error);
+ // Default to assuming it's in use for safety
+ return true;
+ }
+}
+
+/**
+ * The function `pruneImages` in TypeScript prunes Docker images based on the specified mode ('all' or
+ * 'dangling') and returns information about the deleted images and space reclaimed.
+ * @param {'all' | 'dangling'} [mode=all] - The `mode` parameter in the `pruneImages` function is used
+ * to specify whether to prune all unused images or only dangling images. It is a string literal type
+ * with two possible values: `'all'` or `'dangling'`. The default value is `'all'`, meaning that if
+ * @returns The `pruneImages` function returns a Promise that resolves to an object with the following
+ * properties:
+ */
+export async function pruneImages(mode: 'all' | 'dangling' = 'all'): Promise<{
+ ImagesDeleted: Docker.ImageRemoveInfo[] | null;
+ SpaceReclaimed: number;
+}> {
+ try {
+ const docker = getDockerClient();
+ const filterValue = mode === 'all' ? 'false' : 'true';
+ const logMessage = mode === 'all' ? 'Pruning all unused images (docker image prune -a)...' : 'Pruning dangling images (docker image prune)...';
+
+ console.log(`Docker Service: ${logMessage}`);
+
+ const pruneOptions = {
+ filters: { dangling: [filterValue] }
+ };
+
+ const result = await docker.pruneImages(pruneOptions); // Use the options object
+
+ console.log(`Docker Service: Image prune complete. Space reclaimed: ${result.SpaceReclaimed}`);
+ return result;
+ } catch (error: any) {
+ console.error('Docker Service: Error pruning images:', error);
+ throw new Error(`Failed to prune images using host "${dockerHost}". ${error.message || error.reason || ''}`);
+ }
+}
+
+/**
+ * The function `pullImage` asynchronously pulls a Docker image using a specified image reference and
+ * optional platform.
+ * @param {string} imageRef - The `imageRef` parameter in the `pullImage` function is a string that
+ * represents the reference to the Docker image that you want to pull. It typically includes the image
+ * name and tag, such as `nginx:latest` or `myapp:v1.0`.
+ * @param {string} [platform] - The `platform` parameter in the `pullImage` function is an optional
+ * parameter that specifies the platform for which the image should be pulled. This parameter allows
+ * you to specify the architecture, operating system, and variant of the platform for which the image
+ * is intended. If provided, the Docker client will attempt
+ */
+export async function pullImage(imageRef: string, platform?: string): Promise<void> {
+ try {
+ const docker = getDockerClient();
+
+ const pullOptions: any = {};
+ if (platform) {
+ pullOptions.platform = platform;
+ }
+
+ console.log(`Docker Service: Pulling image "${imageRef}"...`);
+
+ // Pull the image - this returns a stream
+ const stream = await docker.pull(imageRef, pullOptions);
+
+ const pullTimeout = 10 * 60 * 1000; // 10 min
+
+ // Wait for the pull to complete by consuming the stream with 10 minute timeout
+ const result = await Promise.race([new Promise((resolve, reject) => docker.modem.followProgress(stream, (err, out) => (err ? reject(err) : resolve(out)))), new Promise((_, reject) => setTimeout(() => reject(new Error(`Pull timed-out after ${pullTimeout} ms`)), pullTimeout))]);
+
+ console.log(`Docker Service: Image "${imageRef}" pulled successfully.`);
+ } catch (error: any) {
+ console.error(`Docker Service: Error pulling image "${imageRef}":`, error);
+
+ // Handle specific error cases
+ if (error.statusCode === 404) {
+ throw new Error(`Image "${imageRef}" not found in registry.`);
+ }
+
+ throw new Error(`Failed to pull image "${imageRef}". ${error.message || error.reason || ''}`);
+ }
+}
diff --git a/src/lib/services/docker/network-service.ts b/src/lib/services/docker/network-service.ts
new file mode 100644
index 000000000..afbba9388
--- /dev/null
+++ b/src/lib/services/docker/network-service.ts
@@ -0,0 +1,102 @@
+import { getDockerClient, dockerHost } from '$lib/services/docker/core';
+import type { ServiceNetwork } from '$lib/types/docker/network.type';
+import type { NetworkInspectInfo, NetworkCreateOptions } from 'dockerode';
+
+/* The line `const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress']);` is creating
+a Set named `DEFAULT_NETWORK_NAMES` that contains the default network names managed by Docker. These
+default network names are 'host', 'bridge', 'none', and 'ingress'. The purpose of this set is to
+provide a quick and efficient way to check if a given network name is one of the default networks
+when needed in the code. */
+export const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress']);
+
+/**
+ * This TypeScript function asynchronously lists Docker networks and maps the network properties to a
+ * custom ServiceNetwork type.
+ * @returns The `listNetworks` function returns a Promise that resolves to an array of `ServiceNetwork`
+ * objects. Each `ServiceNetwork` object contains properties such as `id`, `name`, `driver`, `scope`,
+ * `subnet`, `gateway`, and `created`, which are extracted from the networks obtained from the Docker
+ * client.
+ */
+export async function listNetworks(): Promise<ServiceNetwork[]> {
+ try {
+ const docker = getDockerClient();
+ const networks = await docker.listNetworks();
+ return networks.map(
+ (net): ServiceNetwork => ({
+ id: net.Id,
+ name: net.Name,
+ driver: net.Driver,
+ scope: net.Scope,
+ subnet: net.IPAM?.Config?.[0]?.Subnet ?? null,
+ gateway: net.IPAM?.Config?.[0]?.Gateway ?? null,
+ created: net.Created ?? ''
+ })
+ );
+ } catch (error: any) {
+ console.error('Docker Service: Error listing networks:', error);
+ throw new Error(`Failed to list Docker networks using host "${dockerHost}".`);
+ }
+}
+
+/**
+ * The function `removeNetwork` removes a Docker network, handling default networks and error cases.
+ * @param {string} networkId - The `networkId` parameter in the `removeNetwork` function is a string
+ * that represents the ID of the Docker network that you want to remove. This function checks if the
+ * specified network is one of the default networks managed by Docker (`host`, `bridge`, `none`,
+ * `ingress`). If
+ */
+export async function removeNetwork(networkId: string): Promise<void> {
+ try {
+ if (DEFAULT_NETWORK_NAMES.has(networkId)) {
+ throw new Error(`Network "${networkId}" is managed by Docker and cannot be removed.`);
+ }
+ const docker = getDockerClient();
+ const network = docker.getNetwork(networkId);
+ await network.remove();
+ console.log(`Docker Service: Network "${networkId}" removed successfully.`);
+ } catch (error: any) {
+ console.error(`Docker Service: Error removing network "${networkId}":`, error);
+ if (error.statusCode === 404) {
+ throw new Error(`Network "${networkId}" not found.`);
+ }
+ if (error.statusCode === 409) {
+ // 409 Conflict usually means it's in use or predefined
+ throw new Error(`Network "${networkId}" cannot be removed (possibly in use or predefined).`);
+ }
+ throw new Error(`Failed to remove network "${networkId}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
+ }
+}
+
+/**
+ * The function `createNetwork` in TypeScript creates a Docker network with the specified options and
+ * returns detailed inspection information.
+ * @param {NetworkCreateOptions} options - The `options` parameter in the `createNetwork` function is
+ * of type `NetworkCreateOptions`. This object likely contains the configuration details for creating a
+ * network in Docker. The specific properties and structure of the `NetworkCreateOptions` type would be
+ * defined elsewhere in your codebase.
+ * @returns The function `createNetwork` is returning a Promise that resolves to a `NetworkInspectInfo`
+ * object, which contains detailed information about the network that was created.
+ */
+export async function createNetwork(options: NetworkCreateOptions): Promise<NetworkInspectInfo> {
+ try {
+ const docker = getDockerClient();
+ console.log(`Docker Service: Creating network "${options.Name}"...`, options);
+
+ // Dockerode's createNetwork returns the Network object, we need to inspect it after creation
+ const network = await docker.createNetwork(options);
+
+ // Inspect the newly created network to get full details
+ const inspectInfo = await network.inspect();
+
+ console.log(`Docker Service: Network "${options.Name}" (ID: ${inspectInfo.Id}) created successfully.`);
+ return inspectInfo; // Return the detailed inspect info
+ } catch (error: any) {
+ console.error(`Docker Service: Error creating network "${options.Name}":`, error);
+ // Check for specific Docker errors
+ if (error.statusCode === 409) {
+ // Could be duplicate name if CheckDuplicate was true, or other conflicts
+ throw new Error(`Network "${options.Name}" may already exist or conflict with an existing configuration.`);
+ }
+ throw new Error(`Failed to create network "${options.Name}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
+ }
+}
diff --git a/src/lib/services/compose.ts b/src/lib/services/docker/stack-service.ts
similarity index 52%
rename from src/lib/services/compose.ts
rename to src/lib/services/docker/stack-service.ts
index d04129886..b1529d41d 100644
--- a/src/lib/services/compose.ts
+++ b/src/lib/services/docker/stack-service.ts
@@ -1,17 +1,22 @@
-import { promises as fs } from 'fs';
-import { join } from 'path';
+import { promises as fs } from 'node:fs';
+import { join } from 'node:path';
+import { basename } from 'node: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';
-import { getSettings, ensureStacksDirectory } from './settings-service';
+import { nanoid } from 'nanoid';
+
+import { getDockerClient } from '$lib/services/docker/core';
+import { getSettings, ensureStacksDirectory } from '$lib/services/settings-service';
+
+import type { Stack, StackMeta, StackService, StackUpdate } from '$lib/types/docker/stack.type';
+/* The above code is declaring a variable `STACKS_DIR` with an empty string as its initial value in
+TypeScript. */
let STACKS_DIR = '';
/**
- * Initialize the compose service with settings
- * This should be called at app startup
+ * The function `initComposeService` initializes the stacks directory and ensures its existence in a
+ * TypeScript application.
*/
export async function initComposeService(): Promise<void> {
try {
@@ -26,8 +31,11 @@ export async function initComposeService(): Promise<void> {
}
/**
- * Update the stacks directory path - used when settings are updated
- * @param {string} directory New stacks directory path
+ * The function `updateStacksDirectory` updates the `STACKS_DIR` variable with a new directory path and
+ * logs the updated directory path to the console.
+ * @param {string} directory - The `directory` parameter is a string that represents the new directory
+ * path that you want to set for the `STACKS_DIR` variable. When the `updateStacksDirectory` function
+ * is called with a valid `directory` value, it updates the `STACKS_DIR` variable to the new directory
*/
export function updateStacksDirectory(directory: string): void {
if (directory) {
@@ -37,7 +45,9 @@ export function updateStacksDirectory(directory: string): void {
}
/**
- * Ensure stacks directory exists and return the path
+ * The function `ensureStacksDir` ensures the existence of a directory for storing stacks.
+ * @returns The function `ensureStacksDir()` returns the `STACKS_DIR` variable after ensuring that the
+ * stacks directory exists.
*/
async function ensureStacksDir(): Promise<string> {
try {
@@ -54,17 +64,30 @@ async function ensureStacksDir(): Promise<string> {
}
/**
- * Get stack directory path
- * @param {string} stackId
+ * The function `getStackDir` returns the directory path for a given stack ID after ensuring the
+ * existence of the stacks directory.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
+ * of a stack.
+ * @returns The function `getStackDir` returns a Promise that resolves to a string representing the
+ * directory path where the stack with the given `stackId` is located.
*/
async function getStackDir(stackId: string): Promise<string> {
const stacksDir = await ensureStacksDir();
- return join(stacksDir, stackId);
+ const safeId = basename(stackId); // strips path
+ if (safeId !== stackId) {
+ throw new Error('Invalid stack id');
+ }
+ return join(stacksDir, safeId);
}
/**
- * Get compose file path
- * @param {string} stackId
+ * The function `getComposeFilePath` returns the path to the docker-compose.yml file within the
+ * directory of a given stack ID.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
+ * of a stack in a system.
+ * @returns The function `getComposeFilePath` returns a Promise that resolves to a string representing
+ * the file path of the `docker-compose.yml` file within the directory of the stack identified by
+ * `stackId`.
*/
async function getComposeFilePath(stackId: string): Promise<string> {
const stackDir = await getStackDir(stackId);
@@ -72,8 +95,13 @@ async function getComposeFilePath(stackId: string): Promise<string> {
}
/**
- * Get stack metadata file path
- * @param {string} stackId
+ * The function `getStackMetaPath` returns the path to the meta.json file within the directory of a
+ * given stack ID.
+ * @param {string} stackId - StackId is a string parameter that represents the unique identifier of a
+ * stack.
+ * @returns The function `getStackMetaPath` returns a `Promise` that resolves to a string representing
+ * the path to the `meta.json` file within the directory of the stack identified by the `stackId`
+ * parameter.
*/
async function getStackMetaPath(stackId: string): Promise<string> {
const stackDir = await getStackDir(stackId);
@@ -81,8 +109,15 @@ async function getStackMetaPath(stackId: string): Promise<string> {
}
/**
- * Initialize a DockerodeCompose instance for a stack
- * @param {string} stackId
+ * The function `getComposeInstance` returns a new instance of `DockerodeCompose` using a Docker
+ * client, compose file path, and stack ID.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the identifier of a
+ * Docker stack. It is used to retrieve the compose file path and create a new instance of
+ * `DockerodeCompose` with the specified stack identifier.
+ * @returns The function `getComposeInstance` is returning a Promise that resolves to an instance of
+ * `DockerodeCompose`. The `DockerodeCompose` instance is created using the Docker client obtained from
+ * `getDockerClient()`, the compose file path obtained asynchronously from
+ * `getComposeFilePath(stackId)`, and the `stackId` parameter.
*/
async function getComposeInstance(stackId: string): Promise<DockerodeCompose> {
const docker = getDockerClient();
@@ -91,9 +126,19 @@ async function getComposeInstance(stackId: string): Promise<DockerodeCompose> {
}
/**
- * Get the services and their status for a specific stack
- * @param {string} stackId Stack ID
- * @param {string} composeContent Compose file content
+ * This TypeScript function retrieves information about services in a Docker stack based on the
+ * provided stack ID and compose file content.
+ * @param {string} stackId - The `stackId` parameter in the `getStackServices` function is a string
+ * that represents the identifier of a stack in a Docker environment. This identifier is used to filter
+ * and identify containers associated with the specific stack.
+ * @param {string} composeContent - The `composeContent` parameter in the `getStackServices` function
+ * is expected to be a string containing the content of a Docker Compose file in YAML format. This file
+ * defines the services that make up a stack in Docker. The function parses this content to extract
+ * service names and then retrieves information about
+ * @returns The `getStackServices` function returns a Promise that resolves to an array of
+ * `StackService` objects. Each `StackService` object contains information about a service in a
+ * specific stack, including the service ID, name, and state (whether it is running, its status, and
+ * exit code). If an error occurs during the process, an empty array is returned.
*/
async function getStackServices(stackId: string, composeContent: string): Promise<StackService[]> {
const docker = getDockerClient();
@@ -138,7 +183,7 @@ async function getStackServices(stackId: string, composeContent: string): Promis
state: {
Running: containerData.State === 'running',
Status: containerData.State,
- ExitCode: 0
+ ExitCode: 0
}
};
@@ -167,8 +212,12 @@ async function getStackServices(stackId: string, composeContent: string): Promis
}
/**
- * Load all compose stacks
- * @returns {Promise<Array<Stack>>} List of stacks
+ * This TypeScript function asynchronously loads information about Docker Compose stacks from a
+ * directory and returns an array of Stack objects.
+ * @returns The `loadComposeStacks` function returns a Promise that resolves to an array of `Stack`
+ * objects. Each `Stack` object represents a stack loaded from the stacks directory. The `Stack` object
+ * contains properties such as `id`, `name`, `serviceCount`, `runningCount`, `status`, `createdAt`, and
+ * `updatedAt`.
*/
export async function loadComposeStacks(): Promise<Stack[]> {
const stacksDir = await ensureStacksDir();
@@ -220,8 +269,15 @@ export async function loadComposeStacks(): Promise<Stack[]> {
}
/**
- * Get stack by ID
- * @param {string} stackId
+ * This TypeScript function retrieves information about a stack, including its services and status,
+ * based on the provided stack ID.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
+ * of a stack. It is used to retrieve information about a specific stack, such as its metadata,
+ * services, status, and content.
+ * @returns The `getStack` function returns a Promise that resolves to an object of type `Stack`. The
+ * `Stack` object contains properties such as `id`, `name`, `services`, `serviceCount`, `runningCount`,
+ * `status`, `createdAt`, `updatedAt`, and `composeContent`. These properties hold information about a
+ * specific stack identified by `stackId`.
*/
export async function getStack(stackId: string): Promise<Stack> {
try {
@@ -262,13 +318,25 @@ export async function getStack(stackId: string): Promise<Stack> {
}
/**
- * Create a new stack
- * @param {string} name Stack name
- * @param {string} composeContent Compose file content
+ * The function `createStack` creates a new stack with a unique ID, saves the stack's metadata and
+ * Docker Compose file to disk, and returns information about the created stack.
+ * @param {string} name - The `name` parameter is a string that represents the name of the stack being
+ * created. It is used to identify the stack and is included in the metadata of the stack.
+ * @param {string} composeContent - The `composeContent` parameter in the `createStack` function is a
+ * string that represents the content of a Docker Compose file. This file defines the services,
+ * networks, and volumes for a Docker application. It is used to configure and run multiple Docker
+ * containers as a single application.
+ * @returns The `createStack` function returns a Promise that resolves to a `Stack` object with the
+ * following properties:
+ * - `id`: The unique identifier of the stack
+ * - `name`: The name of the stack
+ * - `serviceCount`: The number of services defined in the Docker Compose file
+ * - `runningCount`: The number of services currently running
+ * - `status`: The status of the
*/
export async function createStack(name: string, composeContent: string): Promise<Stack> {
const stackId = nanoid();
- const stackDir = await getStackDir(stackId);
+ const stackDir = await getStackDir(stackId);
const composePath = join(stackDir, 'docker-compose.yml');
const metaPath = join(stackDir, 'meta.json');
@@ -285,7 +353,7 @@ export async function createStack(name: string, composeContent: string): Promise
let serviceCount = 0;
try {
const composeData = yaml.load(composeContent) as any;
- if (composeData && composeData.services) {
+ if (composeData?.services) {
serviceCount = Object.keys(composeData.services).length;
}
} catch (parseErr) {
@@ -293,14 +361,14 @@ export async function createStack(name: string, composeContent: string): Promise
}
return {
- id: stackId,
+ id: stackId,
name: meta.name,
- serviceCount: serviceCount,
+ serviceCount: serviceCount,
runningCount: 0,
status: 'stopped',
createdAt: meta.createdAt,
updatedAt: meta.updatedAt,
- composeContent: composeContent
+ composeContent: composeContent
};
} catch (err) {
console.error('Error creating stack:', err);
@@ -314,9 +382,19 @@ export async function createStack(name: string, composeContent: string): Promise
}
/**
- * Update an existing stack
- * @param {string} stackId Stack ID
- * @param {StackUpdate} updates Updates to apply
+ * The function `updateStack` updates a stack's metadata and compose file, calculates the status of the
+ * stack based on its services, and returns the updated stack information.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
+ * of the stack that you want to update.
+ * @param {StackUpdate} updates - The `updates` parameter in the `updateStack` function is an object
+ * that contains the changes you want to apply to the stack. It can have the following properties:
+ * @returns The `updateStack` function returns a Promise that resolves to a `Stack` object with the
+ * following properties:
+ * - `id`: The ID of the stack
+ * - `name`: The updated name of the stack
+ * - `serviceCount`: The total number of services in the stack
+ * - `runningCount`: The number of services currently running in the stack
+ * - `status`: The status of the
*/
export async function updateStack(stackId: string, updates: StackUpdate): Promise<Stack> {
const metaPath = await getStackMetaPath(stackId);
@@ -369,8 +447,11 @@ export async function updateStack(stackId: string, updates: StackUpdate): Promis
}
/**
- * Start a stack
- * @param {string} stackId Stack ID
+ * The function `startStack` asynchronously starts a Docker stack identified by `stackId`, pulling the
+ * latest images and bringing up the services.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the identifier of the
+ * stack that you want to start.
+ * @returns The `startStack` function returns a `Promise<boolean>`.
*/
export async function startStack(stackId: string): Promise<boolean> {
try {
@@ -386,8 +467,14 @@ export async function startStack(stackId: string): Promise<boolean> {
}
/**
- * Stop a stack
- * @param {string} stackId Stack ID
+ * The function `stopStack` stops a Docker stack identified by its ID and returns a boolean indicating
+ * success.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the identifier of the
+ * stack that you want to stop.
+ * @returns The `stopStack` function returns a Promise that resolves to a boolean value. If the stack
+ * is stopped successfully, it returns `true`. If an error occurs during the process of stopping the
+ * stack, it will log the error, throw a new Error with a message indicating the failure, and the
+ * Promise will be rejected.
*/
export async function stopStack(stackId: string): Promise<boolean> {
try {
@@ -402,8 +489,11 @@ export async function stopStack(stackId: string): Promise<boolean> {
}
/**
- * Restart a stack
- * @param {string} stackId Stack ID
+ * 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> {
try {
@@ -419,16 +509,66 @@ export async function restartStack(stackId: string): Promise<boolean> {
}
/**
- * Remove a stack
- * @param {string} stackId Stack ID
+ * The function `fulllyRedployStack` asynchronously stops, pulls latest images, and restarts a
+ * specified stack, returning true if successful.
+ * @param {string} stackId - The `stackId` parameter in the `fulllyRedployStack` 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 `fulllyRedployStack` 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 removeStack(stackId: string): Promise<boolean> {
+export async function fulllyRedployStack(stackId: string): Promise<boolean> {
try {
const compose = await getComposeInstance(stackId);
+
+ // Stop the stack
+ console.log(`Stopping stack ${stackId}...`);
await compose.down();
+ console.log(`Stack ${stackId} stopped.`);
+
+ // Pull the latest images
+ console.log(`Pulling images for stack ${stackId}...`);
+ await compose.pull();
+ console.log(`Images pulled for stack ${stackId}.`);
+ // Start the stack again
+ console.log(`Starting stack ${stackId}...`);
+ await compose.up();
+ console.log(`Stack ${stackId} started.`);
+
+ // If all commands succeeded, return true
+ return true;
+ } catch (err: unknown) {
+ console.error(`Error restarting stack ${stackId}:`, err);
+ const errorMessage = err instanceof Error ? err.message : String(err);
+ throw new Error(`Failed to restart stack: ${errorMessage}`);
+ }
+}
+/**
+ * The function `removeStack` removes a Docker stack by stopping its services and deleting its
+ * directory.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the unique identifier
+ * of the stack that needs to be removed.
+ * @returns The `removeStack` function returns a `Promise<boolean>`. The function attempts to remove a
+ * stack identified by `stackId`. If the removal process is successful, it resolves the promise with a
+ * value of `true`. If an error occurs during the removal process, it catches the error, logs it, and
+ * then throws a new `Error` with a message indicating the failure to remove the stack.
+ */
+export async function removeStack(stackId: string): Promise<boolean> {
+ try {
+ const compose = await getComposeInstance(stackId);
const stackDir = await getStackDir(stackId);
- await fs.rm(stackDir, { recursive: true, force: true });
+
+ await compose.down();
+ try {
+ await fs.rm(stackDir, { recursive: true, force: true });
+ } catch (e) {
+ console.error(`Failed to remove stack directory ${stackDir}:`, e);
+ return false;
+ }
return true;
} catch (err: unknown) {
@@ -439,8 +579,13 @@ export async function removeStack(stackId: string): Promise<boolean> {
}
/**
- * Discover existing Docker Compose stacks by analyzing container labels
- * @returns {Promise<Stack[]>} External stacks discovered
+ * The function `discoverExternalStacks` asynchronously discovers external Docker stacks and their
+ * services, categorizing them based on their running status.
+ * @returns The `discoverExternalStacks` function returns a Promise that resolves to an array of
+ * `Stack` objects representing external stacks discovered by querying Docker containers. The `Stack`
+ * objects contain information about the external stacks, such as the stack name, services, service
+ * count, running service count, status (running, stopped, partially running), and timestamps for
+ * creation and update. If an error occurs during the discovery
*/
export async function discoverExternalStacks(): Promise<Stack[]> {
try {
@@ -516,10 +661,12 @@ export async function discoverExternalStacks(): Promise<Stack[]> {
}
/**
- * Import an external stack into Arcane
- *
- * @param stackId The ID of the external stack to import
- * @returns The newly imported stack object
+ * The function `importExternalStack` imports an external Docker stack by retrieving containers,
+ * reading the compose file, and creating a new stack in Arcane's managed stacks.
+ * @param {string} stackId - The `stackId` parameter is a string that represents the identifier of the
+ * external stack that you want to import. It is used to locate the stack and its associated containers
+ * in the Docker environment.
+ * @returns The `importExternalStack` function returns a Promise that resolves to a `Stack` object.
*/
export async function importExternalStack(stackId: string): Promise<Stack> {
// 1. First, check if we can find the stack by ID
diff --git a/src/lib/services/docker/volume-service.ts b/src/lib/services/docker/volume-service.ts
new file mode 100644
index 000000000..6bb223cf8
--- /dev/null
+++ b/src/lib/services/docker/volume-service.ts
@@ -0,0 +1,130 @@
+import { getDockerClient, dockerHost } from '$lib/services/docker/core';
+import type { ServiceVolume } from '$lib/types/docker/volume.type';
+import type { VolumeCreateOptions } from 'dockerode';
+
+/**
+ * This TypeScript function asynchronously lists Docker volumes and maps the response to a custom
+ * ServiceVolume type.
+ * @returns The `listVolumes` function returns a Promise that resolves to an array of `ServiceVolume`
+ * objects. Each `ServiceVolume` object contains properties such as `name`, `driver`, `scope`,
+ * `mountpoint`, and `labels` extracted from the volumes obtained from the Docker client. If an error
+ * occurs during the process, an error message is logged and a new Error is thrown with a failure
+ */
+export async function listVolumes(): Promise<ServiceVolume[]> {
+ try {
+ const docker = getDockerClient();
+ const volumeResponse = await docker.listVolumes();
+ const volumes = volumeResponse.Volumes || [];
+
+ return volumes.map(
+ (vol): ServiceVolume => ({
+ name: vol.Name,
+ driver: vol.Driver,
+ scope: vol.Scope,
+ mountpoint: vol.Mountpoint,
+ labels: vol.Labels
+ })
+ );
+ } catch (error: any) {
+ console.error('Docker Service: Error listing volumes:', error);
+ throw new Error(`Failed to list Docker volumes using host "${dockerHost}".`);
+ }
+}
+
+/**
+ * The function `isVolumeInUse` checks if a specified volume is currently in use by any Docker
+ * containers.
+ * @param {string} volumeName - The `volumeName` parameter in the `isVolumeInUse` function is a string
+ * that represents the name of the volume you want to check if it is in use by any Docker containers.
+ * @returns The `isVolumeInUse` function returns a Promise that resolves to a boolean value. The
+ * function checks if a specified volume is being used by any Docker containers. If the volume is found
+ * to be in use by any container, the function returns `true`. If the volume is not in use by any
+ * container, the function returns `false`. In case of any errors during the process, the function
+ */
+export async function isVolumeInUse(volumeName: string): Promise<boolean> {
+ try {
+ const docker = getDockerClient();
+ const containers = await docker.listContainers({ all: true });
+ // Inspect each container to check its mounts
+ for (const containerInfo of containers) {
+ const details = await docker.getContainer(containerInfo.Id).inspect();
+ if (details.Mounts?.some((m) => m.Type === 'volume' && m.Name === volumeName)) {
+ return true;
+ }
+ }
+ return false;
+ } catch (error) {
+ console.error(`Error checking if volume ${volumeName} is in use:`, error);
+ // Default to assuming it's in use for safety
+ return true;
+ }
+}
+
+/**
+ * The function `createVolume` creates a Docker volume with specified options and returns basic
+ * information about the created volume.
+ * @param {VolumeCreateOptions} options - The `options` parameter in the `createVolume` function is of
+ * type `VolumeCreateOptions`. This object likely contains the necessary information to create a volume
+ * in Docker, such as the volume name, driver, labels, and scope. The function uses this information to
+ * create a volume using the Docker client
+ * @returns The `createVolume` function returns an object with the following properties:
+ * - Name: The name of the created volume
+ * - Driver: The driver used for the volume
+ * - Mountpoint: The mountpoint of the volume
+ * - Labels: Any labels associated with the volume (defaults to an empty object if none provided)
+ * - Scope: The scope of the volume (defaults to 'local' if not
+ */
+export async function createVolume(options: VolumeCreateOptions): Promise<ServiceVolume> {
+ try {
+ const docker = getDockerClient();
+ // createVolume returns the volume data directly - no need to inspect
+ const volume = await docker.createVolume(options);
+
+ console.log(`Docker Service: Volume "${options.Name}" created successfully.`);
+
+ // Return the creation response which contains basic info
+ return {
+ name: volume.Name,
+ driver: volume.Driver,
+ mountpoint: volume.Mountpoint,
+ labels: volume.Labels || {},
+ scope: volume.Scope || 'local'
+ };
+ } catch (error: any) {
+ console.error(`Docker Service: Error creating volume "${options.Name}":`, error);
+ // Check for specific Docker errors, like volume already exists (often 409)
+ if (error.statusCode === 409) {
+ throw new Error(`Volume "${options.Name}" already exists.`);
+ }
+ throw new Error(
+ `Failed to create volume "${options.Name}" using host "${dockerHost}". ${
+ error.message || error.reason || '' // Include reason if available
+ }`
+ );
+ }
+}
+
+/**
+ * The function `removeVolume` asynchronously removes a Docker volume by name, with an optional force
+ * flag to handle volume in use errors.
+ * @param {string} name - The `name` parameter is a string that represents the name of the volume you
+ * want to remove.
+ * @param {boolean} [force=false] - The `force` parameter in the `removeVolume` function is a boolean
+ * parameter that determines whether to forcefully remove the volume even if it is in use by a
+ * container. By default, its value is set to `false`, meaning that the volume will not be removed if
+ * it is in use. If
+ */
+export async function removeVolume(name: string, force: boolean = false): Promise<void> {
+ try {
+ const docker = getDockerClient();
+ const volume = docker.getVolume(name);
+ await volume.remove({ force });
+ console.log(`Docker Service: Volume "${name}" removed successfully.`);
+ } catch (error: any) {
+ console.error(`Docker Service: Error removing volume "${name}":`, error);
+ if (error.statusCode === 409) {
+ throw new Error(`Volume "${name}" is in use by a container. Use force option to remove.`);
+ }
+ throw new Error(`Failed to remove volume "${name}" using host "${dockerHost}". ${error.message || error.reason || ''}`);
+ }
+}
diff --git a/src/lib/types/docker/connection.type.ts b/src/lib/types/docker/connection.type.ts
new file mode 100644
index 000000000..a36116782
--- /dev/null
+++ b/src/lib/types/docker/connection.type.ts
@@ -0,0 +1,8 @@
+export interface DockerConnectionOptions {
+ socketPath?: string;
+ host?: string;
+ port?: number;
+ ca?: string;
+ cert?: string;
+ key?: string;
+}
\ No newline at end of file
diff --git a/src/lib/types/docker.ts b/src/lib/types/docker/container.type.ts
similarity index 88%
rename from src/lib/types/docker.ts
rename to src/lib/types/docker/container.type.ts
index 542f383a6..12d6bb64e 100644
--- a/src/lib/types/docker.ts
+++ b/src/lib/types/docker/container.type.ts
@@ -1,57 +1,18 @@
+import type Docker from 'dockerode';
import type { ContainerCreateOptions, HealthConfig } from 'dockerode';
-export interface DockerConnectionOptions {
- socketPath?: string;
- host?: string;
- port?: number;
- ca?: string;
- cert?: string;
- key?: string;
-}
-
-// Container types
-export interface ContainerCreate extends ContainerCreateOptions {
- name?: string; // Container name
-}
-
-// Container configuration for creating containers
-export interface ContainerConfig {
+export type ServiceContainer = {
+ id: string;
+ names: string[];
name: string;
image: string;
- ports?: Array<{
- hostPort: string;
- containerPort: string;
- }>;
- volumes?: Array<{
- source: string;
- target: string;
- readOnly?: boolean;
- }>;
- envVars?: Array<{
- key: string;
- value: string;
- }>;
- network?: string;
- restart?: 'no' | 'always' | 'on-failure' | 'unless-stopped';
- networkConfig?: {
- ipv4Address?: string;
- ipv6Address?: string;
- };
- healthcheck?: HealthConfig;
- labels?: { [key: string]: string };
- command?: string[];
- user?: string;
- memoryLimit?: number;
- cpuLimit?: number;
-}
-
-// Container port mapping
-export interface ContainerPort {
- IP?: string;
- PrivatePort: number;
- PublicPort?: number;
- Type: string;
-}
+ imageId: string;
+ command: string;
+ created: number;
+ state: string;
+ status: string;
+ ports: Docker.Port[];
+};
// Container state
export interface ContainerState {
@@ -102,3 +63,47 @@ export interface ContainerDetails {
Propagation: string;
}>;
}
+
+// Container types
+export interface ContainerCreate extends ContainerCreateOptions {
+ name?: string; // Container name
+}
+
+// Container configuration for creating containers
+export interface ContainerConfig {
+ name: string;
+ image: string;
+ ports?: Array<{
+ hostPort: string;
+ containerPort: string;
+ }>;
+ volumes?: Array<{
+ source: string;
+ target: string;
+ readOnly?: boolean;
+ }>;
+ envVars?: Array<{
+ key: string;
+ value: string;
+ }>;
+ network?: string;
+ restart?: 'no' | 'always' | 'on-failure' | 'unless-stopped';
+ networkConfig?: {
+ ipv4Address?: string;
+ ipv6Address?: string;
+ };
+ healthcheck?: HealthConfig;
+ labels?: { [key: string]: string };
+ command?: string[];
+ user?: string;
+ memoryLimit?: number;
+ cpuLimit?: number;
+}
+
+// Container port mapping
+export interface ContainerPort {
+ IP?: string;
+ PrivatePort: number;
+ PublicPort?: number;
+ Type: string;
+}
diff --git a/src/lib/types/docker/image.type.ts b/src/lib/types/docker/image.type.ts
new file mode 100644
index 000000000..5bddff8ae
--- /dev/null
+++ b/src/lib/types/docker/image.type.ts
@@ -0,0 +1,15 @@
+export type ServiceImage = {
+ id: string;
+ repoTags: string[] | undefined;
+ repoDigests: string[] | undefined;
+ created: number;
+ size: number;
+ virtualSize: number;
+ labels: { [label: string]: string } | undefined;
+ repo: string;
+ tag: string;
+};
+
+export type EnhancedImageInfo = ServiceImage & {
+ inUse: boolean;
+};
\ No newline at end of file
diff --git a/src/lib/types/docker/index.ts b/src/lib/types/docker/index.ts
new file mode 100644
index 000000000..cd6d569e6
--- /dev/null
+++ b/src/lib/types/docker/index.ts
@@ -0,0 +1,6 @@
+export * from './stack.type';
+export * from './network.type';
+export * from './container.type';
+export * from './image.type';
+export * from './volume.type';
+export * from './connection.type';
diff --git a/src/lib/types/docker/network.type.ts b/src/lib/types/docker/network.type.ts
new file mode 100644
index 000000000..fb5a536f7
--- /dev/null
+++ b/src/lib/types/docker/network.type.ts
@@ -0,0 +1,9 @@
+export type ServiceNetwork = {
+ id: string;
+ name: string;
+ driver: string;
+ scope: string;
+ subnet: string | null;
+ gateway: string | null;
+ created: string;
+};
\ No newline at end of file
diff --git a/src/lib/types/stack.ts b/src/lib/types/docker/stack.type.ts
similarity index 100%
rename from src/lib/types/stack.ts
rename to src/lib/types/docker/stack.type.ts
diff --git a/src/lib/types/docker/volume.type.ts b/src/lib/types/docker/volume.type.ts
new file mode 100644
index 000000000..2d59071a6
--- /dev/null
+++ b/src/lib/types/docker/volume.type.ts
@@ -0,0 +1,7 @@
+export type ServiceVolume = {
+ name: string;
+ driver: string;
+ scope: string;
+ mountpoint: string;
+ labels: { [label: string]: string } | null;
+};
\ No newline at end of file
diff --git a/src/lib/types/image.ts b/src/lib/types/image.ts
deleted file mode 100644
index 52b5b7b10..000000000
--- a/src/lib/types/image.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import type { ServiceImage } from '$lib/services/docker-service';
-
-export type EnhancedImageInfo = ServiceImage & {
- inUse: boolean;
-};
diff --git a/src/routes/+page.server.ts b/src/routes/+page.server.ts
index d8ed2f776..e3cb6ce48 100644
--- a/src/routes/+page.server.ts
+++ b/src/routes/+page.server.ts
@@ -1,6 +1,8 @@
import type { PageServerLoad } from './$types';
-import { getDockerInfo, listContainers, listImages } from '$lib/services/docker-service';
-import type { ServiceContainer, ServiceImage } from '$lib/services/docker-service';
+import { listContainers } from '$lib/services/docker/container-service';
+import { getDockerInfo } from '$lib/services/docker/core';
+import { listImages } from '$lib/services/docker/image-service';
+import type { ServiceContainer, ServiceImage } from '$lib/types/docker';
// Infer the Docker Info type from the return type of getDockerInfo
type DockerInfoType = Awaited<ReturnType<typeof getDockerInfo>>;
diff --git a/src/routes/+page.svelte b/src/routes/+page.svelte
index 4c2040d92..1729ea663 100644
--- a/src/routes/+page.svelte
+++ b/src/routes/+page.svelte
@@ -7,7 +7,6 @@
import { AlertCircle, Box, HardDrive, Cpu, MemoryStick, ArrowRight, PlayCircle, StopCircle, Trash2, Settings } from '@lucide/svelte';
import * as Alert from '$lib/components/ui/alert/index.js';
import { Progress } from '$lib/components/ui/progress/index.js';
- import { Badge } from '$lib/components/ui/badge/index.js';
import { formatBytes } from '$lib/utils';
import StatusBadge from '$lib/components/badges/status-badge.svelte';
diff --git a/src/routes/api/containers/+server.ts b/src/routes/api/containers/+server.ts
index 20e2210ea..55855e094 100644
--- a/src/routes/api/containers/+server.ts
+++ b/src/routes/api/containers/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { createContainer } from '$lib/services/docker-service';
+import { createContainer } from '$lib/services/docker/container-service';
import type { ContainerConfig } from '$lib/types/docker';
export const POST: RequestHandler = async ({ request }) => {
diff --git a/src/routes/api/docker/containers/+server.ts b/src/routes/api/docker/containers/+server.ts
index 5a6b2c9b5..a45511a85 100644
--- a/src/routes/api/docker/containers/+server.ts
+++ b/src/routes/api/docker/containers/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { listContainers } from '$lib/services/docker-service'; // Import the service function
+import { listContainers } from '$lib/services/docker/container-service';
export const GET: RequestHandler = async () => {
try {
diff --git a/src/routes/api/docker/test-connection/+server.ts b/src/routes/api/docker/test-connection/+server.ts
index c8f3ccf64..310658d6f 100644
--- a/src/routes/api/docker/test-connection/+server.ts
+++ b/src/routes/api/docker/test-connection/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { getDockerInfo } from '$lib/services/docker-service'; // Adjust path if needed
+import { getDockerInfo } from '$lib/services/docker/core'; // Adjust path if needed
export const GET: RequestHandler = async ({ url }) => {
// Get the host to test from query parameters
diff --git a/src/routes/api/images/[id]/+server.ts b/src/routes/api/images/[id]/+server.ts
index 6caab9a13..73c2742cf 100644
--- a/src/routes/api/images/[id]/+server.ts
+++ b/src/routes/api/images/[id]/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { removeImage } from '$lib/services/docker-service';
+import { removeImage } from '$lib/services/docker/image-service';
export const DELETE: RequestHandler = async ({ params, url }) => {
const { id } = params;
diff --git a/src/routes/api/images/prune/+server.ts b/src/routes/api/images/prune/+server.ts
index 3c075c2bd..d07b9dc1d 100644
--- a/src/routes/api/images/prune/+server.ts
+++ b/src/routes/api/images/prune/+server.ts
@@ -1,6 +1,6 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { pruneImages } from '$lib/services/docker-service';
+import { pruneImages } from '$lib/services/docker/image-service';
import { getSettings } from '$lib/services/settings-service';
import { formatBytes } from '$lib/utils';
diff --git a/src/routes/api/images/pull-stream/[...name]/+server.ts b/src/routes/api/images/pull-stream/[...name]/+server.ts
index cdb137b0c..409af8a4a 100644
--- a/src/routes/api/images/pull-stream/[...name]/+server.ts
+++ b/src/routes/api/images/pull-stream/[...name]/+server.ts
@@ -1,5 +1,5 @@
import type { RequestHandler } from './$types';
-import { getDockerClient } from '$lib/services/docker-service';
+import { getDockerClient } from '$lib/services/docker/core';
export const GET: RequestHandler = async ({ params, request }) => {
const imageRef = params.name;
diff --git a/src/routes/api/images/pull/[...name]/+server.ts b/src/routes/api/images/pull/[...name]/+server.ts
index a4465a460..294e102f9 100644
--- a/src/routes/api/images/pull/[...name]/+server.ts
+++ b/src/routes/api/images/pull/[...name]/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from '@sveltejs/kit';
-import { pullImage } from '$lib/services/docker-service';
+import { pullImage } from '$lib/services/docker/image-service';
export const POST: RequestHandler = async ({ params, request }) => {
try {
diff --git a/src/routes/api/networks/[id]/+server.ts b/src/routes/api/networks/[id]/+server.ts
index 5f23cd153..1a93de95c 100644
--- a/src/routes/api/networks/[id]/+server.ts
+++ b/src/routes/api/networks/[id]/+server.ts
@@ -1,6 +1,6 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { removeNetwork } from '$lib/services/docker-service';
+import { removeNetwork } from '$lib/services/docker/network-service';
export const DELETE: RequestHandler = async ({ params }) => {
const networkId = params.id;
diff --git a/src/routes/api/networks/create/+server.ts b/src/routes/api/networks/create/+server.ts
index ffcdb7d19..341b1911d 100644
--- a/src/routes/api/networks/create/+server.ts
+++ b/src/routes/api/networks/create/+server.ts
@@ -1,6 +1,6 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { createNetwork } from '$lib/services/docker-service';
+import { createNetwork } from '$lib/services/docker/network-service';
import type { NetworkCreateOptions } from 'dockerode';
export const POST: RequestHandler = async ({ request }) => {
diff --git a/src/routes/api/stacks/create/+server.ts b/src/routes/api/stacks/create/+server.ts
index 9d6088329..c516eeafe 100644
--- a/src/routes/api/stacks/create/+server.ts
+++ b/src/routes/api/stacks/create/+server.ts
@@ -1,6 +1,6 @@
import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { createStack } from '$lib/services/compose';
+import { createStack } from '$lib/services/docker/stack-service';
export const POST: RequestHandler = async ({ request }) => {
try {
diff --git a/src/routes/api/stacks/import/+server.ts b/src/routes/api/stacks/import/+server.ts
index 44bc97a03..52b78475a 100644
--- a/src/routes/api/stacks/import/+server.ts
+++ b/src/routes/api/stacks/import/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { importExternalStack } from '$lib/services/compose';
+import { importExternalStack } from '$lib/services/docker/stack-service';
export const POST: RequestHandler = async ({ request }) => {
const data = await request.formData();
diff --git a/src/routes/api/volumes/+server.ts b/src/routes/api/volumes/+server.ts
index 2384bfe07..5a08615a5 100644
--- a/src/routes/api/volumes/+server.ts
+++ b/src/routes/api/volumes/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { createVolume } from '$lib/services/docker-service';
+import { createVolume } from '$lib/services/docker/volume-service';
import type { VolumeCreateOptions } from 'dockerode';
export const POST: RequestHandler = async ({ request }) => {
diff --git a/src/routes/api/volumes/[name]/+server.ts b/src/routes/api/volumes/[name]/+server.ts
index a133c81b3..ce0fc8bbe 100644
--- a/src/routes/api/volumes/[name]/+server.ts
+++ b/src/routes/api/volumes/[name]/+server.ts
@@ -1,6 +1,6 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { removeVolume } from '$lib/services/docker-service';
+import { removeVolume } from '$lib/services/docker/volume-service';
export const DELETE: RequestHandler = async ({ params, url }) => {
const { name } = params;
diff --git a/src/routes/columns.ts b/src/routes/columns.ts
index 5eff842b6..dfd220c45 100644
--- a/src/routes/columns.ts
+++ b/src/routes/columns.ts
@@ -1,5 +1,5 @@
import type { ColumnDef } from '@tanstack/table-core';
-import type { ServiceContainer, ServiceImage } from '$lib/services/docker-service';
+import type { ServiceContainer, ServiceImage } from '$lib/types/docker'
import { formatBytes } from '$lib/utils';
import { capitalizeFirstLetter } from '$lib/utils';
import { statusVariantMap } from '$lib/types/statuses';
diff --git a/src/routes/containers/+page.server.ts b/src/routes/containers/+page.server.ts
index 4d1b8de04..f5c2e8cfd 100644
--- a/src/routes/containers/+page.server.ts
+++ b/src/routes/containers/+page.server.ts
@@ -1,5 +1,8 @@
-import { fail, redirect } from '@sveltejs/kit';
-import { listContainers, listVolumes, listNetworks, listImages, createContainer } from '$lib/services/docker-service';
+import { fail } from '@sveltejs/kit';
+import { listContainers, createContainer } from '$lib/services/docker/container-service';
+import { listImages } from '$lib/services/docker/image-service';
+import { listNetworks } from '$lib/services/docker/network-service';
+import { listVolumes } from '$lib/services/docker/volume-service';
import type { PageServerLoad, Actions } from './$types';
import type { ContainerConfig } from '$lib/types/docker';
@@ -49,9 +52,6 @@ export const actions: Actions = {
});
}
- // Log for debugging
- console.log('Creating container with data:', containerData);
-
// Create the container
const container = await createContainer(containerData);
diff --git a/src/routes/containers/+page.svelte b/src/routes/containers/+page.svelte
index 258a66e33..04bc1d8f3 100644
--- a/src/routes/containers/+page.svelte
+++ b/src/routes/containers/+page.svelte
@@ -7,7 +7,7 @@
import { invalidateAll } from '$app/navigation';
import { toast } from 'svelte-sonner';
import CreateContainerDialog from './create-container-dialog.svelte';
- import type { ContainerConfig } from '$lib/types/docker';
+ import type { ContainerConfig, ServiceContainer } from '$lib/types/docker/container.type';
import { enhance } from '$app/forms';
let { data, form } = $props();
@@ -19,11 +19,8 @@
let containerData = $state<ContainerConfig | null>(null);
let formRef: HTMLFormElement;
- // Calculate running containers
- const runningContainers = $derived(containers?.filter((c) => c.state === 'running').length || 0);
-
- // Calculate stopped containers
- const stoppedContainers = $derived(containers?.filter((c) => c.state === 'exited').length || 0);
+ const runningContainers = $derived(containers?.filter((c: ServiceContainer) => c.state === 'running').length || 0);
+ const stoppedContainers = $derived(containers?.filter((c: ServiceContainer) => c.state === 'exited').length || 0);
// Calculate total containers
const totalContainers = $derived(containers?.length || 0);
diff --git a/src/routes/containers/[id]/+page.server.ts b/src/routes/containers/[id]/+page.server.ts
index a79331f5d..52e2e3caa 100644
--- a/src/routes/containers/[id]/+page.server.ts
+++ b/src/routes/containers/[id]/+page.server.ts
@@ -1,5 +1,5 @@
import type { PageServerLoad, Actions } from './$types';
-import { getContainer, startContainer, stopContainer, restartContainer, removeContainer, getContainerLogs } from '$lib/services/docker-service';
+import { getContainer, startContainer, stopContainer, restartContainer, removeContainer, getContainerLogs } from '$lib/services/docker/container-service';
import { error, fail, redirect } from '@sveltejs/kit';
export const load: PageServerLoad = async ({ params }) => {
diff --git a/src/routes/containers/columns.ts b/src/routes/containers/columns.ts
index 17becaa98..17b0578e5 100644
--- a/src/routes/containers/columns.ts
+++ b/src/routes/containers/columns.ts
@@ -1,4 +1,4 @@
-import type { ServiceContainer } from '$lib/services/docker-service';
+import type { ServiceContainer } from '$lib/types/docker';
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table/index.js';
import DataTableActions from './ContainerActions.svelte';
diff --git a/src/routes/containers/create-container-dialog.svelte b/src/routes/containers/create-container-dialog.svelte
index 5b489529f..3bdf89504 100644
--- a/src/routes/containers/create-container-dialog.svelte
+++ b/src/routes/containers/create-container-dialog.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import { preventDefault } from 'svelte/legacy';
- import type { ContainerConfig } from '$lib/types/docker';
+ import type { ContainerConfig } from '$lib/types/docker/container.type';
import type { HealthConfig } from 'dockerode';
import { Button } from '$lib/components/ui/button/index.js';
diff --git a/src/routes/images/+page.server.ts b/src/routes/images/+page.server.ts
index 8303bdf05..91d67b4ae 100644
--- a/src/routes/images/+page.server.ts
+++ b/src/routes/images/+page.server.ts
@@ -1,6 +1,6 @@
import type { PageServerLoad } from './$types';
-import { listImages, isImageInUse } from '$lib/services/docker-service';
-import type { EnhancedImageInfo } from '$lib/types/image';
+import { listImages, isImageInUse } from '$lib/services/docker/image-service';
+import type { EnhancedImageInfo } from '$lib/types/docker';
type ImageData = {
images: EnhancedImageInfo[];
diff --git a/src/routes/images/+page.svelte b/src/routes/images/+page.svelte
index 481927800..b02c8d86f 100644
--- a/src/routes/images/+page.svelte
+++ b/src/routes/images/+page.svelte
@@ -1,6 +1,6 @@
<script lang="ts">
import type { PageData } from './$types';
- import type { EnhancedImageInfo } from '$lib/types/image';
+ import type { EnhancedImageInfo } from '$lib/types/docker';
import UniversalTable from '$lib/components/universal-table.svelte';
import { columns } from './columns';
import { Button } from '$lib/components/ui/button/index.js';
diff --git a/src/routes/images/columns.ts b/src/routes/images/columns.ts
index 4a63d374b..d0791f40c 100644
--- a/src/routes/images/columns.ts
+++ b/src/routes/images/columns.ts
@@ -1,4 +1,4 @@
-import type { ServiceImage } from '$lib/services/docker-service';
+import type { ServiceImage } from '$lib/types/docker';
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table/index.js';
import ImageActions from './ImageActions.svelte';
diff --git a/src/routes/networks/+page.server.ts b/src/routes/networks/+page.server.ts
index dac53cbc8..514d0e66a 100644
--- a/src/routes/networks/+page.server.ts
+++ b/src/routes/networks/+page.server.ts
@@ -1,6 +1,6 @@
import type { PageServerLoad } from './$types';
-import { listNetworks } from '$lib/services/docker-service';
-import type { ServiceNetwork } from '$lib/services/docker-service';
+import { listNetworks } from '$lib/services/docker/network-service';
+import type { ServiceNetwork } from '$lib/types/docker';
// Define the shape of the data returned by the load function
type NetworkPageData = {
diff --git a/src/routes/networks/columns.ts b/src/routes/networks/columns.ts
index f42789849..4b3a52b76 100644
--- a/src/routes/networks/columns.ts
+++ b/src/routes/networks/columns.ts
@@ -2,7 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table/index.js';
import NetworkActions from './NetworkActions.svelte';
import SubnetCell from './SubnetCell.svelte';
-import type { ServiceNetwork } from '$lib/services/docker-service'; // Import the correct type
+import type { ServiceNetwork } from '$lib/types/docker';
// Use the ServiceNetwork type directly
export type NetworkInfo = ServiceNetwork;
diff --git a/src/routes/stacks/+page.server.ts b/src/routes/stacks/+page.server.ts
index 63985d187..346ae966d 100644
--- a/src/routes/stacks/+page.server.ts
+++ b/src/routes/stacks/+page.server.ts
@@ -1,5 +1,5 @@
import { error } from '@sveltejs/kit';
-import { loadComposeStacks, discoverExternalStacks } from '$lib/services/compose';
+import { loadComposeStacks, discoverExternalStacks } from '$lib/services/docker/stack-service';
/** @type {import('./$types').PageServerLoad} */
export async function load() {
diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.ts
index de58dd232..0cd5405d4 100644
--- a/src/routes/stacks/[stackId]/+page.server.ts
+++ b/src/routes/stacks/[stackId]/+page.server.ts
@@ -1,5 +1,5 @@
-import { error, redirect } from '@sveltejs/kit';
-import { getStack, updateStack, startStack, stopStack, restartStack, removeStack } from '$lib/services/compose';
+import { error } from '@sveltejs/kit';
+import { getStack, updateStack, startStack, stopStack, restartStack, removeStack } from '$lib/services/docker/stack-service';
/** @type {import('./$types').PageServerLoad} */
export async function load({ params }) {
diff --git a/src/routes/stacks/columns.ts b/src/routes/stacks/columns.ts
index f7c206e2f..995aa1518 100644
--- a/src/routes/stacks/columns.ts
+++ b/src/routes/stacks/columns.ts
@@ -1,4 +1,4 @@
-import type { Stack } from '$lib/types/stack';
+import type { Stack } from '$lib/types/docker/stack.type';
import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table/index.js';
import StackActions from './StackActions.svelte';
diff --git a/src/routes/volumes/+page.server.ts b/src/routes/volumes/+page.server.ts
index 0f6fd78e9..31d8cc806 100644
--- a/src/routes/volumes/+page.server.ts
+++ b/src/routes/volumes/+page.server.ts
@@ -1,6 +1,6 @@
import type { PageServerLoad } from './$types';
-import { listVolumes, isVolumeInUse } from '$lib/services/docker-service';
-import type { ServiceVolume } from '$lib/services/docker-service';
+import { listVolumes, isVolumeInUse } from '$lib/services/docker/volume-service';
+import type { ServiceVolume } from '$lib/types/docker';
// Enhanced type with usage info
type EnhancedVolumeInfo = ServiceVolume & {
diff --git a/src/routes/volumes/columns.ts b/src/routes/volumes/columns.ts
index 18b0f9af3..c1502d4c8 100644
--- a/src/routes/volumes/columns.ts
+++ b/src/routes/volumes/columns.ts
@@ -2,7 +2,7 @@ import type { ColumnDef } from '@tanstack/table-core';
import { renderComponent } from '$lib/components/ui/data-table/index.js';
import VolumeActions from './VolumeActions.svelte';
import MountpointCell from './MountpointCell.svelte';
-import type { ServiceVolume } from '$lib/services/docker-service';
+import type { ServiceVolume } from '$lib/types/docker';
import UnusedTextBadge from '$lib/components/badges/unused-text-badge.svelte';
// Update the type to include the inUse property