-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
155 lines (139 loc) · 4.7 KB
/
Copy pathindex.js
File metadata and controls
155 lines (139 loc) · 4.7 KB
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
const AWS = require('aws-sdk');
const encrypted = process.env['SLACK_TOKENS'];
let decrypted;
async function processEvent(event, context, callback) {
const endDate = new Date();
const startDate = new Date();
startDate.setHours(startDate.getHours() - 1);
const https = require('https');
const util = require('util');
const slackTokens = decrypted
const alert = event.Records[0].Sns
const message = JSON.parse(alert.Message)
const nameSpace = message.Trigger.Namespace
const metricName = message.Trigger.MetricName
const cloudwatchlogs = new AWS.CloudWatchLogs
const metricParams = {
metricName: metricName,
metricNamespace: nameSpace
};
let metricFiltersLookup
try {
metricFiltersLookup = await cloudwatchlogs.describeMetricFilters(metricParams).promise();
}
catch (err) {
console.log(err);
}
const logGroupName = metricFiltersLookup.metricFilters[0].logGroupName
const encodedFilter = encodeURIComponent(encodeURIComponent(metricFiltersLookup.metricFilters[0].filterPattern));
const searchURL = 'https://' + AWS.config.region + '.console.aws.amazon.com/cloudwatch/home?region=' + AWS.config.region + '#logEventViewer:group=' + logGroupName + ';filter=' + encodedFilter + ';start=' + startDate.toISOString() + ';end=' + endDate.toISOString()
const postData = {
"channel": "#errors",
};
const severity = "danger";
const options = {
method: 'POST',
hostname: 'hooks.slack.com',
port: 443,
path: '/services/'+slackTokens
};
postData.attachments = [
{
"color": severity,
"text": "*" + alert.Subject + "*",
"actions": [
{
"type": "button",
"text": "View Events",
"url": searchURL
}
]
}
];
const req = https.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
context.done(null);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.write(util.format("%j", postData));
req.end();
const emailList = process.env['EMAILS'].split(',');
if ( typeof emailList !== 'undefined' || emailList !== null ) {
const fromEmail = process.env['SENDER_ADDRESS']
const fromName = process.env['SENDER_NAME']
const htmlBody = `
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>New Alert generated from AWS CloudWatch Logs.</p>
<p>
<form action="` + searchURL + `">
<input type="submit" value="View Events" />
</form>
</p>
</body>
</html>
`;
const textBody = `
New Alert generated from AWS CloudWatch Logs.
Click the link to view the events in the browser:` + searchURL;
const emailParams = {
Destination: {
ToAddresses: emailList
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: htmlBody
},
Text: {
Charset: "UTF-8",
Data: textBody
}
},
Subject: {
Charset: "UTF-8",
Data: alert.Subject
}
},
Source: fromName + " <" + fromEmail + ">"
};
const sendPromise = new AWS.SES({ apiVersion: "2010-12-01" })
.sendEmail(emailParams)
.promise();
// Handle promise's fulfilled/rejected states
sendPromise
.then(data => {
console.log(data.MessageId);
context.done(null, "Success");
})
.catch(err => {
console.error(err, err.stack);
context.done(null, "Failed");
});
}
};
exports.handler = (event, context, callback) => {
if (decrypted) {
processEvent(event, context, callback);
} else {
// Decrypt code should run once and variables stored outside of the function
// handler so that these are decrypted once per container
const kms = new AWS.KMS();
kms.decrypt({ CiphertextBlob: new Buffer(encrypted, 'base64') }, (err, data) => {
if (err) {
console.log('Decrypt error:', err);
return callback(err);
}
decrypted = data.Plaintext.toString('ascii');
processEvent(event, context, callback);
});
}
};