suspecteventprocessor.java

来自「opennms得相关源码 请大家看看」· Java 代码 · 共 1,523 行 · 第 1/5 页

JAVA
1,523
字号
//// This file is part of the OpenNMS(R) Application.//// OpenNMS(R) is Copyright (C) 2002-2005 The OpenNMS Group, Inc.  All rights reserved.// OpenNMS(R) is a derivative work, containing both original code, included code and modified// code that was published under the GNU General Public License. Copyrights for modified // and included code are below.//// OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc.//// Modifications://// 2005 Mar 25: Fixed bug 1178 regarding designation of secondary SNMP//              interfaces, as well as a few other minor bugs discovered//              in testing the bug fix.// 2004 Dec 27: Updated code to determine primary SNMP interface to select//              an interface from collectd-configuration.xml first, and if//              none found, then from all interfaces on the node. In either//              case, a loopback interface is preferred if available.// 2004 Apr 01: Fixed case where sysObjectId is null for suspect device// 2004 Feb 12: Rebuild collectd package agaist IP List map when determining primary//              interface.// 2003 Nov 11: Merged changes from Rackspace project// 2003 Sep 09: Modifications to allow OpenNMS to handle duplicate IP addresses.// 2003 Mar 18: Fixed null pointer exceptions from some poorly written SNMP agents.// 2003 Jan 31: Cleaned up some unused imports.// 2002 Oct 03: Added the ability to discover non 127.*.*.* loopback interfaces//		and to use that for the primary SNMP interface, if possible.// 2002 Aug 01: Modified the code to label nodes based first on DNS, then SMB,//		SNMP and finally IP Address. If available, the SNMP primary//		interface will be used.//// Original code base Copyright (C) 1999-2001 Oculan Corp.  All rights reserved.//// This program is free software; you can redistribute it and/or modify// it under the terms of the GNU General Public License as published by// the Free Software Foundation; either version 2 of the License, or// (at your option) any later version.//// This program is distributed in the hope that it will be useful,// but WITHOUT ANY WARRANTY; without even the implied warranty of// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the// GNU General Public License for more details.                                                            //// You should have received a copy of the GNU General Public License// along with this program; if not, write to the Free Software// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.//       // For more information contact: //      OpenNMS Licensing       <license@opennms.org>//      http://www.opennms.org///      http://www.opennms.com///// Tab Size = 8//package org.opennms.netmgt.capsd;import java.net.InetAddress;import java.net.UnknownHostException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.log4j.Category;import org.opennms.core.utils.ThreadCategory;import org.opennms.netmgt.ConfigFileConstants;import org.opennms.netmgt.EventConstants;import org.opennms.netmgt.capsd.snmp.IfTable;import org.opennms.netmgt.capsd.snmp.IfTableEntry;import org.opennms.netmgt.capsd.snmp.IpAddrTable;import org.opennms.netmgt.capsd.snmp.SystemGroup;import org.opennms.netmgt.config.CapsdConfigFactory;import org.opennms.netmgt.config.CollectdConfigFactory;import org.opennms.netmgt.config.DatabaseConnectionFactory;import org.opennms.netmgt.config.PollerConfigFactory;import org.opennms.netmgt.eventd.EventIpcManagerFactory;import org.opennms.netmgt.utils.IPSorter;import org.opennms.netmgt.xml.event.Event;import org.opennms.netmgt.xml.event.Parm;import org.opennms.netmgt.xml.event.Parms;import org.opennms.netmgt.xml.event.Value;import org.opennms.protocols.snmp.SnmpInt32;import org.opennms.protocols.snmp.SnmpObjectId;import org.opennms.protocols.snmp.SnmpOctetString;import org.opennms.protocols.snmp.SnmpUInt32;/** * This class is designed to scan/capability check a suspect interface, update * the database based on the information collected from the device, and generate * events necessary to notify the other OpenNMS services. The constructor takes * a string which is the IP address of the interface to be scanned. *  * @author <a href="mailto:jamesz@opennms.com">James Zuo </a> * @author <a href="mailto:mike@opennms.org">Mike Davidson </a> * @author <a href="mailto:weave@oculan.com">Brian Weaver </a> * @author <a href="http://www.opennms.org/">OpenNMS </a> */final class SuspectEventProcessor implements Runnable {    /**     * SQL statement to retrieve the node identifier for a given IP address     */    private static String SQL_RETRIEVE_INTERFACE_NODEID_PREFIX = "SELECT nodeId FROM ipinterface WHERE ";    /**     * SQL statement to retrieve the ipaddresses for a given node ID     */    private final static String SQL_RETRIEVE_IPINTERFACES_ON_NODEID = "SELECT ipaddr FROM ipinterface WHERE nodeid = ? and ismanaged != 'D'";    private final static String SELECT_METHOD_MIN = "min";    private final static String SELECT_METHOD_MAX = "max";    /**     * IP address of new suspect interface     */    String m_suspectIf;    /**     * Constructor.     *      * @param ifAddress     *            Suspect interface address.     */    SuspectEventProcessor(String ifAddress) {        // Check the arguments        //        if (ifAddress == null)            throw new IllegalArgumentException("The interface address cannot be null");        m_suspectIf = ifAddress;    }    /**     * This method is responsible for determining if a node already exists in     * the database for the current interface. If the IfCollector object     * contains a valid SNMP collection, an attempt will be made to look up in     * the database each interface contained in the SNMP collection's ifTable.     * If an interface is found to already exist in the database a DbNodeEntry     * object will be created from it and returned. If the IfCollector object     * does not contain a valid SNMP collection or if none of the interfaces     * exist in the database null is returned.     *      * @param dbc     *            Connection to the database.     * @param collector     *            Interface collector object     *      * @return dbNodeEntry Returns null if a node does not already exist in the     *         database, otherwise returns the DbNodeEntry object for the node     *         under which the current interface/IP address should be added.     *      * @throws SQLException     *             Thrown if an error occurs retrieving the parent nodeid from     *             the database.     */    private DbNodeEntry getExistingNodeEntry(java.sql.Connection dbc, IfCollector collector) throws SQLException {        Category log = ThreadCategory.getInstance(getClass());        if (log.isDebugEnabled())            log.debug("getExistingNodeEntry: checking for current target: " + collector.getTarget());        // Do we have any additional interface information collected via SNMP?        // If not simply return, there is nothing to check        if (!collector.hasSnmpCollection() || collector.getSnmpCollector().failed())            return null;        // Next verify that ifTable and ipAddrTable entries were collected        IfSnmpCollector snmpc = collector.getSnmpCollector();        IfTable ifTable = null;        IpAddrTable ipAddrTable = null;        if (snmpc.hasIfTable())            ifTable = snmpc.getIfTable();        if (snmpc.hasIpAddrTable())            ipAddrTable = snmpc.getIpAddrTable();        if (ifTable == null || ipAddrTable == null)            return null;        // SQL statement prefix        StringBuffer sqlBuffer = new StringBuffer(SQL_RETRIEVE_INTERFACE_NODEID_PREFIX);        boolean firstAddress = true;        // Loop through the interface table entries and see if any already exist        // in the database.        Iterator iter = ifTable.getEntries().iterator();        List ipaddrsOfNewNode = new ArrayList();        List ipaddrsOfOldNode = new ArrayList();        while (iter.hasNext()) {            IfTableEntry ifEntry = (IfTableEntry) iter.next();            if (ifEntry.containsKey("ifIndex") != true) {                log.debug("getExistingNodeEntry:  Breaking from loop");                break;            }            //            // Get ifIndex            //            int ifIndex = -1;            SnmpInt32 snmpIfIndex = (SnmpInt32) ifEntry.get(IfTableEntry.IF_INDEX);            if (snmpIfIndex != null)                ifIndex = snmpIfIndex.getValue();            //            // Get ALL IP Addresses for this ifIndex            //            List ipAddrs = IpAddrTable.getIpAddresses(ipAddrTable.getEntries(), ifIndex);            if (log.isDebugEnabled())                log.debug("getExistingNodeEntry: number of interfaces retrieved for ifIndex " + ifIndex + " is: " + ipAddrs.size());            //             // Get ifType for this interface            //            int ifType = -1;            SnmpInt32 snmpIfType = (SnmpInt32) ifEntry.get(IfTableEntry.IF_TYPE);            if (snmpIfType != null)                ifType = snmpIfType.getValue();            // Iterate over IP address list and add each to the sql buffer            //            Iterator aiter = ipAddrs.iterator();            while (aiter.hasNext()) {                InetAddress ipAddress = (InetAddress) aiter.next();                //                 // Skip interface if no IP address or if IP address is "0.0.0.0"                // or if this interface is of type loopback                if (ipAddress == null || ipAddress.getHostAddress().equals("0.0.0.0") || ipAddress.getHostAddress().startsWith("127."))                    continue;                if (firstAddress) {                    sqlBuffer.append("ipaddr='").append(ipAddress.getHostAddress()).append("'");                    firstAddress = false;                } else                    sqlBuffer.append(" OR ipaddr='").append(ipAddress.getHostAddress()).append("'");                ipaddrsOfNewNode.add(ipAddress.getHostAddress());            }        } // end while        // Make sure we added at least one address to the SQL query        //        if (firstAddress)            return null;        // Prepare the db statement in advance        //        if (log.isDebugEnabled())            log.debug("getExistingNodeEntry: issuing SQL command: " + sqlBuffer.toString());        PreparedStatement stmt = dbc.prepareStatement(sqlBuffer.toString());        // Do any of the IP addrs already exist in the database under another        // node?        //        int nodeID = -1;        ResultSet rs = null;        try {            rs = stmt.executeQuery();            if (rs.next()) {                nodeID = rs.getInt(1);                if (log.isDebugEnabled())                    log.debug("getExistingNodeEntry: target " + collector.getTarget().getHostAddress() + nodeID);                rs = null;            }        } catch (SQLException sqlE) {            throw sqlE;        } finally {            try {                //we're seeing problems with this so what does it hurt to close it anyway?// automatically closes the result set as well                if (rs != null) rs.close();            } catch (Exception e) {                log.error("getExistingNodeEntry: exception cleaning up jdbc connections: "+e);                // Ignore            } finally {                if (stmt != null) stmt.close();            }        }        if (nodeID == -1)            return null;        try {            stmt = dbc.prepareStatement(SQL_RETRIEVE_IPINTERFACES_ON_NODEID);            stmt.setInt(1, nodeID);            rs = stmt.executeQuery();            while (rs.next()) {                String ipaddr = rs.getString(1);                if (!ipaddr.equals("0.0.0.0"))                    ipaddrsOfOldNode.add(ipaddr);            }        } catch (SQLException sqlE) {            throw sqlE;        } finally {            try {

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?