-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
304 lines (262 loc) · 8.92 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
// JavaScript source code
var AWS = require('aws-sdk')
, Q = require('q')
, request = require('request');
//loggly url, token and tag configuration
//user need to edit while uploading code via blueprint
var logglyConfiguration = {
url: 'http://logs-01.loggly.com/bulk',
tags: 'CloudwatchMetrics'
};
var encryptedLogglyToken = "your KMS encypted key";
var encryptedLogglyTokenBuffer = new Buffer(encryptedLogglyToken, "base64");
var kms = new AWS.KMS({
apiVersion: '2014-11-01'
});
var cloudwatch = new AWS.CloudWatch({
apiVersion: '2010-08-01'
});
//entry point
exports.handler = function (event, context) {
var finalData = [];
var parsedStatics = [];
var nowDate = new Date();
var date = nowDate.getTime();
//time upto which we want to fetch Metrics Statics
//we keep it one hour
var logEndTime = nowDate.toISOString();
//time from which we want to fetch Metrics Statics
var logStartTime = new Date(date - (05 * 60 * 1000)).toISOString();
//initiate the script here
decryptLogglyToken().then(function () {
getMetricsListFromAWSCloudwatch().then(function () {
sendRemainingStatics().then(function () {
context.done('all statics are sent to Loggly');
}, function () {
context.done();
});
}, function () {
context.done();
});
}, function () {
context.done();
});
//decrypts your Loggly Token from your KMS key
function decryptLogglyToken() {
return Q.Promise(function (resolve, reject) {
var params = {
CiphertextBlob: encryptedLogglyTokenBuffer
};
kms.decrypt(params, function (err, data) {
if (err) {
console.log(err, err.stack); // an error occurred
reject();
}
else {
// successful response
logglyConfiguration.customerToken = data.Plaintext.toString('ascii');
resolve();
}
});
});
}
//retreives all list of valid metrics from cloudwatch
function getMetricsListFromAWSCloudwatch() {
return Q.Promise(function (resolve, reject) {
var promisesResult = [];
var getMetricsList = function (nextToken) {
// Remove Coments if requierd filter
var params = {
/*
// Add filter dimensions
// Remove Coments if requierd filter
Dimensions: [{
// Required
Name:"String_Value" ,
Value:""
},
],
//Add Metric name : ["CPUUtilization","DiskReadOps","StatusCheckFailed_System"] -> String Values
MetricName:"String Value"
// more filters
*/
};
//The token returned by a previous call to indicate that there is more data available
//if nextToken returned then next token should
//present to get the Metrics from next page
if (nextToken != null) {
params.NextToken = nextToken;
}
cloudwatch.listMetrics(params, function (err, result) {
if (err) {
console.log(err, err.stack); // an error occurred
}
else {
var pMetricName, pNamespace, pName, pValue;
for (var i = 0; i < result.Metrics.length; i++) {
pNamespace = result.Metrics[i].Namespace;
pMetricName = result.Metrics[i].MetricName;
for (var j = 0; j < result.Metrics[i].Dimensions.length; j++) {
pName = result.Metrics[i].Dimensions[j].Name
pValue = result.Metrics[i].Dimensions[j].Value
}
var promise = fetchMetricStatisticsFromMetrics(pNamespace, pMetricName, pName, pValue);
promisesResult.push(promise)
}
}
if (result.NextToken) {
getMetricsList(result.NextToken);
}
else {
Q.allSettled(promisesResult)
.then(function () {
resolve();
}, function () {
reject();
});
}
});
}
getMetricsList();
});
}
//Gets statistics for the specified metric.
function fetchMetricStatisticsFromMetrics(namespace, metricName, dName, dValue) {
var MetricStatisticsPromises = [];
return Q.Promise(function (resolve, reject) {
/*The maximum number of data points returned from a single GetMetricStatistics request is 1,440,
wereas the maximum number of data points that can be queried is 50,850. If you make a request
that generates more than 1,440 data points, Amazon CloudWatch returns an error. In such a case,
you can alter the request by narrowing the specified time range or increasing the specified period.
Alternatively, you can make multiple requests across adjacent time ranges.*/
var params = {
EndTime: logEndTime, //required
MetricName: metricName, //required
Namespace: namespace, //required
Period: 60, //required
StartTime: logStartTime, //required
Statistics: [ //required
'Average', 'Minimum', 'Maximum', 'SampleCount', 'Sum'
],
Dimensions: [{
Name: dName, // required
Value: dValue //required
},
/* more items */
],
};
var Promises = [];
try {
cloudwatch.getMetricStatistics(params, function (err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
for (var a in data.Datapoints) {
var promise = parseStatics(data.Datapoints[a], data.ResponseMetadata, data.Label, dName, dValue, namespace)
Promises.push(promise);
}
Q.allSettled(Promises).then(function () {
resolve();
}, function () {
reject();
});
}
});
}
catch (e) {
console.log(e);
}
});
}
//converts the Statics to a valid JSON object with the sufficient infomation required
function parseStatics(metricsStatics, responseMetadata, metricName, dimensionName, dimensionValue, namespace) {
return Q.promise(function (resolve, reject) {
var staticdata = {
"timestamp": metricsStatics.Timestamp.toISOString(),
"sampleCount": metricsStatics.SampleCount,
"average": metricsStatics.Average,
"sum": metricsStatics.Sum,
"minimum": metricsStatics.Minimum,
"maximum": metricsStatics.Maximum,
"unit": metricsStatics.Unit,
"metricName": metricName,
"namespace": namespace
};
staticdata[firstToLowerCase(dimensionName)] = dimensionValue;
postStaticsToLoggly(staticdata).then(function () {
resolve();
}, function () {
reject();
});
});
}
//uploads the statics to Loggly
//we will hold the statics in an array until they reaches to 200
//then set the count of zero.
function postStaticsToLoggly(event) {
return Q.promise(function (resolve, reject) {
if (parsedStatics.length == 200) {
upload().then(function () {
resolve();
}, function () {
reject();
});
} else {
parsedStatics.push(event);
resolve();
}
});
}
//checks if any more statics are left
//after sending Statics in multiples of 100
function sendRemainingStatics() {
return Q.promise(function (resolve, reject) {
if (parsedStatics.length > 0) {
upload().then(function () {
resolve();
}, function () {
reject();
});
} else {
resolve();
}
});
}
function upload() {
return Q.promise(function (resolve, reject) {
//get all the Statics, stringify them and join them
//with the new line character which can be sent to Loggly
//via bulk endpoint
var finalResult = parsedStatics.map(JSON.stringify).join('\n');
//empty the main statics array immediately to hold new statics
parsedStatics.length = 0;
//creating logglyURL at runtime, so that user can change the tag or customer token in the go
//by modifying the current script
var logglyURL = logglyConfiguration.url + '/' + logglyConfiguration.customerToken + '/tag/' + logglyConfiguration.tags;
//create request options to send Statics
try {
var requestOptions = {
uri: logglyURL,
method: 'POST',
headers: {}
};
requestOptions.body = finalResult;
//now send the Statics to Loggly
request(requestOptions, function (err, response, body) {
if (err) {
console.log('Error while uploading Statics to Loggly');
reject();
} else {
resolve();
}
});
} catch (ex) {
console.log(ex.message);
reject();
}
});
}
//function to convert the first letter of the string to lowercase
function firstToLowerCase(str) {
return str.substr(0, 1).toLowerCase() + str.substr(1);
}
}