forked from assertible/lambda-cloudwatch-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
332 lines (302 loc) · 11.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
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
var AWS = require('aws-sdk');
var url = require('url');
var https = require('https');
var config = require('./config');
var _ = require('lodash');
var hookUrl;
var baseSlackMessage = {
channel: config.slackChannel,
username: config.slackUsername,
icon_emoji: config.icon_emoji,
attachments: [
{
"footer": config.orgName,
"footer_icon": config.orgIcon
}
]
}
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 = "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(baseSlackMessage, slackMessage);
};
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(baseSlackMessage, slackMessage);
};
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 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=" + config.region + "#cache-nodes:id=" + nodename + ";nodes",
"short": false
}
],
"ts": timestamp
}
]
};
return _.merge(baseSlackMessage, slackMessage);
};
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 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": alarmReason, "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=" + config.region + "#alarm:alarmFilter=ANY;name=" + alarmName,
"short": false
}
],
"ts": timestamp
}
]
};
return _.merge(baseSlackMessage, slackMessage);
};
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(baseSlackMessage, slackMessage);
};
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 eventSnsMessage = event.Records[0].Sns.Message;
if(eventSubscriptionArn.indexOf(config.services.elasticbeanstalk.match_text) > -1 || eventSnsSubject.indexOf(config.services.elasticbeanstalk.match_text) > -1 || eventSnsMessage.indexOf(config.services.elasticbeanstalk.match_text) > -1){
console.log("processing elasticbeanstalk notification");
slackMessage = handleElasticBeanstalk(event,context)
}
else if(eventSubscriptionArn.indexOf(config.services.cloudwatch.match_text) > -1 || eventSnsSubject.indexOf(config.services.cloudwatch.match_text) > -1 || eventSnsMessage.indexOf(config.services.cloudwatch.match_text) > -1){
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 || eventSnsMessage.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 || eventSnsMessage.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 || eventSnsMessage.indexOf(config.services.autoscaling.match_text) > -1){
console.log("processing autoscaling notification");
slackMessage = handleAutoScaling(event, context);
}
else{
context.fail("no matching processor for event");
}
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.');
}
};