forked from assertible/lambda-cloudwatch-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
454 lines (402 loc) · 16.7 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
const {KmsKeyringNode, buildClient, CommitmentPolicy} = require('@aws-crypto/client-node');
const url = require('url');
const https = require('node:https');
const config = require('./config');
const kmsClient = buildClient(
CommitmentPolicy.FORBID_ENCRYPT_ALLOW_DECRYPT
)
let hookUrl;
function postMessage(message, callback) {
const body = JSON.stringify(message);
const options = url.parse(hookUrl);
options.method = 'POST';
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
};
const postReq = https.request(options, function (res) {
const chunks = [];
res.setEncoding('utf8');
res.on('data', function (chunk) {
return chunks.push(chunk);
});
res.on('end', function () {
const body = chunks.join('');
if (callback) {
callback({
body: body,
statusCode: res.statusCode,
statusMessage: res.statusMessage
});
}
});
return res;
});
postReq.write(body);
postReq.end();
}
function handleElasticBeanstalk(event, context) {
const timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime() / 1000;
const subject = event.Records[0].Sns.Subject || "AWS Elastic Beanstalk Notification";
const message = event.Records[0].Sns.Message;
const stateRed = message.indexOf(" to RED");
const stateSevere = message.indexOf(" to Severe");
const butWithErrors = message.indexOf(" but with errors");
const noPermission = message.indexOf("You do not have permission");
const failedDeploy = message.indexOf("Failed to deploy application");
const failedConfig = message.indexOf("Failed to deploy configuration");
const failedQuota = message.indexOf("Your quota allows for 0 more running instance");
const unsuccessfulCommand = message.indexOf("Unsuccessful command execution");
const stateYellow = message.indexOf(" to YELLOW");
const stateDegraded = message.indexOf(" to Degraded");
const stateInfo = message.indexOf(" to Info");
const removedInstance = message.indexOf("Removed instance ");
const addingInstance = message.indexOf("Adding instance ");
const abortedOperation = message.indexOf(" aborted operation.");
const abortedDeployment = message.indexOf("some instances may have deployed the new application version");
const isDangerAlert = (
stateRed !== -1
|| stateSevere !== -1
|| butWithErrors !== -1
|| noPermission !== -1
|| failedDeploy !== -1
|| failedConfig !== -1
|| failedQuota !== -1
|| unsuccessfulCommand !== -1
);
const isWarningAlert = (
stateYellow !== -1
|| stateDegraded !== -1
|| stateInfo !== -1
|| removedInstance !== -1
|| addingInstance !== -1
|| abortedOperation !== -1
|| abortedDeployment !== -1
);
let color;
if (isDangerAlert) {
color = "danger";
} else if (isWarningAlert) {
color = "warning"
} else {
color = "good"
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"fields": [
{"title": "Subject", "value": event.Records[0].Sns.Subject, "short": false},
{"title": "Message", "value": message, "short": false}
],
"color": color,
"ts": timestamp
}
]
};
return slackMessage
}
function handleCodeDeploy(event, context) {
const subject = "AWS CodeDeploy Notification";
const timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime() / 1000;
const snsSubject = event.Records[0].Sns.Subject;
const fields = [];
let color = "warning";
let message;
try {
message = JSON.parse(event.Records[0].Sns.Message);
if (message.status === "SUCCEEDED") {
color = "good";
} else if (message.status === "FAILED") {
color = "danger";
}
fields.push({"title": "Message", "value": snsSubject, "short": false});
fields.push({"title": "Deployment Group", "value": message.deploymentGroupName, "short": true});
fields.push({"title": "Application", "value": message.applicationName, "short": true});
fields.push({
"title": "Status Link",
"value": "https://console.aws.amazon.com/codedeploy/home?region=" + message.region + "#/deployments/" + message.deploymentId,
"short": false
});
} catch (e) {
color = "good";
message = event.Records[0].Sns.Message;
fields.push({"title": "Message", "value": snsSubject, "short": false});
fields.push({"title": "Detail", "value": message, "short": false});
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": fields,
"ts": timestamp
}
]
};
return slackMessage
}
function handleCodePipeline(event, context) {
const subject = "AWS CodePipeline Notification";
const timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime() / 1000;
const fields = [];
let message;
let header;
let color = "warning";
let changeType = "";
try {
message = JSON.parse(event.Records[0].Sns.Message);
const detailType = message['detail-type'];
if (detailType === "CodePipeline Pipeline Execution State Change") {
changeType = "";
} else if (detailType === "CodePipeline Stage Execution State Change") {
changeType = "STAGE " + message.detail.stage;
} else if (detailType === "CodePipeline Action Execution State Change") {
changeType = "ACTION";
}
if (message.detail.state === "SUCCEEDED") {
color = "good";
} else if (message.detail.state === "FAILED") {
color = "danger";
}
header = message.detail.state + ": CodePipeline " + changeType;
fields.push({"title": "Message", "value": header, "short": false});
fields.push({"title": "Pipeline", "value": message.detail.pipeline, "short": true});
fields.push({"title": "Region", "value": message.region, "short": true});
fields.push({
"title": "Status Link",
"value": "https://console.aws.amazon.com/codepipeline/home?region=" + message.region + "#/view/" + message.detail.pipeline,
"short": false
});
} catch (e) {
color = "good";
message = event.Records[0].Sns.Message;
header = message.detail.state + ": CodePipeline " + message.detail.pipeline;
fields.push({"title": "Message", "value": header, "short": false});
fields.push({"title": "Detail", "value": message, "short": false});
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": fields,
"ts": timestamp
}
]
};
return _.merge(slackMessage, baseSlackMessage);
}
function handleElasticache(event, context) {
const subject = "AWS ElastiCache Notification"
const message = JSON.parse(event.Records[0].Sns.Message);
const timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime() / 1000;
const region = event.Records[0].EventSubscriptionArn.split(":")[3];
const color = "good";
let eventname, nodename;
for (let key in message) {
eventname = key;
nodename = message[key];
break;
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": [
{"title": "Event", "value": eventname.split(":")[1], "short": true},
{"title": "Node", "value": nodename, "short": true},
{
"title": "Link to cache node",
"value": "https://console.aws.amazon.com/elasticache/home?region=" + region + "#cache-nodes:id=" + nodename + ";nodes",
"short": false
}
],
"ts": timestamp
}
]
};
return slackMessage
}
function handleCloudWatch(event, context) {
const timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime() / 1000;
const message = JSON.parse(event.Records[0].Sns.Message);
const region = event.Records[0].EventSubscriptionArn.split(":")[3];
const subject = "AWS CloudWatch Notification";
const alarmName = message.AlarmName;
const metricName = message.Trigger.MetricName;
const oldState = message.OldStateValue;
const newState = message.NewStateValue;
const alarmDescription = message.AlarmDescription;
const trigger = message.Trigger;
let color = "warning";
if (message.NewStateValue === "ALARM") {
color = "danger";
} else if (message.NewStateValue === "OK") {
color = "good";
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": [
{"title": "Alarm Name", "value": alarmName, "short": true},
{"title": "Alarm Description", "value": alarmDescription, "short": false},
{
"title": "Trigger",
"value": trigger.Statistic + " "
+ metricName + " "
+ trigger.ComparisonOperator + " "
+ trigger.Threshold + " for "
+ trigger.EvaluationPeriods + " period(s) of "
+ trigger.Period + " seconds.",
"short": false
},
{"title": "Old State", "value": oldState, "short": true},
{"title": "Current State", "value": newState, "short": true},
{
"title": "Link to Alarm",
"value": "https://console.aws.amazon.com/cloudwatch/home?region=" + region + "#alarm:alarmFilter=ANY;name=" + encodeURIComponent(alarmName),
"short": false
}
],
"ts": timestamp
}
]
};
return slackMessage
}
function handleAutoScaling(event, context) {
const subject = "AWS AutoScaling Notification"
const message = JSON.parse(event.Records[0].Sns.Message);
const timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime() / 1000;
const color = "good";
let eventname, nodename;
for (key in message) {
eventname = key;
nodename = message[key];
break;
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": [
{"title": "Message", "value": event.Records[0].Sns.Subject, "short": false},
{"title": "Description", "value": message.Description, "short": false},
{"title": "Event", "value": message.Event, "short": false},
{"title": "Cause", "value": message.Cause, "short": false}
],
"ts": timestamp
}
]
};
return slackMessage
}
function handleCatchAll(event, context) {
const record = event.Records[0]
const subject = record.Sns.Subject
const timestamp = new Date(record.Sns.Timestamp).getTime() / 1000;
const message = JSON.parse(record.Sns.Message)
let color = "warning";
if (message.NewStateValue === "ALARM") {
color = "danger";
} else if (message.NewStateValue === "OK") {
color = "good";
}
// Add all of the values from the event message to the Slack message description
let description = ""
for (key in message) {
const renderedMessage = typeof message[key] === 'object'
? JSON.stringify(message[key])
: message[key]
description = description + "\n" + key + ": " + renderedMessage
}
const slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": [
{"title": "Message", "value": record.Sns.Subject, "short": false},
{"title": "Description", "value": description, "short": false}
],
"ts": timestamp
}
]
}
return slackMessage
}
function processEvent(event, context) {
console.log("sns received:" + JSON.stringify(event, null, 2));
const eventSubscriptionArn = event.Records[0].EventSubscriptionArn;
const eventSnsSubject = event.Records[0].Sns.Subject || 'no subject';
const eventSnsMessageRaw = event.Records[0].Sns.Message;
let eventSnsMessage = null;
try {
eventSnsMessage = JSON.parse(eventSnsMessageRaw);
} catch (e) {
}
let slackMessage;
if (eventSubscriptionArn.indexOf(config.services.codepipeline.match_text) > -1 || eventSnsSubject.indexOf(config.services.codepipeline.match_text) > -1 || eventSnsMessageRaw.indexOf(config.services.codepipeline.match_text) > -1) {
console.log("processing codepipeline notification");
slackMessage = handleCodePipeline(event, context)
} else if (eventSubscriptionArn.indexOf(config.services.elasticbeanstalk.match_text) > -1 || eventSnsSubject.indexOf(config.services.elasticbeanstalk.match_text) > -1 || eventSnsMessageRaw.indexOf(config.services.elasticbeanstalk.match_text) > -1) {
console.log("processing elasticbeanstalk notification");
slackMessage = handleElasticBeanstalk(event, context)
} else if (eventSnsMessage && 'AlarmName' in eventSnsMessage && 'AlarmDescription' in eventSnsMessage) {
console.log("processing cloudwatch notification");
slackMessage = handleCloudWatch(event, context);
} else if (eventSubscriptionArn.indexOf(config.services.codedeploy.match_text) > -1 || eventSnsSubject.indexOf(config.services.codedeploy.match_text) > -1 || eventSnsMessageRaw.indexOf(config.services.codedeploy.match_text) > -1) {
console.log("processing codedeploy notification");
slackMessage = handleCodeDeploy(event, context);
} else if (eventSubscriptionArn.indexOf(config.services.elasticache.match_text) > -1 || eventSnsSubject.indexOf(config.services.elasticache.match_text) > -1 || eventSnsMessageRaw.indexOf(config.services.elasticache.match_text) > -1) {
console.log("processing elasticache notification");
slackMessage = handleElasticache(event, context);
} else if (eventSubscriptionArn.indexOf(config.services.autoscaling.match_text) > -1 || eventSnsSubject.indexOf(config.services.autoscaling.match_text) > -1 || eventSnsMessageRaw.indexOf(config.services.autoscaling.match_text) > -1) {
console.log("processing autoscaling notification");
slackMessage = handleAutoScaling(event, context);
} else {
slackMessage = handleCatchAll(event, context);
}
postMessage(slackMessage, function (response) {
if (response.statusCode < 400) {
console.info('message posted successfully');
context.succeed();
} else if (response.statusCode < 500) {
console.error("error posting message to slack API: " + response.statusCode + " - " + response.statusMessage);
// Don't retry because the error is due to a problem with the request
context.succeed();
} else {
// Let Lambda retry
context.fail("server error when processing message: " + response.statusCode + " - " + response.statusMessage);
}
});
}
exports.handler = function (event, context) {
if (hookUrl) {
processEvent(event, context);
} else if (config.unencryptedHookUrl) {
hookUrl = config.unencryptedHookUrl;
processEvent(event, context);
} else if (config.kmsEncryptedHookUrl && config.kmsEncryptedHookUrl !== '<kmsEncryptedHookUrl>') {
const encryptedBuf = new Buffer(config.kmsEncryptedHookUrl, 'base64');
const cipherText = {CiphertextBlob: encryptedBuf};
const kmsKeyring = new KmsKeyringNode();
kmsClient
.decrypt(kmsKeyring, cipherText, )
.then(({ plaintext }) => {
hookUrl = "https://" + plaintext.toString('ascii');
processEvent(event, context);
})
.catch(err => {
console.error("decrypt error: " + err);
processEvent(event, context);
});
} else {
context.fail('hook url has not been set.');
}
};