Raritan PX2/PX3 JSON-RPC API

Python JSON-RPC Client Binding

## Pre-Requirements

### Linux

Standard Python 2 or Python 3 installations already contain all necessary packages.

### Windows

- download and install the latest Python 2 or Python 3 from https://www.python.org/downloads/
- the installation will associated the file extension *.py with python, so you can start python files directly from the command line or the file manager

## Note on SSL Certificate Verification

All Raritan devices enforce use of HTTPS when accessing the JSON-RPC service. By default, programs written with this client binding try to verify the authenticity of the server when connecting. This requires a valid SSL certificate to be installed on the device. When trying to connect to a device without a valid SSL certificate the client program will terminate with an error message.

It is possible to disable the SSL certificate verification by adding a "disable_certificate_verification" option to the arguments of the rpc.Agent instance:

Code:

agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan", disable_certificate_verification = True)

## Timeout for IDL methods

Per default, there is no time limit for the IDL method calls configured and so the function calls might not return if the target device is not available.

If necessary, a timeout in seconds can be provided by adding a "timeout" option to the arguments of the rpc.Agent instance.

Code:

agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan", timeout = 5)

## Examples

### Getting device information:

Code:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan")
pdu = pdumodel.Pdu("/model/pdu/0", agent)
metadata = pdu.getMetaData()
print(metadata)

Output produced if there is no error:

pdumodel.Pdu.MetaData:
* nameplate = pdumodel.Nameplate:
* manufacturer = Raritan
* model = PX2-2630U-A1
* partNumber =
* serialNumber = PKE0954001
* rating = pdumodel.Nameplate.Rating:
* voltage = 360-415V
* current = 24A
* frequency = 50/60Hz
* power = 15.0-17.3kVA
* imageFileURL =
* ctrlBoardSerial = PKI9050003
* hwRevision = 0x64
* fwRevision = 3.0.2.5-41550
* macAddress = 00:0d:5d:07:87:5c
* hasSwitchableOutlets = True
* hasMeteredOutlets = False
* hasLatchingOutletRelays = False
* isInlineMeter = False

### Switching the first outlet:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan")
pdu = pdumodel.Pdu("/model/pdu/0", agent)
outlets = pdu.getOutlets()
outlets[0].setPowerState(pdumodel.Outlet.PowerState.PS_OFF)

### Get current reading from first outlet:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan")
pdu = pdumodel.Pdu("/model/pdu/0", agent)
outlets = pdu.getOutlets()
outlets[0].getSensors().current.getReading().value

### Configuring the SNMP agent:

Code:

from raritan import rpc
from raritan.rpc import devsettings
agent = rpc.Agent("https", "my-device.example.com", "admin", "raritan")
snmp_proxy = devsettings.Snmp("/snmp", agent)
config = snmp_proxy.getConfiguration()
config.v2enable = True
config.readComm = "public"
config.writeComm = "private"
snmp_proxy.setConfiguration(config)

Note that the URIs given to the object proxies (such as `"/model/pdu/0"`) are well-known references to static (i.e. they are always there) object instances implemented by the device. All well-known references along with their interface are documented in file Well-Known-URIs.txt which comes along with the IDL files.

## IDL-to-Python Mapping

### Modules and Python Packages

All supporting and generated symbols are placed underneath common package `raritan.rpc`. IDL Modules are mapped to corresponding Python package within this common package. Import of all definitions within a module can be done via (for instance):

from raritan.rpc.pdumodel import *

### Interfaces and Methods

IDL interfaces are mapped to Python classes which are defined in the `init`.py file of their according package. The python class implements a proxy that delegates calls to its IDL defined methods to the actual object implementation across the network.

The signature of the methods is slightly altered compared to the IDL signature. All `in` arguments are expected as arguments to the Python method in the same order as they appear in IDL. The return argument, if any, and all `out` arguments are returned as a Python tuple in the same order they appear in IDL. That means if there is a return argument defined it will appear as first element in the tuple, otherwise the first `out` argument is the first element in the tuple. If the IDL method has either only a return value or a single out argument, a single value is returned by the Python method without an embracing tuple.

### Structures

IDL structures are mapped to Python classes which are, like all other definitions, defined in the `init`.py file of their according package. The class has all elements as defined in IDL. In addition there is a constructor with a signature that initializes all elements.

The following is an example for enabling a threshold in a sensor:

from raritan import rpc
from raritan.rpc import pdumodel, sensors
agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan")
outlet = pdumodel.Outlet("/model/pdu/0/outlet/0", agent)
currentsens = outlet.getSensors().current
thresholds = currentsens.getThresholds()
thresholds.lowerWarning = 1.0
thresholds.lowerWarningActive = True
currentsens.setThresholds(thresholds)

### Enumerations

An IDL enumeration is mapped to a concrete class which has an element for each enumerated value. That means access to a particular enumerated value is accomplished by naming the enumeration type and the enumerated value. Consider the following example for switching an outlet:

# pdumodel has been imported and outlet has been initialized before, see above
outlet.setPowerState(pdumodel.Outlet.PowerState.PS_OFF)

`PowerState` is an enumerated type defined in the `Outlet` interface. `PS_OFF` is a specific enumerated value defined in the `PowerState` enumeration.

### Vectors

IDL vectors are mapped to Python lists. Consider the following example for looping over the list of all outlets of a Pdu and printing out informative data:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-px.example.com", "admin", "raritan")
pdu = pdumodel.Pdu("/model/pdu/0", agent)
outlets = pdu.getOutlets()
for outlet in outlets:
print(outlet.getMetaData())

### Maps

IDL maps are mapped to Python dictionaries. Consider the following example for looping over all observed servers of the `servermon.ServerMonitor` and retrieving their entry id mapped to server entry structure which contains information and status:

from raritan import rpc
from raritan.rpc import servermon
agent = rpc.Agent("https", "my-device.example.com", "admin", "raritan")
srvmonitor = servermon.ServerMonitor("/servermon", agent);
servers = srvmonitor.listServers()
for srvid, srventry in servers.iteritems():
print(srvid, srventry.settings.host, srventry.status.reachable)

### Exceptions

Execptional errors conditions may occur because of communication problems or encoding/decoding problems, or because of system errors that occur on the server while processing a request. Reporting of such error conditions is not part a regular IDL signature but part of the JSON-RPC protocol.

The Python implementation of the JSON-RPC protocol maps these error condtions to exception:

- `raritan.rpc.HttpException`

  This exception is raised in case a communication error occured. Typical examples include an unreachable server or a failed authentication. The exception contains a descriptive text that gives more details on the error condition.

- `raritan.rpc.JsonRpcErrorException`

  This exception is raised in case an error happened on the server side while processing the request. The device might be in an unexpected state. Also there might be a version mismatch between client and server, which means the communication contract between client and server as specified by IDL is broken. The exception contains a descriptive text that gives more details on the error condition.

- `raritan.rpc.JsonRpcSyntaxException`

  This exception is raised in case demarshaling of a JSON message went wrong. This may indicate a version mismatch between client and server. The exception contains a descriptive text that gives more details on the error condition.

Consider the following example for catching a communication error:

from raritan import rpc
from raritan.rpc import pdumodel
try:
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
pdu = pdumodel.Pdu("/model/pdu/0", agent)
print("Getting PDU MetaData...")
metadata = pdu.getMetaData()
print("OK ->")
print(metadata)
except rpc.HttpException as e:
print("ERROR:", str(e))

### Bulk Requests

The Bulk RPC interface allows combining multiple JSON-RPC method calls into a single bulk request that can be sent to the server and processed in a single HTTP request. The `raritan.rpc.BulkRequestHelper` class provides a convenient interface to collect and execute method calls:

1. Create a BulkRequestHelper instance.
2. Queue one or more method calls with the `add_request()` method.
3. Call perform_bulk() to submit the bulk request.
4. Use clear() to empty the request and response lists before reusing the BulkRequestHelper instance.

`perform_bulk()` returns a list containing one entry per queued request. Each entry can be one of the following:

- `None` if the called method returns void and has no out parameters.
- A single value if the method has exactly one return type or out parameter.
- A tuple if the method has more than one return type/out parameter.
- An `Exception` object if the request has failed and the optional `raise_subreq_failure` argument is False.

Example:

from raritan import rpc
from raritan.rpc import devsettings
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
snmp_proxy = devsettings.Snmp("/snmp", agent)
cfg = snmp_proxy.getConfiguration()
cfg.v2enable = True
bulk_helper = rpc.BulkRequestHelper(agent)
bulk_helper.add_request(snmp_proxy.getV3EngineId)
bulk_helper.add_request(snmp_proxy.setConfiguration, cfg)
responses = bulk_helper.perform_bulk(raise_subreq_failure = False)
if isinstance(responses[0], Exception):
print("Snmp.getV3EngineId() failed: %s" % (responses[0]))
else:
print("SNMP engine ID: %s" % (responses[0]))
if isinstance(responses[1], Exception):
print("Snmp.setConfiguration() failed: %s" % (responses[1]))
else:
print("Result of setConfiguration(): %d" % (responses[1]))

## raritan.rpc.Agent Method Reference

### Constructor: raritan.rpc.Agent(proto, host, user = None, passwd = None, token = None, debug = False, disable_certificate_verification = False, timeout = None)

Creates a new agent.

Parameters:

- proto Used protocol (either "https" or "http")
- host Hostname or IP address of the target PDU
- user User Name (optional)
- passwd Password (optional)
- token Authentication Token (optional)
- debug Enables debug output (optional, True/False)
- disable_certificate_verification Disables the Certificate Verification (True/False)
- timeout Request timeout (optional, timeout in seconds)

If both, username/password and token are omitted, it is necessary to call either set_auth_basic() or set_auth_token() before the first request.

### set_auth_basic(user, password)

This method enables HTTP basic authentication using username and password.

Parameters:

- user User Name
- password Password

### set_auth_token(token)

This method enables HTTP authentication using a session token. A session token can be obtained by calling the newSession method of the session.SessionManager interface.

Parameters:

- token Session Token

## Firmware Update

It is possible to upload and update the device firmware with the Python JSON-RPC. A file can be uploaded as binary through the firmware upload method. The example uses a file within the current working directory.

Example:

from raritan import rpc
from raritan.rpc import firmware
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
firmware_proxy = firmware.Firmware("/firmware", agent)
# read file in binary mode
fwFile = open("pdu-030600-45660.bin", "rb")
# upload
firmware.upload(agent, fwFile.read())
image_present, image_info = firmware_proxy.getImageInfo()
# check for succesfull upload
if not image_present:
print("Upload failed")
else:
print(image_info)
# start update
firmware_proxy.startUpdate([])

## Certificate Upload and installation

It is possible to upload and install own certificates. The Certificate upload needs two files:

1. certificate file (e.g. my-cert.crt)
2. key file (e.g. my-key.key) It is recommended that the user verifies the pending certificate before installation.

Example:

from raritan import rpc
from raritan.rpc import cert
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
ssl_proxy = cert.ServerSSLCert("/server_ssl_cert", agent)
# read files in binary mode
certFile = open("my-cert.crt", "rb")
keyFile = open("my-key.key", "rb")
# upload
cert.upload(agent, certFile.read(), keyFile.read())
# view pending
print(ssl_proxy.getInfo().pendingCertInfo)
# install
ssl_proxy.installPendingKeyPair()
# view active
print(ssl_proxy.getInfo().activeCertInfo)

## Certificate Download

It is possible to download the installed certificates.

Example:

from raritan import rpc
from raritan.rpc import cert
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# downlaod the current installed certificate
certificate = cert.download(agent)
# view the certificate
print(certificate)

## Raw Configuration Upload

It is possible to upload a raw configuration. The raw configuration upload need one file:

1. raw configuration file (e.g. config.txt)

After uploading a raw configuration a response code is returned. Known response codes are:

Response
0 | Operation was succesfull.
1 | An internal error occured.
2 | A parameter error occured.
3 | A raw config update operation is already running.
4 | The file is too large.
5 | Invalid raw config file provided.
6 | Invalid device list file or match provided.
7 | Device list file required but missing. It must be the first uploaded file!
8 | No matching entry in device list found.
9 | Macro subsitution error.
10 | Decrypting value failed.
11 | Unknown magic line.
12 | Processing magic line fail.

Example:

from raritan import rpc
from raritan.rpc import rawcfg
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# read file in binary mode
cfg_file = open("config.txt", "rb")
# upload
code = rawcfg.upload(agent, cfg_file.read())
# output response code
print(code)

## Raw Configuration Download

It is possible to download the raw configuration.

Example:

from raritan import rpc
from raritan.rpc import rawcfg
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# download
rawconfig = rawcfg.download(agent)
# output raw configuration
print(rawconfig)

## Bulk Configuration Upload

It is possible to upload a bulk configuration. The bulk configuration upload need one file:

1. bulk configuration file (e.g. bulk_config.txt)

After uploading a bulk configuration a response code is returned. Known response codes are:

Response Code | Description | Comment — | — | — 0 | Operation was successful. | 1 | An internal error occured. | 2 | A parameter error occured. | 3 | Invalid XML data provided. | legacy / unused 4 | The config data is incompatible. Device type mismatch. | 5 | The config data is incompatible. Device model mismatch. | 6 | The config data is incompatible. Firmware version mismatch. | 7 | The config data is incompatible. Unknown data type. | legacy / unused 8 | The config data is invalid. | legacy / unused 9 | Checksum of config data is wrong. | legacy / unused 10 | Mode mismatch (bulk config vs. full config). | legacy / unused 11 | Restore operation already running. | 12 | File too large. | 13 | File invalid. | 14 | Checksum missing or invalid. | 15 | Unknown filters. |

Example:

from raritan import rpc
from raritan.rpc import bulkcfg
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# read file in binary mode
cfg_file = open("bulk_config.txt", "rb")
# upload
code = bulkcfg.upload(agent, cfg_file.read())
# view code
print(code)

The bulk configuration upload support different modes, these modes are:

- restore a configuration backup (backup or full)
- restore a bulk configuration (default)

For switching the modes, use the parameters full or backup from the uplaod function.

Example:

# backup mode
code = bulkcfg.upload(agent, cfg_file.read(), backup=True)
# full mode
code = bulkcfg.upload(agent, cfg_file.read(), full=True)

## Bulk Configuration Download

It is possible to download the bulk configuration.

Example:

from raritan import rpc
from raritan.rpc import bulkcfg
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# download
bulkconfig = bulkcfg.download(agent)
# output bulk configuration
print(bulkconfig)

The bulk configuration download support different modes, these modes are:

- restore a configuration backup (backup or full)
- restore a bulk configuration (default)

For switching the modes, use the parameters full or backup from the uplaod function.

Example:

# backup mode
code = bulkcfg.download(agent, backup=True)
# full mode
code = bulkcfg.download(agent, full=True)

## Diagnostic Data Download

It is possible to download the diagnostic data.

Example:

from raritan import rpc
from raritan.rpc import diag
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# download
diag = diag.download_diag(agent)
# view diagnostic data
print(diag)

## ETO Descriptor Download

It is possible to download the ETO descriptor.

Example:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# download
eto_desc = pdumodel.download_eto(agent)
# view eto descriptor
print(eto_desc)

## PMC Data Download

It is possible to download the PMC data of:

1. For all main sensors and circuits of that a specific panel, numbered 1 - 8
2. For all main sensors of all configured power meters and panels

Example:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# download specific,for panel 1 (can be in range 1 - 8)
pmc_data = pdumodel.download_panel_csv(agent, 1)
# download complete
pmc_data = pdumodel.download_powermeter_csv(agent)
# view pmc data
print(pmc_data)

## PMC Configuration Upload

It is possible to upload the pmc configuration. The pmc configuration upload need one file:

1. pmc configuration file (e.g. pmc_config.txt)

Example:

from raritan import rpc
from raritan.rpc import pdumodel
agent = rpc.Agent("https", "my-pdu.example.com", "admin", "raritan")
# read file in binary mode
pmc_config = open("config.txt", "rb")
# upload
response = pdumodel.upload_pmc_config(agent, pmc_config.read())
# output response
print(response)

## Zeroconf device discovery

There is a helper function, that will discover Raritan power products inside of the current subnet and will return a list of ip strings. For this feature there must be the zeroconf python package installed (pip install zeronfonf). This package is only available for python version 3.6 and up.

Example:

from raritan import zeroconf
response = zeroconf.discover()
print(response)