Welcome to docs.opsview.com

Opsview REST API

Opsview has a REST API for updating the Opsview configuration using web service 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 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' }
  3. For all subsequent requests, add the following headers. Replace username and tokenstring appropriately:
    X-Opsview-Username: username
    X-Opsview-Token: tokenstring
    
  4. 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 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 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.

This was committed in trunk in February 2012.

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...") 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, 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 /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
    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": "Slave Cluster",
            "ref": "/rest/config/monitoringserver/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.

export_host_template

This is a small script, /usr/local/nagios/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
  • Downtimes - for changes to scheduled downtimes
  • Status - for querying status information
  • Runtime - for querying objects that are being monitored live
  • Acknowledgements - 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

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.

From Opsview 3.10 onwards, api_version is based on the Opsview Web version number.

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=name&one_time_token=token. 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.

If you specify a URL parameter of “asynchronous=1”, an asynchronous reload will be run. Use a GET request to poll to see if the reload has completed.

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

URL: /rest/serverinfo

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

Requires RELOADACCESS.

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: 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 show a line 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 this in /usr/local/opsview-web/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.

Navigation
Print/export
Toolbox