Search in sources :

Example 16 with Notification

use of org.opennms.netmgt.config.notifications.Notification in project opennms by OpenNMS.

the class NotificationManagerIT method canMatchEventParametersWhenAcknowledgingNotices.

@Test
@JUnitTemporaryDatabase
public void canMatchEventParametersWhenAcknowledgingNotices() throws IOException, SQLException {
    // Insert some event in the database with a few event parameters
    OnmsEvent dbEvent = new OnmsEvent();
    dbEvent.setDistPoller(m_distPollerDao.whoami());
    dbEvent.setEventUei(EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI);
    dbEvent.setEventCreateTime(new Date());
    dbEvent.setEventLog("Y");
    dbEvent.setEventDisplay("Y");
    dbEvent.setEventSeverity(OnmsSeverity.CRITICAL.getId());
    dbEvent.setEventSource("test");
    dbEvent.setEventTime(new Date());
    dbEvent.setNode(node1);
    dbEvent.setEventParameters(Arrays.asList(new OnmsEventParameter(dbEvent, "some-parameter", "some-specific-value", "string"), new OnmsEventParameter(dbEvent, "some-other-parameter", "some-other-specific-value", "string")));
    m_eventDao.save(dbEvent);
    m_eventDao.flush();
    // Create some notification referencing the event we just created
    Notification notification = new Notification();
    Map<String, String> params = new ImmutableMap.Builder<String, String>().put(NotificationManager.PARAM_TEXT_MSG, "some text message").put(NotificationManager.PARAM_NODE, node1.getNodeId()).put(NotificationManager.PARAM_INTERFACE, InetAddressUtils.toIpAddrString(ipInterfaceOnNode1.getIpAddress())).put(NotificationManager.PARAM_SERVICE, "ICMP").put("eventUEI", dbEvent.getEventUei()).put("eventID", Integer.toString(dbEvent.getId())).build();
    m_notificationManager.insertNotice(1, params, "q1", notification);
    final String[] parmMatchList = new String[] { "parm[some-parameter]", "parm[#2]" };
    // Verify that we're able to match the the notice when we have the same parameters set
    Event e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").addParam("some-parameter", "some-specific-value").addParam("some-other-parameter", "some-other-specific-value").getEvent();
    Collection<Integer> eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, parmMatchList);
    assertEquals(1, eventIds.size());
    assertEquals(dbEvent.getId(), eventIds.iterator().next());
    unacknowledgeAllNotices();
    // It should not match when either of the event parameters are different
    e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").addParam("some-parameter", "!some-specific-value").addParam("some-other-parameter", "some-other-specific-value").getEvent();
    eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, parmMatchList);
    assertEquals(0, eventIds.size());
    unacknowledgeAllNotices();
    e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").addParam("some-parameter", "some-specific-value").addParam("some-other-parameter", "!some-other-specific-value").getEvent();
    eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, parmMatchList);
    assertEquals(0, eventIds.size());
    unacknowledgeAllNotices();
    // It should not match when either of the event parameters are missing
    e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").addParam("some-other-parameter", "some-other-specific-value").getEvent();
    eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, parmMatchList);
    assertEquals(0, eventIds.size());
    unacknowledgeAllNotices();
    e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").addParam("some-parameter", "some-specific-value").getEvent();
    eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, parmMatchList);
    assertEquals(0, eventIds.size());
    unacknowledgeAllNotices();
    // Now try matching on other fields without any event parameters
    final String[] fieldMatchList = new String[] { "nodeid", "interfaceid", "serviceid" };
    e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").setNodeid(node1.getId()).setInterface(ipInterfaceOnNode1.getIpAddress()).setService("ICMP").getEvent();
    eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, fieldMatchList);
    assertEquals(1, eventIds.size());
    unacknowledgeAllNotices();
    // Expect no match if we set different values responsive event
    e = new EventBuilder(EventConstants.SERVICE_RESPONSIVE_EVENT_UEI, "test").setNodeid(node1.getId() + 1).setInterface(InetAddressUtils.UNPINGABLE_ADDRESS).setService("HTTP").getEvent();
    eventIds = m_notificationManager.acknowledgeNotice(e, EventConstants.SERVICE_UNRESPONSIVE_EVENT_UEI, fieldMatchList);
    assertEquals(0, eventIds.size());
    unacknowledgeAllNotices();
}
Also used : Date(java.util.Date) Notification(org.opennms.netmgt.config.notifications.Notification) ImmutableMap(com.google.common.collect.ImmutableMap) OnmsEvent(org.opennms.netmgt.model.OnmsEvent) EventBuilder(org.opennms.netmgt.model.events.EventBuilder) OnmsEventParameter(org.opennms.netmgt.model.OnmsEventParameter) Event(org.opennms.netmgt.xml.event.Event) OnmsEvent(org.opennms.netmgt.model.OnmsEvent) Test(org.junit.Test) JUnitTemporaryDatabase(org.opennms.core.test.db.annotations.JUnitTemporaryDatabase)

Example 17 with Notification

use of org.opennms.netmgt.config.notifications.Notification in project opennms by OpenNMS.

the class NotificationManager method getNotifForEvent.

/**
 * <p>getNotifForEvent</p>
 *
 * @param event a {@link org.opennms.netmgt.xml.event.Event} object.
 * @return an array of {@link org.opennms.netmgt.config.notifications.Notification} objects.
 * @throws java.io.IOException if any.
 */
public Notification[] getNotifForEvent(final Event event) throws IOException {
    update();
    List<Notification> notifList = new ArrayList<>();
    boolean matchAll = getConfigManager().getNotificationMatch();
    if (event == null) {
        LOG.warn("unable to get notification for null event!");
        return null;
    } else if (event.getLogmsg() != null && !(event.getLogmsg().getNotify())) {
        LOG.debug("Event {} is configured to suppress notifications.", event.getUei());
        return null;
    }
    for (Notification curNotif : m_notifications.getNotifications()) {
        LOG.trace("Checking notification {} against event {} with UEI {}", curNotif.getUei(), event.getDbid(), event.getUei());
        if (event.getUei().equals(curNotif.getUei()) || "MATCH-ANY-UEI".equals(curNotif.getUei())) {
            // Match!
            LOG.debug("Exact match using notification UEI {} for event UEI: {}", curNotif.getUei(), event.getUei());
        } else if (curNotif.getUei().charAt(0) == '~') {
            if (event.getUei().matches(curNotif.getUei().substring(1))) {
                // Match!
                LOG.debug("Regex hit using notification UEI {} for event UEI: {}", curNotif.getUei(), event.getUei());
            } else {
                LOG.trace("Notification regex {} failed to match event UEI: {}", event.getUei(), curNotif.getUei());
                continue;
            }
        } else {
            LOG.debug("Notification UEI {} did not match UEI of event {}: {}", curNotif.getUei(), event.getDbid(), event.getUei());
            continue;
        }
        /**
         * Check if event severity matches pattern in notification
         */
        LOG.trace("Checking event severity: {} against notification severity: {}", curNotif.getEventSeverity().orElse(null), event.getSeverity());
        // parameter is optional, return true if not set
        if (!curNotif.getEventSeverity().isPresent()) {
        // Skip matching on severity
        } else if (event.getSeverity().toLowerCase().matches(curNotif.getEventSeverity().get().toLowerCase())) {
        // Severities match
        } else {
            LOG.debug("Event severity: {} did not match notification severity: {}", curNotif.getEventSeverity().orElse(null), event.getSeverity());
            continue;
        }
        if (curNotif.getStatus().equals("on")) {
            if (nodeInterfaceServiceValid(curNotif, event)) {
                boolean parmsmatched = getConfigManager().matchNotificationParameters(event, curNotif);
                if (!parmsmatched) {
                    LOG.debug("Event {} did not match parameters for notice {}", event.getUei(), curNotif.getName());
                    continue;
                }
                // Add this notification to the return value
                notifList.add(curNotif);
                LOG.debug("Event {} matched notice {}", event.getUei(), curNotif.getName());
                if (!matchAll)
                    break;
            } else {
                LOG.debug("Node/interface/service combination in the event was invalid");
            }
        } else {
            LOG.debug("Current notification with UEI {} is turned off.", curNotif.getUei());
        }
    }
    if (!notifList.isEmpty()) {
        return notifList.toArray(new Notification[0]);
    } else {
        return null;
    }
}
Also used : ArrayList(java.util.ArrayList) Notification(org.opennms.netmgt.config.notifications.Notification)

Example 18 with Notification

use of org.opennms.netmgt.config.notifications.Notification in project opennms by OpenNMS.

the class NotificationManager method getNotifications.

/**
 * <p>getNotifications</p>
 *
 * @return a {@link java.util.Map} object.
 * @throws java.io.IOException if any.
 */
public Map<String, Notification> getNotifications() throws IOException {
    update();
    Map<String, Notification> newMap = new HashMap<String, Notification>();
    for (final Notification notif : m_notifications.getNotifications()) {
        newMap.put(notif.getName(), notif);
    }
    return Collections.unmodifiableMap(newMap);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Notification(org.opennms.netmgt.config.notifications.Notification)

Example 19 with Notification

use of org.opennms.netmgt.config.notifications.Notification in project opennms by OpenNMS.

the class BroadcastEventProcessor method scheduleNoticesForEvent.

/**
 */
private void scheduleNoticesForEvent(Event event) {
    boolean mapsToNotice = false;
    try {
        mapsToNotice = getNotificationManager().hasUei(event.getUei());
    } catch (Throwable e) {
        LOG.error("Couldn't map uei {} to a notification entry, not scheduling notice.", event.getUei(), e);
        return;
    }
    if (mapsToNotice) {
        // in the event
        if (continueWithNotice(event)) {
            Notification[] notifications = null;
            try {
                notifications = getNotificationManager().getNotifForEvent(event);
            } catch (Throwable e) {
                LOG.error("Couldn't get notification mapping for event {}, not scheduling notice.", event.getUei(), e);
                return;
            }
            long nodeid = event.getNodeid();
            String ipaddr = event.getInterface();
            if (notifications != null) {
                for (Notification notification : notifications) {
                    int noticeId = 0;
                    try {
                        noticeId = getNotificationManager().getNoticeId();
                    } catch (Throwable e) {
                        LOG.error("Failed to get a unique id # for notification, exiting this notification", e);
                        continue;
                    }
                    Map<String, String> paramMap = buildParameterMap(notification, event, noticeId);
                    String queueID = (notification.getNoticeQueue().orElse("default"));
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("destination : {}", notification.getDestinationPath());
                        LOG.debug("text message: {}", paramMap.get(NotificationManager.PARAM_TEXT_MSG));
                        LOG.debug("num message : {}", paramMap.get(NotificationManager.PARAM_NUM_MSG));
                        LOG.debug("subject     : {}", paramMap.get(NotificationManager.PARAM_SUBJECT));
                        LOG.debug("node        : {}", paramMap.get(NotificationManager.PARAM_NODE));
                        LOG.debug("interface   : {}", paramMap.get(NotificationManager.PARAM_INTERFACE));
                        LOG.debug("service     : {}", paramMap.get(NotificationManager.PARAM_SERVICE));
                    }
                    // get the target and escalation information
                    Path path = null;
                    try {
                        path = getDestinationPathManager().getPath(notification.getDestinationPath());
                        if (path == null) {
                            LOG.warn("Unknown destination path {}. Please check the <destinationPath> tag for the notification {} in the notifications.xml file.", notification.getDestinationPath(), notification.getName());
                            // return;
                            continue;
                        }
                    } catch (Throwable e) {
                        LOG.error("Could not get destination path for {}, please check the destinationPath.xml for errors.", notification.getDestinationPath(), e);
                        return;
                    }
                    final String initialDelay = path.getInitialDelay().orElse(Path.DEFAULT_INITIAL_DELAY);
                    Target[] targets = path.getTargets().toArray(new Target[0]);
                    Escalate[] escalations = path.getEscalates().toArray(new Escalate[0]);
                    // notification, if none then generate an event a exit
                    try {
                        if (getUserCount(targets, escalations) == 0) {
                            LOG.warn("The path {} assigned to notification {} has no targets or escalations specified, not sending notice.", notification.getDestinationPath(), notification.getName());
                            sendNotifEvent(EventConstants.NOTIFICATION_WITHOUT_USERS, "The path " + notification.getDestinationPath() + " assigned to notification " + notification.getName() + " has no targets or escalations specified.", "The message of the notification is as follows: " + paramMap.get(NotificationManager.PARAM_TEXT_MSG));
                            return;
                        }
                    } catch (Throwable e) {
                        LOG.error("Failed to get count of users in destination path {}, exiting notification.", notification.getDestinationPath(), e);
                        return;
                    }
                    try {
                        LOG.info("Inserting notification #{} into database: {}", noticeId, paramMap.get(NotificationManager.PARAM_SUBJECT));
                        getNotificationManager().insertNotice(noticeId, paramMap, queueID, notification);
                    } catch (SQLException e) {
                        LOG.error("Failed to enter notification into database, exiting this notification", e);
                        return;
                    }
                    long startTime = System.currentTimeMillis() + TimeConverter.convertToMillis(initialDelay);
                    // Find the first outage which applies at this time
                    String scheduledOutageName = scheduledOutage(nodeid, ipaddr);
                    if (scheduledOutageName != null) {
                        // Must decide what to do
                        if (autoAckExistsForEvent(event.getUei())) {
                            // Defer starttime till the given outage ends -
                            // if the auto ack catches the other event
                            // before then,
                            // then the page will not be sent
                            Calendar endOfOutage = getPollOutagesConfigManager().getEndOfOutage(scheduledOutageName);
                            startTime = endOfOutage.getTime().getTime();
                        } else {
                            // with the next notification (for
                            continue;
                        // loop)
                        }
                    }
                    List<NotificationTask> targetSiblings = new ArrayList<NotificationTask>();
                    try {
                        synchronized (m_noticeQueues) {
                            NoticeQueue noticeQueue = m_noticeQueues.get(queueID);
                            processTargets(targets, targetSiblings, noticeQueue, startTime, paramMap, noticeId);
                            processEscalations(escalations, targetSiblings, noticeQueue, startTime, paramMap, noticeId);
                        }
                    } catch (Throwable e) {
                        LOG.error("notice not scheduled due to error: ", e);
                    }
                }
            } else {
                LOG.debug("Event doesn't match a notice: {} : {} : {} : {}", event.getUei(), nodeid, ipaddr, event.getService());
            }
        }
    } else {
        LOG.debug("No notice match for uei: {}", event.getUei());
    }
}
Also used : Path(org.opennms.netmgt.config.destinationPaths.Path) Escalate(org.opennms.netmgt.config.destinationPaths.Escalate) SQLException(java.sql.SQLException) Calendar(java.util.Calendar) ArrayList(java.util.ArrayList) Notification(org.opennms.netmgt.config.notifications.Notification) Target(org.opennms.netmgt.config.destinationPaths.Target)

Example 20 with Notification

use of org.opennms.netmgt.config.notifications.Notification in project opennms by OpenNMS.

the class BroadcastEventProcessorIT method testExpandNotifParms.

/**
 * Test calling expandNotifParms to see if the regular expression in
 * m_notifdExpandRE is initialized from {@link BroadcastEventProcessor.NOTIFD_EXPANSION_PARM}.
 */
@Test
public void testExpandNotifParms() throws Exception {
    String expandResult = NotificationManager.expandNotifParms("%foo%", new TreeMap<String, String>());
    assertEquals("%foo%", expandResult);
    // This is kinda non-intuitive... but expandNotifParms() only works on whitelisted expansion params
    expandResult = NotificationManager.expandNotifParms("%foo%", Collections.singletonMap("foo", "bar"));
    assertEquals("%foo%", expandResult);
    // The 'noticeid' param is in the whitelist
    expandResult = NotificationManager.expandNotifParms("Notice #%noticeid% RESOLVED: ", Collections.singletonMap("noticeid", "999"));
    assertEquals("Notice #999 RESOLVED: ", expandResult);
    expandResult = NotificationManager.expandNotifParms("RESOLVED: ", Collections.singletonMap("noticeid", "999"));
    assertEquals("RESOLVED: ", expandResult);
    // <notification name="Disk Threshold" status="on"> from bug 2888
    expandResult = NotificationManager.expandNotifParms("Notice %noticeid%: Disk threshold exceeded on %nodelabel%: %parm[all]%.", new TreeMap<String, String>());
    assertEquals("Notice %noticeid%: Disk threshold exceeded on %nodelabel%: %parm[all]%.", expandResult);
    /*
        <event>
            <uei xmlns="">uei.opennms.org/abian/hr-dsk-full</uei>
            <event-label xmlns="">Disk Full</event-label>
            <descr xmlns="">Threshold exceeded for %service% datasource %parm[ds]% on interface %interface%, parms: %parm[all]%</descr>
            <logmsg dest="logndisplay">Threshold exceeded for %service% datasource %parm[ds]% on interface %interface%, parms: %parm[all]%</logmsg>
            <severity xmlns="">Minor</severity>
            <alarm-data reduction-key="%uei%!%nodeid%!%parm[label]%" alarm-type="1" auto-clean="false" />
        </event>
         */
    EventBuilder bldr = new EventBuilder(EventConstants.HIGH_THRESHOLD_EVENT_UEI, "testExpandNotifParms");
    bldr.setDescription("High threshold exceeded for %service% datasource %parm[ds]% on interface %interface%, parms: %parm[all]%");
    bldr.setLogMessage("High threshold exceeded for %service% datasource %parm[ds]% on interface %interface%, parms: %parm[all]%");
    bldr.setNodeid(0);
    bldr.setInterface(addr("0.0.0.0"));
    bldr.addParam("ds", "dsk-usr-pcent");
    bldr.addParam("value", "Crap! RUN AWAY! We need 20% on the SAN and there's only 15");
    bldr.addParam("threshold", "");
    bldr.addParam("trigger", "");
    bldr.addParam("rearm", "");
    bldr.addParam("label", "");
    bldr.addParam("ifIndex", "");
    /*
        List<String> names = m_notificationManager.getNotificationNames();
        Collections.sort(names);
        for (String name : names) {
            System.out.println(name);
        }
        */
    Notification[] notifications = null;
    notifications = m_notificationManager.getNotifForEvent(null);
    assertNull(notifications);
    notifications = m_notificationManager.getNotifForEvent(bldr.getEvent());
    assertNotNull(notifications);
    assertEquals(1, notifications.length);
    Map<String, String> paramMap = m_eventProcessor.buildParameterMap(notifications[0], bldr.getEvent(), 9999);
    /*
        for (Map.Entry<String,String> entry : paramMap.entrySet()) {
            System.out.println(entry.getKey() + " => " + entry.getValue());
        }
         */
    assertEquals("High disk Threshold exceeded on 0.0.0.0, dsk-usr-pcent with Crap! RUN AWAY! We need 20% on the SAN and there's only 15%", paramMap.get("-tm"));
    expandResult = NotificationManager.expandNotifParms("Notice #%noticeid%: Disk threshold exceeded on %nodelabel%: %parm[all]%.", paramMap);
    assertEquals("Notice #9999: Disk threshold exceeded on %nodelabel%: %parm[all]%.", expandResult);
}
Also used : EventBuilder(org.opennms.netmgt.model.events.EventBuilder) TreeMap(java.util.TreeMap) Notification(org.opennms.netmgt.config.notifications.Notification) Test(org.junit.Test)

Aggregations

Notification (org.opennms.netmgt.config.notifications.Notification)22 HashMap (java.util.HashMap)7 Test (org.junit.Test)5 EventBuilder (org.opennms.netmgt.model.events.EventBuilder)4 ArrayList (java.util.ArrayList)3 Date (java.util.Date)2 LinkedHashMap (java.util.LinkedHashMap)2 ServletException (javax.servlet.ServletException)2 Parameter (org.opennms.netmgt.config.notifications.Parameter)2 Event (org.opennms.netmgt.xml.event.Event)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 IOException (java.io.IOException)1 ResultSet (java.sql.ResultSet)1 SQLException (java.sql.SQLException)1 Calendar (java.util.Calendar)1 TreeMap (java.util.TreeMap)1 HttpSession (javax.servlet.http.HttpSession)1 JUnitTemporaryDatabase (org.opennms.core.test.db.annotations.JUnitTemporaryDatabase)1 Querier (org.opennms.core.utils.Querier)1 SingleResultQuerier (org.opennms.core.utils.SingleResultQuerier)1