[jboss-cvs] JBossAS SVN: r110455 - in branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp: config/attribute and 4 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Wed Jan 26 12:24:12 EST 2011
Author: thauser at redhat.com
Date: 2011-01-26 12:24:12 -0500 (Wed, 26 Jan 2011)
New Revision: 110455
Added:
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTable.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTableRow.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java
Modified:
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java
branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java
Log:
rebase work from snmp4j-integration-1.11.1 branch
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -26,6 +26,7 @@
import org.jboss.jmx.adaptor.snmp.config.attribute.AttributeMappings;
import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute;
+import org.jboss.jmx.adaptor.snmp.config.attribute.MappedTable;
import org.jboss.logging.Logger;
import org.jboss.xb.binding.ObjectModelFactory;
import org.jboss.xb.binding.UnmarshallingContext;
@@ -87,9 +88,10 @@
public Object newChild(ManagedBean mbean, UnmarshallingContext navigator,
String namespaceUri, String localName, Attributes attrs)
{
+ Object placeholder = null;
- MappedAttribute attribute = null;
if ("attribute".equals(localName)) {
+ MappedAttribute attribute = null;
String oid = attrs.getValue("oid");
String name = attrs.getValue("name");
String mode = attrs.getValue("mode");
@@ -98,8 +100,22 @@
attribute.setReadWrite(true);
attribute.setName(name);
attribute.setOid(oid);
+ return attribute;
}
- return attribute;
+ else if ("table".equals(localName)){
+ MappedTable attribute = null;
+ String oidPrefix = attrs.getValue("oid-prefix");
+ String name = attrs.getValue("name");
+ int size = Integer.parseInt(attrs.getValue("size"));
+ attribute = new MappedTable();
+ attribute.setName(name);
+ attribute.setPrefix(oidPrefix);
+ attribute.setSize(size);
+ return attribute;
+ }
+
+ return placeholder;
+
}
public void addChild(ManagedBean mbean, MappedAttribute attribute,
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EndOfMibViewException.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,20 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+/** This exception is thrown when a GETNEXT or GETBULK operation
+ * attempts to get an OID that is not in the MIB
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ *
+ */
+
+public class EndOfMibViewException extends Exception {
+
+ public EndOfMibViewException(){
+ super("Traversal of the tree left the subtree.");
+
+ }
+
+ public EndOfMibViewException(String m){
+ super(m);
+ }
+}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -32,4 +32,9 @@
public final String COLDSTART = "jboss.snmp.agent.coldstart";
public final String HEARTBEAT = "jboss.snmp.agent.heartbeat";
+ /** Notification types for testing */
+ public final String V1_TEST_NOTIFICATION = "jboss.snmp.agent.v1test";
+ public final String V2_TEST_NOTIFICATION = "jboss.snmp.agent.v2test";
+ public final String V3_TEST_NOTIFICATION = "jboss.snmp.agent.v3test";
+
}
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchInstanceException.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,20 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import org.snmp4j.smi.OID;
+
+/** This exception is thrown when a manager attempts to retrieve an instance of an object
+ * that does not exist.
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ */
+
+public class NoSuchInstanceException extends Exception {
+
+ public NoSuchInstanceException(){
+ super("Error: Requested an Instance of an Object that does not exist.");
+ }
+
+ public NoSuchInstanceException(OID oid){
+ super("Error: The following Instance does not exist: "+oid);
+ }
+}
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NoSuchObjectException.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,20 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import org.snmp4j.smi.OID;
+
+/** This exception is thrown when a manager attempts to retrieve information
+ * about an OID that does not exist in the attributes.xml
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ */
+
+public class NoSuchObjectException extends Exception {
+
+ public NoSuchObjectException(){
+ super("Error: Requested an OID that does not exist.");
+ }
+
+ public NoSuchObjectException(OID oid){
+ super("Error: The following OID does not exist: "+oid);
+ }
+}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -21,7 +21,7 @@
*/
package org.jboss.jmx.adaptor.snmp.agent;
-import org.opennms.protocols.snmp.SnmpObjectId;
+import org.snmp4j.smi.OID;
/**
* This exception is thrown when an entry is read only and
@@ -37,7 +37,7 @@
super("OID " + oid + " is read only");
}
- public ReadOnlyException(SnmpObjectId oid)
+ public ReadOnlyException(OID oid)
{
super("OID " + oid + " is read only");
}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -24,7 +24,7 @@
import javax.management.MBeanServer;
import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpAgentHandler;
+//import org.opennms.protocols.snmp.SnmpAgentHandler;
/**
* Interface that must be implemented by classes
@@ -33,7 +33,7 @@
* @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
* @version $Revision$
*/
-public interface RequestHandler extends SnmpAgentHandler
+public interface RequestHandler extends SnmpAgentRequestHandler
{
/**
* Perform initialization, possibly by parsing
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -28,7 +28,9 @@
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
+import java.util.HashSet;
import java.util.TreeSet;
+import java.util.Vector;
import javax.management.Attribute;
import javax.management.MBeanServer;
@@ -37,11 +39,29 @@
import org.jboss.jmx.adaptor.snmp.config.attribute.AttributeMappings;
import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute;
+import org.jboss.jmx.adaptor.snmp.config.attribute.MappedTable;
import org.jboss.logging.Logger;
import org.jboss.xb.binding.ObjectModelFactory;
import org.jboss.xb.binding.Unmarshaller;
import org.jboss.xb.binding.UnmarshallerFactory;
-import org.opennms.protocols.snmp.*;
+//import org.opennms.protocols.snmp.*;
+import org.snmp4j.PDU;
+import org.snmp4j.PDUv1;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.event.ResponseEvent;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.smi.Counter32;
+import org.snmp4j.smi.Counter64;
+import org.snmp4j.smi.Integer32;
+import org.snmp4j.smi.Null;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.TimeTicks;
+import org.snmp4j.smi.Variable;
+import org.snmp4j.smi.VariableBinding;
+import org.snmp4j.util.DefaultPDUFactory;
+import org.snmp4j.util.PDUFactory;
/**
* Implement RequestHandler with mapping of snmp get/set requests
@@ -56,7 +76,7 @@
{
// Protected Data ------------------------------------------------
- private static final String NO_ENTRY_FOUND_FOR_OID = "No entry found for oid ";
+ private static final String NO_ENTRY_FOUND_FOR_OID = "No bind entry found for oid ";
private static final String SKIP_ENTRY = " - skipping entry";
@@ -68,6 +88,7 @@
/** Has this RequestHandler instance been initialized? */
private boolean initialized = false;
+
// Constructors --------------------------------------------------
/**
@@ -102,6 +123,9 @@
initialized = true;
}
+ // TODO: change all error handling to Exceptions. Much more extensible.
+ // this must be done because the use of return values could be much more useful if exceptions were thrown instead.
+ // TODO: getValueFor, setValueFor, and getNextOid all need to throw appropriate exceptions.
// Reconfigurable Implementation ---------------------------------
/**
* Reconfigures the RequestHandler
@@ -125,7 +149,153 @@
// SnmpAgentHandler Implementation -------------------------------
- /**
+ /**
+ * <P>
+ * This method handles SNMP GetBulk requests received in this session. Request
+ * is already validated. Builds a response and passes it back.
+ * A GetBulk request has two additional fields:
+ * nonRepeaters: the amount of scalar objects in the PDU
+ * maxRepetitions: the number of getNext requests to be done on the scalar objects.
+ * The parameter PDU is interpreted as follows:
+ * The first nonRepeaters elements in the VariableBinding list are retrieved with a simple GET snmp call.
+ * The remaining (size - nonRepeaters) elements in the VariableBinding list have maxRepetitions GETNEXT calls
+ * upon them. All of these VariableBindings are added into the response.
+ * The resultant response will have N + (M*R) VariableBindings
+ *
+ * </P>
+ * @param pdu
+ * contains the following:
+ * a list of OIDs
+ * an Integer > 0 indicating the number of non-repeaters (set with PDU.setNonRepeaters())
+ * an Integer >= 0 indicating the number of repetitions (set with PDU.setMaxRepetitions())
+ * @return a PDU filled with the appropriate values, and if values were not found, null for those values. GetBulk
+ * will rarely error out completely if non-zero list of VariableBindings is provided in the parameter PDU.
+ * It may be filled with no useful data, but will always return a PDU with some content.
+ *
+ */
+
+ // TODO: find out the proper getBulk behavior, for certain.
+ // - should getBulk fail if the total amount of attributes in a tree is < mR for a repeater?
+ // - or should all values in that tree be returned, with no message?
+ // this method is a work in progress.
+ public PDU snmpReceivedGetBulk(PDU pdu){
+ PDU response;
+
+ if (pdu instanceof ScopedPDU){
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
+ } else if (pdu instanceof PDUv1){
+ log.debug("snmpReceievedGetBulk: cannot getBulk with V1 PDU.");
+ return null;
+ } else {
+ response = new PDU();
+ }
+ response.setType(PDU.RESPONSE);
+ response.setRequestID(pdu.getRequestID());
+
+ final boolean trace = log.isTraceEnabled();
+
+ if (trace) {
+ log.trace("requestID=" + pdu.getRequestID() + ", elementCount="
+ + pdu.size());
+ }
+ if (pdu != null){
+ int counter = 1;
+ int nonRepeaters = pdu.getNonRepeaters();
+ if (nonRepeaters<0)
+ nonRepeaters=0;
+
+ int maxRepetitions = pdu.getMaxRepetitions();
+ if (maxRepetitions<0)
+ maxRepetitions=0;
+ Vector<VariableBinding> it = pdu.getVariableBindings();
+ VariableBinding vb = null;
+ Variable var = null;
+
+ if (it.size() == 0){ // we were given an empty list in the PDU
+ log.debug("snmpReceivedGetBulk: No VariableBindings in received PDU");
+ makeErrorPdu(response, pdu, counter);
+ return response;
+ }
+
+ for (int i=0; i < Math.min(nonRepeaters, it.size());i++){
+ vb = (VariableBinding)it.get(i);
+ OID oid = vb.getOid();
+ OID noid = null;
+
+ try {
+ noid = getNextOid(oid);
+ }
+ catch (EndOfMibViewException e){
+ log.debug("snmpReceivedGetBulk: End of MIB View in NonRepeaters.");
+ var = Null.endOfMibView;
+ response.add(new VariableBinding(oid, var));
+ continue;
+ }
+ try {
+ var = getValueFor(noid);
+ }
+ catch (NoSuchInstanceException e) {
+ // getBulk allows Null values and errors in it's return.
+ // this won't happen because of using getnext;
+ log.debug("snmpReceivedGetBulk: An instance of an OID didn't exist.");
+ response.add(new VariableBinding(oid, Null.noSuchInstance));
+ continue;
+ }
+ catch (VariableTypeException e){
+ log.debug("snmpReceivedGetBulk: Couldn't convert a Variable to a correct type.");
+ makeErrorPdu(response, pdu, counter);
+ return response;
+ }
+ response.add(new VariableBinding(noid,var));
+ counter++;
+ }
+
+ // for the remaining it.size() bindings, we perform maxRepetitions successive getNext calls
+ for (int i = nonRepeaters; i < it.size(); i++){
+ vb = (VariableBinding)it.get(i);
+ OID oid = vb.getOid();
+ OID noid = null;
+ try {
+ noid = getNextOid(oid);
+ }
+
+ catch (EndOfMibViewException e) {
+ // we know that doing more getnext in this case will just give more end of MIB view results. so we try the next VB.
+ response.add(new VariableBinding(oid, Null.endOfMibView));
+ continue;
+ }
+
+ //FIXME: returns null when maxReptitions goes into OIDs that don't exist.
+ for (int j = 0; j < maxRepetitions; j++){
+ try {
+ var = getValueFor(noid);
+ }
+ // since we're using getNext to retrieve the OIDs, this can't happen. we'll always have an instance.
+ catch (NoSuchInstanceException e) {
+ var = Null.noSuchObject;
+ }
+ catch (VariableTypeException e) {
+ makeErrorPdu(response, pdu, counter);
+ var = Null.noSuchInstance;
+ }
+
+ response.add(new VariableBinding(noid,var));
+
+ try {
+ noid = getNextOid(noid);
+ }
+ catch (EndOfMibViewException e) {
+ response.add(new VariableBinding(noid, Null.endOfMibView));
+ break;
+ }
+ }
+ }
+ counter++;
+ }
+ return response;
+ }
+
+ /**
* <P>
* This method is defined to handle SNMP Get requests that are received by
* the session. The request has already been validated by the system. This
@@ -133,97 +303,119 @@
* </P>
*
* @param pdu
- * The SNMP pdu
- * @param getNext
- * The agent is requesting the lexically NEXT item after each
- * item in the pdu.
+ * The SNMP pdu.
*
- * @return SnmpPduRequest filled in with the proper response, or null if
- * cannot process NOTE: this might be changed to throw an exception.
+ * @return a PDU filled in with the proper response, or a PDU filled with appropriate
+ * error indications. Both the error type (ErrorStatus) and error index (the binding in the
+ * PDU being processed that caused the error are returned.)
*/
- public SnmpPduRequest snmpReceivedGet(SnmpPduPacket pdu, boolean getNext)
+ public PDU snmpReceivedGet (PDU pdu)
{
- try
- {
- SnmpPduRequest response = null;
- int pduLength = pdu.getLength();
- final boolean trace = log.isTraceEnabled();
+ PDU response;
+ // this counts the number of VariableBindings and indicates which one caused a problem, if any
+ int counter = 1;
+ // flags the end of the MIB
+ boolean endOfMib = false;
+
+ if (pdu instanceof ScopedPDU){
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
+ } else if (pdu instanceof PDUv1){
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version1);
+ } else {
+ response = new PDU();
+ }
+ response.setType(PDU.RESPONSE);
+ //indicate by copying the Req ID that this response is for the PDU sent with that ReqID.
+ response.setRequestID(pdu.getRequestID());
+
+ final boolean trace = log.isTraceEnabled();
+
+ if (trace) {
+ log.trace("requestID=" + pdu.getRequestID() + ", elementCount="
+ + pdu.size());
+ }
+
+ if (pdu != null){
+
+ Iterator it = pdu.getVariableBindings().iterator();
+ VariableBinding newVB;
+ Variable var;
+ OID noid = null;
+
+ while (it.hasNext()){
+ VariableBinding vb = (VariableBinding)it.next();
+ OID oid = vb.getOid();
+
+ if (pdu.getType()==PDU.GETNEXT){
+ // we get the lexically next OID from the given one.
+ try{
+ noid = getNextOid(oid);
+ }
+ // if this OID is the last one possible, we throw this exception.
+ catch(EndOfMibViewException e){
+ log.debug("snmpReceivedGet: GETNEXT operation left the MIB View");
+ endOfMib=true;
+ //makeErrorPdu(oid,PDU.noAccess, counter,response);
- if (trace)
- log.trace("requestId=" + pdu.getRequestId() + ", pduLength="
- + pduLength + ", getNext=" + getNext);
+ }
+ newVB = new VariableBinding(noid);
+ if (endOfMib)
+ var = Null.endOfMibView;
+ else{
+ try {
+ var = getValueFor(noid);
+ }
+ catch (NoSuchInstanceException e) {
+ log.debug("snmpReceivedGet: GETNEXT operation returned null. No such OID.");
+ var = Null.noSuchInstance;
+ //makeErrorPdu(noid, PDU.noSuchName, counter,response);
- SnmpVarBind[] vblist = new SnmpVarBind[pduLength];
- int errorStatus = SnmpPduPacket.ErrNoError;
- int errorIndex = 0;
+ }
+ catch (VariableTypeException e) {
+ log.debug("snmpReceivedGet: GETNEXT operation could not convert the returned value for " + noid + " into an appropriate type.");
+ makeErrorPdu(response, pdu, counter);
+ return response;
+
+ }
+ }
+ }
+ else {
+ newVB = new VariableBinding(oid);
+ var = null;
+ if (checkObject(oid)){
+ try {
+ var = getValueFor(oid);
+ }
+ catch (NoSuchInstanceException e) {
+ log.debug("snmpReceivedGet: GET operation returned null. No such Instance.");
+ var = Null.noSuchInstance;
+ //makeErrorPdu(oid, PDU.noSuchName, counter, response);
+ }
+ catch (VariableTypeException e) {
+ log.debug("snmpReceivedGet: GET operation could not convert the returned value for " + oid + " into an appropriate type.");
+ makeErrorPdu(response, pdu, counter);
+ return response;
+
- // Process for each varibind in the request
- for (int i = 0; i < pduLength; i++)
- {
- boolean good = true;
- SnmpVarBind vb = pdu.getVarBindAt(i);
- SnmpObjectId oid = vb.getName();
- if (getNext)
- {
- /*
- * We call getNextOid() to find out what is the next valid OID
- * instance in the supported MIB (sub-)tree. Assign that OID to the
- * VB List and then proceed same as that of get request. If the
- * passed oid is already the last, we flag it.
- */
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(oid);
- oid = getNextOid(coid, true);
- if (oid == null)
- {
- good = false;
+ }
+
}
- else
- {
- pdu.setVarBindAt(i, new SnmpVarBind(oid));
+ // if we get here, there's no such object.
+ else{
+ var = Null.noSuchObject;
}
+
}
- if (oid!=null)
- vblist[i] = new SnmpVarBind(oid);
- else
- vblist[i] = new SnmpVarBind(vb.getName()); // oid passed in
-
-
- if (trace)
- log.trace("oid=" + oid);
-
- SnmpSyntax result = null;
- if (good && bindings != null)
- result = getValueFor(oid);
-
- if (trace)
- log.trace("got result of " + result);
-
- if (result == null || !good)
- {
- errorStatus = SnmpPduPacket.ErrNoSuchName;
- errorIndex = i + 1;
- log.debug("Error Occured " + vb.getName().toString());
- }
- else
- {
- vblist[i].setValue(result);
- log.debug("Varbind[" + i + "] := "
- + vblist[i].getName().toString());
- log.debug(" --> " + vblist[i].getValue().toString());
- }
- } // for ...
- response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
- response.setErrorStatus(errorStatus);
- response.setErrorIndex(errorIndex);
- return response;
- } catch (Exception e)
- {
- // TODO Auto-generated catch block
- e.printStackTrace();
- return null;
+ newVB.setVariable(var);
+ response.add(newVB);
+ counter++;
+ }
+
}
- }
-
+ //TODO: check size constraints of the sender
+ return response;
+ }
+
/**
* <P>
* This method is defined to handle SNMP Set requests that are received by
@@ -234,56 +426,134 @@
* @param pdu
* The SNMP pdu
*
- * @return SnmpPduRequest filled in with the proper response, or null if
- * cannot process NOTE: this might be changed to throw an exception.
+ * @return PDU filled with the new value of the given OID and an error of 0 on success,
+ * or a PDU with an empty VB List and an error status indicating why the operation failed,
+ * and which PDU was problematic.
*/
- public SnmpPduRequest snmpReceivedSet(SnmpPduPacket pdu)
+ public PDU snmpReceivedSet(PDU pdu)
{
+ PDU response;
+ // the modified OID entries so far.
+ HashSet<VariableBinding> modified = new HashSet<VariableBinding>(); // modified variable values so far
+ // this counter is so we can indicate which entry in the given VB list caused an error, if any
+ int counter = 1;
+ Variable var, oldVar = null; // oldVar variable for storing into modified
+
+ if (pdu instanceof ScopedPDU){
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
+ } else if (pdu instanceof PDUv1){
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version1);
+ } else {
+ response = new PDU();
+ }
+ response.setType(PDU.RESPONSE);
+
final boolean trace = log.isTraceEnabled();
- SnmpPduRequest response = null;
- int errorStatus = SnmpPduPacket.ErrNoError;
- int errorIndex = 0;
- int k = pdu.getLength();
- SnmpVarBind[] vblist = new SnmpVarBind[k];
-
- for (int i = 0; i < k; i++)
- {
- SnmpVarBind vb = pdu.getVarBindAt(i);
- vblist[i] = new SnmpVarBind(vb);
- SnmpObjectId oid = vb.getName();
- SnmpSyntax newVal = vb.getValue();
- if (trace)
- log.trace("set: received oid " + oid.toString() + " with value " + newVal.toString());
- SnmpSyntax result = null;
- try
- {
- result = setValueFor(oid,newVal);
+ // TODO: why is this before a null check? if the pdu is null, pdu.getRequestID() and pdu.size() will both fail.
+ if (trace) {
+ log.trace("requestID=" + pdu.getRequestID() + ", elementCount="
+ + pdu.size());
+ }
+
+ if (pdu != null){
+ //iterate through the VB in this PDU
+ Iterator<VariableBinding> it = pdu.getVariableBindings().iterator();
+
+ while (it.hasNext()){
+ // if any set fails for any reason, changes must be undone.
+ // so changes that pass all tests should be stored, and all applied
+ // after each VB has been checked.
+ VariableBinding vb = it.next();
+ OID oid = vb.getOid();
+ Variable newVal = vb.getVariable();
+ //setup the new variable binding to put into the response pdu
+ VariableBinding newVB = new VariableBinding(oid,newVal);
+
+ //some errorchecking ....
+ //else is good and do:
+ try{
+ oldVar = getValueFor(oid);
+ modified.add(new VariableBinding(oid, oldVar)); // keep a record of the old variable binding.
+ var = setValueFor(oid,newVal);
+ }
+ catch (NoSuchInstanceException e){
+ log.debug("snmpReceivedSet: attempt to set a non-existent OID " + oid);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, counter);
+ return response;
+ }
+ catch (VariableTypeException e){
+ log.debug("snmpReceievedSet: could not convert the given value into an appropriate type: " +newVal);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, counter);
+ return response;
+ }
+ catch (ReadOnlyException e){
+ log.debug("snmpReceivedSet: attempt to set a read-only attribute: " + newVB);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, counter);
+ return response;
+ }
+
+ //this can probably be removed entirely
+/* if (var != null){
+ log.debug("snmpReceivedSet: attempt to set value resulted in a null PDU being returned");
+ undoSets(modified);
+ return makeErrorPdu(oid, PDU.noSuchName, counter);
+ }*/
+ // if we get here, we modified the value successfully.
+ response.add(newVB);
+ counter++;
}
- catch (ReadOnlyException e)
- {
- errorStatus = SnmpPduPacket.ErrReadOnly;
- errorIndex = i + 1;
- }
-
- if (result != null)
- {
- errorStatus = SnmpPduPacket.ErrReadOnly;
- errorIndex = i + 1;
- log.debug("Error occured " + vb.getName().toString());
- }
-
- if (trace)
- {
- log.trace("Varbind[" + i + "] := " + vb.getName().toString());
- log.trace(" --> " + vb.getValue().toString());
- }
}
- response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
- response.setErrorStatus(errorStatus);
- response.setErrorIndex(errorIndex);
return response;
- }
+ }
+
+ //return null;
+// final boolean trace = log.isTraceEnabled();
+// SnmpPduRequest response = null;
+// int errorStatus = SnmpPduPacket.ErrNoError;
+// int errorIndex = 0;
+// int k = pdu.getLength();
+// SnmpVarBind[] vblist = new SnmpVarBind[k];
+//
+// for (int i = 0; i < k; i++)
+// {
+// SnmpVarBind vb = pdu.getVarBindAt(i);
+// vblist[i] = new SnmpVarBind(vb);
+// SnmpObjectId oid = vb.getName();
+// SnmpSyntax newVal = vb.getValue();
+// if (trace)
+// log.trace("set: received oid " + oid.toString() + " with value " + newVal.toString());
+// SnmpSyntax result = null;
+// try
+// {
+// result = setValueFor(oid,newVal);
+// }
+// catch (ReadOnlyException e)
+// {
+// errorStatus = SnmpPduPacket.ErrReadOnly;
+// errorIndex = i + 1;
+// }
+//
+// if (result != null)
+// {
+// errorStatus = SnmpPduPacket.ErrReadOnly;
+// errorIndex = i + 1;
+// log.debug("Error occured " + vb.getName().toString());
+// }
+//
+// if (trace)
+// {
+// log.trace("Varbind[" + i + "] := " + vb.getName().toString());
+// log.trace(" --> " + vb.getValue().toString());
+// }
+// }
+// response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
+// response.setErrorStatus(errorStatus);
+// response.setErrorIndex(errorIndex);
+//
/**
* <P>
@@ -304,12 +574,12 @@
* The SNMP pdu
*
*/
- public void snmpReceivedPdu(SnmpAgentSession session, InetAddress manager,
- int port, SnmpOctetString community, SnmpPduPacket pdu)
+ public void snmpReceivedPdu(Snmp session, InetAddress manager,
+ int port, OctetString community, PDU pdu)
{
- log.error("Message from manager " + manager.toString() + " on port " + port);
- int cmd = pdu.getCommand();
- log.error("Unsupported PDU command......... " + cmd);
+// log.error("Message from manager " + manager.toString() + " on port " + port);
+// int cmd = pdu.getCommand();
+// log.error("Unsupported PDU command......... " + cmd);
}
/**
@@ -336,22 +606,22 @@
* The PDU reference, or potentially null. It may also be an
* exception.
*/
- public void SnmpAgentSessionError(SnmpAgentSession session, int error, Object ref)
+ public void SnmpAgentSessionError(Snmp session, int error, Object ref)
{
- log.error("An error occured in the trap session");
- log.error("Session error code = " + error);
- if (ref != null)
- {
- log.error("Session error reference: " + ref.toString());
- }
-
- if (error == SnmpAgentSession.ERROR_EXCEPTION)
- {
- synchronized (session)
- {
- session.notify(); // close the session
- }
- }
+// log.error("An error occured in the trap session");
+// log.error("Session error code = " + error);
+// if (ref != null)
+// {
+// log.error("Session error reference: " + ref.toString());
+// }
+//
+// if (error == SnmpAgentSession.ERROR_EXCEPTION)
+// {
+// synchronized (session)
+// {
+// session.notify(); // close the session
+// }
+// }
}
// Private -------------------------------------------------------
@@ -409,212 +679,377 @@
Iterator aIt = attrs.iterator();
while (aIt.hasNext())
{
- MappedAttribute ma = (MappedAttribute)aIt.next();
- String oid;
- if (oidPrefix != null)
- oid = oidPrefix + ma.getOid();
- else
- oid = ma.getOid();
-
- BindEntry be = new BindEntry(oid, mmb.getName(), ma.getName());
- be.isReadWrite = ma.isReadWrite();
-
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(oid);
-
- if (log.isTraceEnabled())
- log.trace("New bind entry " + be);
- if (bindings.containsKey(coid)) {
- log.info("Duplicate oid " + oid + SKIP_ENTRY);
- continue;
- }
- if (mmb.getName() == null || mmb.getName().equals(""))
- {
- log.info("Invalid mbean name for oid " + oid + SKIP_ENTRY);
- continue;
- }
- if (ma.getName() == null || ma.getName().equals(""))
- {
- log.info("Invalid attribute name " + ma.getName() + " for oid " + oid + SKIP_ENTRY);
- continue;
- }
- bindings.put(coid, be);
- oidKeys.add(coid);
-
- }
+ Object check = aIt.next();
+ if (check instanceof MappedTable){
+ MappedTable ma = (MappedTable)check;
+ int size = ma.getSize();
+ String tablePrefix = ma.getPrefix();
+ // the next size attributes in the list are part of this table.
+ for (int i = 0; i < size; i++){
+ MappedAttribute mat = (MappedAttribute)aIt.next();
+ String oid;
+ if (oidPrefix != null && tablePrefix != null){
+ oid = oidPrefix + tablePrefix + mat.getOid();
+ }
+ else{
+ oid = mat.getOid();
+ }
+ // we shouldn't be using this, because we aren't mapping a table row to a JMX attribute.
+ // we should just be storing the name of the table, since it's just a conceptual ordering anyways.
+ addBindEntry(oid,mmb.getName(),mat.getName(),mat.isReadWrite());
+ }
+ }
+
+ else {
+ MappedAttribute ma = (MappedAttribute)check;
+
+ String oid;
+ if (oidPrefix != null)
+ oid = oidPrefix + ma.getOid();
+ else
+ oid = ma.getOid();
+
+ addBindEntry(oid, mmb.getName(), ma.getName(),ma.isReadWrite());
+
+ }
+
+ }
}
}
+
+ /**
+ *
+ * @param oid The OID bound to this particular attribute
+ * @param mmb the name of the MBean server
+ * @param ma the name of the MBeam attribute the OID is concerning
+ * @param rw indicates whether this Attribute is read-write or not (readonly if false)
+ */
+
+ private void addBindEntry(String oid, String mmb, String ma, boolean rw){
+ BindEntry be = new BindEntry(oid, mmb, ma);
+ be.isReadWrite = rw;
+
+ OID coid = new OID(oid);
+ if (log.isTraceEnabled())
+ log.trace("New bind entry " + be);
+ if (bindings.containsKey(coid)) {
+ log.info("Duplicate oid " + oid + SKIP_ENTRY);
+ }
+ if (mmb == null || mmb.equals(""))
+ {
+ log.info("Invalid mbean name for oid " + oid + SKIP_ENTRY);
+ }
+ if (ma == null || ma.equals(""))
+ {
+ log.info("Invalid attribute name " + ma + " for oid " + oid + SKIP_ENTRY);
+ }
+ bindings.put(coid, be);
+ oidKeys.add(coid);
+ }
+
/**
+ * This method checks the existence of an object of a GET / SET request.
+ * This is as opposed to a specific instance, which has a value tied to it. this method simply
+ * returns a boolean.
+ *
+ * @param oid
+ * @return
+ * @throws NoSuchObjectException
+ * @throws VariableTypeException
+ */
+
+ private boolean checkObject(final OID oid) {
+ OID coid = oid;
+ coid.removeLast();
+ return oidKeys.contains(coid);
+ }
+
+ /**
* Return the current value for the given oid
*
* @param oid
* The oid we want a value for
- * @return SnmpNull if no value present
+ * @return Null if no value present
*/
- private SnmpSyntax getValueFor(final SnmpObjectId oid) {
+ private Variable getValueFor(final OID oid) throws NoSuchInstanceException, VariableTypeException {
BindEntry be = findBindEntryForOid(oid);
- SnmpSyntax ssy = null;
+ Variable ssy = null;
if (be != null)
- {
+ {
if (log.isTraceEnabled())
- log.trace("Found entry " + be.toString() + " for oid " + oid);
-
+ log.trace("getValueFor: Found entry " + be.toString() + " for oid " + oid);
+
try
- {
+ {
Object val = server.getAttribute(be.mbean, be.attr.getName());
-
- if (val instanceof Long)
- {
- Long uin = (Long) val;
- ssy = new SnmpUInt32(uin);
+ ssy = prepForPdu(val);
+
+ if (val == null){
+ log.info("getValueFor: Unknown type for " + be);
}
- else if (val instanceof String)
- {
- String in = (String) val;
- ssy = new SnmpOctetString(in.getBytes());
- }
- else if (val instanceof Integer)
- {
- Integer in = (Integer) val;
- ssy = new SnmpInt32(in);
- }
- else if (val instanceof SnmpObjectId)
- {
- ssy = (SnmpObjectId)val;
- }
- else if (val instanceof SnmpTimeTicks)
- {
- ssy = (SnmpTimeTicks)val;
- }
- else
- log.info("Unknown type for " + be);
- }
- catch (Exception e)
- {
- log.warn("getValueFor (" + be.mbean.toString() + ", "
+ }
+ catch (VariableTypeException e){
+ log.debug("getValueFor: didn't find a suitable data type for the requested data");
+ throw e;
+ }
+ catch (Exception e)
+ {
+ log.warn("getValueFor: (" + be.mbean.toString() + ", "
+ be.attr.getName() + ": " + e.toString());
- }
- }
- else
- {
- ssy = new SnmpNull();
- log.info(NO_ENTRY_FOUND_FOR_OID + oid);
+ }
+ }
+ else
+ {
+
+ log.debug("getValueFor: " + NO_ENTRY_FOUND_FOR_OID + oid);
+ throw new NoSuchInstanceException();
}
return ssy;
}
+
- /**
- * Set a jmx attribute
- * @param oid The oid to set. This is translated into a mbean / attribute pair
- * @param newVal The new value to set
- * @return null on success, non-null on failure
- * @throws ReadOnlyException If the referred entry is read only.
+
+ /**This method takes an Object that is typically going to be
+ * put into a VariableBinding for use in a PDU, and thus must be converted
+ * into an SNMP type based on it's type. This Object is usually read
+ * from the MBean server.
+ *
+ * @param val The value needing conversion.
+ * @return the converted value. null on failure.
+ * @throws VariableTypeException if the method was unable to convert val's type into an
+ * equivalent SMI type.
+ *
*/
- private SnmpSyntax setValueFor(final SnmpObjectId oid, final SnmpSyntax newVal) throws ReadOnlyException
- {
+
+ private Variable prepForPdu(final Object val) throws VariableTypeException{
+ Variable result = null;
+ //TODO: all types managed by the PDU
+ if (val instanceof Long)
+ {
+ result = new Counter32((Long)val);
+ }
+ else if (val instanceof String)
+ {
+ result = new OctetString((String) val);
+ }
+ else if (val instanceof Integer)
+ {
+ result = new Integer32((Integer)val);
+ }
+ else if (val instanceof OID)
+ {
+ result = new OID((OID)val);
+ }
+ else if (val instanceof TimeTicks)
+ {
+ // the SNMP4J class TimeTicks default toString method is formatted horribly. This
+ // call emulates the joesnmp SnmpTimeTicks display.
+ result = new OctetString(((TimeTicks)val).toString("{0} d {1} h {2} m {3} s {4} hs"));
+ }
+ else if (val instanceof Counter32)
+ {
+ result = (Counter32) val;
+ }
+ else
+ {
+ throw new VariableTypeException(); // no instance of an SNMP Variable could be created for type
+ }
+ return result;
+ }
+
+ /**
+ * Takes an instance of org.snmp4j.smi.Variable and returns a Java primitive
+ * representation. This is used to set mbean values given a PDU.
+ *
+ * @param val the value to be converted
+ * @return an Object created with the proper type. null if failure
+ * @throws VariableTypeException if the method was unable to convert the type of val into
+ * a type compatible with the MBean server.
+ */
+ private Object convertVariableToValue(final Variable val) throws VariableTypeException{
+ Object result = null;
+ if (val instanceof OctetString)
+ {
+ result = val.toString();
+ }
+ else if (val instanceof Integer32)
+ {
+ result = new Integer(((Integer32)val).getValue());
+ }
+ else if (val instanceof Counter32)
+ {
+ result = new Long(((Counter32)val).getValue());
+ }
+ else if (val instanceof Counter64)
+ {
+ result = new Long(((Counter64)val).getValue());
+ }
+ else{
+ throw new VariableTypeException(); //no instance could be created.
+ }
+ // TODO do more mumbo jumbo for type casting / changing
+ return result;
+
+ }
+
+// /**
+// * Set a jmx attribute
+// * @param oid The oid to set. This is translated into a mbean / attribute pair
+// * @param newVal The new value to set
+// * @return null on success, non-null on failure
+// * @throws ReadOnlyException If the referred entry is read only.
+// */
+
+ //TODO: currently, if one accesses a String and attempts to set it to an Int or Double value,
+ // the response is success, but the result is failure. This must be changed by investigating
+ // what value is given from this method when such a situation arises, and then either throwing an exception
+ // or handling that value in the caller. /** THIS HAS BEEN IMPLEMENTED. AN EXCEPTION SHOULD BE THROWN. **/
+ //TODO: decide what to do in the case of a non writeable entry. (Exception thrown)
+
+ private Variable setValueFor(final OID oid, final Variable newVal)
+ throws ReadOnlyException, VariableTypeException, NoSuchInstanceException {
final boolean trace = log.isTraceEnabled();
BindEntry be = findBindEntryForOid(oid);
+ Variable ssy = null;
if (trace)
log.trace("setValueFor: found bind entry for " + oid);
- SnmpSyntax ssy = null;
if (be != null)
- {
+ {
if (trace)
log.trace("setValueFor: " + be.toString());
if (be.isReadWrite == false)
- {
+ {
if (trace)
log.trace("setValueFor: this is marked read only");
throw new ReadOnlyException(oid);
}
try
- {
- Object val = null;
- if (newVal instanceof SnmpOctetString)
- {
- val = newVal.toString();
+ {
+ Object other = server.getAttribute(be.mbean, be.attr.getName());
+ Object val = convertVariableToValue(newVal);
+
+ if (val.getClass() != other.getClass() ){
+ log.debug("setValueFor: attempt to set an MBean Attribute with the wrong type.");
+ ssy = newVal;
}
- else if (newVal instanceof SnmpInt32)
- {
- val = new Integer(((SnmpInt32)newVal).getValue());
- }
- else if (newVal instanceof SnmpUInt32)
- {
- val = new Long(((SnmpUInt32)newVal).getValue());
- }
- // TODO do more mumbo jumbo for type casting / changing
- if (val != null)
- {
- Attribute at = new Attribute(be.attr.getName(), val);
- server.setAttribute(be.mbean, at);
- if (trace)
- log.trace("setValueFor: set attribute in mbean-Server");
- }
- else
- {
- log.debug("Did not find a suitable data type for newVal " + newVal);
- ssy = new SnmpNull();
- }
- // TODO
+ Attribute at = new Attribute(be.attr.getName(), val);
+ server.setAttribute(be.mbean, at);
+
+ if (trace)
+ log.trace("setValueFor: set attribute in mbean server");
}
- catch (Exception e )
- {
+ catch (VariableTypeException e){
+ log.debug("setValueFor: didn't find a suitable data type for newVal " + newVal);
+ throw e;
+ }
+ catch (Exception e)
+ {
log.debug("setValueFor: exception " + e.getMessage());
- ssy = new SnmpNull();
+ ssy = newVal;
}
}
else
- {
- ssy = new SnmpNull();
- log.info(NO_ENTRY_FOUND_FOR_OID + oid);
+ {
+ throw new NoSuchInstanceException();
+ /*ssy = newVal;
+ log.info("setValueFor: " + NO_ENTRY_FOUND_FOR_OID + oid + " on the mbean server");*/
}
return ssy;
}
+ /** This method is used by snmpReceivedSet to reverse any changes in a
+ * SET PDU if an error is encountered before finishing.
+ *
+ * @param modified HashSet containing OID,Val mappings
+ */
+ private void undoSets(HashSet modified){
+ Iterator<VariableBinding> iter = modified.iterator();
+
+ while (iter.hasNext()){
+ try{
+ VariableBinding vb = iter.next();
+ OID oid = vb.getOid();
+ Variable var = vb.getVariable();
+ setValueFor(oid,var);// this will not fail, because it succeeded earlier.
+ }
+ catch(NoSuchInstanceException e){
+ //impossible
+ }
+ catch(VariableTypeException e){
+ //impossible
+ }
+ catch(ReadOnlyException e){
+ //impossible;
+ }
+ }
+ }
+
+
/**
- * Lookup a BinEntry on the given oid. If the oid ends in .0,
- * then the .0 will be stripped of before the search.
+ * Lookup a BindEntry on the given oid.
+ *
* @param oid The oid look up.
* @return a bind entry or null.
*/
- private BindEntry findBindEntryForOid(final SnmpObjectId oid) {
+ private BindEntry findBindEntryForOid(final OID oid) {
- ComparableSnmpObjectId coid= new ComparableSnmpObjectId(oid);
+ //param probably not supposed to be OID type
+ OID coid= new OID(oid);
- if (coid.isLeaf())
+ //add possible oid format checking
+ //we should not be stripping off the last number if it's 0! that's the instance identifier,
+ //and indicates that the given variable is a scalar value! (not part of a table.)
+ /*if (coid.last() == 0)
{
- coid = coid.removeLastPart();
- }
+ coid.removeLast();
+ }*/
BindEntry be = (BindEntry)bindings.get(coid);
return be;
}
+
+// /**
+// * Lookup a BinEntry on the given oid. If the oid ends in .0,
+// * then the .0 will be stripped of before the search.
+// * @param oid The oid look up.
+// * @return a bind entry or null.
+// */
+// private BindEntry findBindEntryForOid(final SnmpObjectId oid) {
+//
+// ComparableSnmpObjectId coid= new ComparableSnmpObjectId(oid);
+//
+// if (coid.isLeaf())
+// {
+// coid = coid.removeLastPart();
+// }
+// BindEntry be = (BindEntry)bindings.get(coid);
+//
+// return be;
+// }
/**
* Return the next oid that is larger than ours.
* @param oid the starting oid
- * @param stayInSubtree if true, the next oid will not have a different prefix than the one of oid.
* @return the next oid or null if none found.
+ * * @throws EndOfMibViewException if there is no greater OID than the given, valid, oid.
*/
- private ComparableSnmpObjectId getNextOid(final ComparableSnmpObjectId oid, boolean stayInSubtree) {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(oid);
+ private OID getNextOid(final OID oid) throws EndOfMibViewException {
+ OID coid = new OID(oid);
- if (coid.isLeaf())
- coid = coid.removeLastPart();
-
SortedSet ret;
- ret= oidKeys.tailSet(oid); // get oids >= oid
+ ret=oidKeys.tailSet(oid); // get oids >= oid
Iterator it = ret.iterator();
- ComparableSnmpObjectId roid=null;
+ OID roid=null;
/*
* If there are elements in the tail set, then
@@ -623,42 +1058,60 @@
* SortedSet.tailSet() , then get next, which is the
* one we look for.
*/
- if (it.hasNext())
- {
- roid = (ComparableSnmpObjectId)it.next(); // oid
+ if (it.hasNext()){
+
+ roid = (OID)it.next(); // oid
}
-
- if (roid == null)
- {
- return null; // roid is null,
+ // if the tailSet is empty...there aren't any OID larger than the one given. so we're at the End of the MIB.
+ else{
+ log.debug("getNextOid: Placeholder. There is no lexically larger OID than the input.");
+ throw new EndOfMibViewException();
}
if (roid.compareTo(coid)==0) // input elment
{
// if there is a next element, then it is ours.
+ // perhaps change this to try/catch also
if (it.hasNext())
{
- roid = (ComparableSnmpObjectId)it.next();
+ roid = (OID)it.next();
}
else
{
- roid = null; // end of list
+ log.debug("getNextOid: Placeholder. There is no lexically larger OID than the input.");
+ // end of list
+ throw new EndOfMibViewException();
}
}
-
- /*
- * Check if still in subtree if requested to stay within
- */
- if (stayInSubtree && roid != null)
+
+ // Check if still in subtree if requested to stay within
+ // THIS SHOULD BE A MANAGER FUNCTION, NOT AGENT.
+/* if (stayInSubtree && roid != null)
{
- ComparableSnmpObjectId parent = coid.removeLastPart();
- if (!parent.isRootOf(roid))
- roid = null;
- }
+ //OID parent = coid.removeLast();
+ // this emulates the functionality of the "isRoot" in SnmpObjectId from joesnmp
+ if (coid.leftMostCompare((coid.size()-1), roid) != 0){
+ log.debug("getNextOid: Placeholder. The traversal has left the subtree.");
+ throw new EndOfMibViewException();
+ }
+ }*/
return roid;
}
+ /** This utility method is used to construct an error PDU. This code
+ * was repeated so many times it was prudent to give it it's own method.
+ * @param response This PDU is the one being modified into an error PDU.
+ * @param oid The OID to contain the error Null instance.
+ * @param errNo The error number defined in the PDU class that indicates a given failure
+ * @param errInd the VariableBinding in the PDU that caused the error.
+ */
+ private void makeErrorPdu(PDU response, PDU pdu, int counter){
+ response.clear();
+ response.addAll(pdu.toArray());
+ response.setErrorIndex(counter);
+ response.setErrorStatus(PDU.genErr);
+ }
// Inner Class ---------------------------------------------------
@@ -668,12 +1121,12 @@
* @author <a href="mailto:pilhuhn at user.sf.net>">Heiko W. Rupp</a>
*/
private class BindEntry implements Comparable {
- private final ComparableSnmpObjectId oid;
+ private final OID oid;
private ObjectName mbean;
- private Attribute attr;
+ private Attribute attr;
private String mName;
- private String aName;
+ private String aName;
private boolean isReadWrite = false;
/**
@@ -687,7 +1140,7 @@
* The name of the attribute to query
*/
BindEntry(final String oidString, final String mbName, final String attrName) {
- this(new ComparableSnmpObjectId(oidString),
+ this(new OID(oidString),
mbName,
attrName);
}
@@ -698,7 +1151,7 @@
* @param mbName The name of an MBean with attribute to query
* @param attrName The name of the attribute to query
*/
- BindEntry(final ComparableSnmpObjectId coid, final String mbName, final String attrName) {
+ BindEntry(final OID coid, final String mbName, final String attrName) {
oid = coid;
this.mName = mbName;
this.aName = attrName;
@@ -739,7 +1192,7 @@
return mbean;
}
- public ComparableSnmpObjectId getOid()
+ public OID getOid()
{
return oid;
}
@@ -765,13 +1218,98 @@
return 0;
BindEntry obe = (BindEntry) other;
- if (getOid().equals(obe.getOid()))
- return 0;
+// if (getOid().equals(obe.getOid()))
+// return 0;
- int res =oid.compare(obe.getOid());
+ int res =oid.compareTo(obe.getOid());
return res;
}
}
+
+
}
+
+/** Brian Shim commented this out for reference i'm guessing **/
+//try
+//{
+// SnmpPduRequest response = null;
+// int pduLength = pdu.getLength();
+// final boolean trace = log.isTraceEnabled();
+//
+// if (trace)
+// log.trace("requestId=" + pdu.getRequestId() + ", pduLength="
+// + pduLength + ", getNext=" + getNext);
+//
+// SnmpVarBind[] vblist = new SnmpVarBind[pduLength];
+// int errorStatus = SnmpPduPacket.ErrNoError;
+// int errorIndex = 0;
+//
+// // Process for each varibind in the request
+// for (int i = 0; i < pduLength; i++)
+// {
+// boolean good = true;
+// SnmpVarBind vb = pdu.getVarBindAt(i);
+// SnmpObjectId oid = vb.getName();
+//START OF GETNEXT
+// if (getNext) //i don't care about GETNEXT, doing GET first
+// {
+// /*
+// * We call getNextOid() to find out what is the next valid OID
+// * instance in the supported MIB (sub-)tree. Assign that OID to the
+// * VB List and then proceed same as that of get request. If the
+// * passed oid is already the last, we flag it.
+// */
+// ComparableSnmpObjectId coid = new ComparableSnmpObjectId(oid);
+// oid = getNextOid(coid, true);
+// if (oid == null)
+// {
+// good = false;
+// }
+// else
+// {
+// pdu.setVarBindAt(i, new SnmpVarBind(oid));
+// }
+// }
+//End of GETNEXT
+// if (oid!=null)
+// vblist[i] = new SnmpVarBind(oid);
+// else
+// vblist[i] = new SnmpVarBind(vb.getName()); // oid passed in
+//
+//
+// if (trace)
+// log.trace("oid=" + oid);
+//
+// SnmpSyntax result = null;
+// if (good && bindings != null)
+// result = getValueFor(oid);
+//
+// if (trace)
+// log.trace("got result of " + result);
+//
+// if (result == null || !good)
+// {
+// errorStatus = SnmpPduPacket.ErrNoSuchName;
+// errorIndex = i + 1;
+// log.debug("Error Occured " + vb.getName().toString());
+// }
+// else
+// {
+// vblist[i].setValue(result);
+// log.debug("Varbind[" + i + "] := "
+// + vblist[i].getName().toString());
+// log.debug(" --> " + vblist[i].getValue().toString());
+// }
+// } // for ...
+// response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
+// response.setErrorStatus(errorStatus);
+// response.setErrorIndex(errorIndex);
+// return response;
+//} catch (Exception e)
+//{
+// // TODO Auto-generated catch block
+// e.printStackTrace();
+// return null;
+//}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -26,13 +26,14 @@
import javax.management.MBeanServer;
import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpAgentSession;
-import org.opennms.protocols.snmp.SnmpObjectId;
-import org.opennms.protocols.snmp.SnmpOctetString;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduRequest;
-import org.opennms.protocols.snmp.SnmpSyntax;
-import org.opennms.protocols.snmp.SnmpVarBind;
+//import org.opennms.protocols.snmp.SnmpAgentSession;
+//import org.opennms.protocols.snmp.SnmpObjectId;
+//import org.opennms.protocols.snmp.SnmpPduRequest;
+//import org.opennms.protocols.snmp.SnmpSyntax;
+//import org.opennms.protocols.snmp.SnmpVarBind;
+import org.snmp4j.PDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.smi.OctetString;
/**
* Implement RequestHandler with simple tracing of incoming requests.
@@ -98,55 +99,58 @@
* @return SnmpPduRequest filled in with the proper response, or null if cannot process
* NOTE: this might be changed to throw an exception.
*/
- public SnmpPduRequest snmpReceivedGet(SnmpPduPacket pdu, boolean getNext)
- {
- SnmpPduRequest response = null;
- int pduLength = pdu.getLength();
-
- log.debug("requestId=" + pdu.getRequestId() + ", pduLength=" + pduLength);
-
- SnmpVarBind[] vblist = new SnmpVarBind[pduLength];
- int errorStatus = SnmpPduPacket.ErrNoError;
- int errorIndex = 0;
-
- //Process for each varibind in the request
- for (int i = 0; i < pduLength ; i++ )
- {
- SnmpVarBind vb = pdu.getVarBindAt(i);
- SnmpObjectId oid = vb.getName();
- if (getNext)
- {
- log.debug(
- "Should call getNextOid() to find out what is the next valid OID " +
- "instance in the supported MIB tree. Assign that OID to the VB List " +
- "and then proceed same as that of get request" );
- }
- vblist[i] = new SnmpVarBind(oid);
-
- log.debug("oid=" + oid.toString());
-
- log.debug("Should call the respective interface to retrieve current value for this OID" );
-
- SnmpSyntax result = null;
-
- if (result == null)
- {
- errorStatus = SnmpPduPacket.ErrNoSuchName;
- errorIndex = i + 1;
- //log.debug("Error Occured " + vb.getName().toString());
- }
- else
- {
- vblist[i].setValue(result);
- log.debug("Varbind[" + i + "] := " + vblist[i].getName().toString());
- log.debug(" --> " + vblist[i].getValue().toString());
- }
- }
- response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
- response.setErrorStatus(errorStatus);
- response.setErrorIndex(errorIndex);
- return response;
+ public PDU snmpReceivedGetBulk(PDU pdu){
+ return null;
}
+ public PDU snmpReceivedGet(PDU pdu)
+ {return null;
+// SnmpPduRequest response = null;
+// int pduLength = pdu.getLength();
+//
+// log.debug("requestId=" + pdu.getRequestId() + ", pduLength=" + pduLength);
+//
+// SnmpVarBind[] vblist = new SnmpVarBind[pduLength];
+// int errorStatus = SnmpPduPacket.ErrNoError;
+// int errorIndex = 0;
+//
+// //Process for each varibind in the request
+// for (int i = 0; i < pduLength ; i++ )
+// {
+// SnmpVarBind vb = pdu.getVarBindAt(i);
+// SnmpObjectId oid = vb.getName();
+// if (getNext)
+// {
+// log.debug(
+// "Should call getNextOid() to find out what is the next valid OID " +
+// "instance in the supported MIB tree. Assign that OID to the VB List " +
+// "and then proceed same as that of get request" );
+// }
+// vblist[i] = new SnmpVarBind(oid);
+//
+// log.debug("oid=" + oid.toString());
+//
+// log.debug("Should call the respective interface to retrieve current value for this OID" );
+//
+// SnmpSyntax result = null;
+//
+// if (result == null)
+// {
+// errorStatus = SnmpPduPacket.ErrNoSuchName;
+// errorIndex = i + 1;
+// //log.debug("Error Occured " + vb.getName().toString());
+// }
+// else
+// {
+// vblist[i].setValue(result);
+// log.debug("Varbind[" + i + "] := " + vblist[i].getName().toString());
+// log.debug(" --> " + vblist[i].getValue().toString());
+// }
+// }
+// response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
+// response.setErrorStatus(errorStatus);
+// response.setErrorIndex(errorIndex);
+// return response;
+ }
/**
* <P>This method is defined to handle SNMP Set requests
@@ -159,39 +163,41 @@
* @return SnmpPduRequest filled in with the proper response, or null if cannot process
* NOTE: this might be changed to throw an exception.
*/
- public SnmpPduRequest snmpReceivedSet(SnmpPduPacket pdu)
- {
- SnmpPduRequest response = null;
- int errorStatus = SnmpPduPacket.ErrNoError;
- int errorIndex = 0;
- int k = pdu.getLength();
- SnmpVarBind[] vblist = new SnmpVarBind[k];
-
- for (int i = 0; i < k ; i++ )
- {
- SnmpVarBind vb = pdu.getVarBindAt(i);
- vblist[i] = new SnmpVarBind(vb);
- SnmpObjectId oid = vb.getName();
-
- SnmpSyntax result = null;
- log.debug("Should call the respective interface to assign a value for this OID" );
-
- if (result != null)
- {
- errorStatus = SnmpPduPacket.ErrReadOnly;
- errorIndex = i + 1;
- log.debug("Error occured " + vb.getName().toString());
- }
-
- log.debug("Varbind[" + i + "] := " + vb.getName().toString());
- log.debug(" --> " + vb.getValue().toString());
- }
-
- response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
- response.setErrorStatus(errorStatus);
- response.setErrorIndex(errorIndex);
-
- return response;
+ public PDU snmpReceivedSet(PDU pdu)
+ {
+
+ return null;
+// SnmpPduRequest response = null;
+// int errorStatus = SnmpPduPacket.ErrNoError;
+// int errorIndex = 0;
+// int k = pdu.getLength();
+// SnmpVarBind[] vblist = new SnmpVarBind[k];
+//
+// for (int i = 0; i < k ; i++ )
+// {
+// SnmpVarBind vb = pdu.getVarBindAt(i);
+// vblist[i] = new SnmpVarBind(vb);
+// SnmpObjectId oid = vb.getName();
+//
+// SnmpSyntax result = null;
+// log.debug("Should call the respective interface to assign a value for this OID" );
+//
+// if (result != null)
+// {
+// errorStatus = SnmpPduPacket.ErrReadOnly;
+// errorIndex = i + 1;
+// log.debug("Error occured " + vb.getName().toString());
+// }
+//
+// log.debug("Varbind[" + i + "] := " + vb.getName().toString());
+// log.debug(" --> " + vb.getValue().toString());
+// }
+//
+// response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
+// response.setErrorStatus(errorStatus);
+// response.setErrorIndex(errorIndex);
+//
+// return response;
}
/**
@@ -207,12 +213,12 @@
* @param pdu The SNMP pdu
*
*/
- public void snmpReceivedPdu(SnmpAgentSession session, InetAddress manager, int port,
- SnmpOctetString community, SnmpPduPacket pdu)
+ public void snmpReceivedPdu(Snmp session, InetAddress manager, int port,
+ OctetString community, PDU pdu)
{
- log.error("Message from manager " + manager.toString() + " on port " + port);
- int cmd = pdu.getCommand();
- log.error("Unsupported PDU command......... " + cmd);
+// log.error("Message from manager " + manager.toString() + " on port " + port);
+// int cmd = pdu.getCommand();
+// log.error("Unsupported PDU command......... " + cmd);
}
/**
@@ -235,21 +241,21 @@
* @param ref The PDU reference, or potentially null.
* It may also be an exception.
*/
- public void SnmpAgentSessionError(SnmpAgentSession session, int error, Object ref)
+ public void SnmpAgentSessionError(Snmp session, int error, Object ref)
{
- log.error("An error occured in the trap session");
- log.error("Session error code = " + error);
- if(ref != null)
- {
- log.error("Session error reference: " + ref.toString());
- }
-
- if(error == SnmpAgentSession.ERROR_EXCEPTION)
- {
- synchronized(session)
- {
- session.notify(); // close the session
- }
- }
+// log.error("An error occured in the trap session");
+// log.error("Session error code = " + error);
+// if(ref != null)
+// {
+// log.error("Session error reference: " + ref.toString());
+// }
+//
+// if(error == SnmpAgentSession.ERROR_EXCEPTION)
+// {
+// synchronized(session)
+// {
+// session.notify(); // close the session
+// }
+// }
}
}
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentRequestHandler.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,103 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import java.net.InetAddress;
+
+import org.snmp4j.PDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.smi.OctetString;
+
+/**
+* <P>The SnmpAgentRequestHandler interface is implemented by an object that
+* wishs to receive callbacks when an SNMP protocol data unit
+* is received from a manager.</P>
+*
+*/
+public interface SnmpAgentRequestHandler
+{
+/**
+* <P>This method is defined to handle SNMP requests
+* that are received by the session. The parameters
+* allow the handler to determine the host, port, and
+* community string of the received PDU</P>
+*
+* @param session The SNMP session
+* @param manager The remote sender
+* @param port The remote senders port
+* @param community The community string
+* @param pdu The SNMP pdu
+*
+*/
+void snmpReceivedPdu(Snmp session,
+ InetAddress manager,
+ int port,
+ OctetString community,
+ PDU pdu);
+
+/**
+* <P>This method is defined to handle SNMP Get requests
+* that are received by the session. The request has already
+* been validated by the system. This routine will build a
+* response and pass it back to the caller.</P>
+*
+* @param pdu The SNMP pdu
+* @param getNext The agent is requesting the lexically NEXT item after each
+* item in the pdu. *** THIS IS NO LONGER REQUIRED. REMOVED.***
+*
+* @return PDU filled in with the proper response, or null if cannot process. PDU's
+* version is based on the @param pdu.
+*
+* NOTE: this might be changed to throw an exception.
+*/
+PDU snmpReceivedGet(PDU pdu);
+
+/**
+ * <P> This method handles SNMP Get Bulk requests received by the session
+ * Builds a response PDU and passes it back to the caller.
+ * </P
+ *
+ * @param pdu The SNMP pdu
+ * @return PDU filled with the proper response. This PDU is either V2c or V3.
+ * this PDU will always try to ignore errors and fill with as much info
+ * as possible.
+ */
+
+PDU snmpReceivedGetBulk(PDU pdu);
+
+/**
+* <P>This method is defined to handle SNMP Set requests
+* that are received by the session. The request has already
+* been validated by the system. This routine will build a
+* response and pass it back to the caller.</P>
+*
+* @param pdu The SNMP pdu
+*
+* @return PDU filled in with the proper response, or null if cannot process
+* NOTE: this might be changed to throw an exception.
+*/
+PDU snmpReceivedSet(PDU pdu);
+//ResponseEvent maybe
+
+///**
+//* <P>This method is invoked if an error occurs in
+//* the session. The error code that represents
+//* the failure will be passed in the second parameter,
+//* 'error'. The error codes can be found in the class
+//* SnmpAgentSession class.</P>
+//*
+//* <P>If a particular PDU is part of the error condition
+//* it will be passed in the third parameter, 'pdu'. The
+//* pdu will be of the type SnmpPduRequest or SnmpPduTrap
+//* object. The handler should use the "instanceof" operator
+//* to determine which type the object is. Also, the object
+//* may be null if the error condition is not associated
+//* with a particular PDU.</P>
+//*
+//* @param session The SNMP Session
+//* @param error The error condition value.
+//* @param ref The PDU reference, or potentially null.
+//* It may also be an exception.
+//*/
+//void SnmpAgentSessionError(Snmp session,
+// int error,
+// Object ref);
+}
\ No newline at end of file
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -20,6 +20,7 @@
package org.jboss.jmx.adaptor.snmp.agent;
import java.net.InetAddress;
+import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import javax.management.Notification;
@@ -27,10 +28,27 @@
import org.jboss.bootstrap.api.as.config.JBossASServerConfig;
import org.jboss.system.ListenerServiceMBeanSupport;
-import org.opennms.protocols.snmp.SnmpAgentSession;
-import org.opennms.protocols.snmp.SnmpPeer;
-import org.opennms.protocols.snmp.SnmpSMI;
+//import org.opennms.protocols.snmp.SnmpAgentSession;
+//import org.opennms.protocols.snmp.SnmpPeer;
+//import org.opennms.protocols.snmp.SnmpSMI;
+//SNMP4J IMPORTS
+import org.snmp4j.AbstractTarget;
+import org.snmp4j.CommandResponder;
+import org.snmp4j.CommandResponderEvent;
+import org.snmp4j.MessageDispatcher;
+import org.snmp4j.MessageException;
+import org.snmp4j.Snmp;
+import org.snmp4j.Target;
+import org.snmp4j.event.CounterEvent;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.mp.StateReference;
+import org.snmp4j.mp.StatusInformation;
+import org.snmp4j.smi.*;
+import org.snmp4j.transport.DefaultTcpTransportMapping;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
+import org.snmp4j.PDU;
+
/**
* <tt>SnmpAgentService</tt> is an MBean class implementing an SNMP agent.
*
@@ -52,7 +70,8 @@
{
/** Supported versions */
public static final int SNMPV1 = 1;
- public static final int SNMPV2 = 2;
+ public static final int SNMPV2 = 2;
+ public static final int SNMPV3 = 3;
/** Default communities */
public static final String DEFAULT_READ_COMMUNITY = "public";
@@ -115,7 +134,7 @@
private TrapEmitter trapEmitter = null;
/** the snmp agent session for handling get/set requests */
- private SnmpAgentSession agentSession = null;
+// private SnmpAgentSession agentSession = null;
/** the request handler instance handling get/set requests */
private RequestHandler requestHandler;
@@ -503,6 +522,8 @@
// initialise the snmp agent
log.debug("Starting snmp agent ...");
+
+ //At the moment does nothing
startAgent();
log.info("SNMP agent going active");
@@ -530,8 +551,8 @@
this.trapEmitter = null;
log.debug("Stopping snmp agent ...");
- this.agentSession.close();
- this.agentSession = null;
+// this.agentSession.close();
+// this.agentSession = null;
log.info("SNMP agent stopped");
}
@@ -566,27 +587,65 @@
private void startAgent()
throws Exception
{
+
+ // Instantiate and initialize the RequestHandler implementation
+ requestHandler = (RequestHandler)Class.forName(
+ this.requestHandlerClassName, true, this.getClass().getClassLoader()).newInstance();
+ requestHandler.initialize(this.requestHandlerResName, this.getServer(), this.log, this.clock);
+
+ //Snmp snmp = new Snmp(new DefaultTcpTransportMapping(new TcpAddress(this.bindAddress, this.port)));
+ Snmp snmp = new Snmp(new DefaultUdpTransportMapping(new UdpAddress(this.bindAddress, this.port)));
+ SnmpRequest request = new SnmpRequest(requestHandler, log);
+ snmp.addCommandResponder(request);
+ snmp.listen();
+ /********************************************************************
+ *
+ * ORIG!!!!
+ *
+ ********************************************************************/
+
// cater for possible global -b option, if no override has been specified
- InetAddress address = this.bindAddress != null ? this.bindAddress :
- toInetAddress(System.getProperty(JBossASServerConfig.PROP_KEY_JBOSSAS_BIND_ADDRESS));
+// InetAddress address = this.bindAddress != null ? this.bindAddress :
+// toInetAddress(System.getProperty(JBossASServerConfig.PROP_KEY_JBOSSAS_BIND_ADDRESS));
// the listening address
- SnmpPeer peer = new SnmpPeer(address, this.port);
+ //SnmpPeer peer = new SnmpPeer(address, this.port);
- // set community strings and protocol version
- peer.getParameters().setReadCommunity(this.readCommunity);
- peer.getParameters().setWriteCommunity(this.writeCommunity);
- peer.getParameters().setVersion(this.snmpVersion == SNMPV2 ? SnmpSMI.SNMPV2 : SnmpSMI.SNMPV1);
+ /********************************************************************
+ *
+ * START OF MINE!!!!
+ *
+ ********************************************************************/
- // Instantiate and initialize the RequestHandler implementation
- requestHandler = (RequestHandler)Class.forName(
- this.requestHandlerClassName, true, this.getClass().getClassLoader()).newInstance();
- requestHandler.initialize(this.requestHandlerResName, this.getServer(), this.log, this.clock);
+// TcpAddress tcpAddr = new TcpAddress(address, this.port);
+// DefaultTcpTransportMapping tcpMapping = new DefaultTcpTransportMapping(tcpAddr);
+// Snmp snmpPeer = new Snmp(tcpMapping);
+//
+ /********************************************************************
+ *
+ * END OF MINE!!!!
+ *
+ ********************************************************************/
+
+ /********************************************************************
+ *
+ * ORIG!!!!
+ *
+ ********************************************************************/
- // Instantiate the AgentSession with an optional thread pool
- this.agentSession = this.numberOfThreads > 1
- ? new SnmpAgentSession(requestHandler, peer, this.numberOfThreads)
- : new SnmpAgentSession(requestHandler, peer);
+// // set community strings and protocol version
+// peer.getParameters().setReadCommunity(this.readCommunity);
+// peer.getParameters().setWriteCommunity(this.writeCommunity);
+// peer.getParameters().setVersion(this.snmpVersion == SNMPV2 ? SnmpSMI.SNMPV2 : SnmpSMI.SNMPV1);
+//
+
+
+
+
+// // Instantiate the AgentSession with an optional thread pool
+// this.agentSession = this.numberOfThreads > 1
+// ? new SnmpAgentSession(requestHandler, peer, this.numberOfThreads)
+// : new SnmpAgentSession(requestHandler, peer);
}
/**
@@ -601,4 +660,102 @@
return InetAddress.getByName(host);
}
+// @Override
+// public void processPdu(CommandResponderEvent event) {
+// PDU pdu = event.getPDU();
+//
+// if (pdu == null)
+// return;
+//
+// int type = pdu.getType();
+// //switch based on pdu.getType() == ___
+// PDU response = null;
+// try{
+// switch (type) {
+// case PDU.GET:
+// response = requestHandler.snmpReceivedGet(pdu, false);
+//// Address address = event.getPeerAddress();
+//// Snmp snmp = new Snmp(new DefaultTcpTransportMapping((TcpAddress)address));
+// break;
+// case PDU.GETBULK:
+// //TODO maybe make a method called snmpReceivedGetBulk in requesthandler
+// // requestHandler.snmpReceivedGet(pdu);
+// break;
+// case PDU.GETNEXT:
+// response = requestHandler.snmpReceivedGet(pdu, true);
+// break;
+// case PDU.SET:
+// response = requestHandler.snmpReceivedSet(pdu);
+// break;
+// default:
+// log.warn("Invalid PDU type: " + PDU.getTypeString(type));
+// return;
+// }
+// if (response != null) {
+// sendResponse(event, response);
+// }
+// } catch (Exception e){
+// log.debug("Snmp request failed: "+ PDU.getTypeString(pdu.getType()));
+// }
+//
+// }
+
+// private void sendResponse(CommandResponderEvent requestEvent, PDU response) {
+// //MessageDispatcher disp = requestEvent.getMessageDispatcher();
+// try {
+// if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
+// // response is tooBig
+// if (response.getType() != PDU.REPORT) {
+// if (requestEvent.getPDU().getType() == PDU.GETBULK) {
+// while ((response.size() > 0) &&
+// (response.getBERLength() >
+// requestEvent.getMaxSizeResponsePDU()))
+// {
+// response.trim();
+// }
+// }
+// else {
+// response.clear();
+// response.setRequestID(requestEvent.getPDU().getRequestID());
+// response.setErrorStatus(PDU.tooBig);
+// }
+// }
+// if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
+// //still too big and can't send a response
+// return;
+// }
+// }
+////---start of my addition -- Mar 29
+//
+//
+////--end of my addition
+//
+// StatusInformation status = new StatusInformation();
+// StateReference stateRef = requestEvent.getStateReference();
+// if (stateRef == null) {
+// log.warn("No state reference available for requestEvent="+
+// requestEvent+". Cannot return response="+response);
+// }
+// else {
+// stateRef.setTransportMapping(requestEvent.getTransportMapping());
+// int resp = requestEvent.getMessageDispatcher().returnResponsePdu(requestEvent.getMessageProcessingModel(),
+// requestEvent.getSecurityModel(),
+// requestEvent.getSecurityName(),
+// requestEvent.getSecurityLevel(),
+// response,
+// requestEvent.getMaxSizeResponsePDU(),
+// //requestEvent.getStateReference(),
+// stateRef,
+// status);
+// log.info("Response was OK? : "+resp +" Constant: "+SnmpConstants.SNMP_MP_OK);
+// log.info("Returned response for requestID: " +
+// requestEvent.getPDU().getRequestID().toString() +
+// "to peer: "+requestEvent.getPeerAddress().toString());
+// }
+// }
+// catch (MessageException ex) {
+// log.error("Failed to send response to request "+requestEvent, ex);
+// }
+// }
+
}
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpRequest.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,121 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+import org.jboss.logging.Logger;
+import org.snmp4j.CommandResponder;
+import org.snmp4j.CommandResponderEvent;
+import org.snmp4j.MessageException;
+import org.snmp4j.PDU;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.mp.StateReference;
+import org.snmp4j.mp.StatusInformation;
+
+public class SnmpRequest implements CommandResponder {
+
+ /** Logger object */
+ protected Logger log;
+
+ /** the request handler instance handling get/set requests */
+ private RequestHandler requestHandler;
+
+ public SnmpRequest(RequestHandler requestHandler, Logger log){
+ this.requestHandler = requestHandler;
+ this.log = log;
+ }
+
+ public void setRequestHandler(RequestHandler requestHandler){
+ this.requestHandler = requestHandler;
+ }
+
+ public RequestHandler getRequestHandler(){
+ return this.requestHandler;
+ }
+
+ @Override
+ //TODO: catch thrown exceptions properly and decide what to do with them.
+ public void processPdu(CommandResponderEvent event){
+ PDU pdu = event.getPDU();
+
+ if (pdu == null) {
+ log.warn("Null request PDU received ... skipping");
+ return;
+ }
+
+ log.info("Received Snmp request of type: "+PDU.getTypeString(pdu.getType()));
+ int type = pdu.getType();
+
+ PDU response = null;
+ //switch based on pdu.getType() == ___
+ switch (type) {
+ case PDU.GET:
+ case PDU.GETNEXT:
+ response = requestHandler.snmpReceivedGet(pdu);
+ break;
+ case PDU.GETBULK:
+ response = requestHandler.snmpReceivedGetBulk(pdu);
+ break;
+ case PDU.SET:
+ response = requestHandler.snmpReceivedSet(pdu);
+ break;
+ default:
+ log.warn("Cannot process request PDU of type: " +
+ PDU.getTypeString(type) + "unsupported");
+ return;
+ }
+ if (response != null) {
+
+ //VERY IMPORTANT LINE
+ response.setRequestID(event.getPDU().getRequestID());
+ try {
+ sendResponse(event, response);
+ } catch (MessageException e) {
+ log.warn("Response may not have been sent correctly. " +
+ "An error occured snmp4j message processing: " +
+ e.getMessage());
+ }
+ }
+ }
+
+ private void sendResponse(CommandResponderEvent requestEvent, PDU response) throws MessageException{
+
+ if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
+ // response is tooBig
+ if (response.getType() != PDU.REPORT) {
+ if (requestEvent.getPDU().getType() == PDU.GETBULK) {
+ while ((response.size() > 0) &&
+ (response.getBERLength() >
+ requestEvent.getMaxSizeResponsePDU()))
+ {
+ response.trim();
+ }
+ }
+ else {
+ response.clear();
+ response.setRequestID(requestEvent.getPDU().getRequestID());
+ response.setErrorStatus(PDU.tooBig);
+ }
+ }
+ if (response.getBERLength() > requestEvent.getMaxSizeResponsePDU()) {
+ //still too big and can't send a response
+ return;
+ }
+ }
+
+ StatusInformation status = new StatusInformation();
+ StateReference stateRef = requestEvent.getStateReference();
+ if (stateRef == null) {
+ log.warn("No state reference available for requestEvent="+
+ requestEvent+". Cannot return response="+response);
+ }
+ else {
+ stateRef.setTransportMapping(requestEvent.getTransportMapping());
+ int resp = requestEvent.getMessageDispatcher().returnResponsePdu(requestEvent.getMessageProcessingModel(),
+ requestEvent.getSecurityModel(),
+ requestEvent.getSecurityName(),
+ requestEvent.getSecurityLevel(),
+ response,
+ requestEvent.getMaxSizeResponsePDU(),
+ stateRef,
+ status);
+ }
+ }
+}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -29,6 +29,12 @@
import org.opennms.protocols.snmp.SnmpObjectId;
import org.opennms.protocols.snmp.SnmpOctetString;
import org.opennms.protocols.snmp.SnmpVarBind;
+import org.snmp4j.smi.Counter32;
+import org.snmp4j.smi.Counter64;
+import org.snmp4j.smi.Integer32;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.VariableBinding;
/**
* <tt>SnmpVarBindFactory</tt> implements the infrastructure required to
* generate SNMP variable bindings from generic Object instances.
@@ -61,7 +67,7 @@
{
makers.put("java.lang.String", new SnmpOctetStringMaker());
makers.put("java.lang.Integer", new SnmpInt32Maker());
- makers.put("java.lang.Long", new SnmpCounter64Maker());
+ makers.put("java.lang.Long", new SnmpCounter32Maker());
makers.put("java.math.BigInteger", new SnmpCounter64Maker());
makers.put("java.util.Date", new SnmpDateMaker());
}
@@ -71,7 +77,7 @@
* provided value, as this is returned by "getClass().getName()". If a
* match is found the call is delegated to the returned maker.
**/
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException
{
// Get value type and locate the maker
@@ -94,7 +100,7 @@
**/
interface Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException;
}
@@ -104,15 +110,31 @@
class SnmpInt32Maker
implements Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException
{
Integer i = (Integer)value;
- return new SnmpVarBind(new SnmpObjectId(oid),
- new SnmpInt32(i));
+ return new VariableBinding(new OID(oid),
+ new Integer32(i));
}
} // class SnmpInt32Maker
+
+ /**
+ * Generates unsigned long integer SNMP variable bindings
+ **/
+ class SnmpCounter32Maker
+ implements Maker
+ {
+ public VariableBinding make(String oid, Object value)
+ throws MappingFailedException
+ {
+ Long l = (Long)value;
+
+ return new VariableBinding(new OID(oid),
+ new Counter32(l.longValue()));
+ }
+ } // class SnmpCounter64Maker
/**
* Generates unsigned long integer SNMP variable bindings
@@ -120,13 +142,13 @@
class SnmpCounter64Maker
implements Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException
{
Long l = (Long)value;
- return new SnmpVarBind(new SnmpObjectId(oid),
- new SnmpCounter64(l.longValue()));
+ return new VariableBinding(new OID(oid),
+ new Counter64(l.longValue()));
}
} // class SnmpCounter64Maker
@@ -136,13 +158,13 @@
class SnmpOctetStringMaker
implements Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException
{
String s = (String)value;
- return new SnmpVarBind(new SnmpObjectId(oid),
- new SnmpOctetString(s.getBytes()));
+ return new VariableBinding(new OID(oid),
+ new OctetString(s.getBytes()));
}
} // class OctetStringMaker
@@ -152,7 +174,7 @@
class SnmpDateMaker
implements Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException
{
Date d = (Date)value;
@@ -168,7 +190,7 @@
class SnmpObjectMaker
implements Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException
{
SnmpOctetStringMaker sMaker = new SnmpOctetStringMaker();
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -19,6 +19,7 @@
**/
package org.jboss.jmx.adaptor.snmp.agent;
+import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
@@ -36,10 +37,31 @@
import org.jboss.xb.binding.MappingObjectModelFactory;
import org.jboss.xb.binding.Unmarshaller;
import org.jboss.xb.binding.UnmarshallerFactory;
-import org.opennms.protocols.snmp.SnmpIPAddress;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduTrap;
+//import org.opennms.protocols.snmp.SnmpIPAddress;
+//import org.opennms.protocols.snmp.SnmpPduPacket;
+//import org.opennms.protocols.snmp.SnmpPduTrap;
+import org.snmp4j.CommunityTarget;
+import org.snmp4j.PDUv1;
+import org.snmp4j.PDU;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.Target;
+import org.snmp4j.Snmp;
+import org.snmp4j.UserTarget;
+import org.snmp4j.mp.MPv3;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.security.SecurityModels;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.USM;
+import org.snmp4j.smi.Address;
+import org.snmp4j.smi.IpAddress;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.TcpAddress;
+import org.snmp4j.smi.UdpAddress;
+import org.snmp4j.transport.AbstractTransportMapping;
+import org.snmp4j.transport.DefaultTcpTransportMapping;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
+
/**
* <tt>TrapEmitter</tt> is a class that manages SNMP trap emission.
*
@@ -124,14 +146,6 @@
throws Exception
{
synchronized(this.managers) {
-
- // Recycle open sessions to managers
- Iterator i = this.managers.iterator();
-
- while (i.hasNext()) {
- ManagerRecord s = (ManagerRecord)i.next();
- s.closeSession();
- }
// Drop all held manager records
this.managers.clear();
@@ -158,45 +172,79 @@
}
// Cache the translated notification
- SnmpPduTrap v1TrapPdu = null;
- SnmpPduPacket v2TrapPdu = null;
-
+ PDUv1 v1TrapPdu = null;
+ PDU v2cTrapPdu = null;
+ ScopedPDU v3TrapPdu = null;
+
+ //The snmp session
+ Snmp snmp = null;
+
+ //The target to send to
+ Target t = null;
+
// Send trap. Synchronise on the subscription collection while
// iterating
- synchronized(this.managers) {
-
+ synchronized(this.managers) {
+
// Iterate over sessions and emit the trap on each one
Iterator i = this.managers.iterator();
while (i.hasNext()) {
- ManagerRecord s = (ManagerRecord)i.next();
-
+ //ManagerRecord t = (ManagerRecord)i.next();
+ t = (Target)i.next();
+
try {
- switch (s.getVersion()) {
- case SnmpAgentService.SNMPV1:
+ snmp = createSnmpSession(t.getAddress());
+ switch (t.getVersion()) {
+ case SnmpConstants.version1:
+ //case SnmpAgentService.SNMPV1:
if (v1TrapPdu == null)
v1TrapPdu = this.trapFactory.generateV1Trap(n);
// fix the agent ip in the trap depending on which local address is bound
- v1TrapPdu.setAgentAddress(new SnmpIPAddress(s.getLocalAddress()));
-
+ //Should work, but need to upgrade to snmp4j v.1.10.2
+ //v1TrapPdu.setAgentAddress((IpAddress)t.getAddress());
+
// Advance the trap counter
this.trapCount.advance();
// Send
- s.getSession().send(v1TrapPdu);
+ //s.getSession().send(v1TrapPdu);
+ log.debug("Sending trap: "+v1TrapPdu.toString() + "\n to target: "+ t.toString());
+ snmp.send(v1TrapPdu, t);
break;
- case SnmpAgentService.SNMPV2:
- if (v2TrapPdu == null)
- v2TrapPdu = this.trapFactory.generateV2Trap(n);
+ case SnmpConstants.version2c:
+ //case SnmpAgentService.SNMPV2:
+ if (v2cTrapPdu == null)
+ v2cTrapPdu = this.trapFactory.generateV2cTrap(n);
// Advance the trap counter
this.trapCount.advance();
// Send
- s.getSession().send(v2TrapPdu);
+ //t.getSession().send(v2TrapPdu);
+ snmp.send(v2cTrapPdu, t);
break;
+ case SnmpConstants.version3:
+
+ if (v3TrapPdu == null)
+ v3TrapPdu = this.trapFactory.generateV3Trap(n);
+
+// if (contextEngineID != null) {
+// trapPdu.setContextEngineID(contextEngineID);
+// }
+// if (contextName != null) {
+// trapPdu.setContextName(contextName);
+// }
+
+ // Advance the trap counter
+ this.trapCount.advance();
+
+ // Send
+ snmp.send(v3TrapPdu, t);
+ break;
+
default:
log.error("Skipping session: Unknown SNMP version found");
}
@@ -206,11 +254,17 @@
}
catch(Exception e) {
log.error("SNMP send error for " +
- s.getAddress().toString() + ":" +
- s.getPort() + ": <" + e +
+ t.getAddress().toString() + ":" +
+ ": <" + e +
">");
}
- }
+ }
+ if (snmp != null){
+ snmp.close();
+ }
+ else {
+ log.warn("No SNMP managers to send traps to");
+ }
}
}
@@ -261,36 +315,62 @@
{
// Read the monitoring manager's particulars
Manager m = (Manager)i.next();
-
- try
- {
- // Create a record of the manager's interest
- ManagerRecord mr = new ManagerRecord(
- InetAddress.getByName(m.getAddress()),
- m.getPort(),
- toInetAddressWithDefaultBinding(m.getLocalAddress()),
- m.getLocalPort(),
- m.getVersion()
- );
+ fixManagerVersion(m);
+// try
+// {
+ // Create a record of the manager's interest
+
+ Target target = createTarget(m);
+ if (target == null){
+ log.warn("createTarget: manager m: "+m.toString() + " is null!");
+ continue;
+ }
+
+// ManagerRecord mr = new ManagerRecord(
+// InetAddress.getByName(m.getAddress()),
+// m.getPort(),
+// toInetAddressWithDefaultBinding(m.getLocalAddress()),
+// m.getLocalPort(),
+// m.getVersion()
+// );
// Add the record to the list of monitoring managers. If
// successfull open the session to the manager as well.
- if (this.managers.add(mr) == false)
+ if (this.managers.add(target) == false)
{
log.warn("Ignoring duplicate manager: " + m);
}
- else
- {
+ //else
+ //{
// Open the session to the manager
- mr.openSession();
- }
- }
- catch (Exception e)
- {
- log.warn("Error enabling monitoring manager: " + m, e);
- }
+ //mr.openSession();
+ //}
+// }
+// catch (Exception e)
+// {
+// log.warn("Error enabling monitoring manager: " + m, e);
+// }
}
}
+
+ /**
+ * Function used to change the SNMP versions received from managers
+ * config file (1,2,3) to the actual versions used to distinguish in
+ * snmp4j (0,1,3)
+ * @param m the Manager who's version we want to fix
+ */
+ private void fixManagerVersion(Manager m){
+ if (m != null){
+ switch (m.getVersion()){
+ case 1:
+ m.setVersion(SnmpConstants.version1);
+ break;
+ case 2:
+ m.setVersion(SnmpConstants.version2c);
+ }
+
+ }
+ }
/**
* cater for possible global -b option, if no override has been specified
@@ -310,4 +390,81 @@
return InetAddress.getByName(host);
}
+ private Target createTarget(Manager m){
+ Target target = null;
+// String newAddr;
+// if (m.getAddress() != null){
+// System.out.println("*************************************");
+// System.out.println("Address" + m.getAddress());
+// System.out.println("Port" + m.getPort());
+// System.out.println("*************************************");
+// newAddr = m.getAddress()+"/"+m.getPort();
+// }
+// else {return null;}
+
+ int version = m.getVersion();
+ try{
+ if (version == SnmpConstants.version1 || version == SnmpConstants.version2c){
+
+ //change 'public' to a constant somewhere
+ //target = new CommunityTarget(new TcpAddress(newAddr), new OctetString("public"));
+
+ if (m.getAddress() != null){
+ target = new CommunityTarget(new UdpAddress(InetAddress.getByName(m.getAddress()), m.getPort()), new OctetString(m.getCommunityString()));
+ //try defining retries/timeout period in notifications.xml
+ //Timeout and Retries needs to be a field later on
+ //target.setRetries(3);
+ target.setTimeout(8000);
+ }
+ }
+ else if (version == SnmpConstants.version3) {
+ //won't be used at the moment
+ target = new UserTarget();
+ target.setAddress(new UdpAddress(InetAddress.getByName(m.getAddress()), m.getPort()));
+ }
+ else {
+ //unrecognized version
+ return null;
+ }
+
+ } catch (UnknownHostException e) {} //something goes here
+ if (target != null){
+ target.setVersion(version);
+ }
+ return target;
+ }
+
+ private Snmp createSnmpSession(Address address) throws IOException {
+ AbstractTransportMapping transport;
+ if (address instanceof TcpAddress) {
+ transport = new DefaultTcpTransportMapping();
+ }
+ else {
+ transport = new DefaultUdpTransportMapping();
+ }
+ // Could save some CPU cycles:
+ // transport.setAsyncMsgProcessingSupported(false);
+
+ Snmp snmp = new Snmp(transport);
+ OctetString localEngineID =
+ new OctetString(snmp.getLocalEngineID());
+ USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0);
+ SecurityModels.getInstance().addSecurityModel(usm);
+
+
+// SNMPv3 stuff ~ add and fix later
+//
+// ((MPv3)snmp.getMessageProcessingModel(MPv3.ID)).
+// setLocalEngineID(localEngineID.getValue());
+//
+// if (version == SnmpConstants.version3) {
+// USM usm = new USM(SecurityProtocols.getInstance(),
+// localEngineID,
+// engineBootCount);
+// SecurityModels.getInstance().addSecurityModel(usm);
+// addUsmUser(snmp);
+// }
+ return snmp;
+ }
+
} // class TrapEmitter
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -21,8 +21,9 @@
import javax.management.Notification;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduTrap;
+import org.snmp4j.PDUv1;
+import org.snmp4j.PDU;
+import org.snmp4j.ScopedPDU;
/**
* <tt>TrapFactory </tt> takes care of translation of Notifications into
@@ -77,20 +78,31 @@
public void start()
throws Exception;
+
/**
- * Translates a Notification to an SNMP V2 trap.
+ * Traslates a Notification to an SNMP V1 trap.
*
* @param the notification to be translated
**/
- public SnmpPduPacket generateV2Trap(Notification n)
- throws MappingFailedException;
+ public PDUv1 generateV1Trap(Notification n)
+ throws MappingFailedException;
+
+ /**
+ * Translates a Notification to an SNMP V2c trap.
+ *
+ * @param the notification to be translated
+ **/
+// public SnmpPduPacket generateV2Trap(Notification n)
+// throws MappingFailedException;
+ public PDU generateV2cTrap(Notification n)
+ throws MappingFailedException;
/**
- * Traslates a Notification to an SNMP V1 trap.
+ * Traslates a Notification to an SNMP V3 trap.
*
* @param the notification to be translated
**/
- public SnmpPduTrap generateV1Trap(Notification n)
- throws MappingFailedException;
+ public ScopedPDU generateV3Trap(Notification n)
+ throws MappingFailedException;
} // TrapFactory
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -40,9 +40,13 @@
import org.jboss.xb.binding.Unmarshaller;
import org.jboss.xb.binding.UnmarshallerFactory;
import org.jboss.xb.binding.UnmarshallingContext;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduRequest;
-import org.opennms.protocols.snmp.SnmpPduTrap;
+//import org.opennms.protocols.snmp.SnmpPduPacket;
+//import org.opennms.protocols.snmp.SnmpPduRequest;
+//import org.opennms.protocols.snmp.SnmpPduTrap;
+import org.snmp4j.PDU;
+import org.snmp4j.PDUv1;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.smi.OID;
import org.xml.sax.Attributes;
/**
@@ -265,7 +269,7 @@
/**
* Traslates a Notification to an SNMP V1 trap.
**/
- public SnmpPduTrap generateV1Trap(Notification n)
+ public PDUv1 generateV1Trap(Notification n)
throws MappingFailedException
{
if (log.isTraceEnabled())
@@ -287,14 +291,15 @@
Mapping m = (Mapping)this.notificationMapList.get(index);
// Create trap
- SnmpPduTrap trapPdu = new SnmpPduTrap();
+ PDUv1 trapPdu = new PDUv1();
- trapPdu.setTimeStamp(this.clock.uptime());
+ trapPdu.setTimestamp(this.clock.uptime());
+ trapPdu.setType(PDU.V1TRAP);
// Organise the 'variable' payload
- trapPdu.setGeneric(m.getGeneric());
- trapPdu.setSpecific(m.getSpecific());
- trapPdu.setEnterprise(m.getEnterprise());
+ trapPdu.setGenericTrap(m.getGeneric());
+ trapPdu.setSpecificTrap(m.getSpecific());
+ trapPdu.setEnterprise(new OID(m.getEnterprise()));
// Append the specified varbinds. Get varbinds from mapping and for
// each one of the former use the wrapper to get the corresponding
@@ -322,8 +327,8 @@
// wrapper in order for it to locate the required value. That
// value and the aforementioned OID are used to generate the
// variable binding
- trapPdu.addVarBind(
- this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ trapPdu.add(
+ this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
}
}
else
@@ -336,15 +341,15 @@
}
/**
- * Traslates a Notification to an SNMP V2 trap.
+ * Traslates a Notification to an SNMP V2c trap.
*
* TODO: how do you get timestamp, generic, and specific stuff in the trap
**/
- public SnmpPduPacket generateV2Trap(Notification n)
+ public PDU generateV2cTrap(Notification n)
throws MappingFailedException
{
if (log.isTraceEnabled())
- log.trace("generateV2Trap");
+ log.trace("generateV2cTrap");
// Locate mapping for incomming event
int index = -1;
@@ -362,7 +367,8 @@
Mapping m = (Mapping)this.notificationMapList.get(index);
// Create trap
- SnmpPduRequest trapPdu = new SnmpPduRequest(SnmpPduPacket.V2TRAP);
+ PDU trapPdu = new PDU();
+ trapPdu.setType(PDU.TRAP);
// Append the specified varbinds. Get varbinds from mapping and for
// each one of the former use the wrapper to get data from the
@@ -388,8 +394,8 @@
// wrapper in order for it to locate the required value. That
// value and the aforementioned OID are used to generate the
// variable binding
- trapPdu.addVarBind(
- this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ trapPdu.add(
+ this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
}
}
else
@@ -401,6 +407,72 @@
}
/**
+ * Traslates a Notification to an SNMP V3 trap.
+ *
+ * TODO: how do you get timestamp, generic, and specific stuff in the trap
+ **/
+ public ScopedPDU generateV3Trap(Notification n)
+ throws MappingFailedException
+ {
+ if (log.isTraceEnabled())
+ log.trace("generateV3Trap");
+
+ // Locate mapping for incomming event
+ int index = -1;
+
+ try
+ {
+ index = findMappingIndex(n);
+ }
+ catch (IndexOutOfBoundsException e)
+ {
+ throw new MappingFailedException(
+ "No mapping found for notification type: '" + n.getType() + "'");
+ }
+
+ Mapping m = (Mapping)this.notificationMapList.get(index);
+
+ // Create trap
+ ScopedPDU trapPdu = new ScopedPDU();
+ trapPdu.setType(PDU.TRAP);
+
+ // Append the specified varbinds. Get varbinds from mapping and for
+ // each one of the former use the wrapper to get data from the
+ // notification
+
+ // Get the coresponding wrapper
+ NotificationWrapper wrapper =
+ (NotificationWrapper)this.notificationWrapperCache.get(index);
+
+ if (wrapper != null)
+ {
+ // Prime the wrapper with the notification contents
+ wrapper.prime(n);
+
+ List vbList = m.getVarBindList().getVarBindList();
+
+ for (int i = 0; i < vbList.size(); i++)
+ {
+ VarBind vb = (VarBind)vbList.get(i);
+
+ // Append the var bind. Interrogate read vb for OID and
+ // variable tag. The later is used as the key passed to the
+ // wrapper in order for it to locate the required value. That
+ // value and the aforementioned OID are used to generate the
+ // variable binding
+ trapPdu.add(
+ this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ }
+ }
+ else
+ {
+ log.warn("Varbind mapping failure: null wrapper defined for " +
+ " notification type '" + m.getNotificationType() + "'" );
+ }
+ return trapPdu;
+ }
+
+ /**
* Utility class used by JBossXB to help parse notifications.xml
*/
private static class NotificationBinding implements GenericObjectModelFactory
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/VariableTypeException.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,22 @@
+package org.jboss.jmx.adaptor.snmp.agent;
+
+/**
+ * This exception is thrown when a client attempts to either GET a variable that
+ * is of a type not supported by our SNMP adaptor (hopefully very few types eventually),
+ * or if the client attempts to SET an attribute of type T to something of a type that is not T
+ * (ie a String to an int)
+ *
+ * @author Thomas Hauser <a href="mailto:thauser at redhat.com"></a>
+ *
+ */
+
+public class VariableTypeException extends Exception{
+
+ public VariableTypeException(){
+ super("Error: Variable type mismatch.");
+ }
+
+ public VariableTypeException(String m){
+ super(m);
+ }
+}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -23,15 +23,22 @@
/**
* An attribute mapping, by default readonly.
+ * **New addition**
+ * Can now be of type Scalar or Tabular.
+ * If the type is scalar, the OID is created with 0 as the instance identifier.
+ * It may be queried normally, with a .0 suffix on the OID.
*
+ *
+ *
+ *
* @author <a href="mailto:hwr at pilhuhn.de">Heiko W. Rupp</a>
* @version $Revision$
*/
public class MappedAttribute
{
- String name;
- String oid;
- boolean isReadWrite = false;
+ private String name;
+ private String oid;
+ private boolean isReadWrite = false;
/** Attribute name */
public String getName()
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTable.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTable.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTable.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,77 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.config.attribute;
+
+/**
+ * This class denotes a Table of data.
+ * Essentially it is just a conceptual grouping of attributes into a table.
+ * This functionality can simplify retrieving certain attributes and organization of the MIB.
+ * The name can be arbitrary. It is simply a label used for organization.
+ *
+ * Tables are never writable.
+ *
+ * @author <a href="mailto:hwr at pilhuhn.de">Heiko W. Rupp</a>
+ * @version $Revision: 81038 $
+ */
+public class MappedTable
+{
+ private String name;
+ private String oidPrefix;
+ private int size;
+
+ public String getName()
+ {
+ return this.name;
+ }
+
+ public void setName(String name)
+ {
+ this.name = name;
+ }
+
+ // Table OID
+ public String getPrefix()
+ {
+ return this.oidPrefix;
+ }
+
+ public void setPrefix(String oid)
+ {
+ this.oidPrefix = oid;
+ }
+
+ public int getSize(){
+ return this.size;
+ }
+ public void setSize(int n){
+ this.size = n;
+ }
+
+ public String toString()
+ {
+ StringBuffer buf = new StringBuffer();
+ buf.append("[table name=").append(name);
+ buf.append(", oid=").append(oidPrefix);
+ buf.append("]");
+ return buf.toString();
+ }
+}
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTableRow.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTableRow.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedTableRow.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,77 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.jmx.adaptor.snmp.config.attribute;
+
+/**
+ * This class denotes a Table of data.
+ * Essentially it is just a conceptual grouping of attributes into a table.
+ * This functionality can simplify retrieving certain attributes and organization of the MIB.
+ * The name can be arbitrary. It is simply a label used for organization.
+ *
+ * Tables are never writable.
+ *
+ * @author <a href="mailto:hwr at pilhuhn.de">Heiko W. Rupp</a>
+ * @version $Revision: 81038 $
+ */
+public class MappedTableRow
+{
+ private String name;
+ private String oidPrefix;
+ private int size;
+
+ public String getName()
+ {
+ return this.name;
+ }
+
+ public void setName(String name)
+ {
+ this.name = name;
+ }
+
+ // Table OID
+ public String getPrefix()
+ {
+ return this.oidPrefix;
+ }
+
+ public void setPrefix(String oid)
+ {
+ this.oidPrefix = oid;
+ }
+
+ public int getSize(){
+ return this.size;
+ }
+ public void setSize(int n){
+ this.size = n;
+ }
+
+ public String toString()
+ {
+ StringBuffer buf = new StringBuffer();
+ buf.append("[table name=").append(name);
+ buf.append(", oid=").append(oidPrefix);
+ buf.append("]");
+ return buf.toString();
+ }
+}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -37,6 +37,7 @@
private String localAddress;
private int localPort;
private int version;
+ private String communityString;
// Constructors -------------------------------------------------
@@ -102,6 +103,17 @@
}
/**
+ * Method getCommunityString returns the value of field 'communityString'.
+ *
+ * @return the value of field 'communityString'.
+ *
+ */
+ public String getCommunityString()
+ {
+ return communityString;
+ }
+
+ /**
* Method setAddress sets the value of field 'address'.
*
* @param address the value of field 'address'.
@@ -152,6 +164,17 @@
this.version = version;
}
+ /**
+ * Method getCommunityString sets the value of field 'communityString'.
+ *
+ * @return the value of field 'communityString'.
+ *
+ */
+ public void setCommunityString(String communityString)
+ {
+ this.communityString = communityString;
+ }
+
// Object overrides ----------------------------------------------
public String toString()
@@ -163,7 +186,8 @@
.append(", port=").append(port)
.append(", localAddress=").append(localAddress)
.append(", localPort=").append(localPort)
- .append(", version=").append(version)
+ .append(", version=").append(version)
+ .append(", communityString=").append(communityString)
.append(']');
return sbuf.toString();
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -27,8 +27,12 @@
import org.jboss.system.ServiceMBeanSupport;
import org.jboss.system.server.ServerConfigLocator;
import org.jboss.system.server.ServerInfoMBean;
-import org.opennms.protocols.snmp.SnmpObjectId;
-import org.opennms.protocols.snmp.SnmpTimeTicks;
+//import org.opennms.protocols.snmp.SnmpObjectId;
+//import org.opennms.protocols.snmp.SnmpTimeTicks;
+import org.snmp4j.smi.OID;
+// TODO: make a better representation of the time, similar to SnmpTimeTicks, 0m 0w 0d 0h 0s 00ms
+// maybe even extend timeticks and simply override it's toString method;
+import org.snmp4j.smi.TimeTicks;
/**
* An MBean service that defines the MIB-2 system group an agent
@@ -57,7 +61,7 @@
// Private Data --------------------------------------------------
private String sysDescr; // system.1
- private SnmpObjectId sysObjectId; // system.2
+ private OID sysObjectId; // system.2
// private long sysUpTime; // system.3
private String sysContact; // system.4
private String sysName; // system.5 usually fqdn
@@ -112,7 +116,7 @@
/**
* @jmx:managed-attribute
*/
- public SnmpObjectId getSysObjectId()
+ public OID getSysObjectId()
{
return sysObjectId;
}
@@ -121,14 +125,14 @@
* The system uptime in hundreth of a second (TimeTicks)
* @jmx:managed-attribute
*/
- public SnmpTimeTicks getSysUpTime()
+ public TimeTicks getSysUpTime()
{
if (snmpAgent !=null)
{
try
{
Long upTime = (Long)server.getAttribute(snmpAgent, "Uptime");
- return new SnmpTimeTicks(upTime.longValue() / 10);
+ return new TimeTicks(upTime.longValue() / 10);
}
catch (Exception e)
{
@@ -136,7 +140,7 @@
}
}
// fallback
- return new SnmpTimeTicks(System.currentTimeMillis() / 10);
+ return new TimeTicks(System.currentTimeMillis() / 10);
}
/**
@@ -209,7 +213,7 @@
this.sysName = serverConfig + "@" + hostAddress;
log.debug("Setting sysName name to " + sysName);
}
- this.sysObjectId = new SnmpObjectId(JBOSS_PREFIX + PRODUCT + VERSION);
+ this.sysObjectId = new OID(JBOSS_PREFIX + PRODUCT + VERSION);
}
}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -25,8 +25,10 @@
import org.jboss.mx.util.ObjectNameFactory;
import org.jboss.system.ServiceMBean;
-import org.opennms.protocols.snmp.SnmpObjectId;
-import org.opennms.protocols.snmp.SnmpTimeTicks;
+//import org.opennms.protocols.snmp.SnmpObjectId;
+//import org.opennms.protocols.snmp.SnmpTimeTicks;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.TimeTicks;
/**
* MIB2SystemGroupService MBean interface
@@ -51,10 +53,10 @@
String getSysDescr();
/** The oid of the system (system.2) -- not yet supported */
- SnmpObjectId getSysObjectId();
+ OID getSysObjectId();
/** The uptime of the system (system.3) */
- SnmpTimeTicks getSysUpTime();
+ TimeTicks getSysUpTime();
/** The system contact person (system.4) */
void setSysContact(String sysContact);
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -19,9 +19,27 @@
**/
package org.jboss.jmx.adaptor.snmp.test;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
import javax.management.Notification;
-
+import org.jboss.jmx.adaptor.snmp.agent.EventTypes;
import org.jboss.system.ServiceMBeanSupport;
+import org.snmp4j.CommunityTarget;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.PDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.Target;
+import org.snmp4j.event.ResponseEvent;
+import org.snmp4j.smi.Address;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.TcpAddress;
+import org.snmp4j.smi.UdpAddress;
+import org.snmp4j.smi.VariableBinding;
+import org.snmp4j.smi.*;
+import org.snmp4j.transport.DefaultTcpTransportMapping;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
/**
* <tt>NotificationProducerService</tt> is a test class with an MBean interface
@@ -40,6 +58,7 @@
extends ServiceMBeanSupport
implements NotificationProducerServiceMBean
{
+
/**
* Sends a test Notification of type "V1"
*
@@ -48,8 +67,10 @@
public void sendV1()
throws Exception
{
- sendNotification(
- new Notification("V1", this, getNextNotificationSequenceNumber(),
+ log.debug("Sending SnmpV1 test notification");
+
+ sendNotification(
+ new Notification(EventTypes.V1_TEST_NOTIFICATION, this, getNextNotificationSequenceNumber(),
"V1 test notifications"));
}
@@ -61,10 +82,172 @@
public void sendV2()
throws Exception
{
- sendNotification(
- new Notification("V2", this, getNextNotificationSequenceNumber(),
+ log.debug("Sending SnmpV2 test notification");
+ sendNotification(
+ new Notification(EventTypes.V2_TEST_NOTIFICATION, this, getNextNotificationSequenceNumber(),
"V2 test notifications"));
}
+ /**
+ * Sends a test Notification of type "V3"
+ *
+ * @jmx:managed-operation
+ **/
+ public void sendV3()
+ throws Exception
+ {
+ log.debug("Sending SnmpV3 test notification");
+ sendNotification(
+ new Notification(EventTypes.V3_TEST_NOTIFICATION, this, getNextNotificationSequenceNumber(),
+ "V3 test notifications"));
+ }
+
+ public void getBulk(){
+ PDU pdu = new PDU();
+ pdu.setType(PDU.GETBULK);
+ pdu.add(new VariableBinding(new OID("1.2.3.4.1.1")));
+ pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.0")));
+ pdu.setMaxRepetitions(7);
+ pdu.setNonRepeaters(1);
+ CommunityTarget target = new CommunityTarget();
+ OctetString community = new OctetString("public");
+ target.setCommunity(community);
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(2000);
+
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+ long t1 = System.currentTimeMillis();
+ System.out.println("SENDING: "+t1);
+ System.out.println("PDU: "+pdu);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ long t2=System.currentTimeMillis();
+ System.out.println("SENT: "+t2);
+ System.out.println("ELAPSED: "+(t2-t1));
+ System.out.println("response " + responseEvent.toString());
+
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null){
+ System.out.println("Request timed out");
+ }
+ else{
+ System.out.println("Received response "+responsePDU);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!");
+ }
+
+
+ }
+
+
+ /**
+ * Sends a test GET request
+ *
+ * @jmx:managed-operation
+ */
+ public void get(){
+ PDU pdu = new PDU();
+ pdu.setType(PDU.GET);
+ pdu.add(new VariableBinding(new OID("1.2.3.4.1.3")));
+
+ CommunityTarget target = new CommunityTarget();
+ OctetString community = new OctetString("public");
+ target.setCommunity(community);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(2000);
+
+ try {
+
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ Snmp snmp = new Snmp(transport);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ System.out.println("response " + responseEvent.toString());
+ // extract the response PDU (could be null if timed out)
+
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null){
+ System.out.println("Request Timed out ...");
+ }
+ else {
+ System.out.println("RESPONSE RECEIVED!");
+ System.out.println("responsePdu = " + responsePDU);
+
+ }
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Sends a test SET request
+ *
+ * @jmx:managed-operation
+ */
+ public void set(){
+ PDU pdu = new PDU();
+ OID oidn = new OID("1.3.6.1.2.1.1.1");
+ Variable var = new OctetString("MBean Set Test");
+ VariableBinding varBind = new VariableBinding(oidn, var);
+ pdu.add(varBind);
+ pdu.setType(PDU.SET);
+
+ CommunityTarget target = new CommunityTarget();
+ target.setCommunity(new OctetString("private"));
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(1000);
+
+ try
+ {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ Snmp snmp = new Snmp(transport);
+
+ ResponseEvent responseEvent = snmp.set(pdu, target);
+
+ PDU responsePDU = responseEvent.getResponse();
+
+ if (responsePDU == null){
+ System.out.println("Request timed out.");
+ }
+ else {
+ System.out.println("Received response "+responsePDU);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ } catch (UnknownHostException e1) {
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!");
+ }
+
+
+ }
+
} // class NotificationProducerService
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -35,5 +35,20 @@
* Sends a test Notification of type "V2"
*/
void sendV2() throws java.lang.Exception;
+
+ /**
+ * Sends a test Notification of type "V3"
+ */
+ void sendV3() throws java.lang.Exception;
+
+ /**
+ * Sends a test SNMP GET
+ */
+ void get();
+
+ /**
+ * Sends a test SNMP SET
+ */
+ void set();
}
Added: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java (rev 0)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/Test.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -0,0 +1,409 @@
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Vector;
+
+import org.snmp4j.CommandResponder;
+import org.snmp4j.CommandResponderEvent;
+import org.snmp4j.CommunityTarget;
+import org.snmp4j.PDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.Target;
+import org.snmp4j.event.ResponseEvent;
+import org.snmp4j.event.ResponseListener;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.smi.*;
+import org.snmp4j.transport.DefaultTcpTransportMapping;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
+//v3 requires the following
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.UserTarget;
+import org.snmp4j.security.AuthMD5;
+import org.snmp4j.security.PrivDES;
+import org.snmp4j.security.UsmUser;
+import org.snmp4j.security.SecurityLevel;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.SecurityModels;
+import org.snmp4j.security.USM;
+import org.snmp4j.mp.MPv3;
+
+public class Test {
+
+ public static void main(String[] args){
+
+ //original oid "1.2.3.4.5"
+ if (args[0].equals("get")){
+ get(args);
+ }
+ else if (args[0].equals("getnext")){
+ getnext(args);
+ }
+ else if (args[0].equals("getbulk")){
+ getbulk();
+ }
+ else if (args[0].equals("set")){
+ set(args);
+ }
+ else if (args[0].equals("testnullpdu")){
+ testnull();
+ }
+ else if (args[0].equals("snmpwalk")){
+ snmpwalk(args);
+ }
+ else
+ {
+ System.out.println("Arg1: "+ args[1]);
+ System.out.println("Arg2: "+ args[2]);
+ System.out.println("*Usage*\n" +
+ "<get/getnext> <oid>\n" +
+ "<set> <oid> <value>\n" +
+ "<getbulk> (test snmpReceivedGetBulk)\n" +
+ "<testnullpdu> (test sending a null pdu)\n" +
+ "<snmpwalk> <oid> (walk the tree from the given oid.");
+
+ //improper action
+ }
+}
+ public static void snmpwalk(String [] args){
+ PDU pdu = new PDU();
+ Vector<PDU> pduResp = new Vector<PDU>();
+
+
+ CommunityTarget target = new CommunityTarget();
+ OctetString community = new OctetString("public");
+ target.setCommunity(community);
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(0);
+ target.setTimeout(2000);
+
+ pdu.setType(PDU.GETNEXT);
+
+ // initiate parallell walk.
+ for (int i = 1; i < args.length; i++){ //walk each OID.
+ OID treeOID = new OID (args[i]);
+ OID currentOID = new OID(treeOID);
+
+ // construct the PDU with all values required
+ while (currentOID.leftMostCompare(treeOID.getValue().length, treeOID)==0){
+ pdu.add(new VariableBinding(currentOID));
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ Snmp snmp = new Snmp(transport);
+
+ System.out.println("Sending PDU: "+pdu);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null){
+ System.out.println("Request timed out");
+ }
+ else{
+ if (responsePDU.getErrorStatus()!= 0){
+ System.out.println("Received error response: " + responsePDU);
+ pdu.clear();
+ return;
+ }
+ pduResp.add(new PDU(responsePDU));
+ // System.out.println("Received response "+responsePDU);
+ }
+ Vector<VariableBinding> vbs = responsePDU.getVariableBindings();
+ currentOID = vbs.get(0).getOid();
+ responsePDU = null;
+ pdu.clear();
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+
+ System.out.println("Some Other exception!!");
+ System.out.println(e);
+ }
+
+
+ }
+ }
+ for (PDU response : pduResp){
+ System.out.println("Results of snmpwalk: " + response);
+ }
+
+
+
+ }
+
+
+
+ public static void getbulk(){
+ PDU pdu = new PDU();
+ pdu.setType(PDU.GETBULK);
+ pdu.add(new VariableBinding(new OID("1.2.3.4.1.1")));
+ pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.0")));
+ pdu.add(new VariableBinding(new OID("1.3.1.1")));
+ pdu.setMaxRepetitions(7);
+ pdu.setNonRepeaters(1);
+ CommunityTarget target = new CommunityTarget();
+ OctetString community = new OctetString("public");
+ target.setCommunity(community);
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(0);
+ target.setTimeout(2000);
+
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+ long t1 = System.currentTimeMillis();
+ System.out.println("SENDING: "+t1);
+ System.out.println("PDU: "+pdu);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ long t2=System.currentTimeMillis();
+ System.out.println("SENT: "+t2);
+ System.out.println("ELAPSED: "+(t2-t1));
+ System.out.println("response " + responseEvent.toString());
+
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null){
+ System.out.println("Request timed out");
+ }
+ else{
+ System.out.println("Received response "+responsePDU);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!");
+ }
+
+
+ }
+
+
+
+ public static void getnext(String [] oids){
+ PDU pdu = new PDU();
+ pdu.setType(PDU.GETNEXT);
+ for (int i =1; i < oids.length; i++){
+ pdu.add(new VariableBinding(new OID(oids[i])));
+ }
+
+ CommunityTarget target = new CommunityTarget();
+ OctetString community = new OctetString("public");
+ target.setCommunity(community);
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(2000);
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+ long t1 = System.currentTimeMillis();
+ System.out.println("SENDING: "+t1);
+ System.out.println("PDU: "+pdu);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ long t2=System.currentTimeMillis();
+ System.out.println("SENT: "+t2);
+ System.out.println("ELAPSED: "+(t2-t1));
+ System.out.println("response " + responseEvent.toString());
+
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null){
+ System.out.println("Request timed out");
+ }
+ else{
+ System.out.println("Received response "+responsePDU);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!");
+ }
+ }
+
+ public static void testnull(){
+ PDU pdu = null;
+
+ CommunityTarget target = new CommunityTarget();
+ OctetString community = new OctetString("public");
+ target.setCommunity(community);
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(2000);
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+ //snmp.listen();
+ long t1 = System.currentTimeMillis();
+ System.out.println("SENDING: "+t1);
+ System.out.println("PDU: "+pdu);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ long t2=System.currentTimeMillis();
+ System.out.println("SENT: "+t2);
+ System.out.println("ELAPSED: "+(t2-t1));
+ System.out.println("response " + responseEvent.toString());
+
+ // extract the response PDU (could be null if timed out)
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null) {
+ System.out.println("Request timed out");
+ }
+ else {
+ // System.out.println("Received response "+response);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ System.out.println("responsePdu = " + responsePDU);
+
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!");
+ System.out.println(e);
+ }
+
+ }
+
+
+ /**
+ * Sends a test GET request
+ *
+ * @jmx:managed-operation
+ */
+
+ public static void get(String [] oids){
+ PDU pdu = new ScopedPDU();
+ pdu.setType(PDU.GET);
+ for (int i =1; i < oids.length; i++){
+ pdu.add(new VariableBinding(new OID(oids[i])));
+ }
+
+ UserTarget target = new UserTarget();
+ target.setVersion(SnmpConstants.version3);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(2000);
+ target.setSecurityLevel(SecurityLevel.AUTH_PRIV);
+ target.setSecurityName(new OctetString("MD5DES"));
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+
+ transport.listen();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+
+ //snmp.listen();
+ long t1 = System.currentTimeMillis();
+ System.out.println("SENDING: "+t1);
+ System.out.println("PDU: "+pdu);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ long t2=System.currentTimeMillis();
+ System.out.println("SENT: "+t2);
+ System.out.println("ELAPSED: "+(t2-t1));
+ System.out.println("response " + responseEvent.toString());
+
+ // extract the response PDU (could be null if timed out)
+ PDU responsePDU = responseEvent.getResponse();
+ if (responsePDU == null) {
+ System.out.println("Request timed out");
+ }
+ else {
+ // System.out.println("Received response "+response);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ System.out.println("responsePdu = " + responsePDU);
+
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!" + e);
+ }
+
+ }
+
+ public static void set(String []oids){
+ PDU pdu = new PDU();
+ for (int i = 1; i < oids.length; i+=2){
+ pdu.add(new VariableBinding(new OID(oids[i]), new OctetString(oids[i+1])));
+ }
+ // OID oidn = new OID(oid);
+ // Variable var = new OctetString(value);
+ // VariableBinding varBind = new VariableBinding(oidn, var);
+ // pdu.add(varBind);
+ pdu.setType(PDU.SET);
+
+ CommunityTarget target = new CommunityTarget();
+ target.setCommunity(new OctetString("private"));
+ target.setVersion(SnmpConstants.version2c);
+ Address targetAddress = GenericAddress.parse("udp:127.0.0.1/1161");
+ target.setAddress(targetAddress);
+ target.setRetries(2);
+ target.setTimeout(1000);
+ try{
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ Snmp snmp = new Snmp(transport);
+ long t1 = System.currentTimeMillis();
+ System.out.println("SENDING: "+t1);
+ System.out.println("PDU: " + pdu);
+ ResponseEvent responseEvent = snmp.set(pdu, target);
+ long t2=System.currentTimeMillis();
+ System.out.println("SENT: "+t2);
+ System.out.println("ELAPSED: "+(t2-t1));
+ System.out.println("response " + responseEvent.toString());
+
+ PDU responsePDU = responseEvent.getResponse();
+
+ if (responsePDU == null){
+ System.out.println("Response is null. Check RequestHandlerImpl");
+ System.out.println("Request timed out.");
+ }
+ else {
+ System.out.println("Received response "+responsePDU);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+
+
+ } catch (UnknownHostException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!");
+ }
+
+ }
+
+}
Modified: branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java
===================================================================
--- branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java 2011-01-26 17:03:05 UTC (rev 110454)
+++ branches/snmp4j-int/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java 2011-01-26 17:24:12 UTC (rev 110455)
@@ -21,11 +21,39 @@
import java.net.InetAddress;
import java.net.UnknownHostException;
+import java.util.Iterator;
+import java.util.Vector;
import org.jboss.bootstrap.api.as.config.JBossASServerConfig;
import org.jboss.system.ServiceMBeanSupport;
-import org.opennms.protocols.snmp.SnmpTrapSession;
+//import org.opennms.protocols.snmp.SnmpPduRequest;
+//import org.opennms.protocols.snmp.SnmpTrapSession;
+//import org.opennms.protocols.snmp.SnmpVarBind;
+
+import org.snmp4j.CommandResponder;
+import org.snmp4j.CommandResponderEvent;
+import org.snmp4j.MessageDispatcher;
+import org.snmp4j.MessageDispatcherImpl;
+import org.snmp4j.PDU;
+import org.snmp4j.PDUv1;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.TransportMapping;
+import org.snmp4j.mp.MPv1;
+import org.snmp4j.mp.MPv2c;
+import org.snmp4j.mp.MPv3;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.security.SecurityModels;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.USM;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.TcpAddress;
+import org.snmp4j.smi.UdpAddress;
+import org.snmp4j.smi.VariableBinding;
+import org.snmp4j.transport.DefaultTcpTransportMapping;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
+
/**
* MBean wrapper class that acts as an SNMP trap receiver/logger.
* It logs traps as INFO messages - change log4j configuration to
@@ -42,7 +70,7 @@
**/
public class TrapdService
extends ServiceMBeanSupport
- implements TrapdServiceMBean
+ implements TrapdServiceMBean, CommandResponder
{
/** The listening port */
private int port;
@@ -51,7 +79,7 @@
private InetAddress bindAddress;
/** The snmp session used to receive the traps*/
- protected SnmpTrapSession trapSession;
+ protected Snmp snmp;
/**
* Empty CTOR
@@ -123,19 +151,34 @@
{
// Create the SNMP trap receiving session with the logging handler,
// using Logger inherited from ServiceMBeanSupport
- try {
+
// cater for possible global -b option, if no override has been specified
InetAddress address = this.bindAddress != null ? this.bindAddress :
toInetAddress(System.getProperty(JBossASServerConfig.PROP_KEY_JBOSSAS_BIND_ADDRESS));
- this.trapSession =
- new SnmpTrapSession(new TrapReceiver(this.log), this.port, address);
- }
- catch (Exception e) {
- log.error("Cannot instantiate trap session");
-
- throw e; // ServiceMBeanSupport will log this
- }
+ MessageDispatcher mtDispatcher = new MessageDispatcherImpl();
+//
+// // add message processing models
+ mtDispatcher.addMessageProcessingModel(new MPv1());
+ mtDispatcher.addMessageProcessingModel(new MPv2c());
+ mtDispatcher.addMessageProcessingModel(new MPv3());
+ TransportMapping transport =
+ new DefaultUdpTransportMapping(new UdpAddress(address,port));
+
+ this.snmp = new Snmp(mtDispatcher,transport);
+
+ //start test
+// OctetString localEngineID =
+// new OctetString(snmp.getLocalEngineID());
+// USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0);
+// SecurityModels.getInstance().addSecurityModel(usm);
+ //end test
+
+// this.snmp = new Snmp(mtDispatcher, transport);
+
+ snmp.addCommandResponder(this);
+ snmp.listen();
+ log.debug("listening on: "+address);
}
/**
@@ -144,8 +187,7 @@
protected void stopService()
throws Exception
{
- this.trapSession.close();
- this.trapSession = null; // gc
+ snmp.close();
}
/**
@@ -159,5 +201,100 @@
else
return InetAddress.getByName(host);
}
+
+ @Override
+ public void processPdu(CommandResponderEvent e) {
+ PDU pdu = e.getPDU();
+ if (pdu != null){
+
+ if (pdu instanceof PDUv1){
+ processPDUv1((PDUv1)pdu);
+ }
+ else if (pdu instanceof ScopedPDU) {
+ processScopedPDU((ScopedPDU)pdu);
+ }
+ else if (pdu instanceof PDU){
+ processPDUv2c(pdu);
+ }
+ else {
+ log.warn("Unknown PDU type: " + PDU.getTypeString(pdu.getType()));
+ }
+
+ }
+ }
+
+ private void processPDUv2c(PDU pdu){
+ StringBuffer sbuf = new StringBuffer();
+ sbuf.append("\nV2 Trap from agent ").append(this.bindAddress.toString());
+ sbuf.append(" on port ").append(this.port);
+ sbuf.append("\n");
+
+ Vector bindings = pdu.getVariableBindings();
+ Iterator it = bindings.iterator();
+ int counter = 0;
+ while (it.hasNext())
+ {
+ VariableBinding vb = (VariableBinding)it.next();
+ if (vb != null) {
+ sbuf.append("Varbind[").append(counter++).append("] := ");
+ sbuf.append(vb.getOid().toString()).append(" --> ");
+ sbuf.append(vb.getVariable().toString()).append("\n");
+ }
+ }
+ sbuf.append("\nLength............. ").append(counter);
+ log.debug(sbuf.toString());
+ }
+
+ private void processScopedPDU(ScopedPDU pdu) {
+ //****
+ StringBuffer sbuf = new StringBuffer();
+ sbuf.append("\nV3 Trap from agent ").append(this.bindAddress.toString());
+ sbuf.append(" on port ").append(this.port);
+ sbuf.append("\n");
+
+ Vector bindings = pdu.getVariableBindings();
+ Iterator it = bindings.iterator();
+ int counter = 0;
+ while (it.hasNext())
+ {
+ VariableBinding vb = (VariableBinding)it.next();
+ if (vb != null) {
+ sbuf.append("Varbind[").append(counter++).append("] := ");
+ sbuf.append(vb.getOid().toString()).append(" --> ");
+ sbuf.append(vb.getVariable().toString()).append("\n");
+ }
+ }
+ sbuf.append("\nLength............. ").append(counter);
+ log.debug(sbuf.toString());
+
+ }
+
+ private void processPDUv1(PDUv1 pdu) {
+ StringBuffer sbuf = new StringBuffer();
+ sbuf.append("\nV1 Trap from agent ").append(this.bindAddress.toString());
+ sbuf.append(" on port ").append(this.port);
+ sbuf.append("\nIP Address......... ").append(pdu.getAgentAddress().toString());
+ sbuf.append("\nEnterprise Id...... ").append(pdu.getEnterprise());
+ sbuf.append("\nGeneric ........... ").append(pdu.getGenericTrap());
+ sbuf.append("\nSpecific .......... ").append(pdu.getSpecificTrap());
+ sbuf.append("\nTimeStamp ......... ").append(pdu.getTimestamp());
+
+ sbuf.append("\n");
+
+ Vector bindings = pdu.getVariableBindings();
+ Iterator it = bindings.iterator();
+ int counter = 0;
+ while (it.hasNext())
+ {
+ VariableBinding vb = (VariableBinding)it.next();
+ if (vb != null) {
+ sbuf.append("Varbind[").append(counter++).append("] := ");
+ sbuf.append(vb.getOid().toString()).append(" --> ");
+ sbuf.append(vb.getVariable().toString()).append("\n");
+ }
+ }
+ sbuf.append("\nLength............. ").append(counter);
+ log.debug(sbuf.toString());
+ }
} // class TrapdService
More information about the jboss-cvs-commits
mailing list