Пример #1
0
    def queryArchive(self, page=None, limit=0, start=0, sort='lastTime', dir='desc', params=None, exclusion_filter=None, keys=None, uid=None, detailFormat=False):
        if not self._canViewEvents():
            return DirectResponse.succeed(
                events = [],
                totalCount = 0,
                asof = time.time()
                )

        filter = self._buildFilter([uid], params)
        if exclusion_filter is not None:
            exclusion_filter = self._buildFilter([uid], exclusion_filter)
        events = self.zep.getEventSummariesFromArchive(limit=limit, offset=start, sort=self._buildSort(sort,dir),
                                                       filter=filter, exclusion_filter=exclusion_filter)
        eventFormat = EventCompatInfo
        if detailFormat:
            eventFormat = EventCompatDetailInfo

        dmd = self.context.dmd
        # filter out the component and device UUIDs that no longer exist in our system
        evdata = self._filterInvalidUuids(events['events'])
        eventObs = [eventFormat(dmd, e) for e in evdata]
        return DirectResponse.succeed(
            events = Zuul.marshal(eventObs, keys),
            totalCount = events['total'],
            asof = time.time()
        )
Пример #2
0
 def parseFilter(self, source):
     try:
         response = self._getFacade().parseFilter(source)
         return DirectResponse.succeed(data=response)
     except Exception, e:
         log.exception(e)
         return DirectResponse.exception(e, "Error parsing filter source. Please check your syntax.")
Пример #3
0
    def add_event(self, summary, device, component, severity, evclasskey, evclass=None):
        """
        Create a new event.

        @type  summary: string
        @param summary: New event's summary
        @type  device: string
        @param device: Device uid to use for new event
        @type  component: string
        @param component: Component uid to use for new event
        @type  severity: string
        @param severity: Severity of new event. Can be one of the following:
                         Critical, Error, Warning, Info, Debug, or Clear
        @type  evclasskey: string
        @param evclasskey: The Event Class Key to assign to this event
        @type  evclass: string
        @param evclass: Event class for the new event
        @rtype:   DirectResponse
        """
        try:
            self.zep.create(summary, severity, device, component, eventClassKey=evclasskey, eventClass=evclass)
            return DirectResponse.succeed("Created event")
        except NoConsumersException:
            # This occurs if the event is queued but there are no consumers - i.e. zeneventd is not
            # currently running.
            msg = 'Queued event. Check zeneventd status on <a href="/zport/About/zenossInfo">Daemons</a>'
            return DirectResponse.succeed(msg, sticky=True)
        except PublishException, e:
            # This occurs if there is a failure publishing the event to the queue.
            log.exception("Failed creating event")
            return DirectResponse.exception(e, "Failed to create event")
Пример #4
0
    def add_event(self, summary, device, component, severity, evclasskey, evclass=None):
        """
        Create a new event.

        @type  summary: string
        @param summary: New event's summary
        @type  device: string
        @param device: Device id to use for new event
        @type  component: string
        @param component: Component uid to use for new event
        @type  severity: string
        @param severity: Severity of new event. Can be one of the following:
                         Critical, Error, Warning, Info, Debug, or Clear
        @type  evclasskey: string
        @param evclasskey: The Event Class Key to assign to this event
        @type  evclass: string
        @param evclass: Event class for the new event
        @rtype:   DirectResponse
        """
        device = device.strip()  # ZEN-2479: support entries like "localhost "
        try:
            self.zep.create(summary, severity, device, component, eventClassKey=evclasskey,
                            eventClass=evclass, immediate=True)
            return DirectResponse.succeed("Created event")
        except NoConsumersException:
            # This occurs if the event is queued but there are no consumers - i.e. zeneventd is not
            # currently running.
            msg = 'Queued event. Check zeneventd status on <a href="/zport/About/zenossInfo">Daemons</a>'
            return DirectResponse.succeed(msg, sticky=True)
        except PublishException, e:
            # This occurs if there is a failure publishing the event to the queue.
            log.exception("Failed creating event")
            return DirectResponse.exception(e, "Failed to create event")
Пример #5
0
    def queryArchive(self, page=None, limit=0, start=0, sort='lastTime', dir='desc', params=None, exclusion_filter=None, keys=None, uid=None, detailFormat=False):
        if not self._canViewEvents():
            return DirectResponse.succeed(
                events=[],
                totalCount=0,
                asof=time.time()
                )

        filter = self._buildFilter(uid, params)
        if exclusion_filter is not None:
            exclusion_filter = self._buildFilter(uid, exclusion_filter)
        events = self.zep.getEventSummariesFromArchive(limit=limit, offset=start, sort=self._buildSort(sort, dir),
                                                       filter=filter, exclusion_filter=exclusion_filter)
        eventFormat = EventCompatInfo
        if detailFormat:
            eventFormat = EventCompatDetailInfo

        dmd = self.context.dmd
        # filter out the component and device UUIDs that no longer exist in our system
        evdata = self._filterInvalidUuids(events['events'])
        eventObs = [eventFormat(dmd, e) for e in evdata]
        return DirectResponse.succeed(
            events=Zuul.marshal(eventObs, keys),
            totalCount=events['total'],
            asof=time.time()
        )
Пример #6
0
 def parseFilter(self, source):
     try:
         response = self._getFacade().parseFilter(source)
         return DirectResponse.succeed(data=response)
     except Exception, e:
         log.exception(e)
         return DirectResponse.exception(
             e, 'Error parsing filter source. Please check your syntax.')
Пример #7
0
 def addTrigger(self, newId):
     try:
         data = self._getFacade().addTrigger(newId)
     except DuplicateTriggerName as tnc:
         log.debug("Exception DuplicateTriggerName: %s" % tnc)
         return DirectResponse.fail(str(tnc))
     else:
         audit('UI.Trigger.Add', newId)
         return DirectResponse.succeed(data=data)
Пример #8
0
 def addTrigger(self, newId):
     try:
         data = self._getFacade().addTrigger(newId)
     except DuplicateTriggerName as tnc:
         log.debug("Exception DuplicateTriggerName: %s" % tnc)
         return DirectResponse.fail(str(tnc))
     else:
         audit('UI.Trigger.Add', newId)
         return DirectResponse.succeed(data=data)
Пример #9
0
 def updateDetails(self, evid, **detailInfo):
     """
     On success, returns the status.
     """
     try:
         resp = self.zep.updateDetails(evid, **detailInfo)
     except ServiceResponseError as ex:
         return DirectResponse.fail(msg=str(ex))
     audit('UI.Event.UpdateEventDetails', self.context, evid=evid,
           details=detailInfo)
     return DirectResponse.succeed(status=resp['status'])
Пример #10
0
 def updateDetails(self, evid, **detailInfo):
     """
     On success, returns the status.
     """
     try:
         resp = self.zep.updateDetails(evid, **detailInfo)
     except ServiceResponseError as ex:
         return DirectResponse.fail(msg=str(ex))
     audit('UI.Event.UpdateEventDetails', self.context, evid=evid,
           details=detailInfo)
     return DirectResponse.succeed(status=resp['status'])
Пример #11
0
 def importConfiguration(self, triggers=None, notifications=None):
     try:
         tcount = len(triggers) if triggers is not None else 0
         ncount = len(notifications) if notifications is not None else 0
         facade = self._getFacade()
         itcount, incount = facade.importConfiguration(triggers, notifications)
         msg = "Imported %d of %d triggers and %d of %d notifications" % (tcount, itcount, ncount, incount)
         audit("UI.TriggerNotification.Import", msg)
         return DirectResponse.succeed(msg=msg)
     except Exception as ex:
         audit("UI.TriggerNotification.Import", "Failed to import trigger/notification data")
         log.exception("Unable to import data:\ntriggers=%s\nnotifications=%s", repr(triggers), repr(notifications))
         return DirectResponse.fail(str(ex))
Пример #12
0
 def importConfiguration(self, triggers=None, notifications=None):
     try:
         tcount = len(triggers) if triggers is not None else 0
         ncount = len(notifications) if notifications is not None else 0
         facade = self._getFacade()
         itcount, incount = facade.importConfiguration(triggers, notifications)
         msg = "Imported %d of %d triggers and %d of %d notifications" % (
                     tcount, itcount, ncount, incount)
         audit('UI.TriggerNotification.Import', msg) 
         return DirectResponse.succeed(msg=msg)
     except Exception as ex:
         audit('UI.TriggerNotification.Import', "Failed to import trigger/notification data")
         log.exception("Unable to import data:\ntriggers=%s\nnotifications=%s",
                       repr(triggers), repr(notifications))
         return DirectResponse.fail(str(ex))
Пример #13
0
 def getNotificationTypes(self, query=''):
     utils = getUtilitiesFor(IAction)
     actionTypes = sorted(
         (dict(id=id, name=util.name) for id, util in utils),
         key=itemgetter('id'))
     log.debug('notification action types are: %s' % actionTypes)
     return DirectResponse.succeed(data=actionTypes)
Пример #14
0
 def getUserInterfaceSettings(self):
     """
     Retrieves the collection of User interface settings
     """
     settings = self._getUISettings()
     return DirectResponse.succeed(
         data=Zuul.marshal(settings.getSettingsData()))
Пример #15
0
 def updateTrigger(self, **data):
     data['rule']['api_version'] = 1
     data['rule']['type'] = RULE_TYPE_JYTHON
     triggerUid = data['uuid']
     response = self._getFacade().updateTrigger(**data)
     audit('UI.Trigger.Edit', triggerUid, data_=data)
     return DirectResponse.succeed(msg="Trigger updated successfully.", data=response)
Пример #16
0
    def clear_device_heartbeats(self, params, limit=None):
        """
        @type  params: dictionary
        @param params: Key-value pair of filters for this search.
        """
        if isinstance(params, basestring):
            params = loads(params)

        device = params['device']

        log.debug('Clearing heartbeats for device: {device}'.format(device=device))

        params['eventState'] = [STATUS_NEW, STATUS_ACKNOWLEDGED]
        params['eventClass'] = '/Status/Heartbeat'

        includeFilter, excludeFilter = self._buildRequestFilters(None, params, None, None)

        status, summaryUpdateResponse = self.zep.closeEventSummaries(
            eventFilter=includeFilter,
            exclusionFilter=excludeFilter,
            limit=limit,
        )

        log.debug('Done clearing heartbeats for device: {device}'.format(device=device))
        log.debug(summaryUpdateResponse)
        audit('UI.Device.ClearHeartbeats', device=device)

        return DirectResponse.succeed(data=summaryUpdateResponse)
Пример #17
0
 def getConfig(self):
     # this data var is not a ZepConfig, it's a config structure that has been
     # constructed to include default values and be keyed by the protobuf
     # property name.
     data = self.zep.getConfig()
     config = self._mergeSchemaAndZepConfig(data, self.configSchema)
     return DirectResponse.succeed(data=config)
Пример #18
0
    def setConfigValues(self, values):
        """
        @type  values: Dictionary
        @param values: Key Value pairs of config values
        """
        # Remove empty strings from values
        empty_keys = [
            k for k, v in values.iteritems()
            if isinstance(v, basestring) and not len(v)
        ]
        for empty_key in empty_keys:
            del values[empty_key]

        # we store default syslog priority and default availability days on the event manager
        defaultSyslogPriority = values.pop('default_syslog_priority', None)
        if defaultSyslogPriority is not None:
            self.context.dmd.ZenEventManager.defaultPriority = int(
                defaultSyslogPriority)

        defaultAvailabilityDays = values.pop('default_availability_days', None)
        if defaultAvailabilityDays is not None:
            self.context.dmd.ZenEventManager.defaultAvailabilityDays = int(
                defaultAvailabilityDays)

        self.zep.setConfigValues(values)
        return DirectResponse.succeed()
Пример #19
0
 def getSupportSettings(self):
     """
     Retrieves the collection of settings
     """
     settings = self._getSupportSettings()
     return DirectResponse.succeed(
         data=Zuul.marshal(settings.getSupportSettingsData()))
Пример #20
0
    def clear_device_heartbeats(self, params, limit=None):
        """
        @type  params: dictionary
        @param params: Key-value pair of filters for this search.
        """
        if isinstance(params, basestring):
            params = loads(params)

        device = params['device']

        log.debug(
            'Clearing heartbeats for device: {device}'.format(device=device))

        params['eventState'] = [STATUS_NEW, STATUS_ACKNOWLEDGED]
        params['eventClass'] = '/Status/Heartbeat'

        includeFilter, excludeFilter = self._buildRequestFilters(
            None, params, None, None)

        status, summaryUpdateResponse = self.zep.closeEventSummaries(
            eventFilter=includeFilter,
            exclusionFilter=excludeFilter,
            limit=limit,
        )

        log.debug('Done clearing heartbeats for device: {device}'.format(
            device=device))
        log.debug(summaryUpdateResponse)
        audit('UI.Device.ClearHeartbeats', device=device)

        return DirectResponse.succeed(data=summaryUpdateResponse)
Пример #21
0
 def getConfig(self):
     # this data var is not a ZepConfig, it's a config structure that has been
     # constructed to include default values and be keyed by the protobuf
     # property name.
     data = self.zep.getConfig()
     config = self._mergeSchemaAndZepConfig(data, self.configSchema)
     return DirectResponse.succeed(data=config)
Пример #22
0
 def updateTrigger(self, **data):
     data["rule"]["api_version"] = 1
     data["rule"]["type"] = RULE_TYPE_JYTHON
     triggerUid = data["uuid"]
     response = self._getFacade().updateTrigger(**data)
     audit("UI.Trigger.Edit", triggerUid, data_=data)
     return DirectResponse.succeed(msg="Trigger updated successfully.", data=response)
Пример #23
0
 def getSecurityPermissions(self, uid):
     """
     returns a dictionary of all the permissions a
     user has on the context
     """
     obj = self.context.dmd.unrestrictedTraverse(uid)
     permissions = permissionsForContext(obj)
     return DirectResponse.succeed(data=permissions)
Пример #24
0
 def getSecurityPermissions(self, uid):
     """
     returns a dictionary of all the permissions a
     user has on the context
     """
     obj = self.context.dmd.unrestrictedTraverse(uid)
     permissions = permissionsForContext(obj)
     return DirectResponse.succeed(data=permissions)
Пример #25
0
 def getNotificationTypes(self, query=''):
     utils = getUtilitiesFor(IAction)
     actionTypes = sorted(
         (dict(id=id, name=util.name) for id, util in utils),
         key=itemgetter('id')
     )
     log.debug('notification action types are: %s' % actionTypes)
     return DirectResponse.succeed(data=actionTypes)
Пример #26
0
 def getConfig(self):
     # this data var is not a ZepConfig, it's a config structure that has been
     # constructed to include default values and be keyed by the protobuf
     # property name.
     data = self.zep.getConfig()
     schema = self._mergeSchemaAndZepConfig(data, self.configSchema)
     config = [setting for setting in schema if self.iseditable(setting['id'])]
     return DirectResponse.succeed(data=config)
Пример #27
0
 def removeTrigger(self, uuid):
     updated_count = self._getFacade().removeTrigger(uuid)
     audit('UI.Trigger.Remove', uuid)
     msg = "Trigger removed successfully. {count} {noun} {verb} updated.".format(
         count=updated_count,
         noun='notification' if updated_count == 1 else 'notifications',
         verb='was' if updated_count == 1 else 'were')
     return DirectResponse.succeed(msg=msg, data=None)
Пример #28
0
 def updateEventSummaries(self,
                          update,
                          event_filter=None,
                          exclusion_filter=None,
                          limit=None):
     status, response = self.zep.updateEventSummaries(
         update, event_filter, exclusion_filter, limit)
     return DirectResponse.succeed(data=response)
Пример #29
0
 def exportConfiguration(self, triggerIds=None, notificationIds=None):
     facade = self._getFacade()
     triggers, notifications = facade.exportConfiguration(triggerIds, notificationIds)
     msg = "Exported %d triggers and %d notifications" % (len(triggers), len(notifications))
     audit("UI.TriggerNotification.Export", msg)
     return DirectResponse.succeed(
         triggers=Zuul.marshal(triggers), notifications=Zuul.marshal(notifications), msg=msg
     )
Пример #30
0
 def exportConfiguration(self, triggerIds=None, notificationIds=None):
     facade = self._getFacade()
     triggers, notifications = facade.exportConfiguration(triggerIds, notificationIds)
     msg = "Exported %d triggers and %d notifications" % (
              len(triggers), len(notifications)) 
     audit('UI.TriggerNotification.Export', msg)
     return DirectResponse.succeed(triggers=Zuul.marshal(triggers),
                                   notifications=Zuul.marshal(notifications),
                                   msg=msg)
Пример #31
0
 def removeTrigger(self, uuid):
     updated_count = self._getFacade().removeTrigger(uuid)
     audit('UI.Trigger.Remove', uuid)
     msg = "Trigger removed successfully. {count} {noun} {verb} updated.".format(
         count = updated_count,
         noun = 'notification' if updated_count == 1 else 'notifications',
         verb = 'was' if updated_count == 1 else 'were'
     )
     return DirectResponse.succeed(msg=msg, data=None)
Пример #32
0
 def updateNotification(self, **data):
     notificationUid = data['uid']
     response = self._getFacade().updateNotification(**data)
     audit('UI.Notification.Edit', notificationUid,
           data=data, maskFields='password')
     return DirectResponse.succeed(
         msg="Notification updated successfully.",
         data=Zuul.marshal(response)
     )
Пример #33
0
 def removeTrigger(self, uuid):
     updated_count = self._getFacade().removeTrigger(uuid)
     audit("UI.Trigger.Remove", uuid)
     msg = "Trigger removed successfully. {count} {noun} {verb} updated.".format(
         count=updated_count,
         noun="notification" if updated_count == 1 else "notifications",
         verb="was" if updated_count == 1 else "were",
     )
     return DirectResponse.succeed(msg=msg, data=None)
Пример #34
0
 def updateNotification(self, **data):
     notificationUid = data['uid']
     response = self._getFacade().updateNotification(**data)
     audit('UI.Notification.Edit',
           notificationUid,
           data=data,
           maskFields='password')
     return DirectResponse.succeed(msg="Notification updated successfully.",
                                   data=Zuul.marshal(response))
Пример #35
0
    def getRouterMethods(self, router=None):
        """
        Return a JSON list of methods, arguments and documentation

        Example usage from zendmd:

        from Products.Zuul.routers.introspection import IntrospectionRouter
        zz = IntrospectionRouter(dmd)
        pprint(zz.getRouterMethods('DeviceRouter').data)
        """
        if router is not None:
            klasses = self._getRouterByName(router)
            if klasses:
                # TODO: log something?
                klass = klasses[0]
            else:
                return DirectResponse.fail(msg="No router named '%s' found" %
                                           router)
        else:
            klass = self.__class__

        methods = {}
        for name, code in inspect.getmembers(klass):
            if name.startswith('_'):
                continue
            if not inspect.ismethod(code):
                continue

            argspec = inspect.getargspec(code)
            if argspec.defaults is None:
                args = argspec.args[1:]  # Ignore 'self'
                kwargs = {}
            else:
                n = len(argspec.defaults)
                args = argspec.args[1:-n]  # Ignore 'self'
                kwargs = dict(zip(argspec.args[-n:], argspec.defaults))

            methods[name] = dict(
                documentation=inspect.getdoc(code),
                kwargs=kwargs,
                args=args,
            )

        return DirectResponse(data=Zuul.marshal(methods))
Пример #36
0
    def setDmdSettings(self, **kwargs):
        """
        Accepts key value pair of dmd settings
        """
        dmd = self.context.zport.dmd
        for key, value in kwargs.iteritems():
            if hasattr(dmd, key):
                setattr(dmd, key, value)

        return DirectResponse.succeed()
Пример #37
0
    def setDmdSettings(self, **kwargs):
        """
        Accepts key value pair of dmd settings
        """
        dmd = self.context.zport.dmd
        for key, value in kwargs.iteritems():
            if hasattr(dmd, key):
                setattr(dmd, key, value)

        return DirectResponse.succeed()
Пример #38
0
    def clear_heartbeats(self):
        """
        Clear all heartbeat events

        @rtype:   DirectResponse
        @return:  B{Properties}:
           - success: (boolean) True if heartbeats deleted successfully
        """
        self.zep.deleteHeartbeats()
        audit('UI.Event.ClearHeartbeats', self.context)
        return DirectResponse.succeed()
Пример #39
0
    def clear_heartbeats(self):
        """
        Clear all heartbeat events

        @rtype:   DirectResponse
        @return:  B{Properties}:
           - success: (boolean) True if heartbeats deleted successfully
        """
        self.zep.deleteHeartbeats()
        audit('UI.Event.ClearHeartbeats', self.context)
        return DirectResponse.succeed()
Пример #40
0
    def getAllRouters(self):
        """
        Return a description of the Zenoss routers available.

        from Products.Zuul.routers.introspection import IntrospectionRouter
        zz = IntrospectionRouter(dmd)
        pprint(zz.getAllRouters().data)
        """
        routers = self._getAllRouters()
        data = map(self._getRouterInfo, routers)
        return DirectResponse(data=Zuul.marshal(data))
Пример #41
0
 def setSupportSettings(self, **kwargs):
     """
     Accepts key value pair of settings
     """
     settings = self._getSupportSettings()
     oldValues = {}
     newValues = {}
     for key, value in kwargs.iteritems():
         oldValues[key] = str(getattr(settings, key, None))
         newValues[key] = str(value)
         setattr(settings, key, value)
     return DirectResponse.succeed()
Пример #42
0
 def setUserInterfaceSettings(self, **kwargs):
     """
     Accepts key value pair of user interface settings.
     """
     settings = self._getUISettings()
     oldValues = {}
     newValues = {}
     for key, value in kwargs.iteritems():
         oldValues[key] = str(getattr(settings, key, None))
         newValues[key] = str(value)
         setattr(settings, key, value)
     audit('UI.InterfaceSettings.Edit', data_=newValues, oldData_=oldValues)
     return DirectResponse.succeed()
Пример #43
0
 def setUserInterfaceSettings(self, **kwargs):
     """
     Accepts key value pair of user interface settings.
     """
     settings = self._getUISettings()
     oldValues = {}
     newValues = {}
     for key, value in kwargs.iteritems():
         oldValues[key] = str(getattr(settings, key, None))
         newValues[key] = str(value)
         setattr(settings, key, value)
     audit('UI.InterfaceSettings.Edit', data_=newValues, oldData_=oldValues)
     return DirectResponse.succeed()
Пример #44
0
    def add_event(self, summary, device, component, severity, evclasskey,
                  evclass=None, monitor=None, **kwargs):
        """
        Create a new event.

        @type  summary: string
        @param summary: New event's summary
        @type  device: string
        @param device: Device id to use for new event
        @type  component: string
        @param component: Component uid to use for new event
        @type  severity: string
        @param severity: Severity of new event. Can be one of the following:
                         Critical, Error, Warning, Info, Debug, or Clear
        @type  evclasskey: string
        @param evclasskey: The Event Class Key to assign to this event
        @type  evclass: string
        @param evclass: Event class for the new event
        @rtype:   DirectResponse

        For other parameters please see class Event.
        """
        device = device.strip()  # ZEN-2479: support entries like "localhost "
        try:
            self.zep.create(summary, severity, device, component,
                            eventClassKey=evclasskey, eventClass=evclass,
                            monitor=monitor, **kwargs)
            return DirectResponse.succeed("Created event")
        except NoConsumersException:
            # This occurs if the event is queued but there are no consumers - i.e. zeneventd is not
            # currently running.
            msg = 'Queued event. Check zeneventd status on <a href="/zport/dmd/daemons">Services</a>'
            return DirectResponse.succeed(msg, sticky=True)
        except PublishException, e:
            # This occurs if there is a failure publishing the event to the queue.
            log.exception("Failed creating event")
            return DirectResponse.exception(e, "Failed to create event")
Пример #45
0
    def clear_heartbeat(self, monitor, daemon):
        """
        Clears a specific heartbeat event.

        @type monitor: basestring
        @param monitor: The heartbeat monitor (i.e. 'localhost').
        @type daemon: basestring
        @param daemon: The heartbeat daemon (i.e. 'zenhub').
        @rtype: DirectResponse
        @return: A DirectResponse indicating success or failure.
        """
        self.zep.deleteHeartbeat(monitor, daemon)
        audit('UI.Event.ClearHeartbeat', self.context, monitor=monitor,
              daemon=daemon)
        return DirectResponse.succeed()
Пример #46
0
    def clear_heartbeat(self, monitor, daemon):
        """
        Clears a specific heartbeat event.

        @type monitor: basestring
        @param monitor: The heartbeat monitor (i.e. 'localhost').
        @type daemon: basestring
        @param daemon: The heartbeat daemon (i.e. 'zenhub').
        @rtype: DirectResponse
        @return: A DirectResponse indicating success or failure.
        """
        self.zep.deleteHeartbeat(monitor, daemon)
        audit('UI.Event.ClearHeartbeat', self.context, monitor=monitor,
              daemon=daemon)
        return DirectResponse.succeed()
Пример #47
0
    def reopen(self,
               evids=None,
               excludeIds=None,
               params=None,
               uid=None,
               asof=None,
               limit=None,
               timeout=None):
        """
        Reopen event(s).

        @type  evids: [string]
        @param evids: (optional) List of event IDs to reopen (default: None)
        @type  excludeIds: [string]
        @param excludeIds: (optional) List of event IDs to exclude from
                           reopen (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
                       (default: None)
        @type  uid: string
        @param uid: (optional) Context for the query (default: None)
        @type  asof: float
        @param asof: (optional) Only reopen if there has been no state
                     change since this time (default: None)
        @type  limit: The maximum number of events to update in this batch.
        @param limit: (optional) Maximum number of events to update (Default: None).
        @type  timeout: int
        @param timeout: The time (in seconds) before the underlying saved search times out.
        @rtype:   DirectResponse
        @return:  Success message
        """

        log.debug('Issuing a reopen request.')

        includeFilter, excludeFilter = self._buildRequestFilters(
            uid, params, evids, excludeIds)

        status, summaryUpdateResponse = self.zep.reopenEventSummaries(
            eventFilter=includeFilter,
            exclusionFilter=excludeFilter,
            limit=limit,
            timeout=timeout,
        )

        log.debug('Done issuing reopen request.')
        log.debug(summaryUpdateResponse)

        return DirectResponse.succeed(data=summaryUpdateResponse)
Пример #48
0
 def setUserInterfaceSettings(self, **kwargs):
     """
     Accepts key value pair of user interface settings.
     """
     settings = self._getUISettings()
     oldValues = {}
     newValues = {}
     for key, value in kwargs.iteritems():
         # check if user has permissions to update setting
         if not settings.iseditable(key):
             continue
         oldValues[key] = str(getattr(settings, key, None))
         newValues[key] = str(value)
         setattr(settings, key, value)
     audit('UI.InterfaceSettings.Edit', data_=newValues, oldData_=oldValues)
     return DirectResponse.succeed()
Пример #49
0
    def write_log(self, evid=None, message=None):
        """
        Write a message to an event's log.

        @type  evid: string
        @param evid: Event ID to log to
        @type  message: string
        @param message: Message to log
        @rtype:   DirectResponse
        @return:  Success message
        """

        userName = getSecurityManager().getUser().getId()

        self.zep.addNote(uuid=evid, message=message, userName=userName)

        return DirectResponse.succeed()
Пример #50
0
    def getContextMenus(self, uid=None, menuIds=None):
        if uid:
            ob = self.context.dmd.unrestrictedTraverse(uid)
            menuItems = []
            if menuIds:
                menus = self._getDialogMenuItems(menuIds, ob)

                def menuToConfig(menu):
                    return {
                        'id': '%s' % menu.id.lower(),
                        'viewName': menu.action,
                        'text': menu.description
                    }

                if menus:
                    menuItems.extend(menuToConfig(menu) for menu in menus)
        return DirectResponse(menuItems=menuItems)
Пример #51
0
    def classify(self, evrows, evclass):
        """
        Associate event(s) with an event class.

        @type  evrows: [dictionary]
        @param evrows: List of event rows to classify
        @type  evclass: string
        @param evclass: Event class to associate events to
        @rtype:   DirectResponse
        @return:  B{Properties}:
           - msg: (string) Success/failure message
           - success: (boolean) True if class update successful
        """
        msg, url = self.zep.createEventMapping(evrows, evclass)
        if url:
            msg += " | " + url.split('/dmd/')[1]
        return DirectResponse(msg, success=bool(url))
Пример #52
0
    def write_log(self, evid=None, message=None):
        """
        Write a message to an event's log.

        @type  evid: string
        @param evid: Event ID to log to
        @type  message: string
        @param message: Message to log
        @rtype:   DirectResponse
        @return:  Success message
        """

        userName = getSecurityManager().getUser().getId()

        self.zep.addNote(uuid=evid, message=message, userName=userName)

        return DirectResponse.succeed()
Пример #53
0
    def nextEventSummaryUpdate(self, next_request):
        """
        When performing updates from the event console, updates are performed in batches
        to allow the user to see the progress of event changes and cancel out of updates
        while they are in progress. This works by specifying a limit to one of the close,
        acknowledge, or reopen calls in this router. The response will contain an
        EventSummaryUpdateResponse, and if there are additional updates to be performed,
        it will contain a next_request field with all of the parameters used to update
        the next range of events.

        @type  next_request: dictionary
        @param next_request: The next_request field from the previous updates.
        """
        log.debug('Starting next batch of updates')
        status, summaryUpdateResponse = self.zep.nextEventSummaryUpdate(next_request)

        log.debug('Completed updates: %s', summaryUpdateResponse)
        return DirectResponse.succeed(data=summaryUpdateResponse)
Пример #54
0
    def getRouterMethods(self, router=None):
        """
        Return a JSON list of methods, arguments and documentation

        Example usage from zendmd:

        from Products.Zuul.routers.introspection import IntrospectionRouter
        zz = IntrospectionRouter(dmd)
        pprint(zz.getRouterMethods('DeviceRouter').data)
        """
        if router is not None:
            klasses = self._getRouterByName(router)
            if klasses:
                # TODO: log something?
                klass = klasses[0]
            else:
                return DirectResponse.fail(msg="No router named '%s' found" % router)
        else:
            klass = self.__class__

        methods = {}
        for name, code in inspect.getmembers(klass):
            if name.startswith('_'):
                continue
            if not inspect.ismethod(code):
                continue

            argspec = inspect.getargspec(code)
            if argspec.defaults is None:
                args = argspec.args[1:] # Ignore 'self'
                kwargs = {}
            else:
                n = len(argspec.defaults)
                args = argspec.args[1:-n] # Ignore 'self'
                kwargs = dict(zip(argspec.args[-n:], argspec.defaults))

            methods[name] = dict(
                documentation=inspect.getdoc(code),
                kwargs=kwargs,
                args=args,
            )

        return DirectResponse(data=Zuul.marshal(methods))
Пример #55
0
    def detail(self, evid):
        """
        Get event details.

        @type  evid: string
        @param evid: Event ID to get details
        @type  history: boolean
        @param history: Deprecated
        @rtype:   DirectResponse
        @return:  B{Properties}:
           - event: ([dictionary]) List containing a dictionary representing
                    event details
        """
        event_summary = self.zep.getEventSummary(evid)
        if event_summary:
            eventData = Zuul.marshal(EventCompatDetailInfo(self.context.dmd, event_summary))
            return DirectResponse.succeed(event=[eventData])
        else:
            raise Exception('Could not find event %s' % evid)
Пример #56
0
    def setConfigValues(self, values):
        """
        @type  values: Dictionary
        @param values: Key Value pairs of config values
        """
        # Remove empty strings from values
        empty_keys = [k for k, v in values.iteritems() if isinstance(v, basestring) and not len(v)]
        for empty_key in empty_keys:
            del values[empty_key]

        # we store default syslog priority and default availability days on the event manager
        defaultSyslogPriority = values.pop('default_syslog_priority', None)
        if defaultSyslogPriority is not None:
            self.context.dmd.ZenEventManager.defaultPriority = int(defaultSyslogPriority)

        defaultAvailabilityDays = values.pop('default_availability_days', None)
        if defaultAvailabilityDays is not None:
            self.context.dmd.ZenEventManager.defaultAvailabilityDays = int(defaultAvailabilityDays)

        self.zep.setConfigValues(values)
        return DirectResponse.succeed()
Пример #57
0
    def reopen(self, evids=None, excludeIds=None, params=None, uid=None, asof=None, limit=None, timeout=None):
        """
        Reopen event(s).

        @type  evids: [string]
        @param evids: (optional) List of event IDs to reopen (default: None)
        @type  excludeIds: [string]
        @param excludeIds: (optional) List of event IDs to exclude from
                           reopen (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
                       (default: None)
        @type  uid: string
        @param uid: (optional) Context for the query (default: None)
        @type  asof: float
        @param asof: (optional) Only reopen if there has been no state
                     change since this time (default: None)
        @type  limit: The maximum number of events to update in this batch.
        @param limit: (optional) Maximum number of events to update (Default: None).
        @type  timeout: int
        @param timeout: The time (in seconds) before the underlying saved search times out.
        @rtype:   DirectResponse
        @return:  Success message
        """

        log.debug('Issuing a reopen request.')

        includeFilter, excludeFilter = self._buildRequestFilters(uid, params, evids, excludeIds)

        status, summaryUpdateResponse = self.zep.reopenEventSummaries(
            eventFilter=includeFilter,
            exclusionFilter=excludeFilter,
            limit=limit,
            timeout=timeout,
        )

        log.debug('Done issuing reopen request.')
        log.debug(summaryUpdateResponse)

        return DirectResponse.succeed(data=summaryUpdateResponse)
Пример #58
0
    def acknowledge(self, evids=None, excludeIds=None, params=None, uid=None, asof=None, limit=None):
        """
        Acknowledge event(s).

        @type  evids: [string]
        @param evids: (optional) List of event IDs to acknowledge (default: None)
        @type  excludeIds: [string]
        @param excludeIds: (optional) List of event IDs to exclude from
                           acknowledgment (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
                       (default: None)
        @type  uid: string
        @param uid: (optional) Context for the query (default: None)
        @type  asof: float
        @param asof: (optional) Only acknowledge if there has been no state
                     change since this time (default: None)
        @type  limit: The maximum number of events to update in this batch.
        @param limit: (optional) Maximum number of events to update (default: None).
        @rtype:   DirectResponse
        @return:  Success message
        """
        log.debug('Issuing an acknowledge request.')

        includeFilter, excludeFilter = self._buildRequestFilters(uid, params, evids, excludeIds)

        status, summaryUpdateResponse = self.zep.acknowledgeEventSummaries(
            eventFilter=includeFilter,
            exclusionFilter=excludeFilter,
            limit=limit,
        )

        log.debug('Done issuing acknowledge request.')
        log.debug(summaryUpdateResponse)

        return DirectResponse.succeed(data=summaryUpdateResponse)
Пример #59
0
 def addNotification(self, newId, action):
     response = self._getFacade().addNotification(newId, action)
     audit('UI.Notification.Add', newId)
     return DirectResponse.succeed(data=Zuul.marshal(response))