forked from martinlindenberg/serverless-plugin-alerting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
524 lines (446 loc) · 18.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
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
'use strict';
module.exports = function(S) {
const AWS = require('aws-sdk'),
SCli = require(S.getServerlessPath('utils/cli')),
SUtils = require(S.getServerlessPath('utils')),
fs = require('fs'),
BbPromise = require('bluebird'); // Serverless uses Bluebird Promises and we recommend you do to because they provide more than your average Promise :)
class ServerlessPluginAlerting extends S.classes.Plugin {
constructor(S) {
super(S);
}
static getName() {
return 'com.serverless.' + ServerlessPluginAlerting.name;
}
registerHooks() {
S.addHook(this._addAlertsAfterDeploy.bind(this), {
action: 'functionDeploy',
event: 'post'
});
S.addHook(this._addAlertsAfterDeploy.bind(this), {
action: 'dashDeploy',
event: 'post'
});
return BbPromise.resolve();
}
/**
* adds alerts after the deployment of a function
*
* @param object evt
*
* @return promise
*/
_addAlertsAfterDeploy(evt) {
let _this = this;
return new BbPromise(function(resolve, reject) {
for(var region in evt.data.deployed) {
_this._manageAlerts(evt, region);
}
return resolve(evt);
});
}
/**
* Handles the Creation of an alert and the required topics
*
* @param object evt Event
* @param string region
*
* @return promise
*/
_manageAlerts (evt, region) {
let _this = this;
_this.stage = evt.options.stage;
_this._initAws(region);
if (S.cli.action != 'deploy' || (S.cli.context != 'function' && S.cli.context != 'dash'))
return;
// merges global and local alertsettings
var alertSettings = _this._mergeAlertSettings([
_this._getFunctionsAlertSettings(evt, region),
_this._getProjectAlertSettings(evt, region),
]);
// no settings found
if (alertSettings.length == 0) {
return;
}
var requiredTopics = _this._getRequiredTopics(alertSettings);
return _this._createTopics(requiredTopics)
.then(function(){
// topics exist now
let _this = this;
var metricFilterPromises = _this._createMetricFilters(alertSettings, _this)
var subscriptionFilterPromises = _this._createSubscriptionFilters(alertSettings, _this);
var alertPromises = _this._createAlerts(alertSettings, _this);
if (metricFilterPromises.length > 0) {
BbPromise.all(metricFilterPromises)
.then(function(){
console.log('metric filters created');
});
}
if (subscriptionFilterPromises.length > 0) {
BbPromise.all(subscriptionFilterPromises)
.then(function(){
console.log('subscription filters created');
});
}
if(alertPromises.length > 0) {
BbPromise.all(alertPromises)
.then(function(){
console.log('alerts created');
});
}
}.bind(_this))
.catch(function(e){
console.log('e', e)
SCli.log('error in creating alerts', e)
});
}
/**
* creates alerts for the function
*
* @param array functionAlertSettings List of settings for each deployed function
* @param object _this as this function returns an array, i can not use _createAlerts(a,b).bind(_this) to attach a pointer to _this
*
* @return array
*/
_createAlerts (functionAlertSettings, _this) {
var alertActions = [];
var alertNamesProcessed = [];
for (var i in functionAlertSettings) {
var alertContents = functionAlertSettings[i];
for (var j in alertContents) {
var alertContent = alertContents[j];
// only if there is a sns topic
if (!alertContent.notificationTopicStageMapping[_this.stage]) {
continue;
}
var notificationAction = _this._getNotificationActionByArn(
alertContent.Arn,
alertContent.notificationTopicStageMapping,
_this.stage
);
var functionName = _this._getFunctionNameByArn(alertContent.Arn, _this.stage);
for (var metricname in alertContent.alerts) {
var topicName = alertContent.notificationTopicStageMapping[_this.stage];
var alertConfig = _this._getAlarmConfig(functionName, metricname, alertContent.alerts[metricname], _this.stage, topicName, notificationAction);
if (alertNamesProcessed.indexOf(alertConfig.AlarmName) === -1) {
alertNamesProcessed.push(alertConfig.AlarmName);
alertActions.push(
_this.cloudWatch.putMetricAlarmAsync(alertConfig)
);
} else
console.log('skipping \''+alertConfig.AlarmName+'\', alerting.json has overriding settings.')
}
}
}
return alertActions;
}
/**
* creates metric filters for the function
*
* @param array functionAlertSettings List of settings for each deployed function
* @param object _this as this function returns an array, i can not use _createMetricFilters(a,b).bind(_this) to attach a pointer to _this
*
* @return array
*/
_createMetricFilters (functionAlertSettings, _this) {
var metricFilterActions = [];
for (var i in functionAlertSettings) {
var alertContents = functionAlertSettings[i];
for (var j in alertContents) {
var alertContent = alertContents[j];
if (!alertContent.metricFilters) {
console.log('no metric filters defined');
return [];
}
var functionName = _this._getFunctionNameByArn(alertContent.Arn, _this.stage);
var logGroupName = '/aws/lambda/' + functionName;
for (var metricfilter in alertContent.metricFilters) {
alertContent.metricFilters[metricfilter].filterName = logGroupName + '_' + metricfilter;
alertContent.metricFilters[metricfilter].logGroupName = logGroupName;
alertContent.metricFilters[metricfilter].metricTransformations.forEach(function (transformation, index) {
if(!transformation.metricNamespace) {
transformation.metricNamespace = functionName;
}
});
metricFilterActions.push(
_this.cloudWatchLogs.putMetricFilterAsync(alertContent.metricFilters[metricfilter])
);
}
}
}
return metricFilterActions;
}
/**
* creates subscription filters for the function
*
* @param array functionAlertSettings List of settings for each deployed function
* @param object _this as this function returns an array, i can not use _createsubscriptionFilters(a,b).bind(_this) to attach a pointer to _this
*
* @return array
*/
_createSubscriptionFilters (functionAlertSettings, _this) {
var subscriptionFilterActions = [];
for (var i in functionAlertSettings) {
var alertContents = functionAlertSettings[i];
for (var j in alertContents) {
var alertContent = alertContents[j];
if (!alertContent.subscriptionFilters) {
console.log('no subscription filters defined');
return [];
}
var functionName = _this._getFunctionNameByArn(alertContent.Arn, _this.stage);
var logGroupName = '/aws/lambda/' + functionName;
for (var subscriptionFilter in alertContent.subscriptionFilters) {
alertContent.subscriptionFilters[subscriptionFilter].filterName = subscriptionFilter;
alertContent.subscriptionFilters[subscriptionFilter].logGroupName = logGroupName;
subscriptionFilterActions.push(
_this.cloudWatchLogs.putSubscriptionFilterAsync(alertContent.subscriptionFilters[subscriptionFilter])
);
}
}
}
return subscriptionFilterActions;
}
/**
* creates topics if not yet done
*
* @param array topics
*
* @return BpPromise
*/
_createTopics (topics) {
var _this = this;
_this.topics = topics;
return _this.sns.listTopicsAsync()
.then(function(topicListResult){
var _this = this;
//create fast checkable topiclist['topic1'] = 'topic1'
var topicList = [];
if (topicListResult['Topics']) {
for (var i in topicListResult.Topics) {
var arnParts = topicListResult.Topics[i].TopicArn.split(':')
var topicName = arnParts[arnParts.length - 1];
topicList[topicName] = topicName;
}
}
for (var i in this.topics) {
if (!topicList[i]) {
console.log('topic ' + i + ' does not exist. it will be created now');
_this.sns.createTopicAsync({
'Name': i
})
.then(function(){
console.log('topic created');
})
.catch(function(e){
console.log('error during creation of the topic !', e)
});
} else {
console.log('topic ' + i + ' exists.');
}
}
}.bind(this));
}
/**
* initializes aws
*
* @param string region
*
* @return void
*/
_initAws (region) {
let _this = this,
credentials = S.getProvider('aws').getCredentials(_this.stage, region);
_this.cloudWatch = new AWS.CloudWatch({
region: region,
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken
});
_this.cloudWatchLogs = new AWS.CloudWatchLogs({
region: region,
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken
});
_this.sns = new AWS.SNS({
region: region,
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken
});
BbPromise.promisifyAll(_this.cloudWatch);
BbPromise.promisifyAll(_this.cloudWatchLogs);
BbPromise.promisifyAll(_this.sns);
}
/**
* finds the topics for the function
*
* @param array functionAlertSettings
*
* @return array
*/
_getRequiredTopics(functionAlertSettings) {
let _this = this;
var topics = [];
for (var i in functionAlertSettings) {
var alertContents = functionAlertSettings[i];
for (var j in alertContents) {
var alertContent = alertContents[j];
// only if there is a sns topic
if (!alertContent.notificationTopicStageMapping[_this.stage]) {
continue;
}
topics[alertContent.notificationTopicStageMapping[_this.stage]] = alertContent.notificationTopicStageMapping[_this.stage];
}
}
return topics;
}
/**
* receives a list of settings and merges them (AND-Connected)
*
* @param array settingsList
*
* @return array
*/
_mergeAlertSettings(settingsList){
var result = [];
for (var i in settingsList) {
for (var j in settingsList[i]) {
result.push(settingsList[i][j]);
}
}
return result;
}
/**
* parses the alert json file and returns the data
*
* @param object evt
* @param string region
*
* @return array
*/
_getFunctionsAlertSettings(evt, region){
let _this = this;
var settings = [];
for (var deployedIndex in evt.data.deployed[region]) {
var deployed = evt.data.deployed[region][deployedIndex],
functionName = deployed['functionName'],
alertPathFile = S.getProject().getFunction(functionName).getFilePath().replace('s-function.json', 'alerting.json');
if (!fs.existsSync(alertPathFile)) {
continue;
}
try {
var alertContents = JSON.parse(fs.readFileSync(alertPathFile));
if (!alertContents.length > 0) {
alertContents = [alertContents];
}
for (var i in alertContents) {
alertContents[i].Arn = deployed.Arn;
}
settings.push(alertContents);
} catch (e) {
console.log('alerting.json not readable');
continue;
}
}
return SUtils.populate(S.getProject(), {}, settings, evt.options.stage, region);
}
/**
* parses the global alert josn file and returns data
*
* @param object evt
* @param string region
*
* @return array
*/
_getProjectAlertSettings(evt, region){
let _this = this;
var settings = [];
var globalAlertFile = S.getProject().getRootPath('global-alerting.json');
if (!fs.existsSync(globalAlertFile)) {
return settings;
}
try {
// each deployed function receives its alert settings
for (var deployedIndex in evt.data.deployed[region]) {
var deployed = evt.data.deployed[region][deployedIndex];
var alertContents = JSON.parse(fs.readFileSync(globalAlertFile));
if (!alertContents.length > 0) {
alertContents = [alertContents];
}
for (var i in alertContents) {
alertContents[i].Arn = deployed.Arn;
}
settings.push(alertContents);
}
} catch (e) {
console.log('global-alerting.json not readable');
}
return SUtils.populate(S.getProject(), {}, settings, evt.options.stage, region);
}
/**
* @deprecated
*/
_getFunctionNameByArn(arn, stage) {
return arn.split(':function:')[1].replace(':' + stage, '');
}
/**
* set the NotificationAction by ARN
*
* @param string arn ARN of the function
* @param array map Notificationtopic mapping
* @param string stage
*
*
* @param void
*/
_getNotificationActionByArn(arn, map, stage) {
var name = arn.split(':function:')[0].replace(':lambda:', ':sns:');
return name + ':' + map[stage];
}
/**
* returns config object for the sns command
*
* @param string functionname
* @param string metric
* @param object alertConfig
* @param string stage
* @param string topicName
* @param string notificationAction
*
* @return object
*/
_getAlarmConfig(functionName, metric, alertConfig, stage, topicName, notificationAction) {
let resourceName = functionName + ":" + stage;
let metricName = metric;
if('metricName' in alertConfig) {
metricName = alertConfig.metricName;
}
let dimensions = [{ Name: "Resource", Value: resourceName },
{ Name: "FunctionName", Value: functionName }
];
if('dimensions' in alertConfig) {
dimensions = alertConfig.dimensions;
}
var config = {
AlarmName: resourceName + ' ' + metric + ' -> ' + topicName,
ActionsEnabled: alertConfig.enabled || true,
ComparisonOperator: alertConfig.comparisonOperator,
EvaluationPeriods: alertConfig.evaluationPeriod,
MetricName: metricName,
Namespace: alertConfig.alarmNamespace,
Period: alertConfig.alarmPeriod,
Statistic: alertConfig.alarmStatisticType,
Threshold: alertConfig.alarmThreshold,
AlarmDescription: alertConfig.description,
Dimensions: dimensions,
InsufficientDataActions: [notificationAction],
OKActions: [notificationAction],
AlarmActions: [notificationAction]
};
return config;
}
}
return ServerlessPluginAlerting;
};