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

📄 commandprocessor.java

📁 你个snmp的源码
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/*_############################################################################
  _##
  _##  SNMP4J-Agent - CommandProcessor.java
  _##
  _##  Copyright 2005-2006  Frank Fock (SNMP4J.org)
  _##
  _##  Licensed under the Apache License, Version 2.0 (the "License");
  _##  you may not use this file except in compliance with the License.
  _##  You may obtain a copy of the License at
  _##
  _##      http://www.apache.org/licenses/LICENSE-2.0
  _##
  _##  Unless required by applicable law or agreed to in writing, software
  _##  distributed under the License is distributed on an "AS IS" BASIS,
  _##  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  _##  See the License for the specific language governing permissions and
  _##  limitations under the License.
  _##
  _##########################################################################*/


package org.snmp4j.agent;

import java.util.*;

import org.snmp4j.*;
import org.snmp4j.agent.request.*;
import org.snmp4j.agent.security.*;
import org.snmp4j.event.*;
import org.snmp4j.mp.*;
import org.snmp4j.smi.*;
import org.snmp4j.util.*;
import org.snmp4j.agent.util.TemporaryList;
import org.snmp4j.agent.mo.snmp.CoexistenceInfo;
import org.snmp4j.agent.mo.snmp.CoexistenceInfoProvider;
import org.snmp4j.log.LogAdapter;
import org.snmp4j.log.LogFactory;

/**
 * The <code>CommandProcessor</code> is the central glue code that puts together
 * the various sub-systems of a SNMP agent.
 *
 * @author Frank Fock
 * @version 1.0
 */
public class CommandProcessor
    implements CommandResponder, NotificationOriginator {

  private static final LogAdapter logger =
      LogFactory.getLogger(CommandProcessor.class);

  protected ThreadPool threadPool = null;
  protected VACM vacm = null;
  protected Vector moServers;
  protected OctetString ownContextEngineID;
  protected Vector pduHandler;
  protected TemporaryList requestList;
  protected RequestFactory requestFactory;
  protected NotificationOriginator notificationOriginator;
  protected ProxyMap proxyForwarder;
  protected CoexistenceInfoProvider coexistenceProvider;

  private transient Vector counterListeners;

  public CommandProcessor(OctetString contextEngineID) {
    this.ownContextEngineID = contextEngineID;
    moServers = new Vector();
    requestList = new TemporaryList();
    pduHandler = new Vector();
    pduHandler.add(new GetHandler());
    pduHandler.add(new GetNextHandler());
    pduHandler.add(new SetHandler());
    pduHandler.add(new GetBulkHandler());
    requestFactory = new DefaultRequestFactory();
  }

  public void processPdu(CommandResponderEvent event) {
    if (event.getPDU() != null) {
      CoexistenceInfo cinfo = null;
      OctetString sname = new OctetString(event.getSecurityName());
      if (event.getPDU() instanceof ScopedPDU) {
        ScopedPDU spdu = (ScopedPDU)event.getPDU();
        cinfo = new CoexistenceInfo(sname,
                                    spdu.getContextEngineID(),
                                    spdu.getContextName());
      }
      else if (coexistenceProvider != null) {
        cinfo = coexistenceProvider.getCoexistenceInfo(sname);
        if (cinfo != null) {
          if (!coexistenceProvider.passesFilter(event.getPeerAddress(),
                                                cinfo)) {
            logger.warn("Access attempt from "+event.getPeerAddress()+
                        " denied because of source address filtering");

            fireIncrementCounter(
                new CounterEvent(this,
                                 SnmpConstants.snmpInBadCommunityNames));
            return;
          }
          event.setMaxSizeResponsePDU(cinfo.getMaxMessageSize());
        }
        else {
          if (logger.isInfoEnabled()) {
            logger.info("Community name '"+sname+
                        "' not found in SNMP-COMMUNITY-MIB");
          }
          fireIncrementCounter(
              new CounterEvent(this,
                               SnmpConstants.snmpInBadCommunityNames));
          return;
        }
      }
      if ((cinfo == null) ||
          (ownContextEngineID.equals(cinfo.getContextEngineID()))) {
        event.setProcessed(true);
        Command command = new Command(event, cinfo);
        if (threadPool != null) {
          threadPool.execute(command);
        }
        else {
          command.run();
        }
      }
      else if (proxyForwarder != null) {
        ProxyForwardRequest request =
            new ProxyForwardRequest(event,
                                    cinfo.getContextEngineID(),
                                    cinfo.getContextName());
        ProxyForwarder proxy =
            proxyForwarder.get(cinfo.getContextEngineID(),
                               request.getProxyType());
        ProxyCommand command = new ProxyCommand(proxy, request);
        if (proxy != null) {
          if (logger.isDebugEnabled()) {
            logger.debug("Processsing proxy request with proxy forwarder "+
                         proxy);
          }
          if (threadPool != null) {
            threadPool.execute(command);
          }
          else {
            command.run();
          }
        }
        else {
          fireIncrementCounter(new CounterEvent(this,
                                                SnmpConstants.snmpProxyDrops));
        }
      }
      else {
        fireIncrementCounter(new CounterEvent(this,
                                              SnmpConstants.snmpSilentDrops));
      }
    }
  }

  public void setThreadPool(ThreadPool threadPool) {
    this.threadPool = threadPool;
  }

  public VACM getVacm() {
    return vacm;
  }

  public void setVacm(VACM vacm) {
    this.vacm = vacm;
  }
  public OctetString getContextEngineID() {
    return ownContextEngineID;
  }
  public void setContextEngineID(OctetString contextEngineID) {
    this.ownContextEngineID = contextEngineID;
  }

  /**
   * Sends notification/inform messages to all registered targets. This method
   * uses the internal {@link ThreadPool} to send the message(s) via the
   * <code>NotificationOriginator</code>
   * (see {@link #getNotificationOriginator}) to the targets specified by the
   * SnmpTargetMIB and SnmpNotificationMIB instances supplied to the
   * notification originator.
   *
   * @param context
   *    the context name of the context on whose behalf this notification has
   *    been generated.
   * @param notificationID
   *    the object ID that uniquely identifies this notification. For SNMPv1
   *    traps, the notification ID has to be build using the rules provided
   *    by RFC 2576.
   * @param vbs
   *    an array of <code>VariableBinding</code> instances representing the
   *    payload of the notification.
   * @return
   *    an array of ResponseEvent instances or NotificationTask instance if
   *    the notification has been send asynchronously. Since the
   *    <code>NotificationOriginator</code> determines on behalf of the
   *    SNMP-NOTIFICTON-MIB contents whether a notification is sent as
   *    trap/notification or as inform request, the returned array will contain
   *    an element for each addressed target, but only a response PDU for
   *    inform targets.
   *    <p>
   *    <code>null</code> will be returned when sending the notification failed
   *    because there is no {@link NotificationOriginator} set.
   *    <p>
   *    NOTE: If this command processor is using a ThreadPool then the returned
   *    object will be {@link NotificationTask} instance. If all response have
   *    been received {@link Object#notify()} will be called on the returned
   *    <code>NotificationTask</code> object by the sending thread.
   */
  public Object notify(final OctetString context,
                       final OID notificationID,
                       final VariableBinding[] vbs) {
    return notify(context, notificationID, null, vbs);
  }

  public Object notify(OctetString context, OID notificationID,
                       TimeTicks sysUpTime, VariableBinding[] vbs) {
    if (notificationOriginator != null) {
      NotificationTask notifyTask =
          new NotificationTask(notificationOriginator,
                               context, notificationID,
                               sysUpTime, vbs);
      if (threadPool != null) {
        threadPool.execute(notifyTask);
        return notifyTask;
      }
      else {
        notifyTask.run();
        return notifyTask.getResponses();
      }
    }
    else {
      logger.warn("Could not sent notification '"+notificationID+"'="+
                  Arrays.asList(vbs)+" because NotificationOriginator not set");
    }
    return null;
  }


  public void setNotificationOriginator(NotificationOriginator
                                        notificationOriginator) {
    this.notificationOriginator = notificationOriginator;
  }

  public void setCoexistenceProvider(CoexistenceInfoProvider
                                     coexistenceProvider) {
    this.coexistenceProvider = coexistenceProvider;
  }

  public ProxyForwarder addProxyForwarder(ProxyForwarder proxyForwarder,
                                          OctetString contextEngineID,
                                          int proxyType) {
    if (this.proxyForwarder == null) {
      this.proxyForwarder = new ProxyMap();
    }
    return this.proxyForwarder.add(proxyForwarder, contextEngineID, proxyType);
  }

  public ProxyForwarder removeProxyForwarder(OctetString contextEngineID,
                                          int proxyType) {
    if (proxyForwarder != null) {
      return proxyForwarder.remove(contextEngineID, proxyType);
    }
    return null;
  }

  protected RequestHandler getHandler(int pduType) {
    synchronized (pduHandler) {
      for (int i = 0; i < pduHandler.size(); i++) {
        RequestHandler handler = (RequestHandler) pduHandler.get(i);
        if (handler.isSupported(pduType)) {
          return handler;
        }
      }
    }
    return null;
  }

  protected void dispatchCommand(CommandResponderEvent command,
                                 CoexistenceInfo cinfo) {
    RequestHandler handler = getHandler(command.getPDU().getType());
    if (handler != null) {
      processRequest(command, cinfo, handler);
    }
    else {
      /**@todo send report */
    }
  }

  protected void processRequest(CommandResponderEvent command,
                                CoexistenceInfo cinfo, RequestHandler handler) {
    Request req = requestFactory.createRequest(command, cinfo);
    requestList.add(req);

    MOServer server = null;
    OctetString context = req.getContext();
    OctetString viewName = getViewName(command, context, req.getViewType());
    if (viewName == null) {
      setAuthorizationError(req, VACM.VACM_NO_SUCH_VIEW);
    }
    else {
      req.setViewName(viewName);
      server = getServer(context);
      processRequest(server, handler, req);
    }
    finalizeRequest(command, req, server);
  }

  protected void reprocessRequest(MOServer server, SnmpRequest req) {
    RequestHandler handler =
        getHandler(req.getInitiatingEvent().getPDU().getType());
    if (handler != null) {
      req.resetProcessedStatus();
      req.incReprocessCounter();
      processRequest(server, handler, req);
    }
    else {
      logger.error("No PDU handler found for request "+req);
      /**@todo send report*/
    }
  }

  /**
   * Processs (or re-process) a request and try to complete the request (thus
   * to complete any incomplete subrequests).
   *
   * @param server
   *    the <code>MOServer</code> instance to use for accessing instrumentation.
   * @param handler
   *    the <code>RequestHandler</code> to use to process the request.
   * @param req
   *    the <code>Request</code>.
   */
  protected void processRequest(MOServer server,

⌨️ 快捷键说明

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