Beispiel #1
0
    def from_database(self, database_manager, user: UserModel,
                      permission: AccessControlPermission):
        """Get all objects from the collection"""
        manager = ObjectManager(database_manager=database_manager)
        dep_object_manager = CmdbObjectManager(
            database_manager=database_manager)

        try:
            _params = self.export_config.parameters
            _result: List[CmdbObject] = manager.iterate(
                filter=_params.filter,
                sort=_params.sort,
                order=_params.order,
                limit=0,
                skip=0,
                user=user,
                permission=permission).results

            self.data = RenderList(
                object_list=_result,
                request_user=user,
                database_manager=database_manager,
                object_manager=dep_object_manager,
                ref_render=True).render_result_list(raw=False)

        except CMDBError as e:
            return abort(400, e)
Beispiel #2
0
def get_objects(params: CollectionParameters, request_user: UserModel):

    manager = ObjectManager(database_manager=current_app.database_manager)
    view = params.optional.get('view', 'native')

    if _fetch_only_active_objs():
        if isinstance(params.filter, dict):
            filter_ = params.filter
            params.filter = [{'$match': filter_}]
            params.filter.append({'$match': {'active': {"$eq": True}}})
        elif isinstance(params.filter, list):
            params.filter.append({'$match': {'active': {"$eq": True}}})

    try:
        iteration_result: IterationResult[CmdbObject] = manager.iterate(
            filter=params.filter,
            limit=params.limit,
            skip=params.skip,
            sort=params.sort,
            order=params.order,
            user=request_user,
            permission=AccessControlPermission.READ)

        if view == 'native':
            object_list: List[dict] = [
                object_.__dict__ for object_ in iteration_result.results
            ]
            api_response = GetMultiResponse(object_list,
                                            total=iteration_result.total,
                                            params=params,
                                            url=request.url,
                                            model=CmdbObject.MODEL,
                                            body=request.method == 'HEAD')
        elif view == 'render':
            rendered_list = RenderList(
                object_list=iteration_result.results,
                request_user=request_user,
                database_manager=current_app.database_manager,
                object_manager=object_manager,
                ref_render=True).render_result_list(raw=True)
            api_response = GetMultiResponse(rendered_list,
                                            total=iteration_result.total,
                                            params=params,
                                            url=request.url,
                                            model=Model('RenderResult'),
                                            body=request.method == 'HEAD')
        else:
            return abort(401, 'No possible view parameter')

    except ManagerIterationError as err:
        return abort(400, err.message)
    except ManagerGetError as err:
        return abort(404, err.message)
    return api_response.make_response()
Beispiel #3
0
def get_unstructured_objects(public_id: int, request_user: UserModel):
    """
    HTTP `GET`/`HEAD` route for a multi resources which are not formatted according the type structure.
    Args:
        public_id (int): Public ID of the type.
    Raises:
        ManagerGetError: When the selected type does not exists or the objects could not be loaded.
    Returns:
        GetListResponse: Which includes the json data of multiple objects.
    """
    manager = ObjectManager(database_manager=current_app.database_manager)

    try:
        type_instance: TypeModel = type_manager.get(public_id=public_id)
        objects: List[CmdbObject] = manager.iterate({
            'type_id': public_id
        },
                                                    limit=0,
                                                    skip=0,
                                                    sort='public_id',
                                                    order=1,
                                                    user=request_user).results
    except ManagerGetError as err:
        return abort(400, err.message)
    type_fields = sorted([field.get('name') for field in type_instance.fields])
    unstructured: List[dict] = []
    for object_ in objects:
        object_fields = [field.get('name') for field in object_.fields]
        if sorted(object_fields) != type_fields:
            unstructured.append(object_.__dict__)

    api_response = GetListResponse(unstructured,
                                   url=request.url,
                                   model=CmdbObject.MODEL,
                                   body=request.method == 'HEAD')
    return api_response.make_response()
Beispiel #4
0
def update_unstructured_objects(public_id: int, request_user: UserModel):
    """
    HTTP `PUT`/`PATCH` route for a multi resources which will be formatted based on the TypeModel
    Args:
        public_id (int): Public ID of the type.
    Raises:
        ManagerGetError: When the type with the `public_id` was not found.
        ManagerUpdateError: When something went wrong during the update.
    Returns:
        UpdateMultiResponse: Which includes the json data of multiple updated objects.
    """
    manager = ObjectManager(database_manager=current_app.database_manager)

    try:
        update_type_instance = type_manager.get(public_id)
        type_fields = update_type_instance.fields
        objects_by_type = manager.iterate({
            'type_id': public_id
        },
                                          limit=0,
                                          skip=0,
                                          sort='public_id',
                                          order=1,
                                          user=request_user).results

        for obj in objects_by_type:
            incorrect = []
            correct = []
            obj_fields = obj.get_all_fields()
            for t_field in type_fields:
                name = t_field["name"]
                for field in obj_fields:
                    if name == field["name"]:
                        correct.append(field["name"])
                    else:
                        incorrect.append(field["name"])
            removed_type_fields = [
                item for item in incorrect if not item in correct
            ]
            for field in removed_type_fields:
                manager.update_many(
                    query={'public_id': obj.public_id},
                    update={'$pull': {
                        'fields': {
                            "name": field
                        }
                    }})

        objects_by_type = manager.iterate({
            'type_id': public_id
        },
                                          limit=0,
                                          skip=0,
                                          sort='public_id',
                                          order=1,
                                          user=request_user).results
        for obj in objects_by_type:
            for t_field in type_fields:
                name = t_field["name"]
                value = None
                if [
                        item for item in obj.get_all_fields()
                        if item["name"] == name
                ]:
                    continue
                if "value" in t_field:
                    value = t_field["value"]

                manager.update_many(query={'public_id': obj.public_id},
                                    update={
                                        '$addToSet': {
                                            'fields': {
                                                "name": name,
                                                "value": value
                                            }
                                        }
                                    })

    except ManagerUpdateError as err:
        return abort(400, err.message)

    api_response = UpdateMultiResponse([],
                                       url=request.url,
                                       model=CmdbObject.MODEL)

    return api_response.make_response()