File size: 14,913 Bytes
dacd41a
c85705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dacd41a
 
c85705b
 
 
 
dacd41a
c85705b
 
 
 
 
 
 
dacd41a
c85705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dacd41a
c85705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dacd41a
c85705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
dacd41a
c85705b
 
 
dacd41a
c85705b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402

import Docker from 'dockerode';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import fs from 'fs-extra';

export interface ContainerConfig {
    id: string;
    image: string;
    memory: number; // in bytes
    cpu: number;    // e.g., 0.5
    hostPort: number;       // unique port on the host (e.g. 3101)
    containerPort?: number; // port inside the container (default: 3000)
    env?: Record<string, string>;
}

export class DockerManager {
    private activeContainers: Map<string, Docker.Container> = new Map();

    constructor(private docker: Docker) { }

    async createContainer(config: ContainerConfig): Promise<Docker.Container> {

        // Pull image if not exists locally
        try {
            await this.docker.pull(config.image);
        } catch {
            // Image might already exist locally
        }

        const containerPort = (config.containerPort ?? 3000).toString();
        const portKey = `${containerPort}/tcp`;

        const container = await this.docker.createContainer({
            Image: config.image,
            name: `coder-project-${config.id}`,
            ExposedPorts: {
                [portKey]: {},
            },
            HostConfig: {
                Memory: config.memory,
                NanoCpus: config.cpu * 1e9,
                AutoRemove: true,
                PortBindings: {
                    [portKey]: [{ HostPort: config.hostPort.toString() }],
                },
            },
            Env: [
                ...Object.entries(config.env || {}).map(([k, v]) => `${k}=${v}`),
                // Tell vite/next/uvicorn to listen on ALL interfaces so Docker NAT can reach it
                `HOST=0.0.0.0`,
                `PORT=${containerPort}`,
            ],
            Tty: true,
        });

        this.activeContainers.set(config.id, container);
        return container;
    }

    async startContainer(id: string): Promise<void> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);
        await container.start();
    }

    async stopContainer(id: string): Promise<void> {
        const container = this.activeContainers.get(id);
        if (container) {
            await container.stop().catch(() => { }); // Ignore if already stopped
            this.activeContainers.delete(id);
        }
    }

    async execCommand(id: string, cmd: string[], onLog?: (data: string) => void): Promise<number> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        // Set PATH so node_modules/.bin, bun etc. are always found
        const fullCmd = `export PATH="/app/node_modules/.bin:/root/.bun/bin:$PATH" && cd /app && ${cmd.join(' ')}`;
        const exec = await container.exec({
            Cmd: ['sh', '-c', fullCmd],
            AttachStdout: true,
            AttachStderr: true,
        });

        const stream = await exec.start({ hijack: true, stdin: false });

        return new Promise((resolve, reject) => {
            // Use on('data') instead of demuxStream to avoid backpressure deadlock
            stream.on('data', (chunk: Buffer) => {
                // Docker multiplexed stream: first 8 bytes are header
                // byte 0: stream type (1=stdout, 2=stderr)
                // bytes 4-7: payload length (big-endian uint32)
                let offset = 0;
                while (offset < chunk.length) {
                    if (chunk.length < offset + 8) break;
                    const payloadLen = chunk.readUInt32BE(offset + 4);
                    const payload = chunk.slice(offset + 8, offset + 8 + payloadLen);
                    if (payload.length > 0) {
                        onLog?.(payload.toString());
                    }
                    offset += 8 + payloadLen;
                }
            });

            stream.on('end', async () => {
                try {
                    const result = await exec.inspect();
                    resolve(result.ExitCode ?? 0);
                } catch {
                    resolve(0);
                }
            });

            stream.on('error', reject);
        });
    }

    async execCommandBackground(id: string, cmd: string[], onLog?: (data: string) => void): Promise<void> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        // Include node_modules/.bin and bun in PATH so binaries like `next`, `vite` are found
        const cmdStr = cmd.join(' ');
        const fullCmd = `export PATH="/app/node_modules/.bin:/root/.bun/bin:$PATH" && ${cmdStr} >> /tmp/server.log 2>&1`;
        console.log("Command =>", cmdStr);
        const exec = await container.exec({
            Cmd: ['sh', '-c', `ls && npm i && ${fullCmd}`],
            AttachStdout: true,
            AttachStderr: true,
        });

        const stream = await exec.start({
            hijack: true,
            stdin: false,
        });

        stream.on("data", (chunk) => {
            console.log(chunk.toString());
        });
        onLog?.(`Started: ${cmdStr}`);
    }

    async waitForInstall(id: string, timeout: number = 300000): Promise<boolean> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        const startTime = Date.now();
        let lastLog = '';

        while (Date.now() - startTime < timeout) {
            try {
                // Check if node_modules exists (successful install indicator)
                const exec = await container.exec({
                    Cmd: ['sh', '-c', 'test -d /app/node_modules && echo "INSTALLED" || echo "NOT_INSTALLED"'],
                    AttachStdout: true,
                    AttachStderr: true,
                });

                const stream = await exec.start({});
                let output = '';

                await new Promise<void>((resolve) => {
                    this.docker.modem.demuxStream(stream, {
                        write: (chunk: Buffer) => { output += chunk.toString(); }
                    } as any, {
                        write: (chunk: Buffer) => { output += chunk.toString(); }
                    } as any);

                    stream.on('end', () => resolve());
                });

                if (output.includes('INSTALLED')) {
                    return true;
                }

                // Also check the install log for completion
                const logExec = await container.exec({
                    Cmd: ['sh', '-c', 'tail -5 /tmp/server.log 2>/dev/null || echo "No log yet"'],
                    AttachStdout: true,
                    AttachStderr: true,
                });

                const logStream = await logExec.start({});
                let logOutput = '';

                await new Promise<void>((resolve) => {
                    this.docker.modem.demuxStream(logStream, {
                        write: (chunk: Buffer) => { logOutput += chunk.toString(); }
                    } as any, {
                        write: (chunk: Buffer) => { logOutput += chunk.toString(); }
                    } as any);

                    logStream.on('end', () => resolve());
                });

                if (logOutput !== lastLog && logOutput.trim()) {
                    lastLog = logOutput;
                    console.log(`[${id}] Install log: ${logOutput.trim()}`);
                }

                // Check for common error patterns
                if (logOutput.includes('error') || logOutput.includes('Error') || logOutput.includes('ERR_')) {
                    return false;
                }

            } catch {
                // Keep waiting
            }

            await new Promise(r => setTimeout(r, 3000));
        }

        return false;
    }

    async waitForServer(id: string, port: number = 3000, timeout: number = 120000): Promise<boolean> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        const startTime = Date.now();

        while (Date.now() - startTime < timeout) {
            try {
                const exec = await container.exec({
                    Cmd: ['sh', '-c', `curl -s -o /dev/null -w "%{http_code}" http://localhost:${port} || echo "000"`],
                    AttachStdout: true,
                    AttachStderr: true,
                });

                const stream = await exec.start({ hijack: true, stdin: false });
                let output = '';

                await new Promise<void>((resolve, reject) => {
                    const timeoutId = setTimeout(() => {
                        stream.destroy();
                        resolve();
                    }, 5000);

                    stream.on('data', (chunk: Buffer) => {
                        let offset = 0;
                        while (offset < chunk.length) {
                            if (chunk.length < offset + 8) break;
                            const payloadLen = chunk.readUInt32BE(offset + 4);
                            const payload = chunk.slice(offset + 8, offset + 8 + payloadLen);
                            output += payload.toString();
                            offset += 8 + payloadLen;
                        }
                    });

                    stream.on('end', () => {
                        clearTimeout(timeoutId);
                        resolve();
                    });
                    stream.on('error', (err) => {
                        clearTimeout(timeoutId);
                        resolve(); // Resolve anyway to try again
                    });
                });

                const httpCode = parseInt(output.trim());
                if (!isNaN(httpCode) && httpCode >= 200 && httpCode < 500) {
                    return true;
                }
            } catch (err) {
                // Server not ready yet
            }

            await new Promise(r => setTimeout(r, 2000));
        }

        return false;
    }

    async tailLogs(id: string, filePath: string, onLog: (data: string) => void): Promise<void> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        const exec = await container.exec({
            Cmd: ['sh', '-c', `touch ${filePath} && tail -f ${filePath}`],
            AttachStdout: true,
            AttachStderr: true,
        });

        const stream = await exec.start({ hijack: true, stdin: false });

        stream.on('data', (chunk: Buffer) => {
            let offset = 0;
            while (offset < chunk.length) {
                if (chunk.length < offset + 8) break;
                const payloadLen = chunk.readUInt32BE(offset + 4);
                const payload = chunk.slice(offset + 8, offset + 8 + payloadLen);
                if (payload.length > 0) {
                    onLog(payload.toString());
                }
                offset += 8 + payloadLen;
            }
        });

        stream.on('error', (err) => {
            console.error(`[${id}] tailLogs error:`, err);
        });
    }

    async getContainerLogs(id: string): Promise<string> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        try {
            const logStream = await container.logs({
                stdout: true,
                stderr: true,
                tail: 100,
            });

            return logStream.toString();
        } catch {
            return '';
        }
    }

    async getContainerIp(id: string): Promise<string> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);
        const inspect = await container.inspect();
        // Fallback to Bridge network if available
        const networks = inspect.NetworkSettings.Networks;
        const netName = Object.keys(networks)[0];
        return networks[netName]?.IPAddress || '';
    }

    async copyToContainer(id: string, sourcePath: string, destPath: string): Promise<void> {
        const container = this.activeContainers.get(id);
        if (!container) throw new Error(`Container ${id} not found`);

        const archiver = require('archiver');
        const tarStream = archiver('tar');

        tarStream.directory(sourcePath, false);
        tarStream.finalize();

        await container.putArchive(tarStream, { path: destPath });
    }

    async buildWorkerImage(dockerfilePath: string, imageTag: string): Promise<void> {
        console.log(`Building worker image: ${imageTag}...`);
        const tar = require('tar-fs');
        const stream = tar.pack(path.dirname(dockerfilePath));

        return new Promise((resolve, reject) => {
            this.docker.buildImage(stream, { t: imageTag, dockerfile: path.basename(dockerfilePath) }, (err, response) => {
                if (err) return reject(err);
                if (!response) return reject(new Error('No response from docker build'));

                this.docker.modem.followProgress(response, (err, res) => {
                    if (err) return reject(err);
                    console.log(`${imageTag} image built successfully`);
                    resolve();
                }, (event) => {
                    if (event.stream) process.stdout.write(event.stream);
                });
            });
        });
    }

    async isProcessRunning(id: string, searchPattern: string): Promise<boolean> {
        const container = this.activeContainers.get(id);
        if (!container) return false;

        try {
            const exec = await container.exec({
                Cmd: ['sh', '-c', `ps aux | grep "${searchPattern}" | grep -v grep`],
                AttachStdout: true,
                AttachStderr: true,
            });

            const stream = await exec.start({ hijack: true, stdin: false });
            let output = '';

            await new Promise<void>((resolve) => {
                stream.on('data', (chunk: Buffer) => {
                    let offset = 0;
                    while (offset < chunk.length) {
                        if (chunk.length < offset + 8) break;
                        const payloadLen = chunk.readUInt32BE(offset + 4);
                        const payload = chunk.slice(offset + 8, offset + 8 + payloadLen);
                        output += payload.toString();
                        offset += 8 + payloadLen;
                    }
                });
                stream.on('end', () => resolve());
                stream.on('error', () => resolve());
            });

            return output.trim().length > 0;
        } catch {
            return false;
        }
    }
}