Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Copyright 2010 Jacob Kaplan-Moss # Copyright 2011 OpenStack LLC. # Copyright 2011 Piston Cloud Computing, Inc. # Copyright 2011 Nebula, Inc.
# All Rights Reserved. OpenStack Client interface. Handles the REST calls and responses. """
except ImportError: import simplejson as json
# Python 2.5 compat fix import cgi urlparse.parse_qsl = cgi.parse_qsl
try: import keyring import pickle return True except ImportError: if (hasattr(sys.stderr, 'isatty') and sys.stderr.isatty()): print >> sys.stderr, 'Failed to load keyring modules.' else: _logger.warning('Failed to load keyring modules.') return False
password=None, auth_url=None, region_name=None, timeout=None, endpoint=None, token=None, cacert=None, key=None, cert=None, insecure=False, original_ip=None, debug=False, auth_ref=None, use_keyring=False, force_new_token=False, stale_duration=None): """Construct a new http client
@param: timeout the request libary timeout in seconds (default None)
""" # set baseline defaults else: # if loading from a dictionary passed in via auth_ref, # load values from AccessInfo parsing that dictionary # allow override of the auth_ref defaults from explicit # values provided to the client else: else: self.verify_cert = False
# logging setup ch = logging.StreamHandler() _logger.setLevel(logging.DEBUG) _logger.addHandler(ch) if hasattr(requests, 'logging'): requests.logging.getLogger(requests.__name__).addHandler(ch)
# keyring setup
def auth_token(self):
def auth_token(self, value):
def auth_token(self): del self.auth_token_from_user
tenant_id=None, auth_url=None, token=None): """ Authenticate user.
Uses the data provided at instantiation to authenticate against the Keystone server. This may use either a username and password or token for authentication. If a tenant name or id was provided then the resulting authenticated client will be scoped to that tenant and contain a service catalog of available endpoints.
With the v2.0 API, if a tenant name or ID is not provided, the authenication token returned will be 'unscoped' and limited in capabilities until a fully-scoped token is acquired.
If successful, sets the self.auth_ref and self.auth_token with the returned token. If not already set, will also set self.management_url from the details provided in the token.
:returns: ``True`` if authentication was successful. :raises: AuthorizationFailure if unable to authenticate or validate the existing authorization token :raises: ValueError if insufficient parameters are used.
If keyring is used, token is retrieved from keyring instead. Authentication will only be necessary if any of the following conditions are met:
* keyring is not used * if token is not found in keyring * if token retrieved from keyring is expired or about to expired (as determined by stale_duration) * if force_new_token is true
"""
and not self.auth_ref.will_expire_soon(self.stale_duration)): token = self.auth_ref.auth_token
username, tenant_name, tenant_id, token) username, password, tenant_name, tenant_id, token) else: self.auth_ref = auth_ref
tenant_id, token): """ Create a unique key for keyring.
Used to store and retrieve auth_ref from keyring.
""" keys = [auth_url, username, tenant_name, tenant_id, token] for index, key in enumerate(keys): if key is None: keys[index] = '?' keyring_key = '/'.join(keys) return keyring_key
tenant_id, token): """ Retrieve auth_ref from keyring.
If auth_ref is found in keyring, (keyring_key, auth_ref) is returned. Otherwise, (keyring_key, None) is returned.
:returns: (keyring_key, auth_ref) or (keyring_key, None)
""" keyring_key = self._build_keyring_key(auth_url, username, tenant_name, tenant_id, token) try: auth_ref = keyring.get_password("keystoneclient_auth", keyring_key) if auth_ref: auth_ref = pickle.loads(auth_ref) if self.auth_ref.will_expire_soon(self.stale_duration): # token has expired, don't use it auth_ref = None except Exception as e: auth_ref = None _logger.warning('Unable to retrieve token from keyring %s' % ( e))
""" Store auth_ref into keyring.
""" try: keyring.set_password("keystoneclient_auth", keyring_key, pickle.dumps(self.auth_ref)) except Exception as e: _logger.warning("Failed to store token into keyring %s" % (e))
""" Extract and process information from the new auth_ref.
""" raise NotImplementedError
password=None, tenant_name=None, tenant_id=None, token=None): """ Authenticate against the Identity API and get a token.
Not implemented here because auth protocols should be API version-specific.
Expected to authenticate or validate an existing authentication reference already associated with the client. Invoking this call *always* makes a call to the Keystone.
:returns: ``raw token``
""" raise NotImplementedError
""" Set the client's service catalog from the response data.
Not implemented here because data returned may be API version-specific. """ raise NotImplementedError
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" % "".join(string_parts)) if 'data' in kwargs: _logger.debug("REQ BODY: %s\n" % (kwargs['data']))
_logger.debug( "RESP: [%s] %s\nRESP BODY: %s\n", resp.status_code, resp.headers, resp.text)
""" Send an http request with the specified characteristics.
Wrapper around requests.request to handle tasks such as setting headers, JSON encoding/decoding, and error handling. """ # Copy the kwargs so we can reuse the original in case of redirects self.original_ip, self.USER_AGENT)
method, url, verify=self.verify_cert, **request_kwargs) except requests.ConnectionError: msg = 'Unable to establish connection to %s' % url raise exceptions.ClientException(msg)
% resp.text) else:
"Request returned failure status: %s", resp.status_code) # Redirected. Reissue the request to the new location.
""" Makes an authenticated request to keystone endpoint by concatenating self.management_url and url and passing in method and any associated kwargs. """
'Current authorization does not have a known management url')
**kwargs)
|