Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
feat: auto update containers and stacks (#83)
Kyle Mendell0a5132fed65d
diff --git a/src/hooks.server.ts b/src/hooks.server.tsindex adbb104ed..5b6494a72 100644--- a/src/hooks.server.ts+++ b/src/hooks.server.ts@@ -1,9 +1,13 @@import { initComposeService } from '$lib/services/docker/stack-service';+import { initAutoUpdateScheduler } from '$lib/services/docker/scheduler-service';// Initialize needed services-initComposeService().catch((err) => {- console.error('Failed to initialize compose service:', err);-});+try {+ await Promise.all([initComposeService(), initAutoUpdateScheduler()]);+} catch (err) {+ console.error('Critical service init failed, exiting:', err);+ process.exit(1);+}export async function handle({ event, resolve }) {return await resolve(event);diff --git a/src/lib/services/docker/auto-update-service.ts b/src/lib/services/docker/auto-update-service.tsnew file mode 100644index 000000000..d02925a08--- /dev/null+++ b/src/lib/services/docker/auto-update-service.ts@@ -0,0 +1,281 @@+import { listContainers, getContainer, recreateContainer } from './container-service'; // Import recreateContainer, remove restartContainer+import { listStacks, getStack, fullyRedeployStack } from './stack-service';+import { pullImage, getImage, listImages } from './image-service';+import { getSettings } from '../settings-service';+import type { ServiceContainer } from '$lib/types/docker';+import type { Stack } from '$lib/types/docker/stack.type';++// Track which entities are being updated to avoid concurrent updates+const updatingContainers = new Set<string>();+const updatingStacks = new Set<string>();++/**+ * Checks for container image updates and applies them if configured+ */+export async function checkAndUpdateContainers(): Promise<{+ checked: number;+ updated: number;+ errors: Array<{ id: string; error: string }>;+}> {+ const settings = await getSettings();++ // Skip if global auto-update is disabled+ if (!settings.autoUpdate) {+ return { checked: 0, updated: 0, errors: [] };+ }++ const containers = await listContainers();++ // Get detailed container info for each container to access labels+ const eligibleContainers: ServiceContainer[] = [];++ for (const container of containers) {+ // Skip containers that aren't running+ if (container.state !== 'running') continue;++ try {+ // Get detailed container info to access labels+ const containerDetails = await getContainer(container.id);++ // Check if auto-update label exists and is set to true+ if (containerDetails?.labels?.['arcane.auto-update'] === 'true') {+ eligibleContainers.push(container);+ }+ } catch (error) {+ console.error(`Error fetching container details for ${container.id}:`, error);+ }+ }++ const results = {+ checked: eligibleContainers.length,+ updated: 0,+ errors: [] as Array<{ id: string; error: string }>+ };++ // Process eligible containers+ for (const container of eligibleContainers) {+ const containerId = container.id; // Use consistent ID variable+ try {+ // Skip if already being updated+ if (updatingContainers.has(containerId)) {+ console.log(`Auto-update: Skipping ${container.name} (${containerId}), already in progress.`);+ continue;+ }++ const updateAvailable = await checkContainerImageUpdate(container);+ if (updateAvailable) {+ updatingContainers.add(containerId);+ console.log(`Auto-update: Update found for container ${container.name} (${containerId}). Recreating...`);++ // Pull the latest image first+ console.log(`Auto-update: Pulling latest image ${container.image} for ${container.name}...`);+ await pullImage(container.image);++ // Recreate the container using the new helper function+ await recreateContainer(containerId);++ console.log(`Auto-update: Container ${container.name} recreated successfully`);+ results.updated++;++ updatingContainers.delete(containerId);+ } else {+ console.log(`Auto-update: Container ${container.name} (${containerId}) is up-to-date.`);+ }+ } catch (error: any) {+ console.error(`Auto-update error for container ${containerId}:`, error);+ results.errors.push({+ id: containerId,+ error: error.message || 'Unknown error during auto-update'+ });+ // Ensure the lock is released even on error+ updatingContainers.delete(containerId);+ }+ }++ return results;+}++/**+ * Checks for stack updates and applies them if configured+ */+export async function checkAndUpdateStacks(): Promise<{+ checked: number;+ updated: number;+ errors: Array<{ id: string; error: string }>;+}> {+ const settings = await getSettings();++ // Skip if global auto-update is disabled+ if (!settings.autoUpdate) {+ return { checked: 0, updated: 0, errors: [] };+ }++ const stacks = await listStacks();+ const eligibleStacks = stacks.filter(+ (s) =>+ // Only consider running stacks with auto-update enabled+ (s.status === 'running' || s.status === 'partially running') && s.meta && s.meta.autoUpdate === true+ );++ const results = {+ checked: eligibleStacks.length,+ updated: 0,+ errors: [] as Array<{ id: string; error: string }>+ };++ // Process eligible stacks+ for (const stack of eligibleStacks) {+ try {+ // Skip if already being updated+ if (updatingStacks.has(stack.id)) continue;++ const updateAvailable = await checkStackImagesUpdate(stack);+ if (updateAvailable) {+ updatingStacks.add(stack.id);++ console.log(`Auto-update: Redeploying stack ${stack.name} (${stack.id})`);+ await fullyRedeployStack(stack.id);++ console.log(`Auto-update: Stack ${stack.name} redeployed successfully`);+ results.updated++;++ updatingStacks.delete(stack.id);+ }+ } catch (error: any) {+ console.error(`Auto-update error for stack ${stack.id}:`, error);+ results.errors.push({+ id: stack.id,+ error: error.message || 'Unknown error during auto-update'+ });+ updatingStacks.delete(stack.id);+ }+ }++ return results;+}++/**+ * Checks if a container's image has an update available+ */+async function checkContainerImageUpdate(container: ServiceContainer): Promise<boolean> {+ try {+ const imageRef = container.image;+ // Skip digest-only references (e.g. sha256:… – they can’t be updated by tag)+ if (/^sha256:[A-Fa-f0-9]{64}$/.test(imageRef)) {+ return false;+ }++ // Current image digest+ const currentImage = await getImage(container.imageId);+ if (!currentImage) return false;++ // Pull the image to check for updates (but don't use it yet)+ await pullImage(imageRef);++ // Get the fresh image info+ const lastColon = imageRef.lastIndexOf(':');+ const imageName = lastColon === -1 ? imageRef : imageRef.slice(0, lastColon);+ const tag = lastColon === -1 ? 'latest' : imageRef.slice(lastColon + 1);+ const freshImages = await listImages();+ const freshImage = freshImages.find((img) => (img.repo === imageName || img.repo.endsWith(`/${imageName}`)) && img.tag === tag);++ if (!freshImage) return false;++ // Compare image IDs - if different, update is available+ return freshImage.id !== container.imageId;+ } catch (error) {+ console.error(`Error checking for image update for ${container.name}:`, error);+ return false;+ }+}++/**+ * Checks if any images referenced in a stack's compose file have updates available.+ * Iterates through all images and returns true if at least one has a new digest.+ */+async function checkStackImagesUpdate(stack: Stack): Promise<boolean> {+ let updateFound = false; // Flag to track if any update is found++ try {+ const fullStack = await getStack(stack.id);+ if (!fullStack || !fullStack.composeContent) {+ console.warn(`Stack ${stack.name} (${stack.id}) compose content not found.`);+ return false;+ }++ // Extract image references from compose file (simplified parsing)+ const composeLines = fullStack.composeContent.split('\n');+ const imageLines = composeLines.filter((line) => line.trim().startsWith('image:') || line.includes(' image:'));++ if (imageLines.length === 0) {+ console.log(`No image references found in stack ${stack.name}.`);+ return false;+ }++ const imageRefs = imageLines+ .map((line) => {+ const imagePart = line.split('image:')[1].trim();+ // Handle potential comments or extra content on the line+ return imagePart.replace(/['"]/g, '').split(/[\s#]/)[0];+ })+ .filter((ref) => ref && (ref.includes(':') || ref.includes('/'))); // Filter out invalid/local refs++ const uniqueImageRefs = [...new Set(imageRefs)]; // Check each unique image only once+ console.log(`Checking images for stack ${stack.name}: ${uniqueImageRefs.join(', ')}`);++ // Check each unique image for updates+ for (const imageRef of uniqueImageRefs) {+ try {+ // 1. Get current image details (if it exists locally)+ let currentImageId: string | null = null;+ try {+ const currentImage = await getImage(imageRef);+ if (currentImage) {+ currentImageId = currentImage.Id; // Use the full ID (digest)+ }+ } catch (e: any) {+ // Ignore errors if image doesn't exist locally yet+ if (e.statusCode !== 404) {+ console.warn(`Could not get current details for image ${imageRef}: ${e.message}`);+ }+ }++ // 2. Pull the image to get the latest version+ console.log(`Pulling ${imageRef} to check for updates...`);+ await pullImage(imageRef); // This might throw if pull fails++ // 3. Get new image details after pull+ let newImageId: string | null = null;+ try {+ const newImage = await getImage(imageRef); // Get details of the potentially updated image+ if (newImage) {+ newImageId = newImage.Id;+ } else {+ console.warn(`Image ${imageRef} not found after pull.`);+ continue; // Skip if image disappeared after pull (unlikely)+ }+ } catch (e: any) {+ console.error(`Could not get details for image ${imageRef} after pull: ${e.message}`);+ continue; // Skip this image if we can't get its details+ }++ // 4. Compare IDs+ if (newImageId && newImageId !== currentImageId) {+ console.log(`Update found for image ${imageRef} in stack ${stack.name}. New ID: ${newImageId}, Old ID: ${currentImageId}`);+ updateFound = true;+ // Do NOT return early, continue checking other images+ } else {+ console.log(`Image ${imageRef} is up-to-date.`);+ }+ } catch (error: any) {+ console.error(`Error checking/pulling image update for ${imageRef} in stack ${stack.name}:`, error.message || error);+ // Continue checking other images even if one fails+ }+ } // End of loop through imageRefs++ return updateFound; // Return true only if at least one update was found+ } catch (error: any) {+ console.error(`Error processing stack updates for ${stack.name}:`, error.message || error);+ return false; // Return false if there's an error processing the stack itself+ }+}diff --git a/src/lib/services/docker/container-service.ts b/src/lib/services/docker/container-service.tsindex bb6d93992..865b3d626 100644--- a/src/lib/services/docker/container-service.ts+++ b/src/lib/services/docker/container-service.ts@@ -65,7 +65,8 @@ export async function getContainer(containerId: string) {image: inspectData.Image,config: inspectData.Config,networkSettings: inspectData.NetworkSettings,- mounts: inspectData.Mounts+ mounts: inspectData.Mounts,+ labels: inspectData.Config.Labels};} catch (error: any) {console.error(`Docker Service: Error getting container ${containerId}:`, error);@@ -396,3 +397,108 @@ export async function getContainerStats(containerId: string): Promise<Docker.Conthrow new DockerApiError(`Failed to get stats for container ${containerId}: ${error.message || 'Unknown Docker error'}`, error.statusCode);}}++/**+ * Recreates a container with the same configuration but potentially a newer image.+ * Stops, removes the old container, creates a new one, and starts it.+ * Assumes the image tag used in the original config now points to the desired (potentially updated) image.+ * @param {string} containerId - The ID of the container to recreate.+ * @returns {Promise<ServiceContainer>} Information about the newly created and started container.+ * @throws {DockerApiError} If any step fails.+ */+export async function recreateContainer(containerId: string): Promise<ServiceContainer> {+ const docker = getDockerClient();+ let originalContainer = null;++ try {+ console.log(`Recreating container ${containerId}: Fetching original config...`);+ // 1. Get existing container details+ originalContainer = await getContainer(containerId);+ if (!originalContainer) {+ throw new DockerApiError(`Container ${containerId} not found for recreation.`, 404);+ }++ // Extract necessary config parts+ const createOptions: Docker.ContainerCreateOptions = {+ name: originalContainer.name,+ Image: originalContainer.config.Image,+ Env: originalContainer.config.Env,+ Labels: originalContainer.labels,+ ExposedPorts: originalContainer.config.ExposedPorts,+ HostConfig: {+ PortBindings: originalContainer.networkSettings?.Ports || {},+ NetworkMode: originalContainer.networkSettings?.Networks?.bridge ? 'bridge' : Object.keys(originalContainer.networkSettings?.Networks || {})[0] || undefined,+ Binds: originalContainer.mounts?.filter((mount) => mount.Type === 'bind' || mount.Type === 'volume').map((mount) => `${mount.Source}:${mount.Destination}${mount.RW ? '' : ':ro'}`)+ },+ Cmd: originalContainer.config.Cmd,+ Entrypoint: originalContainer.config.Entrypoint,+ WorkingDir: originalContainer.config.WorkingDir,+ User: originalContainer.config.User,+ Volumes: originalContainer.config.Volumes,+ Tty: originalContainer.config.Tty,+ OpenStdin: originalContainer.config.OpenStdin,+ StdinOnce: originalContainer.config.StdinOnce+ };++ // If we need to add custom network configuration for non-default networks+ if (originalContainer.networkSettings?.Networks) {+ const networks = Object.entries(originalContainer.networkSettings.Networks);+ // If container uses a non-default network, set it up+ if (networks.length > 0 && networks[0][0] !== 'bridge') {+ const [networkName, networkConfig] = networks[0];+ createOptions.HostConfig!.NetworkMode = networkName;++ // If network has specific IP assignments, add NetworkingConfig+ if (networkConfig.IPAddress) {+ createOptions.NetworkingConfig = {+ EndpointsConfig: {+ [networkName]: {+ IPAMConfig: {+ IPv4Address: networkConfig.IPAddress+ }+ }+ }+ };+ }+ }+ }++ // 2. Stop the existing container (optional but safer)+ try {+ console.log(`Recreating container ${containerId}: Stopping...`);+ await stopContainer(containerId);+ } catch (stopError: any) {+ // Ignore "already stopped" errors+ if (stopError.statusCode !== 304 && stopError.statusCode !== 404) {+ console.warn(`Could not stop container ${containerId} before removal: ${stopError.message}`);+ }+ }++ // 3. Remove the existing container+ console.log(`Recreating container ${containerId}: Removing...`);+ await removeContainer(containerId, true); // Use force to ensure removal even if stop failed++ // 4. Create the new container with the extracted config+ console.log(`Recreating container ${containerId}: Creating new container with image ${createOptions.Image}...`);+ const newContainer = await docker.createContainer(createOptions);++ // 5. Start the new container+ console.log(`Recreating container ${containerId}: Starting new container ${newContainer.id}...`);+ await startContainer(newContainer.id);++ console.log(`Recreating container ${containerId}: Successfully recreated and started as ${newContainer.id}.`);++ // 6. Get basic container info to return as ServiceContainer+ const containers = await listContainers(true); // Get all containers including the new one+ const newServiceContainer = containers.find((c) => c.id === newContainer.id);++ if (!newServiceContainer) {+ throw new Error(`Container ${newContainer.id} was created but not found in container list`);+ }++ return newServiceContainer;+ } catch (error: any) {+ console.error(`Failed to recreate container ${containerId}:`, error);+ throw new DockerApiError(`Failed to recreate container ${originalContainer?.name || containerId}: ${error.message || 'Unknown error'}`, error.statusCode);+ }+}diff --git a/src/lib/services/docker/scheduler-service.ts b/src/lib/services/docker/scheduler-service.tsnew file mode 100644index 000000000..5adf3b22d--- /dev/null+++ b/src/lib/services/docker/scheduler-service.ts@@ -0,0 +1,65 @@+import { getSettings } from '../settings-service';+import { checkAndUpdateContainers, checkAndUpdateStacks } from './auto-update-service';++// Track timers+let autoUpdateTimer: NodeJS.Timeout | null = null;++/**+ * Start the auto-update scheduler+ */+export async function initAutoUpdateScheduler(): Promise<void> {+ const settings = await getSettings();++ // Clear any existing timer+ if (autoUpdateTimer) {+ clearInterval(autoUpdateTimer);+ autoUpdateTimer = null;+ }++ // If auto-update is disabled globally, do nothing+ if (!settings.autoUpdate) {+ console.log('Auto-update is disabled in settings');+ return;+ }++ const intervalMinutes = settings.autoUpdateInterval || 60; // Default to 60 minutes+ const intervalMs = intervalMinutes * 60 * 1000;++ console.log(`Starting auto-update scheduler with interval of ${intervalMinutes} minutes`);++ // Initial run+ await runAutoUpdateChecks();++ // Schedule regular checks+ autoUpdateTimer = setInterval(runAutoUpdateChecks, intervalMs);+}++/**+ * Run the auto-update checks for containers and stacks+ */+async function runAutoUpdateChecks(): Promise<void> {+ console.log('Running scheduled auto-update checks...');++ try {+ // Check containers first+ const containerResults = await checkAndUpdateContainers();+ console.log(`Auto-update check completed for containers: Checked ${containerResults.checked}, Updated ${containerResults.updated}, Errors ${containerResults.errors.length}`);++ // Then check stacks+ const stackResults = await checkAndUpdateStacks();+ console.log(`Auto-update check completed for stacks: Checked ${stackResults.checked}, Updated ${stackResults.updated}, Errors ${stackResults.errors.length}`);+ } catch (error) {+ console.error('Error during auto-update check:', error);+ }+}++/**+ * Stop the auto-update scheduler+ */+export function stopAutoUpdateScheduler(): void {+ if (autoUpdateTimer) {+ clearInterval(autoUpdateTimer);+ autoUpdateTimer = null;+ console.log('Auto-update scheduler stopped');+ }+}diff --git a/src/lib/services/docker/stack-service.ts b/src/lib/services/docker/stack-service.tsindex aacb66838..8d77aa4dd 100644--- a/src/lib/services/docker/stack-service.ts+++ b/src/lib/services/docker/stack-service.ts@@ -358,7 +358,8 @@ export async function getStack(stackId: string): Promise<Stack> {status,createdAt: meta.createdAt,updatedAt: meta.updatedAt,- composeContent+ composeContent,+ meta};} catch (err) {console.error(`Error getting stack ${stackId}:`, err);@@ -456,7 +457,9 @@ export async function updateStack(stackId: string, updates: StackUpdate): Promisconst updatedMeta: StackMeta = {...meta,name: updates.name || meta.name,- updatedAt: new Date().toISOString()+ updatedAt: new Date().toISOString(),+ // Add auto-update flag if provided+ ...(updates.autoUpdate !== undefined ? { autoUpdate: updates.autoUpdate } : {})};const promises = [fs.writeFile(metaPath, JSON.stringify(updatedMeta, null, 2), 'utf8')];@@ -901,3 +904,41 @@ ${yaml.dump({ services }).substring(10)}`; // Remove the services: line// 5. Create a new stack in Arcane's managed stacksreturn await createStack(stackId, composeContent);}++/**+ * Lists all managed and optionally external stacks+ */+export async function listStacks(includeExternal = false): Promise<Stack[]> {+ // Get managed stacks+ const managedStacks = await loadComposeStacks();++ // Add meta information to managed stacks+ const enrichedManagedStacks = await Promise.all(+ managedStacks.map(async (stack) => {+ try {+ // Read the meta file to get autoUpdate property+ const metaPath = await getStackMetaPath(stack.id);+ const metaContent = await fs.readFile(metaPath, 'utf8');+ const meta = JSON.parse(metaContent) as StackMeta;++ // Return stack with meta included+ return {+ ...stack,+ meta+ };+ } catch (err) {+ console.warn(`Failed to read meta for stack ${stack.id}:`, err);+ return stack; // Return stack without meta if there was an error+ }+ })+ );++ // Get external stacks if requested+ let externalStacks: Stack[] = [];+ if (includeExternal) {+ externalStacks = await discoverExternalStacks();+ }++ // Combine managed and external stacks+ return [...enrichedManagedStacks, ...externalStacks];+}diff --git a/src/lib/services/settings-service.ts b/src/lib/services/settings-service.tsindex 45047222d..f057145f6 100644--- a/src/lib/services/settings-service.ts+++ b/src/lib/services/settings-service.ts@@ -16,6 +16,7 @@ const SETTINGS_FOLDER = path.join(BASE_PATH, 'settings');export const DEFAULT_SETTINGS: SettingsData = {dockerHost: isDev ? (process.platform === 'win32' ? 'npipe:////./pipe/docker_engine' : 'unix:///var/run/docker.sock') : 'unix:///var/run/docker.sock',autoUpdate: false,+ autoUpdateInterval: 5,pollingEnabled: true,pollingInterval: 10,pruneMode: 'all',diff --git a/src/lib/types/docker/stack.type.ts b/src/lib/types/docker/stack.type.tsindex 79c160077..69f58c065 100644--- a/src/lib/types/docker/stack.type.ts+++ b/src/lib/types/docker/stack.type.ts@@ -2,6 +2,7 @@ export interface StackMeta {name: string;createdAt: string;updatedAt: string;+ autoUpdate?: boolean;}export interface StackService {@@ -27,9 +28,11 @@ export interface Stack {composeContent?: string;isExternal?: boolean;compose?: any;+ meta?: StackMeta;}export interface StackUpdate {name?: string;composeContent?: string;+ autoUpdate?: boolean;}diff --git a/src/lib/types/settings.ts b/src/lib/types/settings.tsindex 731c99658..2dc8afe3e 100644--- a/src/lib/types/settings.ts+++ b/src/lib/types/settings.ts@@ -1,6 +1,7 @@export interface SettingsData {dockerHost: string;autoUpdate: boolean;+ autoUpdateInterval: number;pollingEnabled: boolean;pollingInterval: number;stacksDirectory: string;diff --git a/src/routes/api/stacks/[stackId]/+server.ts b/src/routes/api/stacks/[stackId]/+server.tsindex 448785a39..87a8db3fd 100644--- a/src/routes/api/stacks/[stackId]/+server.ts+++ b/src/routes/api/stacks/[stackId]/+server.ts@@ -1,46 +1,16 @@import type { RequestHandler } from './$types';import { json } from '@sveltejs/kit';import { updateStack } from '$lib/services/docker/stack-service';-import { NotFoundError, ServiceError } from '$lib/types/errors';-import { startStack } from '$lib/services/docker/stack-service';export const PATCH: RequestHandler = async ({ params, request }) => {- const stackId = params.stackId;+ const { stackId } = params;+ const { name, composeContent, autoUpdate } = await request.json();try {- const body = await request.json();- const { name, composeContent } = body;-- // Basic validation- if (!stackId) {- return json({ error: 'Stack ID is required' }, { status: 400 });- }- if (typeof name !== 'string' || name.trim() === '') {- return json({ error: 'Stack name is required' }, { status: 400 });- }- // Allow empty compose content? Assuming yes for now.- if (typeof composeContent !== 'string') {- return json({ error: 'Invalid composeContent format' }, { status: 400 });- }-- const updatedStack = await updateStack(stackId, { name: name.trim(), composeContent });-- return json({ message: 'Stack updated successfully', stack: updatedStack }, { status: 200 });+ await updateStack(stackId, { name, composeContent, autoUpdate });+ return json({ success: true, message: 'Stack updated successfully' });} catch (error: any) {- console.error(`Error updating stack ${stackId}:`, error);-- if (error instanceof SyntaxError) {- // Handle invalid JSON- return json({ error: 'Invalid request body' }, { status: 400 });- }- if (error instanceof NotFoundError) {- return json({ error: error.message }, { status: 404 });- }- if (error instanceof ServiceError) {- // Handle errors from stack-service- return json({ error: error.message }, { status: 500 });- }-- return json({ error: 'Failed to update stack' }, { status: 500 });+ console.error('Error updating stack:', error);+ return json({ success: false, error: error.message || 'Failed to update stack' }, { status: 500 });}};diff --git a/src/routes/api/system/auto-update/+server.ts b/src/routes/api/system/auto-update/+server.tsnew file mode 100644index 000000000..e18ed8add--- /dev/null+++ b/src/routes/api/system/auto-update/+server.ts@@ -0,0 +1,46 @@+import type { RequestHandler } from './$types';+import { json } from '@sveltejs/kit';+import { getSettings } from '$lib/services/settings-service';+import { checkAndUpdateContainers, checkAndUpdateStacks } from '$lib/services/docker/auto-update-service';++export const GET: RequestHandler = async () => {+ try {+ const settings = await getSettings();++ return json({+ enabled: settings.autoUpdate,+ interval: settings.autoUpdateInterval || 60,+ message: settings.autoUpdate ? `Auto-update is enabled and checks every ${settings.autoUpdateInterval || 60} minutes` : 'Auto-update is disabled'+ });+ } catch (error: any) {+ console.error('Error getting auto-update status:', error);+ return json(+ {+ error: error.message || 'Failed to get auto-update status',+ enabled: false+ },+ { status: 500 }+ );+ }+};++export const POST: RequestHandler = async () => {+ try {+ const [containerResults, stackResults] = await Promise.all([checkAndUpdateContainers(), checkAndUpdateStacks()]);++ return json({+ success: true,+ containers: containerResults,+ stacks: stackResults+ });+ } catch (error: any) {+ console.error('Error running manual update check:', error);+ return json(+ {+ success: false,+ error: error.message || 'Failed to run update check'+ },+ { status: 500 }+ );+ }+};diff --git a/src/routes/containers/[id]/+page.svelte b/src/routes/containers/[id]/+page.svelteindex 44a0cad46..854881d3e 100644--- a/src/routes/containers/[id]/+page.svelte+++ b/src/routes/containers/[id]/+page.svelte@@ -12,6 +12,8 @@import ActionButtons from '$lib/components/action-buttons.svelte';import { formatDate, formatLogLine, formatBytes } from '$lib/utils';import type Docker from 'dockerode';+ import StatusBadge from '$lib/components/badges/status-badge.svelte';+ import * as Tabs from '$lib/components/ui/tabs/index.js';let { data, form }: { data: PageData; form: ActionData } = $props();let { container, logs, stats } = $derived(data);@@ -99,6 +101,8 @@isRefreshing = false;}, 500);}++ let activeTab = $state('overview');</script><div class="space-y-6 pb-8">@@ -125,10 +129,9 @@<h1 class="text-2xl font-bold tracking-tight">{container?.name || 'Container Details'}</h1>+{#if container?.state}- <Badge variant={container.state.Running ? 'default' : 'destructive'} class="capitalize">- {container.state.Status}- </Badge>+ <span class="self-start mt-1.5"><StatusBadge variant={container.state.Status === 'running' ? 'green' : container.state.Status === 'exited' ? 'red' : 'amber'} text={container.state.Status} /></span>{/if}</div></div>@@ -176,74 +179,165 @@{/if}{#if container}- <!-- Container Details Section -->- <div class="space-y-6">- <Card.Root class="border shadow-sm">- <Card.Header>- <Card.Title>Container Details</Card.Title>- <Card.Description>Basic information about the container</Card.Description>- </Card.Header>- <Card.Content>- <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">- <!-- Image -->- <div class="flex items-start gap-3">- <div class="bg-blue-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">- <HardDrive class="h-5 w-5 text-blue-500" />+ <!-- NEW: Tabbed Interface -->+ <Tabs.Root value={activeTab} onValueChange={(val) => (activeTab = val)} class="space-y-4">+ <Tabs.List>+ <Tabs.Trigger value="overview">Overview</Tabs.Trigger>+ <Tabs.Trigger value="config">Configuration</Tabs.Trigger>+ <Tabs.Trigger value="network">Networks</Tabs.Trigger>+ <Tabs.Trigger value="storage">Storage</Tabs.Trigger>+ <Tabs.Trigger value="logs">Logs</Tabs.Trigger>+ <Tabs.Trigger value="stats">Metrics</Tabs.Trigger>+ </Tabs.List>++ <!-- Overview Tab -->+ <Tabs.Content value="overview" class="space-y-6">+ <!-- Container Details Card -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <Card.Title>Container Details</Card.Title>+ <Card.Description>Basic information about the container</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">+ <!-- Image -->+ <div class="flex items-start gap-3">+ <div class="bg-blue-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">+ <HardDrive class="h-5 w-5 text-blue-500" />+ </div>+ <div class="min-w-0 flex-1">+ <p class="text-sm font-medium text-muted-foreground">Image</p>+ <p class="text-base font-semibold mt-1 break-all">+ <span class="truncate block" title={container.config?.Image || 'N/A'}>+ {container.config?.Image || 'N/A'}+ </span>+ </p>+ </div></div>- <div class="min-w-0 flex-1">- <p class="text-sm font-medium text-muted-foreground">Image</p>- <p class="text-base font-semibold mt-1 break-all">- <span class="truncate block" title={container.config?.Image || 'N/A'}>- {container.config?.Image || 'N/A'}- </span>- </p>++ <!-- Created -->+ <div class="flex items-start gap-3">+ <div class="bg-green-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">+ <Clock class="h-5 w-5 text-green-500" />+ </div>+ <div class="min-w-0 flex-1">+ <p class="text-sm font-medium text-muted-foreground">Created</p>+ <p class="text-base font-semibold mt-1 truncate" title={formatDate(container.created)}>+ {formatDate(container.created)}+ </p>+ </div></div>- </div>- <!-- Created -->- <div class="flex items-start gap-3">- <div class="bg-green-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">- <Clock class="h-5 w-5 text-green-500" />+ <!-- IP Address -->+ <div class="flex items-start gap-3">+ <div class="bg-purple-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">+ <Network class="h-5 w-5 text-purple-500" />+ </div>+ <div class="min-w-0 flex-1">+ <p class="text-sm font-medium text-muted-foreground">IP Address</p>+ <p class="text-base font-semibold mt-1 truncate" title={primaryIpAddress}>+ {primaryIpAddress}+ </p>+ </div></div>- <div class="min-w-0 flex-1">- <p class="text-sm font-medium text-muted-foreground">Created</p>- <p class="text-base font-semibold mt-1 truncate" title={formatDate(container.created)}>- {formatDate(container.created)}- </p>++ <!-- Command -->+ <div class="flex items-start gap-3">+ <div class="bg-amber-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">+ <Terminal class="h-5 w-5 text-amber-500" />+ </div>+ <div class="min-w-0 flex-1">+ <p class="text-sm font-medium text-muted-foreground">Command</p>+ <p class="text-base font-semibold mt-1 truncate" title={container.config?.Cmd?.join(' ') || 'N/A'}>+ {container.config?.Cmd?.join(' ') || 'N/A'}+ </p>+ </div></div></div>+ </Card.Content>+ </Card.Root>- <!-- IP Address -->- <div class="flex items-start gap-3">- <div class="bg-purple-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">- <Network class="h-5 w-5 text-purple-500" />- </div>- <div class="min-w-0 flex-1">- <p class="text-sm font-medium text-muted-foreground">IP Address</p>- <p class="text-base font-semibold mt-1 truncate" title={primaryIpAddress}>- {primaryIpAddress}- </p>+ <!-- Advanced Container Info -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <Card.Title>Container Configuration</Card.Title>+ <Card.Description>Additional container settings</Card.Description>+ </Card.Header>+ <Card.Content>+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm">+ <!-- Container ID -->+ <div>+ <span class="font-semibold">Container ID:</span>+ <div class="font-mono mt-1 text-xs break-all">{container.id}</div></div>++ <!-- Working Directory -->+ {#if container.config?.WorkingDir}+ <div>+ <span class="font-semibold">Working Directory:</span>+ <div class="mt-1 break-all">{container.config.WorkingDir}</div>+ </div>+ {/if}++ <!-- User -->+ {#if container.config?.User}+ <div>+ <span class="font-semibold">User:</span>+ <div class="mt-1">{container.config.User}</div>+ </div>+ {/if}++ <!-- Health Check section -->+ {#if container.state?.Health}+ <div class="col-span-full">+ <span class="font-semibold">Health Status:</span>+ <div class="mt-1 flex gap-2 items-center">+ <StatusBadge variant={container.state.Health.Status === 'healthy' ? 'green' : container.state.Health.Status === 'unhealthy' ? 'red' : 'amber'} text={container.state.Health.Status} />+ {#if container.state.Health.Log && container.state.Health.Log.length > 0}+ <span class="text-xs text-muted-foreground">+ Last check: {new Date(container.state.Health.Log[0].Start).toLocaleString()}+ </span>+ {/if}+ </div>+ </div>+ {/if}</div>+ </Card.Content>+ </Card.Root>+ </Tabs.Content>- <!-- Command -->- <div class="flex items-start gap-3">- <div class="bg-amber-500/10 p-2 rounded-full h-10 w-10 flex items-center justify-center flex-shrink-0">- <Terminal class="h-5 w-5 text-amber-500" />- </div>- <div class="min-w-0 flex-1">- <p class="text-sm font-medium text-muted-foreground">Command</p>- <p class="text-base font-semibold mt-1 truncate" title={container.config?.Cmd?.join(' ') || 'N/A'}>- {container.config?.Cmd?.join(' ') || 'N/A'}- </p>+ <!-- Configuration Tab -->+ <Tabs.Content value="config" class="space-y-6">+ <!-- Environment Variables -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <Card.Title>Environment Variables</Card.Title>+ <Card.Description>Container environment configuration</Card.Description>+ </Card.Header>+ <Card.Content class="max-h-[360px] overflow-y-auto">+ {#if container.config?.Env && container.config.Env.length > 0}+ <div class="space-y-2">+ {#each container.config.Env as env}+ <div class="text-xs flex overflow-hidden">+ {#if env.includes('=')}+ {@const [key, ...valueParts] = env.split('=')}+ {@const value = valueParts.join('=')}+ <div class="flex w-full">+ <span class="font-semibold mr-2 min-w-[120px] max-w-[180px] truncate flex-shrink-0" title={key}>{key}:</span>+ <span class="truncate flex-1" title={value}>{value}</span>+ </div>+ {:else}+ <span>{env}</span>+ {/if}+ </div>+ {/each}</div>- </div>- </div>- </Card.Content>- </Card.Root>+ {:else}+ <div class="text-sm text-muted-foreground italic">No environment variables set</div>+ {/if}+ </Card.Content>+ </Card.Root>- <!-- Advanced Details (Ports, Volumes, Env) -->- <div class="grid grid-cols-1 gap-6"><!-- Ports --><Card.Root class="border shadow-sm"><Card.Header>@@ -279,134 +373,366 @@</Card.Content></Card.Root>- <!-- Environment Variables -->+ <!-- Labels --><Card.Root class="border shadow-sm"><Card.Header>- <Card.Title>Environment Variables</Card.Title>- <Card.Description>Container environment configuration</Card.Description>+ <Card.Title>Labels</Card.Title>+ <Card.Description>Container metadata labels</Card.Description></Card.Header>- <Card.Content class="max-h-[180px] overflow-y-auto">- {#if container.config?.Env && container.config.Env.length > 0}+ <Card.Content class="max-h-[360px] overflow-y-auto">+ {#if container.labels && Object.keys(container.labels).length > 0}<div class="space-y-2">- {#each container.config.Env as env}+ {#each Object.entries(container.labels) as [key, value]}<div class="text-xs flex overflow-hidden">- {#if env.includes('=')}- {@const [key, ...valueParts] = env.split('=')}- {@const value = valueParts.join('=')}- <div class="flex w-full">- <span class="font-semibold mr-2 min-w-[120px] max-w-[180px] truncate flex-shrink-0" title={key}>{key}:</span>- <span class="truncate flex-1" title={value}>{value}</span>- </div>- {:else}- <span>{env}</span>- {/if}+ <div class="flex w-full">+ <span class="font-semibold mr-2 min-w-[120px] max-w-[180px] truncate flex-shrink-0" title={key}>{key}:</span>+ <span class="truncate flex-1" title={value?.toString()}>{value?.toString() || ''}</span>+ </div></div>{/each}</div>{:else}- <div class="text-sm text-muted-foreground italic">No environment variables set</div>+ <div class="text-sm text-muted-foreground italic">No labels defined</div>{/if}</Card.Content></Card.Root>- </div>- </div>+ </Tabs.Content>- <Separator class="my-6" />-- <!-- Logs and Stats Section -->- <div class="grid grid-cols-1 lg:grid-cols-12 gap-6">- <!-- Logs Card -->- <Card.Root class="lg:col-span-8 border shadow-sm">- <Card.Header>- <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center w-full gap-4">- <div>- <Card.Title class="text-lg font-semibold">Container Logs</Card.Title>- <Card.Description>Recent output from the container</Card.Description>- </div>- <Button variant="outline" size="sm" onclick={refreshData} disabled={isRefreshing}>- <RefreshCw class={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />- Refresh Logs- </Button>- </div>- </Card.Header>-- <Card.Content>- <div class="bg-muted/50 text-foreground p-4 rounded-md font-mono text-xs h-80 overflow-auto whitespace-pre-wrap border" bind:this={logsContainer} id="logs-container" style="word-break: break-all;">- {#if logs}- {@html formattedLogs}- {:else}- <div class="flex flex-col items-center justify-center h-full text-center">- <Terminal class="h-8 w-8 text-muted-foreground mb-3 opacity-40" />- <p class="text-muted-foreground italic">No logs available. The container may not have started yet.</p>+ <!-- Networks Tab -->+ <Tabs.Content value="network" class="space-y-6">+ <!-- Networks -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <Card.Title>Connected Networks</Card.Title>+ <Card.Description>Network settings and connections</Card.Description>+ </Card.Header>+ <Card.Content>+ {#if container.networkSettings?.Networks && Object.keys(container.networkSettings.Networks).length > 0}+ <div class="space-y-4">+ {#each Object.entries(container.networkSettings.Networks) as [networkName, networkConfig]}+ <div class="rounded-md bg-muted/40 p-3">+ <div class="text-sm font-medium">{networkName}</div>+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-x-4 gap-y-2 mt-2">+ <div class="text-xs">+ <span class="font-semibold">IP Address:</span>+ {networkConfig.IPAddress || 'N/A'}+ </div>+ <div class="text-xs">+ <span class="font-semibold">Gateway:</span>+ {networkConfig.Gateway || 'N/A'}+ </div>+ <div class="text-xs">+ <span class="font-semibold">MAC Address:</span>+ {networkConfig.MacAddress || 'N/A'}+ </div>+ <div class="text-xs">+ <span class="font-semibold">Subnet:</span>+ {networkConfig.IPPrefixLen ? `${networkConfig.IPAddress}/${networkConfig.IPPrefixLen}` : 'N/A'}+ </div>+ {#if networkConfig.Aliases && networkConfig.Aliases.length > 0}+ <div class="text-xs col-span-full">+ <span class="font-semibold">Aliases:</span>+ {networkConfig.Aliases.join(', ')}+ </div>+ {/if}+ {#if networkConfig.Links && networkConfig.Links.length > 0}+ <div class="text-xs col-span-full">+ <span class="font-semibold">Links:</span>+ {networkConfig.Links.join(', ')}+ </div>+ {/if}+ </div>+ </div>+ {/each}</div>+ {:else}+ <div class="text-sm text-muted-foreground italic">No networks connected</div>{/if}- </div>- </Card.Content>-- <Card.Footer class="flex justify-end border-t pt-4">- <Button variant="outline" size="sm" href="/containers/{container.id}/logs" class="text-sm">View full logs</Button>- </Card.Footer>- </Card.Root>-- <!-- Stats Card -->- <Card.Root class="lg:col-span-4 border shadow-sm">- <Card.Header>- <div class="flex justify-between items-center">- <div>- <Card.Title class="text-lg font-semibold">Resource Usage</Card.Title>- <Card.Description>Live container metrics</Card.Description>- </div>- <Button variant="ghost" size="icon" onclick={refreshData} disabled={isRefreshing} title="Refresh Stats & Logs">- <RefreshCw class={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />- </Button>- </div>- </Card.Header>-- <Card.Content>- {#if stats && container.state?.Running}- <div class="space-y-4">- <!-- CPU Usage -->- <div>- <div class="flex justify-between items-center mb-1">- <span class="text-sm font-medium flex items-center gap-2"><Cpu class="h-4 w-4 text-muted-foreground" /> CPU Usage</span>- <span class="text-sm font-semibold">{cpuUsagePercent.toFixed(2)}%</span>+ </Card.Content>+ </Card.Root>+ </Tabs.Content>++ <!-- Storage Tab -->+ <Tabs.Content value="storage" class="space-y-6">+ <!-- Volumes/Mounts -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <Card.Title>Volumes & Mounts</Card.Title>+ <Card.Description>Container filesystem mounts</Card.Description>+ </Card.Header>+ <Card.Content>+ {#if container.mounts && container.mounts.length > 0}+ <div class="space-y-4">+ <!-- Mount Type Summary -->+ <div class="flex flex-wrap gap-2 pb-2">+ {#if container.mounts.filter((m) => m.Type === 'bind').length > 0}+ <Badge variant="outline" class="bg-blue-500/10 text-blue-600 border-blue-200">+ {container.mounts.filter((m) => m.Type === 'bind').length} bind+ {container.mounts.filter((m) => m.Type === 'bind').length === 1 ? 'mount' : 'mounts'}+ </Badge>+ {/if}+ {#if container.mounts.filter((m) => m.Type === 'volume').length > 0}+ <Badge variant="outline" class="bg-purple-500/10 text-purple-600 border-purple-200">+ {container.mounts.filter((m) => m.Type === 'volume').length}+ {container.mounts.filter((m) => m.Type === 'volume').length === 1 ? 'volume' : 'volumes'}+ </Badge>+ {/if}+ {#if container.mounts.filter((m) => m.Type === 'tmpfs').length > 0}+ <Badge variant="outline" class="bg-amber-500/10 text-amber-600 border-amber-200">+ {container.mounts.filter((m) => m.Type === 'tmpfs').length} tmpfs+ {container.mounts.filter((m) => m.Type === 'tmpfs').length === 1 ? 'mount' : 'mounts'}+ </Badge>+ {/if}</div>- <div class="w-full bg-secondary rounded-full h-2 overflow-hidden">- <div class="bg-primary h-2 rounded-full transition-all duration-300" style="width: {Math.min(cpuUsagePercent, 100)}%"></div>++ <!-- Mount List -->+ {#each container.mounts as mount}+ <div class="rounded-md overflow-hidden border border-muted">+ <!-- Mount Header -->+ <div+ class={`p-3 flex items-center justify-between gap-2+ ${mount.Type === 'volume' ? 'bg-purple-500/5 border-b border-purple-200/30' : mount.Type === 'bind' ? 'bg-blue-500/5 border-b border-blue-200/30' : 'bg-amber-500/5 border-b border-amber-200/30'}`}+ >+ <!-- Mount Type Icon & Info -->+ <div class="flex items-center gap-2">+ <div+ class={`p-1.5 rounded-md+ ${mount.Type === 'volume' ? 'bg-purple-500/10' : mount.Type === 'bind' ? 'bg-blue-500/10' : 'bg-amber-500/10'}`}+ >+ <!-- Display appropriate icon based on mount type -->+ {#if mount.Type === 'volume'}+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-purple-600">+ <path d="M21 9v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h10"></path>+ <path d="m16 2 5 5-9 9H7v-5l9-9Z"></path>+ </svg>+ {:else if mount.Type === 'bind'}+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-blue-600">+ <path d="M20 6v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6"></path>+ <path d="M3 6h18"></path>+ <path d="M15 3h-6a2 2 0 0 0-2 2v1h10V5a2 2 0 0 0-2-2Z"></path>+ </svg>+ {:else}+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-amber-600">+ <path d="m14 12-8.5 8.5a2.12 2.12 0 1 1-3-3L11 9"></path>+ <path d="M15 3h6v6"></path>+ <path d="M14 4 21 11"></path>+ </svg>+ {/if}+ </div>++ <div>+ <div class="text-sm font-medium">+ {mount.Type === 'tmpfs' ? 'Temporary filesystem' : mount.Type === 'volume' ? mount.Name || 'Docker volume' : 'Host directory'}+ </div>+ <div class="text-xs text-muted-foreground">+ {mount.Type} mount {mount.RW ? '(read-write)' : '(read-only)'}+ </div>+ </div>+ </div>++ <!-- Access Badge -->+ <Badge variant={mount.RW ? 'outline' : 'secondary'}>+ {mount.RW ? 'Read/Write' : 'Read Only'}+ </Badge>+ </div>++ <!-- Mount Details -->+ <div class="bg-card p-3">+ <div class="grid gap-3 text-sm">+ <!-- Destination Path -->+ <div class="flex items-start gap-2">+ <div class="min-w-[80px] text-xs font-semibold pt-0.5 text-muted-foreground">CONTAINER</div>+ <div class="font-mono text-xs bg-muted/50 py-1 px-2 rounded break-all flex-1">+ {mount.Destination}+ </div>+ </div>++ <!-- Source Path -->+ <div class="flex items-start gap-2">+ <div class="min-w-[80px] text-xs font-semibold pt-0.5 text-muted-foreground">+ {mount.Type === 'volume' ? 'VOLUME' : mount.Type === 'bind' ? 'HOST' : 'SOURCE'}+ </div>+ <div class="font-mono text-xs bg-muted/50 py-1 px-2 rounded break-all flex-1">+ {mount.Source}+ </div>+ </div>++ <!-- Additional Info -->+ {#if mount.Driver || mount.Mode || (mount.Propagation && mount.Propagation !== 'rprivate')}+ <div class="pt-1 grid grid-cols-2 gap-x-4 gap-y-1 text-xs text-muted-foreground">+ {#if mount.Driver}+ <div>+ <span class="font-semibold">Driver:</span>+ {mount.Driver}+ </div>+ {/if}+ {#if mount.Mode}+ <div>+ <span class="font-semibold">Mode:</span>+ {mount.Mode}+ </div>+ {/if}+ {#if mount.Propagation && mount.Propagation !== 'rprivate'}+ <div>+ <span class="font-semibold">Propagation:</span>+ {mount.Propagation}+ </div>+ {/if}+ </div>+ {/if}+ </div>+ </div>+ </div>+ {/each}+ </div>+ {:else}+ <div class="text-center py-8 border rounded-md border-dashed">+ <div class="mb-3 w-12 h-12 rounded-full bg-muted/50 flex items-center justify-center mx-auto">+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="text-muted-foreground">+ <path d="M21 5c0-1.1-.9-2-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V5Z"></path>+ <path d="M2 10h20"></path>+ </svg></div>+ <div class="text-sm text-muted-foreground">No volumes or mounts configured</div>+ <div class="text-xs text-muted-foreground/70 mt-1">This container runs without persistent storage</div></div>+ {/if}+ </Card.Content>+ </Card.Root>+ </Tabs.Content>- <!-- Memory Usage -->+ <!-- Logs Tab -->+ <Tabs.Content value="logs" class="space-y-6">+ <!-- Logs Card -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center w-full gap-4"><div>- <div class="flex justify-between items-center mb-1">- <span class="text-sm font-medium flex items-center gap-2"><MemoryStick class="h-4 w-4 text-muted-foreground" /> Memory Usage</span>- <span class="text-sm font-semibold">{memoryUsageFormatted} / {memoryLimitFormatted}</span>- </div>- <div class="w-full bg-secondary rounded-full h-2 overflow-hidden">- <div class="bg-primary h-2 rounded-full transition-all duration-300" style="width: {memoryUsagePercent.toFixed(2)}%"></div>+ <Card.Title class="text-lg font-semibold">Container Logs</Card.Title>+ <Card.Description>Recent output from the container</Card.Description>+ </div>+ <Button variant="outline" size="sm" onclick={refreshData} disabled={isRefreshing}>+ <RefreshCw class={`h-4 w-4 mr-2 ${isRefreshing ? 'animate-spin' : ''}`} />+ Refresh Logs+ </Button>+ </div>+ </Card.Header>++ <Card.Content>+ <div class="bg-muted/50 text-foreground p-4 rounded-md font-mono text-xs h-[500px] overflow-auto whitespace-pre-wrap border" bind:this={logsContainer} id="logs-container" style="word-break: break-all;">+ {#if logs}+ {@html formattedLogs}+ {:else}+ <div class="flex flex-col items-center justify-center h-full text-center">+ <Terminal class="h-8 w-8 text-muted-foreground mb-3 opacity-40" />+ <p class="text-muted-foreground italic">No logs available. The container may not have started yet.</p></div>+ {/if}+ </div>+ </Card.Content>++ <Card.Footer class="flex justify-end border-t pt-4">+ <Button variant="outline" size="sm" href="/containers/{container.id}/logs" class="text-sm">View full logs</Button>+ </Card.Footer>+ </Card.Root>+ </Tabs.Content>++ <!-- Metrics Tab -->+ <Tabs.Content value="stats" class="space-y-6">+ <!-- Stats Card -->+ <Card.Root class="border shadow-sm">+ <Card.Header>+ <div class="flex justify-between items-center">+ <div>+ <Card.Title class="text-lg font-semibold">Resource Usage</Card.Title>+ <Card.Description>Live container metrics</Card.Description></div>+ <Button variant="ghost" size="icon" onclick={refreshData} disabled={isRefreshing} title="Refresh Stats">+ <RefreshCw class={`h-4 w-4 ${isRefreshing ? 'animate-spin' : ''}`} />+ </Button>+ </div>+ </Card.Header>++ <Card.Content>+ {#if stats && container.state?.Running}+ <div class="space-y-6">+ <!-- CPU Usage -->+ <div>+ <div class="flex justify-between items-center mb-2">+ <span class="text-sm font-medium flex items-center gap-2"><Cpu class="h-4 w-4 text-muted-foreground" /> CPU Usage</span>+ <span class="text-sm font-semibold">{cpuUsagePercent.toFixed(2)}%</span>+ </div>+ <div class="w-full bg-secondary rounded-full h-3 overflow-hidden">+ <div class="bg-primary h-3 rounded-full transition-all duration-300" style="width: {Math.min(cpuUsagePercent, 100)}%"></div>+ </div>+ </div>- <!-- Network I/O -->- <div class="text-xs text-muted-foreground space-y-1 pt-2 border-t">- <div class="flex justify-between">- <span>Network RX:</span>- <span>{formatBytes(stats.networks?.eth0?.rx_bytes || 0)}</span>+ <!-- Memory Usage -->+ <div>+ <div class="flex justify-between items-center mb-2">+ <span class="text-sm font-medium flex items-center gap-2"><MemoryStick class="h-4 w-4 text-muted-foreground" /> Memory Usage</span>+ <span class="text-sm font-semibold">{memoryUsageFormatted} / {memoryLimitFormatted}</span>+ </div>+ <div class="w-full bg-secondary rounded-full h-3 overflow-hidden">+ <div class="bg-primary h-3 rounded-full transition-all duration-300" style="width: {memoryUsagePercent.toFixed(2)}%"></div>+ </div></div>- <div class="flex justify-between">- <span>Network TX:</span>- <span>{formatBytes(stats.networks?.eth0?.tx_bytes || 0)}</span>++ <!-- Network I/O -->+ <div>+ <h4 class="text-sm font-medium mb-2 flex items-center gap-2">+ <Network class="h-4 w-4 text-muted-foreground" /> Network I/O+ </h4>+ <div class="grid grid-cols-2 gap-4 bg-muted/30 p-3 rounded-md">+ <div>+ <div class="text-xs text-muted-foreground">Received</div>+ <div class="text-sm font-medium mt-1">{formatBytes(stats.networks?.eth0?.rx_bytes || 0)}</div>+ </div>+ <div>+ <div class="text-xs text-muted-foreground">Transmitted</div>+ <div class="text-sm font-medium mt-1">{formatBytes(stats.networks?.eth0?.tx_bytes || 0)}</div>+ </div>+ </div></div>++ <!-- Block I/O -->+ {#if stats.blkio_stats && stats.blkio_stats.io_service_bytes_recursive && stats.blkio_stats.io_service_bytes_recursive.length > 0}+ <div>+ <h4 class="text-sm font-medium mb-2">Block I/O</h4>+ <div class="grid grid-cols-2 gap-4 bg-muted/30 p-3 rounded-md">+ <div>+ <div class="text-xs text-muted-foreground">Read</div>+ <div class="text-sm font-medium mt-1">+ {formatBytes(stats.blkio_stats.io_service_bytes_recursive.filter((item) => item.op === 'Read').reduce((acc, item) => acc + item.value, 0))}+ </div>+ </div>+ <div>+ <div class="text-xs text-muted-foreground">Write</div>+ <div class="text-sm font-medium mt-1">+ {formatBytes(stats.blkio_stats.io_service_bytes_recursive.filter((item) => item.op === 'Write').reduce((acc, item) => acc + item.value, 0))}+ </div>+ </div>+ </div>+ </div>+ {/if}++ <!-- Process Count -->+ {#if stats.pids_stats && stats.pids_stats.current !== undefined}+ <div class="text-sm">+ <span class="font-medium">Process count:</span>+ <span class="ml-2">{stats.pids_stats.current}</span>+ </div>+ {/if}</div>- </div>- {:else if !container.state?.Running}- <div class="text-center text-sm text-muted-foreground italic py-8">Container is not running. Stats unavailable.</div>- {:else}- <div class="text-center text-sm text-muted-foreground italic py-8">Could not load stats.</div>- {/if}- </Card.Content>- </Card.Root>- </div>+ {:else if !container.state?.Running}+ <div class="text-center text-sm text-muted-foreground italic py-12">Container is not running. Stats unavailable.</div>+ {:else}+ <div class="text-center text-sm text-muted-foreground italic py-12">Could not load stats.</div>+ {/if}+ </Card.Content>+ </Card.Root>+ </Tabs.Content>+ </Tabs.Root>{:else}<div class="flex flex-col items-center justify-center py-12 border rounded-lg shadow-sm bg-card"><div class="rounded-full bg-muted/50 p-4 mb-4">diff --git a/src/routes/containers/create-container-dialog.svelte b/src/routes/containers/create-container-dialog.svelteindex deb09f248..d455bca54 100644--- a/src/routes/containers/create-container-dialog.svelte+++ b/src/routes/containers/create-container-dialog.svelte@@ -13,7 +13,7 @@import { parseBytes } from '$lib/utils/bytes';import { createEventDispatcher } from 'svelte';- import { optional } from 'zod';+ import Switch from '$lib/components/ui/switch/switch.svelte';const dispatch = createEventDispatcher();// Functions for events@@ -87,6 +87,9 @@let memoryLimitStr = $state(''); // Input as string (e.g., "512m", "1g")let cpuLimitStr = $state(''); // Input as string (e.g., "0.5", "1")+ // Add state for Auto-update+ let autoUpdate = $state(false);+// Port validation - improvedfunction validatePortNumber(port: string | number): {isValid: boolean;@@ -219,6 +222,11 @@{} as { [key: string]: string });+ // Add auto-update label if enabled+ if (autoUpdate) {+ filteredLabels['arcane.auto-update'] = 'true';+ }+// Prepare healthcheck config if enabled and test command is providedlet healthcheckConfig: HealthConfig | undefined = undefined;if (enableHealthcheck && healthcheckTest.length > 0 && healthcheckTest[0].trim() !== '') {@@ -606,6 +614,13 @@</div></div></div>++ <!-- Auto-update -->+ <div class="flex items-center space-x-2 py-4 border-t">+ <Switch id="auto-update" name="autoUpdate" bind:checked={autoUpdate} />+ <Label for="auto-update" class="font-medium">Enable auto-update</Label>+ <p class="text-xs text-muted-foreground">When enabled, Arcane will periodically check for newer versions of this container's image and automatically update it.</p>+ </div></div></Tabs.Content></form>diff --git a/src/routes/settings/+page.server.ts b/src/routes/settings/+page.server.tsindex e10aa81a9..800951967 100644--- a/src/routes/settings/+page.server.ts+++ b/src/routes/settings/+page.server.ts@@ -26,6 +26,11 @@ export const actions: Actions = {// Explicitly check for the "on" value for both toggle switchesconst autoUpdate = formData.get('autoUpdate') === 'on';+ const autoUpdateInterval = Number.parseInt(formData.get('autoUpdateInterval') as string, 10) || 60;++ // Validate interval range+ const validatedAutoUpdateInterval = Math.min(Math.max(autoUpdateInterval, 5), 1440);+const pollingEnabled = formData.get('pollingEnabled') === 'on';const pollingIntervalStr = formData.get('pollingInterval') as string;@@ -89,6 +94,7 @@ export const actions: Actions = {autoUpdate,pollingEnabled,pollingInterval,+ autoUpdateInterval: validatedAutoUpdateInterval,stacksDirectory,pruneMode: pruneMode,externalServicesdiff --git a/src/routes/settings/tabs/app-settings.svelte b/src/routes/settings/tabs/app-settings.svelteindex 675a7100d..69def3066 100644--- a/src/routes/settings/tabs/app-settings.svelte+++ b/src/routes/settings/tabs/app-settings.svelte@@ -17,6 +17,7 @@let pollingEnabled = $derived(form?.values?.pollingEnabled !== undefined ? form.values.pollingEnabled === 'on' : settings?.pollingEnabled || false);let pollingInterval = $derived(form?.values?.pollingInterval !== undefined ? Number(form.values.pollingInterval) : settings?.pollingInterval || 10);+ let autoUpdateInterval = $derived(form?.values?.autoUpdateInterval !== undefined ? Number(form.values.autoUpdateInterval) : settings?.autoUpdateInterval || 10);let stacksDirectory = $derived(form?.values?.stacksDirectory || settings?.stacksDirectory || '');let autoUpdate = $derived(form?.values?.autoUpdate !== undefined ? form.values.autoUpdate === 'on' : settings?.autoUpdate || false);@@ -109,6 +110,14 @@</div><Switch id="autoUpdateSwitch" name="autoUpdate" bind:checked={autoUpdate} /></div>++ {#if autoUpdate}+ <div class="space-y-2 mt-4">+ <Label for="autoUpdateInterval" class="text-base font-medium">Auto-update check interval (minutes)</Label>+ <Input id="autoUpdateInterval" name="autoUpdateInterval" type="number" min="5" max="1440" bind:value={autoUpdateInterval} />+ <p class="text-sm text-muted-foreground">How often Arcane will check for container and stack updates (minimum 5 minutes, maximum 24 hours)</p>+ </div>+ {/if}{/if}</Card.Content></Card.Root>diff --git a/src/routes/stacks/[stackId]/+page.server.ts b/src/routes/stacks/[stackId]/+page.server.tsindex a4acb601d..cd6975055 100644--- a/src/routes/stacks/[stackId]/+page.server.ts+++ b/src/routes/stacks/[stackId]/+page.server.ts@@ -17,7 +17,8 @@ export async function load({ params }) {name: stack.name || '',composeContent: stack.composeContent || '',originalName: stack.name || '',- originalComposeContent: stack.composeContent || ''+ originalComposeContent: stack.composeContent || '',+ autoUpdate: stack.meta?.autoUpdate || false}};} catch (err) {@@ -30,7 +31,8 @@ export async function load({ params }) {name: '',composeContent: '',originalName: '',- originalComposeContent: ''+ originalComposeContent: '',+ autoUpdate: false}};}@@ -44,23 +46,16 @@ export const actions = {const name = formData.get('name')?.toString() || '';const composeContent = formData.get('composeContent')?.toString() || '';+ const autoUpdate = formData.get('autoUpdate') === 'on';try {- await updateStack(stackId, { name, composeContent });+ await updateStack(stackId, { name, composeContent, autoUpdate });return {success: true,message: 'Stack updated successfully'};} catch (err) {console.error('Error updating stack:', err);- // Consider using fail() for form action errors- // import { fail } from '@sveltejs/kit';- // return fail(422, { // Example: Unprocessable Entity- // name, // Return submitted values for repopulation- // composeContent,- // error: err instanceof Error ? err.message : 'Failed to update stack'- // });- // Or keep the simple return for now:return {success: false,error: err instanceof Error ? err.message : 'Failed to update stack'diff --git a/src/routes/stacks/[stackId]/+page.svelte b/src/routes/stacks/[stackId]/+page.svelteindex 644386b56..5272c3a87 100644--- a/src/routes/stacks/[stackId]/+page.svelte+++ b/src/routes/stacks/[stackId]/+page.svelte@@ -15,6 +15,7 @@import { toast } from 'svelte-sonner';import { enhance } from '$app/forms';import YamlEditor from '$lib/components/yaml-editor.svelte';+ import { Switch } from '$lib/components/ui/switch/index.js';let { data }: { data: PageData; form: ActionData } = $props();let { stack, editorState } = $derived(data);@@ -29,8 +30,9 @@let composeContent = $derived(editorState.composeContent);let originalName = $derived(editorState.originalName);let originalComposeContent = $derived(editorState.originalComposeContent);+ let originalAutoUpdate = $derived(editorState.autoUpdate);- let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent);+ let hasChanges = $derived(name !== originalName || composeContent !== originalComposeContent || editorState.autoUpdate !== originalAutoUpdate);$effect(() => {depoloying = false;@@ -52,7 +54,11 @@headers: {'Content-Type': 'application/json'},- body: JSON.stringify({ name, composeContent })+ body: JSON.stringify({+ name,+ composeContent,+ autoUpdate: editorState.autoUpdate+ })});const result = await response.json();@@ -66,6 +72,7 @@originalName = name;originalComposeContent = composeContent;+ originalAutoUpdate = editorState.autoUpdate;await invalidateAll();} catch (error: any) {@@ -205,6 +212,14 @@Edit your <span class="font-bold">compose.yaml</span> file directly. Syntax errors will be highlighted.</p></div>++ <div class="flex items-center space-x-2 mt-4">+ <Switch id="auto-update" name="autoUpdate" bind:checked={editorState.autoUpdate} />+ <Label for="auto-update" class="font-medium">Enable auto-update</Label>+ <div class="inline-block">+ <p class="text-xs text-muted-foreground">When enabled, Arcane will periodically check for newer versions of all images in this stack and automatically redeploy it.</p>+ </div>+ </div></div></Card.Content><Card.Footer class="flex justify-between">