Search in sources :

Example 71 with SnmpAgentConfig

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

the class NrtController method createCollectionJobs.

private List<CollectionJob> createCollectionJobs(OnmsResource reportResource, PrefabGraph prefabGraph, String nrtCollectionTaskId) {
    List<CollectionJob> collectionJobs = new ArrayList<CollectionJob>();
    OnmsResource nodeResource = reportResource.getParent();
    OnmsNode node = m_nodeDao.get(nodeResource.getName());
    Integer nodeId = node.getId();
    Date createTimestamp = new Date();
    // What protocols are involved?
    // For each protocol build a new CollectionJob
    Set<RrdGraphAttribute> relevantRrdGraphAttributes = getRequiredRrdGraphAttributes(reportResource, prefabGraph);
    Map<String, String> rrdGraphAttributesMetaData = getMetaDataForReport(relevantRrdGraphAttributes);
    Map<String, List<MetricTuple>> metricsByProtocol = getMetricIdsByProtocol(rrdGraphAttributesMetaData);
    // Destinations for MeasurementSets
    Set<String> resultDestinations = new HashSet<String>();
    resultDestinations.add(nrtCollectionTaskId);
    for (final Map.Entry<String, List<MetricTuple>> entry : metricsByProtocol.entrySet()) {
        final String protocol = entry.getKey();
        final List<MetricTuple> tuples = entry.getValue();
        final CollectionJob collectionJob = new DefaultCollectionJob();
        collectionJob.setService(protocol);
        collectionJob.setNodeId(nodeId);
        collectionJob.setCreationTimestamp(createTimestamp);
        for (final MetricTuple metricTuple : tuples) {
            collectionJob.addMetric(metricTuple.getMetricId(), resultDestinations, metricTuple.getOnmsLogicMetricId());
        }
        // I know....
        if (protocol.equals("SNMP") || protocol.equals("TCA")) {
            collectionJob.setNetInterface(protocol);
            OnmsMonitoringLocation location = node.getLocation();
            String locationName = (location == null) ? null : location.getLocationName();
            final SnmpAgentConfig snmpAgentConfig = m_snmpAgentConfigFactory.getAgentConfig(node.getPrimaryInterface().getIpAddress(), locationName);
            collectionJob.setProtocolConfiguration(snmpAgentConfig.toProtocolConfigString());
            collectionJob.setNetInterface(node.getPrimaryInterface().getIpAddress().getHostAddress());
            collectionJobs.add(collectionJob);
        } else {
            logger.error("Protocol '{}' is not supported yet. CollectionJob will be ignorred.", protocol);
        }
    }
    return collectionJobs;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) OnmsNode(org.opennms.netmgt.model.OnmsNode) DefaultCollectionJob(org.opennms.nrtg.api.model.DefaultCollectionJob) ArrayList(java.util.ArrayList) Date(java.util.Date) RrdGraphAttribute(org.opennms.netmgt.model.RrdGraphAttribute) OnmsResource(org.opennms.netmgt.model.OnmsResource) DefaultCollectionJob(org.opennms.nrtg.api.model.DefaultCollectionJob) CollectionJob(org.opennms.nrtg.api.model.CollectionJob) ArrayList(java.util.ArrayList) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) OnmsMonitoringLocation(org.opennms.netmgt.model.monitoringLocations.OnmsMonitoringLocation)

Example 72 with SnmpAgentConfig

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

the class BgpSessionMonitor 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 = "";
    PollStatus status = PollStatus.unavailable();
    InetAddress ipaddr = svc.getAddress();
    // Initialize the messages if the session is down
    String adminStateMsg = "N/A";
    String peerStateMsg = "N/A";
    String remoteAsMsg = "N/A";
    String lastErrorMsg = "N/A";
    String estTimeMsg = "N/A";
    // 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 bgpPeerIp = ParameterMap.getKeyedString(parameters, "bgpPeerIp", null);
    if (bgpPeerIp == null) {
        LOG.warn("poll: No BGP-Peer IP Defined! ");
        return status;
    }
    // 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()));
    // 
    try {
        LOG.debug("poll: SnmpAgentConfig address: {}", agentConfig);
        // Get the BGP peer state
        SnmpObjId bgpPeerStateSnmpObject = SnmpObjId.get(BGP_PEER_STATE_OID + "." + bgpPeerIp);
        SnmpValue bgpPeerState = SnmpUtils.get(agentConfig, bgpPeerStateSnmpObject);
        // If no peer state is received or SNMP is not possible, service is down
        if (bgpPeerState == null) {
            LOG.warn("No BGP peer state received!");
            return status;
        } else {
            LOG.debug("poll: bgpPeerState: {}", bgpPeerState);
            peerStateMsg = resolvePeerState(bgpPeerState.toInt());
        }
        /*
             *  Do no unnecessary SNMP requests, if peer state is up, return with 
             *  service available and go away.
             */
        if (bgpPeerState.toInt() == BGP_PEER_STATE.ESTABLISHED.value()) {
            LOG.debug("poll: bgpPeerState: {}", BGP_PEER_STATE.ESTABLISHED.name());
            return PollStatus.available();
        }
        // Peer state is not established gather some information
        SnmpObjId bgpPeerAdminStateSnmpObject = SnmpObjId.get(BGP_PEER_ADMIN_STATE_OID + "." + bgpPeerIp);
        SnmpValue bgpPeerAdminState = SnmpUtils.get(agentConfig, bgpPeerAdminStateSnmpObject);
        // Check correct MIB-Support
        if (bgpPeerAdminState == null) {
            LOG.warn("Cannot receive bgpAdminState");
        } else {
            LOG.debug("poll: bgpPeerAdminState: {}", bgpPeerAdminState);
            adminStateMsg = resolveAdminState(bgpPeerAdminState.toInt());
        }
        SnmpObjId bgpPeerRemoteAsSnmpObject = SnmpObjId.get(BGP_PEER_REMOTEAS_OID + "." + bgpPeerIp);
        SnmpValue bgpPeerRemoteAs = SnmpUtils.get(agentConfig, bgpPeerRemoteAsSnmpObject);
        // Check correct MIB-Support
        if (bgpPeerRemoteAs == null) {
            LOG.warn("Cannot receive bgpPeerRemoteAs");
        } else {
            LOG.debug("poll: bgpPeerRemoteAs: {}", bgpPeerRemoteAs);
            remoteAsMsg = bgpPeerRemoteAs.toString();
        }
        SnmpObjId bgpPeerLastErrorSnmpObject = SnmpObjId.get(BGP_PEER_LAST_ERROR_OID + "." + bgpPeerIp);
        SnmpValue bgpPeerLastError = SnmpUtils.get(agentConfig, bgpPeerLastErrorSnmpObject);
        // Check correct MIB-Support
        if (bgpPeerLastError == null) {
            LOG.warn("Cannot receive bgpPeerLastError");
        } else {
            LOG.debug("poll: bgpPeerLastError: {}", bgpPeerLastError);
            lastErrorMsg = resolveBgpErrorCode(bgpPeerLastError.toHexString());
        }
        SnmpObjId bgpPeerFsmEstTimeSnmpObject = SnmpObjId.get(BGP_PEER_FSM_EST_TIME_OID + "." + bgpPeerIp);
        SnmpValue bgpPeerFsmEstTime = SnmpUtils.get(agentConfig, bgpPeerFsmEstTimeSnmpObject);
        // Check correct MIB-Support
        if (bgpPeerFsmEstTime == null) {
            LOG.warn("Cannot receive bgpPeerFsmEstTime");
        } else {
            LOG.debug("poll: bgpPeerFsmEsmTime: {}", bgpPeerFsmEstTime);
            estTimeMsg = bgpPeerFsmEstTime.toString();
        }
        returnValue = "BGP Session state to AS-" + remoteAsMsg + " via " + bgpPeerIp + " is " + peerStateMsg + "! Last peer " + "error message is " + lastErrorMsg + ". BGP admin state is " + adminStateMsg + ". BGP Session established time: " + estTimeMsg;
        // Set service down and return gathered information
        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) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) InetAddress(java.net.InetAddress)

Example 73 with SnmpAgentConfig

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

use of org.opennms.netmgt.snmp.SnmpAgentConfig 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() / 1000d).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() * 2L);
    } 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 75 with SnmpAgentConfig

use of org.opennms.netmgt.snmp.SnmpAgentConfig 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)

Aggregations

SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)120 InetAddress (java.net.InetAddress)31 Test (org.junit.Test)31 JUnitSnmpAgents (org.opennms.core.test.snmp.annotations.JUnitSnmpAgents)23 ArrayList (java.util.ArrayList)22 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)21 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)21 SnmpInstId (org.opennms.netmgt.snmp.SnmpInstId)16 PollStatus (org.opennms.netmgt.poller.PollStatus)14 Map (java.util.Map)11 ExecutionException (java.util.concurrent.ExecutionException)9 ParameterMap (org.opennms.core.utils.ParameterMap)9 SnmpWalker (org.opennms.netmgt.snmp.SnmpWalker)8 Date (java.util.Date)7 LldpLink (org.opennms.netmgt.model.LldpLink)7 OnmsNode (org.opennms.netmgt.model.OnmsNode)7 HashMap (java.util.HashMap)6 List (java.util.List)5 LldpLocPortGetter (org.opennms.netmgt.enlinkd.snmp.LldpLocPortGetter)4 LldpRemTableTracker (org.opennms.netmgt.enlinkd.snmp.LldpRemTableTracker)4