Exemple #1
0
 def manage_events(self,
                   evids=None,
                   excludeIds=None,
                   params=None,
                   uid=None,
                   asof=None,
                   limit=None,
                   timeout=None):
     if Zuul.checkPermission(ZEN_MANAGE_EVENTS, self.context):
         return True
     if params.get('excludeNonActionables'):
         return Zuul.checkPermission('ZenCommon', self.context)
     return False
Exemple #2
0
 def manage_events(self, evids=None, excludeIds=None, params=None, uid=None, asof=None, limit=None, timeout=None):
     user = self.context.dmd.ZenUsers.getUserSettings()
     if Zuul.checkPermission(ZEN_MANAGE_EVENTS, self.context):
         return True
     if params.get('excludeNonActionables'):
         return Zuul.checkPermission('ZenCommon', self.context)
     try:
         if uid is not None:
             organizer_name = self.context.dmd.Devices.getOrganizer(uid).getOrganizerName()
         else:
             return self._hasPermissionsForAllEvents(ZEN_MANAGE_EVENTS, evids)
     except (AttributeError, KeyError):
         return False
     manage_events_for = (r.managedObjectName() for r in user.getAllAdminRoles() if r.role in READ_WRITE_ROLES)
     return organizer_name in manage_events_for
Exemple #3
0
    def updateConfigFiles(self, id, configFiles):
        """
        Updates the configuration files for an application specified by id.
        The configFiles parameters is an array of dictionaries of the form:
        {
            filename: "blah",
            content: "line 1\nline 2\n..."
        }
        The filename parameter serves as the "id" of each configFile
        passed in.
        """

        if not Zuul.checkPermission('Manage DMD'):
            return DirectResponse.fail("You don't have permission to set update config files", sticky=False)

        facade = self._getFacade()
        deployedApp = facade.get(id)
        newConfigs = []
        for deployedAppConfig in deployedApp.configurations:
            if deployedAppConfig.filename in [ cf['filename'] for cf in configFiles ]:
                audit('UI.Applications.UpdateConfigFiles',
                      service=id,
                      servicename=deployedApp.name,
                      filename=deployedAppConfig.filename)
                deployedAppConfig.content = next((cf['content'] for cf in configFiles if cf['filename'] == deployedAppConfig.filename))
            newConfigs.append(deployedAppConfig)
        deployedApp.configurations = newConfigs
        return DirectResponse.succeed()
    def add_ovirt(self,
                  url,
                  username,
                  domain,
                  password,
                  collector='localhost'):
        # Check the permissions on the context
        context = self.context.dmd.Devices.oVirt
        if not Zuul.checkPermission(ZEN_MANAGE_DMD, context):
            message = "Insufficient privileges to add an oVirt infrastructure"
            audit('UI.oVirt.Login', url=url)
            return DirectResponse.fail(message)

        facade = self._getFacade()
        success, message = facade.add_ovirt(url, username, domain, password,
                                            collector)

        if success:
            audit('UI.oVirt.Add',
                  url=url,
                  username=username,
                  domain=domain,
                  password=password,
                  collector=collector,
                  jobId=message)
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Exemple #5
0
 def write_event_logs(self, evid=None, message=None):
     data = self.detail(evid).data['event'][0]
     uuid = data['component_uuid'] or data['device_uuid']
     if uuid is None:
         ctx = self.context
     else:
         ctx = self.manager.getObject(uuid)
     return Zuul.checkPermission(ZEN_MANAGE_EVENTS, ctx)
 def wrapped_fn(f, self, *args, **kwargs):
     context = kwargs[contextKeywordArgument]
     if isinstance(context, basestring):
         context = self.context.unrestrictedTraverse(context)
     if not Zuul.checkPermission(permission, context):
         args = (f.__name__, permission)
         raise Unauthorized('Calling %s requires "%s" permission.' % args)
     return f(self, *args, **kwargs)
Exemple #7
0
 def iconCls(self):
     icon = None
     if self._root._showSeverityIcons:
         obj = self._get_object()
         if Zuul.checkPermission(ZEN_VIEW, obj):
             sev = self._loadSeverity()
             icon = self.getIconCls(sev)
     return icon
Exemple #8
0
 def iconCls(self):
     icon = None
     if self._root._showSeverityIcons:
         obj = self._get_object()
         if Zuul.checkPermission(ZEN_VIEW, obj):
             sev = self._loadSeverity()
             icon = self.getIconCls(sev)
     return icon
Exemple #9
0
 def write_event_logs(self, evid=None, message=None):
     data = self.detail(evid).data['event'][0]
     uuid = data['component_uuid'] or data['device_uuid']
     if uuid is None:
         ctx = self.context
     else:
         ctx = self.manager.getObject(uuid)
     return Zuul.checkPermission(ZEN_MANAGE_EVENTS, ctx)
 def wrapped_fn(f, self, *args, **kwargs):
     context = kwargs[contextKeywordArgument]
     if isinstance(context, basestring):
         context = self.context.unrestrictedTraverse(context)
     if not Zuul.checkPermission(permission, context):
         args = (f.__name__, permission)
         raise Unauthorized('Calling %s requires "%s" permission.' % args)
     return f(self, *args, **kwargs)
    def query(self,
              limit=None,
              start=None,
              sort=None,
              dir=None,
              params=None,
              page=None,
              history=False,
              uid=None,
              criteria=()):
        """
        Retrieve a list of services based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - services: ([dictionary]) List of objects representing services
             - totalCount: (integer) Total number of services
             - hash: (string) Hashcheck of the current services state
             - disabled: (boolean) True if current user cannot manage services
        """
        if uid is None:
            uid = "/".join(self.context.getPhysicalPath())

        if isinstance(params, basestring):
            params = unjson(params)
        services = self.api.getList(limit, start, sort, dir, params, uid,
                                    criteria)

        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(services['serviceInfos'],
                            keys=('name', 'description', 'count', 'uid',
                                  'port'))
        return DirectResponse(services=data,
                              totalCount=services['total'],
                              hash=services['hash'],
                              disabled=disabled)
    def query(self,
              limit=None,
              start=None,
              sort=None,
              dir=None,
              params=None,
              page=None,
              history=False,
              uid=None,
              criteria=()):
        """
        Retrieve a list of processes based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - processes: ([dictionary]) List of objects representing processes
             - totalCount: (integer) Total number of processes
             - hash: (string) Hashcheck of the current processes state
             - disabled: (boolean) True if current user cannot manage processes
        """
        facade = self._getFacade()
        if uid is None:
            uid = self.context

        if isinstance(params, basestring):
            params = unjson(params)

        processes = facade.getList(limit, start, sort, dir, params, uid,
                                   criteria)
        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(processes)
        return DirectResponse(processes=data,
                              totalCount=processes.total,
                              hash=processes.hash_,
                              disabled=disabled)
Exemple #13
0
 def saveDashboard(self, **data):
     user = getSecurityManager().getUser()
     facade = self._getFacade()
     obj = facade._getObject(data['uid'])
     if obj.owner != user.getId() and not Zuul.checkPermission(
             ZEN_MANAGE_DMD, facade.context):
         raise Exception("you have no permission to edit this dashboard")
     result = facade.saveDashboard(data)
     if data.get('audit'): audit('UI.Dashboard.Edit', data_=data)
     return DirectResponse.succeed(data=Zuul.marshal(result))
Exemple #14
0
 def wrapped_fn(f, self, *args, **kwargs):
     if callable(permission):
         if not permission(self, *args, **kwargs):
             args = (f.__name__, permission.__name__)
             raise Unauthorized('Calling %s requires "%s" permission' % args)
         return f(self, *args, **kwargs)
     else:
         if not Zuul.checkPermission(permission, self.context):
             args = (f.__name__, permission)
             raise Unauthorized('Calling %s requires "%s" permission' % args)
         return f(self, *args, **kwargs)
 def wrapped_fn(f, self, *args, **kwargs):
     if callable(permission):
         if not permission(self, *args, **kwargs):
             args = (f.__name__, permission.__name__)
             raise Unauthorized('Calling %s requires "%s" permission' %
                                args)
         return f(self, *args, **kwargs)
     else:
         if not Zuul.checkPermission(permission, self.context):
             args = (f.__name__, permission)
             raise Unauthorized('Calling %s requires "%s" permission' %
                                args)
         return f(self, *args, **kwargs)
Exemple #16
0
 def deleteDashboard(self, uid):
     user = getSecurityManager().getUser()
     facade = self._getFacade()
     obj = facade._getObject(uid)
     # can't delete the default dashboard
     if obj.getPrimaryId() == "/zport/dmd/ZenUsers/dashboards/default":
         return
     if obj.owner != user.getId() and not Zuul.checkPermission(
             ZEN_DELETE, facade.context):
         raise Exception("You have no permission to delete this dashboard")
     result = facade.deleteObject(uid)
     audit('UI.Dashboard.Remove', uid)
     return DirectResponse.succeed(data=Zuul.marshal(result))
Exemple #17
0
    def events(self):
        severities = self.getEventSeverities()
        events = {}
        zep = getFacade('zep')
        events = dict((zep.getSeverityName(sev).lower(), counts) for (sev, counts) in severities.iteritems())

        # If the user does not have view permissions, we reset the rainbow
        if hasattr(self, "_object") and not Zuul.checkPermission(ZEN_VIEW, self._object):
            for sev, counts in events.iteritems():
                counts['count'] = 0
                counts['acknowledged_count'] = 0

        return events
Exemple #18
0
    def events(self):
        severities = self.getEventSeverities()
        events = {}
        zep = getFacade('zep')
        events = dict((zep.getSeverityName(sev).lower(), counts)
                      for (sev, counts) in severities.iteritems())

        # If the user does not have view permissions, we reset the rainbow
        if hasattr(self, "_object") and not Zuul.checkPermission(
                ZEN_VIEW, self._object):
            for sev, counts in events.iteritems():
                counts['count'] = 0
                counts['acknowledged_count'] = 0

        return events
Exemple #19
0
    def getInfo(self, uid, keys=None):
        """Returns a dictionary of the properties of an object.

        @type  uid: string
        @param uid: Unique identifier of an object
        @type  keys: list
        @param keys: (optional) List of keys to include in the returned
                     dictionary. If None then all keys will be returned
        @rtype:   DirectResponse
        @return:  B{Properties}
            - data: (dictionary) Object properties
        """
        network = self.api.getInfo(uid)
        data = Zuul.marshal(network, keys)
        disabled = not Zuul.checkPermission("Manage DMD")
        return DirectResponse.succeed(data=data, disabled=disabled)
Exemple #20
0
    def deleteJobs(self, jobids):
        # Make sure they have permission to delete.
        if not Zuul.checkPermission('Manage DMD'):
            return DirectResponse.fail("You don't have permission to execute this command", sticky=False)

        deletedJobs = []
        for id_ in jobids:
            try:
                self.api.deleteJob(id_)
            except NoSuchJobException:
                log.debug("Unable to delete job: %s No such job found.", id_)
            else:
                deletedJobs.append(id_)
        if deletedJobs:
            audit('UI.Jobs.Delete', ids=deletedJobs)
            return DirectResponse.succeed(deletedJobs=Zuul.marshal(deletedJobs))
    def query(self, limit=None, start=None, sort=None, dir=None, params=None,
              page=None, history=False, uid=None, criteria=()):
        """
        Retrieve a list of processes based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - processes: ([dictionary]) List of objects representing processes
             - totalCount: (integer) Total number of processes
             - hash: (string) Hashcheck of the current processes state
             - disabled: (boolean) True if current user cannot manage processes
        """
        facade = self._getFacade()
        if uid is None:
            uid = self.context

        if isinstance(params, basestring):
            params = unjson(params)

        processes = facade.getList(limit, start, sort, dir, params, uid,
                                  criteria)
        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(processes)
        return DirectResponse(processes=data, totalCount=processes.total,
                              hash=processes.hash_, disabled=disabled)
    def add_ovirt(self, url, username, domain, password, collector='localhost'):
        # Check the permissions on the context
        context = self.context.dmd.Devices.oVirt
        if not Zuul.checkPermission(ZEN_MANAGE_DMD, context):
           message = "Insufficient privileges to add an oVirt infrastructure"
           audit('UI.oVirt.Login', url=url)
           return DirectResponse.fail(message)

        facade = self._getFacade()
        success, message = facade.add_ovirt(url, username, domain, password, collector)

        if success:
            audit('UI.oVirt.Add', url=url, username=username, domain=domain,
                  password=password, collector=collector, jobId=message)
            return DirectResponse.succeed(jobId=message)
        else:
            return DirectResponse.fail(message)
Exemple #23
0
    def getInfo(self, uid, keys=None):
        """
        Returns a dictionary of the properties of an object

        @type  uid: string
        @param uid: Unique identifier of an object
        @type  keys: list
        @param keys: (optional) List of keys to include in the returned
                     dictionary. If None then all keys will be returned
        @rtype:   DirectResponse
        @return:  B{Properties}
            - data: (dictionary) Object properties
        """
        network = self.api.getInfo(uid)
        data = Zuul.marshal(network, keys)
        disabled = not Zuul.checkPermission('Manage DMD')
        return DirectResponse.succeed(data=data, disabled=disabled)
    def query(self, limit=None, start=None, sort=None, dir=None, params=None,
              page=None, history=False, uid=None, criteria=()):
        """
        Retrieve a list of services based on a set of parameters.

        @type  limit: integer
        @param limit: (optional) Number of items to return; used in pagination
                      (default: None)
        @type  start: integer
        @param start: (optional) Offset to return the results from; used in
                      pagination (default: None)
        @type  sort: string
        @param sort: (optional) Key on which to sort the return results (default:
                     None)
        @type  dir: string
        @param dir: (optional) Sort order; can be either 'ASC' or 'DESC'
                    (default: None)
        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
        @type  history: boolean
        @param history: not used
        @type  uid: string
        @param uid: Service class UID to query
        @type  criteria: list
        @param criteria: not used
        @rtype:   DirectResponse
        @return:  B{Properties}:
             - services: ([dictionary]) List of objects representing services
             - totalCount: (integer) Total number of services
             - hash: (string) Hashcheck of the current services state
             - disabled: (boolean) True if current user cannot manage services
        """
        if uid is None:
            uid = "/".join(self.context.getPhysicalPath())

        if isinstance(params, basestring):
            params = unjson(params)
        services = self.api.getList(limit, start, sort, dir, params, uid,
                                  criteria)

        disabled = not Zuul.checkPermission('Manage DMD')

        data = Zuul.marshal(services['serviceInfos'], keys=('name','description', 'count', 'uid','port'))
        return DirectResponse(services=data, totalCount=services['total'],
                              hash=services['hash'], disabled=disabled)
Exemple #25
0
    def deleteJobs(self, jobids):
        # Make sure they have permission to delete.
        if not Zuul.checkPermission('Manage DMD'):
            return DirectResponse.fail(
                "You don't have permission to execute this command",
                sticky=False)

        deletedJobs = []
        for id_ in jobids:
            try:
                self.api.deleteJob(id_)
            except NoSuchJobException:
                log.debug("Unable to delete job: %s No such job found.", id_)
            else:
                deletedJobs.append(id_)
        if deletedJobs:
            audit('UI.Jobs.Delete', ids=deletedJobs)
            return DirectResponse.succeed(
                deletedJobs=Zuul.marshal(deletedJobs))
Exemple #26
0
    def restart(self, uids):
        """
        Will issue the command to restart the selected ids
        @type uids: Array[Strings]
        @param uids: List of valid daemon ids that will need to restarted
        @rtype: DirectResposne
        @return: DirectReponse of success if no errors are encountered
        """

        if not Zuul.checkPermission('Manage DMD'):
            return DirectResponse.fail("You don't have permission to restart a daemon", sticky=False)

        facade = self._getFacade()
        for uid in uids:
            facade.restart(uid)
            audit('UI.Applications.Restart', uid)
        if len(uids) > 1:
            return DirectResponse.succeed("Restarted %s daemons" % len(uids))
        return DirectResponse.succeed()
Exemple #27
0
    def getInfo(self, uid, keys=None):
        """
        Get the properties of a service.

        @type  uid: string
        @param uid: Unique identifier of a service
        @type  keys: list
        @param keys: (optional) List of keys to include in the returned
                     dictionary. If None then all keys will be returned
                     (default: None)
        @rtype:   DirectResponse
        @return:  B{Properties}
            - data: (dictionary) Object representing a service's properties
            - disabled: (boolean) True if current user cannot manage services
        """
        service = self.api.getInfo(uid)
        data = Zuul.marshal(service, keys)
        if 'serviceKeys' in data and isinstance(data['serviceKeys'], (tuple, list)):
            data['serviceKeys'] = ', '.join(data['serviceKeys'])
        disabled = not Zuul.checkPermission('Manage DMD')
        return DirectResponse.succeed(data=data, disabled=disabled)
    def getInfo(self, uid, keys=None):
        """
        Get the properties of a service.

        @type  uid: string
        @param uid: Unique identifier of a service
        @type  keys: list
        @param keys: (optional) List of keys to include in the returned
                     dictionary. If None then all keys will be returned
                     (default: None)
        @rtype:   DirectResponse
        @return:  B{Properties}
            - data: (dictionary) Object representing a service's properties
            - disabled: (boolean) True if current user cannot manage services
        """
        service = self.api.getInfo(uid)
        data = Zuul.marshal(service, keys)
        if 'serviceKeys' in data and isinstance(data['serviceKeys'], (tuple, list)):
            data['serviceKeys'] = ', '.join(data['serviceKeys'])
        disabled = not Zuul.checkPermission('Manage DMD')
        return DirectResponse.succeed(data=data, disabled=disabled)
Exemple #29
0
    def setAutoStart(self, uids, enabled):
        """
        Enables or disables autostart on all applications passed into uids.
        If it is already in that state it is a noop.
        @type uids: Array[Strings]
        @param uids: List of valid daemon ids that will need to enabled
        @type enabled: boolean
        @param uids: true for enabled or false for disabled
        @rtype: DirectResposne
        @return: DirectReponse of success if no errors are encountered
        """

        if not Zuul.checkPermission('Manage DMD'):
            return DirectResponse.fail("You don't have permission to set autostart", sticky=False)

        facade = self._getFacade()
        applications = facade.query()
        for app in applications:
            if app.id in uids:
                app.autostart = enabled
                audit('UI.Applications.AutoStart', app.id, {'autostart': enabled})
        return DirectResponse.succeed()
Exemple #30
0
    def _buildFilter(self,
                     uids,
                     params,
                     specificEventUuids=None,
                     includeContextInUid=True):
        """
        Construct a dictionary that can be converted into an EventFilter protobuf.

        @type  params: dictionary
        @param params: (optional) Key-value pair of filters for this search.
                       (default: None)
        @type  uids: iterable(string)
        @param uids: (optional) Contexts for the query (default: None)
        """
        if not uids:
            uids = []
        elif isinstance(uids, basestring):
            uids = [uids]

        if params:
            log.debug('logging params for building filter: %s', params)
            if isinstance(params, basestring):
                params = loads(params)

            # params comes from the grid's filtering column -
            # some of these properties are normal properties on an event
            # while others are considered event details. Separate the
            # two here.
            params, details = self.zep.parseParameterDetails(params)

            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)

            event_filter = self.zep.createEventFilter(**filter_params)
            log.debug(
                'Found params for building filter, ended up building  the following:'
            )
            log.debug(event_filter)
        elif specificEventUuids:
            # if they passed in specific uuids but not other params
            event_filter = self.zep.createEventFilter(uuid=specificEventUuids)
        else:
            log.debug('Did not get parameters, using empty filter.')
            event_filter = {}

        if not uids and includeContextInUid:
            uids = [self.context]

        contexts = (resolve_context(uid) for uid in uids)

        context_uuids = []
        for context in contexts:
            if context and context.id not in ('Events', 'dmd'):
                try:
                    # make a specific instance of tag_filter just for the context tag.
                    if not context_uuids:
                        context_tag_filter = {'tag_uuids': context_uuids}
                        # if it exists, filter['tag_filter'] will be a list. just append the special
                        # context tag filter to whatever that list is.
                        tag_filter = event_filter.setdefault('tag_filter', [])
                        tag_filter.append(context_tag_filter)
                    context_uuids.append(IGlobalIdentifier(context).getGUID())

                except TypeError:
                    if isinstance(context, EventClass):
                        event_filter['event_class'] = [context.getDmdKey()]
                    else:
                        raise Exception('Unknown context %s' % context)

        log.debug('Final filter will be:')
        log.debug(event_filter)

        return event_filter
Exemple #31
0
    def _buildFilter(self, uid, params, specificEventUuids=None):
        """
        Construct a dictionary that can be converted into an EventFilter protobuf.

        @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) 
        """
        if params:
            log.debug('logging params for building filter: %s', params)
            if isinstance(params, basestring):
                params = loads(params)

            # params comes from the grid's filtering column -
            # some of these properties are normal properties on an event
            # while others are considered event details. Separate the
            # two here.
            params, details = self.zep.parseParameterDetails(params)

            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)

            event_filter = self.zep.createEventFilter(**filter_params)

            log.debug('Found params for building filter, ended up building  the following:')
            log.debug(event_filter)
        elif specificEventUuids:
            # if they passed in specific uuids but not other params
            event_filter = self.zep.createEventFilter(
                uuid=specificEventUuids
                )
        else:
            log.debug('Did not get parameters, using empty filter.')
            event_filter = {}

        if uid is None:
            uid = self.context

        context = resolve_context(uid)

        if context and context.id not in ('Events', 'dmd'):
            try:
                # make a specific instance of tag_filter just for the context tag.
                context_tag_filter = {
                    'tag_uuids': [IGlobalIdentifier(context).getGUID()]
                }
                # if it exists, filter['tag_filter'] will be a list. just append the special
                # context tag filter to whatever that list is.
                tag_filter = event_filter.setdefault('tag_filter', [])
                tag_filter.append(context_tag_filter)
            except TypeError:
                if isinstance(context, EventClass):
                    event_filter['event_class'] = [context.getDmdKey()]
                else:
                    raise Exception('Unknown context %s' % context)

        log.debug('Final filter will be:')
        log.debug(event_filter)

        return event_filter
Exemple #32
0
 def manage_events(self, evids=None, excludeIds=None, params=None, uid=None, asof=None, limit=None, timeout=None):
     if Zuul.checkPermission(ZEN_MANAGE_EVENTS, self.context):
         return True
     if params.get('excludeNonActionables'):
         return Zuul.checkPermission('ZenCommon', self.context)
     return False