forked from petersem/monocker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
472 lines (430 loc) · 15.9 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
import Telegram from "telegram-notify";
import Docker from "dockerode";
import { createRequire } from "module";
const pjson = createRequire(import.meta.url)("./package.json");
import PushBullet from "pushbullet";
import { IncomingWebhook } from "ms-teams-webhook";
import Pushover from 'node-pushover';
import { Webhook } from 'discord-webhook-node';
import { NtfyClient } from 'ntfy';
import { WebClient } from '@slack/web-api';
import { gotify } from 'gotify';
import Matrix from "matrix-js-sdk";
import express from 'express';
import axios from 'axios';
process.on('warning', (warning) => {
console.log(warning.stack);
});
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// app.get('/', function(req, res) {
// res.writeHead(200);
// res.end("Monocker is functional!");
// });
app.get('/status', function(req, res) {
const status = {'status': 'healthy', 'messages-sent-since-started': messageCountSinceStart }
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
res.end(JSON.stringify(status) + '\r\n');
});
// Experimental! You must add a "PORTS: - custom_port:8000" entry to your YAML for this to be availlable
app.post('/send', (req, res) => {
const hasValue = (obj, value) => Object.values(obj).includes(value);
const hasKey = (obj, key) => Object.keys(obj).includes(key);
let hasTitle = hasKey(req.body, 'title');
let hasMsg = hasKey(req.body, 'msg');
let title = req.body.title;
let msg = req.body.msg;
if(hasMsg){
// send a message
send(msg, title);
res.writeHead(200);
res.end('Success\n\r');
}
else {
// let's make out there is nothing on this route
res.writeHead(401);
res.end('Page not found\n\r');
}
});
app.listen(8000);
// main program
let docker = new Docker({socketPath: '/var/run/docker.sock'});
const NODE_ENV = process.env.NODE_ENV || "production";
const SERVER_LABEL = process.env.SERVER_LABEL || "";
const SERVER_AVATAR = process.env.SERVER_AVATAR || "";
const MESSAGE_PLATFORM = process.env.MESSAGE_PLATFORM || "";
const LABEL_ENABLE = process.env.LABEL_ENABLE || 'false';
const ONLY_OFFLINE_STATES = process.env.ONLY_OFFLINE_STATES || 'false';
const EXCLUDE_EXITED = process.env.EXCLUDE_EXITED || 'false';
const SHA = process.env.SHA || 'false';
// Default to 10 seconds if less than 10, blank or undefined.
if(process.env.PERIOD == "" || process.env.PERIOD === undefined || process.env.PERIOD < 10) {process.env.PERIOD = 10;}
const PERIOD = process.env.PERIOD;
const DISABLE_STARTUP_MSG = process.env.DISABLE_STARTUP_MSG || 'false';
let messageCountSinceStart = 0
// NTFY settings
const CUSTOM_NTFY_SERVER = process.env.CUSTOM_NTFY_SERVER || null;
const NTFY_USER = process.env.NTFY_USER || "";
const NTFY_PASS = process.env.NTFY_PASS || "";
let msgDetails = MESSAGE_PLATFORM.split("@");
let isFirstRun = true;
let monContainers = [];
let offlineStates = ["exited", "dead", "running (unhealthy)", "paused"];
let runClock;
console.log("-------------------------------------------------------");
console.log(" Monocker - MONitor dOCKER container states");
console.log(" Developed by Matt Petersen - Brisbane Australia");
console.log(" Donate: https://www.paypal.com/paypalme/thanksmp")
console.log(" ");
console.log(" Version: " + pjson.version);
console.log("-------------------------------------------------------");
console.log(" ");
console.log(`Monitoring started
- Version: ` + pjson.version + `
- Messaging platform: ` + MESSAGE_PLATFORM.split("@")[0] + `
- Polling period: ` + PERIOD + ` seconds
- Only offline state monitoring: ` + ONLY_OFFLINE_STATES + `
- Only include labelled containers: ` + LABEL_ENABLE + `
- Do not monitor 'Exited': ` + EXCLUDE_EXITED + `
- Disable Startup Messages: ` + DISABLE_STARTUP_MSG.toLowerCase() + `
- Display SHA ID: ` + SHA);
console.log()
async function sendTelegram(message) {
try {
let notify = new Telegram({ token: msgDetails[1], chatId: msgDetails[2] });
await notify.send(message, { timeout: 10000 }, { parse_mode: "html" });
} catch (e) {
console.error("** Telegram Exception: " + e.message);
}
}
async function sendPushbullet(title, message) {
try {
var pusher = new PushBullet(msgDetails[1]);
pusher.note(msgDetails[2], title, message, function (err, res) {
if (err) return console.log(err.message);
console.error(res.message);
});
} catch (e) {
console.error("** Pushbullet Exception: " + e.message);
}
}
async function sendGotify(title, message) {
try {
await gotify({
server: msgDetails[1],
app: msgDetails[2],
title: title,
message: message,
priority: 5
});
} catch (e) {
console.error("** Gotify Exception: " + e.message);
}
}
async function sendPushover(title, message) {
try {
var push = new Pushover({
token: msgDetails[2],
user: msgDetails[1],
});
push.send(title, message, function (err, res) {
if (err) return console.log(err);
console.error(res);
});
} catch (e) {
console.error("** Pushover Exception: " + e.message);
}
}
async function sendDiscord(title, message) {
try {
const hook = new Webhook(msgDetails[1]);
hook.setUsername(title);
hook.setAvatar(SERVER_AVATAR);
try {
await hook.send(message);
} catch (e) {
console.error(e.message);
}
} catch (e) {
console.error("** Discord Exception: " + e.message);
}
}
async function sendTeams(title, message) {
console.log(msgDetails[1] + msgDetails[2])
console.log(message)
try {
const webhook = new IncomingWebhook(msgDetails[1] + "@" + msgDetails[2]);
await webhook.send({
"@type": "MessageCard",
"@context": "https://schema.org/extensions",
summary: "Monitoring Report",
themeColor: "0078D7",
title: title,
sections: [
{
activityTitle: "Docker Monitoring",
activitySubtitle: new Date().toLocaleString("de-DE"),
activityImage:
"https://connectorsdemo.azurewebsites.net/images/MSC12_Oscar_002.jpg",
text: message,
},
],
});
} catch (e) {
console.error("** Teams Exception: " + e.message);
}
}
async function sendMatrix(title, message) {
try {
const matrixClient = Matrix.createClient({
baseUrl: msgDetails[1],
accessToken: msgDetails[3],
userId: "@" + msgDetails[2]
});
//# tag0 server1 user2 access-token3 room-id4
var content = new Object();
content.body = message;
content.msgtype = "m.text";
matrixClient.sendEvent(msgDetails[4], "m.room.message", content, "", (err, res) => {
console.log(err);
});
} catch (e) {
console.error("** Matrix Exception: " + e.message);
}
}
async function sendNtfyAuth(title, message) {
const ntfy = new NtfyClient();
try {
await ntfy.publish({
authorization: {
password: NTFY_PASS,
username: NTFY_USER
},
server: CUSTOM_NTFY_SERVER,
topic: msgDetails[1],
title: title,
message: message,
iconURL: SERVER_AVATAR
});
} catch (e) {
console.error("** NTFY Auth Exception: " + e.message);
}
}
async function sendNtfy(title, message) {
const ntfy = new NtfyClient();
try {
await ntfy.publish({
server: CUSTOM_NTFY_SERVER,
topic: msgDetails[1],
title: title,
message: message,
iconURL: SERVER_AVATAR,
});
} catch (e) {
console.error("** NTFY Exception: " + e.message);
}
}
async function sendSlack(title, message) {
const web = new WebClient(msgDetails[1]);
try {
await web.chat.postMessage({
channel: msgDetails[2],
username: title,
text: message,
icon_url: SERVER_AVATAR,
});
} catch (e) {
console.error(e.message);
}
}
async function sendApprise(aTitle, message) {
let url = msgDetails[1] + '/notify/' + msgDetails[2] + '/?tags=' + msgDetails[3];
await axios.post(url, {
title: aTitle,
body: message,
}, {
headers: {
'Content-Type': 'multipart/form-data'
}
}
)
.then(function (response) {
// console.log(response);
})
.catch(function (error) {
console.log("** Apprise execption" + error);
});
}
async function send(message, extTitle) {
let title = "MONOCKER";
if(extTitle != null){
title = extTitle
if (SERVER_LABEL.length !== 0) title += " (" + SERVER_LABEL + ")";
}
else{
if (SERVER_LABEL.length !== 0) title += " (" + SERVER_LABEL + ")";
}
messageCountSinceStart+=1
switch (msgDetails[0].toLowerCase()) {
case "telegram":
sendTelegram(`<b>` + title + `</b>` + message);
break;
case "pushbullet":
sendPushbullet(title, message);
break;
case "pushover":
sendPushover(title, message);
break;
case "discord":
sendDiscord(title, message);
break;
case "teams":
sendTeams(title, message);
break;
case "ntfy":
if (NTFY_PASS.length == 0) sendNtfy(title, message);
else sendNtfyAuth(title, message);
break;
case "slack":
sendSlack(title, message);
break;
case "gotify":
sendGotify(title, message);
break;
case "matrix":
sendMatrix(title, message);
break;
case "apprise":
sendApprise(title, message);
break;
case "default":
// do nothing
break;
}
}
async function list() {
let opts;
let messages = "";
if(LABEL_ENABLE == 'true') {
opts = {
filters: '{"label": ["monocker.enable=true"]}',
};
} else {
opts = { all: true };
}
//let now = new Date();
//console.log(now.toLocaleString() + " - Container scan");
docker.listContainers(opts, function(err, containers) {
// check for changes in status (first run is populating data only)
let newConArray = [];
if (containers.length > 0) {
containers.forEach(c => {
// if label_enable is false then exclude any specifically false labelled containers
if (LABEL_ENABLE == 'false' && JSON.stringify(c.Labels).includes('"monocker.enable":"false"')) {
if (isFirstRun == true) {
console.log(' - Excluding: ' + c.Names[0].replace("/", ""));
//send('Excluding: ' + c.Names[0].replace("/",""));
messages += 'Excluding: ' + c.Names[0].replace("/", "") + "\r\n";
}
}
else {
// If label_enable is true, list the specifically included containers
if (LABEL_ENABLE == 'true' && JSON.stringify(c.Labels).includes('"monocker.enable":"true"')) {
if (isFirstRun == true) {
console.log(' - Monitoring: ' + c.Names[0].replace("/", ""));
//send('Monitoring: ' + c.Names[0].replace("/",""));
messages += 'Monitoring: ' + c.Names[0].replace("/", "") + "\r\n";
}
}
// determine if covered by healthcheck
let hcStatus = "";
if (c.Status.includes("(healthy)")) hcStatus = "(healthy)"
if (c.Status.includes("(unhealthy)")) hcStatus = "(unhealthy)"
if (monContainers.includes(c.Id + "," + c.State + "," + c.Names[0] + "," + hcStatus) == false && monContainers.length !== 0) {
// exclude exited status if set
if (EXCLUDE_EXITED == 'true' && c.State.toLocaleLowerCase() == 'exited') {
// ignore
}
else {
// if only offline is set, then only show state changes that are offline
var output = c.Names[0].replace("/", "") + ": " + c.State + " " + hcStatus;
if (SHA.toLowerCase() == 'true') {
output += " " + c.ImageID
}
if (ONLY_OFFLINE_STATES == 'true') {
if (offlineStates.includes(c.State) || offlineStates.includes(c.State + " " + hcStatus)) {
console.log(" - " + output);
//send(output);
messages += output + "\r\n";
}
}
else {
console.log(" - " + output);
//send(output);
messages += output + "\r\n";
}
}
}
// create new container array
newConArray.push(c.Id + "," + c.State + "," + c.Names[0] + "," + hcStatus);
}
}
);
}
if(isFirstRun==true){
console.log(" - Currently monitoring " + newConArray.length + " (running) containers");
if(DISABLE_STARTUP_MSG.toLowerCase()!='true'){
//send("Currently monitoring " + newConArray.length + " (running) containers");
messages ="Monitoring started" + `
- Version: ` + pjson.version + `
- Messaging platform: ` + MESSAGE_PLATFORM.split("@")[0] +`
- Polling period: ` + PERIOD + ` seconds` +`
- Only offline state monitoring: ` + ONLY_OFFLINE_STATES +`
- Only include labelled containers: ` + LABEL_ENABLE +`
- Do not monitor 'Exited': ` + EXCLUDE_EXITED +`
- Disable Startup Messages: ` + DISABLE_STARTUP_MSG +`
- Display SHA ID: ` + SHA +`
`;
messages += "Currently monitoring " + newConArray.length + " (running) containers" + "\r\n";
}
isFirstRun=false;
}
// check if any containers have been deleted between scans
if(monContainers.length !== 0 ){
monContainers.forEach(c => {
let delArray = newConArray.filter(nc => nc.includes(c.split(",")[0]));
// if no match in history array and latest scan, then is deleted
if(delArray.length==0 && EXCLUDE_EXITED !== 'true'){
var output = c.split(",")[2].replace("/","") + ": exited"
if(SHA.toLowerCase()=='true'){
output += " " + c.ImageID
}
console.log(" - " + output);
//send(output)
messages += output + "\r\n";
}
});
}
// do final send of any messages generated
//send(messages.length);
if(messages.length != 0){
send(messages);
}
// let now = new Date();
// send('tick: ' + now.toLocaleString());
// assign new array to be current array state
monContainers = newConArray;
}, Promise.resolve(0));
}
async function run() {
// stop timer to ensure no race conditions
clearInterval(runClock);
// run check
await list();
// restart timer
runClock = setInterval(run, PERIOD * 1000);
}
// start processing
run();