⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pollerconfigfactory.java

📁 opennms得相关源码 请大家看看
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
//// 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 Nov 11: Merged changes from Rackspace project// 2003 Jan 31: Added code to allow for RRA definitions within poller packages.//// 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.config;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.Reader;import java.io.StringWriter;import java.util.Collections;import java.util.Enumeration;import java.util.HashMap;import java.util.List;import java.util.ArrayList;import java.util.Map;import java.util.TreeMap;import org.apache.log4j.Category;import org.apache.log4j.Priority;import org.exolab.castor.xml.MarshalException;import org.exolab.castor.xml.Marshaller;import org.exolab.castor.xml.Unmarshaller;import org.exolab.castor.xml.ValidationException;import org.opennms.core.utils.ThreadCategory;import org.opennms.netmgt.ConfigFileConstants;import org.opennms.netmgt.config.poller.ExcludeRange;import org.opennms.netmgt.config.poller.IncludeRange;import org.opennms.netmgt.config.poller.Monitor;import org.opennms.netmgt.config.poller.PollerConfiguration;import org.opennms.netmgt.config.poller.Service;import org.opennms.netmgt.filter.Filter;import org.opennms.netmgt.poller.monitors.ServiceMonitor;import org.opennms.netmgt.utils.IPSorter;import org.opennms.netmgt.utils.IpListFromUrl;/** * This is the singleton class used to load the configuration for the OpenNMS * Poller service from the poller-configuration xml file. *  * A mapping of the configured URLs to the iplist they contain is built at * init() time so as to avoid numerous file reads. *  * <strong>Note: </strong>Users of this class should make sure the * <em>init()</em> is called before calling any other method to ensure the * config is loaded before accessing other convenience methods. *  * @author <a href="mailto:jamesz@opennms.com">James Zuo </a> * @author <a href="mailto:mike@opennms.org">Mike Davidson </a> * @author <a href="mailto:sowmya@opennms.org">Sowmya Nataraj </a> * @author <a href="http://www.opennms.org/">OpenNMS </a> */public final class PollerConfigFactory implements PollerConfig {    /**     * The singleton instance of this factory     */    private static PollerConfigFactory m_singleton = null;    /**     * This member is set to true if the configuration file has been loaded.     */    private static boolean m_loaded = false;    /**     * The config class loaded from the config file     */    private PollerConfiguration m_config;    /**     * A mapping of the configured URLs to a list of the specific IPs configured     * in each - so as to avoid file reads     */    private Map m_urlIPMap;    /**     * A mapping of the configured package to a list of IPs selected via filter     * rules, so as to avoid repetetive database access.     */    private Map m_pkgIpMap;    /**     * A mapp of service names to service monitors. Constructed based on data in     * the configuration file.     */    private Map m_svcMonitors = Collections.synchronizedMap(new TreeMap());    /**     * A boolean flag to indicate If a filter rule agaist the local OpenNMS     * server has to be used.     */    private static boolean m_verifyServer;    /**     * The name of the local OpenNMS server     */    private static String m_localServer;    /**     * Go through the poller configuration and build a mapping of each     * configured URL to a list of IPs configured in that URL - done at init()     * time so that repeated file reads can be avoided     */    private void createUrlIpMap() {        m_urlIPMap = new HashMap();        Enumeration pkgEnum = m_config.enumeratePackage();        while (pkgEnum.hasMoreElements()) {            org.opennms.netmgt.config.poller.Package pkg = (org.opennms.netmgt.config.poller.Package) pkgEnum.nextElement();            Enumeration urlEnum = pkg.enumerateIncludeUrl();            while (urlEnum.hasMoreElements()) {                String urlname = (String) urlEnum.nextElement();                java.util.List iplist = IpListFromUrl.parse(urlname);                if (iplist.size() > 0) {                    m_urlIPMap.put(urlname, iplist);                }            }        }    }    /**     * Private constructor     *      * @exception java.io.IOException     *                Thrown if the specified config file cannot be read     * @exception org.exolab.castor.xml.MarshalException     *                Thrown if the file does not conform to the schema.     * @exception org.exolab.castor.xml.ValidationException     *                Thrown if the contents do not match the required schema.     */    private PollerConfigFactory(OpennmsServerConfigFactory serverConfig, Reader reader) throws IOException, MarshalException, ValidationException {        reloadXML(serverConfig, reader);    }    private void reloadXML(OpennmsServerConfigFactory serverConfig, Reader reader) throws MarshalException, ValidationException, IOException {        m_config = (PollerConfiguration) Unmarshaller.unmarshal(PollerConfiguration.class, reader);        reader.close();        createUrlIpMap();        m_verifyServer = serverConfig.verifyServer();        m_localServer = serverConfig.getServerName();        createPackageIpListMap();        createServiceMonitors();    }    /**     * Load the config from the default config file and create the singleton     * instance of this factory.     *      * @exception java.io.IOException     *                Thrown if the specified config file cannot be read     * @exception org.exolab.castor.xml.MarshalException     *                Thrown if the file does not conform to the schema.     * @exception org.exolab.castor.xml.ValidationException     *                Thrown if the contents do not match the required schema.     */    public static synchronized void init() throws IOException, MarshalException, ValidationException {        if (m_loaded) {            // init already called - return            // to reload, reload() will need to be called            return;        }        OpennmsServerConfigFactory.init();        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONFIG_FILE_NAME);        ThreadCategory.getInstance(PollerConfigFactory.class).debug("init: config file path: " + cfgFile.getPath());        m_singleton = new PollerConfigFactory(OpennmsServerConfigFactory.getInstance(), new FileReader(cfgFile));        m_loaded = true;    }    /**     * Reload the config from the default config file     *      * @exception java.io.IOException     *                Thrown if the specified config file cannot be read/loaded     * @exception org.exolab.castor.xml.MarshalException     *                Thrown if the file does not conform to the schema.     * @exception org.exolab.castor.xml.ValidationException     *                Thrown if the contents do not match the required schema.     */    public static synchronized void reload() throws IOException, MarshalException, ValidationException {        init();        getInstance().update();    }    /**     * Saves the current in-memory configuration to disk and reloads     */    public synchronized void saveCurrent() throws MarshalException, IOException, ValidationException {        File cfgFile = ConfigFileConstants.getFile(ConfigFileConstants.POLLER_CONFIG_FILE_NAME);        // marshall to a string first, then write the string to the file. This        // way the original config        // isn't lost if the xml from the marshall is hosed.        StringWriter stringWriter = new StringWriter();        Marshaller.marshal(m_config, stringWriter);        if (stringWriter.toString() != null) {            FileWriter fileWriter = new FileWriter(cfgFile);            fileWriter.write(stringWriter.toString());            fileWriter.flush();            fileWriter.close();        }        update();    }    /**     * Return the singleton instance of this factory.     *      * @return The current factory instance.     *      * @throws java.lang.IllegalStateException     *             Thrown if the factory has not yet been initialized.     */    public static synchronized PollerConfigFactory getInstance() {        if (!m_loaded)            throw new IllegalStateException("The factory has not been initialized");        return m_singleton;    }    /**     * Return the poller configuration object.     */    public synchronized PollerConfiguration getConfiguration() {        return m_config;    }    public synchronized org.opennms.netmgt.config.poller.Package getPackage(String name) {        Enumeration packageEnum = m_config.enumeratePackage();        while (packageEnum.hasMoreElements()) {            org.opennms.netmgt.config.poller.Package thisPackage = (org.opennms.netmgt.config.poller.Package) packageEnum.nextElement();            if (thisPackage.getName().equals(name)) {                return thisPackage;            }        }        return null;    }    /**     * This method is used to determine if the named interface is included in     * the passed package's url includes. If the interface is found in any of     * the URL files, then a value of true is returned, else a false value is     * returned.     *      * <pre>     *      *  The file URL is read and each entry in this file checked. Each line     *   in the URL file can be one of -     *   &lt;IP&gt;&lt;space&gt;#&lt;comments&gt;     *   or     *   &lt;IP&gt;     *   or     *   #&lt;comments&gt;     *       *   Lines starting with a '#' are ignored and so are characters after     *   a '&lt;space&gt;#' in a line.     *       * </pre>     *      * @param addr     *            The interface to test against the package's URL     * @param url     *            The url file to read     *      * @return True if the interface is included in the url, false otherwise.     */    private boolean interfaceInUrl(String addr, String url) {        boolean bRet = false;        // get list of IPs in this URL        java.util.List iplist = (java.util.List) m_urlIPMap.get(url);        if (iplist != null && iplist.size() > 0) {            bRet = iplist.contains(addr);        }        return bRet;    }    /**     * This method returns the boolean flag xmlrpc to indicate if notification     * to external xmlrpc server is needed.     *      * @return true if need to notify an external xmlrpc server     */    public synchronized boolean getXmlrpc() {        String flag = m_config.getXmlrpc();        if (flag.equals("true"))            return true;        else            return false;    }    /**     * This method returns the configured critical service name.     *      * @return the name of the configured critical service, or null if none is     *         present     */    public synchronized String getCriticalService() {        return m_config.getNodeOutage().getCriticalService().getName();    }    /**     * This method returns the configured value of the     * 'pollAllIfNoCriticalServiceDefined' flag.     *      * A value of true causes the poller's node outage code to poll all the     * services on an interface if a status change has occurred and there is no     * critical service defined on the interface.     *      * A value of false causes the poller's node outage code to not poll all the     * services on an interface in this situation.     * </p>     *      * @return true or false based on configured value     */    public synchronized boolean pollAllIfNoCriticalServiceDefined() {        String flag = m_config.getNodeOutage().getPollAllIfNoCriticalServiceDefined();        if (flag.equals("true"))            return true;        else            return false;    }    /**     * Returns true if node outage processing is enabled.     */    public synchronized boolean nodeOutageProcessingEnabled() {        String status = m_config.getNodeOutage().getStatus();        if (status.equals("on"))            return true;        else            return false;    }    /**     * Returns true if serviceUnresponsive behavior is enabled. If enabled a     * serviceUnresponsive event is generated for TCP-based services if the     * service monitor is able to connect to the designated port but times out     * before receiving the expected response. If disabled, an outage will be     * generated in this scenario.     */    public synchronized boolean serviceUnresponsiveEnabled() {        String enabled = m_config.getServiceUnresponsiveEnabled();        if (enabled.equals("true"))            return true;        else            return false;    }    /**     * This method is used to establish package agaist iplist mapping, with     * which, the iplist is selected per package via the configured filter rules     * from the database.     */    private void createPackageIpListMap() {        Category log = ThreadCategory.getInstance(this.getClass());        m_pkgIpMap = new HashMap();        Enumeration pkgEnum = m_config.enumeratePackage();        while (pkgEnum.hasMoreElements()) {            org.opennms.netmgt.config.poller.Package pkg = (org.opennms.netmgt.config.poller.Package) pkgEnum.nextElement();            //            // Get a list of ipaddress per package agaist the filter rules from            // database and populate the package, IP list map.            //            Filter filter = new Filter();            StringBuffer filterRules = new StringBuffer(pkg.getFilter().getContent());            try {                if (m_verifyServer) {                    filterRules.append(" & (serverName == ");                    filterRules.append('\"');                    filterRules.append(m_localServer);

⌨️ 快捷键说明

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