forked from poma/docker-telegram-notifier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
81 lines (68 loc) · 2.11 KB
/
app.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
const utils = require('./utils');
const Docker = require('dockerode');
const TelegramClient = require('./telegram');
const JSONStream = require('JSONStream');
const templates = require('./templates');
const { ONLY_WHITELIST } = process.env;
const docker = new Docker();
const telegram = new TelegramClient();
async function sendEvent(event) {
// console.debug(event);
const template = templates[`${event.Type}_${event.Action}`];
if (template) {
const label = event.Actor && event.Actor.Attributes && event.Actor.Attributes['telegram-notifier.monitor'];
const shouldMonitor = label === undefined ? undefined : label.toLowerCase().trim() !== 'false';
if (shouldMonitor || !ONLY_WHITELIST && shouldMonitor !== false) {
const attachment = template(event);
console.log(attachment, "\n");
await telegram.send(attachment)
}
}
}
async function sendEventStream() {
const eventStream = await docker.getEvents();
eventStream.pipe(JSONStream.parse())
.on('data', event => sendEvent(event).catch(handleError))
.on('error', handleError);
}
async function sendVersion() {
const version = await docker.version();
let hostDetails = utils.getHostDetails();
if (hostDetails.length > 0) {
hostDetails += ` with docker `;
}
const text = `Connected to ${hostDetails}${version.Version} ${version.Arch}`;
console.log(text, "\n");
await telegram.send(text);
}
async function main() {
await sendVersion();
await sendEventStream();
}
async function healthcheck() {
try {
await docker.version();
} catch (e) {
console.error(e);
console.error(`${utils.getHostDetails()}: Docker is unavailable`);
process.exit(101);
}
try {
console.log(await telegram.check());
} catch (e) {
console.error(e);
console.error(`${utils.getHostDetails()}: Telegram API is unavailable`);
process.exit(102);
}
console.log("OK");
process.exit(0);
}
function handleError(e) {
console.error(`${utils.getHostDetails()}: ${e}`);
telegram.sendError(e).catch(console.error);
}
if (process.argv.includes("healthcheck")) {
healthcheck();
} else {
main().catch(handleError);
}