Search in sources :

Example 1 with IfTttConfig

use of org.opennms.features.ifttt.config.IfTttConfig in project opennms by OpenNMS.

the class IfTttDaemon method startPoller.

/**
 * Initializes and starts the alarm poller.
 *
 * @param pollInterval the poller interval to be used
 */
private void startPoller(final long pollInterval) {
    LOG.debug("Starting alarm poller (interval {}s).", pollInterval);
    m_alarmPoller = Executors.newScheduledThreadPool(1);
    m_alarmPoller.scheduleWithFixedDelay(new Runnable() {

        private Map<Boolean, Map<String, Integer>> oldAlarmCount = new HashMap<>();

        private Map<Boolean, Map<String, OnmsSeverity>> oldSeverity = new HashMap<>();

        {
            oldAlarmCount.put(Boolean.TRUE, new HashMap<>());
            oldAlarmCount.put(Boolean.FALSE, new HashMap<>());
            oldSeverity.put(Boolean.TRUE, new HashMap<>());
            oldSeverity.put(Boolean.FALSE, new HashMap<>());
        }

        private List<OnmsAlarm> filterAlarms(List<OnmsAlarm> alarms, TriggerPackage triggerPackage) {
            if (triggerPackage.getOnlyUnacknowledged()) {
                return alarms.stream().filter(alarm -> alarm.getNodeId() != null).filter(alarm -> !alarm.isAcknowledged()).filter(alarm -> Strings.isNullOrEmpty(triggerPackage.getCategoryFilter()) || alarm.getNode().getCategories().stream().anyMatch(category -> category.getName().matches(triggerPackage.getCategoryFilter()))).collect(Collectors.toList());
            } else {
                return alarms.stream().filter(alarm -> alarm.getNodeId() != null).filter(alarm -> Strings.isNullOrEmpty(triggerPackage.getCategoryFilter()) || alarm.getNode().getCategories().stream().anyMatch(category -> category.getName().matches(triggerPackage.getCategoryFilter()))).collect(Collectors.toList());
            }
        }

        @Override
        public void run() {
            try {
                final IfTttConfig ifTttConfig = m_fileReloadContainer.getObject();
                if (ifTttConfig.getPollInterval() != pollInterval) {
                    restartPoller(ifTttConfig.getPollInterval());
                    return;
                }
                if (!ifTttConfig.getEnabled()) {
                    LOG.debug("Disabled - skipping alarm polling.");
                    return;
                }
                transactionOperations.execute(new TransactionCallbackWithoutResult() {

                    @Override
                    protected void doInTransactionWithoutResult(TransactionStatus status) {
                        // Retrieve the alarms with an associated node and filter for matching categories.
                        final CriteriaBuilder criteriaBuilder = new CriteriaBuilder(OnmsAlarm.class).isNotNull("node").gt("severity", OnmsSeverity.NORMAL);
                        final List<OnmsAlarm> alarms = alarmDao.findMatching(criteriaBuilder.toCriteria());
                        for (final TriggerPackage triggerPackage : ifTttConfig.getTriggerPackages()) {
                            if (!oldSeverity.get(triggerPackage.getOnlyUnacknowledged()).containsKey(triggerPackage.getCategoryFilter())) {
                                oldSeverity.get(triggerPackage.getOnlyUnacknowledged()).put(triggerPackage.getCategoryFilter(), OnmsSeverity.INDETERMINATE);
                                oldAlarmCount.get(triggerPackage.getOnlyUnacknowledged()).put(triggerPackage.getCategoryFilter(), 0);
                            }
                            final List<OnmsAlarm> filteredAlarms = filterAlarms(alarms, triggerPackage);
                            // Compute the maximum severity.
                            final Optional<OnmsSeverity> maxAlarmsSeverity = filteredAlarms.stream().map(OnmsAlarm::getSeverity).max(Comparator.naturalOrder());
                            final OnmsSeverity newSeverity = maxAlarmsSeverity.orElse(OnmsSeverity.NORMAL);
                            final int newAlarmCount = filteredAlarms.size();
                            LOG.debug("Received {} filtered, {} new severity", newAlarmCount, newSeverity);
                            final DefaultVariableNameExpansion defaultVariableNameExpansion = new DefaultVariableNameExpansion(oldSeverity.get(triggerPackage.getOnlyUnacknowledged()).get(triggerPackage.getCategoryFilter()), newSeverity, oldAlarmCount.get(triggerPackage.getOnlyUnacknowledged()).get(triggerPackage.getCategoryFilter()), newAlarmCount);
                            if (!newSeverity.equals(oldSeverity.get(triggerPackage.getOnlyUnacknowledged()).get(triggerPackage.getCategoryFilter())) || newAlarmCount != oldAlarmCount.get(triggerPackage.getOnlyUnacknowledged()).get(triggerPackage.getCategoryFilter())) {
                                fireIfTttTriggerSet(ifTttConfig, triggerPackage.getCategoryFilter(), newSeverity, defaultVariableNameExpansion);
                            }
                            LOG.debug("Old severity: {}, new severity: {}, old alarm count: {}, new alarm count: {}", oldSeverity.get(triggerPackage.getOnlyUnacknowledged()).get(triggerPackage.getCategoryFilter()), newSeverity, oldAlarmCount.get(triggerPackage.getOnlyUnacknowledged()).get(triggerPackage.getCategoryFilter()), newAlarmCount);
                            oldSeverity.get(triggerPackage.getOnlyUnacknowledged()).put(triggerPackage.getCategoryFilter(), newSeverity);
                            oldAlarmCount.get(triggerPackage.getOnlyUnacknowledged()).put(triggerPackage.getCategoryFilter(), newAlarmCount);
                        }
                    }
                });
            } catch (Exception e) {
                LOG.error("Error while polling alarm table.", e);
            } finally {
                LOG.debug("Run complete. Next poll in {}s.", pollInterval);
            }
        }
    }, pollInterval, pollInterval, TimeUnit.SECONDS);
}
Also used : Trigger(org.opennms.features.ifttt.config.Trigger) TriggerPackage(org.opennms.features.ifttt.config.TriggerPackage) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) OnmsAlarm(org.opennms.netmgt.model.OnmsAlarm) Strings(com.google.common.base.Strings) DefaultVariableNameExpansion(org.opennms.features.ifttt.helper.DefaultVariableNameExpansion) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) JaxbUtils(org.opennms.core.xml.JaxbUtils) FileReloadContainer(org.opennms.core.spring.FileReloadContainer) Logger(org.slf4j.Logger) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) IfTttConfig(org.opennms.features.ifttt.config.IfTttConfig) TriggerSet(org.opennms.features.ifttt.config.TriggerSet) Collectors(java.util.stream.Collectors) File(java.io.File) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) Paths(java.nio.file.Paths) VariableNameExpansion(org.opennms.features.ifttt.helper.VariableNameExpansion) AlarmDao(org.opennms.netmgt.dao.api.AlarmDao) TransactionOperations(org.springframework.transaction.support.TransactionOperations) TransactionStatus(org.springframework.transaction.TransactionStatus) Optional(java.util.Optional) CriteriaBuilder(org.opennms.core.criteria.CriteriaBuilder) Comparator(java.util.Comparator) IfTttTrigger(org.opennms.features.ifttt.helper.IfTttTrigger) OnmsSeverity(org.opennms.netmgt.model.OnmsSeverity) CriteriaBuilder(org.opennms.core.criteria.CriteriaBuilder) TriggerPackage(org.opennms.features.ifttt.config.TriggerPackage) HashMap(java.util.HashMap) OnmsAlarm(org.opennms.netmgt.model.OnmsAlarm) TransactionStatus(org.springframework.transaction.TransactionStatus) OnmsSeverity(org.opennms.netmgt.model.OnmsSeverity) IfTttConfig(org.opennms.features.ifttt.config.IfTttConfig) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) DefaultVariableNameExpansion(org.opennms.features.ifttt.helper.DefaultVariableNameExpansion)

Example 2 with IfTttConfig

use of org.opennms.features.ifttt.config.IfTttConfig in project opennms by OpenNMS.

the class IfTttDaemonTest method runIfTttDaemonTest.

public Map<String, List<ResultEntry>> runIfTttDaemonTest(int timeout, int entryCount) throws Exception {
    final AlarmDao alarmDao = mock(AlarmDao.class);
    when(alarmDao.findMatching((Criteria) Matchers.anyObject())).thenReturn(alarmMap.values().stream().collect(Collectors.toList()));
    final TransactionOperations transactionOperations = mock(TransactionOperations.class);
    when(transactionOperations.execute(Matchers.anyObject())).thenAnswer(new Answer<Void>() {

        @Override
        public Void answer(InvocationOnMock invocationOnMock) throws Throwable {
            TransactionCallbackWithoutResult transactionCallbackWithoutResult = invocationOnMock.getArgumentAt(0, TransactionCallbackWithoutResult.class);
            transactionCallbackWithoutResult.doInTransaction(null);
            return null;
        }
    });
    // final List<ResultEntry> receivedEntries = new ArrayList<>();
    final Map<String, List<ResultEntry>> receivedEntries = new HashMap<>();
    final IfTttDaemon ifTttDaemon = new IfTttDaemon(alarmDao, transactionOperations, new File("src/test/resources/etc/ifttt-config.xml")) {

        @Override
        protected void fireIfTttTriggerSet(IfTttConfig ifTttConfig, String categoryFilter, String name, VariableNameExpansion variableNameExpansion) {
            if (!receivedEntries.containsKey(categoryFilter)) {
                receivedEntries.put(categoryFilter, new ArrayList<>());
            }
            receivedEntries.get(categoryFilter).add(new ResultEntry(name, variableNameExpansion));
        }
    };
    ifTttDaemon.start();
    await().atMost(timeout, SECONDS).until(() -> allEntrySizesMatch(receivedEntries, entryCount - 2));
    LOG.debug("#1: {}", receivedEntries);
    addAlarm(12, 4, OnmsSeverity.MAJOR);
    when(alarmDao.findMatching((Criteria) Matchers.anyObject())).thenReturn(alarmMap.values().stream().collect(Collectors.toList()));
    await().atMost(timeout, SECONDS).until(() -> allEntrySizesMatch(receivedEntries, entryCount - 1));
    LOG.debug("#2: {}", receivedEntries);
    ifTttDaemon.stop();
    await().atMost(timeout, SECONDS).until(() -> allEntrySizesMatch(receivedEntries, entryCount));
    LOG.debug("#3: {}", receivedEntries);
    return receivedEntries;
}
Also used : TransactionOperations(org.springframework.transaction.support.TransactionOperations) HashMap(java.util.HashMap) AlarmDao(org.opennms.netmgt.dao.api.AlarmDao) InvocationOnMock(org.mockito.invocation.InvocationOnMock) IfTttConfig(org.opennms.features.ifttt.config.IfTttConfig) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) TransactionCallbackWithoutResult(org.springframework.transaction.support.TransactionCallbackWithoutResult) DefaultVariableNameExpansion(org.opennms.features.ifttt.helper.DefaultVariableNameExpansion) VariableNameExpansion(org.opennms.features.ifttt.helper.VariableNameExpansion)

Aggregations

File (java.io.File)2 HashMap (java.util.HashMap)2 List (java.util.List)2 IfTttConfig (org.opennms.features.ifttt.config.IfTttConfig)2 DefaultVariableNameExpansion (org.opennms.features.ifttt.helper.DefaultVariableNameExpansion)2 VariableNameExpansion (org.opennms.features.ifttt.helper.VariableNameExpansion)2 AlarmDao (org.opennms.netmgt.dao.api.AlarmDao)2 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)2 TransactionOperations (org.springframework.transaction.support.TransactionOperations)2 Strings (com.google.common.base.Strings)1 Paths (java.nio.file.Paths)1 ArrayList (java.util.ArrayList)1 Comparator (java.util.Comparator)1 Map (java.util.Map)1 Optional (java.util.Optional)1 Executors (java.util.concurrent.Executors)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 TimeUnit (java.util.concurrent.TimeUnit)1 Collectors (java.util.stream.Collectors)1 InvocationOnMock (org.mockito.invocation.InvocationOnMock)1