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

📄 agentconfigmanager.java

📁 用snmp4j实现的agent,代码比较多,但是很值得一看,尤其是对于要用SNMP监控信息的编程者,可以仔细研究一下里面的代码.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
        String txt = "Failed to load agent state: "+ex.getMessage();
        logger.error(txt, ex);
        runState.addError(new ErrorDescriptor(txt, runState.getState(),
                                              STATE_RESTORED, ex));
      }
    }
    return false;
  }

  /**
   * Configures components and managed objects.
   */
  public void configure() {
    if (configuration != null) {
      MOInput config = configuration.createMOInput();
      if (config == null) {
        logger.debug("No configuration returned by configuration factory "+
                     configuration);
        return;
      }
      MOServerPersistence serverPersistence = new MOServerPersistence(servers);
      try {
        serverPersistence.loadData(config);
      }
      catch (IOException ex) {
        String txt = "Failed to load agent configuration: "+ex.getMessage();
        logger.error(txt, ex);
        runState.addError(new ErrorDescriptor(txt, runState.getState(),
                                              STATE_CONFIGURED, ex));
        throw new RuntimeException(txt, ex);
      }
      finally {
        try {
          config.close();
        }
        catch (IOException ex1) {
          logger.warn("Failed to close config input stream: "+ex1.getMessage());
        }
      }
    }
    runState.advanceState(STATE_CONFIGURED);
  }

  protected void initMandatoryMIBs() {
    targetMIB = new SnmpTargetMIB(dispatcher);
    targetMIB.addDefaultTDomains();
    snmpv2MIB = new SNMPv2MIB(getSysDescr(), getSysOID(), getSysServices());
    notificationMIB = new SnmpNotificationMIB();
    vacmMIB = new VacmMIB(servers);
    usmMIB = new UsmMIB(usm, getSupportedSecurityProtocols());
    communityMIB = new SnmpCommunityMIB(targetMIB);
  }

  protected void linkCounterListener() {
    agent.removeCounterListener(snmpv2MIB);
    agent.addCounterListener(snmpv2MIB);
    usm.getCounterSupport().removeCounterListener(snmpv2MIB);
    usm.getCounterSupport().addCounterListener(snmpv2MIB);
  }

  /**
   * Gets the set of security protocols supported by this agent configuration.
   *
   * @return
   *    {@link SecurityProtocols#getInstance()} by default after initialization
   *    by {@link SecurityProtocols#addDefaultProtocols()}.
   */
  protected SecurityProtocols getSupportedSecurityProtocols() {
    SecurityProtocols.getInstance().addDefaultProtocols();
    return SecurityProtocols.getInstance();
  }

  /**
   * Creates the USM used by this agent configuration.
   *
   * @return
   *    an USM initialized by the engine boots from the
   *    <code>engineBootsProvider</code> and <code>engineID</code>.
   */
  protected USM createUSM() {
    return new USM(getSupportedSecurityProtocols(), engineID,
                   engineBootsProvider.updateEngineBoots());
  }

  /**
   * Gets the system services ID which can be modified by altering its value.
   *
   * @return
   *    72 by default.
   */
  public Integer32 getSysServices() {
    return sysServices;
  }

  /**
   * Gets the system OID which can be modified by altering its value.
   *
   * @return
   *    an OID - by default the SNMP4J root OID is returned.
   */
  public OID getSysOID() {
    return sysOID;
  }

  /**
   * Returns the sysDescr.0 value for this agent which can be modified by
   * altering its value.
   *
   * @return
   *    an OctetString describing the node of the form
   *    <pre>SNMP4J-Agent version [SNMP4J-version] -
   *         <os.name> - <os.arch> - <os.version></pre>.
   */
  public OctetString getSysDescr() {
    return sysDescr;
  }

  /**
   * Gets the sysUpTime.0 instance for the default context.
   *
   * @return
   *    a <code>SysUpTime</code> instance.
   */
  public SysUpTime getSysUpTime() {
    return snmpv2MIB.getSysUpTime();
  }

  /**
   * Gets the notification originator of this agent configuration.
   * @return
   *    a <code>NotificationOriginator</code> instance.
   */
  public NotificationOriginator getNotificationOriginator() {
    return notificationOriginator;
  }

  /**
   * Sets the notification originator of this agent configuration.
   * @param notificationOriginator
   *    a <code>NotificationOriginator</code> instance.
   */
  public void setNotificationOriginator(NotificationOriginator notificationOriginator) {
    this.notificationOriginator = notificationOriginator;
    if (agent != null) {
      agent.setNotificationOriginator(notificationOriginator);
    }
  }

  public void initialize() {
    session = createSnmpSession(dispatcher);
    if (engineID == null) {
      engineID = new OctetString(MPv3.createLocalEngineID());
    }
    agent = createCommandProcessor(engineID);
    agent.setWorkerPool(workerPool);
    initSecurityModels(engineBootsProvider);
    initMessageDispatcherWithMPs(dispatcher);
    initMandatoryMIBs();
    linkCounterListener();
    // use VACM-MIB as VACM by default
    if (vacm == null) {
      vacm = vacmMIB;
    }
    agent.setVacm(vacm);
    for (int i=0; i<servers.length; i++) {
      agent.addMOServer(servers[i]);
    }
    agent.setCoexistenceProvider(communityMIB);
    if (notificationOriginator == null) {
      notificationOriginator = createNotificationOriginator();
    }
    agent.setNotificationOriginator(notificationOriginator);
    snmpv2MIB.setNotificationOriginator(notificationOriginator);

    initOptionalMIBs();

    try {
      registerMIBs(getDefaultContext());
    }
    catch (DuplicateRegistrationException drex) {
      logger.error("Duplicate MO registration: "+drex.getMessage(), drex);
    }
    runState.advanceState(STATE_INITIALIZED);
  }

  protected void initOptionalMIBs() {
    initSnmp4jLogMIB();
    initSnmp4jConfigMIB(null);
  }

  /**
   * Returns the default context - which is the context that is used by the
   * base agent to register its MIB objects. By default it is <code>null</code>
   * which causes the objects to be registered virtually for all contexts.
   * In that case, subagents for example my not register their own objects
   * under the same subtree(s) in any context. To allow subagents to register
   * their own instances of those MIB modules, an empty <code>OctetString</code>
   * should be used as default context instead.
   * @return
   *    <code>null</code> or an <code>OctetString</code> (normally the empty
   *    string) denoting the context used for registering default MIBs.
   */
  public OctetString getDefaultContext() {
    return defaultContext;
  }

  /**
   * This method can be overwritten by a subagent to specify the contexts
   * each MIB module (group) will be registered to.
   *
   * @param mibGroup
   *    a group of {@link ManagedObject}s (i.e., a MIB module).
   * @param defaultContext
   *    the context to be used by default (i.e., the <code>null</code> context)
   * @return
   *    the context for which the module should be registered.
   */
  protected OctetString getContext(MOGroup mibGroup,
                                   OctetString defaultContext) {
    return defaultContext;
  }


  /**
   * Register the initialized MIB modules in the specified context of the agent.
   * @param context
   *    the context to register the internal MIB modules. This should be
   *    <code>null</code> by default.
   * @throws DuplicateRegistrationException if some of the MIB modules
   * registration regions conflict with already registered regions.
   */
  protected void registerMIBs(OctetString context) throws
      DuplicateRegistrationException
  {
    MOServer server = agent.getServer(context);
    targetMIB.registerMOs(server, getContext(targetMIB, context));
    notificationMIB.registerMOs(server, getContext(notificationMIB, context));
    vacmMIB.registerMOs(server, getContext(vacmMIB, context));
    usmMIB.registerMOs(server, getContext(usmMIB, context));
    snmpv2MIB.registerMOs(server, getContext(snmpv2MIB, context));
    frameworkMIB.registerMOs(server, getContext(frameworkMIB, context));
    communityMIB.registerMOs(server, getContext(communityMIB, context));
    if (snmp4jLogMIB != null) {
      snmp4jLogMIB.registerMOs(server, getContext(snmp4jLogMIB, context));
    }
    if (snmp4jConfigMIB != null) {
      snmp4jConfigMIB.registerMOs(server, getContext(snmp4jConfigMIB, context));
    }
    if (proxyMIB != null) {
      proxyMIB.registerMOs(server, getContext(proxyMIB, context));
    }
  }

  /**
   * Unregister the initialized MIB modules from the default context of the
   * agent.
   * @param context
   *    the context where the MIB modules have been previously registered.
   */
  protected void unregisterMIBs(OctetString context) {
    MOServer server = agent.getServer(context);
    targetMIB.unregisterMOs(server, getContext(targetMIB, context));
    notificationMIB.unregisterMOs(server, getContext(notificationMIB, context));
    vacmMIB.unregisterMOs(server, getContext(vacmMIB, context));
    usmMIB.unregisterMOs(server, getContext(usmMIB, context));
    snmpv2MIB.unregisterMOs(server, getContext(snmpv2MIB, context));
    frameworkMIB.unregisterMOs(server, getContext(frameworkMIB, context));
    communityMIB.unregisterMOs(server, getContext(communityMIB, context));
    if (snmp4jLogMIB != null) {
      snmp4jLogMIB.unregisterMOs(server, getContext(snmp4jLogMIB, context));
    }
    if (snmp4jConfigMIB != null) {
      snmp4jConfigMIB.unregisterMOs(server, getContext(targetMIB, context));
    }
    if (proxyMIB != null) {
      proxyMIB.unregisterMOs(server, getContext(proxyMIB, context));
    }
  }

  public void setupProxyForwarder() {
    proxyForwarder = createProxyForwarder(agent);
  }

  protected NotificationOriginator createNotificationOriginator() {
    return new NotificationOriginatorImpl(session, vacm,
                                          snmpv2MIB.getSysUpTime(),
                                          targetMIB, notificationMIB);
  }

  /**
   * Creates and registers the default proxy forwarder application
   * ({@link ProxyForwarderImpl}).
   * @param agent
   *    the command processor that uses the proxy forwarder.
   * @return
   *    a ProxyForwarder instance.
   */
  protected ProxyForwarder createProxyForwarder(CommandProcessor agent) {
    proxyMIB = new SnmpProxyMIB();
    ProxyForwarderImpl pf =
        new ProxyForwarderImpl(session, proxyMIB, targetMIB);
    agent.addProxyForwarder(pf,
                            null, ProxyForwarder.PROXY_TYPE_ALL);
    pf.addCounterListener(snmpv2MIB);
    return proxyForwarder;
  }


  /**
   * Creates the command processor.
   *
   * @param engineID
   *    the engine ID of the agent.
   * @return
   *    a new CommandProcessor instance.
   */
  protected CommandProcessor createCommandProcessor(OctetString engineID) {
    return new CommandProcessor(engineID);
  }

  /**
   * Creates the SNMP session to be used for this agent.
   *
   * @param dispatcher
   *    the message dispatcher to be associated with the session.
   * @return
   *    a SNMP session (a {@link Snmp} instance by default).
   */
  protected Session createSnmpSession(MessageDispatcher dispatcher) {
    return new Snmp(dispatcher);
  }

  public class AgentState {
    private int state = STATE_CREATED;
    /**
     * Contains a list of ErrorDescription objects describing errors occured
     * since agent launched for the first time.
     */
    private List errorsOccured = new LinkedList();

    public int getState() {
      return state;
    }

    void setState(int newState) {
      this.state = newState;
      logger.info("Agent state set to "+newState);
    }

    void advanceState(int newState) {
      if (state < newState) {
        state = newState;
        logger.info("Agent state advanced to "+newState);
      }
    }

    void addError(ErrorDescriptor error) {
      errorsOccured.add(error);
    }

    public List getErrors() {
      return new ArrayList(errorsOccured);
    }
  }

  static class ErrorDescriptor {
    private Exception exception;
    private int sourceState;
    private int targetState;
    private String description;

    ErrorDescriptor(String descr, int sourceState, int targetState,
                    Exception ex) {
      this.description = descr;
      this.sourceState = sourceState;
      this.targetState = targetState;
      this.exception = ex;
    }

    public String getDescription() {
      return description;
    }

    public int getSourceState() {
      return sourceState;
    }

    public int getTargetState() {
      return targetState;
    }

    public Exception getException() {
      return exception;
    }
  }
}

⌨️ 快捷键说明

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