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

📄 baseagent.java

📁 用snmp4j实现的agent,代码比较多,但是很值得一看,尤其是对于要用SNMP监控信息的编程者,可以仔细研究一下里面的代码.
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
   * Stops the agent by closing the SNMP session and associated transport
   * mappings.
   * @since 1.1
   */
  public void stop() {
    if (agentState != STATE_RUNNING) {
      logger.error("Agent is stopped although it is not running, "+
                   "current state is "+agentState);
    }
    try {
      session.close();
    }
    catch (IOException ex) {
      logger.warn("Closing agent session threw IOException: "+ex.getMessage());
    }
    session = null;
    agentState = STATE_STOPPED;
  }

  /**
   * Initializes the message dispatcher ({@link MessageDispatcherImpl}) with
   * the transport mappings.
   */
  protected void initMessageDispatcher() {
    dispatcher = new MessageDispatcherImpl();
    mpv3 = new MPv3(agent.getContextEngineID().getValue());
    usm = new USM(SecurityProtocols.getInstance(),
                  agent.getContextEngineID(),
                  updateEngineBoots());
    SecurityModels.getInstance().addSecurityModel(usm);
    SecurityProtocols.getInstance().addDefaultProtocols();
    dispatcher.addMessageProcessingModel(new MPv1());
    dispatcher.addMessageProcessingModel(new MPv2c());
    dispatcher.addMessageProcessingModel(mpv3);
    initSnmpSession();
  }

  protected void initSnmpSession() {
    session = new Snmp(dispatcher);
    for (int i=0; i<transportMappings.length; i++) {
      try {
        session.addTransportMapping(transportMappings[i]);
      }
      catch (Exception ex) {
        logger.warn("Failed to initialize transport mapping '"+
                    transportMappings[i]+"' with: "+ex.getMessage());
      }
    }
    updateSession(session);
  }

  /**
   * Updates all objects with a new session instance. This method must be
   * overwritten, if non-default SNMP MIB instances are created by a subclass.
   * @param session
   *    a SNMP Session instance.
   */
  protected void updateSession(Session session) {
    if (notificationOriginator instanceof NotificationOriginatorImpl) {
      ((NotificationOriginatorImpl)notificationOriginator).setSession(session);
    }
    if (defaultProxyForwarder instanceof ProxyForwarderImpl) {
      ((ProxyForwarderImpl)defaultProxyForwarder).setSession(session);
    }
  }

  /**
   * Updates the engine boots counter and returns the actual value.
   * @return
   *    the actual boots counter value.
   */
  protected int updateEngineBoots() {
    int boots = getEngineBoots();
    boots++;
    if (boots <= 0) {
      boots = 1;
    }
    setEngineBoots(boots);
    return boots;
  }

  /**
   * Reads the engine boots counter from the corresponding input stream (file).
   * @return
   *    the boots counter value read or zero if it could not be read.
   */
  protected int getEngineBoots() {
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(bootCounterFile);
      ObjectInputStream ois = new ObjectInputStream(fis);
      int boots = ois.readInt();
      if (logger.isInfoEnabled()) {
        logger.info("Engine boots is: "+boots);
      }
      return boots;
    }
    catch (FileNotFoundException ex) {
      logger.warn("Could not find boot counter file: "+bootCounterFile);
    }
    catch (IOException iox) {
      if (logger.isDebugEnabled()) {
        iox.printStackTrace();
      }
      logger.error("Failed to read boot counter: "+iox.getMessage());
    }
    finally {
      if (fis != null) {
        try {
          fis.close();
        }
        catch (IOException ex1) {
          logger.warn(ex1);
        }
      }
    }
    return 0;
  }

  protected void setEngineBoots(int engineBoots) {
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(bootCounterFile);
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeInt(engineBoots);
      oos.close();
      if (logger.isInfoEnabled()) {
        logger.info("Wrote boot counter: " + engineBoots);
      }
    }
    catch (FileNotFoundException fnfex) {
      logger.error("Boot counter configuration file not found: "+
                   fnfex.getMessage());
    }
    catch (IOException iox) {
      logger.error("Failed to write boot counter: "+iox.getMessage());
    }
    finally {
      if (fos != null) {
        try {
          fos.close();
        }
        catch (IOException ex1) {
          logger.warn(ex1);
        }
      }
    }
  }

  /**
   * Adds all the necessary initial users to the USM.
   * @param usm
   *    the USM instance used by this agent.
   */
  protected abstract void addUsmUser(USM usm);

  /**
   * Adds initial notification targets and filters.
   * @param targetMIB
   *    the SnmpTargetMIB holding the target configuration.
   * @param notificationMIB
   *    the SnmpNotificationMIB holding the notification (filter)
   *    configuration.
   */
  protected abstract void addNotificationTargets(SnmpTargetMIB targetMIB,
                                                 SnmpNotificationMIB notificationMIB);

  /**
   * Adds initial VACM configuration.
   * @param vacmMIB
   *    the VacmMIB holding the agent's view configuration.
   */
  protected abstract void addViews(VacmMIB vacmMIB);

  /**
   * Adds community to security name mappings needed for SNMPv1 and SNMPv2c.
   * @param communityMIB
   *    the SnmpCommunityMIB holding coexistence configuration for community
   *    based security models.
   */
  protected abstract void addCommunities(SnmpCommunityMIB communityMIB);

  /**
   * Initializes the transport mappings (ports) to be used by the agent.
   * @throws IOException
   */
  protected void initTransportMappings() throws IOException {
    transportMappings = new TransportMapping[1];
    transportMappings[0] =
        new DefaultUdpTransportMapping(new UdpAddress("0.0.0.0/161"));
  }

  public NotificationOriginator getNotificationOriginator() {
    return notificationOriginator;
  }

  public void setDefaultProxyForwarder(ProxyForwarder defaultProxyForwarder) {
    this.defaultProxyForwarder = defaultProxyForwarder;
  }

  public void setSysDescr(OctetString sysDescr) {
    this.sysDescr.setValue(sysDescr.getValue());
  }

  public void setSysOID(OID sysOID) {
    this.sysOID.setValue(sysOID.getValue());
  }

  public void setSysServices(Integer32 sysServices) {
    this.sysServices.setValue(sysServices.getValue());
  }

  public void setAgent(CommandProcessor agent) {
    this.agent = agent;
  }

  public void setBootCounterFile(File bootCounterFile) {
    this.bootCounterFile = bootCounterFile;
  }

  public void setConfigFile(File configFile) {
    this.configFileURI = configFile.getPath();
  }

  /**
   * Sets the default context for this base agent. By setting this value before
   * any MIB modules have been registered at the internal server, the context
   * for which the registration is performed can be changed. The default context
   * is <code>null</code> which causes MIB objects to be virtually registered
   * for all contexts.
   *
   * @param defaultContext
   *    the context for default MIB objects.
   * @since 1.1
   */
  public void setDefaultContext(OctetString defaultContext) {
    this.defaultContext = defaultContext;
  }

  public ProxyForwarder getDefaultProxyForwarder() {
    return defaultProxyForwarder;
  }

  public OctetString getSysDescr() {
    return sysDescr;
  }

  public OID getSysOID() {
    return sysOID;
  }

  public Integer32 getSysServices() {
    return sysServices;
  }

  public CommandProcessor getAgent() {
    return agent;
  }

  public File getBootCounterFile() {
    return bootCounterFile;
  }

  public File getConfigFile() {
    return new File(configFileURI);
  }

  public Snmp4jConfigMib getSnmp4jConfigMIB() {
    return snmp4jConfigMIB;
  }

  public Snmp4jLogMib getSnmp4jLogMIB() {
    return snmp4jLogMIB;
  }

  public SnmpCommunityMIB getSnmpCommunityMIB() {
    return snmpCommunityMIB;
  }

  public SnmpFrameworkMIB getSnmpFrameworkMIB() {
    return snmpFrameworkMIB;
  }

  public SnmpNotificationMIB getSnmpNotificationMIB() {
    return snmpNotificationMIB;
  }

  public SnmpProxyMIB getSnmpProxyMIB() {
    return snmpProxyMIB;
  }

  public SnmpTargetMIB getSnmpTargetMIB() {
    return snmpTargetMIB;
  }

  public SNMPv2MIB getSnmpv2MIB() {
    return snmpv2MIB;
  }

  public UsmMIB getUsmMIB() {
    return usmMIB;
  }

  public VacmMIB getVacmMIB() {
    return vacmMIB;
  }

  public Snmp getSession() {
    return session;
  }

  public DefaultMOServer getServer() {
    return server;
  }

  public MPv3 getMPv3() {
    return mpv3;
  }

  public USM getUsm() {
    return usm;
  }

  /**
   * Returns the agent's state.
   * @return
   *    one of the state's starting from {@link #STATE_CREATED} to
   *    {@link #STATE_RUNNING}.
   * @since 1.1
   */
  public int getAgentState() {
    return agentState;
  }

  /**
   * 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.
   * @since 1.1
   */
  public OctetString getDefaultContext() {
    return defaultContext;
  }
}

⌨️ 快捷键说明

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