The purpose of this post is to familiarize Foglight stake-holders and developers with the new Foglight API.  I will go from showing something very basic in the first 10 minute video, to a more advanced coding use case in the second video.  Before we start I wanted to share some of the value that comes from leveraging the Foglight API.  I have worked with several customers to implement API use cases over the last few months.  These are 2 examples of use cases and subsequent business value:

Use Case 1 Database Backup Auditing

A Foglight customer has hundreds of SQL server databases.  The databases are labeled in their CMDB according to their function.  For example, data warehouse, transaction processing, packaged application, etc.  The databases are also labeled by their importance.  For example, Mission Critical, normal, or low importance. There may be other labels but lets just consider those 2 for explanation purposes.  The company has backup requirements depending on the matrix of labels. Mission critical transactions may need to be backed up every day where low priority data warehouse may only need to be backed up once per month.  

The customer used the Foglight API to pull the last backup time and other backup metrics for each database instance, out of the Foglight API and appended that information to the database CI in the CMDB. I'm not sure if was implemented as a batch or on-demand pull, either one would have been possible with the Foglight API.  Foglight is now integrated with their centralized database CI record and that view is now enriched to reflect database backup compliance status!  

The alternative would have been to copy all of the business logic (labels) for each database into Foglight for reporting and alerting.  That would have taken weeks or even months and would have created an ongoing maintenance challenge that would likely be untenable.  With the Foglight API the customer can do this in a matter of hours or days and doesn't have to worry about the ongoing maintenance or changes in business logic.    

Use Case 2 Basic Host Metrics to Management Host Usage View 

This is a similar use case to the one above where the default Foglight views are not ideal for some of the IT managers.  Also the IT managers are used to viewing information about their hosts in a homegrown view that they've been using for years.  Instead of forcing the managers to login to Foglight or do something different, the Foglight team just pushed data collected by Foglight into the existing interface.  

This effort saved training time and saved the burden of having to develop a custom Foglight view for the managers. The result was that they can now see the new Foglight data in their existing views.  

Foglight helped to enrich the managers host perspective with no change to their daily workflows, resulting in a low cost implementation with a high value benefit for the customer.

Demo 0 to 50 MPH

In this video I will demonstrate how to get started with the Foglight API.  Some Foglight teams are not familiar with using APIs and that's OK for this demo.  The demo will let you get a good enough understanding of the API to where you can get your hands dirty and get to a point where you can have a conversation with a developer.  Your position as a Foglight specialist should be to show the developer what data to fetch and explain the API call(s) that can be used to fetch it. Developers can typically take it from there.

Demo 50 to 100 MPH

In this second video I pick up the pace to show a Java code example.  It is useful for Foglight stake-holders to understand the level of information that the developers need to use the Foglight API in code to write an actual application.  It is also useful for the developers to see a practical example outside of the provided documentation.  The example will be more understandable for those with some development background.

 

Resources

Postman

Download: https://www.getpostman.com/

Import the Foglight Rest API Collection: https://www.getpostman.com/collections/efbaade018ffccead0b2 

 

Java Code from Example

   
1) Test your script in the Foglight Script Console

package system._administration_blackout_configuration.scripts;
svc = server.get("TopologyService");

objectIds =["3f4ecf55-882d-44a9-ac99-0ecdb4708c83"];
scheduleId="30afa315-3131-48c2-b0e8-71fea187af4e";
name="test1";
inheritable=false;
description="test for KP team";

if (scheduleId == null || name == null || objectIds.isEmpty()) {
return null;
}

blackout = svc.getObjectShell(svc.getType("FSMTopologyObjectBlackout"));
list = new ArrayList();
names = new ArrayList();
tbsvc = server.get("TopologyBlackoutService");

for (objectId in objectIds) {
bl = tbsvc.getTopologyBlackout(objectId);
String[] str = new String[1];
str[0] = scheduleId;
bl.addSchedules(str, inheritable);
list.add(bl.getTopologyObject());
names.add(bl.getTopologyObject().getName());
}

scheduleIds = new ArrayList();
scheduleIds.add(scheduleId);
blackout.set("scheduleIds", scheduleIds);
blackout.set("components", list);
blackout.set("inheritable", inheritable);

blackout.set("name", name);

if (description != null ) {
blackout.set("description", description);
}

// audit
asvc = server.AuditingService;
event = asvc.newAuditableEvent();
event.setTimeStamp(new java.sql.Timestamp(System.currentTimeMillis()));
event.setUserName(server.SecurityService.getCurrentPrincipal().username);
event.setServiceName("TopologyBlackoutService");

methodName = new StringBuilder();
blackoutType = functionHelper.invokeFunction("system:administration_blackout_configuration.37", "Object");
scheSvc = server.get("ScheduleService").getSchedule(scheduleId);
scheDesc = scheSvc.description == "One Time Schedule" ? "One-Time Blackout" : "Scheduled Blackout";
scheName = scheSvc.name;
methodName.append(blackoutType + ": ");
methodName.append(scheDesc + "=" + scheName + " (");
names.eachWithIndex{ name, index ->
if(index == 0){
methodName.append(name);
}else{
methodName.append(", " + name);
}
};
methodName.append(")");
event.setMethodName(methodName.toString());

asvc.audit(event);

return svc.mergeData(blackout);

 

 

2) To run a script through the API

                a) Remove helper functions, those are not supported

                b) Carefully format the groovy script as a string:

                     http://www.freeformatter.com/javascript-escape.html    

               

3) Java code example

                a) Jersey libraries and code walk through

 

         b) Main class     

                                package FoglightAPI;

                                import org.codehaus.jettison.json.JSONException;

                                public class Main {

                                                public static void main(String a[]) {

                                                                Login fmsLogin = new Login();

                                                                String myToken = fmsLogin.getToken("foglight", "foglight");

                                                                if(myToken != null){

                                                                                System.out.println("login successful!");

                                                                                Blackout blackOut = new Blackout();

                                                                                try {

                                                                                                blackOut.setBlackout("not_used", "setting",myToken);

                                                                                } catch (JSONException e) {

                                                                                                // TODO Auto-generated catch block

                                                                                                e.printStackTrace();

                                                                                }

                                                                }else{

                                                                                System.err.println("login failed");

                                                                }

                                                };

                                }

 

c) Login class

 

package FoglightAPI;

 

import org.codehaus.jettison.json.JSONException;

import org.codehaus.jettison.json.JSONObject;

 

import com.sun.jersey.api.client.Client;

import com.sun.jersey.api.client.ClientHandlerException;

import com.sun.jersey.api.client.ClientResponse;

import com.sun.jersey.api.client.UniformInterfaceException;

import com.sun.jersey.api.client.WebResource;

import com.sun.jersey.api.representation.Form;

 

 

public class Login {

       Client restClient = Client.create();

       String authToken = null;

 

       String getToken(String username, String password) {

 

              Form form = new Form();

              form.add("username", username);

              form.add("pwd", password);

 

              WebResource webTarget = restClient.resource("10.1.48.13:8080/.../login");

 

              ClientResponse resp = webTarget.accept("application/json").post(ClientResponse.class, form);

 

              if (resp.getStatus() != 200) {

                     System.err.println("Fail Respose Code is: " + resp.getStatus());

                    

              } else {

                     JSONObject output = null;

                     try {

                           output = (JSONObject) new JSONObject(resp.getEntity(String.class)).get("data");

                     } catch (ClientHandlerException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     } catch (UniformInterfaceException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     } catch (JSONException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     }

                     try {

                           authToken = output.getString("token");

                     } catch (JSONException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     }

              }

 

              return authToken;

              }

}                             

d) Blackout class


package FoglightAPI;

 

import java.io.IOException;

import java.nio.charset.Charset;

import java.nio.file.Files;

import java.nio.file.Paths;

import org.codehaus.jettison.json.JSONException;

import org.codehaus.jettison.json.JSONObject;

 

import com.sun.jersey.api.client.Client;

import com.sun.jersey.api.client.ClientHandlerException;

import com.sun.jersey.api.client.ClientResponse;

import com.sun.jersey.api.client.UniformInterfaceException;

import com.sun.jersey.api.client.WebResource;

 

 

public class Blackout {

 

       public int setBlackout(String objectID, String description, String token) throws JSONException {

 

              String myScript = null;

              try {

                     myScript = readFile("resc/resource/blackoutScript.groovy",Charset.defaultCharset());

              } catch (IOException e) {

                     // TODO Auto-generated catch block

                     e.printStackTrace();

              }

              System.out.println("----- FILE -----\n" + myScript);

             

              Client restClient = Client.create();

             

              WebResource webTarget = restClient.resource("10.1.48.13:8080/.../runScript");

 

              System.out.println("Token is: " + token);

             

              JSONObject scriptCall = new JSONObject("{\"script\":\"" + myScript + "\"}");

              JSONObject output = null;

 

              ClientResponse response = webTarget.accept("application/json")

                           .header("Auth-Token", token)

                           .post(ClientResponse.class, scriptCall);

             

              // check response status code

              if (response.getStatus() != 200) {

                     System.err.println("Fail Respose Code is: " + response.getStatus());

                    

              } else {

                     try {

                           output = (JSONObject) new JSONObject(response.getEntity(String.class)).get("data");

                     } catch (ClientHandlerException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     } catch (UniformInterfaceException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     } catch (JSONException e) {

                           // TODO Auto-generated catch block

                           e.printStackTrace();

                     }

              }

             

              System.out.println("Blackout Call Return: " + output);

              return 0;

      

}

       static String readFile(String path, Charset encoding)

                       throws IOException

                     {

                       byte[] encoded = Files.readAllBytes(Paths.get(path));

                       return new String(encoded, encoding);

                     }

 

}

  

Anonymous
  • Hello John, can one utilize Foglight REST API functionality to introduce alerts from 3rd party systems into Foglight?  We have several 3rd party tools and various scripting solutions that we want to send events \ alarms from over into Foglight.  The other option is the custom script agent, but when I noticed REST API was available I thought to inquire.  

    Regards

    Shelderick E Bailey

    Senior Solutions Architect Manager

    AWS CSA, PMP, ITIL V3 Intermediate, Certified ServiceNow \ BMC Administrator

    CSRA Inc.

    50 F Street NW, Washington DC, 20001 DC Office +1.202.654.8820  |

    Mobile +1.570.269.2224  |  CSRA Email:  shelderick.bailey@csra.com  |  DHS Email: shelderick.e.bailey@associates.ice.dhs.gov  |  GMAIL:  shelderickb@gmail.com

    www.csra.com  

    Follow us on Facebook, Twitter, and LinkedIn

    Think Next. Now.

Related Content