Example #1
0
def get_file_contents(fname):
    with open(fname, 'r') as f:
        content = f.read()
    try:
        return json.loads(content)
    except ValueError:
        msg = _("Error occured while trying to translate JSON")
        raise exceptions.MagnetoDBClientException(message=msg)
    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 MagnetoDB service'))
                    time.sleep(self.retry_interval)

        raise exceptions.ConnectionFailed(reason=_("Maximum attempts reached"))
 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
         # MagnetoDB error
         des_error_body = {'message': response_body}
     # Raise the appropriate exception
     exception_handler_v1(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().serialize(data, self.content_type)
        else:
            raise Exception(_("Unable to serialize object of type = '%s'") %
                            type(data))
Example #5
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[api_name][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)
Example #6
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))
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})
 def _handle_fault_response(self, status_code, response_body):
     # Create exception with HTTP status code and message
     _logger.debug(_("Error message: %s"), response_body)
     exception_handler_v1(status_code, response_body)