org.snmp4j.smi.VariableBinding Java Examples

The following examples show how to use org.snmp4j.smi.VariableBinding. 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: SNMPClient.java    From mysql_perf_analyzer with 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 File: SnmpH3C.java    From yuzhouwan with Apache License 2.0 7 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 #3
Source File: PolatisOpticalUtility.java    From onos with 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 #4
Source File: PolatisPowerConfig.java    From onos with 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 #5
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with 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 #6
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 #7
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 #8
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 #9
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 #10
Source File: PolatisFlowRuleProgrammable.java    From onos with 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 #11
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 #12
Source File: SnmpH3C.java    From yuzhouwan with 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 #13
Source File: SNMPClient.java    From mysql_perf_analyzer with 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 #14
Source File: SNMPClient.java    From mysql_perf_analyzer with 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 #15
Source File: LumentumAlarmConsumer.java    From onos with 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 #16
Source File: SNMPClient.java    From mysql_perf_analyzer with 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 #17
Source File: SNMPUtils.java    From localization_nifi with 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 #18
Source File: SNMPUtils.java    From nifi with 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 #19
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 #20
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 #21
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 #22
Source File: SNMPUtils.java    From nifi with 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 #23
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 #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 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 #26
Source File: SNMPHelper.java    From 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 #27
Source File: SNMPUtils.java    From localization_nifi with 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 #28
Source File: SNMPHelper.java    From 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 #29
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 4 votes vote down vote up
private List<FlowRule> fetchRules(OID oid, boolean isAdd, PortNumber linePort) {
    List<FlowRule> rules = new LinkedList<>();

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

        VariableBinding[] varBindings = event.getVariableBindings();
        for (VariableBinding varBinding : varBindings) {
            CrossConnectCache cache = this.handler().get(CrossConnectCache.class);

            if (varBinding.getVariable().toInt() == IN_SERVICE) {
                int channel = varBinding.getOid().removeLast();

                PortNumber addDropPort = getAddDropPort(channel, isAdd);
                if (addDropPort == null) {
                    continue;
                }

                TrafficSelector selector = DefaultTrafficSelector.builder()
                        .matchInPort(isAdd ? addDropPort : linePort)
                        .add(Criteria.matchOchSignalType(OchSignalType.FIXED_GRID))
                        .add(Criteria.matchLambda(toOchSignal(channel)))
                        .build();
                TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                        .setOutput(isAdd ? linePort : addDropPort)
                        .build();

                // Lookup flow ID and priority
                int hash = Objects.hash(data().deviceId(), selector, treatment);
                Pair<FlowId, Integer> lookup = cache.get(hash);
                if (lookup == null) {
                    continue;
                }

                FlowRule fr = DefaultFlowRule.builder()
                        .forDevice(data().deviceId())
                        .makePermanent()
                        .withSelector(selector)
                        .withTreatment(treatment)
                        .withPriority(lookup.getRight())
                        .withCookie(lookup.getLeft().value())
                        .build();
                rules.add(fr);
            }
        }
    }

    return rules;
}
 
Example #30
Source File: PolatisPowerConfig.java    From onos with Apache License 2.0 4 votes vote down vote up
private List<PortNumber> acquirePorts() {
    List<TableEvent> events;
    DeviceId deviceId = handler().data().deviceId();
    List<PortNumber> ports = new ArrayList<>();

    try {
        OID[] columnOIDs = {new OID(OPM_POWER_OID)};
        events = getTable(handler(), columnOIDs);
    } catch (IOException e) {
        log.error("Error reading opm power table for device {} exception {}", deviceId, e);
        return ports;
    }

    if (events == null) {
        log.error("Error reading opm power table for device {}", deviceId);
        return ports;
    }

    for (TableEvent event : events) {
        if (event == null) {
            log.error("Error reading event for device {}", deviceId);
            continue;
        }
        VariableBinding[] columns = event.getColumns();
        if (columns == null) {
            log.error("Error reading columns for device {}", deviceId);
            continue;
        }

        VariableBinding opmColumn = columns[0];
        if (opmColumn == null) {
            continue;
        }

        int port = event.getIndex().last();
        int opm = opmColumn.getVariable().toInt();
        if (opm == 0) {
            continue;
        }

        ports.add(PortNumber.portNumber(port));
    }

    return ports;
}