in nodejs/app.js [35:118]
exports.handler = function (input, context, callback) {
// API metrics array.
let apiMetrics = {};
// decode input from base64
const zippedInput = new Buffer(input.awslogs.data, 'base64');
// decompress the input
zlib.gunzip(zippedInput, function (err, buffer) {
if (err) { callback(err); }
// Parse JSON from input.
const awslogsData = JSON.parse(buffer.toString('utf8'));
if (awslogsData.messageType === 'CONTROL_MESSAGE') {
callback(null, "Successfully posted control message!");
}
// Populate metrics params array from log events.
console.log(awslogsData.logEvents.length + " events captured.");
awslogsData.logEvents.forEach(function (logEvent, index, logEventsArr) {
const event = JSON.parse(logEvent.message);
const hash = [event.eventTime, event.eventName, event.awsRegion, event.eventSource];
// Filling any undefined values to prevent errors on "PutMetricData" call.
for (index in hash) {
if (!hash[index]) { hash[index] = '-' }
}
if (apiMetrics[hash]) {
apiMetrics[hash].Value++;
} else {
apiMetrics[hash] = {
Timestamp: hash[0],
MetricName: hash[1],
Dimensions: [{
Name: 'awsRegion',
Value: hash[2]
}, {
Name: 'eventSource',
Value: hash[3]
}],
Value: 1
};
}
});
let apiMetricParams = [];
let promiseList = [];
// Submit every 20 metric (BATCH size)
for (const hash in apiMetrics) {
apiMetricParams.push(apiMetrics[hash]);
if (apiMetricParams.length == BATCH) {
promiseList.push(postToCloudWatch(apiMetricParams));
apiMetricParams = [];
}
}
// Submit final set of metric
if (apiMetricParams.length > 0) promiseList.push(postToCloudWatch(apiMetricParams));
// Ensure all data posted before callback
Promise.all(promiseList).then(function (val) {
console.log("Successfully posted " + val + " events!");
callback(null, "Successfully posted " + val + " events!");
}).catch(function (err) {
console.log('A promise failed to resolve', err);
callback(err);
});
});
};