Exemple #1
0
    def get_all_design_documents(
            self,  # type: ViewIndexManager
            namespace,  # type: DesignDocumentNamespace
            *options,  # type: GetAllDesignDocumentsOptions
            **kwargs):
        # type: (...) -> Iterable[DesignDocument]
        """
        Fetches all design documents from the server.

        :param DesignDocumentNamespace namespace: indicates whether the user wants to get production documents (PRODUCTION) or development documents (DEVELOPMENT).
        :param GetAllDesignDocumentsOptions options: Options for get all design documents request.
        :param Any kwargs: Override corresponding value in options.
        :return: An iterable of DesignDocument.
        """

        args = forward_args(kwargs, *options)
        args['path'] = "pools/default/buckets/{bucketname}/ddocs".format(
            bucketname=self._bucketname)
        response = self._http_request(**args).value

        def matches(row):
            return namespace == DesignDocumentNamespace(
                row['doc']['meta']['id'].startswith("_design/dev_"))

        rows = [r for r in response['rows'] if matches(r)]
        return list(
            map(
                lambda x: DesignDocument.from_json(x['doc']['meta']['id'], **x[
                    'doc']['json']), rows))
    def get_user(
            self,
            username,  # type: str
            *options,  # type: GetUserOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> UserAndMetadata
        """
        Gets a user.

        :param str username: ID of the user.
        :param options: GetUserOptions
        :param Any kwargs: override corresponding values in the options.

        :returns: An instance of UserAndMetadata.

        :raises: UserNotFoundException
        :raises: InvalidArgumentsException
        Any exceptions raised by the underlying platform
        """

        # Implementation Notes
        # When parsing the "get" and "getAll" responses,
        # take care to distinguish between roles assigned directly to the user (role origin with type="user") and
        # roles inherited from groups (role origin with type="group" and name=<group name>).
        # If the server response does not include an "origins" field for a role,
        # then it was generated by a server version prior to 6.5 and the SDK MUST treat the role as if it had a
        # single origin of type="user".
        final_args = forward_args(kwargs, *options)
        domain = final_args.pop("domain_name", "local")
        timeout = final_args.pop("timeout", None)
        return UserAndMetadata.load_from_server(
            self._admin_bucket.user_get(username, domain, timeout).value)
    def upsert_group(
            self,
            group,  # type: Group
            *options,  # type: UpsertGroupOptions
            **kwargs  # type: Any
    ):
        """
        Creates or updates a group.

        :param Group group: the new version of the group.
        :param options: UpsertGroupOptions
        :param Any kwargs: override corresponding values in the options.

        :raises: InvalidArgumentsException
        Any exceptions raised by the underlying platform
        """
        # This endpoint accepts application/x-www-form-urlencoded and requires the data be sent as form data.
        # The name/id should not be included in the form data.
        # Roles should be a comma separated list of strings.
        # If, only if, the role contains a bucket name then the rolename should be suffixed
        # with[<bucket_name>] e.g. bucket_full_access[default],security_admin.

        final_args = forward_args(kwargs, *options)
        final_args.update({
            k: v
            for k, v in group.as_dict.items()
            if k in {'roles', 'description', 'ldap_group_reference'}
        })
        self._admin_bucket.group_upsert(group.name, **final_args)
Exemple #4
0
    def upsert_design_document(
            self,  # type: ViewIndexManager
            design_doc_data,  # type: DesignDocument
            namespace,  # type: DesignDocumentNamespace
            *options,  # type: UpsertDesignDocumentOptions
            **kwargs):
        # type: (...) -> None
        """
        Updates, or inserts, a design document.

        :param DesignDocument design_doc_data: the data to use to create the design document
        :param DesignDocumentNamespace namespace: indicates whether the user wants to upsert the document to the
               production namespace (PRODUCTION) or development namespace (DEVELOPMENT).
        :param UpsertDesignDocumentOptions options: Options for request to upsert design doc.
        :param Any kwargs: Override corresponding value in options.
        :return:
        """
        name = namespace.prefix(design_doc_data.name)
        ddoc = json.dumps(design_doc_data.as_dict(namespace))

        args = forward_args(kwargs, *options)
        args['path'] = "_design/{name}".format(name=name,
                                               bucketname=self._bucketname)
        args['method'] = _LCB.LCB_HTTP_METHOD_PUT
        args['post_data'] = ddoc
        self._http_request(False, **args)
    def get_group(
            self,
            group_name,  # type: str
            *options,  # type: GetGroupOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> Group
        """
        Gets a group.

        :param str group_name: name of the group to get.
        :param options: GetRolesOptions
        :param Any kwargs: override corresponding values in the options.

        :return: An instance of Group.

        :raises: GroupNotFoundException
        :raises: InvalidArgumentsException
        Any exceptions raised by the underlying platform
        """

        final_args = forward_args(kwargs, *options)
        timeout = final_args.get("timeout", None)
        return Group.load_from_server(
            self._admin_bucket.group_get(group_name, timeout).value)
Exemple #6
0
    def get_user(
            self,  # type: UserManager
            username,  # type: str
            domain_name=AuthDomain.Local,  # type: AuthDomain
            *options,  # type: GetUserOptions
            **kwargs):
        # type: (...)->UserAndMetadata
        """
        Gets a user.

        :param str username: ID of the user.
        :param AuthDomain domain_name: name of the user domain. Defaults to local.
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.

        :returns: An instance of UserAndMetadata.

        :raises: UserNotFoundException
        :raises: InvalidArgumentsException
        Any exceptions raised by the underlying platform
        """

        # Implementation Notes
        # When parsing the "get" and "getAll" responses,
        # take care to distinguish between roles assigned directly to the user (role origin with type="user") and
        # roles inherited from groups (role origin with type="group" and name=<group name>).
        # If the server response does not include an "origins" field for a role,
        # then it was generated by a server version prior to 6.5 and the SDK MUST treat the role as if it had a
        # single origin of type="user".
        return RawUserAndMetadata(
            self._admin_bucket.user_get(domain_name, username,
                                        **forward_args(kwargs, *options)))
    def get_all_indexes(
            self,  # type: QueryIndexManager
            bucket_name,  # type: str
            *options,  # type: GetAllQueryIndexOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> List[QueryIndex]
        """
        Fetches all indexes from the server.

        :param str bucket_name: the name of the bucket.
        :param GetAllQueryIndexOptions options: Options to use for getting all indexes.
        :param Any kwargs: Override corresponding value in options.
        :return: A list of QueryIndex objects.
        :raises: InvalidArgumentsException
        """
        # N1QL
        # SELECT idx.* FROM system:indexes AS idx
        # WHERE keyspace_id = "bucket_name"
        # ORDER BY is_primary DESC, name ASC
        info = N1qlIndex()
        info.keyspace = bucket_name
        response = IxmgmtRequest(self._admin_bucket, 'list', info,
                                 **forward_args(kwargs, *options)).execute()
        return list(map(QueryIndex.from_n1qlindex, response))
Exemple #8
0
    def get_design_document(
            self,  # type: ViewIndexManager
            design_doc_name,  # type: str
            namespace,  # type: DesignDocumentNamespace
            *options,  # type: GetDesignDocumentOptions
            **kwargs):
        # type: (...)->DesignDocument
        """
        Fetches a design document from the server if it exists.

        :param str design_doc_name: the name of the design document.
        :param DesignDocumentNamespace namespace: PRODUCTION if the user is requesting a document from the production namespace
        or DEVELOPMENT if from the development namespace.
        :param GetDesignDocumentOptions options:  Options to use when requesting design document.
        :param Any kwargs: Override corresponding value in options.
        :return: An instance of DesignDocument.

        :raises: DesignDocumentNotFoundException
        """
        args = forward_args(kwargs, *options)
        name = namespace.prefix(design_doc_name)
        args['path'] = "_design/" + name

        response = self._http_request(False, **args)
        return DesignDocument.from_json(name, **response.value)
    def upsert_user(
            self,
            user,  # type: User
            *options,  # type: UpsertUserOptions
            **kwargs  # type: Any
    ):
        """
        Creates or updates a user.

        :param User user: the new version of the user.
        :param options: UpsertUserOptions
        :param Any kwargs: override corresponding values in the options.

        :raises: InvalidArgumentsException
        """

        # Implementation Notes
        #
        # When building the PUT request to send to the REST endpoint, implementations MUST omit the "password" property
        # if it is not present in the given User domain object (so that the password is only changed if the calling code
        # provided a new password).

        final_args = forward_args(kwargs, *options)
        domain = final_args.pop("domain_name", "local")
        final_args.update({
            k: v
            for k, v in user.as_dict.items()
            if k in {'password', 'roles', 'name', 'groups'}
        })
        self._admin_bucket.user_upsert(user.username, domain, **final_args)
    def create_collection(
            self,  # type: CollectionManager
            collection,  # type: CollectionSpec
            *options,  # type: CreateCollectionOptions
            **kwargs  # type: Any
    ):
        """
        Creates a new collection.

        :param CollectionSpec collection: specification of the collection.
        :param CreateCollectionOptions options:  options (currently just timeout).
        :param kwargs: keyword version of 'options'
        :return:
        :raises: InvalidArgumentsException
        :raises: CollectionAlreadyExistsException
        :raises: ScopeNotFoundException
        """

        params = {'name': collection.name}
        if collection.max_ttl:
            params['maxTTL'] = int(collection.max_ttl.total_seconds())

        form = mk_formstr(params)
        kwargs.update({
            'path':
            '{}/{}/collections'.format(self.base_path, collection.scope_name),
            'method':
            'POST',
            'content_type':
            'application/x-www-form-urlencoded',
            'content':
            form
        })
        return self._admin_bucket.http_request(
            **forward_args(kwargs, *options))
    def get_all_scopes(
            self,  # type: CollectionManager
            *options,  # type: GetAllScopesOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> Iterable[ScopeSpec]
        """
        Gets all scopes. This will fetch a manifest and then pull the scopes out of it.

        :param GetAllScopesOptions options: (currently just timeout).
        :param kwargs: keyword version of options
        :return: An Iterable[ScopeSpec] containing all scopes in the associated bucket.
        """
        kwargs.update({'path': self.base_path, 'method': 'GET'})
        response = self._admin_bucket.http_request(
            **forward_args(kwargs, *options))
        # now lets turn the response into a list of ScopeSpec...
        # the response looks like:
        # {'uid': '0', 'scopes': [{'name': '_default', 'uid': '0', 'collections': [{'name': '_default', 'uid': '0'}]}]}
        retval = list()
        for s in response.value['scopes']:
            scope = ScopeSpec(s['name'], list())
            for c in s['collections']:
                scope.collections.append(CollectionSpec(c['name'], scope.name))
            retval.append(scope)
        return retval
    def create_scope(
            self,  # type: CollectionManager
            scope_name,  # type: str
            *options,  # type: CreateScopeOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> None
        """
        Creates a new scope.

        :param str scope_name: name of the scope.
        :param CreateScopeOptions options: options (currently just timeout).
        :param kwargs: keyword version of `options`
        :return:

        :raises: InvalidArgumentsException
        Any exceptions raised by the underlying platform
        Uri
        POST http://localhost:8091/pools/default/buckets/<bucket>/collections -d name=<scope_name>
        """
        params = {'name': scope_name}

        form = mk_formstr(params)
        kwargs.update({
            'path': self.base_path,
            'method': 'POST',
            'content_type': 'application/x-www-form-urlencoded',
            'content': form
        })

        self._admin_bucket.http_request(**forward_args(kwargs, *options))
Exemple #13
0
    def upsert_group(
            self,  # type: UserManager
            group,  # type: Group
            *options,  # type: UpsertGroupOptions
            **kwargs):
        """
        Add or replace a group.

        :warning: Does not appear to work correctly yet - tracked here: https://issues.couchbase.com/browse/PYCBC-667

        :param Group group: the new version of the group.
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.
        :raises: InvalidArgumentsException
        """
        # This endpoint accepts application/x-www-form-urlencoded and requires the data be sent as form data.
        # The name/id should not be included in the form data.
        # Roles should be a comma separated list of strings.
        # If, only if, the role contains a bucket name then the rolename should be suffixed
        # with[<bucket_name>] e.g. bucket_full_access[default],security_admin.

        group_dict = group.as_dict()
        form_data = mk_formstr(group_dict)
        self._admin_bucket.http_request(
            "/settings/rbac/groups/{}".format(group.name), 'PUT', form_data,
            **forward_args(kwargs, *options))
 def _drop_index(self, bucket_name, index_name, *options, **kwargs):
     info = BucketManager._mk_index_def(bucket_name,
                                        index_name,
                                        primary=kwargs.pop(
                                            'primary', False))
     final_args = {
         k.replace('ignore_if_not_exists', 'ignore_missing'): v
         for k, v in forward_args(kwargs, *options).items()
     }
     IxmgmtRequest(self._admin_bucket, 'drop', info, **final_args).execute()
 def _create_index(self, bucket_name, fields, index_name, *options,
                   **kwargs):
     final_args = {
         k.replace('deferred',
                   'defer').replace('condition',
                                    'cond').replace('ignore_if_exists',
                                                    'ignore_exists'): v
         for k, v in forward_args(kwargs, *options).items()
     }
     self._n1ql_index_create(bucket_name,
                             index_name,
                             fields=fields,
                             **final_args)
Exemple #16
0
    def get_all_groups(
            self,  # type: UserManager
            *options,  # type: GetAllGroupsOptions
            **kwargs):
        # type: (...)->Iterable[Group]
        """
        Get all groups.

        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.
        :returns: An iterable collection of Group.
        """
        groups = self._admin_bucket.http_request(
            "/settings/rbac/groups/", **forward_args(kwargs, *options))
        return list(map(Group.from_json, groups.value))
 def _create_index(self, bucket_name, fields, index_name, *options,
                   **kwargs):
     final_args = {
         k.replace('deferred',
                   'defer').replace('condition',
                                    'cond').replace('ignore_if_exists',
                                                    'ignore_exists'): v
         for k, v in forward_args(kwargs, *options).items()
     }
     try:
         self._n1ql_index_create(bucket_name,
                                 index_name,
                                 fields=fields,
                                 **final_args)
     except QueryIndexAlreadyExistsException:
         if not final_args.get('ignore_exists', False):
             raise
    def build_deferred_indexes(
            self,  # type: QueryIndexManager
            bucket_name,  # type: str
            *options,  # type: BuildDeferredQueryIndexOptions
            **kwargs):
        """
        Build Deferred builds all indexes which are currently in deferred state.

        :param str bucket_name: name of the bucket.
        :param BuildDeferredQueryIndexOptions options: Options for building deferred indexes.
        :param Any kwargs: Override corresponding value in options.
        :raise: InvalidArgumentsException

        """
        final_args = forward_args(kwargs, *options)
        return BucketManager._n1ql_index_build_deferred(
            bucket_name, self._admin_bucket, **final_args)
    def drop_index(
            self,  # type: QueryIndexManager
            bucket_name,  # type: str
            index_name,  # type: str
            *options,  # type: DropQueryIndexOptions
            **kwargs):
        """
        Drops an index.

        :param str bucket_name: name of the bucket.
        :param str index_name: name of the index.
        :param DropQueryIndexOptions options: Options for dropping index.
        :param Any kwargs: Override corresponding value in options.
        :raises: QueryIndexNotFoundException
        :raises: InvalidArgumentsException
        """
        final_args = forward_args(kwargs, *options)
        self._drop_index(bucket_name, index_name, **final_args)
Exemple #20
0
    def get_roles(
            self,  # type: UserManager
            *options,  # type: GetRolesOptions
            **kwargs):
        # type: (...)->Iterable[RoleAndDescription]
        """
        Returns the roles supported by the server.

        :param options: misc options
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.
        :return: An iterable collection of RoleAndDescription.
        """
        return list(
            map(
                lambda x: RoleAndDescription.of(**x),
                self._admin_bucket.http_request(
                    "/settings/rbac/roles/", **forward_args(kwargs,
                                                            *options)).value))
Exemple #21
0
    def drop_group(
            self,  # type: UserManager
            group_name,  # type: str
            *options,  # type: DropGroupOptions
            **kwargs):
        """
        Removes a group.

        :param str group_name: name of the group. 
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.

        :raises: GroupNotFoundException
        :raises: InvalidArgumentsException
        """
        self._admin_bucket.http_request(
            "/settings/rbac/groups/{}".format(group_name),
            method='DELETE',
            **forward_args(kwargs, *options))
Exemple #22
0
    def drop_scope(
            self,  # type: CollectionManager
            scope_name,  # type: str
            *options,  # type: DropScopeOptions
            **kwargs  # type: Any
    ):
        """
        Removes a scope.

        :param str scope_name: name of the scope
        :param DropScopeOptions options: (currently just timeout)
        :param kwargs: keyword version of `options`

        :raises: ScopeNotFoundException
        """
        path = "pools/default/buckets/{}/collections/{}".format(
            self.bucket_name, scope_name)
        kwargs.update({'path': path, 'method': 'DELETE'})
        self._admin_bucket.http_request(**forward_args(kwargs, *options))
    def get_all_groups(
            self,
            *options,  # type: GetAllGroupsOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> Iterable[Group]
        """
        Get all groups.

        :param timedelta timeout: the time allowed for the operation to be terminated. This is controlled by the client.

        :returns: An iterable collection of Group.
        """

        final_args = forward_args(kwargs, *options)
        timeout = final_args.get("timeout", None)
        return list(
            map(lambda g: Group.load_from_server(g),
                self._admin_bucket.groups_get(timeout).value))
Exemple #24
0
    def get_group(
            self,  # type: UserManager
            group_name,  # type: str
            *options,  # type: GetGroupOptions
            **kwargs):
        # type: (...)->Group
        """
        Get info about the named group.

        :param str group_name: name of the group to get.
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.
        :return: An instance of Group.
        :raises: GroupNotFoundException
        :raises: InvalidArgumentsException
        """
        return Group.from_json(
            self._admin_bucket.http_request(
                "/settings/rbac/groups/{}".format(group_name),
                **forward_args(kwargs, *options)).value)
Exemple #25
0
    def drop_user(
            self,  # type: UserManager
            user_name,  # type: str
            domain=AuthDomain.Local,  # type: AuthDomain
            *options,  # type: DropUserOptions
            **kwargs):
        """
        Removes a user.

        :param str user_name: ID of the user.
        :param AuthDomain domain: name of the user domain. Defaults to local.
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.
        :return:

        :raises: UserNotFoundException
        :raises: InvalidArgumentsException
        """
        final_args = forward_args(kwargs, *options)
        self._admin_bucket.user_remove(domain, user_name, **final_args)
    def watch_indexes(
            self,  # type: QueryIndexManager
            bucket_name,  # type: str
            index_names,  # type: Iterable[str]
            *options,  # type: WatchQueryIndexOptions
            **kwargs):
        """
        Watch polls indexes until they are online.

        :param str bucket_name: name of the bucket.
        :param Iterable[str] index_names: name(s) of the index(es).
        :param WatchQueryIndexOptions options: Options for request to watch indexes.
        :param Any kwargs: Override corresponding valud in options.
        :raises: QueryIndexNotFoundException
        :raises: InvalidArgumentsException
        """
        final_args = forward_args(kwargs, *options)
        BucketManager(self._admin_bucket).n1ql_index_watch(
            index_names, **final_args)
    def drop_group(
            self,
            group_name,  # type: str
            *options,  # type: DropGroupOptions
            **kwargs  # type: Any
    ):
        """
        Removes a group.

        :param str group_name: name of the group.
        :param options: DropGroupOptions
        :param Any kwargs: override corresponding values in the options.

        :raises: GroupNotFoundException
        :raises: InvalidArgumentsException
        """
        self._admin_bucket.http_request(
            "/settings/rbac/groups/{}".format(group_name),
            method='DELETE',
            **forward_args(kwargs, *options))
    def get_all_users(
            self,
            *options,  # type: GetAllUsersOptions
            **kwargs  # type: Any
    ):
        # type: (...) -> Iterable[UserAndMetadata]
        """
        Gets all users.

        :param options: GetAllUsersOptions
        :param Any kwargs: override corresponding values in the options.

        :return: An iterable collection of UserAndMetadata.
        """
        final_args = forward_args(kwargs, *options)
        domain = final_args.get("domain_name", "local")
        timeout = final_args.get("timeout", None)
        return list(
            map(lambda u: UserAndMetadata.load_from_server(u),
                self._admin_bucket.users_get(domain, timeout).value))
    def watch_indexes(
            self,  # type: QueryIndexManager
            bucket_name,  # type: str
            index_names,  # type: Iterable[str]
            *options,  # type: WatchQueryIndexOptions
            **kwargs):
        """
        Watch polls indexes until they are online.

        :param str bucket_name: name of the bucket.
        :param Iteralbe[str] index_names: name(s) of the index(es).
        :param Duration timeout: the time allowed for the operation to be terminated. This is controlled by the client.
        :param: bool watch_primary: whether or not to watch the primary index.

        :raises: QueryIndexNotFoundException
        :raises: InvalidArgumentsException
        """
        final_args = forward_args(kwargs, *options)
        BucketManager(self._admin_bucket).n1ql_index_watch(
            index_names, **final_args)
    def drop_primary_index(
            self,  # type: QueryIndexManager
            bucket_name,  # type: str
            *options,  # type: DropPrimaryQueryIndexOptions
            **kwargs):
        """
        Drops a primary index.

        :param bucket_name: name of the bucket.
        :param index_name:  name of the index.
        :param ignore_if_not_exists: Don't error/throw if the index does not exist.
        :param timeout:  the time allowed for the operation to be terminated. This is controlled by the client.

        :raises: QueryIndexNotFoundException
        :raises: InvalidArgumentsException
        """
        final_args = forward_args(kwargs, *options)
        final_args['primary'] = True
        index_name = final_args.pop("index_name", "")
        self._drop_index(bucket_name, index_name, **final_args)