-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcloudWatchThreshold.check.js
79 lines (66 loc) · 2.44 KB
/
cloudWatchThreshold.check.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
'use strict';
const {
CloudWatchClient,
GetMetricStatisticsCommand
} = require('@aws-sdk/client-cloudwatch');
const logger = require('@dotcom-reliability-kit/logger');
const status = require('./status');
const Check = require('./check');
// Detects when the value of a metric climbs above/below a threshold value
class CloudWatchThresholdCheck extends Check {
constructor(options) {
super(options);
this.threshold = options.threshold;
this.direction = options.direction || 'above';
this.samplePeriod = parseInt(options.samplePeriod, 10) || 60 * 5;
this.cloudWatchRegion = options.cloudWatchRegion || 'eu-west-1';
this.cloudWatchMetricName = options.cloudWatchMetricName;
this.cloudWatchNamespace = options.cloudWatchNamespace;
this.cloudWatchStatistic = options.cloudWatchStatistic || 'Sum';
this.cloudWatchDimensions = options.cloudWatchDimensions || [];
this.cloudWatch = new CloudWatchClient({
region: this.cloudWatchRegion,
apiVersion: '2010-08-01'
});
this.checkOutput = 'CloudWatch threshold check has not yet run';
}
generateParams() {
// use a larger window when gathering stats, because CloudWatch
// can take its sweet time with populating new datapoints.
let timeWindowInMs = this.samplePeriod * 1.5 * 1000;
const now = new Date();
const startTime = new Date(now.getTime() - timeWindowInMs);
return {
EndTime: now,
StartTime: startTime,
MetricName: this.cloudWatchMetricName,
Namespace: this.cloudWatchNamespace,
Period: this.samplePeriod,
Statistics: [this.cloudWatchStatistic],
Dimensions: this.cloudWatchDimensions
};
}
async tick() {
const params = this.generateParams();
try {
const res = await this.cloudWatch.send(
new GetMetricStatisticsCommand(params)
);
res.Datapoints.sort((a, b) => b['Timestamp'] - a['Timestamp']);
const value = res.Datapoints[0][this.cloudWatchStatistic];
const ok =
this.direction === 'above'
? value <= this.threshold
: value >= this.threshold;
this.status = ok ? status.PASSED : status.FAILED;
this.checkOutput = ok
? `No threshold change detected in CloudWatch data. Current value: ${value}`
: `CloudWatch data ${this.direction} required threshold. Current value: ${value}`;
} catch (err) {
logger.error('Failed to get CloudWatch data', err);
this.status = status.FAILED;
this.checkOutput = `Cloudwatch threshold check failed to fetch data: ${err.message}`;
}
}
}
module.exports = CloudWatchThresholdCheck;