Search in sources :

Example 21 with SnmpObjId

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

the class Snmp4JStrategyIT method testPreparePduWithTooManyValues.

@Test
public void testPreparePduWithTooManyValues() throws Exception {
    SnmpObjId[] oids = new SnmpObjId[] { SnmpObjId.get(".1.3.5.1.1.3.0"), SnmpObjId.get(".1.3.5.1.1.4.0") };
    SnmpValue[] values = new SnmpValue[] { snmpValue("foo"), snmpValue("bar"), snmpValue("baz") };
    PDU pdu = m_strategy.buildPdu(new Snmp4JAgentConfig(getAgentConfig()), PDU.SET, oids, values);
    assertNull("PDU should be null", pdu);
}
Also used : PDU(org.snmp4j.PDU) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) Test(org.junit.Test)

Example 22 with SnmpObjId

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

the class WalkCommand method execute.

@Override
public Object execute() throws Exception {
    LOG.debug("snmp:walk {} {} {}", m_location != null ? "-l " + m_location : "", m_host, m_oids);
    final List<SnmpObjId> snmpObjIds = m_oids.stream().map(SnmpObjId::get).collect(Collectors.toList());
    final SnmpAgentConfig agent = snmpAgentConfigFactory.getAgentConfig(InetAddress.getByName(m_host), m_location);
    final CompletableFuture<List<SnmpResult>> future = locationAwareSnmpClient.walk(agent, snmpObjIds).withDescription("snmp:walk").withLocation(m_location).withSystemId(m_systemId).execute();
    while (true) {
        try {
            future.get(1, TimeUnit.SECONDS).stream().forEach(res -> {
                System.out.printf("[%s].[%s] = %s%n", res.getBase(), res.getInstance(), res.getValue());
            });
            break;
        } catch (TimeoutException e) {
        // pass
        }
        System.out.print(".");
    }
    return null;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) List(java.util.List) TimeoutException(java.util.concurrent.TimeoutException)

Example 23 with SnmpObjId

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

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

the class LaTableMonitor 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.
 */
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    PollStatus status = PollStatus.available();
    InetAddress ipaddr = svc.getAddress();
    ArrayList<String> errorStringReturn = new ArrayList<>();
    // 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);
    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);
    try {
        LOG.debug("PrTableMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
        SnmpObjId laTableErrorSnmpObject = SnmpObjId.get(laTableErrorFlag);
        Map<SnmpInstId, SnmpValue> flagResults = SnmpUtils.getOidValues(agentConfig, "LaTableMonitor", laTableErrorSnmpObject);
        if (flagResults.size() == 0) {
            LOG.debug("SNMP poll failed: no results, addr={} oid={}", hostAddress, laTableErrorSnmpObject);
            return PollStatus.unavailable();
        }
        for (Map.Entry<SnmpInstId, SnmpValue> e : flagResults.entrySet()) {
            LOG.debug("poll: SNMPwalk poll succeeded, addr={} oid={} instance={} value={}", hostAddress, laTableErrorSnmpObject, e.getKey(), e.getValue());
            if (e.getValue().toString().equals("1")) {
                LOG.debug("LaTableMonitor.poll: found errorFlag=1");
                SnmpObjId laTableErrorMsgSnmpObject = SnmpObjId.get(laTableErrorMsg + "." + e.getKey().toString());
                String LaErrorMsg = SnmpUtils.get(agentConfig, laTableErrorMsgSnmpObject).toDisplayString();
                // Stash the error in an ArrayList to then enumerate over later
                errorStringReturn.add(LaErrorMsg);
            }
        }
        // Check the arraylist and construct return value
        if (errorStringReturn.size() > 0) {
            return PollStatus.unavailable(errorStringReturn.toString());
        } else {
            return status;
        }
    } catch (NumberFormatException e) {
        String reason1 = "Number operator used on a non-number " + e.getMessage();
        LOG.error(reason1, e);
        return PollStatus.unavailable(reason1);
    } catch (IllegalArgumentException e) {
        String reason1 = "Invalid SNMP Criteria: " + e.getMessage();
        LOG.error(reason1, e);
        return PollStatus.unavailable(reason1);
    } catch (Throwable t) {
        String reason1 = "Unexpected exception during SNMP poll of interface " + hostAddress;
        LOG.warn(reason1);
        return PollStatus.unavailable(reason1);
    }
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) PollStatus(org.opennms.netmgt.poller.PollStatus) ArrayList(java.util.ArrayList) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) InetAddress(java.net.InetAddress) Map(java.util.Map) ParameterMap(org.opennms.core.utils.ParameterMap)

Example 25 with SnmpObjId

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

the class OmsaStorageMonitor method poll.

/**
 * {@inheritDoc}
 */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    PollStatus status = PollStatus.available();
    InetAddress ipaddr = svc.getAddress();
    final StringBuilder returnValue = new StringBuilder();
    SnmpAgentConfig agentConfig = configureAgent(svc, parameters);
    Integer virtualDiskNumber = ParameterMap.getKeyedInteger(parameters, "virtualDiskNumber", 1);
    LOG.debug("poll: service= SNMP address= {}", agentConfig);
    final String hostAddress = InetAddressUtils.str(ipaddr);
    try {
        LOG.debug("OMSAStorageMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
        SnmpObjId virtualDiskRollUpStatusSnmpObject = SnmpObjId.get(virtualDiskRollUpStatus + "." + virtualDiskNumber);
        SnmpValue virtualDiskRollUpStatus = SnmpUtils.get(agentConfig, virtualDiskRollUpStatusSnmpObject);
        if (virtualDiskRollUpStatus == null || virtualDiskRollUpStatus.isNull()) {
            LOG.debug("SNMP poll failed: no results, addr={} oid={}", hostAddress, virtualDiskRollUpStatusSnmpObject);
            return PollStatus.unavailable();
        }
        if (virtualDiskRollUpStatus.toInt() != 3) {
            // array or one of its components is not happy lets find out which
            // XXX should degraded be the virtualDiskState ?
            returnValue.append("log vol(").append(virtualDiskNumber).append(") degraded");
            SnmpObjId arrayDiskLogicalConnectionVirtualDiskNumberSnmpObject = SnmpObjId.get(arrayDiskLogicalConnectionVirtualDiskNumber);
            Map<SnmpInstId, SnmpValue> arrayDisks = SnmpUtils.getOidValues(agentConfig, "OMSAStorageMonitor", arrayDiskLogicalConnectionVirtualDiskNumberSnmpObject);
            SnmpObjId arrayDiskLogicalConnectionArrayDiskNumberSnmpObject = SnmpObjId.get(arrayDiskLogicalConnectionArrayDiskNumber);
            Map<SnmpInstId, SnmpValue> arrayDiskConnectionNumber = SnmpUtils.getOidValues(agentConfig, "OMSAStorageMonitor", arrayDiskLogicalConnectionArrayDiskNumberSnmpObject);
            for (Map.Entry<SnmpInstId, SnmpValue> disk : arrayDisks.entrySet()) {
                LOG.debug("OMSAStorageMonitor :: arrayDiskNembers=", disk.getValue());
                if (disk.getValue().toInt() == virtualDiskNumber) {
                    LOG.debug("OMSAStorageMonitor :: Disk Found! ");
                    LOG.debug("OMSAStorageMonitor :: Found This Array Disk Value {}", disk.getKey());
                    SnmpObjId arrayDiskStateSnmpObject = SnmpObjId.get(arrayDiskState + "." + arrayDiskConnectionNumber.get(disk.getKey()));
                    SnmpValue diskValue = SnmpUtils.get(agentConfig, arrayDiskStateSnmpObject);
                    LOG.debug("OmsaStorageMonitor :: Disk State=", diskValue);
                    if (diskValue.toInt() != 3) {
                        String arrayDiskState = getArrayDiskStatus(diskValue);
                        SnmpObjId arrayDiskNexusIDSnmpObject = SnmpObjId.get(arrayDiskNexusID + "." + disk.getKey().toString());
                        SnmpValue nexusValue = SnmpUtils.get(agentConfig, arrayDiskNexusIDSnmpObject);
                        returnValue.append(" phy drv(").append(nexusValue).append(") ").append(arrayDiskState);
                    }
                }
            }
            return PollStatus.unavailable(returnValue.toString());
        }
    } 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);
    }
    return status;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) PollStatus(org.opennms.netmgt.poller.PollStatus) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) InetAddress(java.net.InetAddress) Map(java.util.Map) ParameterMap(org.opennms.core.utils.ParameterMap)

Aggregations

SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)73 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)47 SnmpInstId (org.opennms.netmgt.snmp.SnmpInstId)23 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)21 InetAddress (java.net.InetAddress)19 ArrayList (java.util.ArrayList)15 Test (org.junit.Test)14 Map (java.util.Map)13 PollStatus (org.opennms.netmgt.poller.PollStatus)12 PDU (org.snmp4j.PDU)10 ParameterMap (org.opennms.core.utils.ParameterMap)9 SnmpResult (org.opennms.netmgt.snmp.SnmpResult)7 SnmpTrapBuilder (org.opennms.netmgt.snmp.SnmpTrapBuilder)6 List (java.util.List)5 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)4 SnmpWalker (org.opennms.netmgt.snmp.SnmpWalker)4 IOException (java.io.IOException)3 Date (java.util.Date)3 HashMap (java.util.HashMap)3 ExecutionException (java.util.concurrent.ExecutionException)3