-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLambdaPing.nodejs
84 lines (74 loc) · 2.97 KB
/
LambdaPing.nodejs
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
exports.handler = function(event, context, callback) {
var Ping_domain = (event.domain === undefined ? 'example.com' : event.domain);
var Ping_protocol = (event.protocol === undefined ? 'https' : event.protocol);
var Ping_port = (event.port === undefined ? 443 : event.port);
var Ping_path = (event.path === undefined ? '/' : event.path);
var Ping_method = (event.method === undefined ? 'GET' : event.method);
var Ping_success = 0;
var Ping_responsetime = 0;
const http = require(Ping_protocol);
var options = {
hostname: Ping_domain,
port: Ping_port,
path: Ping_path,
method: Ping_method
};
var start = new Date();
var req = http.request(options, function(res) {
Ping_responsetime = (new Date() - start);
if (res.statusCode < '400') { Ping_success = 1 } else { Ping_success = 0 }
console.log('statusCode:', res.statusCode);
console.log('Request took:', Ping_responsetime.toFixed(1), 'ms');
console.log('Request success:', Ping_success.toFixed(1));
console.log('Region:', process.env.AWS_DEFAULT_REGION);
putCloudWatch(Ping_domain,Ping_success,Ping_responsetime, callback);
});
req.setTimeout(20000);
req.end();
req.on('error', function(e) {
putCloudWatch(Ping_domain,0,'', callback);
});
};
function putCloudWatch(Domain, Success, ResponseTime, callback){
var AWS = require('aws-sdk');
AWS.config.region = process.env.AWS_DEFAULT_REGION;
var cloudwatch = new AWS.CloudWatch();
var params = {
MetricData: [
{
MetricName: 'Available', /* required */
Dimensions: [
{
Name: 'Destination', /* required */
Value: Domain /* required */
},
],
Timestamp: + Math.floor(new Date() / 1000),
Unit: 'Count',
Value: + Success.toFixed(1)
},
{
MetricName: 'Response Time', /* required */
Dimensions: [
{
Name: 'Destination', /* required */
Value: Domain + "_" + process.env.AWS_DEFAULT_REGION /* required */
},
],
Timestamp: + Math.floor(new Date() / 1000),
Unit: 'Milliseconds',
Value: + ResponseTime.toFixed(1)
}
],
Namespace: 'LambdaPing' /* required */
};
cloudwatch.putMetricData(params, function(err, data) {
if (err) {
console.log(err, err.stack);
callback("Ping Failed");
} else {
console.log(data);
callback(null, "Ping data delivered");
}
});
}