コード例 #1
0
ファイル: SnmpObjId.java プロジェクト: rohtaash/opennms
  public SnmpInstId getInstance(SnmpObjId base) {
    if (!base.isPrefixOf(this)) return null;

    int[] instanceIds = new int[length() - base.length()];
    System.arraycopy(m_ids, base.length(), instanceIds, 0, instanceIds.length);
    return new SnmpInstId(instanceIds);
  }
コード例 #2
0
ファイル: SeltaSted.java プロジェクト: rssntn67/SLT
  /** run */
  @Override
  public void run() {
    if (polling()) {
      log().debug("run: polling Selta STED on primary address: " + getIpaddress());

      boolean pollhierarchy = true;
      SnmpValue lastCommit =
          SnmpUtils.get(getAgentConfig(), SnmpObjId.get(SeltaMibCommon.OID_S_lastCommit));
      if (lastCommit != null) {
        String lastCommitString = SeltaUtils.ConvertDateToString(lastCommit.getBytes());
        if (getLastCommit() == null || !getLastCommit().equals(lastCommitString)) {
          log().info("lastCommit changed from " + getLastCommit() + " to " + lastCommitString);
          setLastCommit(lastCommitString);
          storeProperty("nePrimaryIP", getIpaddress().toString());
          createInventory();
          savePropertiesFile("STED properties");
          pollhierarchy = false;
        }
      }

      SnmpValue lastAlarm =
          SnmpUtils.get(getAgentConfig(), SnmpObjId.get(SeltaMibCommon.OID_S_lastAlarm));
      if (lastAlarm != null) {
        String lastAlarmString = SeltaUtils.ConvertDateToString(lastAlarm.getBytes());
        if (getLastAlarm() == null || !getLastAlarm().equals(lastAlarmString)) {
          log().info("lastAlarm changed from " + getLastAlarm() + " to " + lastAlarmString);
          setLastAlarm(lastAlarmString);
          poll(pollhierarchy);
          savePropertiesFile("STED properties");
        }
      }
    } else {
      log().info("not polling: " + getIpaddress());
    }
  }
コード例 #3
0
    /**
     * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as
     * an SnmpObjectId. The value is assumed to have been encoded with the specified encoding (only
     * XML_ENCODING_TEXT is supported).
     *
     * @param name The name (a.k.a. "id") of the variable binding to be created
     * @param encoding Describes the way in which the value content has been encoded (i.e.
     *     XML_ENCODING_TEXT, or XML_ENCODING_BASE64)
     * @param value The variable binding value
     * @return The newly-created variable binding
     * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any
     *     reason (e.g. encoding not supported, invalid value, etc.).
     */
    @Override
    public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value)
        throws SnmpTrapHelperException {

      if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) {
        trap.addVarBind(
            SnmpObjId.get(name), SnmpUtils.getValueFactory().getObjectId(SnmpObjId.get(value)));
      } else {
        throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpObjectId");
      }
    }
コード例 #4
0
 @Override
 protected TrapIdentity getTrapIdentity() {
   // Get the value for the snmpTrapOID
   SnmpObjectId snmpTrapOid =
       (SnmpObjectId) m_pdu.getVarBindAt(V2TrapInformation.SNMP_TRAP_OID_INDEX).getValue();
   SnmpObjectId lastVarBindOid = m_pdu.getVarBindAt(getPduLength() - 1).getName();
   SnmpSyntax lastVarBindValue = m_pdu.getVarBindAt(getPduLength() - 1).getValue();
   return new TrapIdentity(
       SnmpObjId.get(snmpTrapOid.getIdentifiers()),
       SnmpObjId.get(lastVarBindOid.getIdentifiers()),
       new JoeSnmpValue(lastVarBindValue));
 }
コード例 #5
0
  @Override
  public ResponseProcessor buildNextPdu(PduBuilder pduBuilder) {
    if (pduBuilder.getMaxVarsPerPdu() < 1) {
      throw new IllegalArgumentException("maxVarsPerPdu < 1");
    }

    SnmpObjId requestOid = m_oid.decrement();
    LOG.debug("Requesting oid following: {}", requestOid);
    pduBuilder.addOid(requestOid);
    pduBuilder.setNonRepeaters(1);
    pduBuilder.setMaxRepetitions(1);

    ResponseProcessor rp =
        new ResponseProcessor() {

          @Override
          public void processResponse(SnmpObjId responseObjId, SnmpValue val) {
            LOG.debug("Processing varBind: {} = {}", responseObjId, val);

            if (val.isEndOfMib()) {
              receivedEndOfMib();
            }

            if (m_oid.equals(responseObjId)) {
              storeResult(new SnmpResult(m_base, m_inst, val));
            }

            setFinished(true);
          }

          @Override
          public boolean processErrors(int errorStatus, int errorIndex) {
            if (errorStatus == NO_ERR) {
              return false;
            } else if (errorStatus == TOO_BIG_ERR) {
              throw new IllegalArgumentException(
                  "Unable to handle tooBigError for oid request " + m_oid.decrement());
            } else if (errorStatus == GEN_ERR) {
              reportGenErr(
                  "Received genErr requesting oid "
                      + m_oid.decrement()
                      + ". Marking column is finished.");
              errorOccurred();
              return true;
            } else if (errorStatus == NO_SUCH_NAME_ERR) {
              reportNoSuchNameErr(
                  "Received noSuchName reqeusting oid "
                      + m_oid.decrement()
                      + ". Marking column is finished.");
              errorOccurred();
              return true;
            } else {
              throw new IllegalArgumentException(
                  "Unexpected error processing oid " + m_oid.decrement() + ". Aborting!");
            }
          }
        };

    return rp;
  }
コード例 #6
0
ファイル: SnmpDetector.java プロジェクト: aashrestha/opennms
 /**
  * getValue
  *
  * @param agentConfig a {@link org.opennms.netmgt.snmp.SnmpAgentConfig} object.
  * @param oid a {@link java.lang.String} object.
  * @return a {@link java.lang.String} object.
  */
 protected String getValue(SnmpAgentConfig agentConfig, String oid) {
   SnmpValue val = SnmpUtils.get(agentConfig, SnmpObjId.get(oid));
   if (val == null || val.isNull() || val.isEndOfMib() || val.isError()) {
     return null;
   } else {
     return val.toString();
   }
 }
コード例 #7
0
  @Test(expected = EndPointStatusException.class)
  @JUnitSnmpAgent(host = "192.168.254.10", resource = "/horizon_duo_walk.properties")
  public void dwoTestLinkMonitorHorizonDuoCapacity3DownModemLossSignal()
      throws UnknownHostException, EndPointStatusException {
    SnmpUtils.set(
        getAgentConfig("192.168.254.10"),
        SnmpObjId.get(HORIZON_DUO_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(2));
    SnmpUtils.set(
        getAgentConfig("192.168.254.10"),
        SnmpObjId.get(HORIZON_DUO_SYSTEM_CAPACITY),
        SnmpUtils.getValueFactory().getCounter32(3));

    EndPoint endPoint = getEndPoint(HORIZON_DUO_SYS_OID, "192.168.254.10");

    m_configDao.getValidator().validate(endPoint);
  }
コード例 #8
0
  @Test(expected = EndPointStatusException.class)
  @JUnitSnmpAgent(host = "192.168.255.31", resource = "/horizon_compact_walk.properties")
  public void dwoTestLinkMonitorHorizonCompactDownEthernetLinkDown()
      throws EndPointStatusException, UnknownHostException {
    SnmpUtils.set(
        getAgentConfig("192.168.255.31"),
        SnmpObjId.get(HORIZON_COMPACT_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(1));
    SnmpUtils.set(
        getAgentConfig("192.168.255.31"),
        SnmpObjId.get(HORIZON_COMPACT_ETHERNET_LINK_DOWN),
        SnmpUtils.getValueFactory().getCounter32(2));

    EndPoint endPoint = getEndPoint(HORIZON_COMPACT_SYS_OID, "192.168.255.31");

    m_configDao.getValidator().validate(endPoint);
  }
コード例 #9
0
  @Test(expected = EndPointStatusException.class)
  @JUnitSnmpAgent(host = "192.168.255.10", resource = "classpath:/airPairR3_walk.properties")
  public void dwoTestLinkMonitorAirPair3DownLossOfSignal()
      throws UnknownHostException, EndPointStatusException {
    SnmpUtils.set(
        getAgentConfig("192.168.255.10"),
        SnmpObjId.get(AIR_PAIR_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(2));
    SnmpUtils.set(
        getAgentConfig("192.168.255.10"),
        SnmpObjId.get(AIR_PAIR_R3_DUPLEX_MISMATCH),
        SnmpUtils.getValueFactory().getCounter32(1));

    EndPointImpl endPoint = getEndPoint(AIR_PAIR_R3_SYS_OID, "192.168.255.10");

    m_configDao.getValidator().validate(endPoint);
  }
コード例 #10
0
ファイル: SnmpRowResult.java プロジェクト: aashrestha/opennms
  /**
   * @param base
   * @return
   */
  public SnmpValue getValue(SnmpObjId base) {
    for (SnmpResult result : getResults()) {
      if (base.equals(result.getBase())) {
        return result.getValue();
      }
    }

    return null;
  }
コード例 #11
0
ファイル: SnmpObjId.java プロジェクト: rohtaash/opennms
  public boolean isPrefixOf(final SnmpObjId other) {
    if (other == null || length() > other.length()) return false;

    for (int i = 0; i < m_ids.length; i++) {
      if (m_ids[i] != other.m_ids[i]) return false;
    }

    return true;
  }
コード例 #12
0
ファイル: Snmp4JValue.java プロジェクト: aashrestha/opennms
 @Override
 public SnmpObjId toSnmpObjId() {
   switch (m_value.getSyntax()) {
     case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
       return SnmpObjId.get(((OID) m_value).getValue());
     default:
       throw new IllegalArgumentException("cannot convert " + m_value + " to an SnmpObjId");
   }
 }
コード例 #13
0
  /**
   * matches
   *
   * @param base a {@link org.opennms.netmgt.snmp.SnmpObjId} object.
   * @param inst a {@link org.opennms.netmgt.snmp.SnmpInstId} object.
   * @return a boolean.
   */
  public boolean matches(SnmpObjId base, SnmpInstId inst) {
    if (!base.equals(getSnmpObjId())) {
      return false;
    }

    if (getInstance().equals(MibObject.INSTANCE_IFINDEX) || m_mibObj.getResourceType() != null) {
      return true;
    } else {
      return getInstance().equals(inst.toString());
    }
  }
コード例 #14
0
ファイル: SnmpObjId.java プロジェクト: rohtaash/opennms
  @Override
  public int compareTo(SnmpObjId o) {
    if (o == null) throw new NullPointerException("o is null");
    SnmpObjId other = (SnmpObjId) o;

    // compare each element in order for as much length as they have in common
    // which is the entire length of one or both oids
    int minLen = Math.min(length(), other.length());
    for (int i = 0; i < minLen; i++) {
      long diff = toLong(m_ids[i]) - toLong(other.m_ids[i]);
      // the first one that is not equal indicates which is bigger
      if (diff != 0) {
        return diff > 0 ? 1 : -1;
      }
    }

    // if they get to hear then both are identifical for their common length
    // so which ever is longer is then greater
    return length() - other.length();
  }
コード例 #15
0
    /**
     * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as
     * an SnmpOpaque. The value is assumed to have been encoded with the specified encoding (only
     * XML_ENCODING_BASE64 is supported).
     *
     * @param name The name (a.k.a. "id") of the variable binding to be created
     * @param encoding Describes the way in which the value content has been encoded (i.e.
     *     XML_ENCODING_TEXT, or XML_ENCODING_BASE64)
     * @param value The variable binding value
     * @return The newly-created variable binding
     * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any
     *     reason (e.g. encoding not supported, invalid value, etc.).
     */
    @Override
    public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value)
        throws SnmpTrapHelperException {

      if (EventConstants.XML_ENCODING_BASE64.equals(encoding)) {
        trap.addVarBind(
            SnmpObjId.get(name),
            SnmpUtils.getValueFactory().getOpaque(Base64.decodeBase64(value.toCharArray())));
      } else {
        throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpOpaque");
      }
    }
コード例 #16
0
  @Test
  @JUnitSnmpAgent(host = "192.168.255.10", resource = "classpath:/airPairR3_walk.properties")
  public void dwoTestLinkMonitorAirPairR3() throws UnknownHostException {
    SnmpUtils.set(
        getAgentConfig("192.168.255.10"),
        SnmpObjId.get(AIR_PAIR_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(1));
    SnmpUtils.set(
        getAgentConfig("192.168.255.10"),
        SnmpObjId.get(AIR_PAIR_R3_DUPLEX_MISMATCH),
        SnmpUtils.getValueFactory().getCounter32(1));

    EndPointImpl endPoint = getEndPoint(AIR_PAIR_R3_SYS_OID, "192.168.255.10");

    EndPointTypeValidator validator = m_configDao.getValidator();
    try {
      validator.validate(endPoint);
    } catch (EndPointStatusException e) {
      assertTrue(false);
    }
  }
コード例 #17
0
  @Test
  @Ignore
  @JUnitSnmpAgent(host = "192.168.255.20", resource = "/airPairR4_walk.properties")
  public void dwoTestLinkMonitorAirPairR4() throws UnknownHostException {
    SnmpUtils.set(
        getAgentConfig("192.168.255.20"),
        SnmpObjId.get(AIR_PAIR_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(1));
    SnmpUtils.set(
        getAgentConfig("192.168.255.20"),
        SnmpObjId.get(AIR_PAIR_R4_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(1));

    EndPointImpl endPoint = getEndPoint(AIR_PAIR_R4_SYS_OID, "192.168.255.20");

    try {
      m_configDao.getValidator().validate(endPoint);
    } catch (EndPointStatusException e) {
      assertTrue("An EndPointStatusException was caught resulting in a failed test", false);
    }
  }
コード例 #18
0
  /**
   * Create an SNMP V1 trap with the specified enterprise IS, agent address, generic ID, specific
   * ID, and time stamp.
   *
   * @param entId The enterprise ID for the trap.
   * @param agentAddr The agent address for the trap.
   * @param generic The generic ID for the trap.
   * @param specific The specific ID for the trap.
   * @param timeStamp The time stamp for the trap.
   * @return The newly-created trap.
   * @throws java.net.UnknownHostException if any.
   */
  public SnmpV1TrapBuilder createV1Trap(
      String entId, String agentAddr, int generic, int specific, long timeStamp)
      throws UnknownHostException {

    SnmpV1TrapBuilder trap = SnmpUtils.getV1TrapBuilder();
    trap.setEnterprise(SnmpObjId.get(entId));
    trap.setAgentAddress(InetAddressUtils.addr(agentAddr));
    trap.setGeneric(generic);
    trap.setSpecific(specific);
    trap.setTimeStamp(timeStamp);

    return trap;
  }
コード例 #19
0
  @Test
  @JUnitSnmpAgent(host = "192.168.255.31", resource = "/horizon_compact_walk.properties")
  public void dwoTestLinkMonitorHorizonCompact() throws UnknownHostException {
    SnmpUtils.set(
        getAgentConfig("192.168.255.31"),
        SnmpObjId.get(HORIZON_COMPACT_MODEM_LOSS_OF_SIGNAL),
        SnmpUtils.getValueFactory().getCounter32(1));
    SnmpUtils.set(
        getAgentConfig("192.168.255.31"),
        SnmpObjId.get(HORIZON_COMPACT_ETHERNET_LINK_DOWN),
        SnmpUtils.getValueFactory().getCounter32(1));

    EndPointImpl endPoint = getEndPoint(HORIZON_COMPACT_SYS_OID, "192.168.255.31");

    try {
      m_configDao.getValidator().validate(endPoint);
    } catch (Throwable e) {
      assertTrue(
          "An EndPointStatusException was thrown which shouldn't have and thats why the test failed",
          false);
    }
  }
コード例 #20
0
    /**
     * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as
     * an SnmpIPAddress. The value is assumed to have been encoded with the specified encoding (only
     * XML_ENCODING_TEXT is supported).
     *
     * @param name The name (a.k.a. "id") of the variable binding to be created
     * @param encoding Describes the way in which the value content has been encoded (i.e.
     *     XML_ENCODING_TEXT, or XML_ENCODING_BASE64)
     * @param value The variable binding value
     * @return The newly-created variable binding
     * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any
     *     reason (e.g. encoding not supported, invalid value, etc.).
     */
    @Override
    public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value)
        throws SnmpTrapHelperException {

      if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) {
        final InetAddress addr = InetAddressUtils.addr(value);
        if (addr == null) {
          throw new SnmpTrapHelperException(
              "Value " + value + "is invalid, or host unknown for SnmpIPAddress");
        }
        trap.addVarBind(SnmpObjId.get(name), SnmpUtils.getValueFactory().getIpAddress(addr));
      } else {
        throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpIPAddress");
      }
    }
コード例 #21
0
ファイル: Snmp4JValue.java プロジェクト: aashrestha/opennms
 @Override
 public String toDisplayString() {
   switch (m_value.getSyntax()) {
     case SMIConstants.SYNTAX_OBJECT_IDENTIFIER:
       return SnmpObjId.get(((OID) m_value).getValue()).toString();
     case SMIConstants.SYNTAX_TIMETICKS:
       return Long.toString(toLong());
     case SMIConstants.SYNTAX_OCTET_STRING:
       return toStringDottingCntrlChars(((OctetString) m_value).getValue());
     case SMIConstants.SYNTAX_NULL:
       return "";
     default:
       return m_value.toString();
   }
 }
コード例 #22
0
    /**
     * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as
     * an SnmpCounter64. The value is assumed to have been encoded with the specified encoding (only
     * XML_ENCODING_TEXT is supported).
     *
     * @param name The name (a.k.a. "id") of the variable binding to be created
     * @param encoding Describes the way in which the value content has been encoded (i.e.
     *     XML_ENCODING_TEXT, or XML_ENCODING_BASE64)
     * @param value The variable binding value
     * @return The newly-created variable binding
     * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any
     *     reason (e.g. encoding not supported, invalid value, etc.).
     */
    @Override
    public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value)
        throws SnmpTrapHelperException {

      if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) {
        try {
          trap.addVarBind(
              SnmpObjId.get(name), SnmpUtils.getValueFactory().getCounter64(new BigInteger(value)));
        } catch (IllegalArgumentException e) {
          throw new SnmpTrapHelperException("Value " + value + "is invalid for SnmpCounter64");
        } catch (NullPointerException e) {
          throw new SnmpTrapHelperException("Value is null for SnmpCounter64");
        }
      } else {
        throw new SnmpTrapHelperException("Encoding " + encoding + "is invalid for SnmpCounter64");
      }
    }
コード例 #23
0
    /**
     * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as
     * an SnmpOctetString. The value is assumed to have been encoded with the specified encoding
     * (i.e. XML_ENCODING_TEXT, XML_ENCODING_BASE64, or XML_ENCODING_MAC_ADDRESS).
     *
     * @param name The name (a.k.a. "id") of the variable binding to be created
     * @param encoding Describes the way in which the value content has been encoded (i.e.
     *     XML_ENCODING_TEXT, XML_ENCODING_BASE64, or XML_ENCODING_MAC_ADDRESS)
     * @param value The variable binding value
     * @return The newly-created variable binding
     * @exception Throws SnmpTrapHelperException if the variable binding cannot be created for any
     *     reason (e.g. encoding not supported, invalid value, etc.).
     */
    @Override
    public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value)
        throws SnmpTrapHelperException {

      byte[] contents;
      if (EventConstants.XML_ENCODING_TEXT.equals(encoding)) {
        contents = value.getBytes();
      } else if (EventConstants.XML_ENCODING_BASE64.equals(encoding)) {
        contents = Base64.decodeBase64(value.toCharArray());
      } else if (EventConstants.XML_ENCODING_MAC_ADDRESS.equals(encoding)) {
        contents = InetAddressUtils.macAddressStringToBytes(value);
      } else {
        throw new SnmpTrapHelperException(
            "Encoding " + encoding + "is invalid for SnmpOctetString");
      }
      trap.addVarBind(SnmpObjId.get(name), SnmpUtils.getValueFactory().getOctetString(contents));
    }
コード例 #24
0
 @Override
 protected void processVarBindAt(int i) {
   if (i < 2) {
     if (i == 0) {
       log()
           .debug(
               "Skipping processing of varbind it is the sysuptime and the first varbind, it is not processed as a parm per RFC2089");
     } else {
       log()
           .debug(
               "Skipping processing of varbind it is the trap OID and the second varbind, it is not processed as a parm per RFC2089");
     }
   } else {
     SnmpObjId name = SnmpObjId.get(getVarBindAt(i).getName().getIdentifiers());
     SnmpValue value = new JoeSnmpValue(getVarBindAt(i).getValue());
     processVarBind(name, value);
   }
 }
コード例 #25
0
 /**
  * Constructs a new SnmpVarBind with the specified name and value. The value will be encoded as
  * an SnmpNull.The value and encoding parameters are ignored.
  *
  * @param name The name (a.k.a. "id") of the variable binding to be created
  * @param encoding This parameter value is ignored.
  * @param value This parameter value is ignored.
  * @return The newly-created variable binding
  */
 @Override
 public void addVarBind(SnmpTrapBuilder trap, String name, String encoding, String value) {
   trap.addVarBind(SnmpObjId.get(name), SnmpUtils.getValueFactory().getNull());
 }
コード例 #26
0
  /**
   * Create an SNMP V1 trap, based on the content of the specified event, and forward the trap to
   * the specified address and port. It is assumed that the specified event represents an SNMP V1 or
   * V2 trap that was received by OpenNMS (TrapD).
   *
   * @param event The event upon which the trap content should be based
   * @param destAddr The address to which the trap should be forwarded
   * @param destPort The port to which the trap should be forwarded
   * @exception Throws SnmpTrapHelperException if the variable binding cannot be added to the trap
   *     for any reason.
   * @throws org.opennms.netmgt.scriptd.helper.SnmpTrapHelperException if any.
   */
  public void forwardV1Trap(Event event, String destAddr, int destPort)
      throws SnmpTrapHelperException {
    // the event must correspond to an SNMP trap

    Snmp snmpInfo = event.getSnmp();

    if (snmpInfo == null) {
      throw new SnmpTrapHelperException(
          "Cannot forward an event with no SNMP info: " + event.getUei());
    }

    // check the version of the original trap

    String version = snmpInfo.getVersion();

    SnmpV1TrapBuilder trap = SnmpUtils.getV1TrapBuilder();

    if ("v1".equals(version)) {

      trap.setEnterprise(SnmpObjId.get(snmpInfo.getId()));

      InetAddress agentAddress;
      agentAddress = InetAddressUtils.addr(event.getSnmphost());
      if (agentAddress == null) {
        throw new SnmpTrapHelperException("Invalid ip address.");
      }

      trap.setAgentAddress(agentAddress);

      if (snmpInfo.hasGeneric()) {
        trap.setGeneric(snmpInfo.getGeneric());
      }

      if (snmpInfo.hasSpecific()) {
        trap.setSpecific(snmpInfo.getSpecific());
      }

      trap.setTimeStamp(snmpInfo.getTimeStamp());

      // varbinds

      int i = 0;
      for (Parm parm : event.getParmCollection()) {
        try {
          Value value = parm.getValue();
          addVarBinding(
              trap, parm.getParmName(), value.getType(), value.getEncoding(), value.getContent());
        } catch (SnmpTrapHelperException e) {
          throw new SnmpTrapHelperException(e.getMessage() + " in event parm[" + i + "]");
        } finally {
          i++;
        }
      }
    } else if ("v2".equals(version)) {

      // converting V2 trap to V1 (see RFC2576)

      trap.setEnterprise(SnmpObjId.get(snmpInfo.getId()));

      String addr = null;

      for (Parm parm : event.getParmCollection()) {
        if (SNMP_TRAP_ADDRESS_OID.equals(parm.getParmName())) {
          addr = parm.getValue().getContent();
          break;
        }
      }

      if (addr == null) {
        addr = "0.0.0.0";
      }

      InetAddress agentAddress;
      agentAddress = InetAddressUtils.addr(addr);
      if (agentAddress == null) {
        throw new SnmpTrapHelperException("Invalid ip address.");
      }

      trap.setAgentAddress(agentAddress);

      trap.setGeneric(snmpInfo.getGeneric());

      trap.setSpecific(snmpInfo.getSpecific());

      trap.setTimeStamp(snmpInfo.getTimeStamp());

      // varbinds

      int i = 0;
      for (Parm parm : event.getParmCollection()) {
        Value value = parm.getValue();

        // omit any parms with type=Counter64

        if (!(EventConstants.TYPE_SNMP_COUNTER64.equals(value.getType()))) {

          try {
            addVarBinding(
                trap, parm.getParmName(), value.getType(), value.getEncoding(), value.getContent());
          } catch (SnmpTrapHelperException e) {
            throw new SnmpTrapHelperException(e.getMessage() + " in event parm[" + i + "]");
          }
        }

        i++;
      }

    } else {
      throw new SnmpTrapHelperException("Invalid SNMP version: " + version);
    }

    // send the trap

    sendTrap(destAddr, destPort, snmpInfo.getCommunity(), trap);
  }
コード例 #27
0
 @Test
 public void testAgent() throws Exception {
   SnmpValue snmpValue = SnmpUtils.get(snmpAgentConfig, SnmpObjId.get(".1.3.6.1.2.1.1.1.0"));
   Assert.assertEquals("Mock Juniper TCA Device", snmpValue.toDisplayString());
 }
コード例 #28
0
 SysUpTimeTracker() {
   super(SnmpObjId.get(SnmpCollector.NODE_SYSUPTIME), SnmpInstId.INST_ZERO);
 }
コード例 #29
0
  private static String fetchSnmpAssetString(
      final SnmpAgentConfig agentConfig, final MibObjs mibObjs, final String formatString)
      throws MissingFormatArgumentException {

    final List<String> aliases = new ArrayList<String>();
    final List<SnmpObjId> objs = new ArrayList<SnmpObjId>();
    for (final MibObj mibobj : mibObjs.getMibObj()) {
      aliases.add(mibobj.getAlias());
      objs.add(SnmpObjId.get(mibobj.getOid()));
    }
    // Fetch the values from the SNMP agent
    final SnmpValue[] values = SnmpUtils.get(agentConfig, objs.toArray(new SnmpObjId[0]));
    if (values.length == aliases.size()) {
      final Properties substitutions = new Properties();
      boolean foundAValue = false;
      for (int i = 0; i < values.length; i++) {
        // If the value is a NO_SUCH_OBJECT or NO_SUCH_INSTANCE error, then skip it
        if (values[i] == null || values[i].isError()) {
          // No value for this OID
          continue;
        }
        foundAValue = true;
        // Use trapd's SyntaxToEvent parser so that we format base64
        // and MAC address values appropriately
        Parm parm = SyntaxToEvent.processSyntax(aliases.get(i), values[i]);
        substitutions.setProperty(aliases.get(i), parm.getValue().getContent());
      }

      if (!foundAValue) {
        if (log().isDebugEnabled()) {
          log()
              .debug(
                  "fetchSnmpAssetString: Failed to fetch any SNMP values for system "
                      + agentConfig.toString());
        }
        throw new MissingFormatArgumentException(
            "fetchSnmpAssetString: Failed to fetch any SNMP values for system "
                + agentConfig.toString());
      } else {
        log()
            .debug(
                "fetchSnmpAssetString: Fetched asset properties from SNMP agent:\n"
                    + formatPropertiesAsString(substitutions));
      }

      if (objs.size() != substitutions.size()) {
        log()
            .warn(
                "fetchSnmpAssetString: Unexpected number of properties returned from SNMP GET:\n"
                    + formatPropertiesAsString(substitutions));
      }

      return PropertiesUtils.substitute(formatString, substitutions);
    } else {
      log()
          .warn(
              "fetchSnmpAssetString: Invalid number of SNMP parameters returned: "
                  + values.length
                  + " != "
                  + aliases.size());
      throw new MissingFormatArgumentException(
          "fetchSnmpAssetString: Invalid number of SNMP parameters returned: "
              + values.length
              + " != "
              + aliases.size());
    }
  }
コード例 #30
0
/**
 * PhysInterfaceTableTracker
 *
 * @author brozow
 * @version $Id: $
 */
public class PhysInterfaceTableTracker extends TableTracker {
  private static final Logger LOG = LoggerFactory.getLogger(PhysInterfaceTableTracker.class);

  /** Constant <code>IF_TABLE_ENTRY</code> */
  public static final SnmpObjId IF_TABLE_ENTRY = SnmpObjId.get(".1.3.6.1.2.1.2.2.1");
  /** Constant <code>IF_INDEX</code> */
  public static final SnmpObjId IF_INDEX = SnmpObjId.get(IF_TABLE_ENTRY, "1");
  /** Constant <code>IF_DESCR</code> */
  public static final SnmpObjId IF_DESCR = SnmpObjId.get(IF_TABLE_ENTRY, "2");
  /** Constant <code>IF_TYPE</code> */
  public static final SnmpObjId IF_TYPE = SnmpObjId.get(IF_TABLE_ENTRY, "3");
  /** Constant <code>IF_MTU</code> */
  public static final SnmpObjId IF_MTU = SnmpObjId.get(IF_TABLE_ENTRY, "4");
  /** Constant <code>IF_SPEED</code> */
  public static final SnmpObjId IF_SPEED = SnmpObjId.get(IF_TABLE_ENTRY, "5");
  /** Constant <code>IF_PHYS_ADDR</code> */
  public static final SnmpObjId IF_PHYS_ADDR = SnmpObjId.get(IF_TABLE_ENTRY, "6");
  /** Constant <code>IF_ADMIN_STATUS</code> */
  public static final SnmpObjId IF_ADMIN_STATUS = SnmpObjId.get(IF_TABLE_ENTRY, "7");
  /** Constant <code>IF_OPER_STATUS</code> */
  public static final SnmpObjId IF_OPER_STATUS = SnmpObjId.get(IF_TABLE_ENTRY, "8");
  /** Constant <code>IF_LAST_CHANGE</code> */
  public static final SnmpObjId IF_LAST_CHANGE = SnmpObjId.get(IF_TABLE_ENTRY, "9");

  /** Constant <code>IF_XTABLE_ENTRY</code> */
  public static final SnmpObjId IF_XTABLE_ENTRY = SnmpObjId.get(".1.3.6.1.2.1.31.1.1.1");
  /** Constant <code>IF_NAME</code> */
  public static final SnmpObjId IF_NAME = SnmpObjId.get(IF_XTABLE_ENTRY, "1");
  /** Constant <code>IF_IN_MCAST_PKTS</code> */
  public static final SnmpObjId IF_IN_MCAST_PKTS = SnmpObjId.get(IF_XTABLE_ENTRY, "2");
  /** Constant <code>IF_IN_BCAST_PKTS</code> */
  public static final SnmpObjId IF_IN_BCAST_PKTS = SnmpObjId.get(IF_XTABLE_ENTRY, "3");
  /** Constant <code>IF_OUT_MCAST_PKTS</code> */
  public static final SnmpObjId IF_OUT_MCAST_PKTS = SnmpObjId.get(IF_XTABLE_ENTRY, "4");
  /** Constant <code>IF_LINK_UP_DOWN_TRAP_ENABLE</code> */
  public static final SnmpObjId IF_LINK_UP_DOWN_TRAP_ENABLE = SnmpObjId.get(IF_XTABLE_ENTRY, "14");
  /** Constant <code>IF_HIGH_SPEED</code> */
  public static final SnmpObjId IF_HIGH_SPEED = SnmpObjId.get(IF_XTABLE_ENTRY, "15");
  /** Constant <code>IF_PROMISCUOUS_MODE</code> */
  public static final SnmpObjId IF_PROMISCUOUS_MODE = SnmpObjId.get(IF_XTABLE_ENTRY, "16");
  /** Constant <code>IF_CONNECTOR_PRESENT</code> */
  public static final SnmpObjId IF_CONNECTOR_PRESENT = SnmpObjId.get(IF_XTABLE_ENTRY, "17");
  /** Constant <code>IF_ALIAS</code> */
  public static final SnmpObjId IF_ALIAS = SnmpObjId.get(IF_XTABLE_ENTRY, "18");
  /** Constant <code>IF_COUNTER_DISCONTINUITY_TIME</code> */
  public static final SnmpObjId IF_COUNTER_DISCONTINUITY_TIME =
      SnmpObjId.get(IF_XTABLE_ENTRY, "19");

  private static SnmpObjId[] s_tableColumns =
      new SnmpObjId[] {
        IF_INDEX,
        IF_DESCR,
        IF_TYPE,
        IF_MTU,
        IF_SPEED,
        IF_PHYS_ADDR,
        IF_ADMIN_STATUS,
        IF_OPER_STATUS,
        IF_LAST_CHANGE,
        IF_NAME,
        IF_ALIAS,
        IF_HIGH_SPEED
      };

  class PhysicalInterfaceRow extends SnmpRowResult {

    public PhysicalInterfaceRow(final int columnCount, final SnmpInstId instance) {
      super(columnCount, instance);
    }

    public Integer getIfIndex() {
      final SnmpValue value = getValue(IF_INDEX);
      if (value != null) {
        return value.toInt();
      } else {
        // ifIndex is the instance id as well
        final SnmpInstId inst = getInstance();
        if (inst != null && inst.length() == 1) {
          return inst.toInt();
        }
      }
      return null;
    }

    private Integer getIfType() {
      final SnmpValue value = getValue(IF_TYPE);
      return value == null ? null : value.toInt();
    }

    private Long getIfSpeed() {
      final SnmpValue value = getValue(IF_SPEED);
      return value == null ? null : value.toLong();
    }

    private Long getIfHighSpeed() {
      final SnmpValue value = getValue(IF_HIGH_SPEED);
      return value == null ? null : value.toLong();
    }

    private Long getSpeed() {
      final Long highSpeed = getIfHighSpeed();
      final Long ifSpeed = getIfSpeed();
      if (highSpeed != null && highSpeed > 4294L) {
        return highSpeed * 1000000L;
      }
      if (ifSpeed == null) {
        if (highSpeed != null && highSpeed > 0) {
          LOG.warn(
              "the ifSpeed for ifIndex {} is null, which is a violation of the standard (this seems to be related to a broken SNMP agent). But, the ifHighSpeed is {}, so that value will be used instead.",
              getIfIndex(),
              highSpeed);
          return highSpeed * 1000000L;
        } else {
          LOG.warn(
              "the ifSpeed for ifIndex {} is null, which is a violation of the standard (this seems to be related to a broken SNMP agent). Returning 0 instead",
              getIfIndex());
          return 0L;
        }
      }
      return ifSpeed;
    }

    private Integer getIfOperStatus() {
      final SnmpValue value = getValue(IF_OPER_STATUS);
      return value == null ? null : value.toInt();
    }

    private String getIfName() {
      final SnmpValue value = getValue(IF_NAME);
      return value == null ? null : value.toDisplayString();
    }

    private String getIfDescr() {
      final SnmpValue value = getValue(IF_DESCR);
      return value == null ? null : value.toDisplayString();
    }

    private String getIfAlias() {
      final SnmpValue value = getValue(IF_ALIAS);
      return value == null ? null : value.toDisplayString();
    }

    private Integer getIfAdminStatus() {
      final SnmpValue value = getValue(IF_ADMIN_STATUS);
      return value == null ? null : value.toInt();
    }

    private String getPhysAddr() {
      final SnmpValue value = getValue(IF_PHYS_ADDR);
      String hexString = value == null ? null : value.toHexString();
      String displayString = value == null ? null : value.toDisplayString();
      // See ifTableEntry: NMS-4902 (revision cee964fe979e6465aeb4e2efd4772e50ebc54831)
      try {
        if (hexString != null && hexString.length() == 12) {
          // If the hex string is 12 characters long, than the agent is kinda weird and
          // is returning the value as a raw binary value that is 6 bytes in length.
          // But that's OK, as long as we can convert it into a string, that's fine.
          return hexString;
        } else {
          // This is the normal case that most agents conform to: the value is an ASCII
          // string representing the colon-separated MAC address. We just need to reformat
          // it to remove the colons and convert it into a 12-character string.
          return displayString == null || displayString.trim().isEmpty()
              ? null
              : InetAddressUtils.normalizeMacAddress(displayString);
        }
      } catch (IllegalArgumentException e) {
        LOG.warn(e.getMessage(), e);
        return displayString;
      }
    }

    public OnmsSnmpInterface createInterfaceFromRow() {
      final OnmsSnmpInterface snmpIface = new OnmsSnmpInterface(null, getIfIndex());
      snmpIface.setIfAdminStatus(getIfAdminStatus());
      snmpIface.setIfAlias(getIfAlias());
      snmpIface.setIfDescr(getIfDescr());
      snmpIface.setIfName(getIfName());
      snmpIface.setIfOperStatus(getIfOperStatus());
      snmpIface.setIfSpeed(getSpeed());
      snmpIface.setIfType(getIfType());
      snmpIface.setPhysAddr(getPhysAddr());
      return snmpIface;
    }
  }

  /** Constructor for PhysInterfaceTableTracker. */
  public PhysInterfaceTableTracker() {
    super(s_tableColumns);
  }

  /**
   * Constructor for PhysInterfaceTableTracker.
   *
   * @param rowProcessor a {@link org.opennms.netmgt.snmp.RowCallback} object.
   */
  public PhysInterfaceTableTracker(final RowCallback rowProcessor) {
    super(rowProcessor, s_tableColumns);
  }

  /** {@inheritDoc} */
  @Override
  public SnmpRowResult createRowResult(final int columnCount, final SnmpInstId instance) {
    return new PhysicalInterfaceRow(columnCount, instance);
  }

  /** {@inheritDoc} */
  @Override
  public void rowCompleted(final SnmpRowResult row) {
    processPhysicalInterfaceRow((PhysicalInterfaceRow) row);
  }

  /**
   * processPhysicalInterfaceRow
   *
   * @param row a {@link
   *     org.opennms.netmgt.provision.service.PhysInterfaceTableTracker.PhysicalInterfaceRow}
   *     object.
   */
  public void processPhysicalInterfaceRow(final PhysicalInterfaceRow row) {}
}