use of org.opennms.netmgt.snmp.SnmpValue in project opennms by OpenNMS.
the class SnmpMonitor method poll.
/**
* {@inheritDoc}
*
* <P>
* The poll() method is responsible for polling the specified address for
* SNMP service availability.
* </P>
* @exception RuntimeException
* Thrown for any unrecoverable errors.
*/
@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
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);
// Get configuration parameters
//
String oid = ParameterMap.getKeyedString(parameters, "oid", DEFAULT_OBJECT_IDENTIFIER);
String operator = ParameterMap.getKeyedString(parameters, "operator", null);
String operand = ParameterMap.getKeyedString(parameters, "operand", null);
String walkstr = ParameterMap.getKeyedString(parameters, "walk", "false");
String matchstr = ParameterMap.getKeyedString(parameters, "match-all", "true");
int countMin = ParameterMap.getKeyedInteger(parameters, "minimum", 0);
int countMax = ParameterMap.getKeyedInteger(parameters, "maximum", 0);
String reasonTemplate = ParameterMap.getKeyedString(parameters, "reason-template", DEFAULT_REASON_TEMPLATE);
String hexstr = ParameterMap.getKeyedString(parameters, "hex", "false");
hex = "true".equalsIgnoreCase(hexstr);
// 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()));
// Squirrel the configuration parameters away in a Properties for later expansion if service is down
Properties svcParams = new Properties();
svcParams.setProperty("oid", oid);
svcParams.setProperty("operator", String.valueOf(operator));
svcParams.setProperty("operand", String.valueOf(operand));
svcParams.setProperty("walk", walkstr);
svcParams.setProperty("matchAll", matchstr);
svcParams.setProperty("minimum", String.valueOf(countMin));
svcParams.setProperty("maximum", String.valueOf(countMax));
svcParams.setProperty("timeout", String.valueOf(agentConfig.getTimeout()));
svcParams.setProperty("retry", String.valueOf(agentConfig.getRetries()));
svcParams.setProperty("retries", svcParams.getProperty("retry"));
svcParams.setProperty("ipaddr", hostAddress);
svcParams.setProperty("port", String.valueOf(agentConfig.getPort()));
svcParams.setProperty("hex", hexstr);
//
try {
TimeoutTracker tracker = new TimeoutTracker(parameters, agentConfig.getRetries(), agentConfig.getTimeout());
tracker.reset();
tracker.startAttempt();
SnmpObjId snmpObjectId = SnmpObjId.get(oid);
// the parameter "matchall" to "count" will act as if "walk" has been set to "true".
if ("count".equals(matchstr)) {
if (DEFAULT_REASON_TEMPLATE.equals(reasonTemplate)) {
reasonTemplate = "Value: ${matchCount} outside of range Min: ${minimum} to Max: ${maximum}";
}
int matchCount = 0;
List<SnmpValue> results = SnmpUtils.getColumns(agentConfig, "snmpPoller", snmpObjectId);
for (SnmpValue result : results) {
if (result != null) {
LOG.debug("poll: SNMPwalk poll succeeded, addr={} oid={} value={}", hostAddress, oid, result);
if (meetsCriteria(result, operator, operand)) {
matchCount++;
}
}
}
svcParams.setProperty("matchCount", String.valueOf(matchCount));
LOG.debug("poll: SNMPwalk count succeeded, total={} min={} max={}", matchCount, countMin, countMax);
if ((countMin <= matchCount) && (matchCount <= countMax)) {
status = PollStatus.available(tracker.elapsedTimeInMillis());
} else {
String reason = PropertiesUtils.substitute(reasonTemplate, svcParams);
LOG.debug(reason);
status = PollStatus.unavailable(reason);
return status;
}
} else if ("true".equals(walkstr)) {
if (DEFAULT_REASON_TEMPLATE.equals(reasonTemplate)) {
reasonTemplate = "SNMP poll failed, addr=${ipaddr} oid=${oid}";
}
List<SnmpValue> results = SnmpUtils.getColumns(agentConfig, "snmpPoller", snmpObjectId);
for (SnmpValue result : results) {
if (result != null) {
svcParams.setProperty("observedValue", getStringValue(result));
if (meetsCriteria(result, operator, operand)) {
status = PollStatus.available(tracker.elapsedTimeInMillis());
if ("false".equals(matchstr)) {
return status;
}
} else if ("true".equals(matchstr)) {
String reason = PropertiesUtils.substitute(reasonTemplate, svcParams);
LOG.debug(reason);
status = PollStatus.unavailable(reason);
return status;
}
}
}
} else {
if (DEFAULT_REASON_TEMPLATE.equals(reasonTemplate)) {
if (operator != null) {
reasonTemplate = "Observed value '${observedValue}' does not meet criteria '${operator} ${operand}'";
} else {
reasonTemplate = "Observed value '${observedValue}' was null";
}
}
SnmpValue result = SnmpUtils.get(agentConfig, snmpObjectId);
if (result != null) {
svcParams.setProperty("observedValue", getStringValue(result));
LOG.debug("poll: SNMP poll succeeded, addr={} oid={} value={}", hostAddress, oid, result);
if (meetsCriteria(result, operator, operand)) {
status = PollStatus.available(tracker.elapsedTimeInMillis());
} else {
status = PollStatus.unavailable(PropertiesUtils.substitute(reasonTemplate, svcParams));
}
} else {
String reason = "SNMP poll failed, addr=" + hostAddress + " oid=" + oid;
LOG.debug(reason);
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);
}
return status;
}
use of org.opennms.netmgt.snmp.SnmpValue 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;
}
use of org.opennms.netmgt.snmp.SnmpValue in project opennms by OpenNMS.
the class TrapUtils method getTrapData.
/**
* Gets the trap identity.
*
* @param trapNotification the trap notification
* @return the identity
*/
public static TrapData getTrapData(TrapInformation trapNotification) {
if (trapNotification instanceof Snmp4JV1TrapInformation) {
Snmp4JV1TrapInformation info = (Snmp4JV1TrapInformation) trapNotification;
TrapIdentity identity = info.getTrapIdentity();
TrapData data = new TrapData(identity.getEnterpriseId(), identity.getGeneric(), identity.getSpecific());
for (int i = 0; i < info.getPduLength(); i++) {
VariableBinding v = info.getVarBindAt(i);
SnmpValue value = new Snmp4JValue(v.getVariable());
data.addParameter("." + v.getOid().toString(), value.toDisplayString());
}
return data;
} else if (trapNotification instanceof Snmp4JV2TrapInformation) {
Snmp4JV2TrapInformation info = (Snmp4JV2TrapInformation) trapNotification;
TrapIdentity identity = info.getTrapIdentity();
TrapData data = new TrapData(identity.getEnterpriseId(), identity.getGeneric(), identity.getSpecific());
for (int i = 0; i < info.getPduLength(); i++) {
VariableBinding v = info.getVarBindAt(i);
SnmpValue value = new Snmp4JValue(v.getVariable());
data.addParameter("." + v.getOid().toString(), value.toDisplayString());
}
return data;
}
return null;
}
use of org.opennms.netmgt.snmp.SnmpValue in project opennms by OpenNMS.
the class EntityPhysicalTableRow method getOnmsHwEntity.
/**
* Gets the hardware entity.
*
* @param vendorAttributes the vendor attributes
* @param replacementMap the replacement map
* @return the hardware entity
*/
public OnmsHwEntity getOnmsHwEntity(Map<SnmpObjId, HwEntityAttributeType> vendorAttributes, Map<String, String> replacementMap) {
SnmpValue v = null;
final OnmsHwEntity entity = new OnmsHwEntity();
entity.setEntPhysicalIndex(getEntPhysicalIndex());
entity.setEntPhysicalClass(getEntPhysicalClass());
v = getValue(entPhysicalDescr);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalDescr(v.toDisplayString().trim());
v = getValue(entPhysicalVendorType);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalVendorType(v.toDisplayString().trim());
v = getValue(entPhysicalContainedIn);
if (v != null)
entity.setEntPhysicalContainedIn(v.toInt());
v = getValue(entPhysicalParentRelPos);
if (v != null)
entity.setEntPhysicalParentRelPos(v.toInt());
v = getValue(entPhysicalName);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalName(v.toDisplayString().trim().trim());
v = getValue(entPhysicalHardwareRev);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalHardwareRev(v.toDisplayString().trim());
v = getValue(entPhysicalFirmwareRev);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalFirmwareRev(v.toDisplayString().trim());
v = getValue(entPhysicalSoftwareRev);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalSoftwareRev(v.toDisplayString().trim());
v = getValue(entPhysicalSerialNum);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalSerialNum(v.toDisplayString().trim());
v = getValue(entPhysicalMfgName);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalMfgName(v.toDisplayString().trim());
v = getValue(entPhysicalModelName);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalModelName(v.toDisplayString().trim());
v = getValue(entPhysicalAlias);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalAlias(v.toDisplayString().trim());
v = getValue(entPhysicalAssetID);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalAssetID(v.toDisplayString().trim());
v = getValue(entPhysicalIsFRU);
if (v != null)
entity.setEntPhysicalIsFRU(v.toInt() == 1 ? true : false);
v = getValue(entPhysicalUris);
if (v != null && !v.toDisplayString().trim().isEmpty())
entity.setEntPhysicalUris(v.toDisplayString());
if (vendorAttributes != null && vendorAttributes.size() > 0) {
BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(entity);
for (Map.Entry<SnmpObjId, HwEntityAttributeType> entry : vendorAttributes.entrySet()) {
v = getValue(entry.getKey());
if (v != null && !v.toDisplayString().trim().isEmpty()) {
String typeName = entry.getValue().getName();
if (replacementMap.containsKey(typeName)) {
String property = replacementMap.get(typeName);
if (wrapper.isWritableProperty(property)) {
wrapper.setPropertyValue(property, v.toDisplayString().trim());
}
} else {
entity.addAttribute(entry.getValue(), v.toDisplayString().trim());
}
}
}
}
return entity;
}
use of org.opennms.netmgt.snmp.SnmpValue in project opennms by OpenNMS.
the class SyntaxToEventTest method testProcessSyntaxWithTerminatingNull.
/**
* We are allowing NULL in the last position of the string in case there
* are any SNMP agents sending OctetString values in this format.
*
* @see SnmpUtils#allBytesDisplayable()
*/
@Test
public void testProcessSyntaxWithTerminatingNull() {
SnmpValueFactory valueFactory = SnmpUtils.getValueFactory();
assertNotNull(valueFactory);
byte[] macAddr = { 0x55, 0x55, 0x55, 0x55, 0x55, 0x00 };
SnmpValue octetString = valueFactory.getOctetString(macAddr);
Parm parm = SyntaxToEvent.processSyntax("Test", octetString);
assertEquals("Test", parm.getParmName());
assertEquals(EventConstants.XML_ENCODING_TEXT, parm.getValue().getEncoding());
// I'm not sure what is converting the NULL char to a "."...
assertEquals("UUUUU.", parm.getValue().getContent());
}
Aggregations