Welcome to docs.opsview.com

Opsview REST API

Opsview has a REST API for updating the Opsview configuration using webservice calls on the master server. This uses the same underlying models and procedure as the web interface.

You should use the API to update the configuration data in Opsview as object updates are made within transactions (so a failure will rollback other related changes) and there is a lot of validation to ensure that the data is correct.

This is an official Opsview API. See our policy on APIs

Connection

Connection to the REST API is via HTTP or HTTPS, based on how you have configured the Opsview web server. We recommend using HTTPS to encrypt the traffic between the client and the Opsview web server.

The API is hosted under /rest. If you want to use a specific domain for the API, such as api.opsview.example.com, this could be achieved by configuring Apache to proxy a different site through to Opsview Web.

Authentication

The Opsview API authentication requires an authentication token. This is more secure than sending a password on every request because, after the initial login, all authentication is handled via a token. The token has an expiry time of 1 hour on it but every successful request will extend the expiry time.

You need to login to Opsview to received the authentication token. You then need to pass the authentication token for each request.

The flow is this:

  • POST to /rest/login with a username and password. This can be with request parameters or as the request body in a data format (eg, if content-type is set to application/json and body is set to {“username”:“admin”,”password”:“initial”}, then Opsview will use those parameters for login)
  • The response body will include the token value. This is, by default, returned as a perl structure but, by changing the accept header, a different format can be returned (eg JSON or YAML). The token is 40 hexadecimal characters. For example, for JSON, you will get:
{'token' => 'bdd6ad8e242a993107f13260a7007e38384ce4aa'}
  • For all subsequent requests, add the following headers. Replace username and tokenstring appropriately:
X-Opsview-Username: username
X-Opsview-Token: tokenstring
  • If there are any errors, an appropriate status code will be set and the body will contain the appropriate data type with
{ message => "error string }

The authorisation token is not implemented as a cookie, to reduce the possibility of a CSRF attack.

Data exchange

You can exchange data between the webservice and your script by using either JSON, serialized perl objects or XML.

Use Content-Type headers to change the input and output data. Currently tested for:

  • application/json (JSON)
  • text/x-data-dumper (perl format)
  • text/xml (XML format. More details on this page)

You should always set a Content-Type header and the Accept header should be set to the same value. Alternatively, for GET requests only, it is possible to force a content type using a URL parameter, for example: content-type=application/json.

Output As Strings

With JSON output, all values are returned as strings (from Opsview 3.11.0 onwards). Be aware that in Javascript, if you need to add two strings together numerically, you will need to force a conversion to integers, otherwise a + is considered to be string concatention. Use the following: (value1-0)+(value2-0).

Date Time Values As Epoch Seconds

From Opsview 3.13.1 onwards, all date/time values are returned as epoch seconds (as a string), which by definition is always in the UTC timezone.

It is possible to format the date/time value based on the timezone of the Opsview server by using the URL parameter format_datetime=1. This will return a string of the format YYYY-MM-DD HH:MM:SS.

Request

Requests consist of 5 parts:

  • a URL
  • URL parameters
  • a verb (one of PUT, POST, GET, DELETE)
  • headers, to change behaviour of the input and output data
  • data, if appropriate

Response

Responses consist of 2 parts:

  • a status code
  • data, if appropriate

Always Returning a Status 200

Opsview's REST API is implemented with pure REST principles, so the status code of the response reflects the error (eg, 401 for authentication denied). However, sometimes you always want a 200 response back, for instance, if you are using JSONP.

If you set a URL parameter of alwaysReturn200=1, then the status will always be 200 and there will always be REST data, which will be added into the keyword rest:

{"rest":NORMALRESTDATA,"status":"ACTUALSTATUS"}

If there is no data, then rest will be set to null.

This was committed in trunk in February 2012.

Errors

If there was an error, an appropriate status code will be set. Data will be sent with the format in the form of:

{ 
  message => "Text explaining the error",
  detail => "Text with further detail. This may not exist",
}

Note: The content returned may be in a different format than the one requested. For instance, invalid data structures (400 bad request) could return content-type text.

Common errors

400: Bad Request

This can mean that the input parameters can not be parsed. There should be more information in the content.

If the contents shows:

Content-Type application/json had a problem with your request.
***ERROR***
malformed JSON string, neither array, object, number, string or atom, at character offset 180 (before "],\n      "all_servi...") at /usr/local/nagios/perl/lib/Catalyst/Action/Deserialize/JSON.pm line 26, <$fh> line 21.

Then this means there is some invalid JSON data. JSON input is set to “relaxed”, so additional commas at end of lists are valid.

401: Unauthorised

This means you have not authenticated to the REST API.

404: Not found

You will get this error if you try to access a URL that does not exist.

Examples

opsview_rest

You can use /usr/local/nagios/bin/opsview_rest to communicate with the REST API. For example:

opsview_rest --username=admin --password=initial GET config/host/1

This will return back the complete serialisation of the host. Add –data-format=json to change the data format to json. Add –pretty to get nicely formatted output.

You can get the output to edit and put back again:

opsview_rest --username=admin --password=initial --data-format=json --pretty GET config/host/1 > host.json
vi host.json
opsview_rest --username=admin --password=initial --content-file=host.json --data-format=json --pretty PUT config/host/1

export_host_template

This is a small script in /usr/local/nagios/utils/export_host_template to export a specific host template information to JSON format, including related service checks and their related service groups. You can then take the export file and import using import_json.

For example:

utils/export_host_template --username=admin --password=initial "Network - Base" > /tmp/json
utils/datatidy /tmp/json
vi /tmp/json # Edit the file to change the name of the host template to NEW Network - Base
bin/import_json --username=admin --password=initial /tmp/json

This will create the service group if it doesn't exist. It will also update or create service checks that have the requested name. Then it will update or create the host template with the appropriate data.

Note: The importing is based on the name of objects, so if an object already exists with the same name, then it will be updated with the data.

Interface

The REST API is separated into different sections:

Other common endpoints are listed below.

API Version Information

URL: /rest

  • GET - gets version information
  • POST,PUT,DELETE - unimplemented

Authentication not required.

This returns back information about the API. For example, this would respond with:

{
 api_version => "3.0100005360",
 api_min_version => "2.000",
 easyxdm_version => "2.4.15.118",
}

The api_version and api_min_version are floating point numbers.

From Opsview 3.10 onwards, the api_version is based on the Opsview Web version number, in a floating point format.

Clients should check that the api_min_version is less than or equal to the version that the client was written for. The api_min_version will be incremented if backwards compatibility has been broken.

The easyxdm_version information is used for interfacing to EasyXDM's cross domain communication. Load /restxdmxhr.html?version=VERSION to initiate the EasyXDM interface.

Opsview Information

URL: /rest/info. This requires authentication

  • GET - gets version information
  • POST,PUT,DELETE - unimplemented

This returns back information about Opsview. For example, this would respond with:

{
 opsview_version => "3.9.0",
 opsview_build => "3.9.0.3434",
 opsview_edition => "community",
 opsview_name => "Opsview",
 server_timezone => "UTC",
 server_timezone_offset => "0",
 uuid => "5B40A354-90C4-11DE-8C65-487C69EFFEC7",
}

opsview_name is based on the top level in the host group hierarchy.

The opsview_edition is a string value, which could be either community, enterprise, core or commercial.

Note: server_timezone is available from 3.13.1.

server_timezone_offset is the number of seconds that this server's timezone is, relative to UTC. This could be a negative value. This is based on the current time, so you could get a different offset if you are currently in daylights saving time. This is a simple calculation to work out differences between browser time and server time, taking into account the timezone differences. This was committed into trunk on 2012-08-07.

Logging In to the API

URL: /rest/login

  • GET - unimplemented
  • POST - get session token. Pass in username and password
  • PUT - unimplemented
  • DELETE - if session token is valid, deletes from session list, effectively a logout

If a token cannot be generated, a 503 HTTP status code will be returned, with the text: Error creating session token after 5 attempts.

You can pass the parameter include_one_time_token=1 and an extra field will be returned in the response with a one time token for logging into the web user interface. You can then login to http://opsview.example.com/login?login_username=name&one_time_token=token. This token expires after 10 minutes and requires it comes from the same IP address as the RESTAPI request. Once logged in, the token is removed from the system - access through the browser then works via the authentication cookie as normal.

Example response:

{
 "token":"7cd5652f7bfde4220211d063c166b263160a7d52",
 "one_time_token":"e3fab615c06d158b0795cef36ce56408ce7ea6c1"
}

You can pass the parameter include_user_data=1 and an extra field will be returned in the response of user_data. This will contain the data from the /rest/user call.

Logging In to the API Via AuthTkt

This is available from Opsview 3.13.0.

URL: /rest/login_tkt

  • POST - get session token. Pass in username
  • GET,PUT,DELETE - unimplemented

Required parameter:

  • username

This acts like /rest/login, but authenticates a user based on their auth_tkt cookie. This allows a web browser which has already been authenticated to connect to the REST API. The username is still required to be passed in as a secondary check so that knowing the cookie is not sufficient to gain access to the API.

User Information

This was committed in trunk on 2012-03-02.

URL: /rest/user

  • GET - returns user information for the currently authenticated user
  • POST,PUT,DELETE - unimplemented

This returns information about the user. Example response:

{
  "name":"admin",
  "role":"Administrator",
  "fullname":"Admin user",
  "realm":"local",
  "language":"",
  "access_list": { 
    "ACTIONALL":1,
    "ADMINACCESS":1,
    ...
    "VIEWALL":1,
  },
}

Initiating an Opsview Reload

This is available from Opsview 3.9.1.

URL: /rest/reload

  • GET - gets status of reload
  • POST - initiates a synchronous reload. Returns 200 if reload completed. Will return 400 with error messages if reload fails. Will return 409 if a reload already in progress
  • PUT - unimplemented
  • DELETE - unimplemented

Returned data:

  • server_status - this is the state of the server
    • 0 - server running, with no warnings
    • 1 - server reloading
    • 2 - server not running
    • 3 - configuration error or critical error
    • 4 - warnings exist
  • configuration_status - this is the state of the configuration
    • uptodate - all configuration changes have been applied
    • pending - at least one configuration change requires a reload
  • average_duration - number of seconds a reload normally takes, rounded up to nearest 10 seconds
  • lastupdated - epoch time for last configuration update
  • auditlog_entries - number of audit log entries since last backup. This could be undef
  • messages - array of messages

If a reload is already in progress then the status code will be set to 409 with returned data of:

  • server_status - set to 1
  • messages - set to [ “Reload already running” ]

Server information

This is available from Opsview 3.11.0.

Requires RELOADACCESS.

URL: /rest/serverinfo

  • GET - gets server information
  • POST, PUT, DELETE - unimplemented

Example returned data:

{
 reload: {
  auditlog_entries:null,
  average_duration:"10",
  configuration_status:"pending",
  lastupdated:"1294852845",
  messages:[],
  server_status:"2",
 },
 num_hosts:"22",
 num_monitoringservers:"3",
 num_nodes:"4",
 monitoringservers:[
  {
   name:"Master Monitoring Server",
   nodes:[ 
    {
      'status':'2',
      'name':'opsview",
      'ip':'opsviewdev46',
      'latency':null,
      'max_execution_time':'4',            
      'avg_execution_time':'3',
      'num_active_service_results_hour':'85',
      'num_passive_service_results_hour':'509'
    } 
   ],
   activated:1
  },
  {
   name:"ClusterA",
   nodes:[ 
    {
      'status':'0',
      'name':'opslave',
      'ip':'opslave',
      'latency':'0.158',
      'max_execution_time':'4.3',
      'avg_execution_time':'3.1',
      'num_active_service_results_hour':'85',
      'num_passive_service_results_hour':'509'
    } 
   ],
   activated:1
  },
  {
   name:"Cluster",
   nodes:[
    {
      'status':'2',
      'name':'opslaveclusterA',
      'ip':'opslaveclusterAip', 
      'latency':null,
      'max_execution_time':'4.3',
      'avg_execution_time':'3.1',
      'num_active_service_results_hour':'85',
      'num_passive_service_results_hour':'509'
    },
    {
      'status':'3',
      'name':'opslaveclusterB',
      'ip':'opslaveclusterBip', 
      'latency':null,
      'max_execution_time':'4.3',
      'avg_execution_time':'3.1',
      'num_active_service_results_hour':'85',
      'num_passive_service_results_hour':'509'
    },
    {
      'status':'3',
      'name':'opslaveclusterC',
      'ip':'opslaveclusterCip', 
      'latency':null,
      'max_execution_time':'4.3',
      'avg_execution_time':'3.1',
      'num_active_service_results_hour':null,
      'num_passive_service_results_hour':null
    },
   ],
   activated:1
  }
 ]
}

The server and slave status values are based on the Nagios plugins status codes.

The configuration_status parameter can take one of the following values:

  • pending - there is at least one change in the Opsview configuration database that requires a reload to make live
  • uptodate - no changes are pending

Note: The master's status value is based on reload→{server_status} value after conversion to a Nagios® Core status. For each slave node, the status is based on the latest status from the master server's Slave-node: check. If a status is not found, a status value of 3 (unknown) is returned.

Note: For each monitoring server's nodes, the latency is the based on the current result of the average active service check latency as returned by the Nagios Stats service check. If a value is not available, a null value will be returned.

The reload information is the same as /rest/reload.

Note: The activated attribute is available from Opsview 3.13.0.

Note: The max_execution_time and avg_execution_time are available from Opsview 3.13.1.

Logging

From Opsview 3.11.2, all REST failures are logged to /var/log/opsview/opsview-web.log.

This will present output like:

REST response (ERROR=403): GET /rest/config/monitoringserver?cols=-monitors Data:{ message => "Access denied" }

If you want to log all REST requests and responses, uncomment the following in /usr/local/opsview-web/etc/Log4perl.conf:

log4perl.logger.Opsview.Web.ControllerBase.REST=DEBUG

This can take up to 30 seconds to start logging. Note that logging may increase the response times of Opsview Web.

Navigation
Print/export
Toolbox