Search in sources :

Example 81 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class Ssh method poll.

/** {@inheritDoc} */
@Override
public PollStatus poll(TimeoutTracker tracker) throws InsufficientParametersException {
    tracker.startAttempt();
    boolean isAvailable = tryConnect();
    double responseTime = tracker.elapsedTimeInMillis();
    PollStatus ps = PollStatus.unavailable();
    String errorMessage = "";
    if (getError() != null) {
        errorMessage = getError().getMessage();
        ps.setReason(errorMessage);
    }
    if (isAvailable) {
        ps = PollStatus.available(responseTime);
    } else if (errorMessage.matches("^.*Authentication:.*$")) {
        ps = PollStatus.unavailable("authentication failed");
    } else if (errorMessage.matches("^.*java.net.NoRouteToHostException.*$")) {
        ps = PollStatus.unavailable("no route to host");
    } else if (errorMessage.matches("^.*(timeout: socket is not established|java.io.InterruptedIOException|java.net.SocketTimeoutException).*$")) {
        ps = PollStatus.unavailable("connection timed out");
    } else if (errorMessage.matches("^.*(connection is closed by foreign host|java.net.ConnectException).*$")) {
        ps = PollStatus.unavailable("connection exception");
    } else if (errorMessage.matches("^.*NumberFormatException.*$")) {
        ps = PollStatus.unavailable("an error occurred parsing the server version number");
    } else if (errorMessage.matches("^.*java.io.IOException.*$")) {
        ps = PollStatus.unavailable("I/O exception");
    }
    return ps;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus)

Example 82 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class MockMonitor method doPoll.

private PollStatus doPoll(int nodeId, String ipAddr, String svcName) {
    synchronized (m_network) {
        MockService svc = m_network.getService(nodeId, ipAddr, svcName);
        if (svc == null) {
            LOG.info("Invalid Poll: {}/{}/{}", nodeId, ipAddr, svcName);
            m_network.receivedInvalidPoll(ipAddr, svcName);
            return PollStatus.unknown("Mock.");
        } else {
            LOG.info("Poll: [{}/{}/{}]", svc.getInterface().getNode().getLabel(), ipAddr, svcName);
            PollStatus pollStatus = svc.poll();
            return PollStatus.get(pollStatus.getStatusCode(), pollStatus.getReason());
        }
    }
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus)

Example 83 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class MockMonitor method getRuntimeAttributes.

@Override
public Map<String, Object> getRuntimeAttributes(MonitoredService svc, Map<String, Object> parameters) {
    final Map<String, Object> attributes = new HashMap<>();
    final PollStatus pollStatus = doPoll(svc.getNodeId(), svc.getIpAddr(), m_svcName);
    attributes.put("status", Integer.toString(pollStatus.getStatusCode()));
    attributes.put("reason", pollStatus.getReason());
    return attributes;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) HashMap(java.util.HashMap)

Example 84 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class HostResourceSwRunMonitor method poll.

/**
     * {@inheritDoc}
     *
     * <P>
     * The poll() method is responsible for polling the specified address for
     * SNMP service availability.
     * </P>
     * @exception RuntimeException
     *                Thrown for any uncrecoverable errors.
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    InetAddress ipaddr = svc.getAddress();
    // Retrieve this interface's SNMP peer object
    //
    final SnmpAgentConfig agentConfig = getAgentConfig(svc, parameters);
    final String hostAddress = InetAddressUtils.str(ipaddr);
    LOG.debug("poll: setting SNMP peer attribute for interface {}", hostAddress);
    // Get configuration parameters
    //
    // This should never need to be overridden, but it can be in order to be used with similar tables.
    String serviceNameOid = ParameterMap.getKeyedString(parameters, "service-name-oid", HOSTRESOURCE_SW_NAME_OID);
    // This should never need to be overridden, but it can be in order to be used with similar tables.
    String serviceStatusOid = ParameterMap.getKeyedString(parameters, "service-status-oid", HOSTRESOURCE_SW_STATUS_OID);
    // This is the string that represents the service name to be monitored.
    String serviceName = ParameterMap.getKeyedString(parameters, "service-name", null);
    // The service name may appear in the table more than once. If this is set to true, all values must match the run level.
    String matchAll = ParameterMap.getKeyedString(parameters, "match-all", "false");
    // This is one of: 
    //                   running(1),
    //                   runnable(2),    -- waiting for resource
    //                                   -- (i.e., CPU, memory, IO)
    //                   notRunnable(3), -- loaded but waiting for event
    //                   invalid(4)      -- not loaded
    //
    // This represents the maximum run-level, i.e. 2 means either running(1) or runnable(2) pass.
    String runLevel = ParameterMap.getKeyedString(parameters, "run-level", "2");
    // If "match-all" is true, there can be an optional "min-services" and "max-services" parameters that can define a range. The service is up if:
    // a) services_count >= min-services and services_count <= max-services
    // b) either one is not defined, then only one has to pass.
    // c) neither are defined, the monitor acts just like it used to - checking all instances to see if they are all running.
    // It is assumed that all services would have to pass the minimum run state test, no matter what the count.
    int minServices = ParameterMap.getKeyedInteger(parameters, "min-services", -1);
    int maxServices = ParameterMap.getKeyedInteger(parameters, "max-services", -1);
    // set timeout and retries on SNMP peer object
    //
    agentConfig.setTimeout(ParameterMap.getKeyedInteger(parameters, "timeout", agentConfig.getTimeout()));
    agentConfig.setRetries(ParameterMap.getKeyedInteger(parameters, "retry", ParameterMap.getKeyedInteger(parameters, "retries", agentConfig.getRetries())));
    agentConfig.setPort(ParameterMap.getKeyedInteger(parameters, "port", agentConfig.getPort()));
    LOG.debug("poll: service= SNMP address= {}", agentConfig);
    PollStatus status = PollStatus.unavailable("HostResourceSwRunMonitor service not found, addr=" + hostAddress + ", service-name=" + serviceName);
    // Establish SNMP session with interface
    //
    int matches = 0;
    try {
        LOG.debug("HostResourceSwRunMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
        if (serviceName == null) {
            status.setReason("HostResourceSwRunMonitor no service-name defined, addr=" + hostAddress);
            LOG.warn("HostResourceSwRunMonitor.poll: No Service Name Defined! ");
            return status;
        }
        if (minServices > 0 && maxServices > 0 && minServices >= maxServices) {
            String reason = "min-services(" + minServices + ") should be less than max-services(" + maxServices + ")";
            status.setReason("HostResourceSwRunMonitor " + reason + ", addr=" + hostAddress + ", service-name=" + serviceName);
            LOG.warn("HostResourceSwRunMonitor.poll: {}.", reason);
            return status;
        }
        // This updates two maps: one of instance and service name, and one of instance and status.
        final SnmpObjId serviceNameOidId = SnmpObjId.get(serviceNameOid);
        final SnmpObjId serviceStatusOidId = SnmpObjId.get(serviceStatusOid);
        final Map<SnmpInstId, SnmpValue> nameResults = new HashMap<SnmpInstId, SnmpValue>();
        final Map<SnmpInstId, SnmpValue> statusResults = new HashMap<SnmpInstId, SnmpValue>();
        RowCallback callback = new RowCallback() {

            @Override
            public void rowCompleted(SnmpRowResult result) {
                nameResults.put(result.getInstance(), result.getValue(serviceNameOidId));
                statusResults.put(result.getInstance(), result.getValue(serviceStatusOidId));
            }
        };
        TimeoutTracker tracker = new TimeoutTracker(parameters, agentConfig.getRetries(), agentConfig.getTimeout());
        tracker.reset();
        tracker.startAttempt();
        TableTracker tableTracker = new TableTracker(callback, serviceNameOidId, serviceStatusOidId);
        try (SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "HostResourceSwRunMonitor", tableTracker)) {
            walker.start();
            walker.waitFor();
            String error = walker.getErrorMessage();
            if (error != null && !error.trim().equals("")) {
                LOG.warn(error);
                return PollStatus.unavailable(error);
            }
        }
        // Iterate over the list of running services
        for (SnmpInstId nameInstance : nameResults.keySet()) {
            final SnmpValue name = nameResults.get(nameInstance);
            final SnmpValue value = statusResults.get(nameInstance);
            // See if the service name is in the list of running services
            if (name != null && value != null && match(serviceName, StringUtils.stripExtraQuotes(name.toString()))) {
                matches++;
                LOG.debug("poll: HostResourceSwRunMonitor poll succeeded, addr={}, service-name={}, value={}", hostAddress, serviceName, nameResults.get(nameInstance));
                // Using the instance of the service, get its status and see if it meets the criteria
                if (meetsCriteria(value, "<=", runLevel)) {
                    status = PollStatus.available(tracker.elapsedTimeInMillis());
                    // If we get here, that means the service passed the criteria, if only one match is desired we exit.
                    if ("false".equals(matchAll)) {
                        return status;
                    }
                // if we get here, that means the meetsCriteria test failed. 
                } else {
                    String reason = "HostResourceSwRunMonitor poll failed, addr=" + hostAddress + ", service-name=" + serviceName + ", status=" + statusResults.get(nameInstance);
                    LOG.debug(reason);
                    status = PollStatus.unavailable(reason);
                    return status;
                }
            }
        }
        LOG.debug("poll: HostResourceSwRunMonitor the number of matches found for {} was {}", serviceName, matches);
    } catch (NumberFormatException e) {
        String reason = "Number operator used on a non-number " + e.getMessage();
        LOG.debug(reason);
        status = PollStatus.unavailable(reason);
    } catch (IllegalArgumentException e) {
        String reason = "Invalid SNMP Criteria: " + e.getMessage();
        LOG.debug(reason);
        status = PollStatus.unavailable(reason);
    } catch (Throwable t) {
        String reason = "Unexpected exception during SNMP poll of interface " + hostAddress;
        LOG.debug(reason, t);
        status = PollStatus.unavailable(reason);
    }
    // This will be executed only if match-all=true
    boolean minOk = minServices > 0 ? matches >= minServices : true;
    boolean maxOk = maxServices > 0 ? matches <= maxServices : true;
    if (!minOk && maxServices < 0) {
        // failed min-services only
        String reason = "HostResourceSwRunMonitor poll failed: service-count(" + matches + ") >= min-services(" + minServices + "), addr=" + hostAddress + ", service-name=" + serviceName;
        LOG.debug(reason);
        status = PollStatus.unavailable(reason);
    }
    if (!maxOk && minServices < 0) {
        // failed max-services only
        String reason = "HostResourceSwRunMonitor poll failed: service-count(" + matches + ") <= max-services(" + maxServices + "), addr=" + hostAddress + ", service-name=" + serviceName;
        LOG.debug(reason);
        status = PollStatus.unavailable(reason);
    }
    if ((!minOk || !maxOk) && minServices > 0 && maxServices > 0) {
        // failed both (bad range)
        String reason = "HostResourceSwRunMonitor poll failed: min-services(" + minServices + ") >= service-count(" + matches + ") <= max-services(" + maxServices + "), addr=" + hostAddress + ", service-name=" + serviceName;
        LOG.debug(reason);
        status = PollStatus.unavailable(reason);
    }
    return status;
}
Also used : RowCallback(org.opennms.netmgt.snmp.RowCallback) SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) SnmpRowResult(org.opennms.netmgt.snmp.SnmpRowResult) PollStatus(org.opennms.netmgt.poller.PollStatus) SnmpWalker(org.opennms.netmgt.snmp.SnmpWalker) HashMap(java.util.HashMap) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) TableTracker(org.opennms.netmgt.snmp.TableTracker) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) InetAddress(java.net.InetAddress)

Example 85 with PollStatus

use of org.opennms.netmgt.poller.PollStatus in project opennms by OpenNMS.

the class HttpPostMonitor method poll.

/**
     * {@inheritDoc}
     *
     * Poll the specified address for service availability.
     *
     * During the poll an attempt is made to execute the named method (with optional input) connect on the specified port. If
     * the exec on request is successful, the banner line generated by the
     * interface is parsed and if the banner text indicates that we are talking
     * to Provided that the interface's response is valid we set the service
     * status to SERVICE_AVAILABLE and return.
     */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    // Process parameters
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Port
    int port = ParameterMap.getKeyedInteger(parameters, PARAMETER_PORT, DEFAULT_PORT);
    //URI
    String strURI = ParameterMap.getKeyedString(parameters, PARAMETER_URI, DEFAULT_URI);
    //Username
    String strUser = ParameterMap.getKeyedString(parameters, PARAMETER_USERNAME, null);
    //Password
    String strPasswd = ParameterMap.getKeyedString(parameters, PARAMETER_PASSWORD, null);
    //BannerMatch
    String strBannerMatch = ParameterMap.getKeyedString(parameters, PARAMETER_BANNER, null);
    //Scheme
    String strScheme = ParameterMap.getKeyedString(parameters, PARAMETER_SCHEME, DEFAULT_SCHEME);
    //Payload
    String strPayload = ParameterMap.getKeyedString(parameters, PARAMETER_PAYLOAD, null);
    //Mimetype
    String strMimetype = ParameterMap.getKeyedString(parameters, PARAMETER_MIMETYPE, DEFAULT_MIMETYPE);
    //Charset
    String strCharset = ParameterMap.getKeyedString(parameters, PARAMETER_CHARSET, DEFAULT_CHARSET);
    //SSLFilter
    boolean boolSSLFilter = ParameterMap.getKeyedBoolean(parameters, PARAMETER_SSLFILTER, DEFAULT_SSLFILTER);
    // Get the address instance.
    InetAddress ipAddr = svc.getAddress();
    final String hostAddress = InetAddressUtils.str(ipAddr);
    LOG.debug("poll: address = {}, port = {}, {}", hostAddress, port, tracker);
    // Give it a whirl
    PollStatus serviceStatus = PollStatus.unavailable();
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        HttpClientWrapper clientWrapper = null;
        try {
            tracker.startAttempt();
            clientWrapper = HttpClientWrapper.create().setConnectionTimeout(tracker.getSoTimeout()).setSocketTimeout(tracker.getSoTimeout()).setRetries(DEFAULT_RETRY);
            if (boolSSLFilter) {
                clientWrapper.trustSelfSigned(strScheme);
            }
            HttpEntity postReq;
            if (strUser != null && strPasswd != null) {
                clientWrapper.addBasicCredentials(strUser, strPasswd);
            }
            try {
                postReq = new StringEntity(strPayload, ContentType.create(strMimetype, strCharset));
            } catch (final UnsupportedCharsetException e) {
                serviceStatus = PollStatus.unavailable("Unsupported encoding encountered while constructing POST body " + e);
                break;
            }
            URIBuilder ub = new URIBuilder();
            ub.setScheme(strScheme);
            ub.setHost(hostAddress);
            ub.setPort(port);
            ub.setPath(strURI);
            LOG.debug("HttpPostMonitor: Constructed URL is {}", ub);
            HttpPost post = new HttpPost(ub.build());
            post.setEntity(postReq);
            CloseableHttpResponse response = clientWrapper.execute(post);
            LOG.debug("HttpPostMonitor: Status Line is {}", response.getStatusLine());
            if (response.getStatusLine().getStatusCode() > 399) {
                LOG.info("HttpPostMonitor: Got response status code {}", response.getStatusLine().getStatusCode());
                LOG.debug("HttpPostMonitor: Received server response: {}", response.getStatusLine());
                LOG.debug("HttpPostMonitor: Failing on bad status code");
                serviceStatus = PollStatus.unavailable("HTTP(S) Status code " + response.getStatusLine().getStatusCode());
                break;
            }
            LOG.debug("HttpPostMonitor: Response code is valid");
            double responseTime = tracker.elapsedTimeInMillis();
            HttpEntity entity = response.getEntity();
            InputStream responseStream = entity.getContent();
            String Strresponse = IOUtils.toString(responseStream);
            if (Strresponse == null)
                continue;
            LOG.debug("HttpPostMonitor: banner = {}", Strresponse);
            LOG.debug("HttpPostMonitor: responseTime= {}ms", responseTime);
            //Could it be a regex?
            if (!Strings.isNullOrEmpty(strBannerMatch) && strBannerMatch.startsWith("~")) {
                if (!Strresponse.matches(strBannerMatch.substring(1))) {
                    serviceStatus = PollStatus.unavailable("Banner does not match Regex '" + strBannerMatch + "'");
                    break;
                } else {
                    serviceStatus = PollStatus.available(responseTime);
                }
            } else {
                if (Strresponse.indexOf(strBannerMatch) > -1) {
                    serviceStatus = PollStatus.available(responseTime);
                } else {
                    serviceStatus = PollStatus.unavailable("Did not find expected Text '" + strBannerMatch + "'");
                    break;
                }
            }
        } catch (final URISyntaxException e) {
            final String reason = "URISyntaxException for URI: " + strURI + " " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } catch (final Exception e) {
            final String reason = "Exception: " + e.getMessage();
            LOG.debug(reason, e);
            serviceStatus = PollStatus.unavailable(reason);
            break;
        } finally {
            IOUtils.closeQuietly(clientWrapper);
        }
    }
    // return the status of the service
    return serviceStatus;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) PollStatus(org.opennms.netmgt.poller.PollStatus) HttpEntity(org.apache.http.HttpEntity) InputStream(java.io.InputStream) URISyntaxException(java.net.URISyntaxException) URISyntaxException(java.net.URISyntaxException) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) UnsupportedCharsetException(java.nio.charset.UnsupportedCharsetException) HttpClientWrapper(org.opennms.core.web.HttpClientWrapper) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InetAddress(java.net.InetAddress)

Aggregations

PollStatus (org.opennms.netmgt.poller.PollStatus)200 Test (org.junit.Test)92 MonitoredService (org.opennms.netmgt.poller.MonitoredService)51 ServiceMonitor (org.opennms.netmgt.poller.ServiceMonitor)47 InetAddress (java.net.InetAddress)39 MockMonitoredService (org.opennms.netmgt.poller.mock.MockMonitoredService)36 HashMap (java.util.HashMap)35 TimeoutTracker (org.opennms.core.utils.TimeoutTracker)29 ConcurrentSkipListMap (java.util.concurrent.ConcurrentSkipListMap)28 JUnitHttpServer (org.opennms.core.test.http.annotations.JUnitHttpServer)18 IOException (java.io.IOException)17 Socket (java.net.Socket)17 InputStreamReader (java.io.InputStreamReader)16 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)14 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)14 BufferedReader (java.io.BufferedReader)13 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)12 InterruptedIOException (java.io.InterruptedIOException)11 ConnectException (java.net.ConnectException)11 NoRouteToHostException (java.net.NoRouteToHostException)11