Curl
Create window
The following sample creates a schedule maintenance window.
curl -k -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X POST https://{api-url}/api/v2/tenants/{tenantId}/scheduleMaintenances -d
{
"name": "{scheduleMaintenance_name}",
"description": "{scheduleMaintenance_description}",
"dontRunRBA": "false",
"dontInstallPatch": "false",
"devices": [{
"hostName": "{host_name}"
}],
"schedule": {
"type": "{schedule_type}",
"startTime": "{start_time}",
"endTime": "{end_time}",
"timezone": "{time_zone}"
}
}
Search for window
The following sample searches for a schedule maintenance window by name.
curl -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X GET https://{api-url}/api/v2/tenants/{tenantId}/scheduleMaintenances/search?queryString=name:{scheduleMaintenance_name}}
Suspend window
The following sample suspends a schedule maintenance window.
curl -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X POST https://{api-url}/api/v2/tenants/{tenantId}/scheduleMaintenances/{scheduleMaintenance_id}/suspend
Resume window
The following sample resumes a schedule maintenance window.
curl -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X POST https://{api-url}/api/v2/tenants/{tenantId}/scheduleMaintenances/{scheduleMaintenance_id}/resume
Delete window
The following sample deletes a schedule maintenance window.
curl -H "Authorization: Bearer {bearer_token}" -H "Content-Type: application/json" -H "Accept:application/json" -X DELETE https://{api-url}/api/v2/tenants/{tenantId}/scheduleMaintenances/{scheduleMaintenance_id}
Python
import urllib
import urllib2
import json, sys
import time
API_SERVER = "api.vistanet.jp"
CLIENT_ID = "CLIENT_ID"
API_KEY = "API_KEY"
API_SECRET = "API_SECRET"
# Python HTTP client to generate GET/POST requests
def httpRequest(url, data=None, headers={}, repeat_count=None, method='GET',user=None, passwd=None):
try:
http_headers = {
'Content-Type' : 'application/x-www-form-urlencoded',
'Accept' : 'text/html, */*',
}
http_headers.update(headers)
req = urllib2.Request(url, data, http_headers)
req.get_method = lambda: method
if user and passwd:
passReq = urllib2.HTTPPasswordMgrWithDefaultRealm()
passReq.add_password(None, url, user, passwd)
authhandler = urllib2.HTTPBasicAuthHandler(passReq)
opener = urllib2.build_opener(authhandler)
urllib2.install_opener(opener)
request = urllib2.urlopen(req)
return request.read()
except urllib2.HTTPError, emsg:
_msg = emsg.read()
print emsg.getcode()
if emsg.getcode() == 429:
time.sleep(60)
if repeat_count != None and repeat_count < 3:
httpRequest(url, data, headers, repeat_count+1, method)
print _msg
return _msg
elif emsg.getcode() == 500:
print _msg
return _msg
else:
print emsg.read()
raise Exception(emsg.reason)
raise Exception('httpRequest: HTTPError - ' + str(emsg))
except urllib2.URLError, emsg:
raise Exception('httpRequest: URLError - ' + str(emsg))
except Exception, emsg:
raise Exception('httpRequest: Exception - ' + str(emsg))
def schedule_maintenance_actions(URL, DATA):
headers = {
"Authorization" : "Bearer " + ACCESS_TOKEN,
"Content-Type" : "application/json"
}
try:
response = json.loads(httpRequest(URL, DATA, headers, 0, 'GET'))
except Exception, emsg:
print emsg
sys.exit(2)
# Get OpsRamp access token using api key/secret for further communication
def get_access_token():
url = "https://%s/auth/oauth/token" % (API_SERVER)
data = urllib.urlencode({
"client_id" : API_KEY,
"client_secret" : API_SECRET,
"grant_type" : "client_credentials"
})
headers = {"Content-Type": "application/x-www-form-urlencoded", "Accept" : "application/json"}
try:
result = json.loads(httpRequest(url, data, headers, None, 'POST'))
return result['access_token']
except Exception as emsg:
raise Exception("Error while getting access token - " + str(emsg))
if __name__ == '__main__':
try:
ACCESS_TOKEN = str(get_access_token())
''' Creating a schedule maintenance window '''
url = "https://{0}/api/v2/tenants/{1}/scheduleMaintenances".format(API_SERVER, CLIENT_ID)
data = {
"name" : "Test Maintenance from API",
"description" : "Test Maintenance from API",
"dontRunRBA" :"false",
"dontInstallPatch" :"false",
"devices" : [{
"uniqueId": "702c19c4-1991-4e99-8c5f-4104c061fe25"
}],
"schedule" : {
"type":"One-Time",
"startTime": "2016-07-07T08:21:00+0000",
"endTime": "2016-07-09T08:45:00+0000",
"timezone":"America/Los_Angeles"
}
}
# Searching a schedule maintenance window by name
url = """https://%s/api/v2/tenants/%s/scheduleMaintenances/search?queryString="""
+ urllib.encode("name:Test Maintenance from API") %(API_SERVER, CLIENT_ID)
data = None
# Suspending a schedule maintenance window
url = "https://{0}/api/v2/tenants/{1}/scheduleMaintenances/123456/suspend".format(API_SERVER, CLIENT_ID)
data = {"pattern" : "now"}
# Resuming a schedule maintenance window
url = "https://{0}/api/v2/tenants/{1}/scheduleMaintenances/123456/resume".format(API_SERVER, CLIENT_ID)
data = None
# Deleting a schedule maintenance window
url = "https://{0/api/v2/tenants/{1}/scheduleMaintenances/123456".format(API_SERVER, CLIENT_ID)
data = None
schedule_maintenance_actions(url, data)
except Exception as e:
print ("Failed - " + str(e))
Java
package com.opsramp.examples.rest;
import java.io.IOException;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import org.apache.http.HttpException;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* Sample program to perform schedule maintenance actions
*/
public class ScheduleMaintenanceActions {
/**
* Main program which performs schedule maintenance actions
* @param args
* @throws HttpException
* @throws IOException
*/
public static void main(String[] args) throws HttpException, IOException {
//Replace the end point and access token accordingly
String ACCESS_TOKEN = "a0f46d75-534d-4180-b4ec-65a23eb1ae39";
//Creating a schedule maintenance window
String ENDPOINT = "https://{api-url}/api/v2/tenants/client_99999/scheduleMaintenances";
String PAYLOAD = "{"name":"Test Maintenance from API","description":"Test Maintenance from API","
+ ""dontRunRBA":"false","dontInstallPatch":"false", "devices":[{"uniqueId":"
+ ""702c19c4-1991-4e99-8c5f-4104c061fe25"}],"schedule":{"type":"One-Time","startTime":"
+ ""2016-07-07T08:21:00+0000","endTime":"2016-07-09T08:45:00+0000","timezone":"
+ ""America/Los_Angeles"}}";
String response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, PAYLOAD);
System.out.println(response);
//Searching a schedule maintenance window by name
ENDPOINT = "https://{api-url}/api/v2/tenants/client_99999/scheduleMaintenances/search"
+ "?queryString=" + URLEncoder.encode("name:Test Maintenance from API", StandardCharsets.UTF_8.toString());
response = invokeGetRequest(ACCESS_TOKEN, ENDPOINT);
System.out.println(response);
//Suspending a schedule maintenance window
ENDPOINT = "https://{api-url}/api/v2/tenants/client_99999/scheduleMaintenances/123456/suspend";
PAYLOAD = "{"pattern": "now"}";
response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, PAYLOAD);
System.out.println(response);
//Resuming a schedule maintenance window
ENDPOINT = "https://{api-url}/api/v2/tenants/client_99999/scheduleMaintenances/123456/resume";
response = invokePostRequest(ACCESS_TOKEN, ENDPOINT, null);
System.out.println(response);
//Deleting a schedule maintenance window
ENDPOINT = "https://{api-url}/api/v2/tenants/client_99999/scheduleMaintenances/123456";
response = invokeDeleteRequest(ACCESS_TOKEN, ENDPOINT);
System.out.println(response);
}
/**
* Fetches data from given end point
* @param accessToken
* @param endPoint
* @return
* @throws HttpException
* @throws IOException
*/
public static String invokeGetRequest(final String accessToken, final String endPoint)
throws HttpException, IOException {
return invokeRequest(accessToken, endPoint, null, new HttpGet(), 0);
}
/**
* Deletes data at given end point
* @param accessToken
* @param endPoint
* @return
* @throws HttpException
* @throws IOException
*/
public static String invokeDeleteRequest(final String accessToken, final String endPoint)
throws HttpException, IOException {
return invokeRequest(accessToken, endPoint, null, new HttpDelete(), 0);
}
/**
* Posts data to given end point
* @param accessToken
* @param endPoint
* @param payload
* @return
* @throws HttpException
* @throws IOException
*/
public static String invokePostRequest(final String accessToken, final String endPoint,
final String payload) throws HttpException, IOException {
return invokeRequest(accessToken, endPoint, payload, new HttpPost(), 0);
}
/**
* Invokes an OAuth2 API request
* @param accessToken
* @param endPoint
* @param payload
* @param httpRequest
* @return
* @throws HttpException
* @throws IOException
*/
public static String invokeRequest(final String accessToken, final String endPoint,
final String payload, HttpRequestBase httpRequest, final int currentRetryCount) throws HttpException, IOException {
CloseableHttpClient httpclient = HttpClients.custom().build();
try {
httpRequest.setURI(URI.create(endPoint));
httpRequest.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString());
httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
httpRequest.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
if(httpRequest instanceof HttpEntityEnclosingRequestBase && payload != null) {
((HttpEntityEnclosingRequestBase) httpRequest)
.setEntity(new ByteArrayEntity(payload.getBytes(StandardCharsets.UTF_8.toString())));
}
System.out.println("\n" + httpRequest.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpRequest);
try {
System.out.println("Response " + response.getStatusLine());
String responseBody = null;
if(response.getEntity() != null) {
responseBody = EntityUtils.toString(response.getEntity());
if(response.getStatusLine().getStatusCode() == 429) {
if(currentRetryCount > 3) {
System.out.println("Retry Max-Limit(3) reached; Dropping API: " + endPoint);
}
long resetTimeInSeconds = Long.valueOf(response.getFirstHeader("X-RateLimit-Reset").getValue());
long retryInSec = resetTimeInSeconds - (new Date().getTime()/1000);
System.out.println("\tNext retry in: " + retryInSec + "s" + " | " + endPoint);
try {
Thread.sleep(retryInSec*1000);
} catch(Exception ex) {}
invokeRequest(accessToken, endPoint, payload, httpRequest, currentRetryCount+1);
}
}
return responseBody;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}