当前位置: 首页>>代码示例>>Python>>正文


Python IGUIDManager.getObject方法代码示例

本文整理汇总了Python中Products.ZenUtils.guid.interfaces.IGUIDManager.getObject方法的典型用法代码示例。如果您正苦于以下问题:Python IGUIDManager.getObject方法的具体用法?Python IGUIDManager.getObject怎么用?Python IGUIDManager.getObject使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Products.ZenUtils.guid.interfaces.IGUIDManager的用法示例。


在下文中一共展示了IGUIDManager.getObject方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: impacts_for

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
def impacts_for(thing):
    '''
    Return a two element tuple.

    First element is a list of object ids impacted by thing. Second element is
    a list of object ids impacting thing.
    '''
    from ZenPacks.zenoss.Impact.impactd.interfaces \
        import IRelationshipDataProvider

    impacted_by = []
    impacting = []

    guid_manager = IGUIDManager(thing.getDmd())
    for subscriber in subscribers([thing], IRelationshipDataProvider):
        for edge in subscriber.getEdges():
            source = guid_manager.getObject(edge.source)
            impacted = guid_manager.getObject(edge.impacted)

            if source.id == thing.id:
                impacted_by.append(impacted.id)
            elif impacted.id == thing.id:
                impacting.append(source.id)

    return (impacted_by, impacting)
开发者ID:zenoss,项目名称:ZenPacks.zenoss.OpenStackInfrastructure,代码行数:27,代码来源:test_impact.py

示例2: getDeviceDashboard

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
    def getDeviceDashboard(self):
        """return device info for bad device to dashboard"""
        zep = getFacade('zep')
        manager = IGUIDManager(self.context.dmd)
        deviceSeverities = zep.getDeviceIssuesDict()
        zem = self.context.dmd.ZenEventManager

        devdata = []
        for uuid in deviceSeverities.keys():
            dev = manager.getObject(uuid)
            if dev and isinstance(dev, Device):
                if (not zem.checkRemotePerm(ZEN_VIEW, dev)
                    or dev.productionState < zem.prodStateDashboardThresh
                    or dev.priority < zem.priorityDashboardThresh):
                    continue
                alink = dev.getPrettyLink()
                try:
                    severities = deviceSeverities[uuid]
                    severities = dict((zep.getSeverityName(sev).lower(), counts) for (sev, counts) in severities.iteritems())
                    pill = getEventPillME(dev, severities=severities)
                except ServiceException:
                    continue
                evts = [alink,pill]
                devdata.append((evts, severities))
        devdata.sort(key=lambda x:(x[1]['critical'], x[1]['error'], x[1]['warning']), reverse=True)
        return [x[0] for x in devdata[:100]]
开发者ID:SteelHouseLabs,项目名称:zenoss-prodbin,代码行数:28,代码来源:Portlets.py

示例3: __call__

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
    def __call__(self, *args, **kwargs):
        """
        Takes a guid in the request and redirects the browser to the
        object's url
        """
        manager = IGUIDManager(self.context)
        request = self.request
        response = self.request.response
        obj = None
        guid = request.get('guid', None)
        if not guid:
            return response.write("The guid paramater is required")

        # they passed in a uid instead of a guid
        try:
            if guid.startswith("/zport/dmd/"):
                obj = self.context.unrestrictedTraverse(unquote(guid))
            else:
                obj = manager.getObject(guid)
        except KeyError:
            pass

        if not obj:
            return response.write("Could not look up guid %s" % guid)

        path = obj.absolute_url_path()
        return response.redirect(path)
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:29,代码来源:views.py

示例4: lookupGuid

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
 def lookupGuid(guid):
     """
     Given a guid this returns the object that it identifies
     """
     from Products.ZenUtils.guid.interfaces import IGUIDManager
     manager = IGUIDManager(dmd)
     return manager.getObject(guid)
开发者ID:zenoss,项目名称:zenoss-prodbin,代码行数:9,代码来源:zendmd.py

示例5: manage_addAdministrativeRole

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
 def manage_addAdministrativeRole(self, name=None, type='device', role=None,
                                  guid=None, uid=None, REQUEST=None):
     "Add a Admin Role to the passed object"
     unused(role)
     mobj = None
     if guid or uid:
         # look up our object by either guid or uid
         if guid:
             manager = IGUIDManager(self.dmd)
             mobj = manager.getObject(guid)
         elif uid:
             mobj = self.unrestrictedTraverse(uid)
     else:
         # use magic to look up our object
         if not name:
             name = REQUEST.deviceName
         if type == 'device':
             mobj =self.getDmdRoot("Devices").findDevice(name)
         else:
             try:
                 root = type.capitalize()+'s'
                 if type == "deviceClass":
                     mobj = self.getDmdRoot("Devices").getOrganizer(name)
                 else:
                     mobj = self.getDmdRoot(root).getOrganizer(name)
             except KeyError: pass
     if not mobj:
         if REQUEST:
             messaging.IMessageSender(self).sendToBrowser(
                 'Error',
                 "%s %s not found"%(type.capitalize(),name),
                 priority=messaging.WARNING
             )
             return self.callZenScreen(REQUEST)
         else: return
     roleNames = [ r.id for r in mobj.adminRoles() ]
     if self.id in roleNames:
         if REQUEST:
             messaging.IMessageSender(self).sendToBrowser(
                 'Error',
                 (("Administrative Role for %s %s "
                  "for user %s already exists.") % (type, name, self.id)),
                 priority=messaging.WARNING
             )
             return self.callZenScreen(REQUEST)
         else: return
     mobj.manage_addAdministrativeRole(self.id)
     if REQUEST:
         messaging.IMessageSender(self).sendToBrowser(
             'Role Added',
             ("Administrative Role for %s %s for user %s added" %
                 (type, name, self.id))
         )
         audit('UI.User.AddAdministrativeRole', username=self.id,
               data_={mobj.meta_type:mobj.getPrimaryId()})
         return self.callZenScreen(REQUEST)
开发者ID:SteelHouseLabs,项目名称:zenoss-prodbin,代码行数:58,代码来源:UserSettings.py

示例6: getElements

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
    def getElements(self):
        manager = IGUIDManager(self.getDmd())
        memberObjs = []
        for poolmember in self.members:
            obj = manager.getObject(poolmember)
            if obj:
                memberObjs.append(obj)
            else:
                log.warn("Stale ElementPool member: %s", poolmember)

        return memberObjs
开发者ID:zenoss,项目名称:ZenPacks.zenoss.CalculatedPerformance,代码行数:13,代码来源:ElementPool.py

示例7: _getDevices

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
 def _getDevices(self, dmd, results):
     """
     Look up the devices from the events.
     """
     manager = IGUIDManager(dmd)
     events = results['events']
     for event in events:
         occurrence = event['occurrence'][0]
         actor_uuid = occurrence['actor'].get('element_uuid')
         if not actor_uuid:
             continue
         dev = manager.getObject(actor_uuid)
         if dev:
             yield dev
开发者ID:SteelHouseLabs,项目名称:zenoss-prodbin,代码行数:16,代码来源:statuses.py

示例8: getDeviceIssues

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
 def getDeviceIssues(self):
     zep = getFacade('zep', self._dmd)
     manager = IGUIDManager(self._dmd)
     deviceSeverities = zep.getDeviceIssuesDict()
     zem = self.context.dmd.ZenEventManager
     devdata = []
     # only get the first 100 since this is just the portlet
     for uuid in deviceSeverities.keys()[:100]:
         dev = manager.getObject(uuid)
         if dev and isinstance(dev, Device):
             if (not zem.checkRemotePerm(ZEN_VIEW, dev)
                 or dev.productionState < zem.prodStateDashboardThresh
                 or dev.priority < zem.priorityDashboardThresh):
                 continue
             severities = deviceSeverities[uuid]
             info = IInfo(dev)
             info.setEventSeverities(severities)
             devdata.append(info)
     return devdata
开发者ID:dougsyer,项目名称:ZenPacks.zenoss.Dashboard,代码行数:21,代码来源:facades.py

示例9: getDeviceDashboard

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
    def getDeviceDashboard(self):
        """return device info for bad device to dashboard"""
        zep = getFacade('zep')
        manager = IGUIDManager(self.context.dmd)
        deviceSeverities = zep.getDeviceIssuesDict()
        zem = self.context.dmd.ZenEventManager

        bulk_data = []

        for uuid in deviceSeverities.keys():
            uuid_data = {}
            uuid_data['uuid'] = uuid
            severities = deviceSeverities[uuid]
            try:
                uuid_data['severities'] = dict((zep.getSeverityName(sev).lower(), counts) for (sev, counts) in severities.iteritems())
            except ServiceException:
                continue
            bulk_data.append(uuid_data)

        bulk_data.sort(key=lambda x:(x['severities']['critical'], x['severities']['error'], x['severities']['warning']), reverse=True)

        devices_found = 0
        MAX_DEVICES = 100

        devdata = []
        for data in bulk_data:
            uuid = data['uuid']
            severities = data['severities']
            dev = manager.getObject(uuid)
            if dev and isinstance(dev, Device):
                if (not zem.checkRemotePerm(ZEN_VIEW, dev)
                    or dev.productionState < zem.prodStateDashboardThresh
                    or dev.priority < zem.priorityDashboardThresh):
                    continue
                alink = dev.getPrettyLink()
                pill = getEventPillME(dev, severities=severities)
                evts = [alink,pill]
                devdata.append(evts)
                devices_found = devices_found + 1
                if devices_found >= MAX_DEVICES:
                    break
        return devdata
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:44,代码来源:Portlets.py

示例10: load

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
    def load(self, pack, app):
        """
        Load Notifications and Triggers from an actions.json file

        Given a JSON-formatted configuration located at {zenpack}/actions/actions.json,
        create or update triggers and notifications specific to this zenpack.
        When creating or updating, the object is first checked to see whether or
        not an object exists with the configured guid for notifications or uuid
        for triggers. If an object is not found, one will be created. During
        creation, care is taken with regard to the id - integer suffixes will be
        appended to try to create a unique id. If we do not find a unique id after
        100 tries, an error will occur. When updating an object, care is taken
        to not change the name as it may have since been altered by the user (or
        by this loader adding a suffix).

        """
        log.debug("ZPTriggerAction: load")
        import Products.Zuul as Zuul
        from Products.Zuul.facades import ObjectNotFoundException
        
        tf = Zuul.getFacade('triggers', app.dmd)
        guidManager = IGUIDManager(app)
        
        for conf in findFiles(pack, 'zep',lambda f: f == 'actions.json'):

            import json
            data = json.load(open(conf, "r"))
            log.debug("DATA IS: %s" % data)

            triggers = data.get('triggers', [])
            notifications = data.get('notifications', [])


            tf.synchronize()
            all_names = set(t['name'] for t in tf.getTriggerList())

            for trigger_conf in triggers:

                existing_trigger = guidManager.getObject(trigger_conf['uuid'])

                if existing_trigger:
                    trigger_data = tf.getTrigger(trigger_conf['uuid'])
                    trigger_conf['name'] = trigger_data['name']

                    log.info('Existing trigger found, updating: %s' % trigger_conf['name'])
                    tf.updateTrigger(**trigger_conf)
                    
                else:

                    test_name = trigger_conf['name']
                    for x in xrange(1,101):
                        if test_name in all_names:
                            test_name = '%s_%d' % (trigger_conf['name'], x)
                        else:
                            log.debug('Found unused trigger name: %s' % test_name)
                            break
                    else:
                        # if we didn't find a unique name
                        raise Exception('Could not find unique name for trigger: "%s".' % trigger_conf['name'])

                    log.info('Creating trigger: %s' % test_name)
                    tf.createTrigger(test_name, uuid=trigger_conf['uuid'], rule=trigger_conf['rule'])


            for notification_conf in notifications:
                
                existing_notification = guidManager.getObject(str(notification_conf['guid']))

                if existing_notification:
                    log.info("Existing notification found, updating: %s" % existing_notification.id)
                    
                    subscriptions = set(existing_notification.subscriptions + notification_conf['subscriptions'])
                    notification_conf['uid'] = '/zport/dmd/NotificationSubscriptions/%s' % existing_notification.id
                    notification_conf['subscriptions'] = list(subscriptions)
                    notification_conf['name'] = existing_notification.id
                    tf.updateNotification(**notification_conf)
                else:


                    test_id = notification_conf['id']
                    for x in xrange(1,101):
                        test_uid = '/zport/dmd/NotificationSubscriptions/%s' % test_id

                        try:
                            tf.getNotification(test_uid)
                        except ObjectNotFoundException:
                            break

                        test_id = '%s_%d' % (notification_conf['id'], x)
                    else:
                        # if we didn't find a unique name
                        raise Exception('Could not find unique name for notification: "%s".' % notification_conf['id'])

                    log.info('Creating notification: %s' % test_id)
                    tf.createNotification(str(test_id), notification_conf['action'], notification_conf['guid'])

                    notification_conf['uid'] = '/zport/dmd/NotificationSubscriptions/%s' % test_id
                    tf.updateNotification(**notification_conf)
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:100,代码来源:ZenPackLoader.py

示例11: EventsRouter

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]

#.........这里部分代码省略.........
            filterEventUuids = []
            # No specific event uuids passed in-
            # check for event ids from the grid parameters
            if specificEventUuids is None:
                log.debug('No specific event uuids were passed in.')

                # The evid's from params only ever mean anything for filtering - if
                # specific uuids are passed in, this filter will ignore the grid
                # parameters and just act on or filter using these specific event uuids.
                evid = params.get('evid')
                if evid:
                    if not isinstance(evid, (list, tuple)):
                        evid = [evid]
                    filterEventUuids.extend(evid)

            # Specific event uuids were passed in, use those for this filter.
            else:
                log.debug('Specific event uuids passed in: %s', specificEventUuids)
                if not isinstance(specificEventUuids, (list, tuple)):
                    filterEventUuids = [specificEventUuids]
                else:
                    filterEventUuids = specificEventUuids

            log.debug('FilterEventUuids is: %s', filterEventUuids)

            # 'tags' comes from managed object guids.
            # see Zuul/security/security.py
            param_tags = params.get('tags')
            if params.get('excludeNonActionables') and not Zuul.checkPermission(ZEN_MANAGE_EVENTS, self.context):
                if not param_tags:
                    us = self.context.dmd.ZenUsers.getUserSettings()
                    param_tags = [IGlobalIdentifier(ar.managedObject()).getGUID() for ar in us.getAllAdminRoles()]
                if param_tags:
                    param_tags = [tag for tag in param_tags if Zuul.checkPermission(ZEN_MANAGE_EVENTS, self.manager.getObject(tag))]
                if not param_tags:
                    param_tags = ['dne']  # Filter everything (except "does not exist'). An empty tag list would be ignored.

            filter_params = {
                'severity': params.get('severity'),
                'status': [i for i in params.get('eventState', [])],
                'event_class': filter(None, [params.get('eventClass')]),
                'first_seen': params.get('firstTime') and self._timeRange(params.get('firstTime')),
                'last_seen': params.get('lastTime') and self._timeRange(params.get('lastTime')),
                'status_change': params.get('stateChange') and self._timeRange(params.get('stateChange')),
                'uuid': filterEventUuids,
                'count_range': params.get('count'),
                'element_title': params.get('device'),
                'element_sub_title': params.get('component'),
                'event_summary': params.get('summary'),
                'current_user_name': params.get('ownerid'),
                'agent': params.get('agent'),
                'monitor': params.get('monitor'),
                'fingerprint': params.get('dedupid'),
                'tags': param_tags,
                'details': details,
                'event_key': params.get('eventKey'),
                'event_class_key': params.get('eventClassKey'),
                'event_group': params.get('eventGroup'),
                'message': params.get('message'),
            }
            parsed_params = self._filterParser.parseParams(params)
            filter_params.update(parsed_params)

            parsed_details = self._filterParser.parseDetails(details)
            if len(parsed_details) > 0:
                filter_params['details'].update(parsed_details)
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:70,代码来源:zep.py

示例12: ZepFacade

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]

#.........这里部分代码省略.........
                                                            limit=limit, timeout=timeout)
        return status, to_dict(response)

    def getConfig(self):
        # the config client doesn't return a ZepConfig. It merges the ZepConfig
        # with some other properties to create a config structure.
        config = self.configClient.getConfig()
        return config

    def setConfigValues(self, values):
        """
        @type  values: Dictionary
        @param values: Key Value pairs of config values
        """
        zepConfigProtobuf = from_dict(ZepConfig, values)
        self.configClient.setConfigValues(zepConfigProtobuf)

    def setConfigValue(self, name, value):
        self.configClient.setConfigValue(name, value)

    def removeConfigValue(self, name):
        self.configClient.removeConfigValue(name)

    def _getTopLevelOrganizerUuids(self, tagUuid):
        """
        Returns a list of child UUIDs if the specified tagUuid is a top-level
        organizer. Otherwise returns None. This is needed because several
        operations in ZEP are performed on UUIDs tagged in the events, however
        the top-level organizers are not tagged on events as an optimization.

        @type  tagUuid: string
        @param tagUuid: UUID of potential top-level organizer
        """
        obj = self._guidManager.getObject(tagUuid)
        uuids = None
        if obj and obj.getDmdKey() == '/':
            uuids = [IGlobalIdentifier(n).getGUID() for n in obj.children()]
        return uuids

    def getEventSeveritiesByUuid(self, tagUuid, severities=(), status=()):
        """ returns a dict of severities for the element tagUuid """
        uuids = [ tagUuid ]
        return self.getEventSeveritiesByUuids(uuids , severities=severities, status=status)[tagUuid]


    def getEventSeveritiesByUuids(self, tagUuids, severities=(), status=()):
        """ returns a dict whose keys are each uuid in tagUuids and values the dict of severities per uuid """
        uuids = []
        requested_uuids = {}
        for uuid in tagUuids:
            children_uuids = self._getTopLevelOrganizerUuids(uuid)
            if children_uuids:
                requested_uuids[uuid] = children_uuids
                uuids.extend(children_uuids)
            else:
                requested_uuids[uuid] = [ uuid ]
                uuids.append(uuid)

        uuids = list(set(uuids))
        severities = self.getEventSeverities(uuids, severities=severities, status=status)

        severities_to_return = {}

        for requested_uuid in requested_uuids.keys():
            children_uuids = requested_uuids[requested_uuid]
            sevmap = {}
开发者ID:zenoss,项目名称:zenoss-prodbin,代码行数:70,代码来源:zepfacade.py

示例13: TriggersFacade

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
class TriggersFacade(ZuulFacade):

    def __init__(self, context):
        super(TriggersFacade, self).__init__(context)

        self._guidManager = IGUIDManager(self._dmd)

        config = getGlobalConfiguration()
        schema = getUtility(IQueueSchema)
        self.triggers_service = TriggerServiceClient(config.get('zep_uri', 'http://localhost:8084'), schema)

        self.notificationPermissions = NotificationPermissionManager()
        self.triggerPermissions = TriggerPermissionManager()

    def _removeNode(self, obj):
        """
        Remove an object in ZODB.

        This method was created to provide a hook for unit tests.
        """
        context = aq_parent(obj)
        return context._delObject(obj.id)

    def _removeTriggerFromZep(self, uuid):
        """
        Remove a trigger from ZEP.

        This method was created to provide a hook for unit tests.
        """
        return self.triggers_service.removeTrigger(uuid)

    def removeNode(self, uid):
        obj = self._getObject(uid)
        return self._removeNode(obj)

    def _setTriggerGuid(self, trigger, guid):
        """
        @param trigger: The trigger object to set the guid on.
        @type trigger: Products.ZenModel.Trigger.Trigger
        @param guid: The guid
        @type guid: str

        This method was created to provide a hook for unit tests.
        """
        IGlobalIdentifier(trigger).guid = guid

    def _getTriggerGuid(self, trigger):
        """
        @param trigger: The trigger object in zodb.
        @type trigger: Products.ZenModel.Trigger.Trigger

        This method was created to provide a hook for unit tests.
        """
        return IGlobalIdentifier(trigger).guid

    def _setupTriggerPermissions(self, trigger):
        """
        This method was created to provide a hook for unit tests.
        """
        self.triggerPermissions.setupTrigger(trigger)

    def synchronize(self):
        """
        This method will first synchronize all triggers that exist in ZEP to their
        corresponding objects in ZODB. Then, it will clean up notifications and
        remove any subscriptions to triggers that no longer exist.
        """

        log.debug('SYNC: Starting trigger and notification synchronization.')

        _, trigger_set = self.triggers_service.getTriggers()

        zep_uuids = set(t.uuid for t in trigger_set.triggers)
        zodb_triggers = self._getTriggerManager().objectValues()

        # delete all triggers in zodb that do not exist in zep.
        for t in zodb_triggers:
            if not self._getTriggerGuid(t) in zep_uuids:
                log.info('SYNC: Found trigger in zodb that does not exist in zep, removing: %s' % t.id)
                self._removeNode(t)

        zodb_triggers = self._getTriggerManager().objectValues()
        zodb_uuids = set(self._getTriggerGuid(t) for t in zodb_triggers)

        # create all triggers in zodb that do not exist in zep.
        for t in trigger_set.triggers:
            if not t.uuid in zodb_uuids:
                log.info('SYNC: Found trigger uuid in zep that does not seem to exist in zodb, creating: %s' % t.name)
                triggerObject = Trigger(str(t.name))

                try:
                    self._getTriggerManager()._setObject(triggerObject.id, triggerObject)

                except BadRequest:
                    # looks like the id already exists, remove this specific
                    # trigger from zep. This can happen if multiple createTrigger
                    # requests are sent from the browser at once - the transaction
                    # will not abort until after the requests to create a trigger
                    # have already been sent to zep.
                    # See https://dev.zenoss.com/tracint/ticket/28272
#.........这里部分代码省略.........
开发者ID:c0ns0le,项目名称:zenoss-4,代码行数:103,代码来源:triggersfacade.py

示例14: Manager

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
class Manager(object):
    """
    Provides lookup access to processing pipes and performs caching.
    """

    ELEMENT_TYPE_MAP = {
        DEVICE: Device,
        COMPONENT: DeviceComponent,
    }

    def __init__(self, dmd):
        self.dmd = dmd
        self._initCatalogs()

    def _initCatalogs(self):
        self._guidManager = IGUIDManager(self.dmd)

        self._devices = self.dmd._getOb('Devices')
        self._networks = self.dmd._getOb('Networks')
        self._events = self.dmd._getOb('Events')

        self._catalogs = {
            DEVICE: self._devices,
        }

    def reset(self):
        self._initCatalogs()

    def getEventClassOrganizer(self, eventClassName):
        try:
            return self._events.getOrganizer(eventClassName)
        except KeyError:
            # Unknown organizer
            return None

    def lookupEventClass(self, eventContext):
        """
        Find a Device's EventClass
        """
        return self._events.lookup(eventContext.eventProxy,
                                   eventContext.deviceObject)

    def getElementByUuid(self, uuid):
        """
        Get a Device/Component by UUID
        """
        if uuid:
            return self._guidManager.getObject(uuid)

    def uuidFromBrain(self, brain):
        """
        Helper method to deal with catalog brains which are out of date. If
        the uuid is not set on the brain, we attempt to load it from the
        object.
        """
        uuid = brain.uuid
        return uuid if uuid else IGlobalIdentifier(brain.getObject()).getGUID()

    @FunctionCache("getElementUuidById", cache_miss_marker=-1, default_timeout=300)
    def getElementUuidById(self, catalog, element_type_id, id):
        """
        Find element by ID but only cache UUID. This forces us to lookup elements
        each time by UUID (pretty fast) which gives us a chance to see if the element
        has been deleted.
        """
        cls = self.ELEMENT_TYPE_MAP.get(element_type_id)
        if cls:
            catalog = catalog or self._catalogs.get(element_type_id)
            if catalog:
                results = ICatalogTool(catalog).search(cls,
                                                       query=Or(Eq('id', id),
                                                                Eq('name', id)),
                                                       filterPermissions=False,
                                                       limit=1)
                if results.total:
                    try:
                        result = results.results.next()
                    except StopIteration:
                        pass
                    else:
                        return self.uuidFromBrain(result)

    def getElementById(self, catalog, element_type_id, id):
        """
        Find element by ID, first checking a cache for UUIDs then using that UUID
        to load the element. If the element can't be found by UUID, the UUID
        cache is cleared and lookup tried again.
        """
        uuid = self.getElementUuidById(catalog, element_type_id, id)
        if uuid:
            element = self.getElementByUuid(uuid)
            if not element:
                # Lookup cache must be invalid, try looking up again
                self.getElementUuidById.clear()
                log.warning(
                        'Clearing ElementUuidById cache becase we could not find %s' % uuid)
                uuid = self.getElementUuidById(catalog, element_type_id, id)
                element = self.getElementByUuid(uuid)
            return element

#.........这里部分代码省略.........
开发者ID:bbc,项目名称:zenoss-prodbin,代码行数:103,代码来源:processing.py

示例15: cutover

# 需要导入模块: from Products.ZenUtils.guid.interfaces import IGUIDManager [as 别名]
# 或者: from Products.ZenUtils.guid.interfaces.IGUIDManager import getObject [as 别名]
    def cutover(self, dmd):

        # Check to see if the BTree exists
        btree = getattr(dmd, 'prodstate_table', None)
        if btree:
            guidManager = IGUIDManager(dmd)
            count = 0
            total = len(btree)
            for guid, states in btree.iteritems():
                obj = guidManager.getObject(guid)

                # 'ProdState' code no longer exists so 'states' object is going to be broken
                # Setting it this way instead of using 'setProdState' will NOT trigger a re-index
                #  but anybody upgrading to this version is going to have to run a full re-index post-upgrade
                if not obj:
                    continue
                try:
                    obj.productionState = states.__Broken_state__['productionState']
                    obj.preMWProductionState = states.__Broken_state__['preMWProductionState']
                except AttributeError:
                    log.warning("Coulnd't get production state for %s, setting up 'Production' to it", obj)
                    obj.productionState = 1000
                    obj.preMWProductionState = 1000

                count += 1

                if count % 100 == 0:
                    log.info("Migrated production state for %d objects of %d", count, total)

                if count % 1000 == 0:
                    log.info("Committing transaction for 1000 objects")
                    transaction.commit()

            # Tidy up whatever's in the last 1000 that didn't get committed
            if count % 100:
                log.info("Migrated %d objects of %d", count, total)
            if count % 1000:
                log.info("Committing transaction for %d objects", count % 1000)
                transaction.commit()

            # Now drop the BTree
            log.info("Removing production state BTree")
            dmd._delOb('prodstate_table')
            transaction.commit()

            log.info("Migration Complete")
        elif not getattr(dmd, MIGRATED_FLAG, False):
            # We don't have a BTree, but we haven't been migrated yet, so this is from back before the BTree existed,
            #  When prodstate was an attribute called 'productionState' on the object.
            #  Since 'productionState' is now the name of a property, we have to pull the old productionState off of the
            #  object's __dict__
            def migrate_object(obj):
                obj._p_activate() # Activate the object so the old attributes end up in __dict__
                if 'preMWProductionState' in obj.__dict__:
                    obj.preMWProductionState = obj.__dict__['preMWProductionState']
                    del obj.__dict__['preMWProductionState']

                if 'productionState' in obj.__dict__:
                    obj.productionState = obj.__dict__['productionState']
                    del obj.__dict__['productionState']

            count = 0
            for device in dmd.Devices.getSubDevicesGen_recursive():
                migrate_object(device)
                count += 1

                # migrate components
                try:
                    cmps = device.getDeviceComponents()
                except AttributeError:
                    pass
                else:
                    for c in cmps:
                        migrate_object(c)

                if count % 100 == 0:
                    log.info("Migrated production state for %d devices", count)

                if count % 1000 == 0:
                    log.info("Committing transaction for 1000 objects")
                    transaction.commit()

            # Tidy up whatever's in the last 1000 that didn't get committed
            if count % 100:
                log.info("Migrated %d devices", count)
            if count % 1000:
                log.info("Committing transaction for %d devices", count % 1000)
                transaction.commit()
        else:
            log.info("Nothing to migrate")

        setattr(dmd, MIGRATED_FLAG, True)
开发者ID:zenoss,项目名称:zenoss-prodbin,代码行数:94,代码来源:removeProdStateBTree.py


注:本文中的Products.ZenUtils.guid.interfaces.IGUIDManager.getObject方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。