Beispiel #1
0
  private void requestAndVerifyResponse(int pduType, int version) throws Exception {
    PDU pdu = createPDU(version);

    for (AnticipatedRequest a : m_requestedVarbinds) {
      pdu.add(a.getRequestVarbind());
    }
    pdu.setType(pduType);

    PDU response = sendRequest(pdu, version);

    assertNotNull("request timed out", response);
    System.err.println("Response is: " + response);
    assertTrue(
        "unexpected report pdu: "
            + ((VariableBinding) response.getVariableBindings().get(0)).getOid(),
        response.getType() != PDU.REPORT);

    assertEquals(
        "Unexpected number of varbinds returned.",
        m_requestedVarbinds.size(),
        response.getVariableBindings().size());

    for (int i = 0; i < m_requestedVarbinds.size(); i++) {
      AnticipatedRequest a = m_requestedVarbinds.get(i);
      VariableBinding vb = response.get(i);
      a.verify(vb);
    }

    reset();
  }
Beispiel #2
0
 private boolean processWalk(PDU response, PDU request, OID rootOID) throws SnmpException {
   if ((response == null)
       || (response.getErrorStatus() != 0)
       || (response.getType() == PDU.REPORT)) {
     return true;
   }
   boolean finished = false;
   OID lastOID = request.get(0).getOid();
   for (int i = 0; (!finished) && (i < response.size()); i++) {
     VariableBinding vb = response.get(i);
     if ((vb.getOid() == null)
         || (vb.getOid().size() < rootOID.size())
         || (rootOID.leftMostCompare(rootOID.size(), vb.getOid()) != 0)) {
       finished = true;
     } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
       outputResponse(vb);
       finished = true;
     } else if (vb.getOid().compareTo(lastOID) <= 0) {
       throw new SnmpException(
           "Variable received is not lexicographic successor of requested one:"
               + vb.toString()
               + " <= "
               + lastOID);
     } else {
       outputResponse(vb);
       lastOID = vb.getOid();
     }
   }
   if (response.size() == 0) {
     finished = true;
   }
   if (!finished) {
     VariableBinding next = response.get(response.size() - 1);
     next.setVariable(new Null());
     request.set(0, next);
     request.setRequestID(new Integer32(0));
   }
   return finished;
 }
Beispiel #3
0
  public void processPdu(CommandResponderEvent pRequest) {

    final PDU requestPdu = pRequest.getPDU();

    if (requestPdu == null) {
      return;
    }

    try {

      final PDU responsePdu = new PDU(requestPdu);
      responsePdu.setType(PDU.RESPONSE);

      if (requestPdu.getType() == PDU.GET) {

        for (VariableBinding binding : responsePdu.toArray()) {
          final OID oid = binding.getOid();
          final String path = jmxMib.getPathFromOid(oid.toString());

          if (path == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final JmxAttribute attribute = jmxIndex.getAttributeAtPath(path);

          if (attribute == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final Variable variable = getVariableFromJmxAttribute(attribute);

          if (variable != null) {
            binding.setVariable(variable);
          }
        }

      } else if (requestPdu.getType() == PDU.GETNEXT) {

        for (VariableBinding binding : responsePdu.toArray()) {
          final OID oid = binding.getOid();
          final String next = jmxMib.getNextOidFromOid(oid.toString());

          if (next == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final OID nextOid = new OID(next);

          binding.setOid(nextOid);

          final String path = jmxMib.getPathFromOid(nextOid.toString());

          if (path == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final JmxAttribute attribute = jmxIndex.getAttributeAtPath(path);

          if (attribute == null) {
            binding.setVariable(Null.noSuchObject);
            continue;
          }

          final Variable variable = getVariableFromJmxAttribute(attribute);

          if (variable != null) {
            binding.setVariable(variable);
          }
        }

      } else {

      }

      pRequest.getStateReference().setTransportMapping(pRequest.getTransportMapping());
      pRequest
          .getMessageDispatcher()
          .returnResponsePdu(
              pRequest.getMessageProcessingModel(),
              pRequest.getSecurityModel(),
              pRequest.getSecurityName(),
              pRequest.getSecurityLevel(),
              responsePdu,
              pRequest.getMaxSizeResponsePDU(),
              pRequest.getStateReference(),
              new StatusInformation());

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  /** {@inheritDoc} */
  public PDU processPdu(PDU pdu) throws SnmpToolkitException {
    Log log = LogFactory.getLog(this.getClass());

    // 応答用のPDUを生成する
    PDU retPdu = new PDU();
    retPdu.setType(PDU.RESPONSE);

    // 要求のリクエストIDを取得し、応答PDUにセットする
    Integer32 requestID = pdu.getRequestID();
    retPdu.setRequestID(requestID);

    // SNMP4J用の型変換オブジェクト
    SnmpVariableHelper varHelper = new Snmp4jVariableHelper();

    // AgentServiceからAgentを取得する
    Agent agent = this.agentService_.getAgent();

    // 要求PDUのVarbindを走査する
    int varCount = 0;
    List<?> reqVarbinds = pdu.getVariableBindings();
    for (Object reqVarbindObj : reqVarbinds) {
      varCount++;

      // 要求されているOIDを取得する
      VariableBinding reqVarbind = (VariableBinding) reqVarbindObj;
      OID oid = reqVarbind.getOid();

      // GETNEXTでない場合は、指定されたOIDそのものを取得しようとする
      // GETNEXTの場合は、指定されたOID配下で最も近いオブジェクトを探す
      boolean exact = (pdu.getType() != PDU.GETNEXT);
      SnmpVarbind foundVarbind = agent.findObject(oid.toString(), exact);
      if (foundVarbind == null) {
        // Varbindが見つからなかった場合はnoSuchNameを返す
        log.warn("varbind is not found. oid=" + oid.toString());

        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_SUCH_NAME);
        retPdu.setErrorIndex(varCount);

        Variable retObject = new Null();
        VariableBinding retVarbind = new VariableBinding(oid, retObject);
        retPdu.add(retVarbind);
        break;
      }

      // READ-WRITEでなければエラー応答を返す
      String accessibility = foundVarbind.getAccessibility();
      if (accessibility.equals(SnmpVarbind.ACCESSIBILITY_NOT_ACCESSIBLE) == true) {
        log.warn("varbind is not accessible. accessibility=" + accessibility);

        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_NO_ACCESS);
        retPdu.setErrorIndex(varCount);

        Variable retObject = new Null();
        VariableBinding retVarbind = new VariableBinding(oid, retObject);
        retPdu.add(retVarbind);
        break;
      }

      try {
        // 正常の応答を返す
        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_SUCCESS);
        retPdu.setErrorIndex(0);

        log.debug("varbind is found: " + foundVarbind.toString());
        String typeStr = foundVarbind.getType();
        Object retValueObj = foundVarbind.getValue();
        Variable retObject = (Variable) varHelper.createAsnObject(retValueObj, typeStr);

        OID retOID = new OID(foundVarbind.getOid());
        VariableBinding retVarbind = new VariableBinding(retOID, retObject);
        retPdu.add(retVarbind);
      } catch (Exception exception) {
        log.warn("exception occured", exception);

        // 未知のエラーを示す応答PDUを作成する
        retPdu.setErrorStatus(SnmpConstants.SNMP_ERROR_GENERAL_ERROR);
        retPdu.setErrorIndex(varCount);

        if (foundVarbind != null) {
          OID retOID = new OID(foundVarbind.getOid());
          Variable retObject = new Null();
          VariableBinding retVarbind = new VariableBinding(retOID, retObject);
          retPdu.add(retVarbind);
        }
      }
    }
    return retPdu;
  }
    /**
     * This method will be called whenever a pdu is received on the given port specified in the
     * listen() method.
     */
    public synchronized void processPdu(CommandResponderEvent cmdRespEvent) {
      logger.info("Received PDU...");
      PDU pdu = cmdRespEvent.getPDU();

      if (pdu != null) {
        try {
          Event event;
          Map<String, String> headers;
          StringBuilder stringBuilder = new StringBuilder();

          // getVariableBindings: Gets the variable binding vector.
          Vector<? extends VariableBinding> vbs = pdu.getVariableBindings();
          for (VariableBinding vb : vbs) {
            // To extract only the value of the OID
            // stringBuilder.append(vb.getVariable().toString());
            stringBuilder.append(vb.toString() + ",");
          }

          String messageString = stringBuilder.toString();

          // trick: remove the last comma
          messageString = messageString.replaceAll(",$", "");

          byte[] message = messageString.getBytes();

          event = new SimpleEvent();
          headers = new HashMap<String, String>();

          headers.put("timestamp", String.valueOf(System.currentTimeMillis()));
          logger.info("Message: {}", messageString);
          event.setBody(message);
          event.setHeaders(headers);

          if (event == null) {
            return;
          }

          // store the event to underlying channels(s)
          getChannelProcessor().processEvent(event);

          counterGroup.incrementAndGet("events.success");

        } catch (ChannelException ex) {
          counterGroup.incrementAndGet("events.dropped");
          logger.error("Error writting to channel", ex);
          return;
        }

        logger.info("Trap Type = " + pdu.getType());
        logger.info("Variable Bindings = " + pdu.getVariableBindings());

        int pduType = pdu.getType();

        if ((pduType != PDU.TRAP)
            && (pduType != PDU.V1TRAP)
            && (pduType != PDU.REPORT)
            && (pduType != PDU.RESPONSE)) {
          pdu.setErrorIndex(0);
          pdu.setErrorStatus(0);
          pdu.setType(PDU.RESPONSE);
          StatusInformation statusInformation = new StatusInformation();
          StateReference ref = cmdRespEvent.getStateReference();

          try {
            System.out.println(cmdRespEvent.getPDU());
            cmdRespEvent
                .getMessageDispatcher()
                .returnResponsePdu(
                    cmdRespEvent.getMessageProcessingModel(),
                    cmdRespEvent.getSecurityModel(),
                    cmdRespEvent.getSecurityName(),
                    cmdRespEvent.getSecurityLevel(),
                    pdu,
                    cmdRespEvent.getMaxSizeResponsePDU(),
                    ref,
                    statusInformation);
          } catch (MessageException ex) {
            System.err.println("Error while sending response: " + ex.getMessage());
            LogFactory.getLogger(SnmpRequest.class).error(ex);
          }
        }
      }
    }