-
Notifications
You must be signed in to change notification settings - Fork 33
/
index.js
523 lines (463 loc) · 16.6 KB
/
index.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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
var express = require("express");
var basicAuth = require('express-basic-auth')
var bodyParser = require('body-parser');
var Docker = require('dockerode');
var fs = require('fs');
var config = require('./default_settings.js');
var docker = false;
//Setup express
var app = express();
app.use(bodyParser.json());
//If we have set a username and password, require it
if (config.get("http.username")) {
var authUsers = {
users: {}
}
authUsers.users[config.get("http.username")] = config.get("http.password");
app.use(basicAuth(authUsers));
}
//Set the container route
app.all('/container/:containerId', function (req, res) {
if (!req.params.containerId) {
//This paramater is required
res.status(400);
res.send("Container ID is required");
return;
}
var containerId = req.params.containerId;
//Does this container exist in Docker? If not respond with 404 not found and body of off
if (req.method == "POST") {
if (config.get("debug"))
console.log("Updating container " + containerId);
getContainer(containerId, function (container) {
if (req.body.state == "start") {
if (config.get("debug"))
console.log("Attempting to start container " + container.Id);
docker.getContainer(container.Id).start(function (err, data) {
if (err) {
if (config.get("debug")) {
console.log("Failed to start container " + container.Id);
console.log(err);
}
res.status(500);
res.send(err);
return;
}
if (config.get("debug"))
console.log("Container started");
res.status(200);
res.send({
state: "running"
});
});
} else if (req.body.state == "stop") {
if (config.get("debug"))
console.log("Attempting to stop container " + container.Id);
docker.getContainer(container.Id).stop(function (err, data) {
if (err) {
if (config.get("debug")) {
console.log("Failed to stop container " + container.Id);
console.log(err);
}
res.status(500);
res.send(err);
return;
}
if (config.get("debug"))
console.log("Container stopped");
res.status(200); //We found the container! This reponse can be trusted
res.send({
state: "stopped"
});
});
} else if (req.body.state == "pause") {
if (config.get("debug"))
console.log("Attempting to pause container " + container.Id);
docker.getContainer(container.Id).pause(function (err, data) {
if (err) {
if (config.get("debug")) {
console.log("Failed to pause container " + container.Id);
console.log(err);
}
res.status(500);
res.send(err);
return;
}
if (config.get("debug"))
console.log("Container paused");
res.status(200); //We found the container! This reponse can be trusted
res.send({
state: "paused"
});
});
} else if (req.body.state == "unpause") {
if (config.get("debug"))
console.log("Attempting to unpause container " + container.Id);
docker.getContainer(container.Id).unpause(function (err, data) {
if (err) {
if (config.get("debug")) {
console.log("Failed to unpause container " + container.Id);
console.log(err);
}
res.status(500);
res.send(err);
return;
}
if (config.get("debug"))
console.log("Container unpaused");
res.status(200); //We found the container! This reponse can be trusted
res.send({
state: "running"
});
});
} else {
res.status(500);
res.send({
error: "Invalid state specified"
});
return;
}
}, function (status, message) {
if (config.get("debug"))
console.log("Failed to get status of Docker container");
res.status(status);
if (message) {
res.send(message);
if (config.get("debug"))
console.log(message);
}
})
} else {
//We are getting the status of the container
if (config.get("debug"))
console.log("Getting status of container " + containerId);
getContainer(containerId, function(container){
res.status(200); //We found the container! This response can be trusted
if (config.get("debug")) {
console.log("Response received");
console.log(container);
}
res.send({
state: container.SynoStatus || container.State,
status: container.Status,
image: container.Image
});
}, function(status, message){
res.status(status);
if (config.get("debug"))
console.log("Failed to get status of Docker container");
if (message) {
res.send(message);
if (config.get("debug"))
console.log(message);
}
});
}
});
/**
* List all of the containers
*/
app.get('/containers', function (req, res) {
docker.listContainers({ all: true }, function (err, containers) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200);
res.send(containers);
});
});
/**
* Restart the container by the ID specified
*/
app.get('/container/:containerId/restart', function (req, res) {
var containerId = req.params.containerId;
console.log("Restart " + containerId);
getContainer(containerId, function (container) {
docker.getContainer(container.Id).restart(function (err, data) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200); //We found the container! This reponse can be trusted
res.send(data);
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
})
});
/**
* Start the container by the ID specified
*/
app.get('/container/:containerId/start', function (req, res) {
var containerId = req.params.containerId;
console.log("Start " + containerId);
getContainer(containerId, function (container) {
docker.getContainer(container.Id).start(function (err, data) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200); //We found the container! This reponse can be trusted
res.send(data);
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
})
});
/**
* Pause the container by the ID specified
*/
app.get('/container/:containerId/pause', function (req, res) {
var containerId = req.params.containerId;
console.log("Pause " + containerId);
getContainer(containerId, function (container) {
docker.getContainer(container.Id).pause(function (err, data) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200); //We found the container! This reponse can be trusted
res.send(data);
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
})
});
/**
* Unpause the container by the ID specified
*/
app.get('/container/:containerId/unpause', function (req, res) {
var containerId = req.params.containerId;
console.log("Unpause " + containerId);
getContainer(containerId, function (container) {
docker.getContainer(container.Id).unpause(function (err, data) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200); //We found the container! This reponse can be trusted
res.send(data);
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
})
});
/**
* Stats the container by the ID specified
*/
app.get('/container/:containerId/stats', function (req, res) {
var containerId = req.params.containerId;
console.log("Getting Stats for " + containerId);
var opts= new Object();
opts.stream = false
getContainer(containerId, function (container) {
docker.getContainer(container.Id).stats(opts, function (err, data) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200); //We found the container! This reponse can be trusted
res.send(data);
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
})
});
/**
* Stop the container by the ID specified
*/
app.get('/container/:containerId/stop', function (req, res) {
var containerId = req.params.containerId;
console.log("Stop " + containerId);
getContainer(containerId, function (container) {
docker.getContainer(container.Id).stop(function (err, data) {
if (err) {
res.status(500);
res.send(err);
return;
}
res.status(200); //We found the container! This reponse can be trusted
res.send(data);
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
})
});
app.post('/container/:containerId/exec', function(req, res) {
var containerId = req.params.containerId;
console.log("Exec " + containerId);
var command = req.body.command ? req.body.command : false;
if (command == "" || !command) {
res.send({
status: false,
error: "No command specified"
});
res.status(400);
return;
}
getContainer(containerId, function (container) {
if (config.get("debug"))
console.log("Attempting to execute command in container " + container.Id);
var options = {
Cmd: command.split(" "),
AttachStdout: true,
AttachStderr: true
};
if (config.get('debug'))
console.log(options);
var container = docker.getContainer(container.Id);
container.exec(options, function (err, exec) {
if (err) {
if (config.get("debug")) {
console.log("Failed to get container " + container.Id);
console.log(err);
}
res.status(500);
res.send(err);
return;
}
exec.start(function (err, stream) {
if (err) {
if (config.get("debug")) {
console.log("Failed to execute in container " + container.Id);
console.log(err);
}
res.status(500);
res.send(err);
return;
}
console.log("executed query");
const chunks = [];
stream.on("data", function (chunk) {
chunks.push(chunk.toString());
});
// Send the buffer or you can put it into a var
stream.on("end", function () {
// We remove the first 8 chars as the contain a unicode START OF HEADING followed by ENQUIRY.
res.send({
status: true,
result: chunks.join('').substr(8)
});
});
});
return;
});
}, function (status, message) {
res.status(status);
if (message) {
res.send(message);
}
});
})
//Attempt to connect to the Docker daemon
switch (config.get("docker_connection.type")) {
case "http":
var docker = new Docker({ host: config.get("docker_connection.host"), port: config.get("docker_connection.port") });
break;
case "socket":
//Check if the socket is okay
try{
let stats = fs.statSync(config.get("docker_connection.path"));
if (!stats.isSocket()) {
throw new Error('Unable to connect to Docker socket at ' + config.get("docker_connection.path") + ". Is Docker running?");
}
} catch (e) {
console.error('Unable to connect to Docker socket at ' + config.get("docker_connection.path") + ". Is Docker running?");
if (config.get("debug"))
console.log(e);
process.exit(1);
}
//Socket is okay, connect to it
docker = new Docker({ socketPath: config.get("docker_connection.path") });
break;
default:
throw new Error("Docker connection type " + config.get("docker_connection.type") + " is invalid");
break;
}
startServer(docker);
function startServer(docker)
{
var server = app.listen(config.get("http.port"), function () {
console.log("HA-Dockermon server listening on port " + server.address().port);
});
}
function getContainer(name, cb, error)
{
docker.listContainers({ limit:100, filters: { "name": [name] } }, function (err, containers) {
if (err) {
if (typeof error == "function")
return error(500, err);
return;
}
if (containers.length > 0) {
//What is the ID of this container?
//We need to only return the ID as it matches exactly
for(id in containers) {
//Does this container have names set?
if (containers[id].Names.length) {
//Yes it does, loop over all names to see if we get one
for(i in containers[id].Names) {
if (containers[id].Names[i] == "/" + name) {
//Found it by name!
return cb(containers[id]);
}
}
}
}
}
//Hmm lets try get the container by ID instead
docker.listContainers({ filters: { "id": [name] } }, function (err, containers) {
if (err) {
if (typeof error == "function")
return error(500, err);
return;
}
if (containers.length < 1) {
if (typeof error == "function")
return error(404, "container not found");
return;
}
//What is the ID of this container?
//We need to only return the ID as it matches exactly
for(id in containers) {
//Does this container have names set?
if (containers[id].Names.length) {
//Yes it does, check the first name
if (containers[id].Id == name) {
//Found it by name!
return cb(containers[id]);
}
}
}
//Could not find that container - sad face
if (typeof error == "function")
return error(404, "container not found");
return false;
});
});
}