Skip to content

Instantly share code, notes, and snippets.

@khebbie
Created July 11, 2016 09:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khebbie/e0e9d46f75361b50a61ee8bb19547bc0 to your computer and use it in GitHub Desktop.
Save khebbie/e0e9d46f75361b50a61ee8bb19547bc0 to your computer and use it in GitHub Desktop.
'use strict';
var aws = require('aws-sdk');
var https = require('https');
var ses = new aws.SES();
var processingContext = {
noOfSuccesses: 0,
failures: [],
endpoints: [
{url: "https://www.test.com", statusCode: 200},
{url: "https://www.test2.com", statusCode: 200}
]
};
exports.handler = function (event, context) {
var processingContextRunning = JSON.parse(JSON.stringify(processingContext));
processingContextRunning.nodeJsContext = context;
callEndpoints(processingContextRunning);
};
function callEndpoints(processingContext) {
var endpoint = processingContext.endpoints.shift();
if (endpoint) {
https
.get(endpoint.url, processOK(endpoint, processingContext))
.on('error', processError(endpoint, processingContext));
}
}
function processOK(endpoint, processingContext) {
return function(result) {
if (result.statusCode == endpoint.statusCode) {
console.log(["Site ", endpoint.url, " seems OK"].join(""));
processingContext.noOfSuccesses++;
} else {
var msg = ["Site ", endpoint.url, " failed, statusCode=", result.statusCode, ", expected: ", endpoint.statusCode].join("");
console.log(msg);
processingContext.failures.push(msg);
}
nextCall(processingContext);
};
}
function processError(endpoint, processingContext) {
return function(err) {
var msg = [
"Site ",
endpoint.url,
" failed with error: ",
err.message]
.join("");
console.log(msg);
processingContext.failures.push(msg);
};
}
function nextCall(processingContext) {
if (processingContext.endpoints.length > 0) {
callEndpoints(processingContext);
} else {
if (processingContext.failures.length>0) {
sendEmail(processingContext);
} else {
processingContext.nodeJsContext
.done([
"Failures: ",
processingContext.noOfFailures,
", successes: ",
processingContext.noOfSuccesses
].join(""));
}
}
}
function sendEmail(processingContext) {
ses.sendEmail({
Destination: {
ToAddresses: [
"alarmemail@gmail.com"
]
},
Message: {
Subject: {
Data: "AWS Lambda site check failed",
Charset: 'UTF-8'
},
Body: {
Text: {
Data: ["Failures encountered: ", processingContext.failures].join("\n"),
Charset: 'UTF-8'
}
}
},
Source: "alarmemail@gmail.com"
}, function (err, data) {
if (err) {
console.log(err, err.stack);
processingContext.nodeJsContext.fail('Internal Error: The email could not be sent.');
} else {
console.log("Email sent")
processingContext.nodeJsContext.done('Email sent');
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment