/
restclient.py
195 lines (165 loc) · 6.1 KB
/
restclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
methods for contacting to a HTTP server, sending REST commands
and processing the JSON response
"""
import sys
import socket
import httplib
import urllib
import base64
import simplejson as json
import string
class RestClient:
def __init__(self, server, port, opts= {}):
self.server = server
self.port = port
self.debug = opts.get('debug', False)
self.uri = '/pools'
self.method = 'GET'
self.params = {}
self.user = ''
self.password = ''
self.body = ''
self.clientConnect(server, int(port))
def clientConnect(self, server, port):
error_connect = "Unable to connect to %s" % self.server
try:
self.conn = httplib.HTTPConnection(server, port)
except httplib.NotConnected:
print error_connect
sys.exit(2)
except httplib.HTTPException:
print error_connect
sys.exit(2)
except socket.error:
print error_connect
sys.exit(2)
except socket.gaierror:
print error_connect
sys.exit(2)
def setParam(self, param, value):
self.params[param] = value
def setPayload(self, payload):
self.body = payload
def getParam(self, param):
return self.params[param]
def handleResponse(self,
method,
response,
opts={ 'success_msg':'',
'error_msg':'' }):
""" parse response in standard way.
"""
if response.status in [200, 201, 202, 204, 302]:
if method == 'GET' or not opts['success_msg']:
return response.read()
return "SUCCESS: %s" % opts['success_msg']
if response.status == 401:
print 'ERROR: unable to access the REST API - please check your username (-u) and password (-p)'
sys.exit(2)
print 'ERROR: %s (%d) %s' % (opts['error_msg'],
response.status, response.reason)
print response.read()
sys.exit(2)
def bootStrap(self, headers):
""" First REST call needed for info for later REST calls.
"""
self.conn.request('GET', '/pools', '', headers)
response = self.conn.getresponse()
opts = {'error_msg':'bootstrap failed'}
return self.handleResponse('GET', response, opts)
def sendCmd(self, method, uri,
user='', password='', opts = {}):
"""
sendCmd()
This method handles accessing the REST API and returning
either data, if a GET, or a success or error message if a POST
"""
data = ''
headers = {}
encoded_params = ''
if user and password:
self.user = user
self.password = password
auth = ('Basic ' +
string.strip(base64.encodestring(user + ':' + password)))
headers['Authorization'] = auth
self.bootStrap(headers)
if method == 'POST':
if self.body:
headers['Content-type'] = 'application/json;charset=UTF-8'
encoded_params = self.body
elif self.params:
encoded_params = urllib.urlencode(self.params)
headers['Content-type'] = 'application/x-www-form-urlencoded'
elif method == 'DELETE':
encoded_params = urllib.urlencode(self.params)
headers['Content-type'] = 'application/x-www-form-urlencoded'
elif method == 'PUT':
if self.body:
headers['Content-type'] = 'application/json;charset=UTF-8'
encoded_params = self.body
elif self.params:
headers['Content-type'] = 'application/x-www-form-urlencoded'
encoded_params = urllib.urlencode(self.params)
else:
print "ERROR: no input parameters for PUT request"
return None
else:
if self.params:
uri = uri, '?', urllib.urlencode(self.params)
if self.debug:
print "METHOD: %s" % method
print "PARAMS: ", self.params
print "ENCODED_PARAMS: %s" % encoded_params
print "REST CMD: %s %s" % (method,uri)
self.makeRequest(method, uri, encoded_params, headers)
response = self.conn.getresponse()
if self.debug:
print "response.status: %s" % response.status
return response
def makeRequest(self, method, uri, encoded_params, headers):
error_connect = "ERROR: unable to connect to %s:%d" % (self.server, self.port)
try:
self.conn.request(method, uri, encoded_params, headers)
except httplib.NotConnected:
print error_connect
sys.exit(2)
except httplib.HTTPException:
print error_connect
sys.exit(2)
except socket.error:
print error_connect
sys.exit(2)
except socket.gaierror:
print error_connect
sys.exit(2)
def getJson(self, data):
return json.loads(data)
def jsonMessage(self, data):
return json.JSONEncoder().encode(data)
def restCmd(self, method, uri, user='', password='', opts={}):
if method == None:
method = 'GET'
response = self.sendCmd(method, uri,
user, password, opts)
return self.handleResponse(method, response, opts)
class SslRestClient(RestClient):
def clientConnect(self, server, port):
error_connect = "Unable to connect to %s as SSL client" % self.server
try:
self.conn = httplib.HTTPSConnection(server, port)
except httplib.NotConnected:
print error_connect
sys.exit(2)
except httplib.HTTPException:
print error_connect
sys.exit(2)
except socket.error:
print error_connect
sys.exit(2)
except socket.gaierror:
print error_connect
sys.exit(2)