-
Notifications
You must be signed in to change notification settings - Fork 255
/
index.js
436 lines (390 loc) · 15 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
var AWS = require('aws-sdk');
var url = require('url');
var https = require('https');
var config = require('./config');
var _ = require('lodash');
var hookUrl;
var baseSlackMessage = {}
var postMessage = function(message, callback) {
var body = JSON.stringify(message);
var options = url.parse(hookUrl);
options.method = 'POST';
options.headers = {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
};
var postReq = https.request(options, function(res) {
var chunks = [];
res.setEncoding('utf8');
res.on('data', function(chunk) {
return chunks.push(chunk);
});
res.on('end', function() {
var body = chunks.join('');
if (callback) {
callback({
body: body,
statusCode: res.statusCode,
statusMessage: res.statusMessage
});
}
});
return res;
});
postReq.write(body);
postReq.end();
};
var handleElasticBeanstalk = function(event, context) {
var timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime()/1000;
var subject = event.Records[0].Sns.Subject || "AWS Elastic Beanstalk Notification";
var message = event.Records[0].Sns.Message;
var stateRed = message.indexOf(" to RED");
var stateSevere = message.indexOf(" to Severe");
var butWithErrors = message.indexOf(" but with errors");
var noPermission = message.indexOf("You do not have permission");
var failedDeploy = message.indexOf("Failed to deploy application");
var failedConfig = message.indexOf("Failed to deploy configuration");
var failedQuota = message.indexOf("Your quota allows for 0 more running instance");
var unsuccessfulCommand = message.indexOf("Unsuccessful command execution");
var stateYellow = message.indexOf(" to YELLOW");
var stateDegraded = message.indexOf(" to Degraded");
var stateInfo = message.indexOf(" to Info");
var removedInstance = message.indexOf("Removed instance ");
var addingInstance = message.indexOf("Adding instance ");
var abortedOperation = message.indexOf(" aborted operation.");
var abortedDeployment = message.indexOf("some instances may have deployed the new application version");
var color = "good";
if (stateRed != -1 || stateSevere != -1 || butWithErrors != -1 || noPermission != -1 || failedDeploy != -1 || failedConfig != -1 || failedQuota != -1 || unsuccessfulCommand != -1) {
color = "danger";
}
if (stateYellow != -1 || stateDegraded != -1 || stateInfo != -1 || removedInstance != -1 || addingInstance != -1 || abortedOperation != -1 || abortedDeployment != -1) {
color = "warning";
}
var 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 _.merge(slackMessage, baseSlackMessage);
};
var handleCodeDeploy = function(event, context) {
var subject = "AWS CodeDeploy Notification";
var timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime()/1000;
var snsSubject = event.Records[0].Sns.Subject;
var message;
var fields = [];
var color = "warning";
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 });
}
var slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": fields,
"ts": timestamp
}
]
};
return _.merge(slackMessage, baseSlackMessage);
};
var handleCodePipeline = function(event, context) {
var subject = "AWS CodePipeline Notification";
var timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime()/1000;
var snsSubject = event.Records[0].Sns.Subject;
var message;
var fields = [];
var color = "warning";
var changeType = "";
try {
message = JSON.parse(event.Records[0].Sns.Message);
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 });
}
var slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": fields,
"ts": timestamp
}
]
};
return _.merge(slackMessage, baseSlackMessage);
};
var handleElasticache = function(event, context) {
var subject = "AWS ElastiCache Notification"
var message = JSON.parse(event.Records[0].Sns.Message);
var timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime()/1000;
var region = event.Records[0].EventSubscriptionArn.split(":")[3];
var eventname, nodename;
var color = "good";
for(key in message){
eventname = key;
nodename = message[key];
break;
}
var 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 _.merge(slackMessage, baseSlackMessage);
};
var handleCloudWatch = function(event, context) {
var timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime()/1000;
var message = JSON.parse(event.Records[0].Sns.Message);
var region = event.Records[0].EventSubscriptionArn.split(":")[3];
var subject = "AWS CloudWatch Notification";
var alarmName = message.AlarmName;
var metricName = message.Trigger.MetricName;
var oldState = message.OldStateValue;
var newState = message.NewStateValue;
var alarmDescription = message.AlarmDescription;
var alarmReason = message.NewStateReason;
var trigger = message.Trigger;
var color = "warning";
if (message.NewStateValue === "ALARM") {
color = "danger";
} else if (message.NewStateValue === "OK") {
color = "good";
}
var 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 _.merge(slackMessage, baseSlackMessage);
};
var handleAutoScaling = function(event, context) {
var subject = "AWS AutoScaling Notification"
var message = JSON.parse(event.Records[0].Sns.Message);
var timestamp = (new Date(event.Records[0].Sns.Timestamp)).getTime()/1000;
var eventname, nodename;
var color = "good";
for(key in message){
eventname = key;
nodename = message[key];
break;
}
var 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 _.merge(slackMessage, baseSlackMessage);
};
var handleCatchAll = function(event, context) {
var record = event.Records[0]
var subject = record.Sns.Subject
var timestamp = new Date(record.Sns.Timestamp).getTime() / 1000;
var message = JSON.parse(record.Sns.Message)
var 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
var description = ""
for(key in message) {
var renderedMessage = typeof message[key] === 'object'
? JSON.stringify(message[key])
: message[key]
description = description + "\n" + key + ": " + renderedMessage
}
var slackMessage = {
text: "*" + subject + "*",
attachments: [
{
"color": color,
"fields": [
{ "title": "Message", "value": record.Sns.Subject, "short": false },
{ "title": "Description", "value": description, "short": false }
],
"ts": timestamp
}
]
}
return _.merge(slackMessage, baseSlackMessage);
}
var processEvent = function(event, context) {
console.log("sns received:" + JSON.stringify(event, null, 2));
var slackMessage = null;
var eventSubscriptionArn = event.Records[0].EventSubscriptionArn;
var eventSnsSubject = event.Records[0].Sns.Subject || 'no subject';
var eventSnsMessageRaw = event.Records[0].Sns.Message;
var eventSnsMessage = null;
try {
eventSnsMessage = JSON.parse(eventSnsMessageRaw);
}
catch (e) {
}
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>') {
var encryptedBuf = new Buffer(config.kmsEncryptedHookUrl, 'base64');
var cipherText = { CiphertextBlob: encryptedBuf };
var kms = new AWS.KMS();
kms.decrypt(cipherText, function(err, data) {
if (err) {
console.log("decrypt error: " + err);
processEvent(event, context);
} else {
hookUrl = "https://" + data.Plaintext.toString('ascii');
processEvent(event, context);
}
});
} else {
context.fail('hook url has not been set.');
}
};