public void testSnmpv3WithNoAuthNoPriv() throws Exception { SnmpPeerFactory.setInstance( new SnmpPeerFactory(new ByteArrayResource(getSnmpConfig().getBytes()))); SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.11.12.13")); assertEquals("opennmsuser1", agentConfig.getSecurityName()); assertEquals("VF:2", agentConfig.getContextName()); assertNull(agentConfig.getAuthProtocol()); assertNull(agentConfig.getPrivProtocol()); assertNull(agentConfig.getAuthPassPhrase()); assertNull(agentConfig.getPrivPassPhrase()); assertEquals(1, agentConfig.getSecurityLevel()); agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.11.12.14")); assertEquals("opennmsuser2", agentConfig.getSecurityName()); assertEquals("VF:3", agentConfig.getContextName()); assertEquals("", agentConfig.getAuthProtocol()); assertEquals("", agentConfig.getPrivProtocol()); assertEquals("", agentConfig.getAuthPassPhrase()); assertEquals("", agentConfig.getPrivPassPhrase()); assertEquals(1, agentConfig.getSecurityLevel()); agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(myLocalHost())); assertEquals(3, agentConfig.getSecurityLevel()); }
public void testProxiedAgent() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.0.0.3")); assertEquals("10.0.0.3", InetAddressUtils.str(agentConfig.getProxyFor())); assertEquals("127.0.0.1", InetAddressUtils.str(agentConfig.getAddress())); agentConfig.toString(); }
/** {@inheritDoc} */ public boolean isInterfaceInDB(Connection dbConn, InetAddress ifAddress) throws SQLException { boolean result = false; if (log().isDebugEnabled()) { log() .debug( "isInterfaceInDB: attempting to lookup interface " + InetAddressUtils.str(ifAddress) + " in the database."); } // Set connection as read-only // // dbConn.setReadOnly(true); ResultSet rs = null; final DBUtils d = new DBUtils(getClass()); try { PreparedStatement s = dbConn.prepareStatement(RETRIEVE_IPADDR_SQL); d.watch(s); s.setString(1, InetAddressUtils.str(ifAddress)); rs = s.executeQuery(); d.watch(rs); result = rs.next(); } finally { d.cleanUp(); } return result; }
private InetAddress getIpForNode(final OnmsNode node) { LogUtils.debugf( this, "getIpForNode: node: %s Foreign Source: %s", node.getNodeId(), node.getForeignSource()); final OnmsIpInterface primaryInterface = node.getPrimaryInterface(); InetAddress ipaddr = InetAddressUtils.getLocalHostAddress(); if (primaryInterface == null) { log().debug("getIpForNode: found null SNMP Primary Interface, getting interfaces"); final Set<OnmsIpInterface> ipInterfaces = node.getIpInterfaces(); for (final OnmsIpInterface onmsIpInterface : ipInterfaces) { log().debug("getIpForNode: trying Interface with id: " + onmsIpInterface.getId()); if (InetAddressUtils.str(onmsIpInterface.getIpAddress()) != null) ipaddr = onmsIpInterface.getIpAddress(); else log() .debug( "getIpForNode: found null ip address on Interface with id: " + onmsIpInterface.getId()); } } else { log().debug("getIpForNode: found SNMP Primary Interface"); if (InetAddressUtils.str(primaryInterface.getIpAddress()) != null) ipaddr = primaryInterface.getIpAddress(); else log().debug("getIpForNode: found null ip address on Primary Interface"); } return ipaddr; }
public String getForeignSource(InetAddress address) { getReadLock().lock(); try { LOG.debug( "Looking for matching foreign source specific IP or IP range with address: {}...", address); List<Specific> specificCollection = getConfiguration().getSpecificCollection(); for (Specific specific : specificCollection) { String ipAddr = specific.getContent(); if (ipAddr.equals(InetAddressUtils.str(address))) { String foreignSource = specific.getForeignSource(); LOG.debug( "Matched foreign source {} matching address: {} against specific {}.", foreignSource, address, ipAddr); return foreignSource; } } final byte[] laddr = address.getAddress(); List<IncludeRange> includeRangeCollection = getConfiguration().getIncludeRangeCollection(); for (IncludeRange range : includeRangeCollection) { if (InetAddressUtils.isInetAddressInRange(laddr, range.getBegin(), range.getEnd())) { String foreignSource = range.getForeignSource(); LOG.debug( "Found foreign source {} with address {} in the range begin: {} and end: {}.", foreignSource, address, range.getBegin(), range.getEnd()); return foreignSource; } } List<IncludeUrl> includeUrlCollection = getConfiguration().getIncludeUrlCollection(); for (IncludeUrl includeUrl : includeUrlCollection) { String ipAddr = includeUrl.getContent(); if (ipAddr.equals(InetAddressUtils.str(address))) { String foreignSource = includeUrl.getForeignSource(); LOG.debug( "Matched foreign source {} matching address: {} in specified URL.", foreignSource, address); return foreignSource; } } return getConfiguration().getForeignSource(); } finally { getReadLock().unlock(); } }
public void testDefaultMaxRequestSize() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.0.0.1")); assertEquals(SnmpAgentConfig.DEFAULT_MAX_REQUEST_SIZE, agentConfig.getMaxRequestSize()); agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.0.0.2")); assertEquals(484, agentConfig.getMaxRequestSize()); }
/** * getRanges * * @return a {@link java.util.List} object. */ public List<IPPollRange> getRanges() { final List<IPPollRange> includes = new LinkedList<IPPollRange>(); getReadLock().lock(); try { Long defaultTimeout = null; Integer defaultRetries = null; if (getConfiguration().hasTimeout()) defaultTimeout = getConfiguration().getTimeout(); if (getConfiguration().hasRetries()) defaultRetries = getConfiguration().getRetries(); for (final IncludeRange ir : getConfiguration().getIncludeRangeCollection()) { // Validate IP range; if invalid, then log and discard this range try { InetAddressUtils.toIpAddrBytes(ir.getBegin()); } catch (Throwable e) { LogUtils.warnf( this, "Begin address of discovery range is invalid, discarding: %s", ir.getBegin()); continue; } try { InetAddressUtils.toIpAddrBytes(ir.getEnd()); } catch (Throwable e) { LogUtils.warnf( this, "End address of discovery range is invalid, discarding: %s", ir.getEnd()); continue; } long timeout = 800L; if (ir.hasTimeout()) { timeout = ir.getTimeout(); } else if (defaultTimeout != null) { timeout = defaultTimeout; } int retries = 3; if (ir.hasRetries()) { retries = ir.getRetries(); } else if (defaultRetries != null) { retries = defaultRetries; } try { includes.add(new IPPollRange(ir.getBegin(), ir.getEnd(), timeout, retries)); } catch (final UnknownHostException uhE) { LogUtils.warnf( this, uhE, "Failed to convert address range (%s, %s)", ir.getBegin(), ir.getEnd()); } } return includes; } finally { getReadLock().unlock(); } }
public void testGetMaxRepetitions() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("77.5.5.255")); assertEquals("ipmatch", agentConfig.getReadCommunity()); assertEquals(7, agentConfig.getMaxRepetitions()); agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.0.0.1")); assertEquals("specificv1", agentConfig.getReadCommunity()); assertEquals(2, agentConfig.getMaxRepetitions()); }
/** * Tests getting the correct SNMP Peer after a configureSNMP event and merge to the running * config. * * @throws UnknownHostException */ public void testSnmpEventInfoClassWithSpecific() throws UnknownHostException { final String addr = "192.168.0.5"; EventBuilder bldr = createConfigureSnmpEventBuilder(addr, null); addCommunityStringToEvent(bldr, "abc"); SnmpEventInfo info = new SnmpEventInfo(bldr.getEvent()); SnmpPeerFactory.getInstance().define(info); SnmpAgentConfig agent = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr(addr)); assertEquals(InetAddressUtils.str(agent.getAddress()), addr); assertEquals("abc", agent.getReadCommunity()); }
/** * Creates a new IPAddressRange object that can be used to encapsulate a contiguous range of IP * Addresses. Once created the object can be used to get either an Iterator or Enumeration object * to cycle through the list of address encapsulated by this object. * * <p>It is important to note that if the address for start is greater than end, the values will * be swapped so that the iteration is always from the lowest address to the highest address. * * @param start The starting address. * @param end The ending address. */ IPAddrRange(InetAddress start, InetAddress end) { byte[] from = start.getAddress(); byte[] to = end.getAddress(); if (new ByteArrayComparator().compare(from, to) > 0) { LOG.warn( "The beginning of the address range is greater than the end of the address range ({} - {}), swapping values to create a valid IP address range", InetAddressUtils.str(start), InetAddressUtils.str(end)); m_end = from; m_begin = to; } else { m_begin = from; m_end = to; } }
/** * {@inheritDoc} * * <p>Responsible for performing all necessary initialization for the specified interface in * preparation for data collection. */ @Override public void initialize(CollectionAgent agent, Map<String, Object> parameters) { InetAddress ipAddr = agent.getAddress(); int nodeID = agent.getNodeId(); // Retrieve the name of the JMX data collector String collectionName = ParameterMap.getKeyedString(parameters, "collection", serviceName); final String hostAddress = InetAddressUtils.str(ipAddr); LogUtils.debugf( this, "initialize: InetAddress=%s, collectionName=%s", hostAddress, collectionName); JMXNodeInfo nodeInfo = new JMXNodeInfo(nodeID); LogUtils.debugf(this, "nodeInfo: %s %d %s", hostAddress, nodeID, agent); /* * Retrieve list of MBean objects to be collected from the * remote agent which are to be stored in the node-level RRD file. * These objects pertain to the node itself not any individual * interfaces. */ Map<String, List<Attrib>> attrMap = JMXDataCollectionConfigFactory.getInstance() .getAttributeMap(collectionName, serviceName, hostAddress); nodeInfo.setAttributeMap(attrMap); Map<String, JMXDataSource> dsList = buildDataSourceList(collectionName, attrMap); nodeInfo.setDsMap(dsList); nodeInfo.setMBeans(JMXDataCollectionConfigFactory.getInstance().getMBeanInfo(collectionName)); // Add the JMXNodeInfo object as an attribute of the interface agent.setAttribute(NODE_INFO_KEY, nodeInfo); agent.setAttribute("collectionName", collectionName); }
private EndPointImpl getEndPoint(final String sysOid, final String address) throws UnknownHostException { final EndPointImpl endPoint = new EndPointImpl(InetAddressUtils.getLocalHostAddress(), getAgentConfig(address)); endPoint.setSysOid(sysOid); return endPoint; }
/** String representing snmp-config.xml */ public String getSnmpConfig() throws IOException { return ConfigurationTestUtils.getConfigForResourceWithReplacements( this, "/org/opennms/netmgt/mock/snmp-config.xml", new String[] {"\\$\\{myVersion\\}", myVersion()}, new String[] {"\\$\\{myLocalHost\\}", InetAddressUtils.str(myLocalHost())}); }
public DbIfServiceEntry[] getServices(Connection db) throws SQLException { PreparedStatement stmt = null; ResultSet rset = null; final DBUtils d = new DBUtils(getClass()); List<DbIfServiceEntry> l; try { stmt = db.prepareStatement(SQL_LOAD_IFSVC_LIST); d.watch(stmt); stmt.setLong(1, m_nodeId); stmt.setString(2, InetAddressUtils.str(m_ipAddr)); rset = stmt.executeQuery(); d.watch(rset); l = new ArrayList<DbIfServiceEntry>(); while (rset.next()) { int sid = rset.getInt(1); DbIfServiceEntry entry = DbIfServiceEntry.get(db, m_nodeId, m_ipAddr, sid); if (entry != null) { l.add(entry); } } } finally { d.cleanUp(); } DbIfServiceEntry[] entries = new DbIfServiceEntry[l.size()]; return l.toArray(entries); }
@Test(timeout = 20000) @JUnitSnmpAgent( host = PercDetectorTest.TEST_IP_ADDRESS, resource = "classpath:org/opennms/netmgt/provision/detector/percDetector.properties") public void testDetectorSuccessful() throws UnknownHostException { assertTrue(m_detector.isServiceDetected(InetAddressUtils.addr(TEST_IP_ADDRESS))); }
/** * This tests for ranges configured for v3 node and security name * * @throws UnknownHostException */ public void testGetv3ConfigInRange() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("1.1.1.50")); assertNotNull(agentConfig); assertEquals(SnmpAgentConfig.VERSION3, agentConfig.getVersion()); assertEquals("opennmsRangeUser", agentConfig.getSecurityName()); }
/** {@inheritDoc} */ @Override public void foundInterface( final String ipAddr, final Object descr, final InterfaceSnmpPrimaryType snmpPrimary, final boolean managed, final int status) { if ("".equals(ipAddr)) { LOG.error("Found interface on node {} with an empty ipaddr! Ignoring!", m_node.getLabel()); // create a bogus OnmsIpInterface and set it to current to services we run across get ignored // as well m_currentInterface = new OnmsIpInterface(); return; } m_currentInterface = new OnmsIpInterface(ipAddr, m_node); m_currentInterface.setIsManaged(status == 3 ? "U" : "M"); m_currentInterface.setIsSnmpPrimary(PrimaryType.get(snmpPrimary.toString())); // m_currentInterface.setIpStatus(status == 3 ? new Integer(3) : new Integer(1)); if (InterfaceSnmpPrimaryType.P.equals(snmpPrimary)) { final InetAddress addr = InetAddressUtils.addr(ipAddr); if (addr == null) { LOG.error( "Unable to resolve address of snmpPrimary interface for node {}", m_node.getLabel()); } m_collector = new IfSnmpCollector(addr); } // FIXME: verify this doesn't conflict with constructor. The constructor already adds this // interface to the node. m_node.addIpInterface(m_currentInterface); }
/** {@inheritDoc} */ @Override public Integer resolveOutagePendingRegainEventId( int nodeId, String ipAddr, String svcName, Date regainedTime) { LOG.info("resolving outage for {}:{}:{} @ {}", nodeId, ipAddr, svcName, regainedTime); final OnmsMonitoredService service = m_monitoredServiceDao.get(nodeId, InetAddressUtils.addr(ipAddr), svcName); if (service == null) { LOG.warn( "Failed to resolve the pending outage for {}:{}:{} @ {}. The service could not be found.", nodeId, ipAddr, svcName, regainedTime); return null; } final OnmsOutage outage = m_outageDao.currentOutageForService(service); if (outage == null) { return null; } // Update the outage outage.setIfRegainedService(new Timestamp(regainedTime.getTime())); m_outageDao.saveOrUpdate(outage); return outage.getId(); }
/** * This tests for ranges configured for a v2 node and community string * * @throws UnknownHostException */ public void testGetv2cInRange() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.7.23.100")); assertNotNull(agentConfig); assertEquals(SnmpAgentConfig.VERSION2C, agentConfig.getVersion()); assertEquals("rangev2c", agentConfig.getReadCommunity()); }
/** * Method that updates info in List nodes and also save info into database. This method is called * by SnmpCollection after all stuff is done * * @param snmpcoll */ @Transactional public void updateNodeSnmpCollection(final SnmpCollection snmpcoll) { LogUtils.debugf( this, "Updating SNMP collection for %s", InetAddressUtils.str(snmpcoll.getTarget())); LinkableNode node = removeNode(snmpcoll.getTarget()); if (node == null) { LogUtils.errorf( this, "No node found for SNMP collection: %s unscheduling!", snmpcoll.getInfo()); m_scheduler.unschedule(snmpcoll); return; } try { node = m_queryMgr.storeSnmpCollection(node, snmpcoll); } catch (SQLException e) { LogUtils.errorf( this, e, "Failed to save on db snmpcollection/package: %s/%s", snmpcoll.getPackageName(), snmpcoll.getInfo()); return; } if (node != null) { synchronized (m_nodes) { m_nodes.add(node); } } }
/** * This tests for a specifically defined v2c agentConfig * * @throws UnknownHostException */ public void testGetV2cConfig() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("192.168.0.50")); assertNotNull(agentConfig); assertEquals(agentConfig.getVersion(), SnmpAgentConfig.VERSION2C); assertEquals("specificv2c", agentConfig.getReadCommunity()); }
/** * This tests getting a v1 config * * @throws UnknownHostException */ public void testGetV1Config() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.0.0.1")); assertNotNull(agentConfig); assertTrue(agentConfig.getVersion() == SnmpAgentConfig.VERSION1); assertEquals("specificv1", agentConfig.getReadCommunity()); }
/** * getIpAddrToInterfaceMap * * @param imported a {@link org.opennms.netmgt.model.OnmsNode} object. * @return a {@link java.util.Map} object. */ protected Map<String, OnmsIpInterface> getIpAddrToInterfaceMap(OnmsNode imported) { Map<String, OnmsIpInterface> ipAddrToIface = new HashMap<String, OnmsIpInterface>(); for (final OnmsIpInterface iface : imported.getIpInterfaces()) { final String ipAddress = InetAddressUtils.str(iface.getIpAddress()); ipAddrToIface.put(ipAddress, iface); } return ipAddrToIface; }
@Test(timeout = 90000) public void testDetectorFailWrongPort() throws UnknownHostException { m_detector.setPort(5000); m_detector.setLookup("www.google.com"); m_detector.init(); assertFalse(m_detector.isServiceDetected(InetAddressUtils.addr("localhost"))); }
/** * Converts an integer to an InetAdrress object and discards any exceptions. If the address * cannot be constructed then a null reference is returned. * * @param addr The IP address value, in network order. * @return A {@link java.net.InetAddress} object. */ static InetAddress make(BigInteger addr) { InetAddress naddr = null; try { naddr = InetAddressUtils.convertBigIntegerIntoInetAddress(addr); } catch (UnknownHostException uhE) { naddr = null; } return naddr; }
public void testGetTargetFromPatterns() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("77.5.5.255")); assertEquals("ipmatch", agentConfig.getReadCommunity()); assertEquals(128, agentConfig.getMaxVarsPerPdu()); agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("77.15.80.255")); assertEquals("ipmatch", agentConfig.getReadCommunity()); assertEquals(7, agentConfig.getMaxRepetitions()); // should be default community "public" because of 4 agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("77.4.5.255")); assertEquals("public", agentConfig.getReadCommunity()); // should be default community because of 0 agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("77.6.0.255")); assertEquals("public", agentConfig.getReadCommunity()); }
/** {@inheritDoc} */ @Override public Integer openOutagePendingLostEventId( int nodeId, String ipAddr, String svcName, Date lostTime) { LOG.info("opening outage for {}:{}:{} @ {}", nodeId, ipAddr, svcName, lostTime); final OnmsMonitoredService service = m_monitoredServiceDao.get(nodeId, InetAddressUtils.addr(ipAddr), svcName); final OnmsOutage outage = new OnmsOutage(lostTime, service); m_outageDao.saveOrUpdate(outage); return outage.getId(); }
private OnmsNotification buildTestNotification( final NetworkBuilder builder, final OnmsEvent event) { final OnmsNotification notif = new OnmsNotification(); notif.setEvent(event); notif.setTextMsg("This is a test notification"); notif.setIpAddress(InetAddressUtils.getInetAddress("192.168.1.1")); notif.setNode(m_node1); notif.setServiceType(getService("ICMP")); return notif; }
/** * This tests for ranges configured for a v2 node and community string * * @throws UnknownHostException */ public void testReversedRange() throws UnknownHostException { SnmpPeerFactory.setInstance( new SnmpPeerFactory(new ByteArrayResource(getBadRangeSnmpConfig().getBytes()))); SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("10.7.23.100")); assertNotNull(agentConfig); assertEquals(SnmpAgentConfig.VERSION2C, agentConfig.getVersion()); assertEquals("rangev2c", agentConfig.getReadCommunity()); }
/** * This tests for context-name configured for v3 node * * @throws UnknownHostException */ public void testGetv3ConfigWithContextNameAndMore() throws UnknownHostException { SnmpAgentConfig agentConfig = SnmpPeerFactory.getInstance().getAgentConfig(InetAddressUtils.addr("1.1.1.101")); assertNotNull(agentConfig); assertEquals(SnmpAgentConfig.VERSION3, agentConfig.getVersion()); assertEquals("opennmsContextUser", agentConfig.getSecurityName()); assertEquals("testContext", agentConfig.getContextName()); assertEquals("testEngineId", agentConfig.getEngineId()); assertEquals("testContextEngineId", agentConfig.getContextEngineId()); }