Alertra API: Use C# To Automate Maintenance

Introduction

How long does your maintenance window last? In this tutorial you will learn how to programmatically control Alertra maintenance windows without having to access the Alertra web user interface. This will allow you fine grained control over how long the actual maintenance window lasts so that there are fewer gaps in the coverage of your devices. This tutorial will use C# to demonstrate the technique.

Concept

To access your device's maintenance schedule via the Alertra API we will perform the following steps:

  1. Request an API key from support.
  2. Get a list of devices.
  3. Use the device ID to act on that device.

You only need to get an API key once. Send us an email from your primary Alertra account and we'll send you a key. Since the website doesn't force device names to be unique within your account, you need the device list to determine what the unique device identifier is for the one you want to act upon. The Alertra API is implemented as a REST service which uses HTTP URLs, command types and data exchange mechanisms. The C# source code presented here requires the third-party packages Newtonsoft Json and RestSharp. Both packages are available from the NuGet service. It would be possible, but quite painful, to interact with REST services without those packages.

Steps

Source Code The source code implements a class to wrap the Alertra API. The class has 3 public methods to start maintenance, stop maintenance, and get a list of devices respectively. The remainder of the code implements a command line interface for the wrapper. The tutorial explains the basic C# code to interface with the Alertra API, while the source code provides an implementation for you as an example. The wrapper class is not meant to be made a part of a production environment, but merely to show how to interface with the API.

Step 1

First we need to get the list of devices. Using the class wrapper you would do this:

using Alertra;
...
AlertraAPI api = new AlertraAPI("YOUR ACCOUNT KEY");
dynamic r = api.GetDevices()
if (r != null)
{
    // do stuff with the devices
}

r is a dynamic object that contains the json returned by the request converted into a list of objects. So you can access the individual devices like this:

foreach(dynamic device in devices)
    Console.WriteLine( "{0}\t{1}", device.ShortName, device.device_id);

Behind the scenes, the wrapper is doing something like this when you call GetDevices():

using Newtonsoft.Json;
using RestSharp;
...
var client = new RestClient(URL);
var request = new RestRequest("devices", Method.GET);
request.AddHeader("Alertra-API-Key", apikey);
RestResponse resp = (RestResponse)client.Execute(request);
dynamic r = JsonConvert.DeserializeObject(resp.Content);

A little more goes on than that inside to support the optional parameters to the GetDevices() method. But the RestSharp library is handling the details of calling the REST service and the Newtonsoft library converts the json to C# objects that are easy to access in a natural manner.

Step 2

Once we have a device ID, we can use it to put a device into maintenance. Using the wrapper class it works like this:

using Alertra;
using RestSharp;
...
AlertraAPI api = new AlertraAPI("YOUR ACCOUNT KEY");
string duration = "01:00";
RestResponse resp = api.StartMaintenance(deviceID,duration);

where duration is the length of time the device should be put into maintenance for. In this case the device was put into maintenance for 1 hour. The wrapper class is making this call to the API:

using RestSharp;
...
var client = new RestClient(URL);
var request = new RestRequest( "devices/" + device_id + "/start-maintenance", Method.PUT);
request.AddHeader("Alertra-API-Key", apikey);
request.AddParameter("Duration", duration);

RestResponse resp = (RestResponse)client.Execute(request);

If the call succeeded, resp.StatusCode will be equal to System.Net.HttpStatusCode.OK, anything else and the call failed.

Step 3

To bring the device out of maintenance using the wrapper class we do this:

using Alertra;
using RestSharp;
...
AlertraAPI api = new AlertraAPI("YOUR ACCOUNT KEY");
RestRespoonse resp = api.stopMaintenance(deviceID)

This will cause Alertra to cancel the maintenance and resume checking the device. The wrapper class is doing this on our behalf:

using RestSharp;
...
var client = new RestClient(URL);
var request = new RestRequest("devices/" + device_id + "/stop-maintenance", Method.PUT);
request.AddHeader("Alertra-API-Key", apikey);
RestResponse resp = (RestResponse)client.Execute(request);

If the call succeeded, resp.StatusCode will be equal to System.Net.HttpStatusCode.OK, anything else and the call failed.

Summary

Using the Alertra API you can easily start and stop maintenance on any of your devices. Doing this as part of your automated maintenance routine allows you to insure that Alertra won't be checking your devices during the maintenance and will resume checking them as soon as the maintenance is over.

Source Code

Listing 1. AlertraAPI.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using RestSharp;

namespace Alertra
{
    public class AlertraAPI
    {
        private static string URL = "https://api.alertra.com/v1.1";
        private string apikey = null;

        public AlertraAPI(string apikey)
        {
            this.apikey = apikey;
        }

        public RestResponse StartMaintenance(string device_id, string duration) 
        {
            var client = new RestClient(URL);
            var request = new RestRequest( "devices/" + device_id + "/start-maintenance", Method.PUT);
            request.AddHeader("Alertra-API-Key", apikey);
            request.AddParameter("Duration", duration);

            RestResponse resp = (RestResponse)client.Execute(request);
            return resp;
        }

        public RestResponse StopMaintenance(string device_id)
        {
            var client = new RestClient(URL);
            var request = new RestRequest("devices/" + device_id + "/stop-maintenance", Method.PUT);
            request.AddHeader("Alertra-API-Key", apikey);

            RestResponse resp = (RestResponse)client.Execute(request);
            return resp;
        }

        public dynamic GetDevices(string filter="All",int offset=0,int limit=25)
        {
            var client = new RestClient(URL);
            var request = new RestRequest("devices", Method.GET);
            request.AddHeader("Alertra-API-Key", apikey);
            request.AddParameter("Filter", filter);
            request.AddParameter("Offset", offset);
            request.AddParameter("Limit", limit);

            RestResponse resp = (RestResponse)client.Execute(request);

            dynamic r = JsonConvert.DeserializeObject(resp.Content);

            return r;
        }
    }
}

Listing 2. Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Alertra;
using RestSharp;

namespace Test
{
    class Program
    {

        static int Main(string[] args)
        {
            AlertraAPI api = new AlertraAPI(YOUR_ALERTRA_API_KEY);
            int ReturnCode = 0;
            RestResponse resp = null;

            switch (args[0])
            {
                case "getdevices":
                    dynamic devices = api.GetDevices();
                    foreach (dynamic device in devices) {
                        Console.WriteLine( "{0}\t{1}", device.ShortName, device.device_id);
                    }
                    break;

                case "start-maintenance":
                    if (args.Length != 3)
                    {
                        Console.WriteLine("usage: start-maintenance device_id length");
                        ReturnCode = 1;
                    } else
                        resp = api.StartMaintenance(args[1],args[2]);
                    break;

                case "stop-maintenance":
                    if (args.Length != 2)
                    {
                        Console.WriteLine("usage: stop-maintenance device_id ");
                        ReturnCode = 1;
                    } else
                        resp = api.StopMaintenance(args[1]);
                    break;

                default:
                    break;
            }

            if (resp != null)
                if (resp.StatusCode != System.Net.HttpStatusCode.OK)
                    ReturnCode = 1;

            Console.ReadLine();
            return ReturnCode;
        }
    }
}