Hey! These docs are for version 6.3, which is no longer officially supported. Click here for the latest version, 6.7!

Introduction and overview of the Opsview Monitor Rest API

Opsview REST API

Opsview has a REST API for updating the Opsview configuration using web service calls on the primary 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.

There is an official REST API Policy.

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 the /rest URL. 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 log in to Opsview to receive the authentication token. You then need to pass the authentication token for each request.

The flow is:

  1. 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).
  2. 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"
}
  1. For all subsequent requests, add the following headers. Replace the username and tokenstring appropriately:
X-Opsview-Username: username
X-Opsview-Token: tokenstring
  1. 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"
}

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

Data exchange

You can exchange data between the web service 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 XML Serialisation.)

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. 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 concatenation. Use the following: ”(value1-0)+(value2-0)”.

Date and time values as epoch seconds

All date and time values are returned as epoch seconds (as a string), which by definition is always UTC.

It is possible to format the date/time value based on the time zone 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 five 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 necessary

If you cannot use a verb, it is possible to use POST and then tunnel the required verb through using a POST parameter (x-tunneled-method).

Response

Responses consist of two parts:

  • A status code
  • Data, if necessary

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.

Errors

If there was an error, a corresponding 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 cannot be parsed. There should be more information in the content.

If the contents shows something like:

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..."),
 <$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, ie. not logged in.

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 /opt/opsview/coreutils/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
vim host.json
opsview_rest --username=admin --password=initial --content-file=host.json --data-format=json --pretty PUT config/host/1
  • To show all performance statistics for the “unix swap” metric:
opsview_rest --username=admin --password=initial --pretty GET '/rest/status/performancemetric/?servicename=Unix Swap'
  • To show all performance statistics for the host, “opsview”:
opsview_rest --username=admin --password=initial --pretty GET /rest/status/performancemetric/?hostname=opsview
  • To show the “load average” metric from host, “opsview”:
opsview_rest --username=admin --password=initial --pretty GET '/rest/status/performancemetric?order=metricname&order=hostname&metricname=load1&hostname=opsview'
  • To add a host, you need to create a JSON file with the information — you can perform a GET on an existing host to see the template. Eg.,
{
    "hostgroup": {
        "name": "Production"
    },
    "hosttemplates": [
        {
            "name": "OS - Linux Advanced"
        }
    ],
    "icon": {
        "name": "LOGO - Opsview",
        "path": "/images/logos/opsview_small.png"
    },
    "ip": "newhost.fqdn",
    "monitored_by": {
        "name": "Collector Cluster",
        "ref": "/rest/config/monitoringcluster/3"
    },
    "name": "newhost",
    "other_addresses": "192.168.12.1"
}
Then upload the data via the API to create the host:
opsview_rest --user=admin --password=initial --pretty --data-format=json --content-file=/path/to/newhost.json PUT config/host
  • To delete a host via its ID:
opsview_rest --username=admin --password=initial --pretty DELETE config/host/<ID>
  • To perform a reload of Opsview:
opsview_rest --username=admin --password=initial --pretty POST reload
  • opsview_rest can also make use of an authentication token. To create the token file the first login must use a password:
opsview_rest -u admin -p initial -t /path/to/opsview_restapi_token GET info
Thereafter, the password does not need to be supplied:
opsview_rest -u admin -t /path/to/opsview_restapi_token GET info
Upon every use, the token is refreshed and will expire after 60 minutes.

Unix tools

You can use the unix tools curl and wget to query Opsview via the REST API. To login to the REST API using curl:

curl -H 'Content-Type: application/json' -X 'application/json' -X POST -d '{"username":"admin","password":"initial"}' http://localhost/rest/login > logindata

To parse the response, we recommend using jq, a lightweight tool to retrieve specific parts of a JSON file. To extract the token, use:

token=`jq -r .token logindata`

You can then use $token:

curl -H 'Content-Type: text/json' -H 'text/json' -H 'X-Opsview-Username: admin' -H "X-Opsview-Token: $token" -X GET 'http://localhost/rest/event?rows=2' > eventdata

(Note text/json is also valid for requesting JSON response)

To list out the first record in the response:

jq '.list[0]' eventdata

Another REST API usage, for example, to set downtime, is:

curl -H 'Content-Type: application/json'-H application/json' -H 'X-Opsview-Username: admin'-H admin' -H "X-Opsview-Token: $token"-X $token" -X POST -d '{"starttime":"2016-05-26 17:00:00","endtime":"2016-05-26 17:15:00","comment":"Test downtime"}'"http://localhost/rest/downtime?hst.hostgroupid=1"| jq .list

This will set downtime at the specified times for all hosts that are in hostgroup id 1. Note, we have used jq directly in a pipe to list the changed items.

If you are using wget instead of curl, the parameters are slightly different:

wget -q -O logindata --header="Content-Type: application/json"--method=POST --body-data='{"username":"admin","password":"initial"}' http://localhost/rest/login

To post an acknowledgement, the following example can be tailored:

curl -k -H 'Accept: application/json' -H 'Accept: application/json' -H "Content-type: application/json" -H "X-Opsview-Username: admin" -H "X-Opsview-token: $token" -X POST -d '{"comment":"test","notify":"0","sticky":"0"}' 'https://localhost/rest/acknowledge?hostname=webdev&servicename=CPU%20statistics'

export_host_template

This is a small script, /opt/opsview/coreutils/utils/export_host_template, which will export a specific host template in JSON format, including related service checks and their service groups. You can then take the exported file and import using import_json. For example:

utils/export_host_template --username=admin --password=initial "Network - Base" > /tmp/json
utils/datatidy /tmp/json
vim /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 already exist. It will also update or create service checks that have the given name. Then, it will update or create the host template with the given 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:

  • Configuration - for changes to Opsview configuration data
  • Downtime - for changes to scheduled downtimes
  • Status - for querying status information
  • Runtime - for querying objects that are being monitored live
  • Acknowledge - for acknowledgements
  • Rechecks - for re-checking a host or service
  • Graph - for graph data
  • Event - for event data
  • Notes - for static note information
  • Query Host - for querying a host for SNMP information
  • Detail - for getting detail about a specific host/servicecheck
  • Test Service Check - for testing how servicechecks respond
  • Notification Method - for getting sent notification information

Other common endpoints are listed below.

API version information

URL: /rest

Authentication not required.

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

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",
}

api_version and api_min_version are floating point numbers.

Clients should check that api_min_version is less than or equal to the version that the client was written for. 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

Requires authentication.

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

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

{
    opsview_version        => "4.5.0",
    opsview_build          => "4.5.0.16122",
    opsview_edition        => "commercial",
    opsview_name           => "Opsview",
    server_timezone        => "UTC",
    server_timezone_offset => 0,
    uuid                   => "5B40A354-90C4-11DE-8C65-487C69EFFEC7",
    hosts_limit            => "1000",
}

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

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

server_timezone_offset is the number of seconds that this server's time zone is, relative to UTC. This could be a negative value. This is based on the current time, so you will get a different offset if you are currently in daylight saving time. This is a simple calculation to work out differences between browser time and server time, taking into account the time zone differences.

hosts_limit is the maximum number of hosts that you can add to Opsview based on your Opsview subscription. If the value is an empty string, then this means there is no limit on the number of hosts. This field will only exist if the current user can see all the hosts in the system (otherwise this user must have a subset of CONFIGUREHOSTS and thus cannot have a complete list of all hosts).

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”.

If you can pass the parameter, “include_one_time_token=1”, an extra field will be returned in the response with a one time token for logging into the web user interface. You can then log in to http://opsview.example.com/login?login_username=n... This token expires after 10 minutes and requires it come from the same IP address as the REST API 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:

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

If you can pass the parameter, “include_user_data=1”, a “user_data” field will be returned in the response. This will contain the data from the /rest/user call.

Logging in to the API via AuthTkt

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.

Logout

URL: /rest/logout

  • POST - deletes the session
  • GET,PUT,DELETE - unimplemented

User information

URL: /rest/user

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

This returns information about the user. Example response:

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

Initiating an Opsview reload

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

Requires RELOADACCESS.

Parameters:

  • asynchronous - if set to 1, an asynchronous reload will be run. Use a GET request to poll to see if the reload has completed. Default 0
  • changelog - if a POST request and changelog is enabled, you must set the text to save otherwise an error will occur

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, where each message is a hash (or dictionary) of strings

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” ]

Example request/response:

$ opsview_rest --username=admin --password=initial --pretty GET reload
{
   "auditlog_entries" : "0",
   "average_duration" : "30",
   "configuration_status" : "uptodate",
   "lastupdated" : "1519680052",
   "messages" : [
      {
         "detail" : "Missing required variable EMAIL for contact admin for notification method Email - ignoring this notification",
         "monitoringserver" : "Master Monitoring Server",
         "severity" : "warning"
      }
   ],
   "server_status" : "4"
}

Logging

All REST failures are logged to syslog.

This will show a line like:

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

If you want to log all REST requests and responses, uncomment this in /opt/opsview/webapp/etc/Log4perl.conf:

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

It can take up to 30 seconds after the file is saved, to start logging. Note that logging may increase the response times of Opsview Web.