Search in sources :

Example 61 with SnmpValue

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

the class Snmp4JStrategyIT method testPreparePduWithTooFewValues.

@Test
public void testPreparePduWithTooFewValues() 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") };
    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 62 with SnmpValue

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

the class TcaCollectorIT method testCollector.

/**
 * Test collector.
 *
 * @throws Exception the exception
 */
@Test
public void testCollector() throws Exception {
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("collection", "default");
    // Create Collection Set
    TcaCollector collector = new TcaCollector();
    collector.setConfigDao(m_configDao);
    collector.setResourceStorageDao(m_resourceStorageDao);
    collector.setResourceTypesDao(m_resourceTypesDao);
    collector.setLocationAwareSnmpClient(m_client);
    CollectionSetVisitor persister = m_persisterFactory.createOneToOnePersister(new ServiceParameters(parameters), collector.getRrdRepository("default"), false, false);
    // Setup SNMP Value Handling
    SnmpValueFactory valFac = SnmpUtils.getValueFactory();
    SnmpObjId peer1 = SnmpObjId.get(".1.3.6.1.4.1.27091.3.1.6.1.2.171.19.37.60");
    SnmpObjId peer2 = SnmpObjId.get(".1.3.6.1.4.1.27091.3.1.6.1.2.171.19.38.70");
    // Collect and Persist Data - Step 1
    CollectionSet collectionSet = collector.collect(m_collectionAgent, parameters);
    validateCollectionSet(collectionSet);
    collectionSet.visit(persister);
    // Generate new SNMP Data
    final StringBuilder sb = new StringBuilder("|25|");
    long ts = 1327451787l;
    for (int i = 0; i < 25; i++) {
        sb.append(ts++);
        sb.append(",12,-1,12,-2,1|");
    }
    // Get Current Values
    SnmpValue v1a = SnmpUtils.get(m_collectionAgent.getAgentConfig(), peer1);
    SnmpValue v2a = SnmpUtils.get(m_collectionAgent.getAgentConfig(), peer2);
    // Set New Values
    SnmpUtils.set(m_collectionAgent.getAgentConfig(), peer1, valFac.getOctetString(sb.toString().getBytes()));
    SnmpUtils.set(m_collectionAgent.getAgentConfig(), peer2, valFac.getOctetString(sb.toString().getBytes()));
    // Validate New Values
    SnmpValue v1b = SnmpUtils.get(m_collectionAgent.getAgentConfig(), peer1);
    SnmpValue v2b = SnmpUtils.get(m_collectionAgent.getAgentConfig(), peer2);
    Assert.assertFalse(v1a.toDisplayString().equals(v1b.toDisplayString()));
    Assert.assertFalse(v2a.toDisplayString().equals(v2b.toDisplayString()));
    // Collect and Persist Data - Step 2
    collectionSet = collector.collect(m_collectionAgent, parameters);
    validateCollectionSet(collectionSet);
    collectionSet.visit(persister);
    // Validate Persisted Data
    Path pathToJrbFile = getSnmpRoot().toPath().resolve(Paths.get("1", TcaCollectionHandler.RESOURCE_TYPE_NAME, "171.19.37.60", TcaCollectionHandler.INBOUND_DELAY + m_rrdStrategy.getDefaultFileExtension()));
    RrdDb jrb = new RrdDb(pathToJrbFile.toString());
    // According with the Fixed Step
    Assert.assertEquals(1, jrb.getArchive(0).getArcStep());
    // According with the Sample Data
    Assert.assertEquals(ts - 1, jrb.getArchive(0).getEndTime());
    Robin inboundDelay = jrb.getArchive(0).getRobin(0);
    for (int i = inboundDelay.getSize() - 49; i < inboundDelay.getSize() - 25; i++) {
        Assert.assertEquals(new Double(11), Double.valueOf(inboundDelay.getValue(i)));
    }
    for (int i = inboundDelay.getSize() - 24; i < inboundDelay.getSize(); i++) {
        Assert.assertEquals(new Double(12), Double.valueOf(inboundDelay.getValue(i)));
    }
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) CollectionSetVisitor(org.opennms.netmgt.collection.api.CollectionSetVisitor) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) CollectionSet(org.opennms.netmgt.collection.api.CollectionSet) SnmpValueFactory(org.opennms.netmgt.snmp.SnmpValueFactory) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) RrdDb(org.jrobin.core.RrdDb) ServiceParameters(org.opennms.netmgt.collection.api.ServiceParameters) Robin(org.jrobin.core.Robin) Test(org.junit.Test)

Example 63 with SnmpValue

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

the class EventCreator method createEventFrom.

public Event createEventFrom(final TrapDTO trapDTO, final String systemId, final String location, final InetAddress trapAddress) {
    LOG.debug("{} trap - trapInterface: {}", trapDTO.getVersion(), trapDTO.getAgentAddress());
    // Set event data
    final EventBuilder eventBuilder = new EventBuilder(null, "trapd");
    eventBuilder.setTime(new Date(trapDTO.getCreationTime()));
    eventBuilder.setCommunity(trapDTO.getCommunity());
    eventBuilder.setSnmpTimeStamp(trapDTO.getTimestamp());
    eventBuilder.setSnmpVersion(trapDTO.getVersion());
    eventBuilder.setSnmpHost(str(trapAddress));
    eventBuilder.setInterface(trapAddress);
    eventBuilder.setHost(InetAddressUtils.toIpAddrString(trapDTO.getAgentAddress()));
    // Handle trap identity
    final TrapIdentityDTO trapIdentity = trapDTO.getTrapIdentity();
    if (trapIdentity != null) {
        LOG.debug("Trap Identity {}", trapIdentity);
        eventBuilder.setGeneric(trapIdentity.getGeneric());
        eventBuilder.setSpecific(trapIdentity.getSpecific());
        eventBuilder.setEnterpriseId(trapIdentity.getEnterpriseId());
    }
    // Handle var bindings
    for (SnmpResult eachResult : trapDTO.getResults()) {
        final SnmpObjId name = eachResult.getBase();
        final SnmpValue value = eachResult.getValue();
        eventBuilder.addParam(SyntaxToEvent.processSyntax(name.toString(), value));
        if (EventConstants.OID_SNMP_IFINDEX.isPrefixOf(name)) {
            eventBuilder.setIfIndex(value.toInt());
        }
    }
    // Resolve Node id and set, if known by OpenNMS
    resolveNodeId(location, trapAddress).ifPresent(eventBuilder::setNodeid);
    // systemId of the local system if it remains null here.
    if (systemId != null) {
        eventBuilder.setDistPoller(systemId);
    }
    // Get event template and set uei, if unknown
    final Event event = eventBuilder.getEvent();
    final org.opennms.netmgt.xml.eventconf.Event econf = eventConfDao.findByEvent(event);
    if (econf == null || econf.getUei() == null) {
        event.setUei("uei.opennms.org/default/trap");
    } else {
        event.setUei(econf.getUei());
    }
    return event;
}
Also used : EventBuilder(org.opennms.netmgt.model.events.EventBuilder) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SyntaxToEvent(org.opennms.netmgt.model.events.snmp.SyntaxToEvent) Event(org.opennms.netmgt.xml.event.Event) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) Date(java.util.Date) SnmpResult(org.opennms.netmgt.snmp.SnmpResult)

Example 64 with SnmpValue

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

the class TcaProtocolCollector method collect.

@Override
public CollectionJob collect(final CollectionJob collectionJob) {
    logger.info("TcaProtocolCollector is collecting collectionJob '{}'", collectionJob);
    SnmpAgentConfig snmpAgentConfig = SnmpAgentConfig.parseProtocolConfigurationString(collectionJob.getProtocolConfiguration());
    List<Collectable> trackers = new ArrayList<>();
    for (final String metricObjId : collectionJob.getAllMetrics()) {
        final String keyword = metricObjId.substring(metricObjId.lastIndexOf("_") + 1);
        final SnmpObjId requestOid = SnmpObjId.get(metricObjId.substring(0, metricObjId.lastIndexOf("_")));
        SnmpObjId base = requestOid.getPrefix(requestOid.length() - 1);
        int lastId = requestOid.getLastSubId();
        SingleInstanceTracker instanceTracker = new SingleInstanceTracker(base, new SnmpInstId(lastId)) {

            @Override
            protected void storeResult(SnmpResult result) {
                logger.trace("Collected SnmpValue '{}'", result);
                SnmpValue value = result.getValue();
                String compositeResult = getCompositeValue(keyword, value.toDisplayString());
                collectionJob.setMetricValue(metricObjId, "int32", compositeResult);
            }

            @Override
            public void setFailed(boolean failed) {
                super.setFailed(failed);
                logger.trace("Collection Failed for metricObjId '{}'", metricObjId);
                collectionJob.setMetricValue(metricObjId, "unknown", null);
            }

            @Override
            public void setTimedOut(boolean timedOut) {
                super.setTimedOut(timedOut);
                logger.trace("Collection timedOut for metricObjId '{}'", metricObjId);
                collectionJob.setMetricValue(metricObjId, "unknown", null);
            }
        };
        trackers.add(instanceTracker);
    }
    CollectionTracker tracker = new AggregateTracker(trackers);
    try (SnmpWalker walker = m_snmpStrategy.createWalker(snmpAgentConfig, "SnmpProtocolCollector for " + snmpAgentConfig.getAddress(), tracker)) {
        walker.start();
        try {
            walker.waitFor();
        } catch (InterruptedException e) {
            logger.error("Interuppted while waiting for collector. Results may be incomplete.", e);
        }
    }
    return collectionJob;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) Collectable(org.opennms.netmgt.snmp.Collectable) SnmpWalker(org.opennms.netmgt.snmp.SnmpWalker) ArrayList(java.util.ArrayList) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SingleInstanceTracker(org.opennms.netmgt.snmp.SingleInstanceTracker) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) CollectionTracker(org.opennms.netmgt.snmp.CollectionTracker) SnmpResult(org.opennms.netmgt.snmp.SnmpResult) AggregateTracker(org.opennms.netmgt.snmp.AggregateTracker)

Example 65 with SnmpValue

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

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)15 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