def check_api_version(check_version):
    """Validate version supplied by user

    Returns:
    * True if version is OK
    * False if the version has not been checked and the previous plugin
    check should be performed
    * throws an exception if the version is no good
    """

    infra_api_version = api_versioning.get_api_version(check_version)

    # Bypass X.latest format microversion
    if not infra_api_version.is_latest():
        if infra_api_version > api_versioning.APIVersion("2.0"):
            if not infra_api_version.matches(
                watcherclient.API_MIN_VERSION,
                watcherclient.API_MAX_VERSION,
            ):
                msg = "versions supported by client: %(min)s - %(max)s" % {
                    "min": watcherclient.API_MIN_VERSION.get_string(),
                    "max": watcherclient.API_MAX_VERSION.get_string(),
                }
                raise exceptions.CommandError(msg)
    return True
Beispiel #2
0
def check_api_version(check_version):
    """Validate version supplied by user

    Returns:
    * True if version is OK
    * False if the version has not been checked and the previous plugin
    check should be performed
    * throws an exception if the version is no good
    """

    infra_api_version = api_versioning.get_api_version(check_version)

    # Bypass X.latest format microversion
    if not infra_api_version.is_latest():
        if infra_api_version > api_versioning.APIVersion("2.0"):
            if not infra_api_version.matches(
                    watcherclient.API_MIN_VERSION,
                    watcherclient.API_MAX_VERSION,
            ):
                msg = "versions supported by client: %(min)s - %(max)s" % {
                    "min": watcherclient.API_MIN_VERSION.get_string(),
                    "max": watcherclient.API_MAX_VERSION.get_string(),
                }
                raise exceptions.CommandError(msg)
    return True
    def _http_request(self, url, method, **kwargs):
        kwargs.setdefault('user_agent', USER_AGENT)
        kwargs.setdefault('auth', self.auth)
        if isinstance(self.endpoint_override, six.string_types):
            kwargs.setdefault(
                'endpoint_override',
                _trim_endpoint_api_version(self.endpoint_override)
            )

        if getattr(self, 'os_infra_optim_api_version', None):
            api_version = api_versioning.get_api_version(
                self.os_infra_optim_api_version)
            if api_version.is_latest():
                api_version = api_versioning.get_api_version(
                    LATEST_VERSION)
            kwargs['headers'].setdefault(
                'OpenStack-API-Version',
                ' '.join(['infra-optim',
                          api_version.get_string()]))

        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 resp.status_code == http_client.NOT_ACCEPTABLE:
            negotiated_ver = self.negotiate_version(self.session, resp)
            kwargs['headers']['OpenStack-API-Version'] = (
                ' '.join(['infra-optim', negotiated_ver]))
            return self._http_request(url, method, **kwargs)
        if resp.status_code >= http_client.BAD_REQUEST:
            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 (http_client.MOVED_PERMANENTLY,
                                  http_client.FOUND, http_client.USE_PROXY):
            # Redirected. Reissue the request to the new location.
            location = resp.headers.get('location')
            resp = self._http_request(location, method, **kwargs)
        elif resp.status_code == http_client.MULTIPLE_CHOICES:
            raise exceptions.from_response(resp, method=method, url=url)
        return resp
Beispiel #4
0
    def _http_request(self, url, method, **kwargs):
        kwargs.setdefault('user_agent', USER_AGENT)
        kwargs.setdefault('auth', self.auth)
        if isinstance(self.endpoint_override, six.string_types):
            kwargs.setdefault(
                'endpoint_override',
                _trim_endpoint_api_version(self.endpoint_override))

        if getattr(self, 'os_infra_optim_api_version', None):
            api_version = api_versioning.get_api_version(
                self.os_infra_optim_api_version)
            if api_version.is_latest():
                api_version = api_versioning.get_api_version(LATEST_VERSION)
            kwargs['headers'].setdefault(
                'OpenStack-API-Version',
                ' '.join(['infra-optim',
                          api_version.get_string()]))

        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 resp.status_code == http_client.NOT_ACCEPTABLE:
            negotiated_ver = self.negotiate_version(self.session, resp)
            kwargs['headers']['OpenStack-API-Version'] = (' '.join(
                ['infra-optim', negotiated_ver]))
            return self._http_request(url, method, **kwargs)
        if resp.status_code >= http_client.BAD_REQUEST:
            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 (http_client.MOVED_PERMANENTLY,
                                  http_client.FOUND, http_client.USE_PROXY):
            # Redirected. Reissue the request to the new location.
            location = resp.headers.get('location')
            resp = self._http_request(location, method, **kwargs)
        elif resp.status_code == http_client.MULTIPLE_CHOICES:
            raise exceptions.from_response(resp, method=method, url=url)
        return resp
Beispiel #5
0
 def test_major_and_minor_parts_is_presented(self, mock_apiversion):
     version = "2.7"
     self.assertEqual(mock_apiversion.return_value,
                      api_versioning.get_api_version(version))
     mock_apiversion.assert_called_once_with(version)
Beispiel #6
0
 def test_only_major_part_is_presented(self, mock_apiversion):
     version = 7
     self.assertEqual(mock_apiversion.return_value,
                      api_versioning.get_api_version(version))
     mock_apiversion.assert_called_once_with("%s.0" % str(version))
    def _http_request(self, url, method, **kwargs):
        """Send an http request with the specified characteristics.

        Wrapper around request.Session.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)
        if self.os_infra_optim_api_version:
            api_version = api_versioning.get_api_version(
                self.os_infra_optim_api_version)
            if api_version.is_latest():
                api_version = api_versioning.get_api_version(
                    LATEST_VERSION)
            kwargs['headers'].setdefault(
                'OpenStack-API-Version',
                ' '.join(['infra-optim', api_version.get_string()]))
        if self.auth_token:
            kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)

        self.log_curl_request(method, url, kwargs)

        # NOTE(aarefiev): This is for backwards compatibility, request
        # expected body in 'data' field, previously we used httplib,
        # which expected 'body' field.
        body = kwargs.pop('body', None)
        if body:
            kwargs['data'] = body

        conn_url = self._make_connection_url(url)
        try:
            resp = self.session.request(method,
                                        conn_url,
                                        **kwargs)

            # TODO(deva): implement graceful client downgrade when connecting
            # to servers that did not support microversions. Details here:
            # http://specs.openstack.org/openstack/watcher-specs/specs/kilo/api-microversions.html#use-case-3b-new-client-communicating-with-a-old-watcher-user-specified  # noqa

            if resp.status_code == http_client.NOT_ACCEPTABLE:
                negotiated_ver = self.negotiate_version(self.session, resp)
                kwargs['headers']['OpenStack-API-Version'] = (
                    ' '.join(['infra-optim', negotiated_ver]))
                return self._http_request(url, method, **kwargs)

        except requests.exceptions.RequestException as e:
            message = (_("Error has occurred while handling "
                       "request for %(url)s: %(e)s") %
                       dict(url=conn_url, e=e))
            # NOTE(aarefiev): not valid request(invalid url, missing schema,
            # and so on), retrying is not needed.
            if isinstance(e, ValueError):
                raise exceptions.ValidationError(message)

            raise exceptions.ConnectionRefused(message)

        body_iter = resp.iter_content(chunk_size=CHUNKSIZE)

        # Read body into string if it isn't obviously image data
        body_str = None
        if resp.headers.get('Content-Type') != 'application/octet-stream':
            # decoding byte to string is necessary for Python 3 compatibility
            # this issues has not been found with Python 3 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 resp.status_code >= http_client.BAD_REQUEST:
            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_code in (http_client.MOVED_PERMANENTLY,
                                  http_client.FOUND,
                                  http_client.USE_PROXY):
            # Redirected. Reissue the request to the new location.
            return self._http_request(resp['location'], method, **kwargs)
        elif resp.status_code == http_client.MULTIPLE_CHOICES:
            raise exceptions.from_response(resp, method=method, url=url)

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

        Wrapper around request.Session.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)
        if self.os_infra_optim_api_version:
            api_version = api_versioning.get_api_version(
                self.os_infra_optim_api_version)
            if api_version.is_latest():
                api_version = api_versioning.get_api_version(LATEST_VERSION)
            kwargs['headers'].setdefault(
                'OpenStack-API-Version',
                ' '.join(['infra-optim',
                          api_version.get_string()]))
        if self.auth_token:
            kwargs['headers'].setdefault('X-Auth-Token', self.auth_token)

        self.log_curl_request(method, url, kwargs)

        # NOTE(aarefiev): This is for backwards compatibility, request
        # expected body in 'data' field, previously we used httplib,
        # which expected 'body' field.
        body = kwargs.pop('body', None)
        if body:
            kwargs['data'] = body

        conn_url = self._make_connection_url(url)
        try:
            resp = self.session.request(method, conn_url, **kwargs)

            # TODO(deva): implement graceful client downgrade when connecting
            # to servers that did not support microversions. Details here:
            # http://specs.openstack.org/openstack/watcher-specs/specs/kilo/api-microversions.html#use-case-3b-new-client-communicating-with-a-old-watcher-user-specified  # noqa

            if resp.status_code == http_client.NOT_ACCEPTABLE:
                negotiated_ver = self.negotiate_version(self.session, resp)
                kwargs['headers']['OpenStack-API-Version'] = (' '.join(
                    ['infra-optim', negotiated_ver]))
                return self._http_request(url, method, **kwargs)

        except requests.exceptions.RequestException as e:
            message = (_("Error has occurred while handling "
                         "request for %(url)s: %(e)s") %
                       dict(url=conn_url, e=e))
            # NOTE(aarefiev): not valid request(invalid url, missing schema,
            # and so on), retrying is not needed.
            if isinstance(e, ValueError):
                raise exceptions.ValidationError(message)

            raise exceptions.ConnectionRefused(message)

        body_iter = resp.iter_content(chunk_size=CHUNKSIZE)

        # Read body into string if it isn't obviously image data
        body_str = None
        if resp.headers.get('Content-Type') != 'application/octet-stream':
            # decoding byte to string is necessary for Python 3 compatibility
            # this issues has not been found with Python 3 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 resp.status_code >= http_client.BAD_REQUEST:
            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_code in (http_client.MOVED_PERMANENTLY,
                                  http_client.FOUND, http_client.USE_PROXY):
            # Redirected. Reissue the request to the new location.
            return self._http_request(resp['location'], method, **kwargs)
        elif resp.status_code == http_client.MULTIPLE_CHOICES:
            raise exceptions.from_response(resp, method=method, url=url)

        return resp, body_iter