1 | import crypto from 'crypto'
|
2 | import fs from 'fs'
|
3 | import path from 'path'
|
4 |
|
5 | import Docker from 'dockerode'
|
6 |
|
7 | import ndjson from 'ndjson'
|
8 | import parser from 'docker-file-parser'
|
9 | import tarFs from 'tar-fs'
|
10 | import zlib from 'zlib'
|
11 |
|
12 |
|
13 | interface DockerMessage {
|
14 | error?: string
|
15 | stream?: string
|
16 | aux?: {
|
17 | ID?: string
|
18 | }
|
19 | }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 | export default class DockerBuilder {
|
29 |
|
30 | |
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 | async build (dir: string, name?: string, dockerfile: string = 'Dockerfile') {
|
38 | if (!name) {
|
39 | const hash = crypto.createHash('md5').update(dir).digest('hex')
|
40 | name = 'dockter-' + hash
|
41 | }
|
42 |
|
43 | const content = fs.readFileSync(path.join(dir, dockerfile), 'utf8')
|
44 | let instructions = parser.parse(content, { includeComments: true })
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | let workdir = '/'
|
50 | let user = 'root'
|
51 | let dockterize = false
|
52 | let newContent = ''
|
53 | let index = 0
|
54 | for (let instruction of instructions) {
|
55 | if (instruction.name === 'WORKDIR') {
|
56 | workdir = path.join(workdir, instruction.args as string)
|
57 | } else if (instruction.name === 'USER') {
|
58 | user = instruction.args as string
|
59 | } else if (instruction.name === 'COMMENT') {
|
60 | const arg = instruction.args as string
|
61 | if (arg.match(/^# *dockter/)) {
|
62 | instructions = instructions.slice(index + 1)
|
63 | dockterize = true
|
64 | break
|
65 | }
|
66 | }
|
67 | if (instruction.raw) newContent += instruction.raw + '\n'
|
68 | index += 1
|
69 | }
|
70 |
|
71 |
|
72 | if (!dockterize) instructions = []
|
73 |
|
74 |
|
75 | const tar = tarFs.pack(dir, {
|
76 | ignore: name => {
|
77 | const relpath = path.relative(dir, name)
|
78 |
|
79 |
|
80 |
|
81 | return relpath === 'Dockerfile' || relpath[0] === '.' || relpath === 'snapshot'
|
82 | },
|
83 | finalize: false,
|
84 | finish: pack => {
|
85 |
|
86 | pack.entry({ name: 'Dockerfile' }, newContent)
|
87 | pack.finalize()
|
88 | }
|
89 | })
|
90 | const targz = tar.pipe(zlib.createGzip())
|
91 |
|
92 |
|
93 |
|
94 |
|
95 |
|
96 | const docker = new Docker()
|
97 |
|
98 | const messages: Array<any> = []
|
99 | const stream = await docker.buildImage(targz, {
|
100 |
|
101 |
|
102 | t: name + ':system'
|
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 | let currentSystemLayer = await new Promise<string>((resolve, reject) => {
|
130 | let id: string
|
131 | stream.pipe(ndjson.parse()).on('data', (data: DockerMessage) => {
|
132 | if (data.error) {
|
133 | messages.push({
|
134 | level: 'error',
|
135 | message: data.error
|
136 | })
|
137 | console.error(data.error)
|
138 | } else if (data.aux && data.aux.ID) {
|
139 | id = data.aux.ID
|
140 | } else {
|
141 |
|
142 |
|
143 |
|
144 | if (data.stream) {
|
145 | process.stderr.write(data.stream)
|
146 | }
|
147 | }
|
148 | })
|
149 | stream.on('end', () => resolve(id))
|
150 | stream.on('error', reject)
|
151 | })
|
152 |
|
153 | // Check for any error message
|
154 | const errors = messages.filter(message => message.level === 'error')
|
155 | if (errors.length) throw new Error(`There was an error when building the image: ${errors.map(error => error.message).join(',')}`)
|
156 |
|
157 | // Get information on the current
|
158 | const image = docker.getImage(name + ':latest')
|
159 | let appLayer
|
160 | let lastSystemLayer
|
161 | try {
|
162 | const imageInfo = await image.inspect()
|
163 | appLayer = imageInfo.Id
|
164 | lastSystemLayer = imageInfo.Config.Labels && imageInfo.Config.Labels.systemLayer
|
165 | } catch (error) {
|
166 | // No existing image, just continue
|
167 | }
|
168 |
|
169 | // If the foundation image has changed then use the new version,
|
170 | // otherwise use the existing one
|
171 | let layer
|
172 | if (lastSystemLayer) {
|
173 | if (lastSystemLayer !== currentSystemLayer) layer = currentSystemLayer
|
174 | else layer = appLayer
|
175 | } else {
|
176 | layer = currentSystemLayer
|
177 | }
|
178 |
|
179 | // Create a container from the layer and start it up
|
180 | let container = await docker.createContainer({
|
181 | Image: layer,
|
182 | Tty: true,
|
183 | Cmd: ['/bin/bash']
|
184 | })
|
185 | await container.start()
|
186 |
|
187 | // Handle the remaining instructions
|
188 | let count = 1
|
189 | let changes = ''
|
190 | for (let instruction of instructions) {
|
191 | const step = `Dockter ${count}/${instructions.length} :`
|
192 | switch (instruction.name) {
|
193 | case 'USER':
|
194 | user = instruction.args as string
|
195 | break
|
196 |
|
197 | case 'WORKDIR':
|
198 | workdir = path.join(workdir, instruction.args as string)
|
199 | break
|
200 |
|
201 | case 'COPY':
|
202 | case 'ADD':
|
203 | // Add files/subdirs to the container
|
204 | const copy = instruction.args as Array<string>
|
205 | const to = copy.pop() as string
|
206 | const pack = tarFs.pack(dir, {
|
207 |
|
208 | map: function (header) {
|
209 | header.name = to
|
210 | return header
|
211 | },
|
212 |
|
213 | ignore: name => {
|
214 | const relativePath = path.relative(dir, name)
|
215 | return !copy.includes(relativePath)
|
216 | }
|
217 | })
|
218 | await container.putArchive(pack, { path: workdir })
|
219 | break
|
220 |
|
221 | case 'RUN':
|
222 | // Execute code in the container
|
223 | const script = instruction.args as string
|
224 | const exec = await container.exec({
|
225 | Cmd: ['bash', '-c', `${script}`],
|
226 | AttachStdout: true,
|
227 | AttachStderr: true,
|
228 | User: user,
|
229 | Tty: true
|
230 | })
|
231 | await exec.start()
|
232 |
|
233 | exec.output.pipe(process.stdout)
|
234 |
|
235 | // Wait until the exec has finished running, checking every 100ms
|
236 | while (true) {
|
237 | let status = await exec.inspect()
|
238 | if (status.Running === false) break
|
239 | await new Promise(resolve => setTimeout(resolve, 100))
|
240 | }
|
241 | break
|
242 |
|
243 | case 'CMD':
|
244 | // Dockerfile instructions to apply when committing the image
|
245 | changes += instruction.raw + '\n\n'
|
246 | break
|
247 |
|
248 | case 'COMMENT':
|
249 | // Just ignore it!
|
250 | break
|
251 |
|
252 | default:
|
253 | throw new Error(`Dockter can not yet handle a ${instruction.name} instruction. Put it before the # dockter comment in your Dockerfile.`)
|
254 | }
|
255 | count += 1
|
256 | }
|
257 |
|
258 | // Create an image from the modified container
|
259 | const data = await container.commit({
|
260 |
|
261 |
|
262 | repo: name,
|
263 | comment: instructions.length > 0 ? 'Updated application layer' : 'No updates requested',
|
264 | changes,
|
265 | User: user,
|
266 | WorkingDir: workdir,
|
267 | Labels: {
|
268 | systemLayer: currentSystemLayer
|
269 | }
|
270 | })
|
271 |
|
272 | await container.stop()
|
273 | }
|
274 | }
|
275 |
|
\ | No newline at end of file |