Skip to content

Instantly share code, notes, and snippets.

@duggan
Created Mar 6, 2021
Embed
What would you like to do?
Google Apps Script to check whether a HTTP endpoint is available, send a notification to an email address, and silence after three consecutive mails. A notification is also sent when the service becomes available again.
var properties = PropertiesService.getScriptProperties();
var service = "MyService"
var url = "http://example.com";
var email = "you@gmail.com";
function parseDate(date_string) {
return new Date(Date.parse(date_string)).toISOString();
}
function startFailure() {
var failures = parseInt(properties.getProperty('failures'));
properties.setProperty('failures', failures + 1);
var failure_start = new Date();
if (failures == 1) {
properties.setProperty('failure_start', failure_start.toISOString());
}
var message = "Failed to reach endpoint (attempt " + (failures + 1) + ")";
console.log(message);
if ( failures < 3 ) {
if (failures == 2) {
message = message + " Alert will be silenced until recovery.";
}
MailApp.sendEmail(email, service + " is UNHEALTHY", message);
}
}
function endFailure() {
var failures = parseInt(properties.getProperty('failures'));
if (failures > 0) {
var failure_end = new Date();
var failure_start = properties.getProperty('failure_start');
var message = "Downtime lasted from " + parseDate(failure_start) + " to " + failure_end.toISOString();
MailApp.sendEmail(email, service + " returned to HEALTHY", message);
}
properties.setProperty('failures', 0);
properties.deleteProperty('failure_start');
}
function checkService() {
try {
var response = UrlFetchApp.fetch(url, {
muteHttpExceptions: true,
validateHttpsCertificates: false,
followRedirects: true
});
endFailure();
} catch (e) {
startFailure();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment