snmpifcollector.java

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

JAVA
1,030
字号
//// This file is part of the OpenNMS(R) Application.//// OpenNMS(R) is Copyright (C) 2002-2003 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://// 2003 Jan 31: Cleaned up some unused imports.//// 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//// SnmpIfCollector.java,v 1.1.1.1 2001/11/11 17:34:38 ben Exp//package org.opennms.netmgt.collectd;import java.util.ArrayList;import java.util.Collection;import java.util.Iterator;import java.util.List;import java.util.Map;import org.apache.log4j.Category;import org.apache.log4j.Priority;import org.opennms.core.utils.ThreadCategory;import org.opennms.netmgt.utils.Signaler;import org.opennms.protocols.snmp.SnmpHandler;import org.opennms.protocols.snmp.SnmpObjectId;import org.opennms.protocols.snmp.SnmpPduBulk;import org.opennms.protocols.snmp.SnmpPduPacket;import org.opennms.protocols.snmp.SnmpPduRequest;import org.opennms.protocols.snmp.SnmpSMI;import org.opennms.protocols.snmp.SnmpSession;import org.opennms.protocols.snmp.SnmpSyntax;import org.opennms.protocols.snmp.SnmpVarBind;/** * The SnmpIfCollector class is responsible for performing the actual SNMP data * collection for a node over a specified network interface. The SnmpIfCollector * implements the SnmpHandler class in order to receive notifications when an * SNMP reply is received or error occurs. *  * The SnmpIfCollector is provided a list of MIB objects to collect and an * interface over which to collect the data. Data collection can be via SNMPv1 * GetNext requests or SNMPv2 GetBulk requests depending upon the parms used to * construct the collector. *  * @author <A HREF="mailto:mike@opennms.org">Mike </A> * @author <A>Jon Whetzel </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> *  * @version 1.1.1.1 *  */public class SnmpIfCollector implements SnmpHandler {    /**     * Flag indicating the success or failure of the informational query. If the     * flag is set to false then either part of all of the information was     * unable to be retreived. If it is set to true then all of the data was     * received from the remote host.     */    private boolean m_error;    /**     * Reason that the SNMP request failed. Please see     * org.opennms.protocols.snmp.SnmpPduPacket class for a list of possible     * SNMP error codes. This variable only has meaning of m_error flag is true.     */    private int m_errorStatus;    /**     * Array of SNMPv1 error strings. Please see     * org.opennms.protocols.snmp.SnmpPduPacket class for list of SNMP error     * codes which serve as indices into this string array.     */    private static String[] m_errorText = { "ErrNoError", "ErrTooBig", "ErrNoSuchName", "ErrBadValue", "ErrReadOnly", "ErrGenError" };    /**     * If the SNMP collection failed due to a problem with one or more varbinds     * (for example if a particular object oid is requested which is not     * implemented in the target's SNMP agent) then this value will be set equal     * to the *first* failing varbind in the request. This variable only has     * meaning if m_error flag is true. Will be set to -1 if the SNMP collection     * failed for an unrelated reason.     */    private int m_errorIndex;    /**     * Flag indicating if the SNMP collection failed due to the SNMP request     * timing out. Its value only has meaning if m_error flag is true.     */    private boolean m_timeout;    /**     * Used to synchronize the class to ensure that the session has finished     * collecting data before the value of success or failure is set, and     * control is returned to the caller.     */    private Signaler m_signal;    /**     * List of MibObject objects to be collected.     */    private java.util.List m_objList;    /**     * Copy of m_objList list that will used solely by version 2. As each object     * is collected from the remote node via subsequent SNMPv2 GetBulk commands     * the MibObject is removed and the collection for the next object started.     */    private java.util.List m_objList_v2;    /**     * Used to store all the generated maps of the MIB data for each interface.     */    private java.util.List m_entries;    /**     * Used for classifying the SNMP version of the session.     *      */    private int m_version;    /**     * Used for keeping track of all the possible indexes. Needed for generating     * packets for SNMP v1.     *      */    private String[] m_indexArray;    /**     * Used as temporary storage for variables coming from Snmp v2 PDU reponses.     * Once all the data is gathered, we can generate maps of the data, one map     * per interface.     */    private List m_responseVbList;    /**     * For SNMPv1, used for keeping track of the SNMP response PDUs received.     *      * For SNMPv2, this used for keeping track of the total number of variable     * bindings returned during each subsequent MIB object collection. This     * variable is reset back to 0 after the MIB object has been collected for     * all interfaces.     */    private int m_responses;    /**     * For SNMPv1, used to store the collected MIB data.     */    private SNMPCollectorEntry m_collectorEntry;    /**     * For SNMPv1, keeps track of current oid list index.     */    private int m_oidListIndex;    /**     * Holds the ifIndex of the primary SNMP interface.     */    private String m_primaryIfIndex;    /**     * Holds the IP Address of the primary SNMP iterface.     */    private String m_primaryIf;    /**     * The number of interfaces associated with the remote host.     */    private int m_numInterfaces;    /**     * Max number of variables permitted in a single outgoing SNMP PDU request..     */    private int m_maxVarsPerPdu;    /**     * Map of IfInfo objects representing each of the nodes interfaces.     */    private Map m_ifMap;    /**     * The default constructor is marked private and will always throw an     * exception. This is done to disallow the default constructor. The reason     * is that this object requires several arguments to perform it's duties.     *      * @exception java.lang.UnsupportedOperationException     *                Always thrown from this method since it is not supported.     */    private SnmpIfCollector() throws UnsupportedOperationException {        throw new UnsupportedOperationException("Default Constructor not supported");    }    /**     * The class constructor is used to initialize the collector and send out     * the initial SNMP packet requesting data. The data is then received and     * store by the object. When all the data has been collected the passed     * signaler object is <EM>notified</EM> using the notifyAll() method.     *      * @param session     *            The SNMP session with the remote agent.     * @param signaler     *            The object signaled when data collection is done.     * @param primaryIfIndex     *            The ifIndex value linked to the primary IP.     * @param ifMap     *            Map of org.opennms.netmgt.poller.collectd.IfInfo objects.     * @param ifCount     *            Number of interfaces found in node's MIB-II ifTable     * @param maxVarsPerPdu     *            Max number of variables permitted in a single PDU.     */    public SnmpIfCollector(SnmpSession session, Signaler signaler, String primaryIfIndex, Map ifMap, int ifCount, int maxVarsPerPdu) {        super();        // Log4j category        //        Category log = ThreadCategory.getInstance(getClass());        m_error = false;        m_errorIndex = -1;        m_timeout = false;        // Process parameters        //        m_primaryIf = session.getPeer().getPeer().getHostAddress();        m_primaryIfIndex = primaryIfIndex;        m_version = session.getPeer().getParameters().getVersion();        m_signal = signaler;        m_oidListIndex = 0;        m_collectorEntry = null;        m_numInterfaces = ifCount;        m_ifMap = ifMap;        m_maxVarsPerPdu = maxVarsPerPdu;        if (log.isDebugEnabled())            log.debug("SnmpIfCollector: ("+m_primaryIf+") maxVarsPerPdu=" + maxVarsPerPdu);        // Build (String) array of interface indices using ifMap parm        //        Collection interfaces = ifMap.values();        Iterator iter = interfaces.iterator();        m_indexArray = new String[ifMap.size()];        if (log.isDebugEnabled())            log.debug("SnmpIfCollector: ("+m_primaryIf+") ifMap size: " + ifMap.size());        int i = 0;        while (iter.hasNext()) {            IfInfo ifInfo = (IfInfo) iter.next();            m_indexArray[i++] = String.valueOf(ifInfo.getIndex());            if (log.isDebugEnabled())                log.debug("SnmpIfCollector: ("+m_primaryIf+") arrayIndex: " + i + " ifIndex: " + String.valueOf(ifInfo.getIndex()));        }        // Build object lists for SNMPv2 processing        //        m_objList = null;        m_objList_v2 = null;        if (m_version == SnmpSMI.SNMPV2) {            // Generate object list consisting of all unique oids            // to be collected from all interfaces            m_objList = buildV2CombinedOidList(ifMap);            // Create copy of combined oid list which can            // be modified during collection without affecting            // the master list            m_objList_v2 = new ArrayList(m_objList.size());            for (int c = 0; c < m_objList.size(); c++) {                m_objList_v2.add(m_objList.get(c));            }        }        // Allocate temporary storage to hold response varbinds.        //        m_responseVbList = new ArrayList();        m_responses = 0;        // Instantiate ArrayList to hold generated SnmpCollectoryEntry objects        // created during the collection.        //        m_entries = new ArrayList(2);        // Create initial PDU request and send it to the remote host.        //        SnmpPduPacket pdu = null;        if (m_version == SnmpSMI.SNMPV2) {            pdu = getNextSnmpV2Pdu(m_primaryIf);        } else if (m_version == SnmpSMI.SNMPV1) {            pdu = getNextSnmpV1Pdu(m_primaryIf);        }        if (log.isDebugEnabled())            log.debug("SnmpIfCollector: ("+m_primaryIf+") sending initial interface SNMP get(Next/Bulk) request PDU for " + m_primaryIf + " with ifIndex: " + m_primaryIfIndex);        session.send(pdu, this);    }    /**     * This method will take an OID, and generate the succeeding OID. This will     * be used for examining responses from SNMPv2 GETBULK packets when doing     * SNMPv2 collection, so that we can keep all the data for a particular     * object, and throw out the rest.     *      * @param oid     *            Object identifier from which to generate the stop oid     *      * @return SnmpObjectId object which represents the oid on which to stop the     *         bulk collection.     */    public static SnmpObjectId stop_oid(String oid) {        // Log4j category        //        Category log = ThreadCategory.getInstance(SnmpIfCollector.class);        SnmpObjectId id = new SnmpObjectId(oid);        int[] ids = id.getIdentifiers();        ++ids[ids.length - 1];        id.setIdentifiers(ids);        if (log.isDebugEnabled())

⌨️ 快捷键说明

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