This repository has been archived by the owner on May 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
executable file
·246 lines (220 loc) · 8.33 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
'use strict';
module.exports = {};
module.exports.getMetrics = getMetrics;
module.exports.prepareQueries = prepareQueries;
module.exports.outputMetrics = outputMetrics;
module.exports.elbMetrics = elbMetrics;
module.exports.prepareResults = prepareResults;
module.exports.preFlightCheck = preFlightCheck;
var queue = require('d3-queue').queue;
var AWS = module.exports.AWS = require('aws-sdk');
/**
* Creates parameters for each cloudwatch query given the input from the user.
* @param {Object} following input from the user - startTime, endTime, region, elbname
* @param {callback}
*/
function elbMetrics(startTime, endTime, region, elbname, callback) {
AWS.config.update({region: region});
var diffInMinutes;
var awsRegions = ['us-east-1', 'us-west-2', 'ap-southeast-1', 'ap-southeast-2', 'ap-northeast-1', 'eu-central-1', 'eu-west-1', 'us-east-2'];
if (!(awsRegions.indexOf(region) >= 0)) {
return callback(new Error('provided region name not an AWS region'));
}
if (typeof elbname != 'string') {
return callback(new Error('provided ELB name should be a string'));
}
if ((startTime - endTime) > 0) {
return callback(new Error('EndTime should be greater than startTime'));
}
diffInMinutes = Math.round((endTime - startTime) / 60000);
if (diffInMinutes > 60) {
return callback(new Error('start and end time should not be more than 60 minutes apart'));
}
preFlightCheck(elbname, function (err, name) {
var elb = 0;
if (err) return callback(err);
if (name.indexOf('app/') === -1) { elb = 1; }
var parameters = {
startTime: startTime,
endTime: endTime,
region: region,
elbname: name
};
var queries = prepareQueries(parameters, elb);
outputMetrics(queries, region, function (err, data) {
if (err) return callback(err);
var requestPercentages = prepareResults(startTime, endTime, data);
return callback(null, requestPercentages);
});
});
}
function preFlightCheck(elbname, callback) {
var q = queue(2);
q.defer(getELBName, elbname);
q.defer(getALBName, elbname);
q.awaitAll(function (err, data) {
if (err) return callback(err);
data = data.filter(d => { return d; });
return callback(null, data[0]);
});
}
function getALBName(elbname, callback) {
var elbv2 = new AWS.ELBv2();
var parameter = {Names: [elbname]};
elbv2.describeLoadBalancers(parameter, function (err, data) {
if (err) {
if (err.code === 'LoadBalancerNotFound') return callback();
else return callback(err);
} else {
var arn = data.LoadBalancers[0].LoadBalancerArn;
var albName = arn.match(/app.*/);
return callback(null, albName[0]);
}
});
}
function getELBName(elbname, callback) {
var elb = new AWS.ELB();
var parameter = {LoadBalancerNames: [elbname]};
elb.describeLoadBalancers(parameter, function (err, data) {
if (err) {
if (err.code === 'LoadBalancerNotFound') return callback();
else return callback(err);
}
return callback(null, data.LoadBalancerDescriptions[0].LoadBalancerName);
});
}
/**
* Creates parameters for each cloudwatch query given the input from the user.
* @param {Object} commmand line input formatted into an object
* @returns {Array} array of desired metric parameters
*/
function prepareQueries(obj, elb) {
var desiredMetricsParameters = [];
var coeff = 1000 * 60 * 1;
var roundedEndTime = new Date(Math.ceil(obj.endTime / coeff) * coeff).getTime();
var roundedStartTime = new Date(Math.floor(obj.startTime / coeff) * coeff).getTime();
if (elb) {
var desiredELBMetrics = {
'HTTPCode_Backend_2XX': 'Sum',
'HTTPCode_Backend_3XX': 'Sum',
'HTTPCode_Backend_4XX': 'Sum',
'HTTPCode_Backend_5XX': 'Sum',
'RequestCount': 'Sum',
'Latency': 'Average'
};
for (var i in desiredELBMetrics) {
var params = {
EndTime: new Date(roundedEndTime).toISOString(),
MetricName: i,
Namespace: 'AWS/ELB',
Period: 60,
StartTime: new Date(roundedStartTime).toISOString(),
Statistics: [desiredELBMetrics[i].toString()],
Dimensions: [
{
Name: 'LoadBalancerName',
Value: obj.elbname
}
]
};
desiredMetricsParameters.push({parameter: params, region: obj.region});
}
} else {
var desiredALBMetrics = {
'HTTPCode_Target_2XX_Count': 'Sum',
'HTTPCode_Target_3XX_Count': 'Sum',
'HTTPCode_Target_4XX_Count': 'Sum',
'HTTPCode_Target_5XX_Count': 'Sum',
'RequestCount': 'Sum',
'TargetResponseTime': 'Average'
};
for (var j in desiredALBMetrics) {
var parameters = {
EndTime: new Date(roundedEndTime).toISOString(),
MetricName: j,
Namespace: 'AWS/ApplicationELB',
Period: 60,
StartTime: new Date(roundedStartTime).toISOString(),
Statistics: [desiredALBMetrics[j].toString()],
Dimensions: [
{
Name: 'LoadBalancer',
Value: obj.elbname
}
]
};
desiredMetricsParameters.push({parameter: parameters, region: obj.region});
}
}
return desiredMetricsParameters;
}
/**
* Queues requests for each parameter and returns a formatted version of the result
*
* @param {Array} parameters generated by prepareQueries
* @param {String} region where the ELB is present
* @param {callback}
* @returns {Array} formatted results received from cloudwatch getMetricStatistics
*/
function outputMetrics(desiredMetricsDimensions, region, callback) {
var q = queue(6);
var allMetrics = [];
desiredMetricsDimensions.forEach(function (i) {
q.defer(getMetrics, i.parameter, i.region);
});
q.awaitAll(function (err, data) {
if (err) return callback(err);
data.forEach(function (i) {
allMetrics.push({Label: i.Label, Datapoints: i.Datapoints});
});
return callback(null, allMetrics);
});
}
/** Makes requests to the cloudwatch api and gets Sum/Average for
* HTTPCode_Backend_2XX, HTTPCode_Backend_3XX, HTTPCode_Backend_4XX, HTTPCode_Backend_5XX, RequestCount, Latency
*
* @param {Object} parameter Object for getMetricStatistics
* @param {String} region where the ELB is present
* @param {callback}
* @returns {Object} Datapoints and Labels for the given MetricName in the form of an Object
*/
function getMetrics(params, region, callback) {
var cloudwatch = new AWS.CloudWatch();
cloudwatch.getMetricStatistics(params, callback);
}
function prepareResults(startTime, endTime, data) {
var diff = startTime - endTime;
var period = Math.abs(Math.floor(diff / 1000));
var total = [];
var sumLatency = 0;
for (var i = 0; i < data.length - 1; i++) {
total[i] = totalRequests(data[i]);
}
/* calculate percentage of 2xx, 3xx, 4xx, 5xx */
var requestPerSecond = Math.round((total[4] / period) * 100) / 100;
var percent2xx = Math.round(((total[0] / total[4]) * 100) * 100) / 100;
var percent3xx = Math.round(((total[1] / total[4]) * 100) * 100) / 100;
var percent4xx = Math.round(((total[2] / total[4]) * 100) * 100) / 100;
var percent5xx = Math.round(((total[3] / total[4]) * 100) * 100) / 100;
/* average latency */
data[5].Datapoints.forEach(function (i) {
sumLatency += i.Average;
});
var avgLatency = Math.round((sumLatency / data[5].Datapoints.length) * 100) / 100;
return {
'period': period + 's',
'requestPerSecond': requestPerSecond + '/s',
'percent2xx': percent2xx + ' %',
'percent3xx': percent3xx + ' %',
'percent4xx': percent4xx + ' %',
'percent5xx': percent5xx + ' %',
'avgLatency': avgLatency + ' s'
};
}
function totalRequests(metric) {
var sum = 0;
metric.Datapoints.forEach(function (i) {
sum += i.Sum;
});
return sum;
}