Search in sources :

Example 6 with SnmpWalker

use of org.opennms.netmgt.snmp.SnmpWalker 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 7 with SnmpWalker

use of org.opennms.netmgt.snmp.SnmpWalker in project opennms by OpenNMS.

the class NetScalerGroupHealthMonitor method poll.

public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    InetAddress ipaddr = svc.getAddress();
    final SnmpAgentConfig agentConfig = getAgentConfig(svc, parameters);
    final String hostAddress = InetAddressUtils.str(ipaddr);
    PollStatus status = PollStatus.unavailable("NetScalerGroupHealthMonitor: cannot determinate group health, addr=" + hostAddress);
    int groupHealth = ParameterMap.getKeyedInteger(parameters, "group-health", 60);
    String groupName = ParameterMap.getKeyedString(parameters, "group-name", null);
    if (groupName == null) {
        status.setReason("NetScalerGroupHealthMonitor no group-name defined, addr=" + hostAddress);
        LOG.warn("NetScalerGroupHealthMonitor.poll: No Service Name Defined!");
        return status;
    }
    int snLength = groupName.length();
    StringBuffer serviceOidBuf = new StringBuffer(SVC_GRP_MEMBER_STATE);
    serviceOidBuf.append(".").append(Integer.toString(snLength));
    for (byte thisByte : groupName.getBytes()) {
        serviceOidBuf.append(".").append(Byte.toString(thisByte));
    }
    LOG.debug("For group name '{}', OID to check is {}", groupName, serviceOidBuf.toString());
    try {
        final SnmpObjId groupStateOid = SnmpObjId.get(serviceOidBuf.toString());
        final Map<SnmpInstId, SnmpValue> hostResults = new HashMap<SnmpInstId, SnmpValue>();
        RowCallback callback = new RowCallback() {

            @Override
            public void rowCompleted(SnmpRowResult result) {
                hostResults.put(result.getInstance(), result.getValue(groupStateOid));
            }
        };
        TableTracker tracker = new TableTracker(callback, groupStateOid);
        try (SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "NetScalerGroupHealthMonitor", tracker)) {
            walker.start();
            walker.waitFor();
        }
        int totalServers = hostResults.size();
        if (totalServers == 0) {
            status = PollStatus.unavailable("NetScalerGroupHealthMonitor poll failed: there are 0 servers on group " + groupName + " for " + hostAddress);
            LOG.debug(status.getReason());
        }
        int activeServers = 0;
        for (SnmpValue v : hostResults.values()) {
            if (v.toInt() == 7) {
                activeServers++;
            }
        }
        double health = (new Double(activeServers) / new Double(totalServers)) * 100.0;
        LOG.debug("There are {} of {} active servers ({}%) on group {} for NetScaler {}", activeServers, totalServers, health, groupName, hostAddress);
        if (health >= groupHealth) {
            status = PollStatus.available();
        } else {
            status = PollStatus.unavailable("NetScalerGroupHealthMonitor poll failed: there are " + activeServers + " of " + totalServers + " servers active (" + health + "%) on group " + groupName + ", which is less than " + groupHealth + "% for " + hostAddress);
            LOG.debug(status.getReason());
        }
    } catch (Throwable t) {
        status = PollStatus.unavailable("Unexpected exception during SNMP poll of interface " + hostAddress);
        LOG.warn(status.getReason(), t);
    }
    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) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) InetAddress(java.net.InetAddress)

Example 8 with SnmpWalker

use of org.opennms.netmgt.snmp.SnmpWalker in project opennms by OpenNMS.

the class MockSnmpStrategyTest method walk.

private SnmpWalker walk(final CollectionTracker c, final int maxVarsPerPdu, final int maxRepetitions) throws Exception {
    final SnmpAgentConfig config = getAgentConfig();
    final SnmpWalker walker = SnmpUtils.createWalker(config, "test", c);
    assertNotNull(walker);
    return walker;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) SnmpWalker(org.opennms.netmgt.snmp.SnmpWalker)

Example 9 with SnmpWalker

use of org.opennms.netmgt.snmp.SnmpWalker in project opennms by OpenNMS.

the class MockSnmpStrategyTest method testCallbackOnTrackerTimeout.

@Test
public void testCallbackOnTrackerTimeout() throws Exception {
    // Expect an exception on get
    expectedEx.expect(Exception.class);
    expectedEx.expectMessage("Timeout retrieving 'test' for 127.0.0.1");
    final CountingColumnTracker ct = new CountingColumnTracker(SnmpObjId.get(".1.3.5.1.1"));
    final SnmpAgentConfig sac = getAgentConfig();
    sac.setPort(12345);
    try (final SnmpWalker walker = SnmpUtils.createWalker(sac, "test", ct)) {
        walker.start();
        final CompletableFuture<Long> future = toCompletableFuture(ct, walker);
        future.get();
    }
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) SnmpWalker(org.opennms.netmgt.snmp.SnmpWalker) Test(org.junit.Test)

Example 10 with SnmpWalker

use of org.opennms.netmgt.snmp.SnmpWalker in project opennms by OpenNMS.

the class MockSnmpStrategyTest method testCallbackOnTrackerSuccess.

@Test
public void testCallbackOnTrackerSuccess() throws Exception {
    final CountingColumnTracker ct = new CountingColumnTracker(SnmpObjId.get(".1.3.5.1.1"));
    try (final SnmpWalker walker = walk(ct, 10, 3)) {
        final CompletableFuture<Long> future = toCompletableFuture(ct, walker);
        walker.start();
        assertEquals("number of columns returned must match test data", Long.valueOf(9), future.get());
    }
}
Also used : SnmpWalker(org.opennms.netmgt.snmp.SnmpWalker) Test(org.junit.Test)

Aggregations

SnmpWalker (org.opennms.netmgt.snmp.SnmpWalker)13 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)8 Test (org.junit.Test)6 SnmpInstId (org.opennms.netmgt.snmp.SnmpInstId)5 InetAddress (java.net.InetAddress)4 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)4 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)4 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 PollStatus (org.opennms.netmgt.poller.PollStatus)2 AggregateTracker (org.opennms.netmgt.snmp.AggregateTracker)2 Collectable (org.opennms.netmgt.snmp.Collectable)2 CollectionTracker (org.opennms.netmgt.snmp.CollectionTracker)2 RowCallback (org.opennms.netmgt.snmp.RowCallback)2 SingleInstanceTracker (org.opennms.netmgt.snmp.SingleInstanceTracker)2 SnmpResult (org.opennms.netmgt.snmp.SnmpResult)2 SnmpRowResult (org.opennms.netmgt.snmp.SnmpRowResult)2 SnmpWalkCallback (org.opennms.netmgt.snmp.SnmpWalkCallback)2 TableTracker (org.opennms.netmgt.snmp.TableTracker)2