1
# vim: tabstop=4 shiftwidth=4 softtabstop=4
3
# Copyright 2011 Nexenta Systems, Inc.
6
# Licensed under the Apache License, Version 2.0 (the "License"); you may
7
# not use this file except in compliance with the License. You may obtain
8
# a copy of the License at
10
# http://www.apache.org/licenses/LICENSE-2.0
12
# Unless required by applicable law or agreed to in writing, software
13
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
# License for the specific language governing permissions and limitations
18
:mod:`nexenta.jsonrpc` -- Nexenta-specific JSON RPC client
19
=====================================================================
21
.. automodule:: nexenta.jsonrpc
22
.. moduleauthor:: Yuriy Taraday <yorik.sar@gmail.com>
27
from nova.openstack.common import jsonutils
28
from nova.openstack.common import log as logging
29
from nova.volume import nexenta
31
LOG = logging.getLogger(__name__)
34
class NexentaJSONException(nexenta.NexentaException):
38
class NexentaJSONProxy(object):
39
def __init__(self, url, user, password, auto=False, obj=None, method=None):
42
self.password = password
47
def __getattr__(self, name):
49
obj, method = name, None
51
obj, method = self.obj, name
53
obj, method = '%s.%s' % (self.obj, self.method), name
54
return NexentaJSONProxy(self.url, self.user, self.password, self.auto,
57
def __call__(self, *args):
58
data = jsonutils.dumps({'object': self.obj,
59
'method': self.method,
61
auth = ('%s:%s' % (self.user, self.password)).encode('base64')[:-1]
62
headers = {'Content-Type': 'application/json',
63
'Authorization': 'Basic %s' % (auth,)}
64
LOG.debug(_('Sending JSON data: %s'), data)
65
request = urllib2.Request(self.url, data, headers)
66
response_obj = urllib2.urlopen(request)
67
if response_obj.info().status == 'EOF in headers':
68
if self.auto and self.url.startswith('http://'):
69
LOG.info(_('Auto switching to HTTPS connection to %s'),
71
self.url = 'https' + self.url[4:]
72
request = urllib2.Request(self.url, data, headers)
73
response_obj = urllib2.urlopen(request)
75
LOG.error(_('No headers in server response'))
76
raise NexentaJSONException(_('Bad response from server'))
78
response_data = response_obj.read()
79
LOG.debug(_('Got response: %s'), response_data)
80
response = jsonutils.loads(response_data)
81
if response.get('error') is not None:
82
raise NexentaJSONException(response['error'].get('message', ''))
84
return response.get('result')