Java Code Examples for org.snmp4j.smi.VariableBinding

The following examples show how to use org.snmp4j.smi.VariableBinding. These examples are extracted from open source projects. 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 Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: Apache License 2.0 8 votes vote down vote up
public List<SNMPTriple> querySingleSNMPTableByOID(String oid) throws IOException
{
 if(oid == null || oid.isEmpty())return null;
 if(!oid.startsWith("."))oid = "."+oid;
    TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
    List<TableEvent> events = tUtils.getTable(getTarget(), new OID[]{new OID(oid)}, null, null);

 List<SNMPTriple> snmpList = new ArrayList<SNMPTriple>();
    
    for (TableEvent event : events) {
      if(event.isError()) {
     	 logger.warning(this.address + ": SNMP event error: "+event.getErrorMessage());
     	 continue;
           //throw new RuntimeException(event.getErrorMessage());
      }
      for(VariableBinding vb: event.getColumns()) {
   	   String key = vb.getOid().toString();
   	   String value = vb.getVariable().toString();
   	 snmpList.add(new SNMPTriple(key, "", value));
      }
    }
 return snmpList;
}
 
Example #2
Source Project: SuitAgent   Author: DevopsJK   File: SNMPHelper.java    License: 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 #3
Source Project: OpenFalcon-SuitAgent   Author: cqyijifu   File: SNMPHelper.java    License: 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 #4
Source Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: 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 #5
Source Project: yuzhouwan   Author: asdf2014   File: SnmpH3C.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Send PDU to H3C, then waiting response event will be caught by listener.
 *
 * @param snmp
 * @param userTarget
 * @param pdu
 * @throws IOException
 * @throws InterruptedException
 */
private void sendGetPDU(Snmp snmp, UserTarget userTarget, ScopedPDU pdu)
        throws IOException, InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);
    ResponseListener listener = new ResponseListener() {

        @Override
        public void onResponse(ResponseEvent event) {
            ((Snmp) event.getSource()).cancel(event.getRequest(), this);
            PDU response = event.getResponse();
            PDU request = event.getRequest();
            LOG.debug("[request]: {}", request);

            if (response == null) {
                LOG.error("[ERROR]: response is null");

            } else if (response.getErrorStatus() != 0) {
                LOG.error(String.format("[ERROR]: response status %s, Text: %s",
                        response.getErrorStatus(),
                        response.getErrorStatusText()));
            } else {
                LOG.debug("Received response Success!");
                for (int i = 0; i < response.size(); i++) {
                    VariableBinding vb = response.get(i);
                    LOG.info("{} = {}",
                            vb.getOid(),
                            vb.getVariable());
                }
                LOG.debug("SNMP Async GetList OID finished. ");
                latch.countDown();
            }
        }
    };
    snmp.send(pdu, userTarget, null, listener);
    LOG.debug("async send pdu wait for response...");

    boolean wait = latch.await(3, TimeUnit.SECONDS);
    LOG.debug("latch.await =:" + wait);
}
 
Example #6
Source Project: onos   Author: opennetworkinglab   File: PolatisOpticalUtility.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Transforms a flow FlowRule object to a variable binding.
 * @param rule FlowRule object
 * @param delete whether it is a delete or edit request
 * @return variable binding
 */
public static VariableBinding fromFlowRule(FlowRule rule, boolean delete) {
    Set<Criterion> criterions = rule.selector().criteria();
    PortNumber inPort = criterions.stream()
            .filter(c -> c instanceof PortCriterion)
            .map(c -> ((PortCriterion) c).port())
            .findAny()
            .orElse(null);
    long input = inPort.toLong();
    List<Instruction> instructions = rule.treatment().immediate();
    PortNumber outPort = instructions.stream()
            .filter(c -> c instanceof Instructions.OutputInstruction)
            .map(c -> ((Instructions.OutputInstruction) c).port())
            .findAny()
            .orElse(null);
    long output = outPort.toLong();
    OID oid = new OID(PORT_PATCH_OID + "." + input);
    Variable var = new UnsignedInteger32(delete ? 0 : output);
    return new VariableBinding(oid, var);
}
 
Example #7
Source Project: onos   Author: opennetworkinglab   File: PolatisPowerConfig.java    License: Apache License 2.0 6 votes vote down vote up
private boolean setPortTargetPower(PortNumber port, long power) {
    log.debug("Set port{} target power...", port);
    List<VariableBinding> vbs = new ArrayList<>();

    OID voaStateOid = new OID(VOA_STATE_OID + "." + port.toLong());
    Variable voaStateVar = new UnsignedInteger32(VOA_STATE_ABSOLUTE);
    VariableBinding voaStateVb = new VariableBinding(voaStateOid, voaStateVar);
    vbs.add(voaStateVb);

    OID voaLevelOid = new OID(VOA_LEVEL_OID + "." + port.toLong());
    Variable voaLevelVar = new UnsignedInteger32(power);
    VariableBinding voaLevelVb = new VariableBinding(voaLevelOid, voaLevelVar);
    vbs.add(voaLevelVb);

    DeviceId deviceId = handler().data().deviceId();
    try {
        set(handler(), vbs);
    } catch (IOException e) {
        log.error("Error writing ports table for device {} exception {}", deviceId, e);
        return false;
    }
    return true;
}
 
Example #8
Source Project: onos   Author: opennetworkinglab   File: LumentumSdnRoadmFlowRuleProgrammable.java    License: Apache License 2.0 6 votes vote down vote up
private PortNumber getAddDropPort(int channel, boolean isAddPort) {
    OID oid = new OID(CTRL_CHANNEL_ADD_DROP_PORT_INDEX + (isAddPort ? "1" : "2"));

    for (TreeEvent event : snmp.get(oid)) {
        if (event == null) {
            return null;
        }

        VariableBinding[] varBindings = event.getVariableBindings();

        for (VariableBinding varBinding : varBindings) {
            if (varBinding.getOid().last() == channel) {
                int port = varBinding.getVariable().toInt();
                if (!isAddPort) {
                    port += DROP_PORT_OFFSET;
                }
                return PortNumber.portNumber(port);

            }
        }

    }

    return null;
}
 
Example #9
Source Project: localization_nifi   Author: wangrenlei   File: SNMPUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to construct {@link FlowFile} attributes from a vector of {@link VariableBinding}
 * @param attributes attributes
 * @param vector vector of {@link VariableBinding}
 */
private static void addWalkOidValues(Map<String, String> attributes, Object vector) {
    if (vector instanceof VariableBinding[]) {
        VariableBinding[] variables = (VariableBinding[]) vector;
        for (VariableBinding variableBinding : variables) {
            addAttributeFromVariable(variableBinding, attributes);
        }
    }
}
 
Example #10
Source Project: localization_nifi   Author: wangrenlei   File: SNMPUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to construct {@link FlowFile} attributes from a vector of {@link VariableBinding}
 * @param attributes attributes
 * @param vector vector of {@link VariableBinding}
 */
private static void addGetOidValues(Map<String, String> attributes, Object vector) {
    if (vector instanceof Vector) {
        @SuppressWarnings("unchecked")
        Vector<VariableBinding> variables = (Vector<VariableBinding>) vector;
        for (VariableBinding variableBinding : variables) {
            addAttributeFromVariable(variableBinding, attributes);
        }
    }
}
 
Example #11
Source Project: SuitAgent   Author: DevopsJK   File: SNMPHelper.java    License: 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 #12
Source Project: SuitAgent   Author: DevopsJK   File: SNMPHelper.java    License: 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 #13
Source Project: SuitAgent   Author: DevopsJK   File: SNMPHelper.java    License: 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 #14
Source Project: OpenFalcon-SuitAgent   Author: cqyijifu   File: SNMPHelper.java    License: 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 #15
Source Project: OpenFalcon-SuitAgent   Author: cqyijifu   File: SNMPHelper.java    License: 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 #16
Source Project: OpenFalcon-SuitAgent   Author: cqyijifu   File: SNMPHelper.java    License: 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 #17
Source Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: 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 #18
Source Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: 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 #19
Source Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: Apache License 2.0 5 votes vote down vote up
private int getDiskIndex(String device) throws IOException {

      TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
      
      logger.fine("Query "+this.address+" for disk data: "+device);
       @SuppressWarnings("unchecked")
       List<TableEvent> events = tUtils.getTable(getTarget(), new OID[]{new OID("."+DISK_TABLE_DEVICE_OID)}, null, null);

       for (TableEvent event : events) {
         if(event.isError()) {
        	 logger.warning(this.address + ": SNMP event error: "+event.getErrorMessage());
        	 continue;
              //throw new RuntimeException(event.getErrorMessage());
         }
         for(VariableBinding vb: event.getColumns()) {
      	   String key = vb.getOid().toString();
      	   String value = vb.getVariable().toString();
      	   if(value!=null && value.equals(device))
      	   {
      	       logger.fine("Find device OID entry: "+key);
      	         int index = -1;
      	         String[] strs = key.split("\\.");
      	         try
      	         {
      	        	 index = Integer.parseInt(strs[strs.length-1]);
      	         }catch(Exception ex){}
      	         return index;
      	   }
         }
       }
       return -1;
 }
 
Example #20
Source Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: Apache License 2.0 5 votes vote down vote up
private Map<Integer, String> getNetIfIndexes(String device) throws IOException {
  Map<Integer, String> ifMaps = new HashMap<Integer, String> ();
		
     TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
     
     logger.fine("Query "+this.address+" for network interface, excluding lo");
      @SuppressWarnings("unchecked")
      List<TableEvent> events = tUtils.getTable(getTarget(), new OID[]{new OID("."+IF_TABLE_DEVICE_OID)}, null, null);

      for (TableEvent event : events) {
        if(event.isError()) {
       	 logger.warning(this.address + ": SNMP event error: "+event.getErrorMessage());
       	 continue;
             //throw new RuntimeException(event.getErrorMessage());
        }
        for(VariableBinding vb: event.getColumns()) {
     	   String key = vb.getOid().toString();
     	   String value = vb.getVariable().toString();
     	   if(device!=null && !device.isEmpty() && !value.equalsIgnoreCase(device))
     		   continue;
     	   if(value!=null && !value.equalsIgnoreCase("lo"))
     	   {
     	       logger.fine("Find device OID entry: "+key);
     	         int index = -1;
     	         String[] strs = key.split("\\.");
     	         try
     	         {
     	        	 index = Integer.parseInt(strs[strs.length-1]);
     	        	 ifMaps.put(index, value);
     	         }catch(Exception ex){}
     	   }
        }
      }
      return ifMaps;
}
 
Example #21
Source Project: mysql_perf_analyzer   Author: yahoo   File: SNMPClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
  * Query index for given process name. Note the parameter only provides 128 characters,
  * so it could be difficult for us to differentiate each other if multi processes with same name exist.
  * So we will return this list and use the sum from all processes for our metrics
  * @param process
  * @return
  * @throws IOException
  */
 private List<Integer> getProcessIndexes(String process) throws IOException {
  List<Integer> indexes = new ArrayList<Integer> ();
     if(process == null || process.isEmpty())return indexes;

     TableUtils tUtils = new TableUtils(snmp, new DefaultPDUFactory());
     logger.fine("Query "+this.address+" for process " + process);
      @SuppressWarnings("unchecked")
      List<TableEvent> events = tUtils.getTable(getTarget(), new OID[]{new OID("."+PROCESS_TABLE_OID)}, null, null);

      for (TableEvent event : events) {
        if(event.isError()) {
       	 logger.warning(this.address + ": SNMP event error: "+event.getErrorMessage());
       	 continue;
             //throw new RuntimeException(event.getErrorMessage());
        }
        for(VariableBinding vb: event.getColumns()) {
     	   String key = vb.getOid().toString();
     	   String value = vb.getVariable().toString();
     	   if(process!=null && !process.isEmpty() && !value.equalsIgnoreCase(process))
     		   continue;
     	   if(value!=null)
     	   {
     	       logger.fine("Find process OID entry: "+key);
     	       int index = -1;
     	       String[] strs = key.split("\\.");
     	       try
     	       {
     	    	   index = Integer.parseInt(strs[strs.length-1]);
     	    	   indexes.add(index);
     	       }catch(Exception ex){}
     	   }
        }
      }
      return indexes;
}
 
Example #22
Source Project: yuzhouwan   Author: asdf2014   File: SnmpH3C.java    License: Apache License 2.0 5 votes vote down vote up
private void addOIDs2PDU(List<String> oidList) {
    pdu = new ScopedPDU();
    pdu.setType(PDU.GET);
    for (String oid : oidList) {
        pdu.add(new VariableBinding(new OID(oid)));
    }
}
 
Example #23
Source Project: ingestion   Author: Stratio   File: SNMPUtils.java    License: 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 #24
Source Project: onos   Author: opennetworkinglab   File: PolatisFlowRuleProgrammable.java    License: Apache License 2.0 5 votes vote down vote up
private boolean editConnection(FlowRule rule, boolean delete) {
    List<VariableBinding> vbs = new ArrayList<>();
    vbs.add(fromFlowRule(rule, delete));
    DeviceId deviceId = handler().data().deviceId();
    try {
        set(handler(), vbs);
    } catch (IOException e) {
        log.error("Error writing ports table for device {} exception {}", deviceId, e);
        return false;
    }
    // TODO: check for errors
    return true;
}
 
Example #25
Source Project: onos   Author: opennetworkinglab   File: LumentumAlarmConsumer.java    License: Apache License 2.0 5 votes vote down vote up
private int getAlarmId(TreeEvent treeEvents) {
    VariableBinding[] varBindings = treeEvents.getVariableBindings();
    for (VariableBinding varBinding : varBindings) {
        return varBinding.getVariable().toInt();
    }
    return -1;
}
 
Example #26
Source Project: nifi   Author: apache   File: SNMPUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to construct {@link FlowFile} attributes from a vector of {@link VariableBinding}
 * @param attributes attributes
 * @param vector vector of {@link VariableBinding}
 */
private static void addWalkOidValues(Map<String, String> attributes, Object vector) {
    if (vector instanceof VariableBinding[]) {
        VariableBinding[] variables = (VariableBinding[]) vector;
        for (VariableBinding variableBinding : variables) {
            addAttributeFromVariable(variableBinding, attributes);
        }
    }
}
 
Example #27
Source Project: nifi   Author: apache   File: SNMPUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Method to construct {@link FlowFile} attributes from a vector of {@link VariableBinding}
 * @param attributes attributes
 * @param vector vector of {@link VariableBinding}
 */
private static void addGetOidValues(Map<String, String> attributes, Object vector) {
    if (vector instanceof Vector) {
        @SuppressWarnings("unchecked")
        Vector<VariableBinding> variables = (Vector<VariableBinding>) vector;
        for (VariableBinding variableBinding : variables) {
            addAttributeFromVariable(variableBinding, attributes);
        }
    }
}
 
Example #28
Source Project: cloudstack   Author: apache   File: SnmpHelper.java    License: 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 Project: SuitAgent   Author: DevopsJK   File: SNMPHelper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * walk方式获取指定的oid value
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static List<PDU> snmpWalk(Snmp snmp, Target target, String oid) throws IOException {
    List<PDU> pduList = new ArrayList<>();

    ScopedPDU pdu = new ScopedPDU();
    OID targetOID = new OID(oid);
    pdu.add(new VariableBinding(targetOID));

    boolean finished = false;
    while (!finished) {
        VariableBinding vb = null;
        ResponseEvent respEvent = snmp.getNext(pdu, target);

        PDU response = respEvent.getResponse();

        if (null == response) {
            break;
        } else {
            vb = response.get(0);
        }
        // check finish
        finished = checkWalkFinished(targetOID, pdu, vb);
        if (!finished) {
            pduList.add(response);

            // Set up the variable binding for the next entry.
            pdu.setRequestID(new Integer32(0));
            pdu.set(0, vb);
        }
    }

    return pduList;
}
 
Example #30
Source Project: OpenFalcon-SuitAgent   Author: cqyijifu   File: SNMPHelper.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * walk方式获取指定的oid value
 *
 * @param snmp
 * @param target
 * @param oid
 * @return
 * @throws IOException
 */
public static List<PDU> snmpWalk(Snmp snmp, Target target, String oid) throws IOException {
    List<PDU> pduList = new ArrayList<>();

    ScopedPDU pdu = new ScopedPDU();
    OID targetOID = new OID(oid);
    pdu.add(new VariableBinding(targetOID));

    boolean finished = false;
    while (!finished) {
        VariableBinding vb = null;
        ResponseEvent respEvent = snmp.getNext(pdu, target);

        PDU response = respEvent.getResponse();

        if (null == response) {
            break;
        } else {
            vb = response.get(0);
        }
        // check finish
        finished = checkWalkFinished(targetOID, pdu, vb);
        if (!finished) {
            pduList.add(response);

            // Set up the variable binding for the next entry.
            pdu.setRequestID(new Integer32(0));
            pdu.set(0, vb);
        }
    }

    return pduList;
}