class ObjectLinkManager(ManagerBase): def __init__(self, database_manager: DatabaseManagerMongo): self.query_builder = ObjectQueryBuilder() self.object_manager = CmdbObjectManager( database_manager) # TODO: Replace when object api is updated super(ObjectLinkManager, self).__init__(ObjectLinkModel.COLLECTION, database_manager=database_manager) def get(self, public_id: Union[PublicID, int], user: UserModel = None, permission: AccessControlPermission = None) -> ObjectLinkModel: """ Get a single link by its id. Args: public_id (int): ID of the link. user: request user permission: acl permission Returns: ObjectLinkModel: Instance of CmdbLink with data. """ cursor_result = self._get(self.collection, filter={'public_id': public_id}, limit=1) for resource_result in cursor_result.limit(-1): link = ObjectLinkModel.from_data(resource_result) if user and permission: self.object_manager.get_object(public_id=link.primary, user=user, permission=permission) self.object_manager.get_object(public_id=link.secondary, user=user, permission=permission) return link raise ManagerGetError( f'ObjectLinkModel with ID: {public_id} not found!') def iterate(self, filter: Union[List[dict], dict], limit: int, skip: int, sort: str, order: int, user: UserModel = None, permission: AccessControlPermission = None, *args, **kwargs) \ -> IterationResult[ObjectLinkModel]: """ Iterate over a collection where the public id exists. """ try: query: Pipeline = self.query_builder.build(filter=filter, limit=limit, skip=skip, sort=sort, order=order) count_query: Pipeline = self.query_builder.count( filter=filter, user=user, permission=permission) aggregation_result = list(self._aggregate(self.collection, query)) total_cursor = self._aggregate(self.collection, count_query) total = 0 while total_cursor.alive: total = next(total_cursor)['total'] except ManagerGetError as err: raise ManagerIterationError(err=err) iteration_result: IterationResult[ObjectLinkModel] = IterationResult( aggregation_result, total) iteration_result.convert_to(ObjectLinkModel) return iteration_result def insert( self, link: Union[dict, ObjectLinkModel], user: UserModel = None, permission: AccessControlPermission = AccessControlPermission.CREATE ) -> PublicID: """ Insert a single link into the system. Args: link (ObjectLinkModel): Raw data of the link. user: request user permission: acl permission Notes: If no public id was given, the database manager will auto insert the next available ID. Returns: int: The Public ID of the new inserted link """ if isinstance(link, ObjectLinkModel): link = ObjectLinkModel.to_json(link) if 'creation_time' not in link: link['creation_time'] = datetime.now(timezone.utc) if user and permission: self.object_manager.get_object(public_id=link['primary'], user=user, permission=permission) self.object_manager.get_object(public_id=link['secondary'], user=user, permission=permission) return self._insert(self.collection, resource=link) def update(self, public_id: PublicID, link: Union[ObjectLinkModel, dict]): raise NotImplementedError def delete( self, public_id: PublicID, user: UserModel = None, permission: AccessControlPermission = AccessControlPermission.DELETE ) -> ObjectLinkModel: """ Delete a existing link by its PublicID. Args: public_id (int): PublicID of the link in the system. user: request user permission: acl permission Returns: ObjectLinkModel: The deleted link as its model. """ link: ObjectLinkModel = self.get(public_id=public_id) if user and permission: self.object_manager.get_object(public_id=link.primary, user=user, permission=permission) self.object_manager.get_object(public_id=link.secondary, user=user, permission=permission) delete_result = self._delete(self.collection, filter={'public_id': public_id}) if delete_result.deleted_count == 0: raise ManagerDeleteError(err='No link matched this public id') return link
class ExportdManagerBase(ExportdJobManagement): def __init__(self, job: ExportdJob): self.job = job self.exportvars = self.__get_exportvars() self.destinations = self.__get__destinations() scr = SystemConfigReader() database_manager = DatabaseManagerMongo( **scr.get_all_values_from_section('Database')) self.__object_manager = CmdbObjectManager( database_manager=database_manager) self.log_manager = ExportdLogManager(database_manager=database_manager) self.sources = self.__get_sources() super(ExportdManagerBase, self).__init__(database_manager) def __get_exportvars(self): exportvars = {} for variable in self.job.get_variables(): exportvars.update({ variable["name"]: ExportVariable(variable["name"], variable["default"], variable["templates"]) }) return exportvars def __get_sources(self): sources = [] sources.append( ExportSource(self.job, object_manager=self.__object_manager)) return sources def __get__destinations(self): destinations = [] destination_params = {} for destination in self.job.get_destinations(): for param in destination["parameter"]: destination_params.update({param["name"]: param["value"]}) export_destination = ExportDestination( "cmdb.exportd.externals.external_systems.{}".format( destination["className"]), destination_params, self.exportvars) destinations.append(export_destination) return destinations def execute(self, event, user_id: int, user_name: str, log_flag: bool = True) -> ExportdHeader: # get cmdb objects from all sources cmdb_objects = set() exportd_header = ExportdHeader() for source in self.sources: cmdb_objects.update(source.get_objects()) # for every destination: do export for destination in self.destinations: external_system = destination.get_external_system() external_system.prepare_export() for cmdb_object in cmdb_objects: # setup objectdata for use in ExportVariable templates template_data = self.__get_objectdata(cmdb_object, 3) external_system.add_object(cmdb_object, template_data) exportd_header = external_system.finish_export() if log_flag: try: log_params = { 'job_id': self.job.get_public_id(), 'state': True, 'user_id': user_id, 'user_name': user_name, 'event': event.get_type(), 'message': external_system.msg_string, } self.log_manager.insert_log( action=LogAction.EXECUTE, log_type=ExportdJobLog.__name__, **log_params) except LogManagerInsertError as err: LOGGER.error(err) return exportd_header def __get_objectdata(self, cmdb_object, iteration): data = {} data["id"] = cmdb_object.object_information['object_id'] data["fields"] = {} for field in cmdb_object.fields: try: field_name = field["name"] if field["type"] == "ref" and field["value"] and iteration > 0: # resolve type iteration = iteration - 1 current_object = self.__object_manager.get_object( field["value"]) type_instance = self.__object_manager.get_type( current_object.get_type_id()) cmdb_render_object = CmdbRender( object_instance=current_object, type_instance=type_instance, render_user=None) data["fields"][field_name] = self.__get_objectdata( cmdb_render_object.result(), iteration) else: data["fields"][field_name] = field["value"] except Exception as err: LOGGER.error(err) return data