Search in sources :

Example 16 with SnmpInstId

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

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

the class PersistRegexSelectorStrategyTest method setUp.

@Before
public void setUp() throws Exception {
    ipInterfaceDao = EasyMock.createMock(IpInterfaceDao.class);
    String localhost = InetAddress.getLocalHost().getHostAddress();
    NetworkBuilder builder = new NetworkBuilder();
    builder.addNode("myNode");
    builder.addInterface(localhost).setIsManaged("M").setIsSnmpPrimary("P");
    OnmsNode node = builder.getCurrentNode();
    node.setId(1);
    OnmsIpInterface ipInterface = node.getIpInterfaces().iterator().next();
    EasyMock.expect(ipInterfaceDao.load(1)).andReturn(ipInterface).anyTimes();
    EasyMock.replay(ipInterfaceDao);
    Package pkg = new Package();
    pkg.setName("junitTestPackage");
    Filter filter = new Filter();
    filter.setContent("IPADDR != '0.0.0.0'");
    pkg.setFilter(filter);
    Service service = new Service();
    service.setName("SNMP");
    pkg.addService(service);
    Map<String, Object> map = new TreeMap<String, Object>();
    List<org.opennms.netmgt.config.collectd.Parameter> params = pkg.getService("SNMP").getParameters();
    for (org.opennms.netmgt.config.collectd.Parameter p : params) {
        map.put(p.getKey(), p.getValue());
    }
    map.put("collection", "default");
    serviceParams = new ServiceParameters(map);
    LocationAwareSnmpClient locationAwareSnmpClient = new LocationAwareSnmpClientRpcImpl(new MockRpcClientFactory());
    PlatformTransactionManager ptm = new MockPlatformTransactionManager();
    SnmpCollectionAgent agent = DefaultSnmpCollectionAgent.create(1, ipInterfaceDao, ptm);
    OnmsSnmpCollection snmpCollection = new OnmsSnmpCollection(agent, serviceParams, new MockDataCollectionConfigDao(), locationAwareSnmpClient);
    org.opennms.netmgt.config.datacollection.ResourceType rt = new org.opennms.netmgt.config.datacollection.ResourceType();
    rt.setName("myResourceType");
    StorageStrategy storageStrategy = new StorageStrategy();
    storageStrategy.setClazz("org.opennms.netmgt.collection.support.IndexStorageStrategy");
    rt.setStorageStrategy(storageStrategy);
    PersistenceSelectorStrategy persistenceSelectorStrategy = new PersistenceSelectorStrategy();
    persistenceSelectorStrategy.setClazz("org.opennms.netmgt.collectd.PersistRegexSelectorStrategy");
    Parameter param = new Parameter();
    param.setKey(PersistRegexSelectorStrategy.MATCH_EXPRESSION);
    param.setValue("#name matches '^agalue.*$'");
    persistenceSelectorStrategy.addParameter(param);
    rt.setPersistenceSelectorStrategy(persistenceSelectorStrategy);
    GenericIndexResourceType resourceType = new GenericIndexResourceType(agent, snmpCollection, rt);
    resourceA = new GenericIndexResource(resourceType, rt.getName(), new SnmpInstId("1.2.3.4.5.6.7.8.9.1.1"));
    AttributeGroupType groupType = new AttributeGroupType("mib2-interfaces", AttributeGroupType.IF_TYPE_ALL);
    MibObject mibObject = new MibObject();
    mibObject.setOid(".1.2.3.4.5.6.7.8.9.2.1");
    mibObject.setInstance("1");
    mibObject.setAlias("name");
    mibObject.setType("string");
    StringAttributeType attributeType = new StringAttributeType(resourceType, snmpCollection.getName(), mibObject, groupType);
    SnmpValue snmpValue = new Snmp4JValueFactory().getOctetString("agalue rules!".getBytes());
    resourceA.setAttributeValue(attributeType, snmpValue);
    resourceB = new GenericIndexResource(resourceType, rt.getName(), new SnmpInstId("1.2.3.4.5.6.7.8.9.1.2"));
}
Also used : StorageStrategy(org.opennms.netmgt.config.datacollection.StorageStrategy) Snmp4JValueFactory(org.opennms.netmgt.snmp.snmp4j.Snmp4JValueFactory) NetworkBuilder(org.opennms.netmgt.model.NetworkBuilder) LocationAwareSnmpClientRpcImpl(org.opennms.netmgt.snmp.proxy.common.LocationAwareSnmpClientRpcImpl) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) MockPlatformTransactionManager(org.opennms.core.test.MockPlatformTransactionManager) MockDataCollectionConfigDao(org.opennms.netmgt.dao.mock.MockDataCollectionConfigDao) OnmsNode(org.opennms.netmgt.model.OnmsNode) Service(org.opennms.netmgt.config.collectd.Service) TreeMap(java.util.TreeMap) MockPlatformTransactionManager(org.opennms.core.test.MockPlatformTransactionManager) PlatformTransactionManager(org.springframework.transaction.PlatformTransactionManager) IpInterfaceDao(org.opennms.netmgt.dao.api.IpInterfaceDao) MockRpcClientFactory(org.opennms.core.rpc.mock.MockRpcClientFactory) LocationAwareSnmpClient(org.opennms.netmgt.snmp.proxy.LocationAwareSnmpClient) SnmpValue(org.opennms.netmgt.snmp.SnmpValue) OnmsIpInterface(org.opennms.netmgt.model.OnmsIpInterface) Filter(org.opennms.netmgt.config.collectd.Filter) AttributeGroupType(org.opennms.netmgt.collection.api.AttributeGroupType) Parameter(org.opennms.netmgt.config.datacollection.Parameter) MibObject(org.opennms.netmgt.config.datacollection.MibObject) Package(org.opennms.netmgt.config.collectd.Package) ServiceParameters(org.opennms.netmgt.collection.api.ServiceParameters) MibObject(org.opennms.netmgt.config.datacollection.MibObject) PersistenceSelectorStrategy(org.opennms.netmgt.config.datacollection.PersistenceSelectorStrategy) Before(org.junit.Before)

Example 18 with SnmpInstId

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

the class CiscoIpSlaDetector method isServiceDetected.

/**
 * {@inheritDoc}
 *
 * Returns true if the protocol defined by this plugin is supported. If
 * the protocol is not supported then a false value is returned to the
 * caller. The qualifier map passed to the method is used by the plugin to
 * return additional information by key-name. These key-value pairs can be
 * added to service events if needed.
 */
@Override
public boolean isServiceDetected(final InetAddress address, final SnmpAgentConfig agentConfig) {
    try {
        configureAgentPTR(agentConfig);
        configureAgentVersion(agentConfig);
        Map<SnmpInstId, SnmpValue> tagResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaDetector", SnmpObjId.get(RTT_ADMIN_TAG_OID));
        if (tagResults == null) {
            LOG.warn("isServiceDetected: No admin tags received!");
            return false;
        }
        Map<SnmpInstId, SnmpValue> operStateResults = SnmpUtils.getOidValues(agentConfig, "CiscoIpSlaDetector", SnmpObjId.get(RTT_OPER_STATE_OID));
        if (operStateResults == null) {
            LOG.warn("isServiceDetected: No operational states received!");
            return false;
        }
        // Iterate over the list of configured IP SLAs
        for (Entry<SnmpInstId, SnmpValue> ipslaEntry : tagResults.entrySet()) {
            SnmpValue status = operStateResults.get(ipslaEntry.getKey());
            LOG.debug("isServiceDetected: admin-tag={} value={} oper-state={}", m_adminTag, formatValue(ipslaEntry.getValue()), status.toInt());
            // Check if a configured IP SLA with specific tag exist and is the operational state active
            if (m_adminTag.equals(formatValue(ipslaEntry.getValue())) && status.toInt() == RTT_MON_OPER_STATE_ACTIVE) {
                LOG.debug("isServiceDetected: admin tag found");
                return true;
            }
        }
    } catch (Throwable t) {
        throw new UndeclaredThrowableException(t);
    }
    return false;
}
Also used : SnmpValue(org.opennms.netmgt.snmp.SnmpValue) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId)

Example 19 with SnmpInstId

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

the class DiskUsageDetector method isServiceDetected.

/**
 * {@inheritDoc}
 *
 * Returns true if the protocol defined by this plugin is supported. If the
 * protocol is not supported then a false value is returned to the caller.
 * The qualifier map passed to the method is used by the plugin to return
 * additional information by key-name. These key-value pairs can be added to
 * service events if needed.
 */
@Override
public boolean isServiceDetected(final InetAddress address, final SnmpAgentConfig agentConfig) {
    int matchType = MATCH_TYPE_EXACT;
    try {
        if (getPort() > 0) {
            agentConfig.setPort(getPort());
        }
        if (getTimeout() > 0) {
            agentConfig.setTimeout(getTimeout());
        }
        if (getRetries() > -1) {
            agentConfig.setRetries(getRetries());
        }
        if (getForceVersion() != null) {
            String version = getForceVersion();
            // @see http://issues.opennms.org/browse/NMS-7518
            if ("v1".equalsIgnoreCase(version) || "snmpv1".equalsIgnoreCase(version)) {
                agentConfig.setVersion(SnmpAgentConfig.VERSION1);
            } else if ("v2".equalsIgnoreCase(version) || "v2c".equalsIgnoreCase(version) || "snmpv2".equalsIgnoreCase(version) || "snmpv2c".equalsIgnoreCase(version)) {
                agentConfig.setVersion(SnmpAgentConfig.VERSION2C);
            } else if ("v3".equalsIgnoreCase(version) || "snmpv3".equalsIgnoreCase(version)) {
                agentConfig.setVersion(SnmpAgentConfig.VERSION3);
            }
        }
        // 
        if (!"".equals(getMatchType())) {
            String matchTypeStr = getMatchType();
            if (matchTypeStr.equalsIgnoreCase("exact")) {
                matchType = MATCH_TYPE_EXACT;
            } else if (matchTypeStr.equalsIgnoreCase("startswith")) {
                matchType = MATCH_TYPE_STARTSWITH;
            } else if (matchTypeStr.equalsIgnoreCase("endswith")) {
                matchType = MATCH_TYPE_ENDSWITH;
            } else if (matchTypeStr.equalsIgnoreCase("regex")) {
                matchType = MATCH_TYPE_REGEX;
            } else {
                throw new RuntimeException("Unknown value '" + matchTypeStr + "' for parameter 'match-type'");
            }
        }
        SnmpObjId hrStorageDescrSnmpObject = SnmpObjId.get(getHrStorageDescr());
        Map<SnmpInstId, SnmpValue> descrResults = SnmpUtils.getOidValues(agentConfig, "DiskUsagePoller", hrStorageDescrSnmpObject);
        if (descrResults.size() == 0) {
            return false;
        }
        for (Map.Entry<SnmpInstId, SnmpValue> e : descrResults.entrySet()) {
            LOG.debug("capsd: SNMPwalk succeeded, addr={} oid={} instance={} value={}", InetAddressUtils.str(agentConfig.getAddress()), hrStorageDescrSnmpObject, e.getKey(), e.getValue());
            if (isMatch(e.getValue().toString(), getDisk(), matchType)) {
                LOG.debug("Found disk '{}' (matching hrStorageDescr was '{}')", getDisk(), e.getValue());
                return true;
            }
        }
        return false;
    } catch (Throwable t) {
        throw new UndeclaredThrowableException(t);
    }
}
Also used : SnmpValue(org.opennms.netmgt.snmp.SnmpValue) UndeclaredThrowableException(java.lang.reflect.UndeclaredThrowableException) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId) SnmpObjId(org.opennms.netmgt.snmp.SnmpObjId) Map(java.util.Map)

Example 20 with SnmpInstId

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

the class HostResourceSWRunDetector method isServiceDetected.

/**
 * {@inheritDoc}
 *
 * Returns true if the protocol defined by this plugin is supported. If the
 * protocol is not supported then a false value is returned to the caller.
 * The qualifier map passed to the method is used by the plugin to return
 * additional information by key-name. These key-value pairs can be added to
 * service events if needed.
 */
@Override
public boolean isServiceDetected(final InetAddress address, final SnmpAgentConfig agentConfig) {
    boolean status = false;
    // Get configuration parameters
    // 
    // This is the string that represents the service name to be monitored.
    String serviceName = getServiceToDetect();
    // set timeout and retries on SNMP peer object
    // 
    configureAgentPTR(agentConfig);
    LOG.debug("capsd: service= SNMP address={}", agentConfig);
    // Establish SNMP session with interface
    // 
    final String hostAddress = InetAddressUtils.str(agentConfig.getAddress());
    try {
        LOG.debug("HostResourceSwRunMonitor.poll: SnmpAgentConfig address: {}", agentConfig);
        if (serviceName == null) {
            LOG.warn("HostResourceSwRunMonitor.poll: No Service Name Defined! ");
            return status;
        }
        // This returns two maps: one of instance and service name, and one of instance and status.
        Map<SnmpInstId, SnmpValue> nameResults = SnmpUtils.getOidValues(agentConfig, "HostResourceSwRunMonitor", SnmpObjId.get(getServiceNameOid()));
        // Iterate over the list of running services
        for (Entry<SnmpInstId, SnmpValue> entry : nameResults.entrySet()) {
            SnmpValue value = entry.getValue();
            // See if the service name is in the list of running services
            if (match(serviceName, StringUtils.stripExtraQuotes(value.toString())) && !status) {
                LOG.debug("poll: HostResourceSwRunMonitor poll succeeded, addr={} service name={} value={}", hostAddress, serviceName, value);
                status = true;
                break;
            }
        }
    } catch (NumberFormatException e) {
        LOG.warn("Number operator used on a non-number {}", e.getMessage());
    } catch (IllegalArgumentException e) {
        LOG.warn("Invalid SNMP Criteria: {}", e.getMessage());
    } catch (Throwable t) {
        LOG.warn("Unexpected exception during SNMP poll of interface {}", hostAddress, t);
    }
    return status;
}
Also used : SnmpValue(org.opennms.netmgt.snmp.SnmpValue) SnmpInstId(org.opennms.netmgt.snmp.SnmpInstId)

Aggregations

SnmpInstId (org.opennms.netmgt.snmp.SnmpInstId)42 SnmpObjId (org.opennms.netmgt.snmp.SnmpObjId)23 SnmpValue (org.opennms.netmgt.snmp.SnmpValue)20 InetAddress (java.net.InetAddress)16 SnmpAgentConfig (org.opennms.netmgt.snmp.SnmpAgentConfig)16 Map (java.util.Map)12 Test (org.junit.Test)11 PollStatus (org.opennms.netmgt.poller.PollStatus)10 ParameterMap (org.opennms.core.utils.ParameterMap)9 SnmpResult (org.opennms.netmgt.snmp.SnmpResult)9 HashMap (java.util.HashMap)8 ArrayList (java.util.ArrayList)7 ServiceParameters (org.opennms.netmgt.collection.api.ServiceParameters)7 MockDataCollectionConfig (org.opennms.netmgt.mock.MockDataCollectionConfig)6 SnmpTrapBuilder (org.opennms.netmgt.snmp.SnmpTrapBuilder)6 GenericIndexResource (org.opennms.netmgt.collectd.GenericIndexResource)5 GenericIndexResourceType (org.opennms.netmgt.collectd.GenericIndexResourceType)5 SnmpCollectionAgent (org.opennms.netmgt.collectd.SnmpCollectionAgent)5 SnmpCollectionResource (org.opennms.netmgt.collectd.SnmpCollectionResource)5 AttributeGroupType (org.opennms.netmgt.collection.api.AttributeGroupType)5