Search in sources :

Example 1 with ScanReport

use of org.opennms.netmgt.model.ScanReport in project opennms by OpenNMS.

the class ScanReportPollerFrontEnd method performServiceScans.

/**
 * Perform all scans for a given location and return the results as a {@link ScanReport}
 * object. To filter by application, specify the selected applications by using the
 * {@link #setSelectedApplications(Set)} method.
 */
private void performServiceScans() {
    firePropertyChange(ScanReportProperties.percentageComplete.toString(), null, 0.0);
    ScanReport scanReport = new ScanReport();
    scanReport.setLocation(m_location);
    // scanReport.addProperty("monitoring-system-id", getMonitoringSystemId());
    scanReport.setTimestamp(new Date());
    // Add all of the OS and connection metadata to the scan report
    for (final Map.Entry<String, String> entry : getDetails().entrySet()) {
        scanReport.addProperty(entry);
    }
    // Add all of the metadata to the scan report
    for (final Map.Entry<String, String> entry : m_metadata.entrySet()) {
        scanReport.addProperty(entry);
    }
    // Add the selected applications as scan report metadata
    if (m_selectedApplications != null && m_selectedApplications.size() > 0) {
        scanReport.addProperty("applications", m_selectedApplications.stream().collect(Collectors.joining(", ")));
    }
    // Create a log appender that will capture log output to the root logger
    Log4j2StringAppender appender = Log4j2StringAppender.createAppender();
    appender.start();
    try {
        m_pollService.setServiceMonitorLocators(m_backEnd.getServiceMonitorLocators(DistributionContext.REMOTE_MONITOR));
        m_pollerConfiguration = retrieveLatestConfiguration();
        appender.addToLogger(LogManager.ROOT_LOGGER_NAME, Level.DEBUG);
        Set<PolledService> polledServices = getPolledServices().stream().filter(s -> matchesApplications(s, m_selectedApplications)).collect(Collectors.toSet());
        PolledService[] services = polledServices.toArray(POLLED_SERVICE_ARRAY);
        LOG.debug("Polling {} services.", services.length);
        for (int i = 0; i < services.length; i++) {
            PolledService service = services[i];
            try {
                final PollStatus result = doPoll(service);
                if (result == null) {
                    LOG.warn("Null poll result for service {}", service.getServiceId());
                } else {
                    LOG.info(new ToStringBuilder(this).append("statusName", result.getStatusName()).append("reason", result.getReason()).toString());
                    scanReport.addPollResult(new ScanReportPollResult(service.getSvcName(), service.getServiceId(), service.getNodeLabel(), service.getNodeId(), service.getIpAddr(), result));
                }
            } catch (Throwable e) {
                LOG.error("Unexpected exception occurred while polling service ID {}", service.getServiceId(), e);
                setState(new FatalExceptionOccurred(e));
            }
            firePropertyChange(ScanReportProperties.percentageComplete.toString(), null, ((double) i / (double) services.length));
        }
    } catch (final Throwable e) {
        LOG.error("Error while performing scan", e);
    } finally {
        // Remove the log appender from the root logger
        appender.removeFromLogger(LogManager.ROOT_LOGGER_NAME);
    }
    // Set the percentage complete to 100%
    firePropertyChange(ScanReportProperties.percentageComplete.toString(), null, 1.0);
    scanReport.setLog(new ScanReportLog(scanReport.getId(), appender.getOutput()));
    LOG.debug("Returning scan report: {}", scanReport);
    /*
        LOG.debug("=============== Scan report log START ===============");
        LOG.debug("Scan report log: '{}'", appender.getOutput());
        LOG.debug("=============== Scan report log END ===============");
         */
    // Fire an exitNecessary event with the scanReport as the parameter
    firePropertyChange(PollerFrontEndStates.exitNecessary.toString(), null, scanReport);
}
Also used : Arrays(java.util.Arrays) PolledService(org.opennms.netmgt.poller.remote.PolledService) ServicePollStateChangedListener(org.opennms.netmgt.poller.remote.ServicePollStateChangedListener) ServicePollState(org.opennms.netmgt.poller.remote.ServicePollState) ScanReportLog(org.opennms.netmgt.model.ScanReportLog) Date(java.util.Date) PollerFrontEnd(org.opennms.netmgt.poller.remote.PollerFrontEnd) ToStringBuilder(org.apache.commons.lang.builder.ToStringBuilder) LoggerFactory(org.slf4j.LoggerFactory) Level(org.apache.logging.log4j.Level) HashMap(java.util.HashMap) DistributionContext(org.opennms.netmgt.poller.DistributionContext) PollStatus(org.opennms.netmgt.poller.PollStatus) InitializingBean(org.springframework.beans.factory.InitializingBean) InetAddress(java.net.InetAddress) ScanReport(org.opennms.netmgt.model.ScanReport) Map(java.util.Map) PollerBackEnd(org.opennms.netmgt.poller.remote.PollerBackEnd) ScanReportPollResult(org.opennms.netmgt.model.ScanReportPollResult) LinkedList(java.util.LinkedList) PropertyChangeEvent(java.beans.PropertyChangeEvent) ConfigurationChangedListener(org.opennms.netmgt.poller.remote.ConfigurationChangedListener) Properties(java.util.Properties) Logger(org.slf4j.Logger) HOST_ADDRESS_KEY(org.opennms.netmgt.poller.remote.PollerBackEnd.HOST_ADDRESS_KEY) TimeAdjustment(org.opennms.netmgt.poller.remote.TimeAdjustment) InetAddressUtils(org.opennms.core.utils.InetAddressUtils) Collection(java.util.Collection) ObjectUtils(org.springframework.util.ObjectUtils) HOST_NAME_KEY(org.opennms.netmgt.poller.remote.PollerBackEnd.HOST_NAME_KEY) Set(java.util.Set) Collectors(java.util.stream.Collectors) PollService(org.opennms.netmgt.poller.remote.PollService) List(java.util.List) PropertyChangeListener(java.beans.PropertyChangeListener) DisposableBean(org.springframework.beans.factory.DisposableBean) PollerConfiguration(org.opennms.netmgt.poller.remote.PollerConfiguration) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) Assert(org.springframework.util.Assert) PollStatus(org.opennms.netmgt.poller.PollStatus) ScanReport(org.opennms.netmgt.model.ScanReport) Date(java.util.Date) ScanReportLog(org.opennms.netmgt.model.ScanReportLog) PolledService(org.opennms.netmgt.poller.remote.PolledService) ToStringBuilder(org.apache.commons.lang.builder.ToStringBuilder) ScanReportPollResult(org.opennms.netmgt.model.ScanReportPollResult) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with ScanReport

use of org.opennms.netmgt.model.ScanReport in project opennms by OpenNMS.

the class PollerBackEndTest method testUnsuccessfulScanReportMessage.

public void testUnsuccessfulScanReportMessage() {
    expect(m_scanReportDao.save(EasyMock.anyObject(ScanReport.class))).andReturn("");
    m_mocks.replayAll();
    List<ScanReportPollResult> scanReportPollResults = new ArrayList<>();
    scanReportPollResults.add(new ScanReportPollResult("ICMP", 1, "Test Node", 1, "127.0.0.1", PollStatus.available(20.0)));
    scanReportPollResults.add(new ScanReportPollResult("HTTP", 2, "Test Node", 1, "127.0.0.1", PollStatus.unavailable("Weasels ate my HTTP server")));
    scanReportPollResults.add(new ScanReportPollResult("SNMP", 3, "Test Node", 1, "127.0.0.1", PollStatus.available(400.0)));
    scanReportPollResults.add(new ScanReportPollResult("POP3", 3, "Test Node", 1, "127.0.0.1", PollStatus.available(300.0)));
    scanReportPollResults.add(new ScanReportPollResult("IMAP", 4, "Test Node", 1, "127.0.0.1", PollStatus.unavailable("Kiwis infested my mail server")));
    ScanReport report = new ScanReport();
    report.setId(UUID.randomUUID().toString());
    report.setPollResults(scanReportPollResults);
    m_backEnd.reportSingleScan(report);
    // Fetch the event that was sent
    Event unsuccessfulScanEvent = m_eventIpcManager.getEventAnticipator().getUnanticipatedEvents().iterator().next();
    assertTrue(unsuccessfulScanEvent.getParm(DefaultPollerBackEnd.PARM_SCAN_REPORT_FAILURE_MESSAGE).getValue().getContent(), unsuccessfulScanEvent.getParm(DefaultPollerBackEnd.PARM_SCAN_REPORT_FAILURE_MESSAGE).getValue().getContent().contains("2 out of 5 service polls failed"));
}
Also used : ScanReport(org.opennms.netmgt.model.ScanReport) ArrayList(java.util.ArrayList) Event(org.opennms.netmgt.xml.event.Event) ScanReportPollResult(org.opennms.netmgt.model.ScanReportPollResult)

Example 3 with ScanReport

use of org.opennms.netmgt.model.ScanReport in project opennms by OpenNMS.

the class CriteriaBuilderSearchVisitorIT method testScanReportAndCondition.

@Test
public void testScanReportAndCondition() {
    CriteriaBuilder builder = new ScanReportRestService().getCriteriaBuilder(null);
    CriteriaBuilderSearchVisitor<ScanReport, ScanReport> visitor = new CriteriaBuilderSearchVisitor<>(builder, ScanReport.class);
    // Simulates /opennms/api/v2/scanreports?_s=applications%3D%3DLocal+Access;timestamp%3Dle%3D2016-02-01T15:07:14.340-0500&limit=20&offset=0&order=desc&orderBy=timestamp
    List<SearchCondition<ScanReport>> conditions = new ArrayList<SearchCondition<ScanReport>>();
    conditions.add(new PrimitiveSearchCondition<ScanReport>("applications", "blah", String.class, ConditionType.EQUALS, new ScanReport()));
    conditions.add(new PrimitiveSearchCondition<ScanReport>("timestamp", new Date(), Date.class, ConditionType.LESS_OR_EQUALS, new ScanReport()));
    SearchCondition<ScanReport> andCondition = new AndSearchCondition<ScanReport>(conditions);
    visitor.visit(andCondition);
    Criteria criteria = visitor.getQuery().toCriteria();
    System.out.println(criteria.toString());
    m_dao.countMatching(criteria);
}
Also used : CriteriaBuilder(org.opennms.core.criteria.CriteriaBuilder) ScanReport(org.opennms.netmgt.model.ScanReport) ArrayList(java.util.ArrayList) Criteria(org.opennms.core.criteria.Criteria) Date(java.util.Date) ScanReportRestService(org.opennms.web.rest.v2.ScanReportRestService) AndSearchCondition(org.apache.cxf.jaxrs.ext.search.AndSearchCondition) PrimitiveSearchCondition(org.apache.cxf.jaxrs.ext.search.PrimitiveSearchCondition) SearchCondition(org.apache.cxf.jaxrs.ext.search.SearchCondition) AndSearchCondition(org.apache.cxf.jaxrs.ext.search.AndSearchCondition) Test(org.junit.Test)

Example 4 with ScanReport

use of org.opennms.netmgt.model.ScanReport in project opennms by OpenNMS.

the class CriteriaBuilderSearchVisitorIT method testScanReportTwoConditions.

@Test
public void testScanReportTwoConditions() {
    CriteriaBuilder builder = new ScanReportRestService().getCriteriaBuilder(null);
    CriteriaBuilderSearchVisitor<ScanReport, ScanReport> visitor = new CriteriaBuilderSearchVisitor<>(builder, ScanReport.class);
    visitor.visit(new PrimitiveSearchCondition<ScanReport>("applications", "blah", String.class, ConditionType.EQUALS, new ScanReport()));
    visitor.visit(new PrimitiveSearchCondition<ScanReport>("timestamp", new Date(), Date.class, ConditionType.LESS_OR_EQUALS, new ScanReport()));
    Criteria criteria = visitor.getQuery().toCriteria();
    System.out.println(criteria.toString());
    m_dao.countMatching(criteria);
}
Also used : CriteriaBuilder(org.opennms.core.criteria.CriteriaBuilder) ScanReport(org.opennms.netmgt.model.ScanReport) Criteria(org.opennms.core.criteria.Criteria) Date(java.util.Date) ScanReportRestService(org.opennms.web.rest.v2.ScanReportRestService) Test(org.junit.Test)

Example 5 with ScanReport

use of org.opennms.netmgt.model.ScanReport in project opennms by OpenNMS.

the class ScanReportPollerFrontEndIT method testRegister.

@Test
public void testRegister() throws Exception {
    // Check preconditions
    assertFalse(m_frontEnd.isRegistered());
    assertEquals(new Integer(1), m_jdbcTemplate.queryForObject("select count(*) from monitoringsystems", Integer.class));
    assertEquals(new Integer(0), m_jdbcTemplate.queryForObject("select count(*) from monitoringsystemsproperties", Integer.class));
    assertTrue("There were unexpected poll results", 0 == m_jdbcTemplate.queryForObject("select count(*) from location_specific_status_changes", Integer.class));
    // Add a PropertyChangeListener that will report the scan result to
    // the PollerBackEnd
    m_frontEnd.addPropertyChangeListener(new PropertyChangeListener() {

        @Override
        public void propertyChange(PropertyChangeEvent evt) {
            if (evt.getPropertyName().equals(PollerFrontEndStates.exitNecessary.toString())) {
                final ScanReport report = (ScanReport) evt.getNewValue();
                System.out.println("Finished scan: " + report);
                m_backEnd.reportSingleScan(report);
                // uei.opennms.org/test <-- Standard test event
                // uei.opennms.org/remote/unsuccessfulScanReport
                assertEquals(2, getEventCount());
                queryEvents();
                // Check to see if the expected metadata was stored in the database
                assertEquals(System.getProperty("os.arch"), m_jdbcTemplate.queryForObject("select propertyValue from scanreportproperties where scanreportid = ? and property = ?", String.class, report.getId(), "os.arch"));
                assertEquals(System.getProperty("os.name"), m_jdbcTemplate.queryForObject("select propertyValue from scanreportproperties where scanreportid = ? and property = ?", String.class, report.getId(), "os.name"));
                assertEquals(System.getProperty("os.version"), m_jdbcTemplate.queryForObject("select propertyValue from scanreportproperties where scanreportid = ? and property = ?", String.class, report.getId(), "os.version"));
                m_frontEnd.stop();
            }
        }
    });
    m_frontEnd.initialize();
    // Initialization shouldn't change anything since we're unregistered
    assertFalse(m_frontEnd.isRegistered());
    assertEquals(new Integer(1), m_jdbcTemplate.queryForObject("select count(*) from monitoringsystems", Integer.class));
    assertEquals(new Integer(0), m_jdbcTemplate.queryForObject("select count(*) from monitoringsystemsproperties", Integer.class));
    assertTrue("There were unexpected poll results", 0 == m_jdbcTemplate.queryForObject("select count(*) from location_specific_status_changes", Integer.class));
    // Start up the remote poller
    m_frontEnd.register("RDU");
    assertTrue("Front end not started!", m_frontEnd.isStarted());
    // String monitorId = m_frontEnd.getMonitoringSystemId();
    assertTrue(m_frontEnd.isRegistered());
    for (Map.Entry<String, String> entry : ((ScanReportPollerFrontEnd) m_frontEnd).getDetails().entrySet()) {
        LOG.info("Front end detail: " + entry.getKey() + " -> " + entry.getValue());
    }
}
Also used : PropertyChangeEvent(java.beans.PropertyChangeEvent) PropertyChangeListener(java.beans.PropertyChangeListener) ScanReport(org.opennms.netmgt.model.ScanReport) Map(java.util.Map) Test(org.junit.Test)

Aggregations

ScanReport (org.opennms.netmgt.model.ScanReport)8 Date (java.util.Date)6 Test (org.junit.Test)6 Criteria (org.opennms.core.criteria.Criteria)4 CriteriaBuilder (org.opennms.core.criteria.CriteriaBuilder)4 ScanReportRestService (org.opennms.web.rest.v2.ScanReportRestService)4 ScanReportPollResult (org.opennms.netmgt.model.ScanReportPollResult)3 PropertyChangeEvent (java.beans.PropertyChangeEvent)2 PropertyChangeListener (java.beans.PropertyChangeListener)2 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 ScanReportLog (org.opennms.netmgt.model.ScanReportLog)2 PollStatus (org.opennms.netmgt.poller.PollStatus)2 InetAddress (java.net.InetAddress)1 Arrays (java.util.Arrays)1 Collection (java.util.Collection)1 Collections (java.util.Collections)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1 List (java.util.List)1