/
DockerContainer.js
163 lines (138 loc) · 3.83 KB
/
DockerContainer.js
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
import { platform } from 'os'
import execa from 'execa'
import fetch from 'node-fetch'
import pRetry from 'p-retry'
import DockerImage from './DockerImage.js'
import DockerPort from './DockerPort.js'
import debugLog from '../../../debugLog.js'
const { stringify } = JSON
const { entries } = Object
export default class DockerContainer {
static #dockerPort = new DockerPort()
#containerId = null
#env = null
#functionKey = null
#handler = null
#imageNameTag = null
#image = null
#port = null
constructor(env, functionKey, handler, runtime) {
this.#env = env
this.#functionKey = functionKey
this.#handler = handler
this.#imageNameTag = this._baseImage(runtime)
this.#image = new DockerImage(this.#imageNameTag)
}
_baseImage(runtime) {
return `lambci/lambda:${runtime}`
}
async start(codeDir) {
const [, port] = await Promise.all([
this.#image.pull(),
DockerContainer.#dockerPort.get(),
])
debugLog('Run Docker container...')
// TODO: support layer
// https://github.com/serverless/serverless/blob/v1.57.0/lib/plugins/aws/invokeLocal/index.js#L291-L293
const dockerArgs = [
'-v',
`${codeDir}:/var/task:ro,delegated`,
'-p',
`${port}:9001`,
'-e',
'DOCKER_LAMBDA_STAY_OPEN=1', // API mode
]
entries(this.#env).forEach(([key, value]) => {
dockerArgs.push('-e', `${key}=${value}`)
})
if (platform() === 'linux') {
// Add `host.docker.internal` DNS name to access host from inside the container
// https://github.com/docker/for-linux/issues/264
const gatewayIp = await this._getBridgeGatewayIp()
dockerArgs.push('--add-host', `host.docker.internal:${gatewayIp}`)
}
const { stdout: containerId } = await execa('docker', [
'create',
...dockerArgs,
this.#imageNameTag,
this.#handler,
])
const dockerStart = execa('docker', ['start', '-a', containerId], {
all: true,
})
await new Promise((resolve, reject) => {
dockerStart.all.on('data', (data) => {
const str = data.toString()
console.log(str)
if (str.includes('Lambda API listening on port')) {
resolve()
}
})
dockerStart.on('error', (err) => {
reject(err)
})
})
this.#containerId = containerId
this.#port = port
await pRetry(() => this._ping(), {
// default,
factor: 2,
// milliseconds
minTimeout: 10,
// default
retries: 10,
})
}
async _getBridgeGatewayIp() {
let gateway
try {
;({ stdout: gateway } = await execa('docker', [
'network',
'inspect',
'bridge',
'--format',
'{{(index .IPAM.Config 0).Gateway}}',
]))
} catch (err) {
console.error(err.stderr)
throw err
}
return gateway.split('/')[0]
}
async _ping() {
const url = `http://localhost:${this.#port}/2018-06-01/ping`
const res = await fetch(url)
if (!res.ok) {
throw new Error(`Failed to fetch from ${url} with ${res.statusText}`)
}
return res.text()
}
async request(event) {
const url = `http://localhost:${this.#port}/2015-03-31/functions/${
this.#functionKey
}/invocations`
const res = await fetch(url, {
body: stringify(event),
headers: { 'Content-Type': 'application/json' },
method: 'post',
})
if (!res.ok) {
throw new Error(`Failed to fetch from ${url} with ${res.statusText}`)
}
return res.json()
}
async stop() {
if (this.#containerId) {
try {
await execa('docker', ['stop', this.#containerId])
await execa('docker', ['rm', this.#containerId])
} catch (err) {
console.error(err.stderr)
throw err
}
}
}
get isRunning() {
return this.#containerId !== null && this.#port !== null
}
}