org.snmp4j.PDU Java Examples

The following examples show how to use org.snmp4j.PDU. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SwitchCPUStatCollect.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * walk的方式获取监控值
 * 通过获得的总值除数量的逻辑
 * @param session
 * @param oid
 * @return
 * @throws IOException
 */
private static CollectObject walkForSumDivCount(SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();
    List<PDU> pduList = session.walk(oid);

    int count = pduList.size();
    long value = 0;

    for (PDU pdu : pduList) {
        value += Long.parseLong(SNMPHelper.getValueFromPDU(pdu));
    }

    collectObject.setSession(session);
    collectObject.setMetrics(metricsName);
    collectObject.setValue(0 + "");
    if(count > 0){
        collectObject.setValue(String.valueOf(value / count));
    }
    collectObject.setTime(new Date());

    return collectObject;
}
 
Example #2
Source File: SwitchMemoryStatCollect.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
private static CollectObject getOldHuawei_Mem(SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();
    collectObject.setSession(session);
    collectObject.setMetrics(metricsName);
    collectObject.setTime(new Date());

    String memTotalOid = "1.3.6.1.4.1.2011.6.1.2.1.1.2";
    List<PDU> snmpMemTotal = session.walk(memTotalOid);

    String memFreeOid = "1.3.6.1.4.1.2011.6.1.2.1.1.3";
    List<PDU> snmpMemFree = session.walk(memFreeOid);

    if(snmpMemFree.isEmpty() || snmpMemTotal.isEmpty()){
        log.warn("{} No Such Object available on this agent at this OID",session);
        return null;
    }

    int memTotal = Integer.parseInt(SNMPHelper.getValueFromPDU(snmpMemTotal.get(0)));
    int memFree = Integer.parseInt(SNMPHelper.getValueFromPDU(snmpMemFree.get(0)));
    collectObject.setValue(String.valueOf(((float) memTotal - (float)memFree) / (float)memTotal));

    return collectObject;
}
 
Example #3
Source File: SwitchMemoryStatCollect.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
static CollectObject getH3CHWcpumem(String metricsName,SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();

    List<PDU> pduList = session.walk(oid);
    String value = "";
    for (PDU pdu : pduList) {
        if(pdu.get(0).getVariable().toLong() != 0){
            value = SNMPHelper.getValueFromPDU(pdu);
            break;
        }
    }
    collectObject.setSession(session);
    collectObject.setMetrics(metricsName);
    collectObject.setValue(value);
    collectObject.setTime(new Date());

    return collectObject;
}
 
Example #4
Source File: SwitchMemoryStatCollect.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
private static CollectObject getCisco_ASA_Mem(SNMPV3Session session, String oid) throws IOException {
    String memUsedOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.18";
    List<PDU> memUsedListPDU = session.walk(memUsedOid);
    String memFreeOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.20";
    List<PDU> memFreeListPDU = session.walk(memFreeOid);

    CollectObject collectObject = new CollectObject();
    collectObject.setMetrics(metricsName);
    collectObject.setSession(session);
    collectObject.setTime(new Date());

    if(SNMPHelper.isValidPDU(memFreeListPDU.get(0)) && SNMPHelper.isValidPDU(memUsedListPDU.get(0))){
        int memUsed = Integer.parseInt(SNMPHelper.getValueFromPDU(memUsedListPDU.get(0)));
        int memFree = Integer.parseInt(SNMPHelper.getValueFromPDU(memFreeListPDU.get(0)));
        if(memUsed+memFree != 0){
            collectObject.setValue(String.valueOf((double)memUsed / ((double)memUsed + (double)memFree)));
        }
    }

    return collectObject;
}
 
Example #5
Source File: SwitchMemoryStatCollect.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
private static CollectObject getCisco_IOS_XR_Mem(SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();
    collectObject.setMetrics(metricsName);
    collectObject.setSession(session);
    collectObject.setTime(new Date());

    String cpuIndex = "1.3.6.1.4.1.9.9.109.1.1.1.1.2";
    PDU cpuIndexPDU = session.getNext(cpuIndex);
    if(cpuIndexPDU.get(0) != null){
        int index  = Integer.parseInt(SNMPHelper.getValueFromPDU(cpuIndexPDU));
        String memUsedOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.18." + index + ".1";
        String memFreeOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.20." + index + ".1";
        PDU memUsedPDU = session.get(memUsedOid);
        PDU memFreePDU = session.get(memFreeOid);
        setRatioValueHelper(memUsedPDU,memFreePDU,collectObject);
    }

    return collectObject;
}
 
Example #6
Source File: SwitchCPUStatCollect.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * walk的方式获取监控值
 * 通过获得的总值除数量的逻辑
 * @param session
 * @param oid
 * @return
 * @throws IOException
 */
private static CollectObject walkForSumDivCount(SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();
    List<PDU> pduList = session.walk(oid);

    int count = pduList.size();
    long value = 0;

    for (PDU pdu : pduList) {
        value += Long.parseLong(SNMPHelper.getValueFromPDU(pdu));
    }

    collectObject.setSession(session);
    collectObject.setMetrics(metricsName);
    collectObject.setValue(0 + "");
    if(count > 0){
        collectObject.setValue(String.valueOf(value / count));
    }
    collectObject.setTime(new Date());

    return collectObject;
}
 
Example #7
Source File: SNMPUtilsTest.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Test for updating attributes of flow files with {@link PDU}
 */
@Test
public void validateUpdateFlowFileAttributes() {
    GetSNMP processor = new GetSNMP();
    ProcessSession processSession = new MockProcessSession(new SharedSessionState(processor, new AtomicLong()),
            processor);
    FlowFile sourceFlowFile = processSession.create();

    PDU pdu = new PDU();
    pdu.setErrorIndex(0);
    pdu.setErrorStatus(0);
    pdu.setType(4);

    FlowFile f2 = SNMPUtils.updateFlowFileAttributesWithPduProperties(pdu, sourceFlowFile,
            processSession);

    assertEquals("0", f2.getAttributes().get(SNMPUtils.SNMP_PROP_PREFIX + "errorIndex"));
    assertEquals("0", f2.getAttributes().get(SNMPUtils.SNMP_PROP_PREFIX + "errorStatus"));
    assertEquals("4", f2.getAttributes().get(SNMPUtils.SNMP_PROP_PREFIX + "type"));
}
 
Example #8
Source File: SNMPUtilsTest.java    From nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Test for updating attributes of flow files with {@link PDU}
 */
@Test
public void validateUpdateFlowFileAttributes() {
    GetSNMP processor = new GetSNMP();
    ProcessSession processSession = new MockProcessSession(new SharedSessionState(processor, new AtomicLong()),
            processor);
    FlowFile sourceFlowFile = processSession.create();

    PDU pdu = new PDU();
    pdu.setErrorIndex(0);
    pdu.setErrorStatus(0);
    pdu.setType(4);

    FlowFile f2 = SNMPUtils.updateFlowFileAttributesWithPduProperties(pdu, sourceFlowFile,
            processSession);

    assertEquals("0", f2.getAttributes().get(SNMPUtils.SNMP_PROP_PREFIX + "errorIndex"));
    assertEquals("0", f2.getAttributes().get(SNMPUtils.SNMP_PROP_PREFIX + "errorStatus"));
    assertEquals("4", f2.getAttributes().get(SNMPUtils.SNMP_PROP_PREFIX + "type"));
}
 
Example #9
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 6 votes vote down vote up
/**
 * This method is capable of handling multiple OIDs
 * @param oids
 * @return
 * @throws IOException
 */
public Map<OID, String> get(OID oids[]) throws IOException 
{
	PDU pdu = createPDU();
	for (OID oid : oids) {
		pdu.add(new VariableBinding(oid));
	}
	pdu.setType(PDU.GET);
	ResponseEvent event = snmp.send(pdu, getTarget(), null);
	if(event != null) {
		PDU pdu2 = event.getResponse();
		VariableBinding[] binds = pdu2!=null?event.getResponse().toArray():null;
		if(binds!=null)
		{
			Map<OID, String> res = new LinkedHashMap<OID, String>(binds.length);
			for(VariableBinding b: binds)
				res.put(b.getOid(), b.getVariable().toString());
			return res;
		}else return null;
	}
	throw new RuntimeException("GET timed out");
}
 
Example #10
Source File: SNMPHelper.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
    boolean finished = false;
    if (pdu.getErrorStatus() != 0) {
        finished = true;
    } else if (vb.getOid() == null) {
        finished = true;
    } else if (vb.getOid().size() < targetOID.size()) {
        finished = true;
    } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
        finished = true;
    } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
        finished = true;
    } else if (vb.getOid().compareTo(targetOID) <= 0) {
        finished = true;
    }
    return finished;

}
 
Example #11
Source File: SNMPV3Session.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 获取设备描述字符串
 *
 * @return
 * @throws IOException
 */
public String getSysDesc() throws IOException {
    String key = getInfoCacheKey() + CACHE_KEY_SYS_DESC;
    String sysDesc = (String) infoCache.get(key);
    if(sysDesc != null){
        return sysDesc;
    }
    PDU pdu = this.get(SNMPHelper.SYS_DESC_OID);
    if(pdu != null){
        sysDesc = pdu.get(0).getVariable().toString();
        infoCache.put(key,sysDesc);
        return sysDesc;
    }else {
        return "";
    }

}
 
Example #12
Source File: SNMPV3Session.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 获取设备描述字符串
 *
 * @return
 * @throws IOException
 */
public String getSysDesc() throws IOException {
    String key = getInfoCacheKey() + cacheKey_sysDesc;
    String sysDesc = (String) infoCache.get(key);
    if(sysDesc != null){
        return sysDesc;
    }
    PDU pdu = this.get(SNMPHelper.sysDescOid);
    if(pdu != null){
        sysDesc = pdu.get(0).getVariable().toString();
        infoCache.put(key,sysDesc);
        return sysDesc;
    }else {
        return "";
    }

}
 
Example #13
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
private static boolean checkWalkFinished(OID targetOID, PDU pdu, VariableBinding vb) {
    boolean finished = false;
    if (pdu.getErrorStatus() != 0) {
        finished = true;
    } else if (vb.getOid() == null) {
        finished = true;
    } else if (vb.getOid().size() < targetOID.size()) {
        finished = true;
    } else if (targetOID.leftMostCompare(targetOID.size(), vb.getOid()) != 0) {
        finished = true;
    } else if (Null.isExceptionSyntax(vb.getVariable().getSyntax())) {
        finished = true;
    } else if (vb.getOid().compareTo(targetOID) <= 0) {
        finished = true;
    }
    return finished;

}
 
Example #14
Source File: SwitchMemoryStatCollect.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
private static CollectObject getCisco_IOS_XR_Mem(SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();
    collectObject.setMetrics(metricsName);
    collectObject.setSession(session);
    collectObject.setTime(new Date());

    String cpuIndex = "1.3.6.1.4.1.9.9.109.1.1.1.1.2";
    PDU cpuIndexPDU = session.getNext(cpuIndex);
    if(cpuIndexPDU.get(0) != null){
        int index  = Integer.parseInt(SNMPHelper.getValueFromPDU(cpuIndexPDU));
        String memUsedOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.18." + index + ".1";
        String memFreeOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.20." + index + ".1";
        PDU memUsedPDU = session.get(memUsedOid);
        PDU memFreePDU = session.get(memFreeOid);
        setRatioValueHelper(memUsedPDU,memFreePDU,collectObject);
    }

    return collectObject;
}
 
Example #15
Source File: SwitchMemoryStatCollect.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
private static CollectObject getCisco_ASA_Mem(SNMPV3Session session, String oid) throws IOException {
    String memUsedOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.18";
    List<PDU> memUsedListPDU = session.walk(memUsedOid);
    String memFreeOid = "1.3.6.1.4.1.9.9.221.1.1.1.1.20";
    List<PDU> memFreeListPDU = session.walk(memFreeOid);

    CollectObject collectObject = new CollectObject();
    collectObject.setMetrics(metricsName);
    collectObject.setSession(session);
    collectObject.setTime(new Date());

    if(SNMPHelper.isValidPDU(memFreeListPDU.get(0)) && SNMPHelper.isValidPDU(memUsedListPDU.get(0))){
        int memUsed = Integer.parseInt(SNMPHelper.getValueFromPDU(memUsedListPDU.get(0)));
        int memFree = Integer.parseInt(SNMPHelper.getValueFromPDU(memFreeListPDU.get(0)));
        if(memUsed+memFree != 0){
            collectObject.setValue(String.valueOf((double)memUsed / ((double)memUsed + (double)memFree)));
        }
    }

    return collectObject;
}
 
Example #16
Source File: SwitchMemoryStatCollect.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
static CollectObject getH3CHWcpumem(String metricsName,SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();

    List<PDU> pduList = session.walk(oid);
    String value = "";
    for (PDU pdu : pduList) {
        if(pdu.get(0).getVariable().toLong() != 0){
            value = SNMPHelper.getValueFromPDU(pdu);
            break;
        }
    }
    collectObject.setSession(session);
    collectObject.setMetrics(metricsName);
    collectObject.setValue(value);
    collectObject.setTime(new Date());

    return collectObject;
}
 
Example #17
Source File: SwitchMemoryStatCollect.java    From OpenFalcon-SuitAgent with Apache License 2.0 6 votes vote down vote up
private static CollectObject getOldHuawei_Mem(SNMPV3Session session, String oid) throws IOException {
    CollectObject collectObject = new CollectObject();
    collectObject.setSession(session);
    collectObject.setMetrics(metricsName);
    collectObject.setTime(new Date());

    String memTotalOid = "1.3.6.1.4.1.2011.6.1.2.1.1.2";
    List<PDU> snmpMemTotal = session.walk(memTotalOid);

    String memFreeOid = "1.3.6.1.4.1.2011.6.1.2.1.1.3";
    List<PDU> snmpMemFree = session.walk(memFreeOid);

    if(snmpMemFree.isEmpty() || snmpMemTotal.isEmpty()){
        log.warn("{} No Such Object available on this agent at this OID",session);
        return null;
    }

    int memTotal = Integer.parseInt(SNMPHelper.getValueFromPDU(snmpMemTotal.get(0)));
    int memFree = Integer.parseInt(SNMPHelper.getValueFromPDU(snmpMemFree.get(0)));
    collectObject.setValue(String.valueOf(((float) memTotal - (float)memFree) / (float)memTotal));

    return collectObject;
}
 
Example #18
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
private PDU createPDU() {
if(!"3".equals(this.version))
	return new PDU();
      ScopedPDU pdu = new ScopedPDU();
      if(this.context != null && !this.context.isEmpty())
        pdu.setContextEngineID(new OctetString(this.context));    //if not set, will be SNMP engine id            
      return pdu;  
  }
 
Example #19
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
public List<SNMPTriple> getDiskData(String device) throws IOException {

int index = this.getDiskIndex(device);
if(index<0)
{
	return new ArrayList<SNMPTriple>();
}
logger.fine("Query disk stats for "+index);
PDU pdu = createPDU();
for ( int i=1; i< DISK_TABLE_ENTRIES.length; i++) {
	if(DISK_TABLE_ENTRIES[i].length()==0)continue;
	pdu.add(new VariableBinding(new OID("."+DISK_TABLE_OID+"."+i+"."+index)));
}
pdu.setType(PDU.GET);
Map<String, String> res = new HashMap<String, String>(13);
ResponseEvent event = snmp.send(pdu, getTarget(), null);
if(event != null) {
	VariableBinding[] binds = event.getResponse().toArray();
	for(VariableBinding b: binds)
		res.put(b.getOid().toString(), b.getVariable().toString());
	//logger.info(res.toString());
}		
      List<SNMPTriple> resList = new ArrayList<SNMPTriple>(res.size());
      for(int i=1;i<DISK_TABLE_ENTRIES.length; i++) {
	if(DISK_TABLE_ENTRIES[i].length()==0)continue;
	resList.add(new SNMPTriple("."+DISK_TABLE_OID+"."+i+"."+index, DISK_TABLE_ENTRIES[i], res.get(DISK_TABLE_OID+"."+i+"."+index)));
      }
       return resList;
 }
 
Example #20
Source File: SNMPUtils.java    From ingestion with Apache License 2.0 5 votes vote down vote up
public static void sendTrapV2(String port) throws IOException {
    PDU trap = new PDU();
    trap.setType(PDU.TRAP);

    OID oid = new OID("1.2.3.4.5");
    trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, oid));
    trap.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(5000)));
    trap.add(new VariableBinding(SnmpConstants.sysDescr, new OctetString("System Description")));

    // Add Payload
    Variable var = new OctetString("some string");
    trap.add(new VariableBinding(oid, var));

    // Specify receiver
    Address targetaddress = new UdpAddress("127.0.0.1/" + port);
    CommunityTarget target = new CommunityTarget();
    target.setCommunity(new OctetString("public"));
    target.setVersion(SnmpConstants.version2c);
    target.setAddress(targetaddress);

    // Send
    Snmp snmp = new Snmp(new DefaultUdpTransportMapping());
    snmp.send(trap, target, null, null);

    snmp.close();
}
 
Example #21
Source File: PolatisAlarmConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Set<Alarm> translateAlarms(List<T> unparsedAlarms) {
    deviceId = handler().data().deviceId();
    Set<Alarm> alarms = new HashSet<>();
    for (T alarm : unparsedAlarms) {
        if (alarm instanceof CommandResponderEvent) {
            CommandResponderEvent alarmEvent = (CommandResponderEvent) alarm;
            PDU pdu = alarmEvent.getPDU();
            if (pdu != null) {
                String alarmType = pdu.getVariable(SNMP_TRAP_OID).toString();
                if (alarmType.equals(OPM_ALARM_OID.toString())) {
                    String label = pdu.getVariable(ALARM_PORT_LABEL_OID).toString();
                    int port = pdu.getVariable(ALARM_PORT_OID).toInt();
                    String uniqueIdentifier = "LOS" + port;
                    String status = pdu.getVariable(ALARM_STATUS_OID).toString();
                    String alarmMessage = "Loss of Service alarm " + status + " for fibre " + port;
                    SeverityLevel alarmLevel = SeverityLevel.MAJOR;
                    long timeRaised = 0;
                    DefaultAlarm.Builder alarmBuilder = new DefaultAlarm.Builder(
                            AlarmId.alarmId(deviceId, uniqueIdentifier),
                            deviceId, alarmMessage, alarmLevel, timeRaised);
                    if (status.equals(CLEARED)) {
                        long now = System.currentTimeMillis();
                        alarmBuilder.clear().withTimeUpdated(now).withTimeCleared(now);
                    }
                    alarms.add(alarmBuilder.build());
                }
            }
        }
    }
    return alarms;
}
 
Example #22
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 获取指定OID的 get
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static PDU snmpGet(Snmp snmp, Target target, String oid) throws IOException {
    ScopedPDU pdu = new ScopedPDU();
    pdu.setType(PDU.GET);
    pdu.add(new VariableBinding(new OID(oid)));

    ResponseEvent responseEvent = snmp.send(pdu, target);
    PDU response = responseEvent.getResponse();
    if(response == null){
        log.warn("response null - error:{} peerAddress:{} source:{} request:{}",
                responseEvent.getError(),
                responseEvent.getPeerAddress(),
                responseEvent.getSource(),
                responseEvent.getRequest());
    }
    return response;
}
 
Example #23
Source File: SNMPUtils.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Updates {@link FlowFile} with attributes representing PDU properties
 * @param response PDU retried from SNMP Agent
 * @param flowFile instance of target {@link FlowFile}
 * @param processSession instance of {@link ProcessSession}
 * @return updated {@link FlowFile}
 */
public static FlowFile updateFlowFileAttributesWithPduProperties(PDU response, FlowFile flowFile, ProcessSession processSession) {
    if (response != null) {
        try {
            Method[] methods = PDU.class.getDeclaredMethods();
            Map<String, String> attributes = new HashMap<String, String>();
            for (Method method : methods) {
                if (Modifier.isPublic(method.getModifiers()) && (method.getParameterTypes().length == 0) && method.getName().startsWith("get")) {
                    String propertyName = extractPropertyNameFromMethod(method);
                    if (isValidSnmpPropertyName(propertyName)) {
                        Object amqpPropertyValue = method.invoke(response);
                        if (amqpPropertyValue != null) {
                            if (propertyName.equals(SNMP_PROP_PREFIX + "variableBindings") && (amqpPropertyValue instanceof Vector)) {
                                addGetOidValues(attributes, amqpPropertyValue);
                            } else {
                                attributes.put(propertyName, amqpPropertyValue.toString());
                            }
                        }
                    }
                }
            }
            flowFile = processSession.putAllAttributes(flowFile, attributes);
        } catch (Exception e) {
            logger.warn("Failed to update FlowFile with AMQP attributes", e);
        }
    }
    return flowFile;
}
 
Example #24
Source File: SNMPClient.java    From mysql_perf_analyzer with Apache License 2.0 5 votes vote down vote up
public ResponseEvent getEvent(OID oids[]) throws IOException 
{
	PDU pdu = createPDU();
	for (OID oid : oids) {
		pdu.add(new VariableBinding(oid));
	}
	pdu.setType(PDU.GET);
	ResponseEvent event = snmp.send(pdu, getTarget(), null);
	if(event != null) {
		return event;
	}
	throw new RuntimeException("GET timed out");
}
 
Example #25
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 判断传入的PDU是否带有可用的监控数据
 * @param pdu
 * @param index
 * 指定的索引的VariableBinding对象
 * @return
 * true : 可用
 * false : 不可用
 */
public static boolean isValidPDU(PDU pdu,int index){
    if(pdu == null){
        return false;
    }
    VariableBinding vb = pdu.get(index);
    if(vb == null){
        return false;
    }
    String vbResult = vb.toString();
    return !"noSuchInstance".equalsIgnoreCase(vbResult) &&
            !"noSuchObject".equalsIgnoreCase(vbResult) &&
            !"noNextInstance".equalsIgnoreCase(vbResult) &&
            !"endOfView".equalsIgnoreCase(vbResult);
}
 
Example #26
Source File: SNMPHelper.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 判断传入的PDU是否带有可用的监控数据(PDU携带的第一个VariableBinding对象)
 * @param pdu
 * @return
 * true : 可用
 * false : 不可用
 */
public static boolean isValidPDU(PDU pdu){
    if(pdu == null){
        return false;
    }
    VariableBinding vb = pdu.get(0);
    if(vb == null){
        return false;
    }
    String vbResult = vb.toString();
    return !"noSuchInstance".equalsIgnoreCase(vbResult) &&
            !"noSuchObject".equalsIgnoreCase(vbResult) &&
            !"noNextInstance".equalsIgnoreCase(vbResult) &&
            !"endOfView".equalsIgnoreCase(vbResult);
}
 
Example #27
Source File: SwitchMemoryStatCollect.java    From OpenFalcon-SuitAgent with Apache License 2.0 5 votes vote down vote up
/**
 * 使用率设值
 * @param usedPDU
 * @param freePDU
 * @param collectObject
 */
private static void setRatioValueHelper(PDU usedPDU, PDU freePDU, CollectObject collectObject){
    if(SNMPHelper.isValidPDU(usedPDU) && SNMPHelper.isValidPDU(freePDU)){
        int used = Integer.parseInt(SNMPHelper.getValueFromPDU(usedPDU));
        int free = Integer.parseInt(SNMPHelper.getValueFromPDU(freePDU));
        if (free + used != 0){
            collectObject.setValue(String.valueOf((float) used / ((float)used + (float)free)));
        }
    }
}
 
Example #28
Source File: SnmpHelper.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
private PDU createPDU(SnmpTrapInfo snmpTrapInfo) {
    PDU trap = new PDU();
    trap.setType(PDU.TRAP);

    int alertType = snmpTrapInfo.getAlertType() + 1;
    if (alertType > 0) {
        long sysUpTimeTicks = ManagementFactory.getRuntimeMXBean().getUptime() / 10;
        trap.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(sysUpTimeTicks)));
        trap.add(new VariableBinding(SnmpConstants.snmpTrapOID, getOID(CsSnmpConstants.TRAPS_PREFIX + alertType)));
        if (snmpTrapInfo.getDataCenterId() != 0) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.DATA_CENTER_ID), new UnsignedInteger32(snmpTrapInfo.getDataCenterId())));
        }

        if (snmpTrapInfo.getPodId() != 0) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.POD_ID), new UnsignedInteger32(snmpTrapInfo.getPodId())));
        }

        if (snmpTrapInfo.getClusterId() != 0) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.CLUSTER_ID), new UnsignedInteger32(snmpTrapInfo.getClusterId())));
        }

        if (snmpTrapInfo.getMessage() != null) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.MESSAGE), new OctetString(snmpTrapInfo.getMessage())));
        } else {
            throw new CloudRuntimeException(" What is the use of alert without message ");
        }

        if (snmpTrapInfo.getGenerationTime() != null) {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.GENERATION_TIME), new OctetString(snmpTrapInfo.getGenerationTime().toString())));
        } else {
            trap.add(new VariableBinding(getOID(CsSnmpConstants.GENERATION_TIME)));
        }
    } else {
        throw new CloudRuntimeException(" Invalid alert Type ");
    }

    return trap;
}
 
Example #29
Source File: SNMPIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnmpEndpoint() throws Exception {
    int port = AvailablePortFinder.getNextAvailable();

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            fromF("snmp://localhost:%d?protocol=tcp&type=TRAP", port)
            .to("mock:result");
        }
    });

    camelctx.start();
    try {
        String uri = String.format("snmp://localhost:%d?oids=%s&protocol=tcp", port, SNMP_OIDS);

        ProducerTemplate template = camelctx.createProducerTemplate();
        SnmpMessage message = template.requestBody(uri, null, SnmpMessage.class);
        PDU snmpMessage = message.getSnmpMessage();

        Assert.assertNotNull(snmpMessage);
        Assert.assertEquals(0, snmpMessage.getErrorStatus());
    } finally {
        camelctx.close();
    }
}
 
Example #30
Source File: SNMPUtils.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Updates {@link FlowFile} with attributes representing PDU properties
 * @param response PDU retried from SNMP Agent
 * @param flowFile instance of target {@link FlowFile}
 * @param processSession instance of {@link ProcessSession}
 * @return updated {@link FlowFile}
 */
public static FlowFile updateFlowFileAttributesWithPduProperties(PDU response, FlowFile flowFile, ProcessSession processSession) {
    if (response != null) {
        try {
            Method[] methods = PDU.class.getDeclaredMethods();
            Map<String, String> attributes = new HashMap<String, String>();
            for (Method method : methods) {
                if (Modifier.isPublic(method.getModifiers()) && (method.getParameterTypes().length == 0) && method.getName().startsWith("get")) {
                    String propertyName = extractPropertyNameFromMethod(method);
                    if (isValidSnmpPropertyName(propertyName)) {
                        Object amqpPropertyValue = method.invoke(response);
                        if (amqpPropertyValue != null) {
                            if (propertyName.equals(SNMP_PROP_PREFIX + "variableBindings") && (amqpPropertyValue instanceof Vector)) {
                                addGetOidValues(attributes, amqpPropertyValue);
                            } else {
                                attributes.put(propertyName, amqpPropertyValue.toString());
                            }
                        }
                    }
                }
            }
            flowFile = processSession.putAllAttributes(flowFile, attributes);
        } catch (Exception e) {
            logger.warn("Failed to update FlowFile with AMQP attributes", e);
        }
    }
    return flowFile;
}