예제 #1
0
파일: base.py 프로젝트: numvc/LuxoftBot
    def _get(self, resource_id, fields=None, os_ironic_api_version=None):
        """Retrieve a resource.

        :param resource_id: Identifier of the resource.
        :param fields: List of specific fields to be returned.
        :param os_ironic_api_version: String version (e.g. "1.35") to use for
            the request.  If not specified, the client's default is used.
        :raises exc.ValidationError: For invalid resource_id arg value.
        """

        if not resource_id:
            raise exc.ValidationError(
                "The identifier argument is invalid. "
                "Value provided: {!r}".format(resource_id))

        if fields is not None:
            resource_id = '%s?fields=' % resource_id
            resource_id += ','.join(fields)

        try:
            return self._list(
                self._path(resource_id),
                os_ironic_api_version=os_ironic_api_version)[0]
        except IndexError:
            return None
예제 #2
0
 def take_action(self, parsed_args):
     if parsed_args.driver:
         self.log.warning(_LW("This command is deprecated. Instead, use "
                              "'openstack baremetal node create'."))
         return super(CreateBaremetal, self).take_action(parsed_args)
     if not parsed_args.resource_files:
         raise exc.ValidationError(_(
             "If --driver is not supplied to openstack create command, "
             "it is considered that it will create ironic resources from "
             "one or more .json or .yaml files, but no files provided."))
     create_resources.create_resources(self.app.client_manager.baremetal,
                                       parsed_args.resource_files)
     # NOTE(vdrok): CreateBaremetal is still inherited from ShowOne class,
     # which requires the return value of the function to be of certain
     # type, leave this workaround until creation of nodes is removed and
     # then change it so that this inherits from command.Command
     return tuple(), tuple()
예제 #3
0
    def _get(self, resource_id, fields=None):
        """Retrieve a resource.

        :param resource_id: Identifier of the resource.
        :param fields: List of specific fields to be returned.
        :raises exc.ValidationError: For invalid resource_id arg value.
        """

        if not resource_id:
            raise exc.ValidationError(
                "The identifier argument is invalid. "
                "Value provided: {!r}".format(resource_id))

        if fields is not None:
            resource_id = '%s?fields=' % resource_id
            resource_id += ','.join(fields)

        try:
            return self._list(self._path(resource_id))[0]
        except IndexError:
            return None
예제 #4
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.
        """
        # NOTE(TheJulia): self.os_ironic_api_version is reset in
        # the self.negotiate_version() call if negotiation occurs.
        if self.os_ironic_api_version and self._must_negotiate_version():
            self.negotiate_version(self.session, None)
        # 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_ironic_api_version:
            kwargs['headers'].setdefault('X-OpenStack-Ironic-API-Version',
                                         self.os_ironic_api_version)
        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:
            # https://specs.openstack.org/openstack/ironic-specs/specs/kilo-implemented/api-microversions.html#use-case-3b-new-client-communicating-with-a-old-ironic-user-specified  # noqa

            if resp.status_code == http_client.NOT_ACCEPTABLE:
                negotiated_ver = self.negotiate_version(self.session, resp)
                kwargs['headers']['X-OpenStack-Ironic-API-Version'] = (
                    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 exc.ValidationError(message)

            raise exc.ConnectionRefused(message)

        body_str = None
        if resp.headers.get('Content-Type') == 'application/octet-stream':
            body_iter = resp.iter_content(chunk_size=CHUNKSIZE)
            self.log_http_response(resp)
        else:
            # Read body into string if it isn't obviously image data
            body_str = resp.text
            self.log_http_response(resp, body_str)
            body_iter = six.StringIO(body_str)

        if resp.status_code >= http_client.BAD_REQUEST:
            error_json = _extract_error_json(body_str)
            raise exc.from_response(resp, error_json.get('error_message'),
                                    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 exc.from_response(resp, method=method, url=url)

        return resp, body_iter