-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrunDocker.ts
94 lines (88 loc) · 2.61 KB
/
runDocker.ts
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
/*!
* Copyright © 2023 United States Government as represented by the
* Administrator of the National Aeronautics and Space Administration.
* All Rights Reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
import Dockerode, { Container } from 'dockerode'
import { fork } from 'node:child_process'
import { LauncherFunction } from './run.js'
const [, , command, jsonifiedArgs] = process.argv
const docker = new Dockerode({ protocol: 'http' })
let containerId = ''
if (command === 'launch-ddb-local-docker-subprocess') {
const { port } = JSON.parse(jsonifiedArgs)
let container: Container
try {
container = await createDdbContainer(port)
} catch (error) {
// Fix for Windows, containers exit, but do not get removed properly.
console.log('\nExisting container, removing and recreating')
const containers = await docker.listContainers({
limit: 1,
filters: '{"name": ["dynamodb-local"]}',
})
for (const existing of containers) {
if (existing.State !== 'exited') {
await docker.getContainer(existing.Id).kill()
}
await docker.getContainer(existing.Id).remove()
}
container = await createDdbContainer(port)
}
containerId = container.id
const stream = await container.attach({ stream: true, stderr: true })
stream.pipe(process.stderr)
await container.start()
const signals = ['message', 'SIGTERM', 'SIGINT']
signals.forEach((signal) => {
process.on(signal, async () => {
await container.kill()
await container.remove()
})
})
}
export const launchDocker: LauncherFunction = async ({ port, options }) => {
const argv = {
port,
options,
}
const subprocess = fork(new URL(import.meta.url), [
'launch-ddb-local-docker-subprocess',
JSON.stringify(argv),
])
return {
async kill() {
console.log('Killing Docker container')
subprocess.kill()
return containerId
},
async waitUntilStopped() {
return new Promise((resolve) => {
subprocess.on('exit', () => {
console.log('Docker container exited')
resolve()
})
})
},
}
}
export async function removeContainer(containerId: string) {
await docker.getContainer(containerId).remove()
}
async function createDdbContainer(port: number) {
return await docker.createContainer({
Image: 'amazon/dynamodb-local:latest',
name: 'dynamodb-local',
Cmd: ['-jar', 'DynamoDBLocal.jar', '-sharedDb', '-dbPath', '/tmp/'],
ExposedPorts: {
'8000/tcp': {},
},
HostConfig: {
PortBindings: {
[`${port}/tcp`]: [{ HostIp: '0.0.0.0', HostPort: `${port}` }],
},
},
})
}