def _metadata(self, method, key=None, clear=False, delete=False,
                  **metadata):
        for k, v in metadata.items():
            if not isinstance(v, six.string_types):
                raise ValueError("The value for %s (%s) must be "
                                 "a text string" % (k, v))

        # If we're in a ServerDetail, we need to pop the "detail" portion
        # of the URL off and then everything else will work the same.
        pos = self.base_path.find("detail")
        if pos != -1:
            base = self.base_path[:pos]
        else:
            base = self.base_path

        if key is not None:
            url = utils.urljoin(base, self.id, "metadata", key)
        else:
            url = utils.urljoin(base, self.id, "metadata")

        kwargs = {"endpoint_filter": self.service}
        if metadata or clear:
            # 'meta' is the key for singular modifications.
            # 'metadata' is the key for mass modifications.
            key = "meta" if key is not None else "metadata"
            kwargs["json"] = {key: metadata}

        headers = {"Accept": ""} if delete else {}

        response = method(url, headers=headers, **kwargs)

        # DELETE doesn't return a JSON body while everything else does.
        return response.json() if not delete else None
    def _test_get_data_by_id(self, key, response_value, response_body):
        class FakeResource2(FakeResource):
            resource_key = key
            service = "my_service"

        response = mock.MagicMock()
        response.body = response_body

        sess = mock.MagicMock()
        sess.get = mock.MagicMock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.get_data_by_id(sess, resource_id=r_id)
        self.assertEqual(response_value, resp)
        sess.get.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            service=FakeResource2.service)

        path_args = {"name": "my_name"}
        resp = FakeResource2.get_data_by_id(sess, resource_id=r_id,
                                            path_args=path_args)
        self.assertEqual(response_value, resp)
        sess.get.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            service=FakeResource2.service)
    def _test_head_data_by_id(self, key, response_value):
        class FakeResource2(FakeResource):
            resource_key = key
            service = "my_service"

        response = mock.Mock()
        response.headers = response_value

        sess = mock.Mock()
        sess.head = mock.Mock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.head_data_by_id(sess, resource_id=r_id)
        self.assertEqual({'headers': response_value}, resp)
        headers = {'Accept': ''}
        sess.head.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            endpoint_filter=FakeResource2.service,
            headers=headers)

        path_args = {"parent_name": "my_name"}
        resp = FakeResource2.head_data_by_id(sess, resource_id=r_id,
                                             path_args=path_args)
        self.assertEqual({'headers': response_value}, resp)
        headers = {'Accept': ''}
        sess.head.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            endpoint_filter=FakeResource2.service,
            headers=headers)
    def _test_update_by_id(self, key, response_value, response_body,
                           attrs, json_body):

        class FakeResource2(FakeResource):
            put_update = False
            resource_key = key
            service = "my_service"

        response = mock.MagicMock()
        response.body = response_body

        sess = mock.MagicMock()
        sess.patch = mock.MagicMock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.update_by_id(sess, r_id, attrs)
        self.assertEqual(response_value, resp)
        sess.patch.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            service=FakeResource2.service,
            json=json_body)

        path_args = {"name": "my_name"}
        resp = FakeResource2.update_by_id(sess, r_id, attrs,
                                          path_args=path_args)
        self.assertEqual(response_value, resp)
        sess.patch.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            service=FakeResource2.service,
            json=json_body)
    def _test_head_data_by_id(self, key, response_value):
        class FakeResource2(FakeResource):
            resource_key = key
            service = "my_service"

        response = mock.MagicMock()
        response.headers = response_value

        sess = mock.MagicMock()
        sess.head = mock.MagicMock(return_value=response)

        r_id = "my_id"
        resp = FakeResource2.head_data_by_id(sess, resource_id=r_id)
        self.assertEqual({'headers': response_value}, resp)
        sess.head.assert_called_with(
            utils.urljoin(FakeResource2.base_path, r_id),
            service=FakeResource2.service,
            accept=None)

        path_args = {"name": "my_name"}
        resp = FakeResource2.head_data_by_id(sess, resource_id=r_id,
                                             path_args=path_args)
        self.assertEqual({'headers': response_value}, resp)
        sess.head.assert_called_with(
            utils.urljoin(FakeResource2.base_path % path_args, r_id),
            service=FakeResource2.service,
            accept=None)
    def _get_version_match(self, endpoint, profile_version, service_type):
        """Return the best matching version

        Look through each version trying to find the best match for
        the version specified in this profile.
         * The best match will only ever be found within the same
           major version, meaning a v2 profile will never match if
           only v3 is available on the server.
         * The search for the best match is fuzzy if needed.
           * If the profile specifies v2 and the server has
             v2.0, v2.1, and v2.2, the match will be v2.2.
           * When an exact major/minor is specified, e.g., v2.0,
             it will only match v2.0.
        """

        match_version = None

        for version in endpoint.versions:
            api_version = self._parse_version(version["id"])
            if profile_version.major != api_version.major:
                continue

            if profile_version.minor <= api_version.minor:
                for link in version["links"]:
                    if link["rel"] == "self":
                        resp_link = link['href']
                        match_version = parse.urlsplit(resp_link).path

            # Only break out of the loop on an exact match,
            # otherwise keep trying.
            if profile_version.minor == api_version.minor:
                break

        if match_version is None:
            raise exceptions.EndpointNotFound(
                "Unable to determine endpoint for %s" % service_type)

        # Make sure the root endpoint has no overlap with match_version
        root_parts = parse.urlsplit(endpoint.uri)
        match_version = match_version.replace(root_parts.path, "", 1)
        match = utils.urljoin(endpoint.uri, match_version)

        # For services that require the project id in the request URI,
        # add them in here.
        if endpoint.needs_project_id:
            match = utils.urljoin(match, endpoint.project_id)

        return match
    def _request(self, path, method, service=None, authenticate=True,
                 **kwargs):
        """Send an HTTP request with the specified characteristics.

        Handle a session level request.

        :param string path: Path relative to authentictor base url.
        :param string method: The http method to use. (eg. 'GET', 'POST').
        :param service: Object that filters service to the authenticator.
        :type service: :class:`~openstack.service_filter.ServiceFilter`
        :param bool authenticate: True if a token should be attached
        :param kwargs: any other parameter that can be passed to transport
                       and authenticator.

        :returns: The response to the request.
        """

        headers = kwargs.setdefault('headers', dict())
        if authenticate:
            token = self.authenticator.get_token(self.transport)
            if token:
                headers['X-Auth-Token'] = token
        if service:
            profile = self.profile.get_preference(service.service_type)
            if profile:
                service = profile.join(service)

        endpoint = self.authenticator.get_endpoint(self.transport, service)
        url = utils.urljoin(endpoint, path)

        return self.transport.request(method, url, **kwargs)
 def create_by_id(cls, session, attrs, resource_id=None, path_args=None):
     url = cls.base_path % path_args
     url = utils.urljoin(url, resource_id)
     body = {cls.resource_key: {attrs['key']: attrs['value']}}
     resp = session.put(url, service=cls.service, json=body).body
     return {'key': resource_id,
             'value': resp[cls.resource_key][resource_id]}
 def get_data_by_id(cls, session, resource_id, path_args=None,
                    include_headers=False):
     url = cls.base_path % path_args
     url = utils.urljoin(url, resource_id)
     resp = session.get(url, service=cls.service).body
     return {'key': resource_id,
             'value': resp[cls.resource_key][resource_id]}
 def force_delete(self, session):
     """Force delete a cluster."""
     body = {'force': True}
     url = utils.urljoin(self.base_path, self.id)
     resp = session.delete(url, json=body)
     self._translate_response(resp, has_body=False)
     return self
Exemple #11
0
    def adopt(self, session, preview=False, **params):
        """Adopt a node for management.

        :param session: A session object used for sending request.
        :param preview: A boolean indicating whether the adoption is a
                        preview. A "preview" does not create the node object.
        :param dict params: A dict providing the details of a node to be
                            adopted.
        """
        if preview:
            path = 'adopt-preview'
            attrs = {
                'identity': params.get('identity'),
                'overrides': params.get('overrides'),
                'type': params.get('type'),
                'snapshot': params.get('snapshot')
            }
        else:
            path = 'adopt'
            attrs = params

        url = utils.urljoin(self.base_path, path)
        resp = session.post(url, json=attrs)
        if preview:
            return resp.json()

        self._translate_response(resp)
        return self
    def get(self, session, requires_id=True):
        request = self._prepare_request(requires_id=requires_id)

        response = session.get(request.uri,
                               endpoint_filter=self.service).json()

        content_type = None
        if self.payload_content_type is not None:
            content_type = self.payload_content_type
        elif "content_types" in response:
            content_type = response["content_types"]["default"]

        # Only try to get the payload if a content type has been explicitly
        # specified or if one was found in the metadata response
        if content_type is not None:
            payload = session.get(utils.urljoin(request.uri, "payload"),
                                  endpoint_filter=self.service,
                                  headers={"Accept": content_type})
            response["payload"] = payload.text

        # We already have the JSON here so don't call into _translate_response
        body = self._filter_component(response, self._body_mapping())
        self._body.attributes.update(body)
        self._body.clean()

        return self
Exemple #13
0
    def create_by_id(cls, session, attrs, resource_id=None, path_args=None):
        '''Overriden version of Resource.create_by_id method.

        Heat stack_create API is asymetric, so this is necessary.
        '''
        if not cls.allow_create:
            raise exceptions.MethodNotSupported('create')

        body = attrs

        if path_args:
            url = cls.base_path % path_args
        else:
            url = cls.base_path

        if resource_id:
            url = utils.urljoin(url, resource_id)
            resp = session.put(url, service=cls.service, json=body).body
        else:
            resp = session.post(url, service=cls.service,
                                json=body).body

        if cls.resource_key:
            resp = resp[cls.resource_key]

        return resp
Exemple #14
0
 def disassociate_flavor_from_service_profile(
         self, session, service_profile_id=None):
     flavor_id = self.id
     url = utils.urljoin(
         self.base_path, flavor_id, 'service_profiles', service_profile_id)
     session.delete(url,)
     return None
    def create_by_id(cls, session, attrs, r_id=None, path_args=None):
        """Create a remote resource from attributes."""
        if not cls.allow_create:
            raise exceptions.MethodNotSupported('create')

        if cls.resource_key:
            body = {cls.resource_key: attrs}
        else:
            body = attrs

        if path_args:
            url = cls.base_path % path_args
        else:
            url = cls.base_path
        if r_id:
            url = utils.urljoin(url, r_id)
            resp = session.put(url, service=cls.service, json=body).body
        else:
            resp = session.post(url, service=cls.service,
                                json=body).body

        if cls.resource_key:
            resp = resp[cls.resource_key]

        return resp
    def upload_image(self, session):
        url = utils.urljoin(self._get_url(resource_id=self.id), "file")

        headers = self.get_headers()
        headers["Content-Type"] = "application/octet-stream"
        headers["Accept"] = ""
        session.put(url, endpoint_filter=self.service, data=self.data, headers=headers)
    def _prepare_request(self, requires_id=True, prepend_key=False):
        """Prepare a request to be sent to the server

        Create operations don't require an ID, but all others do,
        so only try to append an ID when it's needed with
        requires_id. Create and update operations sometimes require
        their bodies to be contained within an dict -- if the
        instance contains a resource_key and prepend_key=True,
        the body will be wrapped in a dict with that key.

        Return a _Request object that contains the constructed URI
        as well a body and headers that are ready to send.
        Only dirty body and header contents will be returned.
        """
        body = self._body.dirty
        if prepend_key and self.resource_key is not None:
            body = {self.resource_key: body}

        headers = self._header.dirty

        uri = self.base_path % self._uri.attributes
        if requires_id:
            id = self._get_id(self)
            if id is None:
                raise exceptions.InvalidRequest(
                    "Request requires an ID but none was found")

            uri = utils.urljoin(uri, id)

        return _Request(uri, body, headers)
Exemple #18
0
    def list_vifs(self, session):
        """List IDs of VIFs attached to the node.

        The exact form of the VIF ID depends on the network interface used by
        the node. In the most common case it is a Network service port
        (NOT a Bare Metal port) ID.

        :param session: The session to use for making this request.
        :type session: :class:`~keystoneauth1.adapter.Adapter`
        :return: List of VIF IDs as strings.
        :raises: :exc:`~openstack.exceptions.NotSupported` if the server
            does not support the VIF API.
        """
        session = self._get_session(session)
        version = self._assert_microversion_for(
            session, 'fetch', _common.VIF_VERSION,
            error_message=("Cannot use VIF attachment API"))

        request = self._prepare_request(requires_id=True)
        request.url = utils.urljoin(request.url, 'vifs')
        response = session.get(
            request.url, headers=request.headers, microversion=version)

        msg = ("Failed to list VIFs attached to bare metal node {node}"
               .format(node=self.id))
        exceptions.raise_from_response(response, error_message=msg)
        return [vif['id'] for vif in response.json()['vifs']]
    def head_data_by_id(cls, session, resource_id, path_args=None):
        """Get a dictionary representing the headers of a remote resource.

        :param session: The session to use for making this request.
        :type session: :class:`~openstack.session.Session`
        :param resource_id: This resource's identifier, if needed by
                            the request. The default is ``None``.
        :param dict path_args: A dictionary of arguments to construct
                               a compound URL.
                               See `How path_args are used`_ for details.

        :return: A ``dict`` containing the headers.
        :raises: :exc:`~openstack.exceptions.MethodNotSupported` if
                 :data:`Resource.allow_head` is not set to ``True``.
        """
        if not cls.allow_head:
            raise exceptions.MethodNotSupported(cls, 'head')

        if path_args:
            url = cls.base_path % path_args
        else:
            url = cls.base_path
        url = utils.urljoin(url, resource_id)

        data = session.head(url, service=cls.service, accept=None).headers

        return {HEADERS: data}
Exemple #20
0
    def test_new_check(self, session, attributes):
        """Test a new check

        This operation causes Rackspace Cloud Monitoring to attempt to run the
        check on the specified monitoring zones and return the results.
        It allows you to test the check parameters in a single step before the
        check is actually created in the system.

        For the `remote.http` this call also includes debug information and the
        response body. Note: Only the first 512KB of the response body is read.
        If the response body is longer, it is truncated to 512KB.

        It requires a valid set of attributes from the checks attributes table.
        For a tutorial on creating some basic checks, see "Create checks" in
        the "Rackspace Cloud Monitoring Getting Started Guide".

        You can copy the results of a test check response and paste it directly
        into a test alarm.

        :param attributes: Valid set of attributes for check creation.
        :param session: The session to use for making this request.
        :type session: :class:`~openstack.session.Session`
        :returns: ``list``
        """
        url = utils.urljoin(self.base_path, self.id, 'test-check')
        return session.post(url, service=self.service, json=attributes).body
Exemple #21
0
    def stub_url(self, method, path=None, base_url=None, **kwargs):
        if not base_url:
            base_url = self.TEST_URL

        if isinstance(path, (list, tuple)):
            base_url = utils.urljoin(base_url, *path)
        elif path:
            base_url = utils.urljoin(base_url, path)

        if 'json' in kwargs:
            json_data = kwargs.pop('json')
            if json_data is not None:
                kwargs['body'] = json.dumps(json_data)
                kwargs['Content-Type'] = 'application/json'

        httpretty.register_uri(method, base_url, **kwargs)
Exemple #22
0
    def update(self, session, preview=False):
        # This overrides the default behavior of resource update because
        # we need to use other endpoint for update preview.
        base_path = None
        if self.name and self.id:
            base_path = '/stacks/%(stack_name)s/%(stack_id)s' % {
                'stack_name': self.name,
                'stack_id': self.id}
        elif self.name or self.id:
            # We have only one of name/id. Do not try to build a stacks/NAME/ID
            # path
            base_path = '/stacks/%(stack_identity)s' % {
                'stack_identity': self.name or self.id}
        request = self._prepare_request(
            prepend_key=False,
            requires_id=False,
            base_path=base_path)

        microversion = self._get_microversion_for(session, 'commit')

        request_url = request.url
        if preview:
            request_url = utils.urljoin(request_url, 'preview')

        response = session.put(
            request_url, json=request.body, headers=request.headers,
            microversion=microversion)

        self.microversion = microversion
        self._translate_response(response, has_body=True)
        return self
Exemple #23
0
 def associate_flavor_with_service_profile(
         self, session, service_profile_id=None):
     flavor_id = self.id
     url = utils.urljoin(self.base_path, flavor_id, 'service_profiles')
     body = {"service_profile": {"id": service_profile_id}}
     resp = session.post(url, json=body)
     return resp.json()
Exemple #24
0
    def set_power_state(self, session, target):
        """Run an action modifying this node's power state.

        This call is asynchronous, it will return success as soon as the Bare
        Metal service acknowledges the request.

        :param session: The session to use for making this request.
        :type session: :class:`~keystoneauth1.adapter.Adapter`
        :param target: Target power state, e.g. "rebooting", "power on".
            See the Bare Metal service documentation for available actions.
        """
        session = self._get_session(session)

        if target.startswith("soft "):
            version = '1.27'
        else:
            version = None

        version = utils.pick_microversion(session, version)

        # TODO(dtantsur): server timeout support
        body = {'target': target}

        request = self._prepare_request(requires_id=True)
        request.url = utils.urljoin(request.url, 'states', 'power')
        response = session.put(
            request.url, json=body,
            headers=request.headers, microversion=version,
            retriable_status_codes=_common.RETRIABLE_STATUS_CODES)

        msg = ("Failed to set power state for bare metal node {node} "
               "to {target}".format(node=self.id, target=target))
        exceptions.raise_from_response(response, error_message=msg)
 def _get_url(cls, path_args=None, resource_id=None):
     if path_args:
         url = cls.base_path % path_args
     else:
         url = cls.base_path
     if resource_id is not None:
         url = utils.urljoin(url, resource_id)
     return url
Exemple #26
0
 def unassign_role_from_user(self, session, user, role):
     """Unassigns a role from a user on a domain"""
     url = utils.urljoin(self.base_path, self.id, 'users',
                         user.id, 'roles', role.id)
     resp = session.delete(url,)
     if resp.status_code == 204:
         return True
     return False
Exemple #27
0
 def validate_group_has_role(self, session, group, role):
     """Validates that a group has a role on a domain"""
     url = utils.urljoin(self.base_path, self.id, 'groups',
                         group.id, 'roles', role.id)
     resp = session.head(url,)
     if resp.status_code == 201:
         return True
     return False
Exemple #28
0
 def assign_role_to_group(self, session, group, role):
     """Assign role to group on domain"""
     url = utils.urljoin(self.base_path, self.id, 'groups',
                         group.id, 'roles', role.id)
     resp = session.put(url,)
     if resp.status_code == 204:
         return True
     return False
Exemple #29
0
 def unassign_role_from_group(self, session, group, role):
     """Unassigns a role from a group on a domain"""
     url = utils.urljoin(self.base_path, self.id, 'groups',
                         group.id, 'roles', role.id)
     resp = session.delete(url,)
     if resp.status_code == 204:
         return True
     return False
Exemple #30
0
 def validate_user_has_role(self, session, user, role):
     """Validates that a user has a role on a domain"""
     url = utils.urljoin(self.base_path, self.id, 'users',
                         user.id, 'roles', role.id)
     resp = session.head(url,)
     if resp.status_code == 201:
         return True
     return False
 def action(self, session, body):
     url = utils.urljoin(self.base_path, self.id, 'action')
     resp = session.put(url, service=self.service, json=body).body
     return resp
Exemple #32
0
 def add_router_to_agent(self, session, router):
     body = {'router_id': router}
     url = utils.urljoin(self.base_path, self.id, 'l3-routers')
     resp = session.post(url, json=body)
     return resp.json()
Exemple #33
0
 def action(self, session, body):
     url = utils.urljoin(self.base_path, self._get_id(self), 'actions')
     resp = session.post(url, json=body)
     return resp.json()
Exemple #34
0
 def remove_router_from_agent(self, session, router):
     body = {'router_id': router}
     url = utils.urljoin(self.base_path, self.id, 'l3-routers', router)
     endpoint_override = self.service.get_endpoint_override()
     session.delete(url, endpoint_filter=self.service, endpoint_override = endpoint_override ,json=body)
Exemple #35
0
 def remove_agent_from_network(self, session, **body):
     network_id = body.get('network_id')
     url = utils.urljoin(self.base_path, self.id, 'dhcp-networks',
                         network_id)
     session.delete(url, endpoint_filter=self.service, json=body)
    def test_with_none(self):
        root = "http://www.example.com"
        leaves = "foo", None

        result = utils.urljoin(root, *leaves)
        self.assertEqual(result, "http://www.example.com/foo/")
Exemple #37
0
 def delete_subports(self, session, subports):
     url = utils.urljoin('/trunks', self.id, 'remove_subports')
     resp = session.put(url, json={'sub_ports': subports})
     exceptions.raise_from_response(resp)
     self._body.attributes.update(resp.json())
     return self
Exemple #38
0
 def _action(self, session, action, body):
     url = utils.urljoin(Service.base_path, action)
     return session.put(url, json=body)
Exemple #39
0
 def _action(self, session, action, body=None):
     """Preform actions given the message body.
     """
     url = utils.urljoin(self.base_path, self.id, action)
     return session.post(url, json=body)
Exemple #40
0
 def type_ops(self, session):
     url = utils.urljoin(self.base_path, self.id, 'ops')
     resp = session.get(url)
     return resp.json()
Exemple #41
0
 def set_tags(self, session, tags):
     url = utils.urljoin('/policies', self.id, 'tags')
     session.put(url, json={'tags': tags})
     self._body.attributes.update({'tags': tags})
     return self
Exemple #42
0
 def abandon(self, session):
     url = utils.urljoin(self.base_path, self.name, self._get_id(self),
                         'abandon')
     resp = session.delete(url)
     return resp.json()
Exemple #43
0
    def set_provision_state(self, session, target, config_drive=None,
                            clean_steps=None, rescue_password=None,
                            wait=False, timeout=None):
        """Run an action modifying this node's provision state.

        This call is asynchronous, it will return success as soon as the Bare
        Metal service acknowledges the request.

        :param session: The session to use for making this request.
        :type session: :class:`~keystoneauth1.adapter.Adapter`
        :param target: Provisioning action, e.g. ``active``, ``provide``.
            See the Bare Metal service documentation for available actions.
        :param config_drive: Config drive to pass to the node, only valid
            for ``active` and ``rebuild`` targets.
        :param clean_steps: Clean steps to execute, only valid for ``clean``
            target.
        :param rescue_password: Password for the rescue operation, only valid
            for ``rescue`` target.
        :param wait: Whether to wait for the target state to be reached.
        :param timeout: Timeout (in seconds) to wait for the target state to be
            reached. If ``None``, wait without timeout.

        :return: This :class:`Node` instance.
        :raises: ValueError if ``config_drive``, ``clean_steps`` or
            ``rescue_password`` are provided with an invalid ``target``.
        """
        session = self._get_session(session)

        if target in _common.PROVISIONING_VERSIONS:
            version = '1.%d' % _common.PROVISIONING_VERSIONS[target]
        else:
            if config_drive and target == 'rebuild':
                version = '1.35'
            else:
                version = None
        version = utils.pick_microversion(session, version)

        body = {'target': target}
        if config_drive:
            if target not in ('active', 'rebuild'):
                raise ValueError('Config drive can only be provided with '
                                 '"active" and "rebuild" targets')
            # Not a typo - ironic accepts "configdrive" (without underscore)
            body['configdrive'] = config_drive

        if clean_steps is not None:
            if target != 'clean':
                raise ValueError('Clean steps can only be provided with '
                                 '"clean" target')
            body['clean_steps'] = clean_steps

        if rescue_password is not None:
            if target != 'rescue':
                raise ValueError('Rescue password can only be provided with '
                                 '"rescue" target')
            body['rescue_password'] = rescue_password

        if wait:
            try:
                expected_state = _common.EXPECTED_STATES[target]
            except KeyError:
                raise ValueError('For target %s the expected state is not '
                                 'known, cannot wait for it' % target)

        request = self._prepare_request(requires_id=True)
        request.url = utils.urljoin(request.url, 'states', 'provision')
        response = session.put(
            request.url, json=body,
            headers=request.headers, microversion=version,
            retriable_status_codes=_common.RETRIABLE_STATUS_CODES)

        msg = ("Failed to set provision state for bare metal node {node} "
               "to {target}".format(node=self.id, target=target))
        exceptions.raise_from_response(response, error_message=msg)

        if wait:
            return self.wait_for_provision_state(session,
                                                 expected_state,
                                                 timeout=timeout)
        else:
            return self.fetch(session)
Exemple #44
0
 def get_metadata(self, session, snapshot_id, key=None):
     if key:
         url = utils.urljoin(self.base_path, snapshot_id, 'metadata', key)
     else:
         url = utils.urljoin(self.base_path, snapshot_id, 'metadata')
     return self._operate_metadata(session.get, url)
Exemple #45
0
 def delete_subports(self, session, subports):
     url = utils.urljoin('/trunks', self.id, 'remove_subports')
     session.put(url, json={'sub_ports': subports})
     self._body.attributes.update({'sub_ports': subports})
     return self
Exemple #46
0
 def action(self, session, body):
     """Preform server actions given the message body."""
     url = utils.urljoin(self.base_path, self.id, 'action')
     resp = session.put(url, service=self.service, json=body).body
     return resp
Exemple #47
0
 def get_subports(self, session):
     url = utils.urljoin('/trunks', self.id, 'get_subports')
     resp = session.get(url)
     exceptions.raise_from_response(resp)
     self._body.attributes.update(resp.json())
     return resp.json()
 def action(self, session, body):
     url = utils.urljoin(self.base_path, self.id, 'actions')
     resp = session.post(url, endpoint_filter=self.service, json=body)
     return resp.json()
Exemple #49
0
 def _action(self, session, action, body):
     url = utils.urljoin(Service.base_path, action)
     return session.put(url, endpoint_filter=self.service, json=body)
 def _action(self, session, action):
     """Call an action on an image ID."""
     url = utils.urljoin(self.base_path, self.id, 'actions', action)
     return session.post(url, endpoint_filter=self.service)
Exemple #51
0
 def add_agent_to_network(self, session, **body):
     url = utils.urljoin(self.base_path, self.id, 'dhcp-networks')
     resp = session.post(url, endpoint_filter=self.service, json=body)
     return resp.json()
Exemple #52
0
 def get_password(self, session):
     """Get the encrypted administrator password."""
     url = utils.urljoin(Server.base_path, self.id, 'os-server-password')
     return session.get(url)
Exemple #53
0
 def _action(self, session, body):
     """Perform stack actions"""
     url = utils.urljoin(self.base_path, self._get_id(self), 'actions')
     resp = session.post(url, json=body)
     return resp.json()
Exemple #54
0
 def add_agent_to_network(self, session, network_id):
     body = {'network_id': network_id}
     url = utils.urljoin(self.base_path, self.id, 'dhcp-networks')
     resp = session.post(url, json=body)
     return resp.json()
 def add_tag(self, session, tag):
     """Add a tag to an image"""
     url = utils.urljoin(self.base_path, self.id, 'tags', tag)
     session.put(url, endpoint_filter=self.service)
Exemple #56
0
 def remove_router_from_agent(self, session, router):
     body = {'router_id': router}
     url = utils.urljoin(self.base_path, self.id, 'l3-routers', router)
     session.delete(url, json=body)
 def remove_tag(self, session, tag):
     """Remove a tag from an image"""
     url = utils.urljoin(self.base_path, self.id, 'tags', tag)
     session.delete(url, endpoint_filter=self.service)
 def upload(self, session):
     """Upload data into an existing image"""
     url = utils.urljoin(self.base_path, self.id, 'file')
     session.put(url, endpoint_filter=self.service, data=self.data,
                 headers={"Content-Type": "application/octet-stream",
                          "Accept": ""})
    def test_strings(self):
        root = "http://www.example.com"
        leaves = "foo", "bar"

        result = utils.urljoin(root, *leaves)
        self.assertEqual(result, "http://www.example.com/foo/bar")
Exemple #60
0
 def remove_agent_from_network(self, session, network_id):
     body = {'network_id': network_id}
     url = utils.urljoin(self.base_path, self.id, 'dhcp-networks',
                         network_id)
     session.delete(url, json=body)