-
Notifications
You must be signed in to change notification settings - Fork 22
/
docker.js
401 lines (333 loc) · 10 KB
/
docker.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
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
// Copyright © 2016 Team Janitor. All rights reserved.
// The following code is covered by the AGPL-3.0 license.
const Dockerode = require('dockerode');
const tar = require('tar-stream');
const stream = require('stream');
const stringdecoder = require('string_decoder');
const util = require('util');
const db = require('./db');
const hosts = require('./hosts');
const log = require('./log');
// Get client access to a given Docker host.
function getDocker (hostname, callback) {
const host = hosts.get(hostname);
if (!host) {
callback(new Error('Unknown Docker host: ' + hostname));
return;
}
const { ca, client } = db.get('tls');
const docker = new Dockerode({
protocol: 'https',
host: hostname,
port: Number(host.properties.port),
ca: host.properties.ca || ca.crt,
cert: host.properties.cert || host.properties.crt || client.crt,
key: host.properties.key || client.key
});
callback(null, docker);
}
// List all Docker images on a given host.
exports.listImages = function (parameters, callback) {
const { host } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
docker.listImages({ all: 1 }, (error, images) => {
callback(error, images);
});
});
};
// Build a Docker image from a given Dockerfile.
exports.buildImage = function (parameters, callback) {
const { host, tag, dockerfile } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
// Add the Dockerfile to a tar stream for Docker's Remote API.
const pack = tar.pack();
pack.entry({ name: 'Dockerfile' }, dockerfile);
pack.finalize();
// FIXME: If `docker.buildImage()` ever supports streams, use the tar stream
// directly instead of flushing it into a Buffer.
const chunks = [];
pack.on('data', chunk => { chunks.push(chunk); });
pack.on('end', () => {
const buffer = Buffer.concat(chunks);
const options = {
t: tag,
nocache: true
};
docker.buildImage(buffer, options, (error, response) => {
if (error) {
callback(error);
return;
}
// Transform Docker's response into a proper Node.js Stream.
const dockerResponse = new DockerResponse();
response.pipe(dockerResponse);
callback(null, dockerResponse);
});
});
});
};
// Pull a Docker image into a given host.
exports.pullImage = function (parameters, callback) {
const { host, image: imageId } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
docker.pull(imageId, function (error, stream) {
if (error) {
callback(error);
return;
}
callback(null, stream);
});
});
};
// Get low-level information on a Docker image from a given host.
exports.inspectImage = function (parameters, callback) {
const { host, image: imageId } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const image = docker.getImage(imageId);
image.inspect((error, data) => {
callback(error, data);
});
});
};
// Tag a Docker image in a given host.
exports.tagImage = function (parameters, callback) {
const { host, image: imageId, tag: tagId } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const image = docker.getImage(imageId);
const [repo, tag = 'latest'] = tagId.split(':');
image.tag({ repo, tag }, (error, data) => {
callback(error);
});
});
};
// Delete a Docker image from a given host.
exports.removeImage = function (parameters, callback) {
const { host, image: imageId } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const image = docker.getImage(imageId);
image.remove((error, data) => {
callback(error);
});
});
};
// List all Docker containers on a given host.
exports.listContainers = function (parameters, callback) {
const { host } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
docker.listContainers({ all: 1 }, (error, containers) => {
callback(error, containers);
});
});
};
// Spawn a new Docker container from a given image.
exports.runContainer = function (parameters, callback) {
const { host, image, ports } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const options = {
Image: image,
ExposedPorts: {},
HostConfig: {
CapAdd: ['SYS_PTRACE'],
PortBindings: {},
}
};
for (const port in ports) {
options.ExposedPorts[port + '/tcp'] = {};
options.HostConfig.PortBindings[port + '/tcp'] = [{
HostIp: ports[port].publish ? '0.0.0.0' : '127.0.0.1',
HostPort: String(ports[port].hostPort)
}];
}
docker.createContainer(options, (error, container) => {
if (error) {
callback(error, container);
return;
}
container.start((error, logs) => {
callback(error, container, logs);
});
});
});
};
// Copy files into a given Docker container.
exports.copyIntoContainer = function (parameters, callback) {
const { host, container: containerId, files, path } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
// Add the files to a tar stream for Docker's Remote API.
const pack = tar.pack();
for (const name in files) {
pack.entry({ name, mode: 0o600 }, files[name]);
}
pack.finalize();
// FIXME: If `container.putArchive()` ever supports streams, use the tar
// stream directly instead of flushing it into a Buffer.
const chunks = [];
pack.on('data', chunk => { chunks.push(chunk); });
pack.on('end', () => {
const buffer = Buffer.concat(chunks);
const container = docker.getContainer(containerId);
container.putArchive(buffer, { path }, (error, response) => {
callback(error);
});
});
});
};
// Execute a specific command inside a given Docker container.
exports.execInContainer = function (parameters, callback) {
const { host, container: containerId, command } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const container = docker.getContainer(containerId);
const options = {
Cmd: ['/bin/bash', '-c', command],
AttachStdout: true,
AttachStderr: true
};
container.exec(options, (error, exec) => {
if (error) {
callback(error);
return;
}
exec.start((error, stream) => {
callback(error, stream);
});
});
});
};
// List all files that were modified, added or deleted in a Docker container.
exports.listChangedFilesInContainer = function (parameters, callback) {
const { host, container: containerId } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const container = docker.getContainer(containerId);
container.changes((error, changedFiles) => {
callback(error, changedFiles);
});
});
};
// Kill and delete a Docker container from a given host.
exports.removeContainer = function (parameters, callback) {
const { host, container: containerId } = parameters;
getDocker(host, (error, docker) => {
if (error) {
callback(error);
return;
}
const container = docker.getContainer(containerId);
container.remove({ force: true }, (error, data) => {
callback(error);
});
});
};
// Get the Docker version of a given host.
exports.version = function (parameters, callback) {
const { host } = parameters;
getDocker(host, (error, docker) => {
if (error) {
log('[fail] could not get the docker client', error);
}
docker.version((error, data) => {
callback(error, data);
});
});
};
// Docker Remote API response stream.
// Inspired by `JSONParseStream`: https://nodejs.org/api/stream.html#stream_object_mode
function DockerResponse (options) {
// Allow use without `new`.
if (!(this instanceof DockerResponse)) {
return new DockerResponse(options);
}
// Make this a proper Transform stream.
stream.Transform.call(this, options);
this._buffer = '';
this._decoder = new stringdecoder.StringDecoder('utf8');
}
util.inherits(DockerResponse, stream.Transform);
// Transform Docker response chunks into a proper Node.js Stream.
DockerResponse.prototype._transform = function (chunk, encoding, callback) {
// Decode the chunk as a UTF-8 string.
this._buffer += this._decoder.write(chunk);
// Split on line breaks.
const lines = this._buffer.split(/\r?\n/);
// Keep the last partial line buffered.
this._buffer = lines.pop();
// Parse all other lines.
for (let i = 0; i < lines.length; i++) {
this._parse(lines[i]);
}
callback();
};
// Parse Docker response lines as JSON.
DockerResponse.prototype._parse = function (line) {
try {
// We expect JSON objects formatted like `{stream:'…'}`, `{error:'…'}` or `{aux:{…}}`.
// Example: https://docs.docker.com/engine/api/v1.24/#build-image-from-a-dockerfile
const data = JSON.parse(line);
if (data.error) {
this.emit('error', new Error(data.error));
} else if (data.stream) {
this.push(data.stream);
} else if (data.aux) {
// Emit auxilliary data for anyone interested, e.g. `{ID:'…'}`.
this.emit('aux', data.aux);
} else {
// The object didn't have a `stream`, `error` or `aux` property!
this.emit('error', new Error('Unknown format: ' + line));
}
} catch (error) {
// The input was not valid JSON!
this.emit('error', new Error('Invalid JSON: ' + line));
}
};
// Flush any remaining data.
DockerResponse.prototype._flush = function (callback) {
const line = this._buffer.trim();
this._buffer = '';
if (line) {
this._parse(line);
}
callback();
};