API Synthetic maintenance window workaround

Following my browser workaround script, I have a new API synthetic template for you all to try.

// Script-wide timeout for wait and waitAndFind functions (in ms)
var startTime = new Date(),
  thisStep = 0,
  assert = require('assert'),
  Q = require('q'),
  ScriptTimeout = 0,
  MaintenanceMessage = "Script is running during maintenance window";

var log = function(msg) {
  if(typeof msg === "string")
  {
    var totalTimeElapsed = (new Date() - startTime);
    var elapsedSecs =  totalTimeElapsed / 1000;
    console.log('Step ' + thisStep + ': ' + elapsedSecs.toFixed(2) + 's: ' + msg);
    thisStep++;
    
    if(ScriptTimeout > 0 && totalTimeElapsed > ScriptTimeout)
    {
      throw Error('Script timed out. ' + totalTimeElapsed + 'ms is longer than script timeout threshold of ' + ScriptTimeout + 'ms.'); 
    }
  }
};

log("Initialising ...");

 // checks if this run is in within the maintenance window provided
 // @param {string} dayOfWeek - Monday, Tuesday, etc.
 // @param {string} startTime - UTC start time of window in 24hr format
 // @param {string} endTime - UTC end time of window in 24hr format
var checkInMaintenanceWindow = function(dayOfWeek, startTime, endTime)
{
  log("checkInMaintenanceWindow");
  var deferred = Q.defer();
  var daysOfWeek = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
  var now = new Date();
  var day = daysOfWeek[now.getUTCDay()];
  
  if(day != dayOfWeek)
  {
    log("Days do not match");
    deferred.resolve("Days do not match"); // not the specified day
  }
  else
  {
    log("Days match, checking times");
    startParts = startTime.split(":");
    var start = new Date(now);
    start.setUTCHours(parseInt(startParts[0]), parseInt(startParts[1]));

    endParts = endTime.split(":");
    var end = new Date(now);
    end.setUTCHours(parseInt(endParts[0]), parseInt(endParts[1]));

    // check if we are in the maintenance window
    if(now.getTime() >= start.getTime() && now.getTime() <= end.getTime())
    {
      log("In maintenance window");
      $http.get("http://www.google.co.uk"); // workaround for monitor produced no traffic error
      deferred.reject(MaintenanceMessage);
    }
    else
    {
      deferred.resolve("Times do not match");
    }
  }  
  return deferred.promise;
};

function shouldDisplayError(message)
{
  return !(typeof message != "undefined" && message !== null && message.length > 0);
}

var buildSecurityOptions = function()
{
  var deferred = Q.defer();
  log("Building security options");
  // build your security options here
  var options = {};
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var getSecurityToken = function(options){

  var deferred = Q.defer();
  log("Retrieving Security Token");
	
  $http.post(options, function(error, response, body)
  {
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 200 (OK) response code.
      assert.ok(response.statusCode == 200, 'Expected 200 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }    
  });
  return deferred.promise; //promise is returned
};

var extractSecurityToken = function(data){
  log("Extracting Security Token");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  var info = JSON.parse(data);
  log("Security token retrieved successfully");
  deferred.resolve(info.access_token);
  return deferred.promise;
};

var buildApiOptions = function(securityToken){
  var deferred = Q.defer();
  log("Building API options");
  // build your api options here
  var options = {};
  deferred.resolve(options); //fulfills the promise with options as the value
  return deferred.promise; //promise is returned
};

var makeApiCall = function(options){
  var deferred = Q.defer();
  log("Making API call");

  //Make GET request, passing in options and callback.
  $http.get(options, function(error, response, body){
    if (error)
    {
      log(error);
      deferred.reject(error); //rejects the promise with `error` as the reason
    }
    else
    {
      //Verify endpoint returns 200 (OK) response code.
      assert.ok(response.statusCode == 200, 'Expected 200 OK response, actual:' + response.statusCode);
      deferred.resolve(body); //fulfills the promise with body as the value
    }
  });
  return deferred.promise; //promise is returned
};

var validateApiCall = function(body){
  log("Validating Api Call");
  var deferred = Q.defer();
  //Parse JSON received from Insights into variable.
  var info = JSON.parse(body);
  assert.ok(shouldDisplayError(info.ErrorMessage), "Error Message: " + info.ErrorMessage);
	
  // perform any other validation here
  log("Completed successfully");
  deferred.resolve();
  return deferred.promise;
};

checkInMaintenanceWindow("Friday", "00:00", "01:30")
.then(function(){
  return buildSecurityOptions()
  .then(getSecurityToken)
  .then(extractSecurityToken)
  .then(buildApiOptions)
  .then(makeApiCall)
  .then(validateApiCall);
},
function(message){
  if(message != MaintenanceMessage)
  {
    throw new Error(MaintenanceMessage);
  }
  else
  {
    log(message);
  }
})
.done();
5 Likes

This is great @stefan_garnham! Thanks for taking the time to share this and continuing to make this forum a fantastic place to share ideas!

Interesting. Thanks for the cool idea.

I’m still very concerned with script maintenance. What if I have hundreds of monitors? One would hope I would not have to include the same code in EVERY script, right? That’s why they gave us “require()” so we could import common node.js (etc) functions, but we CAN’T do this for our own custom, common code.

Huge limitation. Imagine a world with no #include or require()!!
We would spend our days maintaining repetitive code, over and over again until our brains turned to pudding. Not cool.

1 Like

Totally agree with your post @don_bonin. It is the reason why I posted this feature request :wink: