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
|
2012-07-29 22:12:37 -07:00
|
|
|
import StringIO
|
2012-03-26 22:48:48 -07:00
|
|
|
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
|
|
|
|
|
|
|
|
2012-07-29 22:12:37 -07:00
|
|
|
LOG = logging.getLogger(__name__)
|
2012-03-26 22:48:48 -07:00
|
|
|
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-07-29 22:12:37 -07:00
|
|
|
self.scheme = parts.scheme
|
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)
|
|
|
|
|
2012-07-29 22:12:37 -07:00
|
|
|
def log_curl_request(self, method, url, kwargs):
|
|
|
|
curl = ['curl -i -X %s' % method]
|
|
|
|
|
|
|
|
for (key, value) in kwargs['headers'].items():
|
|
|
|
header = '-H \'%s: %s\'' % (key, value)
|
|
|
|
curl.append(header)
|
|
|
|
|
2012-03-26 22:48:48 -07:00
|
|
|
if 'body' in kwargs:
|
2012-07-29 22:12:37 -07:00
|
|
|
curl.append('-d \'%s\'' % kwargs['body'])
|
|
|
|
|
|
|
|
endpoint_parts = (self.scheme, self.endpoint[0], self.endpoint[1], url)
|
|
|
|
curl.append('%s://%s:%s%s' % endpoint_parts)
|
|
|
|
LOG.debug(' '.join(curl))
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def log_http_response(resp, body=None):
|
|
|
|
status = (resp.version / 10.0, resp.status, resp.reason)
|
|
|
|
dump = ['\nHTTP/%.1f %s %s' % status]
|
|
|
|
dump.extend(['%s: %s' % (k, v) for k, v in resp.getheaders()])
|
|
|
|
dump.append('')
|
|
|
|
if body:
|
|
|
|
dump.extend([body, ''])
|
|
|
|
LOG.debug('\n'.join(dump))
|
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-29 22:12:37 -07:00
|
|
|
self.log_curl_request(method, url, kwargs)
|
|
|
|
|
2012-07-10 20:51:00 -07:00
|
|
|
conn = self.get_connection()
|
|
|
|
conn.request(method, url, **kwargs)
|
|
|
|
resp = conn.getresponse()
|
|
|
|
|
2012-07-29 22:12:37 -07:00
|
|
|
body_iter = ResponseBodyIterator(resp)
|
|
|
|
|
|
|
|
# Read body into string if it isn't obviously image data
|
|
|
|
if resp.getheader('content-type', None) != 'application/octet-stream':
|
|
|
|
body_str = ''.join([chunk for chunk in body_iter])
|
|
|
|
self.log_http_response(resp, body_str)
|
|
|
|
body_iter = StringIO.StringIO(body_str)
|
|
|
|
else:
|
|
|
|
self.log_http_response(resp)
|
2012-03-26 22:48:48 -07:00
|
|
|
|
|
|
|
if 400 <= resp.status < 600:
|
2012-07-29 22:12:37 -07:00
|
|
|
LOG.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-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)
|
2012-03-26 22:48:48 -07:00
|
|
|
|
2012-07-29 22:12:37 -07:00
|
|
|
if 'application/json' in resp.getheader('content-type', None):
|
|
|
|
body = ''.join([chunk for chunk in body_iter])
|
2012-05-15 10:01:47 -07:00
|
|
|
try:
|
|
|
|
body = json.loads(body)
|
|
|
|
except ValueError:
|
2012-07-29 22:12:37 -07:00
|
|
|
LOG.error('Could not decode response body as JSON')
|
2012-05-15 10:01:47 -07:00
|
|
|
else:
|
|
|
|
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()
|