Search in sources :

Example 71 with SnmpValue

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

the class CiscoIpSlaMonitor 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) {
    String returnValue = "SNMP request failed or Cisco IP SLA tag ";
    boolean monitorThresh = false;
    PollStatus status = PollStatus.unavailable();
    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 for tag to monitor
    String adminTag = ParameterMap.getKeyedString(parameters, "admin-tag", null);
    if (adminTag == null) {
        LOG.debug("No IP SLA admin-tag parameter defined! ");
        status = PollStatus.unavailable("No IP SLA admin-tag parameter defined! ");
        return status;
    }
    // If no ip sla tag found, tell which ip sla tag is configured
    returnValue += adminTag + " not found";
    // Get configuration parameter to check if threshold should monitor
    String ignoreThreshold = ParameterMap.getKeyedString(parameters, "ignore-thresh", null);
    if (ignoreThreshold == null) {
        LOG.debug("No ignoreThreshold parmater defined! ");
        status = PollStatus.unavailable("No ignoreThreshold parmater defined! ");
        return status;
    }
    // Convert threshold parameter to boolean
    if (ignoreThreshold.equals("false")) {
        monitorThresh = true;
    }
    // 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()));
    // Establish SNMP session with interface
    try {
        LOG.debug("poll: SnmpAgentConfig address: {}", agentConfig);
        // Get all configured ip sla tags
        Map<SnmpInstId, SnmpValue> tagResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaMonitor", SnmpObjId.get(RTT_ADMIN_TAG_OID));
        if (tagResults == null) {
            LOG.debug("No admin tags received! ");
            status = PollStatus.unavailable("No admin tags received! ");
            return status;
        }
        // Iterate over the list of configured IP SLAs
        for (SnmpInstId ipslaInstance : tagResults.keySet()) {
            // Check if a given IP-SLA with the specific "tag" exist
            if (tagResults.get(ipslaInstance).toString().equals(adminTag)) {
                // Get all operation sense
                Map<SnmpInstId, SnmpValue> operSenseResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaMonitor", SnmpObjId.get(RTT_LATEST_OPERSENSE_OID));
                if (operSenseResults == null) {
                    LOG.debug("No latest oper sense received! ");
                    status = PollStatus.unavailable("No latest oper sense received! ");
                    return status;
                }
                // Get all operation states
                Map<SnmpInstId, SnmpValue> operStateResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaMonitor", SnmpObjId.get(RTT_OPER_STATE_OID));
                if (operStateResults == null) {
                    LOG.debug("No oper state received! ");
                    status = PollStatus.unavailable("No oper state received! ");
                    return status;
                }
                // Get all configured ip sla types
                Map<SnmpInstId, SnmpValue> adminTypeResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaMonitor", SnmpObjId.get(RTT_ADMIN_TYPE_OID));
                if (adminTypeResults == null) {
                    LOG.debug("No ip sla types received! ");
                    status = PollStatus.unavailable("No ip sla types received! ");
                    return status;
                }
                // Get all configured ip sla latest RTT
                Map<SnmpInstId, SnmpValue> latestRttResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaMonitor", SnmpObjId.get(RTT_LATEST_OID));
                if (latestRttResults == null) {
                    LOG.debug("No ip sla latest RTT received! ");
                    status = PollStatus.unavailable("No ip sla latest RTT received! ");
                    return status;
                }
                LOG.debug("poll: instance={} admin tag={} value={} oper state={} ignoreThreshold={} latest RTT{}", ipslaInstance.toInt(), adminTag, tagResults.get(ipslaInstance), operStateResults.get(ipslaInstance), ignoreThreshold, latestRttResults.get(ipslaInstance));
                // Build return value for service down
                returnValue = "Cisco IP SLA tag " + adminTag + " with oper state " + resolveOperSate(operStateResults.get(ipslaInstance).toInt()) + " returned with oper sense " + resolveOperSense(operSenseResults.get(ipslaInstance).toInt()) + ". Configured IP SLA type is " + resolveAdminType(adminTypeResults.get(ipslaInstance).toInt()) + ". Latest RTT is " + latestRttResults.get(ipslaInstance);
                LOG.debug(returnValue);
                // Check if thresholding is relevant
                if (monitorThresh && (operSenseResults.get(ipslaInstance).toInt() == RTT_MON_OPER_SENSE.OVER_THRESHOLD.value())) {
                    // Get all configured ip sla thresholds
                    Map<SnmpInstId, SnmpValue> threshResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaMonitor", SnmpObjId.get(RTT_ADMIN_THRESH_OID));
                    if (monitorThresh && threshResults == null) {
                        LOG.debug("No ip sla thresholds received! ");
                        status = PollStatus.unavailable("No ip sla thresholds received! ");
                        return status;
                    }
                    // Threshold monitoring
                    LOG.debug("IP SLA: {} threshold exceeded.", tagResults.get(ipslaInstance));
                    returnValue += ". Monitoring threshold is enabled. Threshold value is " + threshResults.get(ipslaInstance);
                    // Configured threshold is exceeded, service unavailable
                    return PollStatus.unavailable(returnValue);
                } else {
                    /*
                         *  Threshold should be ignored, check if OK or
                         *  OVER_THRESHOLD.
                         *  Over threshold means also OK, no timeout or other 
                         *  error occurred.
                         */
                    if (operSenseResults.get(ipslaInstance).toInt() == RTT_MON_OPER_SENSE.OK.value() || operSenseResults.get(ipslaInstance).toInt() == RTT_MON_OPER_SENSE.OVER_THRESHOLD.value()) {
                        LOG.debug("Threshold is ignored rttMonLatestOperSense: {}", operSenseResults.get(ipslaInstance).toInt());
                        LOG.debug(returnValue);
                        status = PollStatus.available(Double.parseDouble(latestRttResults.get(ipslaInstance).toString()));
                        // No error or connection timeout, service available
                        return status;
                    }
                }
            }
        // else no configured IP SLA tag exist
        }
        // Otherwise set service down
        status = PollStatus.unavailable(returnValue);
    } catch (NullPointerException e) {
        String reason = "Unexpected error during SNMP poll of interface " + hostAddress;
        LOG.debug(reason, e);
        status = PollStatus.unavailable(reason);
    } 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);
    }
    // Otherwise, the service will be unavailable.
    return status;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) PollStatus(org.opennms.netmgt.poller.PollStatus) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) InetAddress(java.net.InetAddress)

Example 72 with SnmpValue

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

the class CiscoPingMibMonitor method poll.

/**
     * {@inheritDoc}
     *
     * <P>
     * The poll() method is responsible for setting up and following up the IOS
     * ping entry that proxies monitoring of the specified address for ICMP
     * service availability.
     * </P>
     * @exception RuntimeException
     *                Thrown for any unrecoverable errors.
     */
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    final InetAddress targetIpAddr = InetAddrUtils.addr(getKeyedString(parameters, "targetIpAddr", null));
    final InetAddress proxyIpAddr = InetAddrUtils.addr(getKeyedString(parameters, "proxyIpAddr", null));
    int pingProtocol = 0;
    try {
        pingProtocol = determineAddrType(targetIpAddr);
    } catch (RuntimeException e) {
        LOG.debug("Unknown address type - neither IPv4 nor IPv6", e);
        return PollStatus.unavailable("Unknown address type - neither IPv4 nor IPv6");
    }
    // Get configuration parameters into a CiscoPingEntry object
    //
    CiscoPingEntry pingEntry = new CiscoPingEntry();
    pingEntry.setCiscoPingPacketCount(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_COUNT, PARM_PACKET_COUNT_DEFAULT));
    pingEntry.setCiscoPingPacketSize(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_SIZE, PARM_PACKET_SIZE_DEFAULT));
    pingEntry.setCiscoPingPacketTimeout(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_TIMEOUT, PARM_PACKET_TIMEOUT_DEFAULT));
    pingEntry.setCiscoPingPacketDelay(ParameterMap.getKeyedInteger(parameters, PARM_PACKET_DELAY, PARM_PACKET_DELAY_DEFAULT));
    pingEntry.setCiscoPingEntryOwner(ParameterMap.getKeyedString(parameters, PARM_ENTRY_OWNER, PARM_ENTRY_OWNER_DEFAULT));
    pingEntry.setCiscoPingVrfName(ParameterMap.getKeyedString(parameters, PARM_VRF_NAME, PARM_VRF_NAME_DEFAULT));
    pingEntry.setCiscoPingSerialNumber(Double.valueOf(System.currentTimeMillis() / 1000).intValue());
    pingEntry.setCiscoPingProtocol(pingProtocol);
    pingEntry.setCiscoPingAddress(targetIpAddr);
    pingEntry.setCiscoPingEntryStatus(ROWSTATUS_CREATE_AND_GO);
    int minSuccessPercent = ParameterMap.getKeyedInteger(parameters, PARM_SUCCESS_PERCENT, PARM_SUCCESS_PERCENT_DEFAULT);
    // FIXME: Should the cleanup stuff be fixed to actually use this? Not clear if it really matters.
    // int cleanupInterval = ParameterMap.getKeyedInteger(parameters, PARM_CLEANUP_INTERVAL, PARM_CLEANUP_INTERVAL_DEFAULT);
    // Retrieve the *proxy* interface's SNMP peer object
    //
    SnmpAgentConfig agentConfig = getAgentConfig(svc, parameters);
    LOG.debug("poll: setting SNMP peer attribute for interface {}", proxyIpAddr.getHostAddress());
    // 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("Setting up CISCO-PING-MIB proxy poll for service {} on interface {} -- {}", svc.getSvcName(), targetIpAddr, pingEntry);
    PollStatus serviceStatus = null;
    TimeoutTracker timeoutTracker = new TimeoutTracker(parameters, DEFAULT_RETRY, DEFAULT_TIMEOUT);
    // Send the SET-REQUEST PDU to create the ciscoPingEntry in createAndGo mode
    SnmpValue[] setResult = SnmpUtils.set(agentConfig, pingEntry.generateCreateOids(), pingEntry.generateCreateValues());
    if (setResult == null) {
        LOG.warn("SNMP SET operation unsuccessful for proxy-ping entry for target {} -- {}", targetIpAddr, pingEntry);
        return PollStatus.unknown("SNMP SET failed for ciscoPingTable entry on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
    }
    // a good starting point.
    try {
        Thread.sleep(pingEntry.calculateMinInitialWait() * 2);
    } catch (InterruptedException e) {
    }
    // Now check whether the ping has completed and, if so, whether it succeeded and its times
    SnmpValue[] statusValues = null;
    for (timeoutTracker.reset(); (timeoutTracker.shouldRetry() && (statusValues == null || statusValues.length < 6 || statusValues[5].toInt() != 1)); timeoutTracker.nextAttempt()) {
        statusValues = SnmpUtils.get(agentConfig, pingEntry.generateResultsOids());
    }
    // If we didn't get the results back, mark the service as unknown
    if (statusValues == null || (statusValues.length == 1 && statusValues[0] == null)) {
        LOG.warn("SNMP GET operation unsuccessful for proxy-ping entry for target {} -- {}", targetIpAddr, pingEntry);
        return PollStatus.unknown("SNMP GET failed for ciscoPingTable entry on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
    }
    // mark the service unknown
    if (statusValues.length < 6) {
        LOG.warn("Proxy-ping entry did not indicate whether ping completed after retries exhausted for target {} -- {}", targetIpAddr, pingEntry);
        return PollStatus.unknown("ciscoPingTable entry is missing pingCompleted column on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
    }
    // mark the service unknown
    if (statusValues[5].toInt() != 1) {
        LOG.warn("Proxy-ping entry marked not completed after retries exhausted for target {} -- {}", targetIpAddr, pingEntry);
        return PollStatus.unknown("ciscoPingTable entry marked not completed on proxy interface " + proxyIpAddr + " with instance ID " + pingEntry.getCiscoPingSerialNumber());
    }
    // If the ping has completed, verify that the percent of completed pings meets our minimum
    // success percent.  If not, mark the service down.
    double sentPings = statusValues[0].toInt();
    double receivedPings = statusValues[1].toInt();
    double successPct = receivedPings / sentPings * 100;
    if (receivedPings == 0) {
        LOG.info("Proxy-ping entry indicates no pings succeeded for target {} -- {}", targetIpAddr, pingEntry);
        cleanupCurrentEntry(pingEntry, proxyIpAddr, agentConfig);
        return PollStatus.unavailable("All remote pings (" + sentPings + " of " + sentPings + ") failed");
    } else if (successPct < minSuccessPercent) {
        LOG.info("Proxy-ping entry indicates {}% success, which misses the success-percent target of {}% for target {} -- {}", successPct, minSuccessPercent, targetIpAddr, pingEntry);
        cleanupCurrentEntry(pingEntry, proxyIpAddr, agentConfig);
        return PollStatus.unavailable(successPct + " percent (" + receivedPings + "/" + sentPings + ") pings succeeded, less than target " + minSuccessPercent + " percent");
    }
    // If we've arrived here, then enough pings completed to consider the service up!
    Map<String, Number> pingProps = new HashMap<String, Number>();
    double minRtt = statusValues[2].toInt();
    double avgRtt = statusValues[3].toInt();
    double maxRtt = statusValues[4].toInt();
    LOG.debug("Logging successful poll: sent={}, received={}, minRtt={}, avgRtt={}, maxRtt={} for proxy-ping of target {} -- {}", sentPings, receivedPings, minRtt, avgRtt, maxRtt, targetIpAddr, pingEntry);
    pingProps.put("sent", sentPings);
    pingProps.put("received", receivedPings);
    pingProps.put("minRtt", minRtt);
    pingProps.put("avgRtt", avgRtt);
    pingProps.put("maxRtt", maxRtt);
    cleanupCurrentEntry(pingEntry, proxyIpAddr, agentConfig);
    // TODO: Find and clean up defunct rows before returning
    // Actually it's not clear that this is necessary, seems IOS cleans up old
    // entries on its own some minutes after their creation.  Need to investigate.
    serviceStatus = PollStatus.available(avgRtt);
    serviceStatus.setProperties(pingProps);
    return serviceStatus;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) PollStatus(org.opennms.netmgt.poller.PollStatus) HashMap(java.util.HashMap) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) InetAddress(java.net.InetAddress)

Example 73 with SnmpValue

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

the class DiskUsageMonitor method poll.

/**
     * {@inheritDoc}
     *
     * The poll() method is responsible for polling the specified address for
     * SNMP service availability.
     *
     * @param svc
     * @param parameters
     * @return PollStatus
     * <p>
     * @exception RuntimeException
     *                             Thrown for any unrecoverable errors.
     */
@Override
public PollStatus poll(final MonitoredService svc, final Map<String, Object> parameters) {
    MatchType matchType = MatchType.EXACT;
    RequireType reqType = RequireType.ALL;
    PollStatus status = PollStatus.available();
    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);
    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()));
    String diskNamePattern = ParameterMap.getKeyedString(parameters, "disk", null);
    if (diskNamePattern == null) {
        throw new RuntimeException("Invalid null value for parameter 'disk'");
    }
    Integer percentFree = ParameterMap.getKeyedInteger(parameters, "free", 15);
    String matchTypeStr = ParameterMap.getKeyedString(parameters, "match-type", "exact");
    try {
        matchType = MatchType.valueOf(matchTypeStr.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Unknown value '" + matchTypeStr + "' for parameter 'match-type'");
    }
    String reqTypeStr = ParameterMap.getKeyedString(parameters, "require-type", "all");
    try {
        reqType = RequireType.valueOf(reqTypeStr.toUpperCase());
    } catch (IllegalArgumentException e) {
        throw new RuntimeException("Unknown value '" + reqTypeStr + "' for parameter 'require-type'");
    }
    LOG.debug("poll: diskNamePattern={}", diskNamePattern);
    LOG.debug("poll: percentfree={}", percentFree);
    LOG.debug("poll: matchType={}", matchTypeStr);
    LOG.debug("poll: reqType={}", reqTypeStr);
    LOG.debug("poll: service={} address={}", svc, agentConfig);
    try {
        LOG.debug("poll: SnmpAgentConfig address: {}", agentConfig);
        SnmpObjId hrStorageDescrSnmpObject = SnmpObjId.get(hrStorageDescr);
        Map<SnmpInstId, SnmpValue> results = SnmpUtils.getOidValues(agentConfig, "DiskUsagePoller", hrStorageDescrSnmpObject);
        if (results.isEmpty()) {
            LOG.debug("SNMP poll failed: no results, addr={} oid={}", hostAddress, hrStorageDescrSnmpObject);
            return PollStatus.unavailable("No entries found in hrStorageDescr");
        }
        boolean foundDisk = false;
        for (Map.Entry<SnmpInstId, SnmpValue> e : results.entrySet()) {
            LOG.debug("poll: SNMPwalk poll succeeded, addr={} oid={} instance={} value={}", hostAddress, hrStorageDescrSnmpObject, e.getKey(), e.getValue());
            final String snmpInstance = e.getKey().toString();
            final String diskName = e.getValue().toString();
            if (isMatch(diskName, diskNamePattern, matchType)) {
                LOG.debug("poll: found disk={}", diskName);
                final SnmpObjId hrStorageSizeSnmpObject = SnmpObjId.get(hrStorageSize, snmpInstance);
                final SnmpObjId hrStorageUsedSnmpObject = SnmpObjId.get(hrStorageUsed, snmpInstance);
                final SnmpValue snmpSize = SnmpUtils.get(agentConfig, hrStorageSizeSnmpObject);
                final SnmpValue snmpUsed = SnmpUtils.get(agentConfig, hrStorageUsedSnmpObject);
                float calculatedPercentage = ((((float) snmpSize.toLong() - (float) snmpUsed.toLong()) / (float) snmpSize.toLong())) * 100;
                LOG.debug("poll: calculatedPercentage={} percentFree={}", calculatedPercentage, percentFree);
                if (calculatedPercentage < percentFree) {
                    return PollStatus.unavailable(diskName + " usage high (" + (100 - (int) calculatedPercentage) + "%)");
                } else {
                    if (matchType == MatchType.EXACT || reqType == RequireType.ANY) {
                        return status;
                    }
                    if (reqType == RequireType.ALL) {
                        foundDisk = true;
                    }
                }
            }
        }
        if (foundDisk) {
            return status;
        }
        // if we get here.. it means we did not find the disk...  which means we should not be monitoring it.
        LOG.debug("poll: no disks found");
        return PollStatus.unavailable("Could not find " + diskNamePattern + " in hrStorageTable");
    } 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)

Example 74 with SnmpValue

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

the class DskTableMonitor 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<String>();
    // 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("DskTableMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
        SnmpObjId dskTableErrorSnmpObject = SnmpObjId.get(dskTableErrorFlag);
        Map<SnmpInstId, SnmpValue> flagResults = SnmpUtils.getOidValues(agentConfig, "DskTableMonitor", dskTableErrorSnmpObject);
        if (flagResults.size() == 0) {
            LOG.debug("SNMP poll failed: no results, addr={} oid={}", hostAddress, dskTableErrorSnmpObject);
            return PollStatus.unavailable();
        }
        for (Map.Entry<SnmpInstId, SnmpValue> e : flagResults.entrySet()) {
            LOG.debug("poll: SNMPwalk poll succeeded, addr={} oid={} instance={} value={}", hostAddress, dskTableErrorSnmpObject, e.getKey(), e.getValue());
            if (e.getValue().toString().equals("1")) {
                LOG.debug("DskTableMonitor.poll: found errorFlag=1");
                SnmpObjId dskTableErrorMsgSnmpObject = SnmpObjId.get(dskTableErrorMsg + "." + e.getKey().toString());
                String DiskErrorMsg = SnmpUtils.get(agentConfig, dskTableErrorMsgSnmpObject).toDisplayString();
                //Stash the error in an ArrayList to then enumerate over later
                errorStringReturn.add(DiskErrorMsg);
            }
        }
        //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";
        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 + ": " + t.getMessage();
        LOG.warn(reason1, t);
        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 75 with SnmpValue

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

the class Snmp4JStrategyIT method testSendWithGetPduMultipleValues.

@Test
public void testSendWithGetPduMultipleValues() throws Exception {
    SnmpObjId[] oids = new SnmpObjId[] { SnmpObjId.get(".1.3.5.1.1.3.0"), SnmpObjId.get(".1.3.5.1.1.4.0") };
    Snmp4JAgentConfig agentConfig = new Snmp4JAgentConfig(getAgentConfig());
    SnmpValue[] retvalues = null;
    PDU pdu = m_strategy.buildPdu(agentConfig, PDU.GET, oids, null);
    if (pdu != null) {
        retvalues = m_strategy.send(agentConfig, pdu, true);
    }
    SnmpValue[] values = retvalues;
    assertNotNull("values should not be null", values);
    assertEquals("values list size", 2, values.length);
    assertSnmpValueEquals("values[0]", SnmpValue.SNMP_INT32, 42, values[0]);
    assertSnmpValueEquals("values[0]", SnmpValue.SNMP_GAUGE32, 42, values[1]);
}
Also used : PDU(org.snmp4j.PDU) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) Test(org.junit.Test)

Aggregations

SnmpValue (org.opennms.netmgt.snmp.SnmpValue)112 Test (org.junit.Test)57 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)47 SnmpValueFactory (org.opennms.netmgt.snmp.SnmpValueFactory)24 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)21 SnmpInstId (org.opennms.netmgt.snmp.SnmpInstId)20 InetAddress (java.net.InetAddress)19 Map (java.util.Map)14 PollStatus (org.opennms.netmgt.poller.PollStatus)14 JoeSnmpValueFactory (org.opennms.netmgt.snmp.joesnmp.JoeSnmpValueFactory)12 ArrayList (java.util.ArrayList)11 ParameterMap (org.opennms.core.utils.ParameterMap)9 Parm (org.opennms.netmgt.xml.event.Parm)9 PDU (org.snmp4j.PDU)9 AttributeGroupType (org.opennms.netmgt.collection.api.AttributeGroupType)8 SnmpResult (org.opennms.netmgt.snmp.SnmpResult)8 LinkedHashMap (java.util.LinkedHashMap)7 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)5 HashMap (java.util.HashMap)4 NumericAttributeType (org.opennms.netmgt.collectd.NumericAttributeType)4