2012-03-26 22:48:48 -07:00
|
|
|
"""
|
|
|
|
OpenStack Client interface. Handles the REST calls and responses.
|
|
|
|
"""
|
|
|
|
|
|
|
|
import copy
|
2012-07-10 20:51:00 -07:00
|
|
|
import httplib
|
2012-03-26 22:48:48 -07:00
|
|
|
import logging
|
|
|
|
import urlparse
|
|
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
import json
|
|
|
|
except ImportError:
|
|
|
|
import simplejson as json
|
|
|
|
|
|
|
|
# Python 2.5 compat fix
|
|
|
|
if not hasattr(urlparse, 'parse_qsl'):
|
|
|
|
import cgi
|
|
|
|
urlparse.parse_qsl = cgi.parse_qsl
|
|
|
|
|
|
|
|
|
2012-07-12 18:30:54 -07:00
|
|
|
from glanceclient import exc
|
2012-03-26 22:48:48 -07:00
|
|
|
|
|
|
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
USER_AGENT = 'python-glanceclient'
|
2012-07-11 19:34:28 -07:00
|
|
|
CHUNKSIZE = 1024 * 64 # 64kB
|
2012-03-26 22:48:48 -07:00
|
|
|
|
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
class HTTPClient(object):
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-05-24 22:35:14 -05:00
|
|
|
def __init__(self, endpoint, token=None, timeout=600, insecure=False):
|
2012-07-10 20:51:00 -07:00
|
|
|
parts = urlparse.urlparse(endpoint)
|
|
|
|
self.connection_class = self.get_connection_class(parts.scheme)
|
|
|
|
self.endpoint = (parts.hostname, parts.port)
|
2012-03-26 22:48:48 -07:00
|
|
|
self.auth_token = token
|
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
@staticmethod
|
|
|
|
def get_connection_class(scheme):
|
|
|
|
try:
|
|
|
|
return getattr(httplib, '%sConnection' % scheme.upper())
|
|
|
|
except AttributeError:
|
|
|
|
msg = 'Unsupported scheme: %s' % scheme
|
|
|
|
raise exc.InvalidEndpoint(msg)
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
def get_connection(self):
|
|
|
|
return self.connection_class(*self.endpoint)
|
|
|
|
|
|
|
|
def http_log(self, args, kwargs, resp):
|
2012-03-26 22:48:48 -07:00
|
|
|
string_parts = ['curl -i']
|
|
|
|
for element in args:
|
|
|
|
if element in ('GET', 'POST'):
|
|
|
|
string_parts.append(' -X %s' % element)
|
|
|
|
else:
|
|
|
|
string_parts.append(' %s' % element)
|
|
|
|
|
|
|
|
for element in kwargs['headers']:
|
|
|
|
header = ' -H "%s: %s"' % (element, kwargs['headers'][element])
|
|
|
|
string_parts.append(header)
|
|
|
|
|
|
|
|
logger.debug("REQ: %s\n" % "".join(string_parts))
|
2012-04-03 17:39:32 -07:00
|
|
|
if 'raw_body' in kwargs:
|
|
|
|
logger.debug("REQ BODY (RAW): %s\n" % (kwargs['raw_body']))
|
2012-03-26 22:48:48 -07:00
|
|
|
if 'body' in kwargs:
|
|
|
|
logger.debug("REQ BODY: %s\n" % (kwargs['body']))
|
2012-07-10 20:51:00 -07:00
|
|
|
logger.debug("RESP: %s", resp)
|
2012-03-26 22:48:48 -07:00
|
|
|
|
|
|
|
def _http_request(self, url, method, **kwargs):
|
|
|
|
""" Send an http request with the specified characteristics.
|
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
|
|
|
|
as setting headers and error handling.
|
2012-03-26 22:48:48 -07:00
|
|
|
"""
|
|
|
|
# Copy the kwargs so we can reuse the original in case of redirects
|
2012-05-15 10:01:47 -07:00
|
|
|
kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
|
|
|
|
kwargs['headers'].setdefault('User-Agent', USER_AGENT)
|
|
|
|
if self.auth_token:
|
|
|
|
kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
conn = self.get_connection()
|
|
|
|
conn.request(method, url, **kwargs)
|
|
|
|
resp = conn.getresponse()
|
|
|
|
|
|
|
|
self.http_log((url, method,), kwargs, resp)
|
2012-03-26 22:48:48 -07:00
|
|
|
|
|
|
|
if 400 <= resp.status < 600:
|
|
|
|
logger.exception("Request returned failure status.")
|
2012-07-10 20:51:00 -07:00
|
|
|
raise exc.from_response(resp)
|
2012-03-26 22:48:48 -07:00
|
|
|
elif resp.status in (301, 302, 305):
|
|
|
|
# Redirected. Reissue the request to the new location.
|
|
|
|
return self._http_request(resp['location'], method, **kwargs)
|
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
body_iter = ResponseBodyIterator(resp)
|
2012-07-11 19:34:28 -07:00
|
|
|
return resp, body_iter
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-05-15 10:01:47 -07:00
|
|
|
def json_request(self, method, url, **kwargs):
|
2012-03-26 22:48:48 -07:00
|
|
|
kwargs.setdefault('headers', {})
|
2012-05-15 10:01:47 -07:00
|
|
|
kwargs['headers'].setdefault('Content-Type', 'application/json')
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-05-15 10:01:47 -07:00
|
|
|
if 'body' in kwargs:
|
|
|
|
kwargs['body'] = json.dumps(kwargs['body'])
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-07-11 19:34:28 -07:00
|
|
|
resp, body_iter = self._http_request(url, method, **kwargs)
|
|
|
|
body = ''.join([chunk for chunk in body_iter])
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-05-15 10:01:47 -07:00
|
|
|
if body:
|
|
|
|
try:
|
|
|
|
body = json.loads(body)
|
|
|
|
except ValueError:
|
|
|
|
logger.debug("Could not decode JSON from body: %s" % body)
|
|
|
|
else:
|
|
|
|
logger.debug("No body was returned.")
|
|
|
|
body = None
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-05-15 10:01:47 -07:00
|
|
|
return resp, body
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-05-15 10:01:47 -07:00
|
|
|
def raw_request(self, method, url, **kwargs):
|
|
|
|
kwargs.setdefault('headers', {})
|
|
|
|
kwargs['headers'].setdefault('Content-Type',
|
|
|
|
'application/octet-stream')
|
|
|
|
return self._http_request(url, method, **kwargs)
|
2012-07-11 19:34:28 -07:00
|
|
|
|
|
|
|
|
|
|
|
class ResponseBodyIterator(object):
|
|
|
|
"""A class that acts as an iterator over an HTTP response."""
|
|
|
|
|
|
|
|
def __init__(self, resp):
|
|
|
|
self.resp = resp
|
|
|
|
|
|
|
|
def __iter__(self):
|
|
|
|
while True:
|
|
|
|
yield self.next()
|
|
|
|
|
|
|
|
def next(self):
|
|
|
|
chunk = self.resp.read(CHUNKSIZE)
|
|
|
|
if chunk:
|
|
|
|
return chunk
|
|
|
|
else:
|
|
|
|
raise StopIteration()
|