Search in sources :

Example 6 with SnmpResult

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

the class ColumnTrackerProxyTest method canHandleValidResponses.

@Test
public void canHandleValidResponses() {
    // Build a response with the requested OID
    SnmpValue value = mock(SnmpValue.class);
    List<SnmpResult> results = new ArrayList<>();
    results.add(new SnmpResult(base, SnmpInstId.INST_ZERO, value));
    // Outside of base
    results.add(new SnmpResult(SnmpObjId.get(".1.3.6.1.2.2"), SnmpInstId.INST_ZERO, null));
    WalkResponse response = new WalkResponse(results);
    // Resolve the walker
    tracker.handleWalkResponses(Collections.singletonList(response));
    // We should be finished, and have captured the expected value
    assertThat(tracker.isFinished(), equalTo(true));
    assertThat(gatherer.getResults(), hasSize(1));
    assertThat(gatherer.getResults().get(0).getValue(), equalTo(value));
}
Also used : SnmpValue(org.opennms.netmgt.snmp.SnmpValue) ArrayList(java.util.ArrayList) SnmpResult(org.opennms.netmgt.snmp.SnmpResult) Test(org.junit.Test)

Example 7 with SnmpResult

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

the class SingleInstanceTrackerProxyTest method canHandleResponsesForOtherOids.

@Test
public void canHandleResponsesForOtherOids() {
    // Build a response for another OID
    SnmpValue value = mock(SnmpValue.class);
    SnmpResult result = new SnmpResult(SnmpObjId.get(".1.3.6.1.2.1.1.1"), instance, value);
    WalkResponse response = new WalkResponse(Collections.singletonList(result));
    // Resolve the walker
    tracker.handleWalkResponses(Collections.singletonList(response));
    // We should be finished, without any captured values
    assertThat(tracker.isFinished(), equalTo(true));
    assertThat(gatherer.getResults(), hasSize(0));
}
Also used : SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpResult(org.opennms.netmgt.snmp.SnmpResult) Test(org.junit.Test)

Example 8 with SnmpResult

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

the class SnmpProxyRpcModule method walk.

private CompletableFuture<Collection<SnmpResponseDTO>> walk(SnmpRequestDTO request, List<SnmpWalkRequestDTO> walks) {
    final CompletableFuture<Collection<SnmpResponseDTO>> future = new CompletableFuture<>();
    final Map<String, SnmpResponseDTO> responsesByCorrelationId = new LinkedHashMap<>();
    final List<Collectable> trackers = new ArrayList<>(walks.size());
    for (final SnmpWalkRequestDTO walk : walks) {
        CollectionTracker tracker;
        if (walk.getInstance() != null) {
            if (walk.getOids().size() != 1) {
                future.completeExceptionally(new IllegalArgumentException("Single instance requests must have a single OID."));
                return future;
            }
            final SnmpObjId oid = walk.getOids().get(0);
            tracker = new SingleInstanceTracker(oid, new SnmpInstId(walk.getInstance())) {

                @Override
                protected void storeResult(SnmpResult res) {
                    addResult(res, walk.getCorrelationId(), responsesByCorrelationId);
                }
            };
        } else {
            final Collection<Collectable> columnTrackers = walk.getOids().stream().map(SnmpObjId::get).map(ColumnTracker::new).collect(Collectors.toList());
            tracker = new AggregateTracker(columnTrackers) {

                @Override
                protected void storeResult(SnmpResult res) {
                    addResult(res, walk.getCorrelationId(), responsesByCorrelationId);
                }
            };
        }
        if (walk.getMaxRepetitions() != null) {
            tracker.setMaxRepetitions(walk.getMaxRepetitions());
        }
        trackers.add(tracker);
    }
    AggregateTracker aggregate = new AggregateTracker(trackers);
    final SnmpWalker walker = SnmpUtils.createWalker(request.getAgent(), request.getDescription(), aggregate);
    walker.setCallback(new SnmpWalkCallback() {

        @Override
        public void complete(SnmpWalker tracker, Throwable t) {
            try {
                if (t != null) {
                    future.completeExceptionally(t);
                } else {
                    future.complete(responsesByCorrelationId.values());
                }
            } finally {
                // Close the tracker using a separate thread
                // This allows the SnmpWalker to clean up properly instead
                // of interrupting execution as it's executing the callback
                REAPER_EXECUTOR.submit(new Runnable() {

                    @Override
                    public void run() {
                        tracker.close();
                    }
                });
            }
        }
    });
    walker.start();
    return future;
}
Also used : Collectable(org.opennms.netmgt.snmp.Collectable) SnmpWalker(org.opennms.netmgt.snmp.SnmpWalker) ArrayList(java.util.ArrayList) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) SnmpWalkCallback(org.opennms.netmgt.snmp.SnmpWalkCallback) LinkedHashMap(java.util.LinkedHashMap) CompletableFuture(java.util.concurrent.CompletableFuture) SingleInstanceTracker(org.opennms.netmgt.snmp.SingleInstanceTracker) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) Collection(java.util.Collection) CollectionTracker(org.opennms.netmgt.snmp.CollectionTracker) SnmpResult(org.opennms.netmgt.snmp.SnmpResult) AggregateTracker(org.opennms.netmgt.snmp.AggregateTracker)

Example 9 with SnmpResult

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

the class SnmpProtocolCollector method collect.

@Override
public CollectionJob collect(final CollectionJob collectionJob) {
    LOG.info("SnmpProtocolCollector is collecting collectionJob '{}'", collectionJob.getId());
    SnmpAgentConfig snmpAgentConfig = SnmpAgentConfig.parseProtocolConfigurationString(collectionJob.getProtocolConfiguration());
    List<Collectable> trackers = new ArrayList<>();
    for (final String metricObjId : collectionJob.getAllMetrics()) {
        SnmpObjId requestOid = SnmpObjId.get(metricObjId);
        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) {
                LOG.trace("Collected SnmpValue '{}'", result);
                SnmpValue value = result.getValue();
                String metricType = value == null ? "unknown" : typeToString(value.getType());
                collectionJob.setMetricValue(metricObjId, metricType, value == null ? null : value.toDisplayString());
            }

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

            @Override
            public void setTimedOut(boolean timedOut) {
                super.setTimedOut(timedOut);
                LOG.trace("Collection timedOut for metricObjId '{}'", metricObjId);
                collectionJob.setMetricValue(metricObjId, "unknown", null);
            }
        };
        trackers.add(instanceTracker);
    }
    // Attempt to determine the location name
    String locationName = null;
    OnmsNode node = m_nodeDao.get(collectionJob.getNodeId());
    if (node != null) {
        OnmsMonitoringLocation monitoringLocation = node.getLocation();
        if (monitoringLocation != null) {
            locationName = monitoringLocation.getLocationName();
        }
    }
    AggregateTracker tracker = new AggregateTracker(trackers);
    CompletableFuture<AggregateTracker> future = m_locationAwareSnmpClient.walk(snmpAgentConfig, tracker).withDescription("NRTG").withLocation(locationName).execute();
    try {
        future.get();
    } catch (ExecutionException e) {
        LOG.warn("Failed to collect SNMP metrics for {}.", snmpAgentConfig.getAddress(), e);
    } catch (InterruptedException e) {
        LOG.warn("Interupted while collectiong SNMP metrics for {}.", snmpAgentConfig.getAddress());
        Thread.interrupted();
    }
    return collectionJob;
}
Also used : SnmpAgentConfig(org.opennms.netmgt.snmp.SnmpAgentConfig) Collectable(org.opennms.netmgt.snmp.Collectable) OnmsNode(org.opennms.netmgt.model.OnmsNode) 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) ExecutionException(java.util.concurrent.ExecutionException) SnmpResult(org.opennms.netmgt.snmp.SnmpResult) OnmsMonitoringLocation(org.opennms.netmgt.model.monitoringLocations.OnmsMonitoringLocation) AggregateTracker(org.opennms.netmgt.snmp.AggregateTracker)

Example 10 with SnmpResult

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

Aggregations

SnmpResult (org.opennms.netmgt.snmp.SnmpResult)17 SnmpInstId (org.opennms.netmgt.snmp.SnmpInstId)9 Test (org.junit.Test)8 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)8 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)7 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 AttributeGroupType (org.opennms.netmgt.collection.api.AttributeGroupType)4 ServiceParameters (org.opennms.netmgt.collection.api.ServiceParameters)4 MibObject (org.opennms.netmgt.config.datacollection.MibObject)4 MockDataCollectionConfig (org.opennms.netmgt.mock.MockDataCollectionConfig)4 RrdRepository (org.opennms.netmgt.rrd.RrdRepository)4 CollectionResource (org.opennms.netmgt.collection.api.CollectionResource)3 RrdPersistOperationBuilder (org.opennms.netmgt.collection.persistence.rrd.RrdPersistOperationBuilder)3 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)3 File (java.io.File)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 OnmsNode (org.opennms.netmgt.model.OnmsNode)2 AggregateTracker (org.opennms.netmgt.snmp.AggregateTracker)2 Collectable (org.opennms.netmgt.snmp.Collectable)2