-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdocker.ts
More file actions
421 lines (358 loc) · 12.7 KB
/
docker.ts
File metadata and controls
421 lines (358 loc) · 12.7 KB
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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import { spawn } from 'child_process';
import { CLIOptions, Inquirerer, cliExitWithError, extractFirst } from 'inquirerer';
const dockerUsageText = `
Docker Command:
pgpm docker <subcommand> [OPTIONS]
Manage Docker containers for local development.
PostgreSQL is always started by default. Additional services can be
included with the --include flag.
Subcommands:
start Start containers
stop Stop containers
ls List available services and their status
PostgreSQL Options:
--name <name> Container name (default: postgres)
--image <image> Docker image (default: constructiveio/postgres-plus:18)
--port <port> Host port mapping (default: 5432)
--user <user> PostgreSQL user (default: postgres)
--password <pass> PostgreSQL password (default: password)
--shm-size <size> Shared memory size for container (default: 2g)
General Options:
--help, -h Show this help message
--recreate Remove and recreate containers on start
--include <svc> Include additional service (can be repeated)
Available Additional Services:
minio MinIO S3-compatible object storage (port 9000)
Examples:
pgpm docker start Start PostgreSQL only
pgpm docker start --include minio Start PostgreSQL + MinIO
pgpm docker start --port 5433 Start on custom port
pgpm docker start --shm-size 4g Start with 4GB shared memory
pgpm docker start --recreate Remove and recreate containers
pgpm docker start --recreate --include minio Recreate PostgreSQL + MinIO
pgpm docker stop Stop PostgreSQL
pgpm docker stop --include minio Stop PostgreSQL + MinIO
pgpm docker ls List services and status
`;
interface DockerRunOptions {
name: string;
image: string;
port: number;
user: string;
password: string;
shmSize: string;
recreate?: boolean;
}
interface PortMapping {
host: number;
container: number;
}
interface VolumeMapping {
name: string;
containerPath: string;
}
interface ServiceDefinition {
name: string;
image: string;
ports: PortMapping[];
env: Record<string, string>;
command?: string[];
volumes?: VolumeMapping[];
}
const ADDITIONAL_SERVICES: Record<string, ServiceDefinition> = {
minio: {
name: 'minio',
image: 'minio/minio',
ports: [{ host: 9000, container: 9000 }],
env: {
MINIO_ACCESS_KEY: 'minioadmin',
MINIO_SECRET_KEY: 'minioadmin',
},
command: ['server', '/data'],
volumes: [{ name: 'minio-data', containerPath: '/data' }],
},
};
interface SpawnResult {
code: number;
stdout: string;
stderr: string;
}
function run(command: string, args: string[], options: { stdio?: 'inherit' | 'pipe' } = {}): Promise<SpawnResult> {
return new Promise((resolve, reject) => {
const stdio = options.stdio || 'pipe';
const child = spawn(command, args, { stdio });
let stdout = '';
let stderr = '';
if (stdio === 'pipe') {
child.stdout?.on('data', (data) => {
stdout += data.toString();
});
child.stderr?.on('data', (data) => {
stderr += data.toString();
});
}
child.on('error', (error) => {
reject(error);
});
child.on('close', (code) => {
resolve({
code: code ?? 0,
stdout: stdout.trim(),
stderr: stderr.trim()
});
});
});
}
async function checkDockerAvailable(): Promise<boolean> {
try {
const result = await run('docker', ['--version']);
return result.code === 0;
} catch (error) {
return false;
}
}
async function isContainerRunning(name: string): Promise<boolean | null> {
try {
const result = await run('docker', ['inspect', '-f', '{{.State.Running}}', name]);
if (result.code === 0) {
return result.stdout.trim() === 'true';
}
return null;
} catch (error) {
return null;
}
}
async function containerExists(name: string): Promise<boolean> {
try {
const result = await run('docker', ['inspect', name]);
return result.code === 0;
} catch (error) {
return false;
}
}
async function startContainer(options: DockerRunOptions): Promise<void> {
const { name, image, port, user, password, shmSize, recreate } = options;
const dockerAvailable = await checkDockerAvailable();
if (!dockerAvailable) {
await cliExitWithError('Docker is not installed or not available in PATH. Please install Docker first.');
return;
}
const exists = await containerExists(name);
const running = await isContainerRunning(name);
if (running === true) {
console.log(`✅ Container "${name}" is already running`);
return;
}
if (recreate && exists) {
console.log(`🗑️ Removing existing container "${name}"...`);
const removeResult = await run('docker', ['rm', '-f', name], { stdio: 'inherit' });
if (removeResult.code !== 0) {
await cliExitWithError(`Failed to remove container "${name}"`);
return;
}
}
if (exists && running === false) {
console.log(`🔄 Starting existing container "${name}"...`);
const startResult = await run('docker', ['start', name], { stdio: 'inherit' });
if (startResult.code === 0) {
console.log(`✅ Container "${name}" started successfully`);
} else {
await cliExitWithError(`Failed to start container "${name}"`);
}
return;
}
console.log(`🚀 Creating and starting new container "${name}"...`);
const runArgs = [
'run',
'-d',
'--name', name,
'--shm-size', shmSize,
'-e', `POSTGRES_USER=${user}`,
'-e', `POSTGRES_PASSWORD=${password}`,
'-p', `${port}:5432`,
image
];
const runResult = await run('docker', runArgs, { stdio: 'inherit' });
if (runResult.code === 0) {
console.log(`✅ Container "${name}" created and started successfully`);
console.log(`📌 PostgreSQL is available at localhost:${port}`);
console.log(`👤 User: ${user}`);
console.log(`🔑 Password: ${password}`);
} else {
await cliExitWithError(`Failed to create container "${name}". Check if port ${port} is already in use.`);
}
}
async function stopContainer(name: string): Promise<void> {
const dockerAvailable = await checkDockerAvailable();
if (!dockerAvailable) {
await cliExitWithError('Docker is not installed or not available in PATH. Please install Docker first.');
return;
}
const exists = await containerExists(name);
if (!exists) {
console.log(`ℹ️ Container "${name}" not found`);
return;
}
const running = await isContainerRunning(name);
if (running === false) {
console.log(`ℹ️ Container "${name}" is already stopped`);
return;
}
console.log(`🛑 Stopping container "${name}"...`);
const stopResult = await run('docker', ['stop', name], { stdio: 'inherit' });
if (stopResult.code === 0) {
console.log(`✅ Container "${name}" stopped successfully`);
} else {
await cliExitWithError(`Failed to stop container "${name}"`);
}
}
async function startService(service: ServiceDefinition, recreate: boolean): Promise<void> {
const { name, image, ports, env: serviceEnv, command } = service;
const exists = await containerExists(name);
const running = await isContainerRunning(name);
if (running === true) {
console.log(`✅ Container "${name}" is already running`);
return;
}
if (recreate && exists) {
console.log(`🗑️ Removing existing container "${name}"...`);
const removeResult = await run('docker', ['rm', '-f', name], { stdio: 'inherit' });
if (removeResult.code !== 0) {
await cliExitWithError(`Failed to remove container "${name}"`);
return;
}
}
if (exists && running === false) {
console.log(`🔄 Starting existing container "${name}"...`);
const startResult = await run('docker', ['start', name], { stdio: 'inherit' });
if (startResult.code === 0) {
console.log(`✅ Container "${name}" started successfully`);
} else {
await cliExitWithError(`Failed to start container "${name}"`);
}
return;
}
console.log(`🚀 Creating and starting new container "${name}"...`);
const runArgs = [
'run',
'-d',
'--name', name,
];
for (const [key, value] of Object.entries(serviceEnv)) {
runArgs.push('-e', `${key}=${value}`);
}
for (const portMapping of ports) {
runArgs.push('-p', `${portMapping.host}:${portMapping.container}`);
}
if (service.volumes) {
for (const vol of service.volumes) {
runArgs.push('-v', `${vol.name}:${vol.containerPath}`);
}
}
runArgs.push(image);
if (command) {
runArgs.push(...command);
}
const runResult = await run('docker', runArgs, { stdio: 'inherit' });
if (runResult.code === 0) {
console.log(`✅ Container "${name}" created and started successfully`);
const portInfo = ports.map(p => `localhost:${p.host}`).join(', ');
console.log(`📌 ${name} is available at ${portInfo}`);
} else {
const portInfo = ports.map(p => String(p.host)).join(', ');
await cliExitWithError(`Failed to create container "${name}". Check if port ${portInfo} is already in use.`);
}
}
async function stopService(service: ServiceDefinition): Promise<void> {
await stopContainer(service.name);
}
function parseInclude(args: Partial<Record<string, any>>): string[] {
const include = args.include;
if (!include) return [];
if (Array.isArray(include)) return include as string[];
if (typeof include === 'string') return [include];
return [];
}
function resolveIncludedServices(includeNames: string[]): ServiceDefinition[] {
const services: ServiceDefinition[] = [];
for (const name of includeNames) {
const service = ADDITIONAL_SERVICES[name];
if (!service) {
console.warn(`⚠️ Unknown service: "${name}". Available: ${Object.keys(ADDITIONAL_SERVICES).join(', ')}`);
} else {
services.push(service);
}
}
return services;
}
async function listServices(): Promise<void> {
const dockerAvailable = await checkDockerAvailable();
console.log('\nAvailable services:\n');
console.log(' Primary:');
if (dockerAvailable) {
const pgRunning = await isContainerRunning('postgres');
const pgStatus = pgRunning === true ? '\x1b[32mrunning\x1b[0m' : pgRunning === false ? '\x1b[33mstopped\x1b[0m' : '\x1b[90mnot created\x1b[0m';
console.log(` postgres constructiveio/postgres-plus:18 ${pgStatus}`);
} else {
console.log(' postgres constructiveio/postgres-plus:18 \x1b[90m(docker not available)\x1b[0m');
}
console.log('\n Additional (use --include <name>):');
for (const [key, service] of Object.entries(ADDITIONAL_SERVICES)) {
if (dockerAvailable) {
const running = await isContainerRunning(service.name);
const status = running === true ? '\x1b[32mrunning\x1b[0m' : running === false ? '\x1b[33mstopped\x1b[0m' : '\x1b[90mnot created\x1b[0m';
const portInfo = service.ports.map(p => String(p.host)).join(', ');
console.log(` ${key.padEnd(12)}${service.image.padEnd(36)}${status} port ${portInfo}`);
} else {
const portInfo = service.ports.map(p => String(p.host)).join(', ');
console.log(` ${key.padEnd(12)}${service.image.padEnd(36)}\x1b[90m(docker not available)\x1b[0m port ${portInfo}`);
}
}
console.log('');
}
export default async (
argv: Partial<Record<string, any>>,
_prompter: Inquirerer,
_options: CLIOptions
) => {
if (argv.help || argv.h) {
console.log(dockerUsageText);
process.exit(0);
}
const { first: subcommand, newArgv } = extractFirst(argv);
const args = newArgv as Partial<Record<string, any>>;
if (!subcommand) {
console.log(dockerUsageText);
await cliExitWithError('No subcommand provided. Use "start", "stop", or "ls".');
return;
}
const name = (args.name as string) || 'postgres';
const image = (args.image as string) || 'constructiveio/postgres-plus:18';
const port = typeof args.port === 'number' ? args.port : 5432;
const user = (args.user as string) || 'postgres';
const password = (args.password as string) || 'password';
const shmSize = (args['shm-size'] as string) || (args.shmSize as string) || '2g';
const recreate = args.recreate === true;
const includeNames = parseInclude(args);
const includedServices = resolveIncludedServices(includeNames);
switch (subcommand) {
case 'start':
await startContainer({ name, image, port, user, password, shmSize, recreate });
for (const service of includedServices) {
await startService(service, recreate);
}
break;
case 'stop':
await stopContainer(name);
for (const service of includedServices) {
await stopService(service);
}
break;
case 'ls':
await listServices();
break;
default:
console.log(dockerUsageText);
await cliExitWithError(`Unknown subcommand: ${subcommand}. Use "start", "stop", or "ls".`);
}
};