Your data. Anywhere you go.

New Relic for iOS or Android


Download on the App Store    Android App on Google play


New Relic Insights App for iOS


Download on the App Store


Learn more

Close icon

API Synthetic maintenance window workaround

synthetics-script
developer

#1

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();

API Monitoring guidelines
$http.post requests sent syncronyously (one by one)
ReferenceError: $http is not defined
Performing HTTP requests in a Scripted Browser
Schedule synthetics script to start/stop
How to verify json/xml contains string
URL Authentication - 401 error
Wait or .then in an API Test
Multiple API calls in single synthetics
Passing a Variable Into a Callback Function
How do we create APIT Test with 2-legged OAuth?
Maintenance Windows?
Create alert or perfomacnce dashboard using curl command
WebDriver ExecuteScript and Promises
Developing for Synthetics
Synthetics API Tests
Monitor Azure Queue DeadLetter
How do you assert routes don't exist with synthetics?
Is there a way to display other load time percentile ranks like 99th PR in the monitors list?
JSON response checks
Oauth2 Synthetics API Test
Sending a soap request through scripted browser
Synthetic API Test. JSON value persistence from an HTTP POST call and used in an HTTP GET call
API Synthetic monitoring
API Synthetic monitoring
12/11/2015 Posts of the Week: JVMs, Yii2 and Synthetics!
#2

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!


#3

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.


#4

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