/** run */ @Override public void run() { if (polling()) { log().debug("run: polling Selta STED on primary address: " + getIpaddress()); boolean pollhierarchy = true; SnmpValue lastCommit = SnmpUtils.get(getAgentConfig(), SnmpObjId.get(SeltaMibCommon.OID_S_lastCommit)); if (lastCommit != null) { String lastCommitString = SeltaUtils.ConvertDateToString(lastCommit.getBytes()); if (getLastCommit() == null || !getLastCommit().equals(lastCommitString)) { log().info("lastCommit changed from " + getLastCommit() + " to " + lastCommitString); setLastCommit(lastCommitString); storeProperty("nePrimaryIP", getIpaddress().toString()); createInventory(); savePropertiesFile("STED properties"); pollhierarchy = false; } } SnmpValue lastAlarm = SnmpUtils.get(getAgentConfig(), SnmpObjId.get(SeltaMibCommon.OID_S_lastAlarm)); if (lastAlarm != null) { String lastAlarmString = SeltaUtils.ConvertDateToString(lastAlarm.getBytes()); if (getLastAlarm() == null || !getLastAlarm().equals(lastAlarmString)) { log().info("lastAlarm changed from " + getLastAlarm() + " to " + lastAlarmString); setLastAlarm(lastAlarmString); poll(pollhierarchy); savePropertiesFile("STED properties"); } } } else { log().info("not polling: " + getIpaddress()); } }
/** * Stops the currently running service. If the service is not running then the command is silently * discarded. */ public synchronized void onStop() { m_status = STOP_PENDING; // shutdown and wait on the background processing thread to exit. LogUtils.debugf(this, "stop: closing communication paths."); try { if (m_registeredForTraps) { LogUtils.debugf(this, "stop: Closing SNMP trap session."); SnmpUtils.unregisterForTraps(this, getInetAddress(), getSnmpTrapPort()); LogUtils.debugf(this, "stop: SNMP trap session closed."); } else { LogUtils.debugf( this, "stop: not attemping to closing SNMP trap session--it was never opened"); } } catch (final IOException e) { LogUtils.warnf(this, e, "stop: exception occurred closing session"); } catch (final IllegalStateException e) { LogUtils.debugf(this, e, "stop: The SNMP session was already closed"); } LogUtils.debugf(this, "stop: Stopping queue processor."); m_processor.stop(); m_eventReader.close(); m_status = STOPPED; LogUtils.debugf(this, "stop: Trapd stopped"); }
@Test(expected = EndPointStatusException.class) @JUnitSnmpAgent(host = "192.168.255.10", resource = "classpath:/airPairR3_walk.properties") public void dwoTestLinkMonitorAirPair3DownLossOfSignal() throws UnknownHostException, EndPointStatusException { SnmpUtils.set( getAgentConfig("192.168.255.10"), SnmpObjId.get(AIR_PAIR_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(2)); SnmpUtils.set( getAgentConfig("192.168.255.10"), SnmpObjId.get(AIR_PAIR_R3_DUPLEX_MISMATCH), SnmpUtils.getValueFactory().getCounter32(1)); EndPointImpl endPoint = getEndPoint(AIR_PAIR_R3_SYS_OID, "192.168.255.10"); m_configDao.getValidator().validate(endPoint); }
/** * getValue * * @param agentConfig a {@link org.opennms.netmgt.snmp.SnmpAgentConfig} object. * @param oid a {@link java.lang.String} object. * @return a {@link java.lang.String} object. */ protected String getValue(SnmpAgentConfig agentConfig, String oid) { SnmpValue val = SnmpUtils.get(agentConfig, SnmpObjId.get(oid)); if (val == null || val.isNull() || val.isEndOfMib() || val.isError()) { return null; } else { return val.toString(); } }
@Test(expected = EndPointStatusException.class) @JUnitSnmpAgent(host = "192.168.254.10", resource = "/horizon_duo_walk.properties") public void dwoTestLinkMonitorHorizonDuoCapacity3DownModemLossSignal() throws UnknownHostException, EndPointStatusException { SnmpUtils.set( getAgentConfig("192.168.254.10"), SnmpObjId.get(HORIZON_DUO_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(2)); SnmpUtils.set( getAgentConfig("192.168.254.10"), SnmpObjId.get(HORIZON_DUO_SYSTEM_CAPACITY), SnmpUtils.getValueFactory().getCounter32(3)); EndPoint endPoint = getEndPoint(HORIZON_DUO_SYS_OID, "192.168.254.10"); m_configDao.getValidator().validate(endPoint); }
@Test(expected = EndPointStatusException.class) @JUnitSnmpAgent(host = "192.168.255.31", resource = "/horizon_compact_walk.properties") public void dwoTestLinkMonitorHorizonCompactDownEthernetLinkDown() throws EndPointStatusException, UnknownHostException { SnmpUtils.set( getAgentConfig("192.168.255.31"), SnmpObjId.get(HORIZON_COMPACT_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(1)); SnmpUtils.set( getAgentConfig("192.168.255.31"), SnmpObjId.get(HORIZON_COMPACT_ETHERNET_LINK_DOWN), SnmpUtils.getValueFactory().getCounter32(2)); EndPoint endPoint = getEndPoint(HORIZON_COMPACT_SYS_OID, "192.168.255.31"); m_configDao.getValidator().validate(endPoint); }
/** * Create an SNMP V3 trap with the specified trap object ID, and sysUpTime value. * * @param trapOid The trap object id. * @param sysUpTime The system up time. * @return The newly-created trap. * @exception Throws SnmpTrapHelperException if the trap cannot be created for any reason. * @throws org.opennms.netmgt.scriptd.helper.SnmpTrapHelperException if any. */ public SnmpV3TrapBuilder createV3Inform(String trapOid, String sysUpTime) throws SnmpTrapHelperException { SnmpV3TrapBuilder packet = SnmpUtils.getV3InformBuilder(); addVarBinding(packet, SNMP_SYSUPTIME_OID, EventConstants.TYPE_SNMP_TIMETICKS, sysUpTime); addVarBinding(packet, SNMP_TRAP_OID, EventConstants.TYPE_SNMP_OBJECT_IDENTIFIER, trapOid); return packet; }
private void walkTable( final BatchTask currentPhase, final Set<InetAddress> provisionedIps, final TableTracker tracker) { final OnmsNode node = getNode(); LOG.info( "detecting IP interfaces for node {}/{}/{} using table tracker {}", node.getId(), node.getForeignSource(), node.getForeignId(), tracker); if (isAborted()) { LOG.debug("'{}' is marked as aborted; skipping scan of table {}", currentPhase, tracker); } else { Assert.notNull(getAgentConfigFactory(), "agentConfigFactory was not injected"); final SnmpAgentConfig agentConfig = getAgentConfigFactory().getAgentConfig(getAgentAddress()); final SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "IP address tables", tracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { abort("Aborting node scan : Agent timed out while scanning the IP address tables"); } else if (walker.failed()) { abort( "Aborting node scan : Agent failed while scanning the IP address tables : " + walker.getErrorMessage()); } else { // After processing the SNMP provided interfaces then we need to scan any that // were provisioned but missing from the ip table for (final InetAddress ipAddr : provisionedIps) { final OnmsIpInterface iface = node.getIpInterfaceByIpAddress(ipAddr); if (iface != null) { iface.setIpLastCapsdPoll(getScanStamp()); iface.setIsManaged("M"); currentPhase.add(ipUpdater(currentPhase, iface), "write"); } } LOG.debug("Finished phase {}", currentPhase); } } catch (final InterruptedException e) { abort("Aborting node scan : Scan thread failed while waiting for the IP address tables"); } } }
/** * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as * an SnmpObjectId. The value is assumed to have been encoded with the specified encoding (only * XML_ENCODING_TEXT is supported). * * @param name The name (a.k.a. "id") of the variable binding to be created * @param encoding Describes the way in which the value content has been encoded (i.e. * XML_ENCODING_TEXT, or XML_ENCODING_BASE64) * @param value The variable binding value * @return The newly-created variable binding * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any * reason (e.g. encoding not supported, invalid value, etc.). */ @Override public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) throws SnmpTrapHelperException { if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) { trap.addVarBind( SnmpObjId.get(name), SnmpUtils.getValueFactory().getObjectId(SnmpObjId.get(value))); } else { throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpObjectId"); } }
/** * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as * an SnmpOpaque. The value is assumed to have been encoded with the specified encoding (only * XML_ENCODING_BASE64 is supported). * * @param name The name (a.k.a. "id") of the variable binding to be created * @param encoding Describes the way in which the value content has been encoded (i.e. * XML_ENCODING_TEXT, or XML_ENCODING_BASE64) * @param value The variable binding value * @return The newly-created variable binding * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any * reason (e.g. encoding not supported, invalid value, etc.). */ @Override public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) throws SnmpTrapHelperException { if (EventConstants.XML_ENCODING_BASE64.equals(encoding)) { trap.addVarBind( SnmpObjId.get(name), SnmpUtils.getValueFactory().getOpaque(Base64.decodeBase64(value.toCharArray()))); } else { throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpOpaque"); } }
@Test @Ignore @JUnitSnmpAgent(host = "192.168.255.20", resource = "/airPairR4_walk.properties") public void dwoTestLinkMonitorAirPairR4() throws UnknownHostException { SnmpUtils.set( getAgentConfig("192.168.255.20"), SnmpObjId.get(AIR_PAIR_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(1)); SnmpUtils.set( getAgentConfig("192.168.255.20"), SnmpObjId.get(AIR_PAIR_R4_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(1)); EndPointImpl endPoint = getEndPoint(AIR_PAIR_R4_SYS_OID, "192.168.255.20"); try { m_configDao.getValidator().validate(endPoint); } catch (EndPointStatusException e) { assertTrue("An EndPointStatusException was caught resulting in a failed test", false); } }
@Test @JUnitSnmpAgent(host = "192.168.255.10", resource = "classpath:/airPairR3_walk.properties") public void dwoTestLinkMonitorAirPairR3() throws UnknownHostException { SnmpUtils.set( getAgentConfig("192.168.255.10"), SnmpObjId.get(AIR_PAIR_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(1)); SnmpUtils.set( getAgentConfig("192.168.255.10"), SnmpObjId.get(AIR_PAIR_R3_DUPLEX_MISMATCH), SnmpUtils.getValueFactory().getCounter32(1)); EndPointImpl endPoint = getEndPoint(AIR_PAIR_R3_SYS_OID, "192.168.255.10"); EndPointTypeValidator validator = m_configDao.getValidator(); try { validator.validate(endPoint); } catch (EndPointStatusException e) { assertTrue(false); } }
/** * Create an SNMP V1 trap with the specified enterprise IS, agent address, generic ID, specific * ID, and time stamp. * * @param entId The enterprise ID for the trap. * @param agentAddr The agent address for the trap. * @param generic The generic ID for the trap. * @param specific The specific ID for the trap. * @param timeStamp The time stamp for the trap. * @return The newly-created trap. * @throws java.net.UnknownHostException if any. */ public SnmpV1TrapBuilder createV1Trap( String entId, String agentAddr, int generic, int specific, long timeStamp) throws UnknownHostException { SnmpV1TrapBuilder trap = SnmpUtils.getV1TrapBuilder(); trap.setEnterprise(SnmpObjId.get(entId)); trap.setAgentAddress(InetAddressUtils.addr(agentAddr)); trap.setGeneric(generic); trap.setSpecific(specific); trap.setTimeStamp(timeStamp); return trap; }
@Test @JUnitSnmpAgent(host = "192.168.255.31", resource = "/horizon_compact_walk.properties") public void dwoTestLinkMonitorHorizonCompact() throws UnknownHostException { SnmpUtils.set( getAgentConfig("192.168.255.31"), SnmpObjId.get(HORIZON_COMPACT_MODEM_LOSS_OF_SIGNAL), SnmpUtils.getValueFactory().getCounter32(1)); SnmpUtils.set( getAgentConfig("192.168.255.31"), SnmpObjId.get(HORIZON_COMPACT_ETHERNET_LINK_DOWN), SnmpUtils.getValueFactory().getCounter32(1)); EndPointImpl endPoint = getEndPoint(HORIZON_COMPACT_SYS_OID, "192.168.255.31"); try { m_configDao.getValidator().validate(endPoint); } catch (Throwable e) { assertTrue( "An EndPointStatusException was thrown which shouldn't have and thats why the test failed", false); } }
/** onInit */ public synchronized void onInit() { Assert.state(m_trapdIpMgr != null, "trapdIpMgr must be set"); Assert.state(m_eventReader != null, "eventReader must be set"); Assert.state(m_backlogQ != null, "backlogQ must be set"); Assert.state(m_snmpTrapAddress != null, "snmpTrapAddress must be set"); Assert.state(m_snmpTrapPort != null, "snmpTrapPort must be set"); Assert.state(m_processor != null, "processor must be set"); try { m_trapdIpMgr.dataSourceSync(); } catch (final SQLException e) { LogUtils.errorf(this, e, "init: Failed to load known IP address list"); throw new UndeclaredThrowableException(e); } try { InetAddress address = getInetAddress(); LogUtils.infof( this, "Listening on %s:%d", address == null ? "[all interfaces]" : InetAddressUtils.str(address), getSnmpTrapPort()); SnmpUtils.registerForTraps(this, this, address, getSnmpTrapPort(), getSnmpV3Users()); m_registeredForTraps = true; LogUtils.debugf(this, "init: Creating the trap session"); } catch (final IOException e) { if (e instanceof java.net.BindException) { managerLog() .error( "init: Failed to listen on SNMP trap port, perhaps something else is already listening?", e); LogUtils.errorf( this, e, "init: Failed to listen on SNMP trap port, perhaps something else is already listening?"); } else { LogUtils.errorf(this, e, "init: Failed to initialize SNMP trap socket"); } throw new UndeclaredThrowableException(e); } try { m_eventReader.open(); } catch (final Throwable e) { LogUtils.errorf(this, e, "init: Failed to open event reader"); throw new UndeclaredThrowableException(e); } }
/** * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as * an SnmpIPAddress. The value is assumed to have been encoded with the specified encoding (only * XML_ENCODING_TEXT is supported). * * @param name The name (a.k.a. "id") of the variable binding to be created * @param encoding Describes the way in which the value content has been encoded (i.e. * XML_ENCODING_TEXT, or XML_ENCODING_BASE64) * @param value The variable binding value * @return The newly-created variable binding * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any * reason (e.g. encoding not supported, invalid value, etc.). */ @Override public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) throws SnmpTrapHelperException { if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) { final InetAddress addr = InetAddressUtils.addr(value); if (addr == null) { throw new SnmpTrapHelperException( "Value " + value + "is invalid, or host unknown for SnmpIPAddress"); } trap.addVarBind(SnmpObjId.get(name), SnmpUtils.getValueFactory().getIpAddress(addr)); } else { throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpIPAddress"); } }
/** * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as * an SnmpOctetString. The value is assumed to have been encoded with the specified encoding * (i.e. XML_ENCODING_TEXT, XML_ENCODING_BASE64, or XML_ENCODING_MAC_ADDRESS). * * @param name The name (a.k.a. "id") of the variable binding to be created * @param encoding Describes the way in which the value content has been encoded (i.e. * XML_ENCODING_TEXT, XML_ENCODING_BASE64, or XML_ENCODING_MAC_ADDRESS) * @param value The variable binding value * @return The newly-created variable binding * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any * reason (e.g. encoding not supported, invalid value, etc.). */ @Override public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) throws SnmpTrapHelperException { byte[] contents; if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) { contents = value.getBytes(); } else if (EventConstants.XML_ENCODING_BASE64.equals(encoding)) { contents = Base64.decodeBase64(value.toCharArray()); } else if (EventConstants.XML_ENCODING_MAC_ADDRESS.equals(encoding)) { contents = InetAddressUtils.macAddressStringToBytes(value); } else { throw new SnmpTrapHelperException( "Encoding " + encoding + "is invalid for SnmpOctetString"); } trap.addVarBind(SnmpObjId.get(name), SnmpUtils.getValueFactory().getOctetString(contents)); }
/** * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as * an SnmpCounter64. The value is assumed to have been encoded with the specified encoding (only * XML_ENCODING_TEXT is supported). * * @param name The name (a.k.a. "id") of the variable binding to be created * @param encoding Describes the way in which the value content has been encoded (i.e. * XML_ENCODING_TEXT, or XML_ENCODING_BASE64) * @param value The variable binding value * @return The newly-created variable binding * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any * reason (e.g. encoding not supported, invalid value, etc.). */ @Override public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) throws SnmpTrapHelperException { if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) { try { trap.addVarBind( SnmpObjId.get(name), SnmpUtils.getValueFactory().getCounter64(new BigInteger(value))); } catch (IllegalArgumentException e) { throw new SnmpTrapHelperException("Value " + value + "is invalid for SnmpCounter64"); } catch (NullPointerException e) { throw new SnmpTrapHelperException("Value is null for SnmpCounter64"); } } else { throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpCounter64"); } }
protected void runCollection() { final Date now = new Date(); LOG.debug("run: collecting : {}", getPeer()); IpNetToMediaTableTracker ipNetToMediaTableTracker = new IpNetToMediaTableTracker() { public void processIpNetToMediaRow(final IpNetToMediaRow row) { IpNetToMedia macep = row.getIpNetToMedia(); if (macep.getIpNetToMediaType() == IpNetToMediaType.IPNETTOMEDIA_TYPE_DYNAMIC || macep.getIpNetToMediaType() == IpNetToMediaType.IPNETTOMEDIA_TYPE_STATIC) m_linkd.getQueryManager().store(getNodeId(), macep); } }; String trackerName = "ipNetToMedia"; SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, ipNetToMediaTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info( "run:Aborting IpNetToMedia Linkd node scan : Agent timed out while scanning the {} table", trackerName); return; } else if (walker.failed()) { LOG.info( "run:Aborting IpNetToMedia Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return; } } catch (final InterruptedException e) { LOG.error("run: collection interrupted, exiting", e); return; } m_linkd.getQueryManager().reconcileIpNetToMedia(getNodeId(), now); }
@Test public void testAgent() throws Exception { SnmpValue snmpValue = SnmpUtils.get(snmpAgentConfig, SnmpObjId.get(".1.3.6.1.2.1.1.1.0")); Assert.assertEquals("Mock Juniper TCA Device", snmpValue.toDisplayString()); }
protected void runCollection() { final Date now = new Date(); String trackerName = "isisSysObjectCollection"; final IsisSysObjectGroupTracker isisSysObject = new IsisSysObjectGroupTracker(); LOG.info("run: collecting {} on: {}", trackerName, str(getTarget())); SnmpWalker walker = SnmpUtils.createWalker(getPeer(), trackerName, isisSysObject); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info( "run:Aborting Is-Is Linkd node scan : Agent timed out while scanning the {} table", trackerName); return; } else if (walker.failed()) { LOG.info( "run:Aborting Is-Is Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return; } } catch (final InterruptedException e) { LOG.error("run: Is-Is Linkd node collection interrupted, exiting", e); return; } if (isisSysObject.getIsisSysId() == null) { LOG.info("Is-Is mib not supported on: {}", str(getPeer().getAddress())); return; } m_linkd.getQueryManager().store(getNodeId(), isisSysObject.getIsisElement()); final List<IsIsLink> links = new ArrayList<IsIsLink>(); trackerName = "isisISAdjTable"; final IsisISAdjTableTracker isisISAdjTableTracker = new IsisISAdjTableTracker() { @Override public void processIsisAdjRow(IsIsAdjRow row) { links.add(row.getIsisLink()); } }; LOG.info("run: collecting {} on: {}", trackerName, str(getTarget())); walker = SnmpUtils.createWalker(getPeer(), trackerName, isisISAdjTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info( "run:Aborting Is-Is Linkd node scan : Agent timed out while scanning the {} table", trackerName); return; } else if (walker.failed()) { LOG.info( "run:Aborting Is-Is Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return; } } catch (final InterruptedException e) { LOG.error("run: Is-Is Linkd node collection interrupted, exiting", e); return; } trackerName = "isisCircTable"; final IsisCircTableTracker isisCircTableTracker = new IsisCircTableTracker() { @Override public void processIsisCircRow(IsIsCircRow row) { IsIsLink link = row.getIsisLink(); for (IsIsLink adjlink : links) { if (link.getIsisCircIndex().intValue() == adjlink.getIsisCircIndex().intValue()) { adjlink.setIsisCircIfIndex(link.getIsisCircIfIndex()); adjlink.setIsisCircAdminState(link.getIsisCircAdminState()); } } } }; LOG.info("run: collecting {} on: {}", trackerName, str(getTarget())); walker = SnmpUtils.createWalker(getPeer(), trackerName, isisCircTableTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { LOG.info( "run:Aborting Is-Is Linkd node scan : Agent timed out while scanning the {} table", trackerName); return; } else if (walker.failed()) { LOG.info( "run:Aborting Is-Is Linkd node scan : Agent failed while scanning the {} table: {}", trackerName, walker.getErrorMessage()); return; } } catch (final InterruptedException e) { LOG.error("run: Is-Is Linkd node collection interrupted, exiting", e); return; } for (IsIsLink link : links) m_linkd.getQueryManager().store(getNodeId(), link); m_linkd.getQueryManager().reconcileIsis(getNodeId(), now); }
private static String fetchSnmpAssetString( final SnmpAgentConfig agentConfig, final MibObjs mibObjs, final String formatString) throws MissingFormatArgumentException { final List<String> aliases = new ArrayList<String>(); final List<SnmpObjId> objs = new ArrayList<SnmpObjId>(); for (final MibObj mibobj : mibObjs.getMibObj()) { aliases.add(mibobj.getAlias()); objs.add(SnmpObjId.get(mibobj.getOid())); } // Fetch the values from the SNMP agent final SnmpValue[] values = SnmpUtils.get(agentConfig, objs.toArray(new SnmpObjId[0])); if (values.length == aliases.size()) { final Properties substitutions = new Properties(); boolean foundAValue = false; for (int i = 0; i < values.length; i++) { // If the value is a NO_SUCH_OBJECT or NO_SUCH_INSTANCE error, then skip it if (values[i] == null || values[i].isError()) { // No value for this OID continue; } foundAValue = true; // Use trapd's SyntaxToEvent parser so that we format base64 // and MAC address values appropriately Parm parm = SyntaxToEvent.processSyntax(aliases.get(i), values[i]); substitutions.setProperty(aliases.get(i), parm.getValue().getContent()); } if (!foundAValue) { if (log().isDebugEnabled()) { log() .debug( "fetchSnmpAssetString: Failed to fetch any SNMP values for system " + agentConfig.toString()); } throw new MissingFormatArgumentException( "fetchSnmpAssetString: Failed to fetch any SNMP values for system " + agentConfig.toString()); } else { log() .debug( "fetchSnmpAssetString: Fetched asset properties from SNMP agent:\n" + formatPropertiesAsString(substitutions)); } if (objs.size() != substitutions.size()) { log() .warn( "fetchSnmpAssetString: Unexpected number of properties returned from SNMP GET:\n" + formatPropertiesAsString(substitutions)); } return PropertiesUtils.substitute(formatString, substitutions); } else { log() .warn( "fetchSnmpAssetString: Invalid number of SNMP parameters returned: " + values.length + " != " + aliases.size()); throw new MissingFormatArgumentException( "fetchSnmpAssetString: Invalid number of SNMP parameters returned: " + values.length + " != " + aliases.size()); } }
/** * Create an SNMP V2 trap, based on the content of the specified event, and forward the trap to * the specified address and port. It is assumed that the specified event represents an SNMP V1 or * V2 trap that was received by OpenNMS (TrapD). * * @param event The event upon which the trap content should be based * @param destAddr The address to which the trap should be forwarded * @param destPort The port to which the trap should be forwarded * @exception Throws SnmpTrapHelperException if the variable binding cannot be added to the trap * for any reason. * @throws org.opennms.netmgt.scriptd.helper.SnmpTrapHelperException if any. */ public void forwardV2Trap(Event event, String destAddr, int destPort) throws SnmpTrapHelperException { // the event must correspond to an SNMP trap Snmp snmpInfo = event.getSnmp(); if (snmpInfo == null) { throw new SnmpTrapHelperException( "Cannot forward an event with no SNMP info: " + event.getUei()); } // check the version of the original trap String version = snmpInfo.getVersion(); SnmpTrapBuilder packet = SnmpUtils.getV2TrapBuilder(); if ("v1".equals(version)) { // converting V1 trap to V2 (see RFC2576) addVarBinding( packet, SNMP_SYSUPTIME_OID, EventConstants.TYPE_SNMP_TIMETICKS, Long.toString(snmpInfo.getTimeStamp())); String oid; if (snmpInfo.getGeneric() == ENTERPRISE_SPECIFIC && snmpInfo.hasSpecific()) { oid = snmpInfo.getId() + ".0." + snmpInfo.getSpecific(); } else { oid = SNMP_TRAPS + '.' + (snmpInfo.getGeneric() + 1); } addVarBinding(packet, SNMP_TRAP_OID, EventConstants.TYPE_SNMP_OBJECT_IDENTIFIER, oid); // add the V1 var bindings boolean addrPresent = false; boolean communityPresent = false; boolean enterprisePresent = false; int i = 0; for (Parm parm : event.getParmCollection()) { Value value = parm.getValue(); try { addVarBinding( packet, parm.getParmName(), value.getType(), value.getEncoding(), value.getContent()); } catch (SnmpTrapHelperException e) { throw new SnmpTrapHelperException(e.getMessage() + " in event parm[" + i + "]"); } if (SNMP_TRAP_ADDRESS_OID.equals(parm.getParmName())) { addrPresent = true; } else if (SNMP_TRAP_COMMUNITY_OID.equals(parm.getParmName())) { communityPresent = true; } else if (SNMP_TRAP_ENTERPRISE_OID.equals(parm.getParmName())) { enterprisePresent = true; } i++; } if (!addrPresent) { addVarBinding( packet, SNMP_TRAP_ADDRESS_OID, EventConstants.TYPE_SNMP_IPADDRESS, event.getSnmphost()); } if (!communityPresent) { addVarBinding( packet, SNMP_TRAP_COMMUNITY_OID, EventConstants.TYPE_SNMP_OCTET_STRING, snmpInfo.getCommunity()); } if (!enterprisePresent) { addVarBinding( packet, SNMP_TRAP_ENTERPRISE_OID, EventConstants.TYPE_SNMP_OBJECT_IDENTIFIER, snmpInfo.getId()); } } else if ("v2".equals(version)) { addVarBinding( packet, SNMP_SYSUPTIME_OID, EventConstants.TYPE_SNMP_TIMETICKS, Long.toString(snmpInfo.getTimeStamp())); String oid; if (snmpInfo.getGeneric() == ENTERPRISE_SPECIFIC) { oid = snmpInfo.getId() + "." + snmpInfo.getSpecific(); } else { oid = SNMP_TRAPS + '.' + (snmpInfo.getGeneric() + 1); } addVarBinding(packet, SNMP_TRAP_OID, EventConstants.TYPE_SNMP_OBJECT_IDENTIFIER, oid); int i = 0; for (Parm parm : event.getParmCollection()) { Value value = parm.getValue(); try { addVarBinding( packet, parm.getParmName(), value.getType(), value.getEncoding(), value.getContent()); } catch (SnmpTrapHelperException e) { throw new SnmpTrapHelperException(e.getMessage() + " in event parm[" + i + "]"); } i++; } } else { throw new SnmpTrapHelperException("Invalid SNMP version: " + version); } // send the trap sendTrap(destAddr, destPort, snmpInfo.getCommunity(), packet); }
/** * Create an SNMP V1 trap, based on the content of the specified event, and forward the trap to * the specified address and port. It is assumed that the specified event represents an SNMP V1 or * V2 trap that was received by OpenNMS (TrapD). * * @param event The event upon which the trap content should be based * @param destAddr The address to which the trap should be forwarded * @param destPort The port to which the trap should be forwarded * @exception Throws SnmpTrapHelperException if the variable binding cannot be added to the trap * for any reason. * @throws org.opennms.netmgt.scriptd.helper.SnmpTrapHelperException if any. */ public void forwardV1Trap(Event event, String destAddr, int destPort) throws SnmpTrapHelperException { // the event must correspond to an SNMP trap Snmp snmpInfo = event.getSnmp(); if (snmpInfo == null) { throw new SnmpTrapHelperException( "Cannot forward an event with no SNMP info: " + event.getUei()); } // check the version of the original trap String version = snmpInfo.getVersion(); SnmpV1TrapBuilder trap = SnmpUtils.getV1TrapBuilder(); if ("v1".equals(version)) { trap.setEnterprise(SnmpObjId.get(snmpInfo.getId())); InetAddress agentAddress; agentAddress = InetAddressUtils.addr(event.getSnmphost()); if (agentAddress == null) { throw new SnmpTrapHelperException("Invalid ip address."); } trap.setAgentAddress(agentAddress); if (snmpInfo.hasGeneric()) { trap.setGeneric(snmpInfo.getGeneric()); } if (snmpInfo.hasSpecific()) { trap.setSpecific(snmpInfo.getSpecific()); } trap.setTimeStamp(snmpInfo.getTimeStamp()); // varbinds int i = 0; for (Parm parm : event.getParmCollection()) { try { Value value = parm.getValue(); addVarBinding( trap, parm.getParmName(), value.getType(), value.getEncoding(), value.getContent()); } catch (SnmpTrapHelperException e) { throw new SnmpTrapHelperException(e.getMessage() + " in event parm[" + i + "]"); } finally { i++; } } } else if ("v2".equals(version)) { // converting V2 trap to V1 (see RFC2576) trap.setEnterprise(SnmpObjId.get(snmpInfo.getId())); String addr = null; for (Parm parm : event.getParmCollection()) { if (SNMP_TRAP_ADDRESS_OID.equals(parm.getParmName())) { addr = parm.getValue().getContent(); break; } } if (addr == null) { addr = "0.0.0.0"; } InetAddress agentAddress; agentAddress = InetAddressUtils.addr(addr); if (agentAddress == null) { throw new SnmpTrapHelperException("Invalid ip address."); } trap.setAgentAddress(agentAddress); trap.setGeneric(snmpInfo.getGeneric()); trap.setSpecific(snmpInfo.getSpecific()); trap.setTimeStamp(snmpInfo.getTimeStamp()); // varbinds int i = 0; for (Parm parm : event.getParmCollection()) { Value value = parm.getValue(); // omit any parms with type=Counter64 if (!(EventConstants.TYPE_SNMP_COUNTER64.equals(value.getType()))) { try { addVarBinding( trap, parm.getParmName(), value.getType(), value.getEncoding(), value.getContent()); } catch (SnmpTrapHelperException e) { throw new SnmpTrapHelperException(e.getMessage() + " in event parm[" + i + "]"); } } i++; } } else { throw new SnmpTrapHelperException("Invalid SNMP version: " + version); } // send the trap sendTrap(destAddr, destPort, snmpInfo.getCommunity(), trap); }
/** * This helper method helps SNMP trap daemon administrator to set up authentication An snmpv3 trap * is sent using the sender EngineID that needs to be known over remote trap receivers * * @return The local engine ID */ public String getLocalEngineID() { return "0x" + SnmpUtils.getLocalEngineID(); }
/** * {@inheritDoc} * * <p>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 isProtocolSupported(InetAddress address, Map<String, Object> qualifiers) { try { String oid = ParameterMap.getKeyedString(qualifiers, "vbname", DEFAULT_OID); SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(address); String expectedValue = null; String isTable = null; if (qualifiers != null) { // "port" parm // if (qualifiers.get("port") != null) { int port = ParameterMap.getKeyedInteger(qualifiers, "port", agentConfig.getPort()); agentConfig.setPort(port); } // "timeout" parm // if (qualifiers.get("timeout") != null) { int timeout = ParameterMap.getKeyedInteger(qualifiers, "timeout", agentConfig.getTimeout()); agentConfig.setTimeout(timeout); } // "retry" parm // if (qualifiers.get("retry") != null) { int retry = ParameterMap.getKeyedInteger(qualifiers, "retry", agentConfig.getRetries()); agentConfig.setRetries(retry); } // "force version" parm // if (qualifiers.get("force version") != null) { String version = (String) qualifiers.get("force version"); if (version.equalsIgnoreCase("snmpv1")) agentConfig.setVersion(SnmpAgentConfig.VERSION1); else if (version.equalsIgnoreCase("snmpv2") || version.equalsIgnoreCase("snmpv2c")) agentConfig.setVersion(SnmpAgentConfig.VERSION2C); // TODO: make sure JoeSnmpStrategy correctly handles this. else if (version.equalsIgnoreCase("snmpv3")) agentConfig.setVersion(SnmpAgentConfig.VERSION3); } // "vbvalue" parm // if (qualifiers.get("vbvalue") != null) { expectedValue = (String) qualifiers.get("vbvalue"); } if (qualifiers.get("table") != null) { isTable = (String) qualifiers.get("table"); } } if (isTable != null && isTable.equalsIgnoreCase("true")) { SnmpObjId snmpObjId = SnmpObjId.get(oid); Map<SnmpInstId, SnmpValue> table = SnmpUtils.getOidValues(agentConfig, "SnmpPlugin", snmpObjId); for (Map.Entry<SnmpInstId, SnmpValue> e : table.entrySet()) { if (e.getValue().toString().equals(expectedValue)) { return true; } } } else { String retrievedValue = getValue(agentConfig, oid); if (retrievedValue != null && expectedValue != null) { return (Pattern.compile(expectedValue).matcher(retrievedValue).find()); } else { return (retrievedValue != null); // return (expectedValue == null ? true : retrievedValue.equals(expectedValue)); } } } catch (Throwable t) { throw new UndeclaredThrowableException(t); } // should never get here. return false; }
@Override public OnmsAccessPointCollection call() throws IOException { OnmsAccessPointCollection apsUp = new OnmsAccessPointCollection(); InetAddress ipaddr = m_iface.getIpAddress(); // Retrieve this interface's SNMP peer object SnmpAgentConfig agentConfig = getAgentConfig(ipaddr); final String hostAddress = InetAddressUtils.str(ipaddr); LOG.debug("poll: setting SNMP peer attribute for interface {}", hostAddress); // Get configuration parameters String oid = ParameterMap.getKeyedString(m_parameters, "oid", null); if (oid == null) { throw new IllegalStateException("oid parameter is not set."); } String operator = ParameterMap.getKeyedString(m_parameters, "operator", null); String operand = ParameterMap.getKeyedString(m_parameters, "operand", null); String matchstr = ParameterMap.getKeyedString(m_parameters, "match", "true"); LOG.debug("InstanceStrategy.poll: SnmpAgentConfig address= {}", agentConfig); // Establish SNMP session with interface try { SnmpObjId snmpObjectId = SnmpObjId.get(oid); Map<SnmpInstId, SnmpValue> map = SnmpUtils.getOidValues(agentConfig, "AccessPointMonitor::InstanceStrategy", snmpObjectId); if (map.size() <= 0) { throw new IOException("No entries found in table (possible timeout)."); } for (Map.Entry<SnmpInstId, SnmpValue> entry : map.entrySet()) { boolean isUp = false; SnmpInstId instance = entry.getKey(); SnmpValue value = entry.getValue(); // Check the value against the configured criteria if (meetsCriteria(value, operator, operand)) { if ("true".equals(matchstr)) { isUp = true; } } else if ("false".equals(matchstr)) { isUp = true; } // If the criteria is met, find the AP and add it to the list // of online APs if (isUp) { String physAddr = getPhysAddrFromInstance(instance); LOG.debug( "AP at instance '{}' with MAC '{}' is considered to be ONLINE on controller '{}'", instance, physAddr, m_iface.getIpAddress()); OnmsAccessPoint ap = m_accessPointDao.get(physAddr); if (ap != null) { if (ap.getPollingPackage().compareToIgnoreCase(getPackage().getName()) == 0) { // Save the controller's IP address ap.setControllerIpAddress(ipaddr); apsUp.add(ap); } else { LOG.info("AP with MAC '{}' is in a different package.", physAddr); } } else { LOG.info("No matching AP in database for instance '{}'.", instance); } } } } catch (NumberFormatException e) { LOG.error("Number operator used on a non-number ", e); } catch (IllegalArgumentException e) { LOG.error("Invalid SNMP Criteria ", e); } catch (InterruptedException e) { LOG.error("Interrupted while polling {}", hostAddress, e); } return apsUp; }
public void detectPhysicalInterfaces(final BatchTask currentPhase) { if (isAborted()) { return; } final SnmpAgentConfig agentConfig = getAgentConfigFactory().getAgentConfig(getAgentAddress()); Assert.notNull(getAgentConfigFactory(), "agentConfigFactory was not injected"); final PhysInterfaceTableTracker physIfTracker = new PhysInterfaceTableTracker() { @Override public void processPhysicalInterfaceRow(PhysicalInterfaceRow row) { LOG.info( "Processing ifTable row for ifIndex {} on node {}/{}/{}", row.getIfIndex(), getNodeId(), getForeignSource(), getForeignId()); OnmsSnmpInterface snmpIface = row.createInterfaceFromRow(); snmpIface.setLastCapsdPoll(getScanStamp()); final List<SnmpInterfacePolicy> policies = getProvisionService() .getSnmpInterfacePoliciesForForeignSource( getForeignSource() == null ? "default" : getForeignSource()); for (final SnmpInterfacePolicy policy : policies) { if (snmpIface != null) { snmpIface = policy.apply(snmpIface); } } if (snmpIface != null) { final OnmsSnmpInterface snmpIfaceResult = snmpIface; // add call to the SNMP interface collection enable policies final Runnable r = new Runnable() { @Override public void run() { getProvisionService() .updateSnmpInterfaceAttributes(getNodeId(), snmpIfaceResult); } }; currentPhase.add(r, "write"); } } }; final SnmpWalker walker = SnmpUtils.createWalker(agentConfig, "ifTable/ifXTable", physIfTracker); walker.start(); try { walker.waitFor(); if (walker.timedOut()) { abort("Aborting node scan : Agent timed out while scanning the interfaces table"); } else if (walker.failed()) { abort( "Aborting node scan : Agent failed while scanning the interfaces table: " + walker.getErrorMessage()); } else { LOG.debug("Finished phase {}", currentPhase); } } catch (final InterruptedException e) { abort("Aborting node scan : Scan thread interrupted while waiting for interfaces table"); Thread.currentThread().interrupt(); } }
private static String getSnmpImplementation() { return SnmpUtils.getStrategy().getClass().getSimpleName(); }
/** * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as * an SnmpNull.The value and encoding parameters are ignored. * * @param name The name (a.k.a. "id") of the variable binding to be created * @param encoding This parameter value is ignored. * @param value This parameter value is ignored. * @return The newly-created variable binding */ @Override public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) { trap.addVarBind(SnmpObjId.get(name), SnmpUtils.getValueFactory().getNull()); }