예제 #1
0
파일: attribute.py 프로젝트: csmall/rnms
    def prepare(self):
        self.url = url
        hostid_filter = []
        if hasattr(self, 'host_id') and self.host_id is not None:
            hostid_filter = [Attribute.host_id == self.host_id]

        admin_down = DBSession.query(func.count(Attribute.id)).\
            filter(and_(*(
                hostid_filter + [Attribute.admin_state == State.DOWN]
            ))).first()
        self.att_total = int(admin_down[0])
        db_states = DBSession.query(
            EventState.internal_state, func.count(Attribute.id)).\
            join(Attribute).filter(and_(
                *(hostid_filter +
                  [Attribute.admin_state != State.DOWN]))).\
            group_by(EventState.internal_state)
        tmp_states = {}
        for att in db_states:
            tmp_states[att[0]] = att[1]
            self.att_total += att[1]

        self.att_states = []
        for state_val, label in State.NAMES.items():
            if state_val is None:
                self.att_states.append((label, admin_down[0]))
            else:
                try:
                    self.att_states.append((label, tmp_states[state_val]))
                except KeyError:
                    self.att_states.append((label, 0))
        super(AttributeSummary, self).prepare()
예제 #2
0
    def prepare(self):
        self.url = url
        hostid_filter = []
        if hasattr(self, 'host_id') and self.host_id is not None:
            hostid_filter = [Attribute.host_id == self.host_id]

        admin_down = DBSession.query(func.count(Attribute.id)).\
            filter(and_(*(
                hostid_filter + [Attribute.admin_state == State.DOWN]
            ))).first()
        self.att_total = int(admin_down[0])
        db_states = DBSession.query(
            EventState.internal_state, func.count(Attribute.id)).\
            join(Attribute).filter(and_(
                *(hostid_filter +
                  [Attribute.admin_state != State.DOWN]))).\
            group_by(EventState.internal_state)
        tmp_states = {}
        for att in db_states:
            tmp_states[att[0]] = att[1]
            self.att_total += att[1]

        self.att_states = []
        for state_val, label in State.NAMES.items():
            if state_val is None:
                self.att_states.append((label, admin_down[0]))
            else:
                try:
                    self.att_states.append((label, tmp_states[state_val]))
                except KeyError:
                    self.att_states.append((label, 0))
        super(AttributeSummary, self).prepare()
예제 #3
0
파일: graph.py 프로젝트: csmall/rnms
 def types_option(self, a=None):
     if a is not None and type(a) is not list:
         a = [a]
     att_ids = [int(x) for x in a]
     atype = DBSession.query(GraphType.id, GraphType.display_name,
                             GraphType.attribute_type_id).\
         filter(GraphType.attribute_type_id.in_(
                DBSession.query(Attribute.attribute_type_id).
                filter(Attribute.id.in_(att_ids))
                ))
     return dict(data_name='atype', items=atype.all())
예제 #4
0
 def types_option(self, a=None):
     if a is not None and type(a) is not list:
         a = [a]
     att_ids = [int(x) for x in a]
     atype = DBSession.query(GraphType.id, GraphType.display_name,
                             GraphType.attribute_type_id).\
         filter(GraphType.attribute_type_id.in_(
                DBSession.query(Attribute.attribute_type_id).
                filter(Attribute.id.in_(att_ids))
                ))
     return dict(data_name='atype', items=atype.all())
예제 #5
0
 def _delete_rows(self, del_model, del_id=None):
     """ Delete all items of del_model with an ID higher than del_id
         Returns number of deleted items
     """
     deleted_items = 0
     if del_id is None:
         deleted_items = DBSession.query(del_model).delete()
     else:
         deleted_items = DBSession.query(del_model).\
             filter(del_model.id > del_id).delete()
     if deleted_items is None:
         return 0
     return deleted_items
예제 #6
0
 def _delete_rows(self, del_model, del_id=None):
     """ Delete all items of del_model with an ID higher than del_id
         Returns number of deleted items
     """
     deleted_items = 0
     if del_id is None:
         deleted_items = DBSession.query(del_model).delete()
     else:
         deleted_items = DBSession.query(del_model).\
             filter(del_model.id > del_id).delete()
     if deleted_items is None:
         return 0
     return deleted_items
예제 #7
0
파일: hosts.py 프로젝트: nomed/rnms
 def option(self):
     """ Return a list of hosts. If user has required
     permission it shows all, else just their ones """
     if permissions.host_ro:
         hosts = DBSession.query(Host.id, Host.display_name)
     else:
         hosts = DBSession.query(Host.id, Host.display_name).filter(
             Host.id.in_(
                 DBSession.query(Attribute.host_id).filter(
                     Attribute.user_id ==
                     request.identity['user'].user_id)))
     items = hosts.all()
     items.insert(0, ('', '-- Choose Host --'))
     return dict(items=items)
예제 #8
0
파일: hosts.py 프로젝트: csmall/rnms
 def option(self):
     """ Return a list of hosts. If user has required
     permission it shows all, else just their ones """
     if permissions.host_ro:
         hosts = DBSession.query(Host.id, Host.display_name)
     else:
         hosts = DBSession.query(Host.id, Host.display_name).filter(
             Host.id.in_(
                 DBSession.query(Attribute.host_id).filter(
                     Attribute.user_id == request.identity['user'].user_id)
             )
         )
     items = hosts.all()
     items.insert(0, ('', '-- Choose Host --'))
     return dict(items=items)
예제 #9
0
 def prepare(self):
     conditions = []
     conditions.append(Host.show_host == True)  # noqa
     if self.zone_id is not None:
         conditions.append(Host.zone_id == self.zone_id)
     hosts = DBSession.query(Host).join(Zone).filter(
         and_(*conditions)).order_by(asc(Zone.display_name),
                                     asc(Host.display_name))
     if hosts.count() == 0:
         flash('No Hosts Found', 'alert')
         self.map_groups = None
     else:
         for host in hosts:
             vendor, device = host.snmp_type()
             hstate, state_desc = self.host_state(host)
             if self.alarmed_only and hstate == 'ok':
                 continue
             host_fields = [('Zone', host.zone.display_name),
                            ('Status', state_desc), ('Vendor', vendor),
                            ('Device', device),
                            ('Address', host.mgmt_address)]
             self.add_item(
                 host.zone_id, host.zone.display_name, [], {
                     'name': host.display_name,
                     'state': hstate,
                     'url': url('/attributes/map/', {'h': host.id}),
                     'fields': host_fields,
                 })
     super(HostMap, self).prepare()
예제 #10
0
파일: alarms.py 프로젝트: nomed/rnms
def check_alarm_triggers(logger):
    alarms = DBSession.query(Alarm).filter(Alarm.processed == False)
    triggers = Trigger.alarm_triggers()
    logger.info('%d Alarms to process', alarms.count())
    if alarms.count() == 0:
        return
    for alarm in alarms:
        for trigger in triggers:
            rule_result = False
            for rule in trigger.rules:
                rule_result = rule.eval(rule_result, alarm)
                if rule_result == True and rule.stop == True:
                    break

            if rule_result == True:
                if trigger.email_owner == True:
                    logger.debug('A%d T%d: email to %s', alarm.attribute.id,
                                 trigger.id, alarm.attribute.user.user_name)
                    email_action(trigger, alarm.attribute.user, alarm=alarm)
            if trigger.email_users == True:
                sent_users = []
                for trigger_user in trigger.users:
                    sent_users.append(alarm.attribute.user.user_name)
                    trigger.email_action(trigger, trigger_user, alarm=alarm)
                if sent_users != []:
                    logger.debug('A%d T%d: email to %s', alarm.attribute.id,
                                 trigger.id, ','.join(sent_users))
        alarm.processed = True
    transaction.commit()
예제 #11
0
파일: traps.py 프로젝트: csmall/rnms
    def consolidate(self):
        """ Run the consolidator for SNMP traps """
        traps = DBSession.query(SnmpTrap).\
            filter(SnmpTrap.processed == False)  # noqa
        self.logger.info('%d SNMP Traps to process', traps.count())
        if traps.count() == 0:
            return

        for trap in traps:
            trap.processed = True
            try:
                trap_matches = self.trap_matches[trap.trap_oid]
            except KeyError:
                continue
            for trap_match in trap_matches:
                (attribute, trap_value, error) = \
                    trap_match.run(trap.host, trap)
                if error is not None:
                    self.logger.warn(
                        'TrapMatch error: %s',
                        error)
                    continue
                if attribute is not None:
                    # We have matched to this trap
                    backend_result = \
                        trap_match.backend.run(None, attribute, trap_value)
                    self.logger.debug(
                        "A:%d Trap:%s -> %s:%s",
                        attribute.id,
                        str(trap_value)[:100],
                        trap_match.backend.display_name,
                        backend_result)
                    if trap_match.stop_if_match is True:
                        break
        transaction.commit()
예제 #12
0
파일: events.py 프로젝트: csmall/rnms
def process_events(logger):
    """
    Scan all events that have not been previously checked and set alerts
    where required.
    Returns a set of changed attributes
    """
    changed_attributes = set()
    events = DBSession.query(Event).filter(Event.processed == False)
    logger.info('%d Events to process', events.count())
    for event in events:
        if event.event_state is None or event.attribute is None:
            event.set_processed()
            continue


        if event.event_state.is_up():
            event.acknowledged = True

        changed_attributes.add(event.attribute_id)

        if event.event_state.is_alert() == False:
            down_event = Event.find_down(event.attribute_id,
                                         event.event_type_id,
                                        event.id)
            if event.event_state.is_downtesting():
                process_event_downtesting(logger, event, down_event)
            elif event.event_state.is_up():
                process_event_up(logger, event, down_event)
        event.set_processed()
    transaction.commit()
    return changed_attributes
예제 #13
0
파일: events.py 프로젝트: nomed/rnms
def process_events(logger):
    """
    Scan all events that have not been previously checked and set alerts
    where required.
    Returns a set of changed attributes
    """
    changed_attributes = set()
    events = DBSession.query(Event).filter(Event.processed == False)
    logger.info('%d Events to process', events.count())
    for event in events:
        if event.event_state is None or event.attribute is None:
            event.set_processed()
            continue

        if event.event_state.is_up():
            event.acknowledged = True

        changed_attributes.add(event.attribute_id)

        if event.event_state.is_alert() == False:
            down_event = Event.find_down(event.attribute_id,
                                         event.event_type_id, event.id)
            if event.event_state.is_downtesting():
                process_event_downtesting(logger, event, down_event)
            elif event.event_state.is_up():
                process_event_up(logger, event, down_event)
        event.set_processed()
    transaction.commit()
    return changed_attributes
예제 #14
0
    def _get_tabledata(self, table, conditions=None, **kw):
        query = DBSession.query(table)
        if conditions is not None and conditions != []:
            query = query.filter(and_(*conditions))
        if 'sort' in kw:
            insp = inspect(table)
            try:
                sort_col = insp.columns[kw['sort']]
            except KeyError:
                try:
                    sort_table = insp.relationships[kw['sort']]
                    sort_col = sort_table.table.c['display_name']
                    query = query.join(sort_table.table)
                except KeyError:
                    return None
            sort_order = kw.get('order')  # default is asc
            if sort_order == 'desc':
                query = query.order_by(desc(sort_col))
            else:
                query = query.order_by(sort_col)
        total = query.count()
        if 'offset' in kw:
            query = query.offset(kw['offset'])
        if 'limit' in kw:
            query = query.limit(kw['limit'])

        return (total, query)
예제 #15
0
파일: traps.py 프로젝트: nomed/rnms
    def consolidate(self):
        """ Run the consolidator for SNMP traps """
        traps = DBSession.query(SnmpTrap).\
            filter(SnmpTrap.processed == False)  # noqa
        self.logger.info('%d SNMP Traps to process', traps.count())
        if traps.count() == 0:
            return

        for trap in traps:
            trap.processed = True
            try:
                trap_matches = self.trap_matches[trap.trap_oid]
            except KeyError:
                continue
            for trap_match in trap_matches:
                (attribute, trap_value, error) = \
                    trap_match.run(trap.host, trap)
                if error is not None:
                    self.logger.warn('TrapMatch error: %s', error)
                    continue
                if attribute is not None:
                    # We have matched to this trap
                    backend_result = \
                        trap_match.backend.run(None, attribute, trap_value)
                    self.logger.debug("A:%d Trap:%s -> %s:%s", attribute.id,
                                      str(trap_value)[:100],
                                      trap_match.backend.display_name,
                                      backend_result)
                    if trap_match.stop_if_match is True:
                        break
        transaction.commit()
예제 #16
0
파일: attribute.py 프로젝트: csmall/rnms
 def field_value(cls, attribute_id, field_tag):
     """ Return the value of the field for the given attribute that
     matches the tag
     """
     ftag = DBSession.query(AttributeTypeField).\
         join(AttributeType, Attribute).filter(
             Attribute.id == attribute_id,
             AttributeTypeField.tag == field_tag).first()
     if ftag is None:
         return None
     fval = DBSession.query(cls.value).filter(
         cls.attribute_id == attribute_id,
         cls.attribute_type_field_id == ftag.id).first()
     if fval is not None:
         return fval[0]
     return ftag.default_value
예제 #17
0
파일: events.py 프로젝트: nomed/rnms
 def mapseveritycss(self):
     severities = DBSession.query(Severity)
     return dict(
         severities=[
             (s.id, s.bgcolor,
                 '%.6x' % (int(s.bgcolor, 16) & 0xfefefe >> 1))
             for s in severities],)
예제 #18
0
파일: alarms.py 프로젝트: csmall/rnms
def check_alarm_triggers(logger):
    alarms = DBSession.query(Alarm).filter(Alarm.processed == False)
    triggers = Trigger.alarm_triggers()
    logger.info('%d Alarms to process', alarms.count())
    if alarms.count() == 0:
        return
    for alarm in alarms:
        for trigger in triggers:
            rule_result = False
            for rule in trigger.rules:
                rule_result = rule.eval(rule_result, alarm)
                if rule_result == True and rule.stop == True:
                    break

            if rule_result == True:
                if trigger.email_owner == True:
                    logger.debug('A%d T%d: email to %s',alarm.attribute.id, trigger.id, alarm.attribute.user.user_name)
                    email_action(trigger, alarm.attribute.user, alarm=alarm)
            if trigger.email_users == True:
                sent_users = []
                for trigger_user in trigger.users:
                    sent_users.append(alarm.attribute.user.user_name)
                    trigger.email_action(trigger, trigger_user,alarm=alarm)
                if sent_users != [] :
                    logger.debug('A%d T%d: email to %s',alarm.attribute.id, trigger.id, ','.join(sent_users))
        alarm.processed = True
    transaction.commit()
예제 #19
0
파일: host.py 프로젝트: csmall/rnms
 def prepare(self):
     conditions = []
     conditions.append(Host.show_host == True)  # noqa
     if self.zone_id is not None:
         conditions.append(Host.zone_id == self.zone_id)
     hosts = DBSession.query(Host).join(Zone).filter(
         and_(*conditions)).order_by(asc(Zone.display_name),
                                     asc(Host.display_name))
     if hosts.count() == 0:
         flash('No Hosts Found',  'alert')
         self.map_groups = None
     else:
         for host in hosts:
             vendor, device = host.snmp_type()
             hstate, state_desc = self.host_state(host)
             if self.alarmed_only and hstate == 'ok':
                 continue
             host_fields = [('Zone', host.zone.display_name),
                            ('Status', state_desc),
                            ('Vendor', vendor),
                            ('Device', device),
                            ('Address', host.mgmt_address)]
             self.add_item(host.zone_id, host.zone.display_name,
                           [],
                           {'name': host.display_name,
                            'state': hstate,
                            'url': url('/attributes/map/', {'h': host.id}),
                            'fields': host_fields,
                            })
     super(HostMap, self).prepare()
예제 #20
0
파일: attribute.py 프로젝트: csmall/rnms
    def prepare(self):
        conditions = []
        if self.host_id is not None:
            conditions.append(Attribute.host_id == self.host_id)
        if self.alarmed_only:
            conditions.append(EventState.internal_state != State.UP)
        attributes = DBSession.query(Attribute).join(Host, EventState).\
            filter(and_(*conditions)).\
            order_by(asc(Host.display_name), asc(Attribute.display_name))
        if attributes.count() == 0:
            flash('No Attributes Found', 'alert')
            self.map_groups = None
        else:
            for attribute in attributes:
                astate, state_desc = self.attribute_state(attribute)

                try:
                    atype = attribute.attribute_type.display_name
                except AttributeError:
                    atype = 'Unknown'
                att_fields = [('Host', attribute.host.display_name),
                              ('Type', atype),
                              ('Status', state_desc), ]
                for k, v in attribute.description_dict().items():
                    if v != '':
                        att_fields.append((k, v))
                self.add_item(attribute.host_id, attribute.host.display_name,
                              [('Address', attribute.host.mgmt_address)],
                              {'name': attribute.display_name,
                               'state': astate,
                               'url': url('/attributes/'+str(attribute.id)),
                               'fields': att_fields,
                               })
        super(AttributeMap, self).prepare()
예제 #21
0
파일: attribute.py 프로젝트: csmall/rnms
 def next_sla_analysis(cls):
     """
     Return the attribute that would be the next one for SLA
     Used for finding how long before we need to rescan again
     """
     return DBSession.query(cls).\
         filter(and_(cls.sla_id > 1, cls.poller_set_id > 1)).\
         order_by(asc(cls.next_sla)).first()
예제 #22
0
파일: attributes.py 프로젝트: csmall/rnms
 def type_option(self):
     """ Show option list of Attribute Types """
     types = DBSession.query(
         AttributeType.id,
         AttributeType.display_name)
     items = types.all()
     items.insert(0, ('', '-- Choose Type --'))
     return dict(items=items)
예제 #23
0
파일: event.py 프로젝트: csmall/rnms
 def alarmed_events(cls, conditions):
     """
     Find all alarmed Events with extra conditions
     """
     conditions.extend([
         cls.alarmed == True,  # noqa
         cls.stop_time == None])
     return DBSession.query(cls).join(EventState).filter(and_(*conditions))
예제 #24
0
파일: root.py 프로젝트: nomed/rnms
 def attribute_client_option(self):
     """ Show option list of all users who own attributes """
     users = DBSession.query(
         model.User.user_id,
         model.User.display_name).join(model.Attribute).distinct()
     items = users.all()
     items.insert(0, ('', '-- Choose Client --'))
     return dict(items=items)
예제 #25
0
파일: attributes.py 프로젝트: csmall/rnms
 def _get_host_attributes(self, host_id, atype_id):
     """ Return a list of Attributes for the given hosts for a given
     AttributeType """
     atts = DBSession.query(Attribute).filter(and_(
         Attribute.host_id == host_id,
         Attribute.attribute_type_id == atype_id))
     if atts is None:
         return {}
     return {att.index: att for att in atts}
예제 #26
0
파일: attributes.py 프로젝트: csmall/rnms
 def _get_host_attributes(self):
     host_atts = {}
     atts = DBSession.query(Attribute).filter(
         Attribute.host_id == self.dhost.id)
     for att in atts:
         if att.attribute_type_id not in host_atts:
             host_atts[att.attribute_type_id] = {}
         host_atts[att.attribute_type_id][att.index] = att
     return host_atts
예제 #27
0
 def _get_host_attributes(self):
     host_atts = {}
     atts = DBSession.query(Attribute).filter(
         Attribute.host_id == self.dhost.id)
     for att in atts:
         if att.attribute_type_id not in host_atts:
             host_atts[att.attribute_type_id] = {}
         host_atts[att.attribute_type_id][att.index] = att
     return host_atts
예제 #28
0
파일: logfiles.py 프로젝트: csmall/rnms
 def consolidate(self):
     """ Run the actual consolidation for logfiles """
     logfiles = DBSession.query(Logfile)
     for logfile in logfiles:
         if logfile.id == 1:  # Magic 1 means internal database
             self._cons_syslog(logfile)
         else:
             self._cons_logfile(logfile)
     transaction.commit()
예제 #29
0
 def alarmed_events(cls, conditions):
     """
     Find all alarmed Events with extra conditions
     """
     conditions.extend([
         cls.alarmed == True,  # noqa
         cls.stop_time == None
     ])
     return DBSession.query(cls).join(EventState).filter(and_(*conditions))
예제 #30
0
 def _get_host_attributes(self, host_id, atype_id):
     """ Return a list of Attributes for the given hosts for a given
     AttributeType """
     atts = DBSession.query(Attribute).filter(
         and_(Attribute.host_id == host_id,
              Attribute.attribute_type_id == atype_id))
     if atts is None:
         return {}
     return {att.index: att for att in atts}
예제 #31
0
 def host_alarm(cls, host_id):
     """
     Return the highest priority alarmed Event for the given Host id
 """
     return cls.alarmed_events([
         cls.attribute_id.in_(
             DBSession.query(
                 Attribute.id).filter(Attribute.host_id == host_id))
     ]).order_by(desc(EventState.priority)).first()
예제 #32
0
파일: logfiles.py 프로젝트: nomed/rnms
 def consolidate(self):
     """ Run the actual consolidation for logfiles """
     logfiles = DBSession.query(Logfile)
     for logfile in logfiles:
         if logfile.id == 1:  # Magic 1 means internal database
             self._cons_syslog(logfile)
         else:
             self._cons_logfile(logfile)
     transaction.commit()
예제 #33
0
파일: attribute.py 프로젝트: csmall/rnms
 def discovered_exists(cls, host_id, attribute_type_id, index):
     """
     Return True if this discovered item already exists
     """
     query = DBSession.query(cls.id).filter(and_(
         cls.host_id == host_id,
         cls.attribute_type_id == attribute_type_id,
         cls.index == index)).first()
     return query is not None
예제 #34
0
 def _delete_users(self):
     """ Delete all items of del_model with an ID higher than del_id
         Returns number of deleted items
     """
     deleted_items = DBSession.query(model.User).\
         filter(model.User.user_id > 2).delete()
     if deleted_items is None:
         return 0
     return deleted_items
예제 #35
0
파일: event.py 프로젝트: csmall/rnms
 def host_alarm(cls, host_id):
     """
     Return the highest priority alarmed Event for the given Host id
 """
     return cls.alarmed_events(
         [cls.attribute_id.in_(
             DBSession.query(Attribute.id).
             filter(Attribute.host_id == host_id))]).order_by(
             desc(EventState.priority)).first()
예제 #36
0
 def _delete_users(self):
     """ Delete all items of del_model with an ID higher than del_id
         Returns number of deleted items
     """
     deleted_items = DBSession.query(model.User).\
         filter(model.User.user_id > 2).delete()
     if deleted_items is None:
         return 0
     return deleted_items
예제 #37
0
파일: logfiles.py 프로젝트: csmall/rnms
 def load_config(self):
     """ Load configuration for logfiles consolidation """
     self.match_sets = {}
     db_sets = DBSession.query(LogmatchSet)
     for db_set in db_sets:
         self.match_sets[db_set.id] = []
         for row in db_set.rows:
             self.match_sets[db_set.id].append(MatchRow(row))
     self.logger.debug(
         "Consolidator loaded %d match sets.\n", len(self.match_sets))
예제 #38
0
파일: logfiles.py 프로젝트: nomed/rnms
 def load_config(self):
     """ Load configuration for logfiles consolidation """
     self.match_sets = {}
     db_sets = DBSession.query(LogmatchSet)
     for db_set in db_sets:
         self.match_sets[db_set.id] = []
         for row in db_set.rows:
             self.match_sets[db_set.id].append(MatchRow(row))
     self.logger.debug("Consolidator loaded %d match sets.\n",
                       len(self.match_sets))
예제 #39
0
 def set_limit(self, limits):
     from rnms.model import EventType
     """ Convert the limits as tags into indexes """
     fname = trigger_fields[self.field]
     if fname == 'event_type':
         self.limit = ','.join(
             [unicode(x[0]) for x in DBSession.query(EventType.id).
                 filter(EventType.tag.in_(limits.split(',')))])
         return
     raise ValueError('Dont have limits for {}'.format(fname))
예제 #40
0
파일: traps.py 프로젝트: csmall/rnms
 def load_config(self):
     """ Load configuration from Database """
     self.trap_matches = defaultdict(list)
     trap_match_count = 0
     for trap_match in DBSession.query(TrapMatch).\
             order_by(TrapMatch.position):
         trap_match_count += 1
         self.trap_matches[trap_match.trap_oid].append(
             MatchTrap(trap_match))
     self.logger.debug("Trap Consolidator loaded %d trap rules.",
                       trap_match_count)
예제 #41
0
파일: traps.py 프로젝트: nomed/rnms
 def load_config(self):
     """ Load configuration from Database """
     self.trap_matches = defaultdict(list)
     trap_match_count = 0
     for trap_match in DBSession.query(TrapMatch).\
             order_by(TrapMatch.position):
         trap_match_count += 1
         self.trap_matches[trap_match.trap_oid].append(
             MatchTrap(trap_match))
     self.logger.debug("Trap Consolidator loaded %d trap rules.",
                       trap_match_count)
예제 #42
0
파일: attributes.py 프로젝트: csmall/rnms
def check_all_attributes_state(logger):
    """ Recalculate all Attributes Oper state
    This is done when the consolidator is first started
    """
    logger.debug('Recalculating all Attributes Oper state')
    attributes = DBSession.query(Attribute)
    if attributes is None:
        return
    for attribute in attributes:
        attribute.calculate_oper()
    transaction.commit()
예제 #43
0
파일: attribute.py 프로젝트: csmall/rnms
 def have_sla(cls, next_sla_time=None, attribute_ids=None, host_ids=None):
     """ Return attributes have have a SLA set plus polling """
     conditions = [cls.sla_id > 1, cls.poller_set_id > 1]
     if next_sla_time is not None:
         conditions.append(cls.next_sla < next_sla_time)
     if attribute_ids is not None:
         conditions.append(cls.id.in_(attribute_ids))
     if host_ids is not None:
         conditions.append(cls.host_id.in_(host_ids))
     return DBSession.query(cls).options(subqueryload('sla')).\
         filter(and_(*conditions))
예제 #44
0
파일: attributes.py 프로젝트: csmall/rnms
def check_attribute_state(attribute_ids, logger):
    """ Recalculate the given Attributes Oper state """
    if len(attribute_ids) == 0:
        return
    attributes = DBSession.query(Attribute).filter(Attribute.id.in_(list(attribute_ids)))
    if attributes.count() == 0:
        return
    logger.info('%d Attribute States to process', attributes.count())
    for attribute in attributes:
        attribute.calculate_oper()
    transaction.commit()
예제 #45
0
파일: attributes.py 프로젝트: nomed/rnms
def check_all_attributes_state(logger):
    """ Recalculate all Attributes Oper state
    This is done when the consolidator is first started
    """
    logger.debug('Recalculating all Attributes Oper state')
    attributes = DBSession.query(Attribute)
    if attributes is None:
        return
    for attribute in attributes:
        attribute.calculate_oper()
    transaction.commit()
예제 #46
0
파일: logfiles.py 프로젝트: csmall/rnms
 def _cons_syslog(self, logfile):
     """ Consolidates syslog messages from database """
     self.logger.info("LOGF: 1 (database)")
     try:
         match_set = self.match_sets[logfile.logmatchset_id]
     except KeyError:
         self.logger.error("LOGF(%s): MatchSet %d not found",
                           logfile.id, logfile.logmatchset_id)
         return
     lines = DBSession.query(SyslogMessage).\
         filter(SyslogMessage.consolidated == False)  # noqa
     self._run_matches(logfile.id, match_set, lines)
예제 #47
0
파일: attributes.py 프로젝트: nomed/rnms
def check_attribute_state(attribute_ids, logger):
    """ Recalculate the given Attributes Oper state """
    if len(attribute_ids) == 0:
        return
    attributes = DBSession.query(Attribute).filter(
        Attribute.id.in_(list(attribute_ids)))
    if attributes.count() == 0:
        return
    logger.info('%d Attribute States to process', attributes.count())
    for attribute in attributes:
        attribute.calculate_oper()
    transaction.commit()
예제 #48
0
파일: logfiles.py 프로젝트: nomed/rnms
 def _cons_syslog(self, logfile):
     """ Consolidates syslog messages from database """
     self.logger.info("LOGF: 1 (database)")
     try:
         match_set = self.match_sets[logfile.logmatchset_id]
     except KeyError:
         self.logger.error("LOGF(%s): MatchSet %d not found", logfile.id,
                           logfile.logmatchset_id)
         return
     lines = DBSession.query(SyslogMessage).\
         filter(SyslogMessage.consolidated == False)  # noqa
     self._run_matches(logfile.id, match_set, lines)
예제 #49
0
파일: doughnuts.py 프로젝트: nomed/rnms
 def prepare(self):
     conditions = []
     self.graph_data = []
     if self.host_id is not None:
         conditions.append(Attribute.host_id == self.host_id)
     for match, label in State.NAMES.items():
         self.graph_data.append((label, DBSession.query(Attribute).filter(
             and_(*conditions + [
                 Attribute.state_id == EventState.id,
                 EventState.internal_state == match
             ])).count()))
     super(AttributeStateDoughnut, self).prepare()
예제 #50
0
파일: match_trap.py 프로젝트: nomed/rnms
 def _run_first(self, host, trap):
     """
     Return the first Attribute for given host that has the
     required AttributeType. Used for where the Attribute doesn't
     matter OR there is only one of this AttributeType per host.
     Parameters: ignored
     """
     return (DBSession.query(Attribute).filter(
         and_(
             Attribute.host_id == host.id,
             Attribute.attribute_type_id == self._attribute_type_id,
         )).first(), None)
     return (None, None)
예제 #51
0
    def prepare(self):
        hostid_filter = []
        attribute_count = 0
        if self.host_id is not None:
            hostid_filter = [Attribute.host_id == self.host_id]
        admin_down = DBSession.query(func.count(Attribute.id)).\
            filter(and_(*(
                hostid_filter + [Attribute.admin_state == State.DOWN]
            ))).first()
        attribute_count += int(admin_down[0])

        db_states = DBSession.query(
            EventState.internal_state, func.count(Attribute.id)).\
            join(Attribute).filter(and_(
                *(hostid_filter +
                  [Attribute.admin_state != State.DOWN]))).\
            group_by(EventState.internal_state)
        tmp_states = {}
        for att in db_states:
            tmp_states[att[0]] = att[1]
            attribute_count += att[1]

        self.graph_data = []
        for state_val, label in State.NAMES.items():
            if state_val == State.ADMIN_DOWN:
                self.graph_data.append((
                    label.capitalize(),
                    0 if attribute_count == 0 else
                    admin_down[0]*100/attribute_count,
                    admin_down[0]))
            else:
                try:
                    self.graph_data.append(
                        (label.capitalize(),
                         tmp_states[state_val]*100/attribute_count,
                         tmp_states[state_val]))
                except KeyError:
                    self.graph_data.append((label.capitalize(), 0, 0))
        super(HBarGraph, self).prepare()
예제 #52
0
 def find_down(cls, attribute, event_type):
     """
     Find the first down or testing alarm of the given event_type
     for this attribute.
     """
     from rnms.model.event import EventState, Event
     if attribute is None or event_type is None:
         return None
     return DBSession.query(cls).join(Event, EventState).filter(
         and_(
             cls.event.attribute_id == attribute.id,
             cls.event.event_type_id == event_type.id,
             EventState.internal_state.in_([State.DOWN, State.TESTING]),
         )).order_by(desc(cls.id)).first()
예제 #53
0
 def find_down(cls, attribute_id, event_type_id, exclude_event=None):
     """
     Find the first down or testing alarmed Event of the given
     EventType and Attribute
     """
     conditions = [
         cls.alarmed == True,  # noqa
         cls.stop_time == None,
         cls.attribute_id == attribute_id,
         cls.event_type_id == event_type_id,
         EventState.internal_state.in_([State.DOWN, State.TESTING])
     ]
     if exclude_event is not None:
         conditions.append(cls.id != exclude_event)
     return DBSession.query(cls).join(EventState).filter(
         and_(*conditions)).order_by(desc(cls.id)).first()
예제 #54
0
 def parse_range_max(self, attribute_id):
     """
     range_max can either be the value stored in that field, or
     derived from an attributes field
     """
     if self.range_max_field == '':
         return self.range_max
     attribute_field = DBSession.query(AttributeField).filter(and_(
         AttributeField.attribute_id == attribute_id,
         AttributeField.attribute_type_field_id == AttributeTypeField.id,
         AttributeTypeField.tag == self.range_max_field)).first()
     if attribute_field is None:
         return 'U'
     new_max = int(attribute_field.value)
     if new_max == 0:
         return 'U'
     return new_max
예제 #55
0
    def _fill_host_table(self, host_ids):
        """
        Add all or some hosts to the objects list that need
        autodiscovery run on them to find attributes
        """
        conditions = [Host.id > 1]
        if host_ids is not None:
            assert (type(host_ids) == list)
            conditions.append(Host.id.in_(host_ids))
        else:
            conditions.append(Host.pollable == True)  # noqa

        hosts = DBSession.query(Host).options(
            joinedload(Host.autodiscovery_policy),
            joinedload(Host.ro_community)).filter(and_(*conditions))
        for host in hosts:
            self._waiting_hosts.append(DiscoveryHost(self, host))