def retry_request(self, method, action, body=None, headers=None, params=None): """Call do_request with the default retry configuration. Only idempotent requests should retry failed connection attempts. :raises: ConnectionFailed if the maximum # of retries is exceeded """ max_attempts = self.retries + 1 for i in range(max_attempts): try: return self.do_request(method, action, body=body, headers=headers, params=params) except exceptions.ConnectionFailed: # Exception has already been logged by do_request() if i < self.retries: _logger.debug(_('Retrying connection to Tacker service')) time.sleep(self.retry_interval) raise exceptions.ConnectionFailed(reason=_("Maximum attempts reached"))
def http_log_resp(_logger, resp, body): if not _logger.isEnabledFor(logging.DEBUG): return _logger.debug(_("RESP:%(code)s %(headers)s %(body)s\n"), { 'code': resp.status_code, 'headers': resp.headers, 'body': body })
def _handle_fault_response(self, status_code, response_body): # Create exception with HTTP status code and message _logger.debug(_("Error message: %s"), response_body) # Add deserialized error message to exception arguments try: des_error_body = self.deserialize(response_body, status_code) except Exception: # If unable to deserialized body it is probably not a # Tacker error des_error_body = {'message': response_body} # Raise the appropriate exception exception_handler_v10(status_code, des_error_body)
def serialize(self, data): """Serializes a dictionary into either xml or json. A dictionary with a single key can be passed and it can contain any structure. """ if data is None: return None elif type(data) is dict: return serializer.Serializer(self.get_attr_metadata()).serialize( data, self.content_type()) else: raise Exception( _("Unable to serialize object of type = '%s'") % type(data))
def http_log_req(_logger, args, kwargs): if not _logger.isEnabledFor(logging.DEBUG): return string_parts = ['curl -i'] for element in args: if element in ('GET', 'POST', 'DELETE', 'PUT'): 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) if 'body' in kwargs and kwargs['body']: string_parts.append(" -d '%s'" % (kwargs['body'])) string_parts = safe_encode_list(string_parts) _logger.debug(_("\nREQ: %s\n"), "".join(string_parts))
class TackerException(Exception): """Base Tacker Exception To correctly use this class, inherit from it and define a 'message' property. That message will get printf'd with the keyword arguments provided to the constructor. """ message = _("An unknown exception occurred.") def __init__(self, message=None, **kwargs): if message: self.message = message try: self._error_string = self.message % kwargs except Exception: # at least get the core message out if something happened self._error_string = self.message def __str__(self): return self._error_string
def get_client_class(api_name, version, version_map): """Returns the client class for the requested API version :param api_name: the name of the API, e.g. 'compute', 'image', etc :param version: the requested API version :param version_map: a dict of client classes keyed by version :rtype: a client class for the requested API version """ try: client_path = version_map[str(version)] except (KeyError, ValueError): msg = _("Invalid %(api_name)s client version '%(version)s'. must be " "one of: %(map_keys)s") msg = msg % { 'api_name': api_name, 'version': version, 'map_keys': ', '.join(version_map.keys()) } raise exceptions.UnsupportedVersion(msg) return import_class(client_path)
class TackerClientNoUniqueMatch(TackerCLIError): message = _("Multiple %(resource)s matches found for name '%(name)s'," " use an ID to be more specific.")
class InvalidContentType(TackerClientException): message = _("Invalid content type %(content_type)s.")
class MalformedResponseBody(TackerClientException): message = _("Malformed response body: %(reason)s")
class SslCertificateValidationError(TackerClientException): message = _("SSL certificate validation has failed: %(reason)s")
class ConnectionFailed(TackerClientException): message = _("Connection to tacker failed: %(reason)s")
class EndpointTypeNotFound(TackerClientException): message = _("Could not find endpoint type %(type_)s in Service Catalog.")
class EndpointNotFound(TackerClientException): message = _("Could not find Service or Region in Service Catalog.")
class NoAuthURLProvided(Unauthorized): message = _("auth_url was not provided to the Tacker client")
class Unauthorized(TackerClientException): status_code = 401 message = _("Unauthorized: bad credentials.")
class Forbidden(TackerClientException): status_code = 403 message = _("Forbidden: your credentials don't give you access to this " "resource.")
class AmbiguousEndpoints(TackerClientException): message = _("Found more than one matching endpoint in Service Catalog: " "%(matching_endpoints)")