Esempio n. 1
0
 def test_api_version_is_not_null(self):
     api_version = api_versions.APIVersion("2.3")
     headers = {}
     api_versions.update_headers(headers, api_version)
     self.assertEqual(
         {"OpenStack-API-Version":
          "container %s" % api_version.get_string()},
         headers)
Esempio n. 2
0
    def _http_request(self, url, method, **kwargs):
        if url.startswith(API_VERSION):
            url = url[len(API_VERSION):]

        kwargs.setdefault('user_agent', self.user_agent)
        kwargs.setdefault('auth', self.auth)
        kwargs.setdefault('endpoint_override', self.endpoint_override)

        # Copy the kwargs so we can reuse the original in case of redirects
        kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
        kwargs['headers'].setdefault('User-Agent', self.user_agent)
        api_versions.update_headers(kwargs["headers"], self.api_version)

        # NOTE(kevinz): osprofiler_web.get_trace_id_headers does not add any
        # headers in case if osprofiler is not initialized.
        if osprofiler_web:
            kwargs['headers'].update(osprofiler_web.get_trace_id_headers())

        endpoint_filter = kwargs.setdefault('endpoint_filter', {})
        endpoint_filter.setdefault('interface', self.interface)
        endpoint_filter.setdefault('service_type', self.service_type)
        endpoint_filter.setdefault('region_name', self.region_name)
        LOG.debug(
            'httpclient endpoint_filter args xxx endpoint_filter=%s,url=%s,method=%s,kwargs=%s'
            % (endpoint_filter, url, method, kwargs))
        resp = self.session.request(url, method, raise_exc=False, **kwargs)

        if 400 <= resp.status_code < 600:
            error_json = _extract_error_json(resp.content)
            raise exceptions.from_response(resp, error_json.get('faultstring'),
                                           error_json.get('debuginfo'), method,
                                           url)
        elif resp.status_code in (301, 302, 305):
            # Redirected. Reissue the request to the new location.
            location = resp.headers.get('location')
            resp = self._http_request(location, method, **kwargs)
        elif resp.status_code == 300:
            raise exceptions.from_response(resp, method=method, url=url)
        return resp
Esempio n. 3
0
    def _http_request(self, url, method, **kwargs):
        if url.startswith(API_VERSION):
            url = url[len(API_VERSION):]

        kwargs.setdefault('user_agent', self.user_agent)
        kwargs.setdefault('auth', self.auth)
        kwargs.setdefault('endpoint_override', self.endpoint_override)

        # Copy the kwargs so we can reuse the original in case of redirects
        kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
        kwargs['headers'].setdefault('User-Agent', self.user_agent)
        api_versions.update_headers(kwargs["headers"], self.api_version)

        # NOTE(kevinz): osprofiler_web.get_trace_id_headers does not add any
        # headers in case if osprofiler is not initialized.
        if osprofiler_web:
            kwargs['headers'].update(osprofiler_web.get_trace_id_headers())

        endpoint_filter = kwargs.setdefault('endpoint_filter', {})
        endpoint_filter.setdefault('interface', self.interface)
        endpoint_filter.setdefault('service_type', self.service_type)
        endpoint_filter.setdefault('region_name', self.region_name)
        resp = self.session.request(url, method,
                                    raise_exc=False, **kwargs)

        if 400 <= resp.status_code < 600:
            error_json = _extract_error_json(resp.content)
            raise exceptions.from_response(
                resp, error_json.get('faultstring'),
                error_json.get('debuginfo'), method, url)
        elif resp.status_code in (301, 302, 305):
            # Redirected. Reissue the request to the new location.
            location = resp.headers.get('location')
            resp = self._http_request(location, method, **kwargs)
        elif resp.status_code == 300:
            raise exceptions.from_response(resp, method=method, url=url)
        return resp
Esempio n. 4
0
 def test_api_version_is_major(self):
     headers = {}
     api_versions.update_headers(headers, api_versions.APIVersion("7.0"))
     self.assertEqual({}, headers)
Esempio n. 5
0
 def test_api_version_is_null(self):
     headers = {}
     api_versions.update_headers(headers, api_versions.APIVersion())
     self.assertEqual({}, headers)
Esempio n. 6
0
    def _http_request(self, url, method, **kwargs):
        """Send an http request with the specified characteristics.

        Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
        as setting headers and error handling.
        """
        # Copy the kwargs so we can reuse the original in case of redirects
        kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
        kwargs['headers'].setdefault('User-Agent', USER_AGENT)
        api_versions.update_headers(kwargs["headers"], self.api_version)

        if self.auth_token:
            kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)

        self.log_curl_request(method, url, kwargs)
        conn = self.get_connection()

        try:
            conn_url = self._make_connection_url(url)
            conn.request(method, conn_url, **kwargs)
            resp = conn.getresponse()
        except socket.gaierror as e:
            message = ("Error finding address for %(url)s: %(e)s" %
                       dict(url=url, e=e))
            raise exceptions.EndpointNotFound(message)
        except (socket.error, socket.timeout) as e:
            endpoint = self.endpoint
            message = ("Error communicating with %(endpoint)s %(e)s" %
                       dict(endpoint=endpoint, e=e))
            raise exceptions.ConnectionRefused(message)

        body_iter = ResponseBodyIterator(resp)

        # Read body into string if it isn't obviously image data
        body_str = None
        if resp.getheader('content-type', None) != 'application/octet-stream':
            # decoding byte to string is necessary for Python 3.4 compatibility
            # this issues has not been found with Python 3.4 unit tests
            # because the test creates a fake http response of type str
            # the if statement satisfies test (str) and real (bytes) behavior
            body_list = [
                chunk.decode("utf-8") if isinstance(chunk, bytes) else chunk
                for chunk in body_iter
            ]
            body_str = ''.join(body_list)
            self.log_http_response(resp, body_str)
            body_iter = six.StringIO(body_str)
        else:
            self.log_http_response(resp)

        if 400 <= resp.status < 600:
            LOG.warning("Request returned failure status.")
            error_json = _extract_error_json(body_str)
            raise exceptions.from_response(resp, error_json.get('faultstring'),
                                           error_json.get('debuginfo'), method,
                                           url)
        elif resp.status in (301, 302, 305):
            # Redirected. Reissue the request to the new location.
            return self._http_request(resp['location'], method, **kwargs)
        elif resp.status == 300:
            raise exceptions.from_response(resp, method=method, url=url)

        return resp, body_iter
Esempio n. 7
0
    def _http_request(self, url, method, **kwargs):
        """Send an http request with the specified characteristics.

        Wrapper around httplib.HTTP(S)Connection.request to handle tasks such
        as setting headers and error handling.
        """
        # Copy the kwargs so we can reuse the original in case of redirects
        kwargs['headers'] = copy.deepcopy(kwargs.get('headers', {}))
        kwargs['headers'].setdefault('User-Agent', USER_AGENT)
        api_versions.update_headers(kwargs["headers"], self.api_version)

        if self.auth_token:
            kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)

        self.log_curl_request(method, url, kwargs)
        conn = self.get_connection()

        try:
            conn_url = self._make_connection_url(url)
            conn.request(method, conn_url, **kwargs)
            resp = conn.getresponse()
        except socket.gaierror as e:
            message = ("Error finding address for %(url)s: %(e)s"
                       % dict(url=url, e=e))
            raise exceptions.EndpointNotFound(message)
        except (socket.error, socket.timeout) as e:
            endpoint = self.endpoint
            message = ("Error communicating with %(endpoint)s %(e)s"
                       % dict(endpoint=endpoint, e=e))
            raise exceptions.ConnectionRefused(message)

        body_iter = ResponseBodyIterator(resp)

        # Read body into string if it isn't obviously image data
        body_str = None
        if resp.getheader('content-type', None) != 'application/octet-stream':
            # decoding byte to string is necessary for Python 3.4 compatibility
            # this issues has not been found with Python 3.4 unit tests
            # because the test creates a fake http response of type str
            # the if statement satisfies test (str) and real (bytes) behavior
            body_list = [
                chunk.decode("utf-8") if isinstance(chunk, bytes)
                else chunk for chunk in body_iter
            ]
            body_str = ''.join(body_list)
            self.log_http_response(resp, body_str)
            body_iter = six.StringIO(body_str)
        else:
            self.log_http_response(resp)

        if 400 <= resp.status < 600:
            LOG.warning("Request returned failure status.")
            error_json = _extract_error_json(body_str)
            raise exceptions.from_response(
                resp, error_json.get('faultstring'),
                error_json.get('debuginfo'), method, url)
        elif resp.status in (301, 302, 305):
            # Redirected. Reissue the request to the new location.
            return self._http_request(resp['location'], method, **kwargs)
        elif resp.status == 300:
            raise exceptions.from_response(resp, method=method, url=url)

        return resp, body_iter