예제 #1
0
    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 xrange(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 Neutron service'))
                    time.sleep(self.retry_interval)

        raise exceptions.ConnectionFailed(reason=_("Maximum attempts reached"))
예제 #2
0
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})
예제 #3
0
    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 xrange(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 Neutron service"))
                    time.sleep(self.retry_interval)

        raise exceptions.ConnectionFailed(reason=_("Maximum attempts reached"))
예제 #4
0
 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
         # Neutron error
         des_error_body = {'message': response_body}
     # Raise the appropriate exception
     exception_handler_v20(status_code, des_error_body)
예제 #5
0
파일: client.py 프로젝트: wputra/MOS-centos
 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
         # Neutron error
         des_error_body = {'message': response_body}
     # Raise the appropriate exception
     exception_handler_v20(status_code, des_error_body)
예제 #6
0
    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))
예제 #7
0
def http_log_req(_logger, args, kwargs, force_logging=False):
    if not _logger.isEnabledFor(logging.DEBUG) and not force_logging:
        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.get('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)
    if _logger.isEnabledFor(logging.DEBUG):
        _logger.debug(_("\nREQ: %s\n"), "".join(string_parts))
    else:
        _logger.error(_("\nREQ: %s\n"), "".join(string_parts))
예제 #8
0
파일: client.py 프로젝트: wputra/MOS-centos
    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))
예제 #9
0
def http_log_resp(_logger, resp, body):
    if not _logger.isEnabledFor(logging.DEBUG):
        return
    resp_headers_content = """
HTTP/1.1 %(status)s
Content-Type: %(content-type)s
Content-Length: %(content-length)s
Date: %(date)s
"""
    resp_headers_empty = """
HTTP/1.1 %(status)s
Content-Length: %(content-length)s
Date: %(date)s
"""
    json_acceptable_string = str(resp)
    json_acceptable_string = json_acceptable_string.replace('"', '\\"')
    json_acceptable_string = json_acceptable_string.replace("'", '"')
    try:
        response_dict = json.loads(json_acceptable_string)
        resp_headers = resp_headers_content
        if response_dict.get('status') == '200':
            response_dict['status'] = '200 OK'
        elif response_dict.get('status') == '201':
            response_dict['status'] = '201 Created'
        elif response_dict.get('status') == '204':
            response_dict['status'] = '204 No Content'
            resp_headers = resp_headers_empty
        elif response_dict.get('status') == '401':
            response_dict['status'] = '401 Unauthorized'
        elif response_dict.get('status') == '404':
            response_dict['status'] = '404 Not Found'
        x = resp_headers % response_dict
    except Exception:
        _logger.exception(str(resp))
        x = "Failed Parsing"
    try:
        _body = dumps(json.loads(body), indent=1)
    except ValueError:
        _body = body
    _logger.debug(
        _("RESP:%(resp_headers)s\n%(body)s\n\nUnparsed resp: %(resp)s \n"), {
            'resp': resp,
            'resp_headers': x,
            'body': _body
        })
예제 #10
0
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)
예제 #11
0
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))
예제 #12
0
class NeutronException(Exception):
    """Base Neutron 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
class SslCertificateValidationError(NeutronClientException):
    message = _("SSL certificate validation has failed: %(reason)s")
class ConnectionFailed(NeutronClientException):
    message = _("Connection to neutron failed: %(reason)s")
class AmbiguousEndpoints(NeutronClientException):
    message = _("Found more than one matching endpoint in Service Catalog: "
                "%(matching_endpoints)")
class EndpointTypeNotFound(NeutronClientException):
    message = _("Could not find endpoint type %(type_)s in Service Catalog.")
class EndpointNotFound(NeutronClientException):
    message = _("Could not find Service or Region in Service Catalog.")
예제 #18
0
class InvalidContentType(Invalid):
    message = _("Invalid content type %(content_type)s.")
class NeutronClientNoUniqueMatch(NeutronCLIError):
    message = _("Multiple %(resource)s matches found for name '%(name)s',"
                " use an ID to be more specific.")
예제 #20
0
파일: utils.py 프로젝트: wputra/MOS-centos
def http_log_resp(_logger, resp, body):
    if not _logger.isEnabledFor(logging.DEBUG):
        return
    _logger.debug(_("RESP:%(resp)s %(body)s\n"), {'resp': resp, 'body': body})
class Forbidden(NeutronClientException):
    status_code = 403
    message = _("Forbidden: your credentials don't give you access to this "
                "resource.")
예제 #22
0
 def __str__(self):
     msg = _("Could not find endpoint type %s in Service Catalog.")
     return msg % repr(self.message)
예제 #23
0
 def __str__(self):
     msg = _("Could not find endpoint type %s in Service Catalog.")
     return msg % repr(self.message)
예제 #24
0
 def __str__(self):
     return _("AmbiguousEndpoints: %s") % repr(self.message)
예제 #25
0
class MalformedRequestBody(NeutronException):
    message = _("Malformed request body: %(reason)s")
class MalformedResponseBody(NeutronClientException):
    message = _("Malformed response body: %(reason)s")
class InvalidContentType(NeutronClientException):
    message = _("Invalid content type %(content_type)s.")
class NoAuthURLProvided(Unauthorized):
    message = _("auth_url was not provided to the Neutron client")
class Unauthorized(NeutronClientException):
    status_code = 401
    message = _("Unauthorized: bad credentials.")
예제 #30
0
class Unauthorized(NeutronClientException):
    message = _("Unauthorized: bad credentials.")
예제 #31
0
 def __str__(self):
     return _("AmbiguousEndpoints: %s") % repr(self.message)
예제 #32
0
class NoAuthURLProvided(BadInputError):
    message = _("auth_url was not provided to the Neutron client")