Skip to content

Modern Docker Management, Designed for Everyone

fix: dockerhost from settings not being respected (#171)

Kyle Mendell258c3f8db2e1
diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.ts
index 7c5173206..33be4b791 100644
--- a/src/lib/services/docker/container-service.ts
+++ b/src/lib/services/docker/container-service.ts
@@ -17,9 +17,9 @@ import type Docker from 'dockerode';
*/
export async function listContainers(all = true): Promise<ServiceContainer[]> {
try {
- const docker = getDockerClient();
- const containers = await docker.listContainers({ all });
- return containers.map(
+ const docker = await getDockerClient();
+ const containersData = await docker.listContainers({ all });
+ return containersData.map(
(c): ServiceContainer => ({
id: c.Id,
names: c.Names,
@@ -52,7 +52,7 @@ export async function listContainers(all = true): Promise<ServiceContainer[]> {
*/
export async function getContainer(containerId: string) {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
const inspectData = await container.inspect();
return {
@@ -85,7 +85,7 @@ export async function getContainer(containerId: string) {
*/
export async function startContainer(containerId: string): Promise<void> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
await container.start();
} catch (error: unknown) {
@@ -103,7 +103,7 @@ export async function startContainer(containerId: string): Promise<void> {
*/
export async function stopContainer(containerId: string): Promise<void> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
await container.stop();
} catch (error: unknown) {
@@ -120,7 +120,7 @@ export async function stopContainer(containerId: string): Promise<void> {
*/
export async function restartContainer(containerId: string): Promise<void> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
await container.restart();
} catch (error: unknown) {
@@ -145,7 +145,7 @@ export async function restartContainer(containerId: string): Promise<void> {
*/
export async function removeContainer(containerId: string, force = false): Promise<void> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
// Pass the force option directly to dockerode's remove method
@@ -198,7 +198,7 @@ export async function getContainerLogs(
} = {}
): Promise<string> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
const logOptions = {
@@ -251,7 +251,7 @@ export async function getContainerLogs(
*/
export async function createContainer(config: ContainerConfig) {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const containerOptions: ContainerCreate = {
name: config.name,
@@ -368,7 +368,7 @@ export async function createContainer(config: ContainerConfig) {
*/
export async function getContainerStats(containerId: string): Promise<Docker.ContainerStats | null> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const container = docker.getContainer(containerId);
// Check if container exists first (inspect is a good way)
@@ -432,7 +432,7 @@ export async function getContainerStats(containerId: string): Promise<Docker.Con
* @throws {DockerApiError} If any step fails.
*/
export async function recreateContainer(containerId: string): Promise<ServiceContainer> {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
let originalContainer = null;
try {
diff --git a/src/lib/services/docker/core.ts b/src/lib/services/docker/core.ts
index 18e384087..d35585d57 100644
--- a/src/lib/services/docker/core.ts
+++ b/src/lib/services/docker/core.ts
@@ -1,49 +1,68 @@
import Docker from 'dockerode';
import type { DockerConnectionOptions } from '$lib/types/docker';
+import { getSettings } from '$lib/services/settings-service'; // Assuming getSettings is async and available here
let dockerClient: Docker | null = null;
-export let dockerHost = 'unix:///var/run/docker.sock';
+export let dockerHost = 'unix:///var/run/docker.sock'; // Default and cache for the last used host
/**
- * 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.
+ * The function `getDockerInfo` asynchronously retrieves information about the Docker environment.
*/
export async function getDockerInfo() {
- const docker = getDockerClient();
+ const docker = await getDockerClient(); // Changed: await 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`.
+ * The function `getDockerClient` initializes and returns a Docker client.
+ * It fetches Docker host from settings if the client is not already initialized.
*/
-export function getDockerClient(): Docker {
+export async function getDockerClient(): Promise<Docker> {
+ // Changed: now async
if (!dockerClient) {
- const connectionOpts = createConnectionOptions(dockerHost);
+ console.log('Docker client is null, attempting to initialize.');
+ let hostToUse = dockerHost; // Start with current module-level host (default or last used)
+ try {
+ const currentSettings = await getSettings();
+ if (currentSettings?.dockerHost) {
+ hostToUse = currentSettings.dockerHost;
+ console.log(`Fetched dockerHost from settings: "${hostToUse}"`);
+ } else {
+ console.log('No dockerHost found in settings, will use current module dockerHost or default.');
+ }
+ } catch (err) {
+ console.error('Failed to get settings for Docker client initialization, using fallback:', err);
+ // hostToUse remains as the current dockerHost or default
+ }
- dockerClient = new Docker(connectionOpts);
- console.log(`Initialized Docker client with host: ${dockerHost}`, connectionOpts);
+ console.log(`Initializing Docker client with host: "${hostToUse}".`);
+ const connectionOpts = createConnectionOptions(hostToUse);
+ try {
+ dockerClient = new Docker(connectionOpts);
+ dockerHost = hostToUse; // Update module-level variable to the host actually used.
+ console.log(`Docker client initialized successfully with host: ${dockerHost}`, connectionOpts);
+ } catch (initError) {
+ console.error(`Failed to initialize Docker client with host ${hostToUse}:`, initError);
+ dockerClient = null; // Ensure client is null if initialization fails
+ dockerHost = 'unix:///var/run/docker.sock'; // Reset to default on failure to avoid broken state
+ throw initError; // Re-throw error so caller knows initialization failed
+ }
+ }
+ if (!dockerClient) {
+ console.error('PANIC: Docker client is still null after initialization attempt without throwing error.');
+ throw new Error('Failed to obtain Docker client instance.');
}
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.
+ * The function initializes a Docker connection based on the provided options.
+ * This function is typically called by createConnectionOptions or directly if needed.
+ * Note: This function directly mutates dockerClient and dockerHost module variables.
*/
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;
@@ -65,41 +84,40 @@ export function initializeDocker(options: DockerConnectionOptions): Docker {
/**
* 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.
+ * provided host string. This forces a re-initialization of the client.
*/
-export function updateDockerConnection(host: string): void {
+export function updateDockerConnection(newHost: 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');
+ if (!newHost) {
+ console.warn('No Docker host specified for updateDockerConnection, connection not established');
+ return;
+ }
+
+ if (newHost === dockerHost && dockerClient !== null) {
+ console.log(`Docker host for updateDockerConnection (${newHost}) is the same as current and client exists. No update forced.`);
return;
}
- console.log(`Connecting to Docker at ${host}`);
- const connectionOpts = createConnectionOptions(host);
+ console.log(`updateDockerConnection called. Forcing connection update to Docker at ${newHost}`);
+
+ const connectionOpts = createConnectionOptions(newHost);
+ dockerClient = new Docker(connectionOpts); // Create new client
+ dockerHost = newHost; // Update module-level variable
- dockerClient = new Docker(connectionOpts);
- dockerHost = host;
- console.log('Docker connection updated with options:', connectionOpts);
+ console.log('Docker connection explicitly updated with options:', connectionOpts);
} catch (error) {
- console.error('Error connecting to Docker:', error);
+ console.error(`Error explicitly updating Docker connection to ${newHost}:`, error);
+ dockerClient = null; // Ensure client is null if update fails
}
}
/**
- * 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`.
+ * The function `testDockerConnection` checks if a connection to Docker can be established.
*/
export async function testDockerConnection(): Promise<boolean> {
+ // Changed: now async
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient(); // Changed: await getDockerClient
const info = await docker.info();
return !!info;
} catch (err) {
@@ -140,7 +158,12 @@ function createConnectionOptions(host: string): Record<string, any> {
}
/* 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. */
+default export of the module. */
export default getDockerClient;
+
+/**
+ * Perform any other necessary cleanup for this module if needed.
+ */
+export function cleanup() {
+ console.log('core.ts cleanup called.');
+}
diff --git a/src/lib/services/docker/image-service.ts b/src/lib/services/docker/image-service.ts
index 92923b009..43e9e5f55 100644
--- a/src/lib/services/docker/image-service.ts
+++ b/src/lib/services/docker/image-service.ts
@@ -14,7 +14,7 @@ import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors'
*/
export async function listImages(): Promise<ServiceImage[]> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const images = await docker.listImages({ all: false });
const parseRepoTag = (tag: string | undefined): { repo: string; tag: string } => {
@@ -62,7 +62,7 @@ export async function listImages(): Promise<ServiceImage[]> {
*/
export async function getImage(imageId: string): Promise<Docker.ImageInspectInfo> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const image = docker.getImage(imageId);
const inspectInfo = await image.inspect();
console.log(`Docker Service: Inspected image "${imageId}" successfully.`);
@@ -88,7 +88,7 @@ export async function getImage(imageId: string): Promise<Docker.ImageInspectInfo
*/
export async function removeImage(imageId: string, force: boolean = false): Promise<void> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const image = docker.getImage(imageId);
await image.remove({ force });
console.log(`Docker Service: Image "${imageId}" removed successfully.`);
@@ -112,7 +112,7 @@ export async function removeImage(imageId: string, force: boolean = false): Prom
*/
export async function isImageInUse(imageId: string): Promise<boolean> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const containers = await docker.listContainers({ all: true });
// Look for containers using this image
@@ -138,7 +138,7 @@ export async function pruneImages(mode: 'all' | 'dangling' = 'all'): Promise<{
SpaceReclaimed: number;
}> {
try {
- const docker = getDockerClient();
+ const docker = await 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)...';
@@ -169,7 +169,7 @@ export async function pruneImages(mode: 'all' | 'dangling' = 'all'): Promise<{
* @param {object} [authConfig] - Optional authentication configuration for private registries
*/
export async function pullImage(imageRef: string, platform?: string, authConfig?: any): Promise<void> {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const pullOptions: any = {};
if (platform) {
diff --git a/src/lib/services/docker/network-service.ts b/src/lib/services/docker/network-service.ts
index ef31ec16f..dfece497d 100644
--- a/src/lib/services/docker/network-service.ts
+++ b/src/lib/services/docker/network-service.ts
@@ -20,7 +20,7 @@ export const DEFAULT_NETWORK_NAMES = new Set(['host', 'bridge', 'none', 'ingress
*/
export async function listNetworks(): Promise<ServiceNetwork[]> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const networks = await docker.listNetworks();
return networks.map(
(net): ServiceNetwork => ({
@@ -48,7 +48,7 @@ export async function listNetworks(): Promise<ServiceNetwork[]> {
*/
export async function getNetwork(networkId: string): Promise<NetworkInspectInfo> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const network = docker.getNetwork(networkId);
const inspectInfo = await network.inspect();
console.log(`Docker Service: Inspected network "${networkId}" successfully.`);
@@ -81,7 +81,7 @@ export async function removeNetwork(networkId: string): Promise<void> {
if (DEFAULT_NETWORK_NAMES.has(networkId)) {
throw new ConflictError(`Network "${networkId}" is managed by Docker and cannot be removed.`);
}
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const network = docker.getNetwork(networkId);
await network.remove();
console.log(`Docker Service: Network "${networkId}" removed successfully.`);
@@ -114,7 +114,7 @@ export async function removeNetwork(networkId: string): Promise<void> {
*/
export async function createNetwork(options: NetworkCreateOptions): Promise<NetworkInspectInfo> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
console.log(`Docker Service: Creating network "${options.Name}"...`, options);
// Dockerode's createNetwork returns the Network object, we need to inspect it after creation
diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.ts
index 0e5f05375..8d799ed2b 100644
--- a/src/lib/services/docker/stack-service.ts
+++ b/src/lib/services/docker/stack-service.ts
@@ -194,7 +194,7 @@ async function loadEnvFile(stackId: string): Promise<string> {
* `getComposeFilePath(stackId)`, and the `stackId` parameter.
*/
async function getComposeInstance(stackId: string): Promise<DockerodeCompose> {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const composePath = await getComposeFilePath(stackId);
if (!composePath) {
throw new Error(`Compose file not found for stack ${stackId}`);
@@ -218,7 +218,7 @@ async function getComposeInstance(stackId: string): Promise<DockerodeCompose> {
* 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();
+ const docker = await getDockerClient();
const composeProjectLabel = 'com.docker.compose.project'; // Standard label
const composeServiceLabel = 'com.docker.compose.service'; // Standard service label
@@ -641,7 +641,7 @@ export async function startStack(stackId: string): Promise<boolean> {
*/
export async function stopStack(stackId: string): Promise<boolean> {
console.log(`Attempting to stop stack ${stackId} by manually stopping containers...`);
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const composeProjectLabel = 'com.docker.compose.project';
let stoppedCount = 0;
let removedCount = 0;
@@ -959,7 +959,7 @@ export async function renameStack(currentStackId: string, newName: string): Prom
*/
export async function discoverExternalStacks(): Promise<Stack[]> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const containers = await docker.listContainers({ all: true });
const composeProjectLabel = 'com.docker.compose.project';
@@ -1040,7 +1040,7 @@ export async function discoverExternalStacks(): Promise<Stack[]> {
*/
export async function importExternalStack(stackId: string): Promise<Stack> {
// 1. First, check if we can find the stack by ID
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const containers = await docker.listContainers({ all: true });
// Filter containers that belong to this stack
@@ -1197,7 +1197,7 @@ export async function listStacks(includeExternal = false): Promise<Stack[]> {
* @returns {Promise<boolean>} - True if any container in the stack is running.
*/
export async function isStackRunning(stackId: string): Promise<boolean> {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const composeProjectLabel = 'com.docker.compose.project';
try {
diff --git a/src/lib/services/docker/system-service.ts b/src/lib/services/docker/system-service.ts
index 2651976f9..e2263bbba 100644
--- a/src/lib/services/docker/system-service.ts
+++ b/src/lib/services/docker/system-service.ts
@@ -5,7 +5,7 @@ import type { Settings } from '$lib/types/settings.type';
type PruneType = 'containers' | 'images' | 'networks' | 'volumes';
type PruneServiceResult = PruneResult & { type: PruneType; error?: string };
-const docker = getDockerClient();
+const docker = await getDockerClient();
/**
* Prunes specified Docker resources sequentially, fetching settings to determine image prune mode.
diff --git a/src/lib/services/docker/volume-service.ts b/src/lib/services/docker/volume-service.ts
index 9516457ed..c7b46edb2 100644
--- a/src/lib/services/docker/volume-service.ts
+++ b/src/lib/services/docker/volume-service.ts
@@ -14,7 +14,7 @@ import { NotFoundError, ConflictError, DockerApiError } from '$lib/types/errors'
*/
export async function listVolumes(): Promise<ServiceVolume[]> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const volumeResponse = await docker.listVolumes();
const volumes = volumeResponse.Volumes || [];
@@ -45,7 +45,7 @@ export async function listVolumes(): Promise<ServiceVolume[]> {
*/
export async function isVolumeInUse(volumeName: string): Promise<boolean> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const containers = await docker.listContainers({ all: true });
// Inspect each container to check its mounts
for (const containerInfo of containers) {
@@ -71,7 +71,7 @@ export async function isVolumeInUse(volumeName: string): Promise<boolean> {
*/
export async function getVolume(volumeName: string): Promise<VolumeInspectInfo> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const volume = docker.getVolume(volumeName);
const inspectInfo = await volume.inspect();
console.log(`Docker Service: Inspected volume "${volumeName}" successfully.`);
@@ -101,7 +101,7 @@ export async function getVolume(volumeName: string): Promise<VolumeInspectInfo>
*/
export async function createVolume(options: VolumeCreateOptions): Promise<ServiceVolume> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
// createVolume returns the volume data directly - no need to inspect
const volume = await docker.createVolume(options);
@@ -142,7 +142,7 @@ export async function createVolume(options: VolumeCreateOptions): Promise<Servic
*/
export async function removeVolume(name: string, force = false): Promise<void> {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const volume = docker.getVolume(name);
await volume.remove({ force });
console.log(`Docker Service: Volume "${name}" removed successfully (force=${force}).`);
diff --git a/src/routes/api/containers/[containerId]/logs/stream/+server.ts b/src/routes/api/containers/[containerId]/logs/stream/+server.ts
index 3203409e3..1656597b5 100644
--- a/src/routes/api/containers/[containerId]/logs/stream/+server.ts
+++ b/src/routes/api/containers/[containerId]/logs/stream/+server.ts
@@ -7,7 +7,7 @@ import { tryCatch } from '$lib/utils/try-catch';
export const GET: RequestHandler = async ({ params }) => {
const { containerId } = params;
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const result = await tryCatch(
(async () => {
diff --git a/src/routes/api/containers/[containerId]/stats/stream/+server.ts b/src/routes/api/containers/[containerId]/stats/stream/+server.ts
index 90f4836fe..af026f8fd 100644
--- a/src/routes/api/containers/[containerId]/stats/stream/+server.ts
+++ b/src/routes/api/containers/[containerId]/stats/stream/+server.ts
@@ -7,7 +7,7 @@ import { tryCatch } from '$lib/utils/try-catch';
export const GET: RequestHandler = async ({ params, request }) => {
const { containerId } = params;
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const result = await tryCatch(
(async () => {
diff --git a/src/routes/api/images/pull-stream/[...name]/+server.ts b/src/routes/api/images/pull-stream/[...name]/+server.ts
index 594dc4783..2c75bdba9 100644
--- a/src/routes/api/images/pull-stream/[...name]/+server.ts
+++ b/src/routes/api/images/pull-stream/[...name]/+server.ts
@@ -38,7 +38,7 @@ export const GET: RequestHandler = async ({ params, request }) => {
const stream = new ReadableStream({
async start(controller) {
try {
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const settings = await getSettings();
function send(data: any) {
diff --git a/src/routes/api/settings/+server.ts b/src/routes/api/settings/+server.ts
index e62e84ee8..15fa45502 100644
--- a/src/routes/api/settings/+server.ts
+++ b/src/routes/api/settings/+server.ts
@@ -1,14 +1,19 @@
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
-import { getSettings, saveSettings } from '$lib/services/settings-service';
+import { getSettings as getPersistedSettings, saveSettings as persistSettings } from '$lib/services/settings-service';
import type { Settings } from '$lib/types/settings.type';
import { initComposeService } from '$lib/services/docker/stack-service';
import { initAutoUpdateScheduler, stopAutoUpdateScheduler } from '$lib/services/docker/scheduler-service';
import { ApiErrorCode, type ApiErrorResponse } from '$lib/types/errors.type';
import { tryCatch } from '$lib/utils/try-catch';
+import { updateSettingsStore } from '$lib/stores/settings-store'; // To update server-side store instance
+import {
+ updateDockerConnection,
+ dockerHost as currentCoreDockerHost // Import the current host from core.ts
+} from '$lib/services/docker/core';
export const GET: RequestHandler = async () => {
- const result = await tryCatch(getSettings());
+ const result = await tryCatch(getPersistedSettings());
if (result.error) {
console.error('API Error fetching settings:', result.error);
const response: ApiErrorResponse = {
@@ -32,23 +37,10 @@ export const PUT: RequestHandler = async ({ request }) => {
};
return json(response, { status: 400 });
}
- const body = bodyResult.data;
+ const newSettingsData = bodyResult.data as Settings; // Renamed for clarity
- const currentSettingsResult = await tryCatch(getSettings());
- if (currentSettingsResult.error) {
- console.error('API Error fetching current settings:', currentSettingsResult.error);
- const response: ApiErrorResponse = {
- success: false,
- error: currentSettingsResult.error.message || 'Failed to fetch current settings',
- code: ApiErrorCode.INTERNAL_SERVER_ERROR,
- details: currentSettingsResult.error
- };
- return json(response, { status: 500 });
- }
- const currentSettings = currentSettingsResult.data;
-
- // Validate required fields
- if (!body.dockerHost) {
+ // Validate required fields (using newSettingsData)
+ if (!newSettingsData.dockerHost) {
const response: ApiErrorResponse = {
success: false,
error: 'Docker host cannot be empty.',
@@ -56,7 +48,7 @@ export const PUT: RequestHandler = async ({ request }) => {
};
return json(response, { status: 400 });
}
- if (!body.stacksDirectory) {
+ if (!newSettingsData.stacksDirectory) {
const response: ApiErrorResponse = {
success: false,
error: 'Stacks directory cannot be empty.',
@@ -65,25 +57,39 @@ export const PUT: RequestHandler = async ({ request }) => {
return json(response, { status: 400 });
}
- // Normalize boolean values (handle string representation from form data)
- const booleanFields = ['autoUpdate', 'pollingEnabled'];
- const nestedAuthBooleanFields = ['localAuthEnabled', 'rbacEnabled'];
+ // Normalize boolean values.
+ // Ensure that the keys listed in booleanFields correspond to properties in Settings
+ // that are intended to be booleans (e.g., defined as `boolean` or `boolean | undefined`).
+ const booleanFields: Array<keyof Settings> = ['autoUpdate', 'pollingEnabled'];
booleanFields.forEach((field) => {
- if (field in body && typeof body[field] === 'string') {
- body[field] = body[field] === 'true';
+ const currentValue = newSettingsData[field];
+ if (typeof currentValue === 'string') {
+ // If currentValue is a string, convert it to boolean and assign back.
+ // Using `as Record<string, any>` for the assignment target can help if TypeScript
+ // has issues with the specific indexed assignment `newSettingsData[field] = boolean_value;`
+ (newSettingsData as Record<string, any>)[field] = currentValue.toLowerCase() === 'true';
}
});
- if (body.auth) {
+
+ // Normalize boolean values for nested auth settings.
+ // Ensure keys in nestedAuthBooleanFields correspond to boolean properties in Settings['auth'].
+ if (newSettingsData.auth) {
+ // Define keys more safely based on the actual type of newSettingsData.auth
+ const nestedAuthBooleanFields: Array<keyof typeof newSettingsData.auth> = ['localAuthEnabled', 'rbacEnabled'];
nestedAuthBooleanFields.forEach((field) => {
- if (field in body.auth && typeof body.auth[field] === 'string') {
- body.auth[field] = body.auth[field] === 'true';
+ // Ensure the field is a key of newSettingsData.auth before accessing
+ if (Object.prototype.hasOwnProperty.call(newSettingsData.auth, field)) {
+ const currentValue = newSettingsData.auth[field];
+ if (typeof currentValue === 'string') {
+ (newSettingsData.auth as Record<string, any>)[field] = currentValue.toLowerCase() === 'true';
+ }
}
});
}
// Validate polling interval if polling is enabled
- if (body.pollingEnabled) {
- const pollingInterval = parseInt(body.pollingInterval, 10);
+ if (newSettingsData.pollingEnabled) {
+ const pollingInterval = parseInt(String(newSettingsData.pollingInterval), 10);
if (isNaN(pollingInterval) || pollingInterval < 5 || pollingInterval > 60) {
const response: ApiErrorResponse = {
success: false,
@@ -92,76 +98,26 @@ export const PUT: RequestHandler = async ({ request }) => {
};
return json(response, { status: 400 });
}
- body.pollingInterval = pollingInterval;
+ newSettingsData.pollingInterval = pollingInterval;
}
// Validate auto-update interval if enabled
- if (body.autoUpdate) {
- const autoUpdateInterval = parseInt(body.autoUpdateInterval, 10);
+ if (newSettingsData.autoUpdate) {
+ const autoUpdateInterval = parseInt(String(newSettingsData.autoUpdateInterval), 10);
if (isNaN(autoUpdateInterval) || autoUpdateInterval < 5) {
- body.autoUpdateInterval = 60;
- } else {
- const validatedAutoUpdateInterval = Math.min(Math.max(autoUpdateInterval, 5), 1440);
- body.autoUpdateInterval = validatedAutoUpdateInterval;
- }
- }
-
- // Ensure nested objects exist if they are partially updated
- if (!body.externalServices) body.externalServices = {};
- if (!body.auth) body.auth = {};
-
- // Handle registry credentials
- if (body.registryCredentials && typeof body.registryCredentials === 'string') {
- try {
- body.registryCredentials = JSON.parse(body.registryCredentials);
- } catch (e) {
- console.error('Error parsing registry credentials', e);
- body.registryCredentials = currentSettings.registryCredentials;
- }
- }
-
- // Handle authentication settings
- if (body.authentication && typeof body.authentication === 'string') {
- try {
- body.authentication = JSON.parse(body.authentication);
- } catch (e) {
- console.error('Error parsing authentication settings', e);
- body.authentication = currentSettings.auth;
- }
- }
-
- // Handle Auth settings
- if (body.auth !== undefined) {
- body.auth = {
- localAuthEnabled: body.auth.localAuthEnabled ?? currentSettings.auth?.localAuthEnabled ?? true,
- sessionTimeout: body.auth.sessionTimeout ?? currentSettings.auth?.sessionTimeout ?? 60,
- passwordPolicy: body.auth.passwordPolicy ?? currentSettings.auth?.passwordPolicy ?? 'strong'
- };
- } else if (currentSettings.auth) {
- body.auth = currentSettings.auth;
- }
-
- // Add onboarding to accepted fields
- if (body.onboarding) {
- if (typeof body.onboarding.completed === 'string') {
- body.onboarding.completed = body.onboarding.completed === 'true';
- }
- if (!body.onboarding.completedAt) {
- body.onboarding.completedAt = new Date().toISOString();
+ const response: ApiErrorResponse = {
+ success: false,
+ error: 'Auto-update interval must be at least 5 minutes.',
+ code: ApiErrorCode.BAD_REQUEST
+ };
+ return json(response, { status: 400 });
}
+ newSettingsData.autoUpdateInterval = autoUpdateInterval;
}
- // Merge settings
- const updatedSettings: Settings = {
- ...currentSettings,
- ...body
- };
- if (body.pruneMode) {
- updatedSettings.pruneMode = body.pruneMode as 'all' | 'dangling';
- }
+ // Persist the validated new settings to disk
+ const saveResult = await tryCatch(persistSettings(newSettingsData));
- // Save updated settings
- const saveResult = await tryCatch(saveSettings(updatedSettings));
if (saveResult.error) {
console.error('API Error saving settings:', saveResult.error);
const response: ApiErrorResponse = {
@@ -173,34 +129,27 @@ export const PUT: RequestHandler = async ({ request }) => {
return json(response, { status: 500 });
}
- // Handle Docker connection changes
- const dockerHostChanged = currentSettings.dockerHost !== updatedSettings.dockerHost;
- const stacksDirChanged = currentSettings.stacksDirectory !== updatedSettings.stacksDirectory;
- if (dockerHostChanged || stacksDirChanged) {
- const initResult = await tryCatch(initComposeService());
- if (initResult.error) {
- console.error('API Error initializing compose service:', initResult.error);
- // Not returning error since settings were saved successfully
- }
+ console.log('API: Settings saved to disk successfully.');
+
+ // Update the server-side in-memory Svelte store instance.
+ updateSettingsStore(newSettingsData);
+ console.log('API: Server-side settingsStore updated.');
+
+ // Check if Docker host changed and update Docker connection in core.ts if needed
+ const newDockerHost = newSettingsData.dockerHost;
+ if (newDockerHost && newDockerHost !== currentCoreDockerHost) {
+ console.log(`API: Docker host changed from "${currentCoreDockerHost}" to "${newDockerHost}". Updating Docker connection.`);
+ updateDockerConnection(newDockerHost);
+ } else if (newDockerHost) {
+ console.log(`API: Docker host "${newDockerHost}" is the same as current "${currentCoreDockerHost}". No Docker connection update forced from API.`);
}
- // Handle auto-update changes
- const autoUpdateChanged = currentSettings.autoUpdate !== updatedSettings.autoUpdate || currentSettings.autoUpdateInterval !== updatedSettings.autoUpdateInterval;
- if (autoUpdateChanged) {
- if (updatedSettings.autoUpdate) {
- await tryCatch(stopAutoUpdateScheduler());
- const schedulerResult = await tryCatch(initAutoUpdateScheduler());
- if (schedulerResult.error) {
- console.error('API Error initializing auto-update scheduler:', schedulerResult.error);
- }
- } else {
- await tryCatch(stopAutoUpdateScheduler());
- }
+ // Re-initialize services that depend on settings
+ await tryCatch(initComposeService());
+ await tryCatch(stopAutoUpdateScheduler());
+ if (newSettingsData.autoUpdate) {
+ await tryCatch(initAutoUpdateScheduler());
}
- return json({
- success: true,
- message: 'Settings updated successfully',
- settings: updatedSettings
- });
+ return json({ success: true, message: 'Settings updated successfully' });
};
diff --git a/src/routes/api/stacks/[stackId]/pull/+server.ts b/src/routes/api/stacks/[stackId]/pull/+server.ts
index f0068e4bf..caa0efe6c 100644
--- a/src/routes/api/stacks/[stackId]/pull/+server.ts
+++ b/src/routes/api/stacks/[stackId]/pull/+server.ts
@@ -6,7 +6,6 @@ import { getDockerClient } from '$lib/services/docker/core';
import { extractDockerErrorMessage } from '$lib/utils/errors.util';
import { URL } from 'url';
import { getSettings } from '$lib/services/settings-service';
-import type { RegistryCredential } from '$lib/types/settings.type';
import { areRegistriesEquivalent, parseImageNameForRegistry } from '$lib/utils/registry.utils';
import { json } from '@sveltejs/kit';
@@ -19,7 +18,7 @@ interface AuthConfig {
export const POST: RequestHandler = async ({ params, request }) => {
const id = params.stackId;
- const docker = getDockerClient();
+ const docker = await getDockerClient();
const reqUrl = new URL(request.url);
const platform = reqUrl.searchParams.get('platform');