mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-13 20:27:22 +00:00
feat: Implement a comprehensive Docker Compose stack management UI with file editing, deployment, container monitoring, and interactive bash access.
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import Docker from 'dockerode';
|
||||
import WebSocket from 'ws';
|
||||
import { Duplex } from 'stream';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import path from 'path';
|
||||
@@ -13,8 +12,6 @@ const COMPOSE_DIR = process.env.COMPOSE_DIR || '/app/compose';
|
||||
class DockerController {
|
||||
private static instance: DockerController;
|
||||
private docker: Docker;
|
||||
private execStream: Duplex | null = null;
|
||||
private currentExec: Docker.Exec | null = null;
|
||||
|
||||
private constructor() {
|
||||
this.docker = new Docker({ socketPath: '/var/run/docker.sock' });
|
||||
@@ -178,14 +175,32 @@ class DockerController {
|
||||
}
|
||||
}
|
||||
|
||||
// State-safe: silently ignores 304 "already started" errors
|
||||
public async startContainer(containerId: string) {
|
||||
const container = this.docker.getContainer(containerId);
|
||||
await container.start();
|
||||
try {
|
||||
const container = this.docker.getContainer(containerId);
|
||||
await container.start();
|
||||
} catch (error: any) {
|
||||
if (error?.statusCode === 304) {
|
||||
// Container already running — not an error
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// State-safe: silently ignores 304 "already stopped" errors
|
||||
public async stopContainer(containerId: string) {
|
||||
const container = this.docker.getContainer(containerId);
|
||||
await container.stop();
|
||||
try {
|
||||
const container = this.docker.getContainer(containerId);
|
||||
await container.stop();
|
||||
} catch (error: any) {
|
||||
if (error?.statusCode === 304) {
|
||||
// Container already stopped — not an error
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async restartContainer(containerId: string) {
|
||||
@@ -193,6 +208,50 @@ class DockerController {
|
||||
await container.restart();
|
||||
}
|
||||
|
||||
public async getOrphanContainers(knownStackNames: string[]) {
|
||||
// 1. Fetch all containers (running and stopped)
|
||||
const allContainers = await this.docker.listContainers({ all: true });
|
||||
|
||||
// 2. Filter and categorize orphans
|
||||
const orphans: Record<string, any[]> = {};
|
||||
|
||||
allContainers.forEach((container) => {
|
||||
// Look for the docker compose project label
|
||||
const projectName = container.Labels?.['com.docker.compose.project'];
|
||||
|
||||
// If it has a project label, but the project is NOT in our known list...
|
||||
if (projectName && !knownStackNames.includes(projectName)) {
|
||||
if (!orphans[projectName]) {
|
||||
orphans[projectName] = [];
|
||||
}
|
||||
orphans[projectName].push({
|
||||
Id: container.Id,
|
||||
Names: container.Names,
|
||||
State: container.State,
|
||||
Status: container.Status,
|
||||
Image: container.Image
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return orphans;
|
||||
}
|
||||
|
||||
public async removeContainers(containerIds: string[]) {
|
||||
const results = [];
|
||||
for (const id of containerIds) {
|
||||
try {
|
||||
const container = this.docker.getContainer(id);
|
||||
await container.remove({ force: true });
|
||||
results.push({ id, success: true });
|
||||
} catch (error: any) {
|
||||
console.error(`Failed to remove container ${id}:`, error.message);
|
||||
results.push({ id, success: false, error: error.message });
|
||||
}
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
public async streamStats(containerId: string, ws: WebSocket) {
|
||||
const container = this.docker.getContainer(containerId);
|
||||
const stats = await container.stats({ stream: true });
|
||||
@@ -210,6 +269,11 @@ class DockerController {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Exec into a container with full session isolation.
|
||||
* All state (exec instance, stream) lives in this closure — no singleton traps.
|
||||
* The WebSocket message handler is registered here to handle input, resize, and cleanup.
|
||||
*/
|
||||
public async execContainer(containerId: string, ws: WebSocket) {
|
||||
try {
|
||||
const container = this.docker.getContainer(containerId);
|
||||
@@ -234,13 +298,9 @@ class DockerController {
|
||||
});
|
||||
}
|
||||
|
||||
this.currentExec = exec;
|
||||
|
||||
const stream = await exec.start({ hijack: true, stdin: true });
|
||||
|
||||
this.execStream = stream;
|
||||
|
||||
// Handle output from container - send raw text directly
|
||||
// --- Downstream: container output → client ---
|
||||
stream.on('data', (chunk: Buffer) => {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(chunk.toString());
|
||||
@@ -252,27 +312,54 @@ class DockerController {
|
||||
});
|
||||
|
||||
stream.on('end', () => {
|
||||
this.execStream = null;
|
||||
this.currentExec = null;
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.close();
|
||||
}
|
||||
});
|
||||
|
||||
// --- Upstream: client messages → container ---
|
||||
ws.on('message', (raw: WebSocket.Data) => {
|
||||
try {
|
||||
const msg = JSON.parse(raw.toString());
|
||||
|
||||
switch (msg.type) {
|
||||
case 'input':
|
||||
if (msg.data) {
|
||||
stream.write(msg.data);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'resize':
|
||||
if (msg.rows && msg.cols) {
|
||||
exec.resize({ h: msg.rows, w: msg.cols }).catch(() => {
|
||||
// Ignore resize errors (exec may have ended)
|
||||
});
|
||||
}
|
||||
break;
|
||||
|
||||
case 'ping':
|
||||
// Keep-alive, no-op
|
||||
break;
|
||||
}
|
||||
} catch {
|
||||
// Non-JSON or malformed message — ignore
|
||||
}
|
||||
});
|
||||
|
||||
// --- Cleanup: prevent zombie processes ---
|
||||
ws.on('close', () => {
|
||||
try {
|
||||
stream.destroy();
|
||||
} catch {
|
||||
// Ignore destroy errors
|
||||
}
|
||||
});
|
||||
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
console.error('Failed to exec container:', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
public sendExecInput(data: string) {
|
||||
if (this.execStream) {
|
||||
this.execStream.write(data);
|
||||
}
|
||||
}
|
||||
|
||||
public async resizeExec(cols: number, rows: number) {
|
||||
if (this.currentExec) {
|
||||
try {
|
||||
await this.currentExec.resize({ w: cols, h: rows });
|
||||
} catch {
|
||||
// Ignore resize errors
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(`\r\n\x1b[31mFailed to start shell: ${err.message}\x1b[0m\r\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ export class FileSystemService {
|
||||
*/
|
||||
private async hasComposeFile(dir: string): Promise<boolean> {
|
||||
const composeFiles = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
|
||||
|
||||
|
||||
for (const file of composeFiles) {
|
||||
try {
|
||||
await fs.access(path.join(dir, file));
|
||||
@@ -22,7 +22,7 @@ export class FileSystemService {
|
||||
// Continue checking other options
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ export class FileSystemService {
|
||||
private async getComposeFilePath(stackName: string): Promise<string> {
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
const composeFiles = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
|
||||
|
||||
|
||||
for (const file of composeFiles) {
|
||||
const filePath = path.join(stackDir, file);
|
||||
try {
|
||||
@@ -43,7 +43,7 @@ export class FileSystemService {
|
||||
// Continue checking other options
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
throw new Error(`No compose file found for stack: ${stackName}`);
|
||||
}
|
||||
|
||||
@@ -55,18 +55,18 @@ export class FileSystemService {
|
||||
try {
|
||||
const items = await fs.readdir(this.baseDir, { withFileTypes: true });
|
||||
const stackNames: string[] = [];
|
||||
|
||||
|
||||
for (const item of items) {
|
||||
if (!item.isDirectory()) continue;
|
||||
|
||||
|
||||
const stackDir = path.join(this.baseDir, item.name);
|
||||
const hasCompose = await this.hasComposeFile(stackDir);
|
||||
|
||||
|
||||
if (hasCompose) {
|
||||
stackNames.push(item.name);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return stackNames;
|
||||
} catch (error) {
|
||||
console.error('Error reading stacks:', error);
|
||||
@@ -94,9 +94,9 @@ export class FileSystemService {
|
||||
async saveStackContent(stackName: string, content: string): Promise<void> {
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
const filePath = path.join(stackDir, 'compose.yaml');
|
||||
|
||||
|
||||
console.log('Saving to path:', filePath);
|
||||
|
||||
|
||||
try {
|
||||
await fs.writeFile(filePath, content, 'utf-8');
|
||||
console.log('File written successfully');
|
||||
@@ -138,7 +138,7 @@ export class FileSystemService {
|
||||
async saveEnvContent(stackName: string, content: string): Promise<void> {
|
||||
const envPath = path.join(this.baseDir, stackName, '.env');
|
||||
console.log('Saving env to path:', envPath);
|
||||
|
||||
|
||||
try {
|
||||
await fs.writeFile(envPath, content, 'utf-8');
|
||||
console.log('Env file written successfully');
|
||||
@@ -156,9 +156,9 @@ export class FileSystemService {
|
||||
if (!stackName || !/^[a-zA-Z0-9_-]+$/.test(stackName)) {
|
||||
throw new Error('Stack name must contain only alphanumeric characters, underscores, or hyphens');
|
||||
}
|
||||
|
||||
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
|
||||
|
||||
// Check if directory already exists
|
||||
try {
|
||||
await fs.access(stackDir);
|
||||
@@ -169,14 +169,18 @@ export class FileSystemService {
|
||||
}
|
||||
// Directory doesn't exist, proceed
|
||||
}
|
||||
|
||||
|
||||
// Create the directory
|
||||
await fs.mkdir(stackDir, { recursive: true });
|
||||
|
||||
|
||||
// Write boilerplate compose.yaml
|
||||
const composePath = path.join(stackDir, 'compose.yaml');
|
||||
const boilerplate = `services:
|
||||
# Add your services here
|
||||
app:
|
||||
image: nginx:latest
|
||||
ports:
|
||||
- "8080:80"
|
||||
restart: always
|
||||
`;
|
||||
try {
|
||||
await fs.writeFile(composePath, boilerplate, 'utf-8');
|
||||
@@ -192,7 +196,7 @@ export class FileSystemService {
|
||||
*/
|
||||
async deleteStack(stackName: string): Promise<void> {
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
|
||||
|
||||
try {
|
||||
await fs.rm(stackDir, { recursive: true, force: true });
|
||||
console.log('Stack deleted successfully:', stackName);
|
||||
@@ -225,15 +229,15 @@ export class FileSystemService {
|
||||
}
|
||||
|
||||
const items = await fs.readdir(this.baseDir, { withFileTypes: true });
|
||||
|
||||
|
||||
for (const item of items) {
|
||||
// Only process .yml/.yaml files (skip directories and other files)
|
||||
if (!item.isFile()) continue;
|
||||
if (!item.name.endsWith('.yml') && !item.name.endsWith('.yaml')) continue;
|
||||
|
||||
|
||||
const stackName = item.name.replace(/\.(yml|yaml)$/, '');
|
||||
const stackDir = path.join(this.baseDir, stackName);
|
||||
|
||||
|
||||
// Check if target directory already exists
|
||||
try {
|
||||
await fs.access(stackDir);
|
||||
@@ -242,17 +246,17 @@ export class FileSystemService {
|
||||
} catch {
|
||||
// Directory doesn't exist, proceed with migration
|
||||
}
|
||||
|
||||
|
||||
console.log(`Migrating stack: ${stackName}`);
|
||||
|
||||
|
||||
// Create the stack directory
|
||||
await fs.mkdir(stackDir, { recursive: true });
|
||||
|
||||
|
||||
// Move compose file to new location (standardize on compose.yaml)
|
||||
const oldComposePath = path.join(this.baseDir, item.name);
|
||||
const newComposePath = path.join(stackDir, 'compose.yaml');
|
||||
await fs.rename(oldComposePath, newComposePath);
|
||||
|
||||
|
||||
// Move env file if it exists (old pattern: stackname.env)
|
||||
const oldEnvPath = path.join(this.baseDir, `${stackName}.env`);
|
||||
const newEnvPath = path.join(stackDir, '.env');
|
||||
@@ -263,7 +267,7 @@ export class FileSystemService {
|
||||
} catch {
|
||||
// No env file to migrate, that's fine
|
||||
}
|
||||
|
||||
|
||||
console.log(`Successfully migrated stack: ${stackName}`);
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
Reference in New Issue
Block a user