-
Notifications
You must be signed in to change notification settings - Fork 73
/
index.js
208 lines (172 loc) · 6.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
'use strict';
// Dependency
const pm2 = require('pm2');
const pmx = require('pmx');
const MessageQueue = require('./message-queue');
/**
* Get the configuration from PM2
*
* @type {Object}
* @property {boolean} exception
*/
const moduleConfig = pmx.initModule();
/**
* New PM2 is storing log messages with date in format "YYYY-MM-DD hh:mm:ss +-zz:zz"
* Parses this date from begin of message
*
* @param {string} logMessage
* @returns {{description:string|null, timestamp:number|null}}
*/
function parseIncommingLog(logMessage) {
let description = null;
let timestamp = null;
if (typeof logMessage === "string") {
// Parse date on begin (if exists)
const dateRegex = /([0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{1,2}:[0-9]{2}:[0-9]{2}(\.[0-9]{3})? [+\-]?[0-9]{1,2}:[0-9]{2}(\.[0-9]{3})?)[:\-\s]+/;
const parsedDescription = dateRegex.exec(logMessage);
// Note: The `parsedDescription[0]` is datetime with separator(s) on the end.
// The `parsedDescription[1]` is datetime only (without separators).
// The `parsedDescription[2]` are ".microseconds"
if (parsedDescription && parsedDescription.length >= 2) {
// Use timestamp from message
timestamp = Math.floor(Date.parse(parsedDescription[1]) / 1000);
// Use message without date
description = logMessage.replace(parsedDescription[0], "");
} else {
// Use whole original message
description = logMessage;
}
}
return {
description: description,
timestamp: timestamp
}
}
const slackUrlRouter = {
/**
* Keys are slackUrls, values are instances of MessageQueue
*
* @typedef {Object.<string, MessageQueue>}
*/
messageQueues: {},
/**
* Add the message to appropriate message queue (each Slack URL has own independent message enqueing).
*
* @param {Message} message
*/
addMessage: function(message) {
const processName = message.name;
const slackUrl = moduleConfig['slack_url-' + processName] || moduleConfig['slack_url'];
if (!slackUrl) {
return;
// No Slack URL defined for this process and no global Slack URL exists.
}
if (!this.messageQueues[slackUrl]) {
// Init new messageQueue to different Slack URL.
// Resolve configuration parameters.
const configProperties = ['username', 'servername', 'buffer', 'slack_url', 'buffer_seconds', 'buffer_max_seconds', 'queue_max'];
const config = {};
configProperties.map((configPropertyName) => {
// Use process based custom configuration values if exist, else use the global configuration values.
config[configPropertyName] = moduleConfig[configPropertyName + '-' + processName] || moduleConfig[configPropertyName];
});
this.messageQueues[slackUrl] = new MessageQueue(config);
}
this.messageQueues[slackUrl].addMessageToQueue(message);
}
};
/**
* Get pm2 app display name.
* If the app is running in cluster mode, id will append [pm_id] as the suffix.
*
* @param {object} process
* @returns {string} name
*/
function parseProcessName(process) {
return process.name + (process.exec_mode === 'cluster_mode' && process.instances > 1 ? `[${process.pm_id}]` : '');
}
// ----- APP INITIALIZATION -----
// Start listening on the PM2 BUS
pm2.launchBus(function(err, bus) {
// Listen for process logs
if (moduleConfig.log) {
bus.on('log:out', function(data) {
if (data.process.name === 'pm2-slack') { return; } // Ignore messages of own module.
const parsedLog = parseIncommingLog(data.data);
slackUrlRouter.addMessage({
name: parseProcessName(data.process),
event: 'log',
description: parsedLog.description,
timestamp: parsedLog.timestamp,
});
});
}
// Listen for process errors
if (moduleConfig.error) {
bus.on('log:err', function(data) {
if (data.process.name === 'pm2-slack') { return; } // Ignore messages of own module.
const parsedLog = parseIncommingLog(data.data);
slackUrlRouter.addMessage({
name: parseProcessName(data.process),
event: 'error',
description: parsedLog.description,
timestamp: parsedLog.timestamp,
});
});
}
// Listen for PM2 kill
if (moduleConfig.kill) {
bus.on('pm2:kill', function(data) {
slackUrlRouter.addMessage({
name: 'PM2',
event: 'kill',
description: data.msg,
timestamp: Math.floor(Date.now() / 1000),
});
});
}
// Listen for process exceptions
if (moduleConfig.exception) {
bus.on('process:exception', function(data) {
if (data.process.name === 'pm2-slack') { return; } // Ignore messages of own module.
// If it is instance of Error, use it. If type is unknown, stringify it.
const description = (data.data && data.data.message) ? (data.data.code || '') + data.data.message : JSON.stringify(data.data);
slackUrlRouter.addMessage({
name: parseProcessName(data.process),
event: 'exception',
description: description,
timestamp: Math.floor(Date.now() / 1000),
});
});
}
// Listen for PM2 events
bus.on('process:event', function(data) {
if (!moduleConfig[data.event]) { return; } // This event type is disabled by configuration.
if (data.process.name === 'pm2-slack') { return; } // Ignore messages of own module.
let description = null;
switch (data.event) {
case 'start':
case 'stop':
case 'restart':
description = null;
break;
case 'restart overlimit':
description = 'Process has been stopped. Check and fix the issue.';
break;
}
slackUrlRouter.addMessage({
name: parseProcessName(data.process),
event: data.event,
description: description,
timestamp: Math.floor(Date.now() / 1000),
});
});
});
/**
* @typedef {Object} Message
*
* @property {string} name - Process name
* @property {string} event - `start`|`stop`|`restart`|`error`|`exception`|`restart overlimit`| ...
* @property {string} description
* @property {number} timestamp - Linux timestamp format
*/