[jboss-cvs] JBossAS SVN: r112094 - in trunk: component-matrix and 13 other directories.
jboss-cvs-commits at lists.jboss.org
jboss-cvs-commits at lists.jboss.org
Thu Aug 18 16:45:21 EDT 2011
Author: thauser at redhat.com
Date: 2011-08-18 16:45:19 -0400 (Thu, 18 Aug 2011)
New Revision: 112094
Removed:
trunk/testsuite/src/main/org/jboss/test/snmp/ComparableSnmpOidTestCase.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ComparableSnmpObjectId.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ManagerRecord.java
Modified:
trunk/build/build.xml
trunk/component-matrix/pom.xml
trunk/varia/pom.xml
trunk/varia/src/main/java/org/jboss/jmx/adaptor/control/AttrResultInfo.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapper.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapperSupport.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/AttributeMappings.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/ManagedBean.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/Mapping.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBind.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBindList.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java
trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java
trunk/varia/src/resources/services/snmp/config/Manager.xsd
trunk/varia/src/resources/services/snmp/config/Notification.xsd
trunk/varia/src/resources/services/snmp/deploy/META-INF/jboss-service.xml
trunk/varia/src/resources/services/snmp/deploy/attributes.mib
trunk/varia/src/resources/services/snmp/deploy/attributes.xml
trunk/varia/src/resources/services/snmp/deploy/managers.xml
trunk/varia/src/resources/services/snmp/deploy/notifications.xml
Log:
Rewrite of snmp-adaptor to use a new stack, snmp4j, as well as include support for
v2c, v3 of the protocol, GETBULK operations, and tabular objects, and MIB generation.
Modified: trunk/build/build.xml
===================================================================
--- trunk/build/build.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/build/build.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -2194,7 +2194,7 @@
<fileset refid="org.jboss.scanning:scanning-deployers:jar"/>
<fileset refid="org.jboss.mc-int:jboss-mc-int-servlet:jar"/>
<fileset refid="org.beanshell:bsh:jar"/>
- <fileset refid="joesnmp:joesnmp:jar"/>
+ <fileset refid="org.snmp4j:snmp4j:jar"/>
<fileset refid="wutka-dtdparser:dtdparser:jar"/>
<fileset refid="apache-bsf:bsf:jar"/>
<fileset refid="org.jboss.spec.javax.el:jboss-el-api_2.2_spec:jar"/>
Modified: trunk/component-matrix/pom.xml
===================================================================
--- trunk/component-matrix/pom.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/component-matrix/pom.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -145,6 +145,7 @@
<version.org.jboss.xnio>2.1.0.CR2</version.org.jboss.xnio>
<version.org.jboss.xnio.metadata>2.1.0.CR5</version.org.jboss.xnio.metadata>
<version.org.jgroups>2.11.0.GA</version.org.jgroups>
+ <version.org.snmp4j>1.11.3</version.org.snmp4j>
<version.org.slf4j>1.5.6</version.org.slf4j>
<version.org.slf4j.jboss.logmanager>1.0.0.GA</version.org.slf4j.jboss.logmanager>
<version.ch.qos.cal10n>0.7.2</version.ch.qos.cal10n>
@@ -1633,9 +1634,9 @@
</dependency>
<dependency>
- <groupId>joesnmp</groupId>
- <artifactId>joesnmp</artifactId>
- <version>0.3.4</version>
+ <groupId>org.snmp4j</groupId>
+ <artifactId>snmp4j</artifactId>
+ <version>${version.org.snmp4j}</version>
</dependency>
<dependency>
Deleted: trunk/testsuite/src/main/org/jboss/test/snmp/ComparableSnmpOidTestCase.java
===================================================================
--- trunk/testsuite/src/main/org/jboss/test/snmp/ComparableSnmpOidTestCase.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/testsuite/src/main/org/jboss/test/snmp/ComparableSnmpOidTestCase.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -1,189 +0,0 @@
-/*
- * 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.test.snmp;
-
-import java.util.SortedSet;
-import java.util.TreeSet;
-
-import org.jboss.jmx.adaptor.snmp.agent.ComparableSnmpObjectId;
-
-import junit.framework.TestCase;
-
-/**
- * Tests for the ComparableSnmpObjectId, a Subclass of SnmpObjectId from
- * the joesnmp package. Most tests are trivial.
- * @author <a href="mailto:hwr at pilhuhn.de">Heiko W. Rupp</a>
- * @version $Revision$
- */
-public class ComparableSnmpOidTestCase extends TestCase
-{
-
- /**
- * Make sure, that the passed oid which does not end in .0
- * is not detected as leaf.
- */
- public void testIsNotLeaf()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(".1.2.3.4");
- boolean res = coid.isLeaf();
- assertFalse(res);
- }
-
- /**
- * Make sure that the passed oid ending in .0 is detected as leaf.
- */
- public void testIsLeaf()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(".1.2.3.4.0");
- boolean res = coid.isLeaf();
- assertTrue(res);
- }
-
- /**
- * Make sure that the passed oid ending in .0 is detected as leaf.
- */
- public void testIsLeaf2()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.0");
- boolean res = coid.isLeaf();
- assertTrue(res);
- }
-
-
- /**
- * See if the last part of an oid is correctly chopped of.
- *
- */
- public void testRemoveLastPart()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.0");
- ComparableSnmpObjectId res = coid.removeLastPart();
- assertEquals(".1.2.3.4",res.toString());
- }
-
- /**
- * See if compareTo from Comparable works as expected.
- * This is needed for use of the ComparableSnmpObjectId in SortedSets etc.
- * @see java.lang.Comparable
- */
- public void testCompareTo1()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.0");
- ComparableSnmpObjectId coid2 = new ComparableSnmpObjectId(".1.2.3.4.0");
- int res = coid.compareTo(coid2);
- assertEquals(0,res);
- }
-
- /**
- * See if compareTo from Comparable works as expected.
- * This is needed for use of the ComparableSnmpObjectId in SortedSets etc.
- * @see java.lang.Comparable
- */
- public void testCompareTo2()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4");
- ComparableSnmpObjectId coid2 = new ComparableSnmpObjectId("1.2.3.4.0");
- int res = coid.compareTo(coid2);
- assertTrue(res!=0);
- }
-
- /**
- * See if compareTo from Comparable works as expected.
- * This is needed for use of the ComparableSnmpObjectId in SortedSets etc.
- * @see java.lang.Comparable
- */
- public void testCompareTo3()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.1");
- ComparableSnmpObjectId coid2 = new ComparableSnmpObjectId("1.2.3.4.2");
- int res = coid.compareTo(coid2);
- assertTrue(res<0);
- }
-
- /**
- * See if compareTo from Comparable works as expected.
- * This is needed for use of the ComparableSnmpObjectId in SortedSets etc.
- * @see java.lang.Comparable
- */
- public void testCompareTo4()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.2");
- ComparableSnmpObjectId coid2 = new ComparableSnmpObjectId("1.2.3.4.1");
- int res = coid.compareTo(coid2);
- assertTrue(res>0);
- }
-
- /**
- * See if compareTo from Comparable works as expected.
- * This is needed for use of the ComparableSnmpObjectId in SortedSets etc.
- * @see java.lang.Comparable
- */
- public void testCompareTo5()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.2");
- Object coid2 = new Object();
- int res = coid.compareTo(coid2);
- assertTrue(res == -1);
- }
-
-
- public void testGetNextArc()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4");
- ComparableSnmpObjectId res = coid.getNextArc();
- assertEquals(".1.2.4",res.toString());
- }
-
- public void testGetNextArc2()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(".1.2.3.4.5");
- ComparableSnmpObjectId res = coid.getNextArc();
- assertEquals(".1.2.3.5",res.toString());
- }
-
- public void testGetNextArc3()
- {
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId(".1.2.3.4.0");
- ComparableSnmpObjectId res = coid.getNextArc();
- assertEquals(".1.2.4",res.toString());
- }
-
-
- public void testGetSubtree()
- {
- SortedSet s = new TreeSet();
- ComparableSnmpObjectId coid = new ComparableSnmpObjectId("1.2.3.4.0");
- s.add(coid);
- coid = new ComparableSnmpObjectId("1.2.3.5.0");
- s.add(coid);
- coid = new ComparableSnmpObjectId("1.2.3.6.0");
- s.add(coid);
-
- ComparableSnmpObjectId c2 = new ComparableSnmpObjectId("1.2.3.4.1");
- SortedSet subset = s.tailSet(c2);
- assertEquals(2,subset.size());
-
- subset = s.headSet(c2);
- assertEquals(1,subset.size());
- }
-
-}
\ No newline at end of file
Modified: trunk/varia/pom.xml
===================================================================
--- trunk/varia/pom.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/pom.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -87,6 +87,23 @@
</descriptors>
</configuration>
</execution>
+ <execution>
+ <id>MIBGenerator</id>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <phase>package</phase>
+ <configuration>
+ <descriptors>
+ <descriptor>src/assembly/mib-generator.xml</descriptor>
+ </descriptors>
+ <archive>
+ <manifest>
+ <mainClass>org.jboss.jmx.adaptor.snmp.generator.MIBGenerator</mainClass>
+ </manifest>
+ </archive>
+ </configuration>
+ </execution>
</executions>
</plugin>
<plugin>
@@ -176,6 +193,25 @@
</execution>
</executions>
</plugin>
+ <plugin>
+ <groupId>org.jboss</groupId>
+ <artifactId>mibgen-maven-plugin</artifactId>
+ <version>1.0-SNAPSHOT</version>
+ <configuration>
+ <attributesFile>${project.basedir}/src/resources/services/snmp/deploy/attributes.xml</attributesFile>
+ <notificationsFile>${project.basedir}/src/resources/services/snmp/deploy/notifications.xml</notificationsFile>
+ <moduleName>JBOSS-AS-DEFAULT</moduleName>
+ <outputFile>${project.build.directory}/resources/services/snmp/deploy/attributes.mib</outputFile>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>compile</phase>
+ <goals>
+ <goal>generate-mib</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
</plugins>
</build>
@@ -236,10 +272,10 @@
<groupId>apache-velocity</groupId>
<artifactId>velocity</artifactId>
</dependency>
-
+
<dependency>
- <groupId>joesnmp</groupId>
- <artifactId>joesnmp</artifactId>
+ <groupId>org.snmp4j</groupId>
+ <artifactId>snmp4j</artifactId>
</dependency>
<dependency>
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/control/AttrResultInfo.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/control/AttrResultInfo.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/control/AttrResultInfo.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -22,6 +22,7 @@
package org.jboss.jmx.adaptor.control;
import java.beans.PropertyEditor;
+import org.snmp4j.smi.TimeTicks;
/** A simple tuple of an mbean operation name, sigature and result.
@@ -60,6 +61,9 @@
}
else
{
+ if(result instanceof TimeTicks){
+ return ((TimeTicks)result).toString("{0} d {1} h {2} m {3} s {4} hs");
+ }
return result.toString();
}
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/AttributeMappingsBinding.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -93,10 +93,11 @@
String oid = attrs.getValue("oid");
String name = attrs.getValue("name");
String mode = attrs.getValue("mode");
- attribute = new MappedAttribute();
- if ("rw".equalsIgnoreCase(mode))
- attribute.setReadWrite(true);
+ String table = attrs.getValue("table");
+ attribute = new MappedAttribute();
+ attribute.setMode(mode);
attribute.setName(name);
+ attribute.setTable(table);
attribute.setOid(oid);
}
return attribute;
Deleted: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ComparableSnmpObjectId.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ComparableSnmpObjectId.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ComparableSnmpObjectId.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -1,139 +0,0 @@
-/*
- * 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.agent;
-
-import org.opennms.protocols.snmp.SnmpObjectId;
-
-/**
- * Provide SnmpObjectIds that are Comparable to be used
- * in SortedSets etc.
- * @author <a href="mailto:hwr at pilhuhn.de">Heiko W. Rupp</a>
- * @version $Revision$
- */
-public class ComparableSnmpObjectId extends SnmpObjectId implements Comparable
-{
-
- public ComparableSnmpObjectId(String oid)
- {
- super(oid);
- }
-
- public ComparableSnmpObjectId(SnmpObjectId oid)
- {
- super(oid);
- }
-
- public ComparableSnmpObjectId(int[] identifiers)
- {
- super(identifiers);
- }
-
- /**
- * Compare to the passed object. Uses compare()
- * from the underlying snmp-library
- * @see SnmpObjectId.compare()
- * @param o Object to compare with (Usually a ComparableSnmpObjectId)
- * @return -1, if no SnmpObjectId passed in, the result of the underlying compare otherwise.
- */
- public int compareTo(Object o)
- {
-
- if (o==null)
- return -1;
-
- if (!(o instanceof SnmpObjectId))
- return -1;
-
- return this.compare((SnmpObjectId)o);
- }
-
- /**
- * This object is a leaf if the last part of the oid parts is a 0 (Zero)
- * @return true if the oid ends in 0
- */
- public boolean isLeaf()
- {
- int[] ids = getIdentifiers();
- if (ids.length==0) { // no data present (should not happen)
- return false;
- }
- if (ids[ids.length-1]==0)
- {
- return true;
- }
- return false;
- }
-
- /**
- * Removes the last oid-component.
- * Example .1.2.3.4.0 as input yields .1.2.3.4 as output
- * @return an oid with the last part removed.
- */
- public ComparableSnmpObjectId removeLastPart()
- {
- int[] ids = getIdentifiers();
-
- int[] outs = new int[ids.length-1];
- int len = ids.length-1;
- for (int i = 0; i<len ; i++)
- {
- outs[i]=ids[i];
- }
- ComparableSnmpObjectId out = new ComparableSnmpObjectId(outs);
- return out;
- }
-
- /**
- * Build an oid where the second last component
- * (after removing a .0 of a leaf) is increased by 1.
- * The last component is removed, to the result actually forms
- * the root of a subtree, that is adjacent to the subtree this
- * object is in.
- * Example .1.2.3.4.0 -> .1.2.4
- * Example .1.2.3.4.5 -> .1.2.4
- * @return
- */
- public ComparableSnmpObjectId getNextArc()
- {
- ComparableSnmpObjectId cid = this;
- if (isLeaf())
- {
- cid = removeLastPart();
- }
- cid = cid.removeLastPart();
-
- int[] ids = cid.getIdentifiers();
- int[] ods = new int[ids.length];
- System.arraycopy(ids,
- 0,
- ods,
- 0,
- ids.length);
-
- int len = ods.length-1;
- ods[len]++;
-
- ComparableSnmpObjectId ret = new ComparableSnmpObjectId(ods);
- return ret;
- }
-
-}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/EventTypes.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -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";
+
}
Deleted: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ManagerRecord.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ManagerRecord.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ManagerRecord.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -1,242 +0,0 @@
-/*
- * Copyright (c) 2003, Intracom S.A. - www.intracom.com
- *
- * This library 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 of the License, or (at your option) any later version
- *
- * This library 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 library; if not, write to the Free Software
- * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
- *
- * This package and its source code is available at www.jboss.org
-**/
-package org.jboss.jmx.adaptor.snmp.agent;
-
-import java.net.InetAddress;
-import java.net.SocketException;
-
-import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpHandler;
-import org.opennms.protocols.snmp.SnmpParameters;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPeer;
-import org.opennms.protocols.snmp.SnmpSMI;
-import org.opennms.protocols.snmp.SnmpSession;
-import org.opennms.protocols.snmp.SnmpSyntax;
-
-/**
- * <tt>ManagerRecord</tt> is a class that is used as a key
- * to uniquely identify subscribing managers.
- *
- * @version $Revision$
- *
- * @author <a href="mailto:spol at intracom.gr">Spyros Pollatos</a>
- * @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
-**/
-class ManagerRecord implements SnmpHandler
-{
- /** The logger object */
- private static final Logger log = Logger.getLogger(ManagerRecord.class);
-
- /** SNMP parameter for number of retries */
- private int retries = 10;
-
- /** SNMP parameter for timeout */
- private int timeout = 5000;
-
- /** Subscription target IP address */
- private InetAddress address;
-
- /** Subscription target port */
- private int port;
-
- /** The local address to bind */
- private InetAddress localAddress;
-
- /** The local port to use */
- private int localPort;
-
- /** Subscription native SNMP version */
- private int version;
-
- /** The read community string*/
- private final String readCommunity = "public";
-
- /** The session to the manager*/
- private transient SnmpSession session;
-
- /**
- * Creates key for the specified values. <P>
- *
- * @param address the manager's IP adddress
- * @param port the manager listening port
- * @param localAddress the local address to bind
- * @param localPort the local port to bind
- * @param version the session's native SNMP version
- **/
- public ManagerRecord(InetAddress address, int port,
- InetAddress localAddress, int localPort, int version)
- throws BadSnmpVersionException
- {
- this.address = address;
- this.port = port;
- this.localAddress = localAddress;
- this.localPort = localPort;
-
- switch (version) {
- case SnmpAgentService.SNMPV1:
- case SnmpAgentService.SNMPV2:
- this.version = version;
- break;
-
- default:
- throw new BadSnmpVersionException("Bad SNMP Version: " + version);
- }
- }
-
- /**
- *
- **/
- public InetAddress getAddress()
- {
- return this.address;
- }
-
- /**
- *
- **/
- public int getPort()
- {
- return this.port;
- }
-
- /**
- *
- */
- public InetAddress getLocalAddress()
- {
- return this.localAddress;
- }
-
- /**
- *
- **/
- public int getLocalPort()
- {
- return this.localPort;
- }
-
- /**
- *
- **/
- public int getVersion()
- {
- return this.version;
- }
-
- public void openSession()
- throws SocketException
- {
- // Create the SNMP session to the manager
- SnmpPeer peer = new SnmpPeer(this.address, this.port, this.localAddress, this.localPort);
- peer.setRetries(this.retries);
- peer.setTimeout(this.timeout);
-
- SnmpParameters parameters = peer.getParameters();
-
- switch(this.version) {
- case SnmpAgentService.SNMPV1:
- parameters.setVersion(SnmpSMI.SNMPV1);
- break;
-
- case SnmpAgentService.SNMPV2:
- parameters.setVersion(SnmpSMI.SNMPV2);
- break;
- default:
- parameters.setVersion(SnmpSMI.SNMPV1);
- }
-
- parameters.setReadCommunity(this.readCommunity);
- peer.setParameters(parameters);
-
- this.session = new SnmpSession(peer);
- this.session.setDefaultHandler(this);
- }
-
- /**
- * Close the session to the manager
- **/
- public void closeSession()
- {
- this.session.close();
- }
-
- /**
- * Returns the session to the manager
- **/
- public SnmpSession getSession()
- {
- return this.session;
- }
-
- /**
- * Comparison operator. Keys are considered equal if all address, port
- * and version are identical
- *
- * @param o the key to be compared with
- **/
- public boolean equals(Object o)
- {
- if (!(o instanceof ManagerRecord))
- return false;
-
- ManagerRecord other = (ManagerRecord)o;
-
- return (this.port == other.port &&
- this.address.equals(other.address) &&
- this.version == other.version);
- }
-
- /**
- * Hash generator
- **/
- public int hashCode()
- {
- return toString().hashCode();
- }
-
- /**
- *
- **/
- public String toString()
- {
- return new String(this.address + ":" + this.port +
- " (" + this.version + ")" );
- }
-
- /**
- * Stubs to be filled in if we are not only to send traps
- **/
- public void snmpInternalError(SnmpSession session, int err, SnmpSyntax pdu)
- {
- log.error("ManagerRecord::snmpInternalError, code: " + err);
- }
-
- public void snmpTimeoutError(SnmpSession session, SnmpSyntax pdu)
- {
- log.error("ManagerRecord::snmpTimeoutError");
- }
-
- public void snmpReceivedPdu(SnmpSession session, int cmd, SnmpPduPacket pdu)
- {
- log.error("ManagerRecord::snmpReceivedPdu");
- }
-
-} // class ManagerRecord
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapper.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapper.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapper.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -63,6 +63,9 @@
public static final String STARTTIME_TAG = "a:startTime";
public static final String UPTIME_TAG = "a:uptime";
public static final String TRAPCOUNT_TAG = "a:trapCount";
+
+ // user properties
+ public static final String USERDATA_TAG = "u:userData";
/**
* Sets the uptime clock and trap counter
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapperSupport.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapperSupport.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/NotificationWrapperSupport.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -38,7 +38,7 @@
implements NotificationWrapper
{
/** Holds the notification payload keyed on the attibute name */
- protected Map payload = new HashMap();
+ protected Map<String, Object> payload = new HashMap<String, Object>();
/** Provides uptime */
protected Clock clock;
@@ -70,7 +70,7 @@
new DynamicContentAccessor() {
public Object get()
{
- return new Long(NotificationWrapperSupport.this.clock.uptime());
+ return Long.valueOf(NotificationWrapperSupport.this.clock.uptime());
}
});
@@ -78,7 +78,7 @@
new DynamicContentAccessor() {
public Object get()
{
- return new Long(NotificationWrapperSupport.this.trapCount.peek());
+ return Long.valueOf(NotificationWrapperSupport.this.trapCount.peek());
}
});
}
@@ -106,9 +106,11 @@
// that previous content may be overwritten if the same keys as above
// are used
Object userData = n.getUserData();
- if (userData instanceof HashMap) {
+ if (userData instanceof Map) {
// Copy all of the user data in the payload
- this.payload.putAll((HashMap)userData);
+ this.payload.putAll((Map)userData);
+ } else {
+ this.payload.put(USERDATA_TAG, userData);
}
} // prime
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/ReadOnlyException.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -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: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandler.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,10 +21,14 @@
*/
package org.jboss.jmx.adaptor.snmp.agent;
+import java.util.List;
+
import javax.management.MBeanServer;
+import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpAgentHandler;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.Variable;
/**
* Interface that must be implemented by classes
@@ -33,7 +37,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
@@ -45,7 +49,10 @@
* @param uptime the snmp agent uptime
* @throws Exception in case of initialization problem
*/
- public void initialize(String resourceName, MBeanServer server, Logger loggger, Clock uptime)
+ void initialize(String resourceName, MBeanServer server, Logger loggger, Clock uptime)
throws Exception;
+ void addAttributeMappings(List<ManagedBean> mappings);
+ void removeAttributeMappings(List<ManagedBean> mappings);
+ Variable getValueFor(OID oid) throws NoSuchInstanceException, VariableTypeException;
} // RequestHandler
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerImpl.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -23,12 +23,18 @@
import java.io.InputStream;
import java.net.InetAddress;
+import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
+import java.util.Vector;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
import javax.management.Attribute;
import javax.management.MBeanServer;
@@ -41,30 +47,50 @@
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.snmp4j.PDU;
+import org.snmp4j.PDUv1;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.Snmp;
+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;
/**
* Implement RequestHandler with mapping of snmp get/set requests
- * to JMX mbean attribute gets/sets
+ * to JMX mbean attribute gets/sets. Supports up to v3 of the SNMP spec.
*
* @author <a href="mailto:hwr at pilhuhn.de>">Heiko W. Rupp</a>
* @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
+ * @author <a href="mailto:thauser at redhat.com"> or <a href="mailto:tom.hauser at gmail.com">Thomas Hauser</a>
* @version $Revision$
*/
public class RequestHandlerImpl extends RequestHandlerSupport
implements Reconfigurable
{
+ public static final String NO_ENTRY_FOUND_FOR_OID = "No bind entry found for oid ";
+ public static final String SKIP_ENTRY = " - skipping entry";
+
// Protected Data ------------------------------------------------
-
- private static final String NO_ENTRY_FOUND_FOR_OID = "No entry found for oid ";
- private static final String SKIP_ENTRY = " - skipping entry";
-
-
/** Bindings from oid to mbean */
- protected SortedMap bindings = new TreeMap();
-
- private SortedSet oidKeys = null;
-
+ protected SortedMap<OID, BindEntry> bindings = new TreeMap<OID, BindEntry>();
+
+ /** keep track of the instances of variables */
+ private SortedSet<OID> oidKeys = null;
+
+ /** keep track of the objects created */
+// private SortedSet<OID> objectKeys = null;
+
+ private TableMapper tableMapper = null;
+ private AttributeTableMapper attributeTableMapper = null;
+
/** Has this RequestHandler instance been initialized? */
private boolean initialized = false;
@@ -75,8 +101,9 @@
*/
public RequestHandlerImpl()
{
- bindings = new TreeMap();
- oidKeys = new TreeSet();
+ bindings = new TreeMap<OID, BindEntry>();
+ oidKeys = new TreeSet<OID>();
+// objectKeys = new TreeSet<OID>();
}
// RequestHandler Implementation ---------------------------------
@@ -94,6 +121,8 @@
{
log.debug("initialize() with res=" + resourceName);
super.initialize(resourceName, server, log, uptime);
+ tableMapper = new TableMapper(server, log);
+ attributeTableMapper = new AttributeTableMapper(server, log);
if (resourceName != null)
initializeBindings();
else
@@ -102,6 +131,7 @@
initialized = true;
}
+ //
// Reconfigurable Implementation ---------------------------------
/**
* Reconfigures the RequestHandler
@@ -125,166 +155,366 @@
// 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
+ * This method functions according to the protocol definition in RFC-3416
+ *
+ * </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.
+ *
+ */
+
+ public PDU snmpReceivedGetBulk(PDU pdu){
+ PDU response = getResponsePDU(pdu);
+ if(response == null) {
+ return response;
+ }
+
+ final boolean trace = log.isTraceEnabled();
+ if (trace) {
+ log.trace("requestID=" + pdu.getRequestID() + ", elementCount="
+ + pdu.size());
+ }
+
+ int errorIndex = 1;
+ int nonRepeaters = pdu.getNonRepeaters();
+ if (nonRepeaters<0)
+ nonRepeaters=0;
+
+ int maxRepetitions = pdu.getMaxRepetitions();
+ if (maxRepetitions<0)
+ maxRepetitions=0;
+ Vector<VariableBinding> vbList = pdu.getVariableBindings();
+ VariableBinding vb = null;
+ Variable var = null;
+
+ if (vbList.size() == 0){ // we were given an empty list in the PDU
+ log.debug("snmpReceivedGetBulk: No VariableBindings in received PDU");
+ makeErrorPdu(response, pdu, errorIndex, PDU.genErr);
+ return response;
+ }
+ for (int i=0; i < Math.min(nonRepeaters, vbList.size());i++){
+ vb = (VariableBinding)vbList.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){
+ // 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, errorIndex, PDU.genErr);
+ return response;
+ }
+ response.add(new VariableBinding(noid,var));
+ errorIndex++;
+ }
+
+ // for the remaining it.size() bindings, we perform maxRepetitions successive getNext calls
+ for (int i = nonRepeaters; i < vbList.size(); i++){
+ vb = (VariableBinding)vbList.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;
+ }
+
+ 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.noSuchInstance;
+ }
+ catch (VariableTypeException e) {
+ makeErrorPdu(response, pdu, errorIndex, PDU.genErr);
+ var = Null.instance;
+ }
+
+ response.add(new VariableBinding(noid,var));
+
+ try {
+ noid = getNextOid(noid);
+ }
+ catch (EndOfMibViewException e) {
+ // doing more repetitions here is a waste of time.
+ response.add(new VariableBinding(noid, Null.endOfMibView));
+ break;
+ }
+ }
+ errorIndex++;
+ }
+ return response;
+ }
+
+ /**
* <P>
- * This method is defined to handle SNMP Get requests that are received by
+ * This method is defined to handle SNMP GET and GETNEXT 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.
+ * The behaviour is defined in RFC-3416 for v2 protocols.
* </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)
- {
- 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();
- 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;
+ public PDU snmpReceivedGet (PDU pdu) {
+ PDU response;
+ // this counts the number of VariableBindings and indicates which one caused a problem, if any
+ int errorIndex = 1;
+ // flags the end of the MIB
+ boolean endOfMib = false;
+
+ response = getResponsePDU(pdu);
+ //indicate by copying the Req ID that this response is for the PDU sent with that ReqID.
+
+ final boolean trace = log.isTraceEnabled();
+
+ if (trace) {
+ log.trace("requestID=" + pdu.getRequestID() + ", elementCount="
+ + pdu.size());
+ }
+
+ 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 lexicographically next OID from the given one.
+ try{
+ noid = getNextOid(oid);
+ }
+ // if there are no lexicographically larger OIDs than this one
+ catch(EndOfMibViewException e){
+ log.debug("snmpReceivedGet: GETNEXT operation left the MIB View");
+ endOfMib=true;
+ }
+
+ if (endOfMib){
+ newVB = new VariableBinding(oid);
+ var = Null.endOfMibView;
+ }
+ else{
+ newVB = new VariableBinding(noid);
+ try {
+ var = getValueFor(noid);
+ } catch (NoSuchInstanceException e) {
+ log.debug("snmpReceivedGet: GETNEXT operation returned null. No such OID.");
+ var = Null.noSuchInstance;
+ } catch (VariableTypeException e) {
+ log.debug("snmpReceivedGet: GETNEXT operation could not convert the returned value for " + noid + " into an appropriate type.");
+ makeErrorPdu(response, pdu, errorIndex, PDU.genErr);
+ return response;
}
- else
- {
- pdu.setVarBindAt(i, new SnmpVarBind(oid));
+ }
+ }
+ else {
+ newVB = new VariableBinding(oid);
+ var = null;
+ tableMapper.checkTables(oid);
+ // check the existence of the object for the requested instance
+ // the object is the OID with the last number removed.
+ if (checkObject(oid)){
+ try {
+ var = getValueFor(oid);
+ } catch (NoSuchInstanceException e) {
+ log.debug("snmpReceivedGet: GET operation returned null. No such Instance.");
+ var = Null.noSuchInstance;
+ } catch (VariableTypeException e) {
+ log.debug("snmpReceivedGet: GET operation could not convert the returned value for " + oid + " into an appropriate type.");
+ makeErrorPdu(response, pdu, errorIndex, PDU.genErr);
+ return response;
+
}
+
}
- 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());
+ // if we get here, there's no such object.
+ else{
+ var = Null.noSuchObject;
}
- } // 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);
+ errorIndex++;
+ }
+ //TODO: check size constraints of the sender
+ return response;
}
/**
* <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.
+ * routine will build a response and pass it back to the caller.
+ * Upon any error, this method will rollback all sets that were made before the
+ * failure occured.
+ * The behaviour is defined in RFC-3416
* </P>
*
* @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 the same VB list as given and an error status indicating why the operation failed,
+ * and which VariableBinding caused the problem. Any changes that have completed before this problem occured
+ * will be undone, as per RFC-3416
*/
- public SnmpPduRequest snmpReceivedSet(SnmpPduPacket pdu)
+ public PDU snmpReceivedSet(PDU pdu)
{
+ PDU response = getResponsePDU(pdu);
+ // the modified OID entries so far.
+ HashSet<VariableBinding> modified = new HashSet<VariableBinding>();
+ int errorIndex = 1;
+ Variable var, oldVar = null; // oldVar variable for storing into modified
+
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());
+ }
+
+ //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);
+
+ try{
+ tableMapper.checkTables(oid);
+ oldVar = getValueFor(oid);
+ modified.add(new VariableBinding(oid, oldVar)); // keep a record of the old variable binding.
+ if (checkObject(oid)){
+ var = setValueFor(oid,newVal);
+ }
+ else{
+ log.error("snmpReceivedSet: no object for SET request");
+ undoSets(modified);
+ makeErrorPdu(response, pdu, errorIndex, PDU.noAccess);
+ return response;
+ }
}
- catch (ReadOnlyException e)
- {
- errorStatus = SnmpPduPacket.ErrReadOnly;
- errorIndex = i + 1;
+ catch (NoSuchInstanceException e){
+ log.info("snmpReceivedSet: attempt to set a non-existent instance: " + oid.last() + " of object: " + oid.trim(), e);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, errorIndex, PDU.noCreation);
+ return response;
}
-
- 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());
- }
+ catch (VariableTypeException e){
+ log.info("snmpReceievedSet: could not convert the given value into an appropriate type: " +newVal, e);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, errorIndex, PDU.wrongType);
+ return response;
+ }
+ catch (ReadOnlyException e){
+ log.info("snmpReceivedSet: attempt to set a read-only attribute: " + newVB, e);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, errorIndex, PDU.notWritable);
+ return response;
+ }
+ catch (Exception e){
+ log.error("snmpReceivedSet: catastrophe!!! General variable validation error.", e);
+ undoSets(modified);
+ makeErrorPdu(response, pdu, errorIndex, PDU.genErr);
+ return response;
+ }
+
+ // if we get here, we modified the value successfully.
+ response.add(newVB);
+ errorIndex++;
}
- response = new SnmpPduRequest(SnmpPduPacket.RESPONSE, vblist);
- response.setErrorStatus(errorStatus);
- response.setErrorIndex(errorIndex);
-
+ return response;
+ }
+
+ /**
+ * This method returns the correct response PDU from the given request PDU
+ * passed in parameters.
+ */
+ private PDU getResponsePDU(PDU pdu) {
+ PDU response;
+ if (pdu instanceof ScopedPDU){
+ /* ScopedPDUs are not fully supported. this check is here so that when
+ * SnmpAgentService is updated to support v3 correctly, we won't have to
+ * add it in.*/
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version3);
+ /* A.3.4. Applications that Send Responses
+ The contextEngineID, contextName, securityModel, securityName,
+ securityLevel, and stateReference parameters are from the initial
+ processPdu primitive. The PDU and statusInformation are the results
+ of processing.*/
+ ((ScopedPDU)response).setContextEngineID(((ScopedPDU) pdu).getContextEngineID());
+ ((ScopedPDU)response).setContextName(((ScopedPDU) pdu).getContextName());
+ } else if (pdu instanceof PDUv1){
+ if(pdu.getType() == PDU.GETBULK) {
+ log.debug("snmpReceievedGetBulk: cannot getBulk with V1 PDU.");
+ return null;
+ }
+ // v1
+ response = DefaultPDUFactory.createPDU(SnmpConstants.version1);
+ } else {
+ // v2c
+ response = new PDU();
+ }
+ response.setType(PDU.RESPONSE);
return response;
- }
-
+ }
+
/**
* <P>
* This method is defined to handle SNMP requests that are received by the
@@ -304,12 +534,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 +566,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 -------------------------------------------------------
@@ -400,221 +630,606 @@
* We have the MBeans now. Put them into the bindungs.
*/
- Iterator it = mappings.iterator();
- while (it.hasNext())
- {
- ManagedBean mmb = (ManagedBean)it.next();
- String oidPrefix = mmb.getOidPrefix();
- List attrs = mmb.getAttributes();
- 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);
-
- }
- }
+ addAttributeMappings(mappings);
}
+
+ /**
+ * @param mappings
+ */
+ public void addAttributeMappings(List<ManagedBean> mappings) {
+ Iterator<ManagedBean> it = mappings.iterator();
+ while (it.hasNext()) {
+ ManagedBean mmb = it.next();
+ ObjectName oname = null;
+ try{
+ oname = new ObjectName(mmb.getName());
+ } catch (Exception e) {}
+ if (oname.isPattern()){ //it is a pattern. the mat
+ tableMapper.addTableMapping(mmb, oname);
+ } else {
+ String oidPrefix = mmb.getOidPrefix();
+ List<MappedAttribute> attrs = mmb.getAttributes();
+ Iterator<MappedAttribute> aIt = attrs.iterator();
+ while (aIt.hasNext()) {
+ MappedAttribute ma = aIt.next();
+ String oid;
+ if (oidPrefix != null) {
+ oid = oidPrefix + ma.getOid();
+// addObjectEntry(new OID(oidPrefix));
+ } else {
+ oid = ma.getOid();
+// OID objectOID = new OID(oid);
+// addObjectEntry(objectOID.trim());
+ }
+ if(ma.isAttributeTable()) {
+ attributeTableMapper.addTableMapping(mmb, ma);
+ oidKeys.add(new OID(oid));
+ } else {
+ oid = oid + ".0";
+ addBindEntry(oid, mmb.getName(), ma.getName(), ma.isReadWrite());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @param mappings
+ */
+ public void removeAttributeMappings(List<ManagedBean> mappings) {
+ Iterator<ManagedBean> it = mappings.iterator();
+ while (it.hasNext()) {
+ ManagedBean mmb = it.next();
+ ObjectName oname = null;
+ try{
+ oname = new ObjectName(mmb.getName());
+ } catch (Exception e) {}
+ if (oname.isPattern()){ //it is a pattern. the mat
+ tableMapper.removeTableMapping(mmb, oname);
+ } else {
+ String oidPrefix = mmb.getOidPrefix();
+ List<MappedAttribute> attrs = mmb.getAttributes();
+ Iterator<MappedAttribute> aIt = attrs.iterator();
+ while (aIt.hasNext()) {
+ MappedAttribute ma = aIt.next();
+ String oid;
+ if (oidPrefix != null) {
+ oid = oidPrefix + ma.getOid();
+// addObjectEntry(new OID(oidPrefix));
+ } else {
+ oid = ma.getOid();
+// OID objectOID = new OID(oid);
+// addObjectEntry(objectOID.trim());
+ }
+ if(ma.isAttributeTable()) {
+ attributeTableMapper.removeTableMapping(mmb, ma);
+ oidKeys.remove(new OID(oid));
+ } else {
+ oid = oid + ".0";
+ OID coid = new OID(oid);
+ oidKeys.remove(coid);
+ bindings.remove(coid);
+ }
+ }
+ }
+ }
+ }
+
+ /** This method adds a new ObjectEntry to the set of Object OIDs.
+ * @param String representation of the OID to add.
+ *
+ * **/
+// private void addObjectEntry(OID oid){
+// if (objectKeys.contains(oid))
+// log.debug("duplicate object " + oid + SKIP_ENTRY);
+//
+// if (oid == null)
+// log.debug("null oid for object");
+// objectKeys.add(oid);
+//
+// }
+
+ /**
+ *
+ * @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){
+ OID coid = new OID(oid);
+ BindEntry be = new BindEntry(coid, mmb, ma);
+ be.setReadWrite(rw);
+
+ 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;
+ boolean exists = bindings.get(oid) != null;
+ if(!exists) {
+ //needed for table
+ exists = tableMapper.belongsToTable(oid);
+ if(!exists) {
+ exists = attributeTableMapper.belongsToTables(oid);
+ }
+ }
+ return exists;
+ }
+
+ /**
* 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) {
+ public Variable getValueFor(final OID oid) throws NoSuchInstanceException, VariableTypeException {
BindEntry be = findBindEntryForOid(oid);
- SnmpSyntax ssy = null;
- if (be != null)
- {
+ Variable ssy = null;
+ if (be != null) {
if (log.isTraceEnabled())
- log.trace("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);
+ log.debug("getValueFor: Found entry " + be.toString() + " for oid " + oid);
+
+ try {
+ Object val = server.getAttribute(be.getMbean(), be.getAttr().getName());
+ OID tableIndexOID = null;
+ if(be.isTable()) {
+ tableIndexOID = be.getTableIndexOID();
+ }
+ ssy = prepForPdu(val, tableIndexOID);
+ } 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.getMbean().toString() + ", "
+ + be.getAttr().getName() + ": " + e.toString());
+ }
+ } else {
+ ssy = tableMapper.getObjectNameIndexValue(oid);
+ if(ssy != null) {
+ return ssy;
+ }
+ ssy = attributeTableMapper.getIndexValue(oid);
+ if(ssy != null) {
+ return ssy;
+ }
+ log.debug("getValueFor: " + NO_ENTRY_FOUND_FOR_OID + oid);
+ throw new NoSuchInstanceException();
+ }
+ return ssy;
+ }
+
+ /**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.
+ *
+ */
+
+ public static Variable prepForPdu(final Object val, final OID tableIndexOID) throws VariableTypeException{
+ Variable result = null;
+ Object value = val;
+ if(val == null) {
+ return new Null();
+ }
+ //TODO: all types managed by the PDU
+
+ // manage arrays and lists
+ if(tableIndexOID != null) {
+ if(val instanceof List) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
}
- else if (val instanceof String)
- {
- String in = (String) val;
- ssy = new SnmpOctetString(in.getBytes());
+ if(index < ((List)val).size()) {
+ value = ((List)val).get(index);
+ } else {
+ return Null.noSuchObject;
}
- else if (val instanceof Integer)
- {
- Integer in = (Integer) val;
- ssy = new SnmpInt32(in);
+ }
+ if(val instanceof Map) {
+ String key = new String(tableIndexOID.toByteArray());
+ value = ((Map)val).get(key);
+ if(value == null) {
+ return Null.noSuchObject;
}
- else if (val instanceof SnmpObjectId)
- {
- ssy = (SnmpObjectId)val;
+ }
+ if (value instanceof int[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
}
- else if (val instanceof SnmpTimeTicks)
- {
- ssy = (SnmpTimeTicks)val;
- }
- else
- log.info("Unknown type for " + be);
+ if(index < ((int[])val).length) {
+ value = ((int[])val)[index];
+ } else {
+ return Null.noSuchObject;
+ }
}
- 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);
+ if (value instanceof long[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((long[])val).length) {
+ value = ((long[])val)[index];
+ } else {
+ return Null.noSuchObject;
+ }
+ }
+ if (value instanceof boolean[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((boolean[])val).length) {
+ value = ((boolean[])val)[index];
+ } else {
+ return Null.noSuchObject;
+ }
+ }
+ if (value instanceof Object[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((Object[])val).length) {
+ value = ((Object[])val)[index];
+ } else {
+ return Null.noSuchObject;
+ }
+ }
}
- return ssy;
+
+ // manage regular java types
+ if (value instanceof Long) {
+ result = new OctetString(((Long)value).toString());
+ } else if (value instanceof AtomicLong) {
+ result = new OctetString(((AtomicLong)value).toString());
+ } else if (value instanceof Boolean) {
+ if(((Boolean)value).booleanValue())
+ result = new Integer32(1);
+ else
+ result = new Integer32(0);
+ } else if (value instanceof AtomicBoolean) {
+ if(((AtomicBoolean)value).get())
+ result = new Integer32(1);
+ else
+ result = new Integer32(0);
+ } else if (value instanceof String) {
+ result = new OctetString((String) value);
+ } else if (value instanceof Integer) {
+ result = new Integer32((Integer)value);
+ } else if (value instanceof AtomicInteger) {
+ result = new Integer32(((AtomicInteger)value).get());
+ } else if (value instanceof OID) {
+ result = new OID((OID)value);
+ } else if (value 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"));
+ result = (TimeTicks) value;
+ } else if (value instanceof Counter32) {
+ result = (Counter32) value;
+ } 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, final Object attribute) throws VariableTypeException{
+ Object result = null;
+ if (val instanceof OctetString)
+ {
+ if(attribute instanceof Long) {
+ result = Long.parseLong(val.toString());
+ } else if(attribute instanceof AtomicLong) {
+ result = new AtomicLong(Long.parseLong(val.toString()));
+ } else {
+ result = val.toString();
+ }
+ }
+ else if (val instanceof Integer32)
+ {
+ if(attribute instanceof Boolean) {
+ if(((Integer32)val).getValue() == 0) {
+ result = Boolean.FALSE;
+ } else {
+ result = Boolean.TRUE;
+ }
+ } else if(attribute instanceof AtomicBoolean) {
+ if(((Integer32)val).getValue() == 0) {
+ result = new AtomicBoolean(Boolean.FALSE);
+ } else {
+ result = new AtomicBoolean(Boolean.TRUE);
+ }
+ } else if(attribute instanceof AtomicInteger) {
+ result = new AtomicInteger(Integer.valueOf(((Integer32)val).getValue()));
+ } else {
+ result = Integer.valueOf(((Integer32)val).getValue());
+ }
+ }
+ else if (val instanceof Counter32)
+ {
+ result = Long.valueOf(((Counter32)val).getValue());
+ }
+ else if (val instanceof Counter64)
+ {
+ result = Long.valueOf(((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
+
+ /** 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.
- */
- private SnmpSyntax setValueFor(final SnmpObjectId oid, final SnmpSyntax newVal) throws ReadOnlyException
- {
+ * */
+
+ 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 (be != null) {
if (trace)
log.trace("setValueFor: " + be.toString());
- if (be.isReadWrite == false)
- {
+ 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();
- }
- 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
+ try {
+ Object other = server.getAttribute(be.getMbean(), be.getAttr().getName());
+ Object val = convertVariableToValue(newVal, other);
- 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");
+ if (other != null && val.getClass() != other.getClass() ) {
+ if(log.isDebugEnabled())
+ log.debug("setValueFor: attempt to set an MBean Attribute with the wrong type.");
+ ssy = newVal;
}
- else
- {
- log.debug("Did not find a suitable data type for newVal " + newVal);
- ssy = new SnmpNull();
+ OID tableIndexOID = be.getTableIndexOID();
+ if(tableIndexOID == null) {
+ Attribute at = new Attribute(be.getAttr().getName(), val);
+ server.setAttribute(be.getMbean(), at);
+ } else {
+ // manage arrays and lists
+ if(other instanceof List) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((List)other).size()) {
+ ((List)other).set(index, val);
+ } else {
+ return Null.noSuchObject;
+ }
+ }
+ if(other instanceof Map) {
+ String key = new String(tableIndexOID.toByteArray());
+ ((Map)other).put(key, val);
+ }
+ if (other instanceof int[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((int[])other).length) {
+ ((int[])other)[index] = (Integer) val;
+ } else {
+ return Null.noSuchObject;
+ }
+ }
+ if (other instanceof long[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((long[])other).length) {
+ ((long[])other)[index] = (Long) val;
+ } else {
+ return Null.noSuchObject;
+ }
+ }
+ if (other instanceof boolean[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((boolean[])other).length) {
+ ((boolean[])other)[index] = (Boolean) val;
+ } else {
+ return Null.noSuchObject;
+ }
+ }
+ if (other instanceof Object[]) {
+ int index = Integer.valueOf(tableIndexOID.toString()) - 1;
+ if(index < 0) {
+ return Null.noSuchObject;
+ }
+ if(index < ((Object[])other).length) {
+ ((Object[])other)[index] = val;
+ } else {
+ return Null.noSuchObject;
+ }
+ }
}
- // TODO
+
+ 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<VariableBinding> 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);
+ if(be == null) {
+ //needed for tables
+ be = tableMapper.getTableBinding(coid);
+ if(be == null) {
+ be = attributeTableMapper.getTableBinding(coid, false);
+ }
}
- 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);
-
-
- if (coid.isLeaf())
- coid = coid.removeLastPart();
-
- SortedSet ret;
- ret= oidKeys.tailSet(oid); // get oids >= oid
- Iterator it = ret.iterator();
- ComparableSnmpObjectId roid=null;
+ private OID getNextOid(final OID oid) throws EndOfMibViewException {
+ OID coid = new OID(oid);
+ tableMapper.checkTables(oid);
+ OID nextOid = tableMapper.getNextTable(coid);
+ if(nextOid != null) {
+ return nextOid;
+ }
+ nextOid = attributeTableMapper.getNextTable(coid);
+ if(nextOid != null) {
+ return nextOid;
+ }
+ SortedSet<OID> ret = new TreeSet(oidKeys.tailSet(oid)); // get oids >= oid
+ Iterator<OID> it = ret.iterator();
+ OID roid=null;
/*
* If there are elements in the tail set, then
@@ -623,155 +1238,56 @@
* 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: 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: 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)
- {
- ComparableSnmpObjectId parent = coid.removeLastPart();
- if (!parent.isRootOf(roid))
- roid = null;
- }
- return roid;
- }
-
-
- // Inner Class ---------------------------------------------------
-
- /**
- * An entry containing the mapping between oid and mbean/attribute
- *
- * @author <a href="mailto:pilhuhn at user.sf.net>">Heiko W. Rupp</a>
- */
- private class BindEntry implements Comparable {
- private final ComparableSnmpObjectId oid;
-
- private ObjectName mbean;
- private Attribute attr;
- private String mName;
- private String aName;
- private boolean isReadWrite = false;
-
- /**
- * Constructs a new BindEntry
- *
- * @param oid
- * The SNMP-oid, this entry will use.
- * @param mbName
- * The name of an MBean with attribute to query
- * @param attrName
- * The name of the attribute to query
- */
- BindEntry(final String oidString, final String mbName, final String attrName) {
- this(new ComparableSnmpObjectId(oidString),
- mbName,
- attrName);
- }
-
- /**
- * Constructs a new BindEntry.
- * @param coid The SNMP-oid, this entry will use.
- * @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) {
- oid = coid;
- this.mName = mbName;
- this.aName = attrName;
- try
- {
- mbean = new ObjectName(mbName);
- attr = new Attribute(attrName, null);
-
+ if(roid.last() != 0) {
+ nextOid = tableMapper.getNextTable(roid);
+ if(nextOid != null) {
+ return nextOid;
}
- catch (Exception e)
- {
- log.warn(e.toString());
- mName = "-unset-";
- aName = "-unset-";
+ nextOid = attributeTableMapper.getNextTable(roid);
+ if(nextOid != null) {
+ return nextOid;
}
}
-
- /**
- * A string representation of this BindEntry
- */
- public String toString() {
- StringBuffer buf = new StringBuffer();
- buf.append("[oid=");
- buf.append(oid).append(", mbean=");
- buf.append(mName).append(", attr=");
- buf.append(aName).append(", rw=");
- buf.append(isReadWrite).append("]");
-
- return buf.toString();
- }
-
- public Attribute getAttr() {
- return attr;
- }
-
- public ObjectName getMbean()
- {
- return mbean;
- }
-
- public ComparableSnmpObjectId getOid()
- {
- return oid;
- }
-
-
- /**
- * Compare two BindEntries. Ordering is defined at oid-level.
- *
- * @param other
- * The BindEntry to compare to.
- * @return 0 on equals, 1 if this is bigger than other
- */
- public int compareTo(Object other)
- {
- if (other == null)
- throw new NullPointerException("Can't compare to NULL");
-
- if (!(other instanceof BindEntry))
- throw new ClassCastException("Parameter is no BindEntry");
-
- // trivial case
- if (this.equals(other))
- return 0;
-
- BindEntry obe = (BindEntry) other;
- if (getOid().equals(obe.getOid()))
- return 0;
-
- int res =oid.compare(obe.getOid());
- return res;
- }
-
+ 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 errorIndex the VariableBinding in the PDU that caused the error.
+ * @param err The error number defined in the PDU class that indicates a given failure
+ */
+ private void makeErrorPdu(PDU response, PDU pdu, int errorIndex, int err){
+ response.clear();
+ response.addAll(pdu.toArray());
+ response.setErrorIndex(errorIndex);
+ response.setErrorStatus(err);
+ }
+}
\ No newline at end of file
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/RequestHandlerSupport.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -26,13 +26,9 @@
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.snmp4j.PDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.smi.OctetString;
/**
* Implement RequestHandler with simple tracing of incoming requests.
@@ -43,7 +39,7 @@
* @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
* @version $Revision$
*/
-public class RequestHandlerSupport implements RequestHandler
+public abstract class RequestHandlerSupport implements RequestHandler
{
// Protected Data ------------------------------------------------
@@ -82,174 +78,4 @@
this.log = log;
this.clock = uptime;
}
-
- // SnmpAgentHandler Implementation -------------------------------
-
- /**
- * <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.
- *
- * @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;
- }
-
- /**
- * <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 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;
- }
-
- /**
- * <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
- *
- */
- public void snmpReceivedPdu(SnmpAgentSession session, InetAddress manager, int port,
- SnmpOctetString community, SnmpPduPacket pdu)
- {
- log.error("Message from manager " + manager.toString() + " on port " + port);
- int cmd = pdu.getCommand();
- log.error("Unsupported PDU command......... " + cmd);
- }
-
- /**
- * <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.
- */
- public void SnmpAgentSessionError(SnmpAgentSession 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
- }
- }
- }
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentService.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -19,18 +19,41 @@
*/
package org.jboss.jmx.adaptor.snmp.agent;
+import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
import javax.management.Notification;
import javax.management.ObjectName;
-import org.jboss.bootstrap.api.as.config.JBossASServerConfig;
+import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
+import org.jboss.jmx.adaptor.snmp.config.notification.Mapping;
+import org.jboss.jmx.adaptor.snmp.config.user.User;
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.jboss.xb.binding.MappingObjectModelFactory;
+import org.jboss.xb.binding.Unmarshaller;
+import org.jboss.xb.binding.UnmarshallerFactory;
+import org.snmp4j.MessageDispatcherImpl;
+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.security.Priv3DES;
+import org.snmp4j.security.SecurityModels;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.USM;
+import org.snmp4j.security.UsmUser;
+import org.snmp4j.smi.OctetString;
+import org.snmp4j.smi.UdpAddress;
+import org.snmp4j.transport.DefaultUdpTransportMapping;
+
/**
* <tt>SnmpAgentService</tt> is an MBean class implementing an SNMP agent.
*
@@ -52,7 +75,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";
@@ -66,6 +90,9 @@
/** Trap counter */
private Counter trapCounter = null;
+ /** Name of the file containing SNMP users */
+ private String usersResName = null;
+
/** Name of the file containing SNMP manager specifications */
private String managersResName = null;
@@ -113,13 +140,30 @@
/** The trap emitting subsystem*/
private TrapEmitter trapEmitter = null;
-
- /** the snmp agent session for handling get/set requests */
- private SnmpAgentSession agentSession = null;
/** the request handler instance handling get/set requests */
private RequestHandler requestHandler;
+ /** the location of the agent's settings**/
+ private String configFileResName = null;
+
+ /** the location of the boot counter persistent store **/
+ private String bootCounterResName = null;
+
+ private Snmp session;
+
+ private TransportMapping[] transportMappings;
+
+ private SnmpRequest responder;
+
+ private USM usm;
+
+ private MPv3 mpv3;
+
+ private MessageDispatcherImpl dispatcher;
+
+ private Map<String, User> userMap = new HashMap<String, User>();
+
// Constructors --------------------------------------------------
/**
@@ -472,6 +516,14 @@
protected void startService()
throws Exception
{
+
+ // initialise the snmp agent
+ log.debug("Starting snmp agent ...");
+
+ startAgent();
+
+ log.info("SNMP agent going active");
+
// initialize clock and trapCounter
this.clock = new Clock();
this.trapCounter = new Counter(0);
@@ -480,11 +532,7 @@
// ListenerServiceMBeanSupport baseclass
log.debug("Instantiating trap emitter ...");
- this.trapEmitter = new TrapEmitter(this.getTrapFactoryClassName(),
- this.trapCounter,
- this.clock,
- this.getManagersResName(),
- this.getNotificationMapResName());
+ this.trapEmitter = new TrapEmitter(this);
// Start trap emitter
log.debug("Starting trap emitter ...");
@@ -499,13 +547,7 @@
heartbeat.start();
// subscribe for notifications, with the option for dynamic subscriptions
- super.subscribe(this.dynamicSubscriptions);
-
- // initialise the snmp agent
- log.debug("Starting snmp agent ...");
- startAgent();
-
- log.info("SNMP agent going active");
+ super.subscribe(this.dynamicSubscriptions);
// Send the cold start!
this.sendNotification(new Notification(EventTypes.COLDSTART, this,
@@ -530,9 +572,9 @@
this.trapEmitter = null;
log.debug("Stopping snmp agent ...");
- this.agentSession.close();
- this.agentSession = null;
-
+// this.agentSession.close();
+// this.agentSession = null;
+ session.close();
log.info("SNMP agent stopped");
}
@@ -543,8 +585,8 @@
*/
public void handleNotification2(Notification n, Object handback)
{
- if (log.isTraceEnabled()) {
- log.trace("Received notification: <" + n + "> Payload " +
+ if (log.isDebugEnabled()) {
+ log.debug("Received notification: <" + n + "> Payload " +
"TS: <" + n.getTimeStamp() + "> " +
"SN: <" + n.getSequenceNumber() + "> " +
"T: <" + n.getType() + ">");
@@ -559,34 +601,118 @@
}
// Private -------------------------------------------------------
+
+ private void initResponder(){
+ OctetString localEngineID=new OctetString(MPv3.createLocalEngineID());
+ this.responder = new SnmpRequest(this.requestHandler, log, localEngineID);
+ }
+ // add updateEngineBoots to USM constuctor call
+ private void initMessageDispatcher(){
+ this.dispatcher = new MessageDispatcherImpl();
+ usm = new USM(SecurityProtocols.getInstance(),
+ responder.getLocalEngineID(),
+ 0);
+ mpv3 = new MPv3(usm);
+ SecurityModels.getInstance().addSecurityModel(usm);
+ SecurityProtocols.getInstance().addDefaultProtocols();
+ // all other privacy and authentication protocols are provided by the above method
+ SecurityProtocols.getInstance().addPrivacyProtocol(new Priv3DES());
+ dispatcher.addMessageProcessingModel(new MPv1());
+ dispatcher.addMessageProcessingModel(new MPv2c());
+ dispatcher.addMessageProcessingModel(mpv3);
+ }
+
+ private void initRequestHandler()throws Exception{
+ this.requestHandler = (RequestHandler)Class.forName(this.requestHandlerClassName,true,this.getClass().getClassLoader()).newInstance();
+ this.requestHandler.initialize(this.requestHandlerResName,
+ this.getServer(),
+ this.log,
+ this.clock);
+ }
+
+ private void initTransportMapping(){
+ this.transportMappings = new TransportMapping[1];
+ try{
+ this.transportMappings[0] = new DefaultUdpTransportMapping(new UdpAddress(this.bindAddress, this.port));
+ }catch(Exception e){
+ log.debug("Exception in initialization of Tranport Map!!");
+ }
+ }
+
+ private void initSession(){
+ this.session = new Snmp(dispatcher);
+ for (int i = 0; i < transportMappings.length;i++){
+ try{
+ session.addTransportMapping(transportMappings[i]);
+ }
+ catch(Exception e){
+ log.warn("Tranport mapping invalid. Failed to initialize mapping '"+
+ transportMappings[i]+"' with: "+e.getMessage());
+
+ }
+ }
+ this.session.addCommandResponder(responder);
+ }
+
+ /*
+ * Read the users from the users.xml and add them to the usm
+ */
+ private void addUsmUsers() throws Exception {
+ MappingObjectModelFactory momf = new MappingObjectModelFactory();
+ momf.mapElementToClass("user-list", ArrayList.class);
+ momf.mapElementToClass("user", User.class);
+
+ List<User> userList = null;
+ InputStream is = null;
+ try {
+ // locate users.xml
+ final String resName = this.usersResName;
+ is = SecurityActions.getThreadContextClassLoaderResource(resName);
+
+ // create unmarshaller
+ Unmarshaller unmarshaller = UnmarshallerFactory.newInstance()
+ .newUnmarshaller();
+
+ // let JBossXB do it's magic using the MappingObjectModelFactory
+ userList = (ArrayList<User>) unmarshaller.unmarshal(is, momf, null);
+ } catch (Exception e) {
+ log.error("Accessing resource '" + usersResName + "'");
+ throw e;
+ } finally {
+ if (is != null) {
+ // close the XML stream
+ is.close();
+ }
+ }
+
+ for (Iterator<User> userIt = userList.iterator(); userIt.hasNext(); ) {
+ User user = userIt.next();
+
+ UsmUser usmUser = new UsmUser(new OctetString(user.getSecurityName()),
+ user.getAuthenticationProtocolID(),
+ new OctetString(user.getAuthenticationPassphrase()),
+ user.getPrivacyProtocolID(),
+ new OctetString(user.getPrivacyPassphrase()));
+ this.usm.addUser(usmUser.getSecurityName(), usm.getLocalEngineID(),usmUser);
+ this.userMap.put(user.getSecurityName(), user);
+ }
+ }
+ // the new Snmp(TransportMapping) constructor already initializes a MessageDispatcherImpl with all MP's associated.
/**
* Start the embedded agent
*/
private void startAgent()
throws Exception
{
- // 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));
+ initRequestHandler();
+ initResponder();
+ initMessageDispatcher();
+ initTransportMapping();
+ initSession();
+ addUsmUsers();
- // the listening address
- 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);
-
- // 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);
-
- // Instantiate the AgentSession with an optional thread pool
- this.agentSession = this.numberOfThreads > 1
- ? new SnmpAgentSession(requestHandler, peer, this.numberOfThreads)
- : new SnmpAgentSession(requestHandler, peer);
+ session.listen();
}
/**
@@ -601,4 +727,104 @@
return InetAddress.getByName(host);
}
+ /**
+ * @param usersResName the usersResName to set
+ */
+ public void setUsersResName(String usersResName) {
+ this.usersResName = usersResName;
+ }
+
+ /**
+ * @return the usersResName
+ */
+ public String getUsersResName() {
+ return usersResName;
+ }
+
+ /**
+ * @return the clock
+ */
+ public Clock getClock() {
+ return clock;
+ }
+
+ /**
+ * @return the trapCounter
+ */
+ public Counter getTrapCounter() {
+ return trapCounter;
+ }
+
+ /**
+ * @return the userList
+ */
+ public Map<String, User> getUserMap() {
+ return userMap;
+ }
+
+ /**
+ * @return the session
+ */
+ public Snmp getSession() {
+ return session;
+ }
+
+ /**
+ * @return the responder
+ */
+ public SnmpRequest getResponder() {
+ return responder;
+ }
+
+ /**
+ * @return the requestHandler
+ */
+ public RequestHandler getRequestHandler() {
+ return requestHandler;
+ }
+
+ /**
+ * @return the transportMappings
+ */
+ public TransportMapping[] getTransportMappings() {
+ return transportMappings;
+ }
+
+ @Override
+ public void sendJMXNotification(Notification notification) {
+ if(notification.getSequenceNumber() <= 0) {
+ notification.setSequenceNumber(getNextNotificationSequenceNumber());
+ }
+ try {
+ this.trapEmitter.send(notification);
+ } catch (Exception e) {
+ log.error("Problem occured while Sending trap", e);
+ }
+ }
+
+ @Override
+ public long getNextJMXNotificationSequenceNumber() {
+ return getNextNotificationSequenceNumber();
+ }
+
+ @Override
+ public void addAttributeMappings(List<ManagedBean> mappings) {
+ requestHandler.addAttributeMappings(mappings);
+ }
+
+ @Override
+ public void removeAttributeMappings(List<ManagedBean> mappings) {
+ requestHandler.removeAttributeMappings(mappings);
+ }
+
+ @Override
+ public void addNotifications(List<Mapping> notifications) {
+ trapEmitter.addNotifications(notifications);
+ }
+
+ @Override
+ public void removeNotifications(List<Mapping> notifications) {
+ trapEmitter.removeNotifications(notifications);
+ }
+
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpAgentServiceMBean.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -22,9 +22,16 @@
package org.jboss.jmx.adaptor.snmp.agent;
import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import javax.management.Notification;
import javax.management.ObjectName;
+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.notification.Mapping;
import org.jboss.mx.util.ObjectNameFactory;
import org.jboss.system.ListenerServiceMBean;
@@ -44,7 +51,11 @@
/** The name of the file containing SNMP manager specifications */
void setManagersResName(String managersResName);
String getManagersResName();
-
+
+ /** The name of the file containing SNMPv3 users */
+ void setUsersResName(String usersResName);
+ String getUsersResName();
+
/** The name of the file containing the notification/trap mappings */
void setNotificationMapResName(String notificationMapResName);
String getNotificationMapResName();
@@ -105,8 +116,20 @@
long getTrapCount();
// Operations ----------------------------------------------------
-
+
/**
+ *
+ */
+ void sendJMXNotification(Notification notification);
+ long getNextJMXNotificationSequenceNumber();
+
+ void addAttributeMappings(List<ManagedBean> mappings);
+ void removeAttributeMappings(List<ManagedBean> mappings);
+
+ void addNotifications(List<Mapping> notifications);
+ void removeNotifications(List<Mapping> notifications);
+
+ /**
* Reconfigures the RequestHandler, that is
* reponsible for handling get requests etc.
*/
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/SnmpVarBindFactory.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -24,11 +24,11 @@
import java.util.Map;
import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpCounter64;
-import org.opennms.protocols.snmp.SnmpInt32;
-import org.opennms.protocols.snmp.SnmpObjectId;
-import org.opennms.protocols.snmp.SnmpOctetString;
-import org.opennms.protocols.snmp.SnmpVarBind;
+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.
@@ -48,7 +48,7 @@
private static final Logger log = Logger.getLogger(SnmpVarBindFactory.class);
/** Contains "type - maker" tupples */
- private Map makers = new HashMap();
+ private Map<String, Maker> makers = new HashMap<String, Maker>();
/** Default Maker */
private final Maker defaultMaker = new SnmpObjectMaker();
@@ -59,9 +59,10 @@
**/
public SnmpVarBindFactory()
{
+ makers.put("java.lang.Boolean", new SnmpBooleanMaker());
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 SnmpLongMaker());
makers.put("java.math.BigInteger", new SnmpCounter64Maker());
makers.put("java.util.Date", new SnmpDateMaker());
}
@@ -71,7 +72,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 +95,7 @@
**/
interface Maker
{
- public SnmpVarBind make(String oid, Object value)
+ public VariableBinding make(String oid, Object value)
throws MappingFailedException;
}
@@ -104,15 +105,52 @@
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 integer SNMP variable bindings
+ **/
+ class SnmpBooleanMaker
+ implements Maker
+ {
+ public VariableBinding make(String oid, Object value)
+ throws MappingFailedException
+ {
+ Boolean b = (Boolean)value;
+
+ Integer32 result;
+ if(((Boolean)b).booleanValue())
+ result = new Integer32(1);
+ else
+ result = new Integer32(0);
+
+ return new VariableBinding(new OID(oid), result);
+ }
+ } // class SnmpBooleanMaker
+
+ /**
+ * Generates unsigned long integer SNMP variable bindings
+ **/
+ class SnmpLongMaker
+ implements Maker
+ {
+ public VariableBinding make(String oid, Object value)
+ throws MappingFailedException
+ {
+ Long l = (Long)value;
+
+ return new VariableBinding(new OID(oid),
+ new OctetString(l.toString()));
+ }
+ } // class SnmpCounter64Maker
/**
* Generates unsigned long integer SNMP variable bindings
@@ -120,13 +158,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 +174,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 +190,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 +206,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: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapEmitter.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -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;
@@ -26,19 +27,50 @@
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.List;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
import javax.management.Notification;
import org.jboss.bootstrap.api.as.config.JBossASServerConfig;
import org.jboss.jmx.adaptor.snmp.config.manager.Manager;
+import org.jboss.jmx.adaptor.snmp.config.notification.Mapping;
+import org.jboss.jmx.adaptor.snmp.config.notification.VarBind;
+import org.jboss.jmx.adaptor.snmp.config.notification.VarBindList;
+import org.jboss.jmx.adaptor.snmp.config.user.User;
import org.jboss.logging.Logger;
+import org.jboss.xb.binding.GenericObjectModelFactory;
import org.jboss.xb.binding.MappingObjectModelFactory;
+import org.jboss.xb.binding.ObjectModelFactory;
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.jboss.xb.binding.UnmarshallingContext;
+import org.snmp4j.CommunityTarget;
+import org.snmp4j.MessageDispatcherImpl;
+import org.snmp4j.PDU;
+import org.snmp4j.PDUv1;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.Snmp;
+import org.snmp4j.Target;
+import org.snmp4j.UserTarget;
+import org.snmp4j.mp.MPv2c;
+import org.snmp4j.mp.MPv3;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.security.SecurityModel;
+import org.snmp4j.security.SecurityProtocols;
+import org.snmp4j.security.USM;
+import org.snmp4j.security.UsmUser;
+import org.snmp4j.smi.Address;
+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;
+import org.xml.sax.Attributes;
/**
* <tt>TrapEmitter</tt> is a class that manages SNMP trap emission.
@@ -60,38 +92,25 @@
/** Reference to the utilised trap factory*/
private TrapFactory trapFactory = null;
- /** The actual trap factory to instantiate */
- private String trapFactoryClassName = null;
-
- /** The managers resource name */
- private String managersResName = null;
+ private SnmpAgentService snmpAgentService;
- /** The notification map resource name */
- private String notificationMapResName = null;
-
- /** Provides trap count */
- private Counter trapCount = null;
-
- /** Uptime clock */
- private Clock uptime = null;
-
/** Holds the manager subscriptions. Accessed through synch'd wrapper */
private Set managers = Collections.synchronizedSet(new HashSet());
+ /** Contains the read in mappings */
+ private ArrayList notificationMapList = null;
+
+ /** Contains the compiled regular expression type specifications */
+ private ArrayList mappingRegExpCache = null;
+
+ /** Contains instances of the notification wrappers */
+ private ArrayList notificationWrapperCache = null;
+
/**
* Builds a TrapEmitter object for sending SNMP V1 or V2 traps. <P>
**/
- public TrapEmitter(String trapFactoryClassName,
- Counter trapCount,
- Clock uptime,
- String managersResName,
- String notificationMapResName)
- {
- this.trapFactoryClassName = trapFactoryClassName;
- this.trapCount = trapCount;
- this.uptime = uptime;
- this.managersResName = managersResName;
- this.notificationMapResName = notificationMapResName;
+ public TrapEmitter(SnmpAgentService snmpAgentService) {
+ this.snmpAgentService = snmpAgentService;
}
/**
@@ -104,14 +123,14 @@
load();
// Instantiate the trap factory
- this.trapFactory = (TrapFactory) Class.forName(this.trapFactoryClassName,
+ this.trapFactory = (TrapFactory) Class.forName(this.snmpAgentService.getTrapFactoryClassName(),
true,
this.getClass().getClassLoader()).newInstance();
// Initialise
- this.trapFactory.set(this.notificationMapResName,
- this.uptime,
- this.trapCount);
+ this.trapFactory.set(this.snmpAgentService.getClock(),
+ this.snmpAgentService.getTrapCounter(),
+ this.snmpAgentService.getRequestHandler());
// Start the trap factory
this.trapFactory.start();
@@ -124,14 +143,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();
@@ -146,9 +157,7 @@
* @throws Exception if an error occurs during the preparation or
* sending of the trap
**/
- public void send(Notification n)
- throws Exception
- {
+ public void send(Notification n) throws Exception {
// Beeing paranoid
synchronized(this.trapFactory) {
if(this.trapFactory == null) {
@@ -156,62 +165,149 @@
return;
}
}
-
+
+ // Locate mapping for incomming event
+ int index = findMappingIndex(n);
+ if(index < 0) {
+ log.debug("No SNMP notifications configured for Notification " + n.getType() + " doing nothing");
+ return;
+ }
+
+ Mapping m = (Mapping)this.notificationMapList.get(index);
+ // Get the coresponding wrapper to get access to notification payload
+ NotificationWrapper wrapper =
+ (NotificationWrapper)this.notificationWrapperCache.get(index);
+
// Cache the translated notification
- SnmpPduTrap v1TrapPdu = null;
- SnmpPduPacket v2TrapPdu = null;
+ PDUv1 v1TrapPdu = null;
+ PDU v2cTrapPdu = null;
+ ScopedPDU v3TrapPdu = null;
+
+ if(managers.size() > 0) {
+
+ // Send trap. Synchronise on the subscription collection while
+ // iterating
+ synchronized(this.managers) {
+ // Iterate over sessions and emit the trap on each one
+ Iterator i = this.managers.iterator();
+ while (i.hasNext()) {
+
+ Target t = (Target)i.next();
+
+ try {
+ switch (t.getVersion()) {
+ case SnmpConstants.version1:
+ if (v1TrapPdu == null)
+ v1TrapPdu = this.trapFactory.generateV1Trap(n, m, wrapper);
+
+ sendTrap(v1TrapPdu, t, m.getSecurityName());
+ break;
+
+ case SnmpConstants.version2c:
+ if (v2cTrapPdu == null)
+ v2cTrapPdu = this.trapFactory.generateV2cTrap(n, m, wrapper);
+
+ sendTrap(v2cTrapPdu, t, m.getSecurityName());
+ break;
+
+ case SnmpConstants.version3:
+ if (v3TrapPdu == null)
+ v3TrapPdu = this.trapFactory.generateV3Trap(n, m, wrapper);
+
+ sendTrap(v3TrapPdu, t, m.getSecurityName());
+
+ break;
+
+ default:
+ log.error("Skipping session: Unknown SNMP version found");
+ }
+ } catch(MappingFailedException e) {
+ log.error("Translating notification failed ", e);
+ } catch(Exception e) {
+ log.error("SNMP send error for " + t.getAddress().toString(), e);
+ }
+ }
+ }
+ } else {
+ log.warn("No SNMP managers to send traps to");
+ }
+ }
+
+ void sendTrap(PDU trap, Target target, String securityName) throws IOException {
+ // Advance the trap counter
+ this.snmpAgentService.getTrapCounter().advance();
- // Send trap. Synchronise on the subscription collection while
- // iterating
- synchronized(this.managers) {
+ if(target instanceof UserTarget) {
+ if(securityName != null) {
+ if(snmpAgentService.getUserMap().get(securityName) == null) {
+ throw new IllegalArgumentException("Notification Security Name " +securityName + " doesn't match any user defined in users.xml");
+ } else {
+ OctetString userSecurityName = new OctetString(securityName);
+
+ ((UserTarget)target).setSecurityName(userSecurityName);
+ ((UserTarget)target).setSecurityLevel(snmpAgentService.getUserMap().get(securityName).getSecurityLevel());
+ ((UserTarget)target).setSecurityModel(SecurityModel.SECURITY_MODEL_USM);
+
+ if(trap.getType() == PDU.INFORM) {
+ User user = snmpAgentService.getUserMap().get(securityName);
+ UsmUser usmUser = new UsmUser(userSecurityName,
+ user.getAuthenticationProtocolID(),
+ new OctetString(user.getAuthenticationPassphrase()),
+ user.getPrivacyProtocolID(),
+ new OctetString(user.getPrivacyPassphrase()));
+ Snmp snmp = createSnmpSession(target.getAddress());
+ byte[] authorativeEngine = snmp.discoverAuthoritativeEngineID(target.getAddress(), 8000);
+ if(authorativeEngine != null) {
+ OctetString authorativeEngineID = new OctetString(authorativeEngine);
+ snmp.getUSM().addUser(usmUser.getSecurityName(), authorativeEngineID, usmUser);
+ ((UserTarget)target).setAuthoritativeEngineID(authorativeEngine);
+
+ snmp.send(trap, target);
+ } else {
+ log.warn("Couldn't discover the AuthoritativeEngineID for INFORM notification " + trap);
+ }
+ snmp.close();
+ return;
+ }
+ }
+ }
+ }
+ // Send v2 traps or inform without users
+ snmpAgentService.getSession().send(trap, target);
+ }
+
+
+ /**
+ * Locate mapping applicable for the incoming notification. Key is the
+ * notification's type
+ *
+ * @param n the notification to be examined
+ * @return the index of the mapping
+ * @throws IndexOutOfBoundsException if no mapping found
+ **/
+ private int findMappingIndex(Notification n)
+ throws IndexOutOfBoundsException
+ {
+ // Sequentially check the notification type against the compiled
+ // regular expressions. On first match return the coresponding mapping
+ // index
+ for (int i = 0; i < notificationMapList.size(); i++)
+ {
+ Pattern p = (Pattern) this.mappingRegExpCache.get(i);
- // Iterate over sessions and emit the trap on each one
- Iterator i = this.managers.iterator();
- while (i.hasNext()) {
- ManagerRecord s = (ManagerRecord)i.next();
-
- try {
- switch (s.getVersion()) {
- 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()));
-
- // Advance the trap counter
- this.trapCount.advance();
-
- // Send
- s.getSession().send(v1TrapPdu);
- break;
-
- case SnmpAgentService.SNMPV2:
- if (v2TrapPdu == null)
- v2TrapPdu = this.trapFactory.generateV2Trap(n);
-
- // Advance the trap counter
- this.trapCount.advance();
-
- // Send
- s.getSession().send(v2TrapPdu);
- break;
-
- default:
- log.error("Skipping session: Unknown SNMP version found");
- }
- }
- catch(MappingFailedException e) {
- log.error("Translating notification - " + e.getMessage());
- }
- catch(Exception e) {
- log.error("SNMP send error for " +
- s.getAddress().toString() + ":" +
- s.getPort() + ": <" + e +
- ">");
+ if (p != null)
+ {
+ Matcher m = p.matcher(n.getType());
+
+ if (m.matches())
+ {
+ if (log.isTraceEnabled())
+ log.trace("Match for '" + n.getType() + "' on mapping " + i);
+ return i;
}
- }
+ }
}
+ return -1;
}
/**
@@ -219,7 +315,7 @@
**/
private void load() throws Exception
{
- log.debug("Reading resource: '" + this.managersResName + "'");
+ log.debug("Reading resource: '" + this.snmpAgentService.getManagersResName() + "'");
// configure ObjectModelFactory for mapping XML to POJOs
// we'll be simply getting an ArrayList of Manager objects
@@ -232,7 +328,7 @@
try
{
// locate managers.xml
- final String resName = this.managersResName;
+ final String resName = this.snmpAgentService.getManagersResName();
is = SecurityActions.getThreadContextClassLoaderResource(resName);
// create unmarshaller
@@ -244,7 +340,7 @@
}
catch (Exception e)
{
- log.error("Accessing resource '" + managersResName + "'");
+ log.error("Accessing resource '" + snmpAgentService.getManagersResName() + "'");
throw e;
}
finally
@@ -261,38 +357,140 @@
{
// Read the monitoring manager's particulars
Manager m = (Manager)i.next();
+ fixManagerVersion(m);
+
+ Target target = createTarget(m);
+ if (target == null){
+ log.warn("createTarget: manager m: "+m.toString() + " is null!");
+ continue;
+ }
+
+ // Add the record to the list of monitoring managers. If
+ // successfull open the session to the manager as well.
+ if (this.managers.add(target) == false)
+ {
+ log.warn("Ignoring duplicate manager: " + m);
+ }
+ }
+
+ log.debug("Reading resource: '" + snmpAgentService.getNotificationMapResName() + "'");
+
+ ObjectModelFactory omf = new NotificationBinding();
+ try
+ {
+ // locate notifications.xml
+ final String resName = snmpAgentService.getNotificationMapResName();
+ is = SecurityActions.getThreadContextClassLoaderResource(resName);
+
+ // create unmarshaller
+ Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
- 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()
- );
-
- // 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)
- {
- log.warn("Ignoring duplicate manager: " + m);
- }
- else
- {
- // Open the session to the manager
- mr.openSession();
- }
+ // let JBossXB do it's magic using the MappingObjectModelFactory
+ List<Mapping> notifications = (List<Mapping>)unmarshaller.unmarshal(is, omf, null);
+ log.debug("Found " + notifications.size() + " notification mappings");
+
+ // Initialise the cache with the compiled regular expressions denoting
+ // notification type specifications
+ this.mappingRegExpCache =
+ new ArrayList(notifications.size());
+
+ // Initialise the cache with the instantiated notification wrappers
+ this.notificationWrapperCache =
+ new ArrayList(notifications.size());
+
+ this.notificationMapList =
+ new ArrayList(notifications.size());
+
+ addNotifications(notifications);
+ } catch (Exception e) {
+ log.error("Accessing resource '" + snmpAgentService.getNotificationMapResName() + "'");
+ throw e;
+ } finally {
+ if (is != null) {
+ // close the XML stream
+ is.close();
}
- catch (Exception e)
- {
- log.warn("Error enabling monitoring manager: " + m, e);
- }
- }
+ }
}
+ public void addNotifications(List<Mapping> notifications) {
+ for (Iterator<Mapping> i = notifications.iterator(); i.hasNext();) {
+ Mapping mapping = i.next();
+
+ // Compile and add the regular expression
+ String notificationType = mapping.getNotificationType();
+
+ try {
+ Pattern re = Pattern.compile(notificationType);
+ this.mappingRegExpCache.add(re);
+ } catch (PatternSyntaxException e) {
+ // Fill the slot to keep index count correct
+ this.mappingRegExpCache.add(null);
+
+ log.warn("Error compiling notification mapping for type: "
+ + notificationType, e);
+ }
+
+ // Instantiate and add the wrapper
+ // Read wrapper class name
+ String wrapperClassName = mapping.getVarBindList()
+ .getWrapperClass();
+
+ log.debug("notification wrapper class: " + wrapperClassName);
+
+ try {
+ NotificationWrapper wrapper = (NotificationWrapper) Class
+ .forName(wrapperClassName, true,
+ this.getClass().getClassLoader()).newInstance();
+
+ // Initialise it
+ wrapper.set(snmpAgentService.getClock(),
+ snmpAgentService.getTrapCounter());
+
+ // Add the wrapper to the cache
+ this.notificationWrapperCache.add(wrapper);
+ } catch (Exception e) {
+ // Fill the slot to keep index count correct
+ this.notificationWrapperCache.add(null);
+
+ log.warn("Error compiling notification mapping for type: "
+ + notificationType, e);
+ }
+
+ notificationMapList.add(mapping);
+ }
+ }
+
+ public void removeNotifications(List<Mapping> notifications) {
+ for (Iterator<Mapping> i = notifications.iterator(); i.hasNext();) {
+ Mapping mapping = i.next();
+ notificationMapList.remove(mapping);
+ }
+ }
+
/**
+ * 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);
+ break;
+ case 3:
+ m.setVersion(SnmpConstants.version3);
+ }
+
+ }
+ }
+
+ /**
* cater for possible global -b option, if no override has been specified
*/
private InetAddress toInetAddressWithDefaultBinding(String host)
@@ -310,4 +508,193 @@
return InetAddress.getByName(host);
}
+ private Target createTarget(Manager m){
+ Target target = null;
+
+ int version = m.getVersion();
+ try{
+ if (version == SnmpConstants.version1 || version == SnmpConstants.version2c){
+ 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) {
+ target = new UserTarget();
+ target.setRetries(1);
+ target.setTimeout(8000);
+ target.setAddress(new UdpAddress(InetAddress.getByName(m.getAddress()), m.getPort()));
+ }
+ else {
+ //unrecognized version
+ throw new IllegalArgumentException("version " + version + " is not supported in managers.xml, only 1, 2 and 3 are valid values");
+ }
+ } catch (UnknownHostException e) {
+ log.error("A problem occured creating the target towards " + m.getAddress() + ":" + m.getPort(), 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);
+
+ MessageDispatcherImpl dispatcher = new MessageDispatcherImpl();
+ Snmp snmp = new Snmp(dispatcher, transport);
+ OctetString localEngineID= new OctetString(MPv3.createLocalEngineID());
+ USM usm = new USM(SecurityProtocols.getInstance(), localEngineID, 0);
+ MPv3 mpv3 = new MPv3(usm);
+ dispatcher.addMessageProcessingModel(new MPv2c());
+ dispatcher.addMessageProcessingModel(mpv3);
+
+ snmp.listen();
+
+ return snmp;
+ }
+
+ /**
+ * Utility class used by JBossXB to help parse notifications.xml
+ */
+ private static class NotificationBinding implements
+ GenericObjectModelFactory {
+ // GenericObjectModelFactory implementation ----------------------
+
+ public Object completeRoot(Object root, UnmarshallingContext ctx,
+ String uri, String name) {
+ return root;
+ }
+
+ public Object newRoot(Object root, UnmarshallingContext navigator,
+ String namespaceURI, String localName, Attributes attrs) {
+ ArrayList notifList;
+
+ if (root == null) {
+ root = notifList = new ArrayList();
+ } else {
+ notifList = (ArrayList) root;
+ }
+ return root;
+ }
+
+ public Object newChild(Object parent, UnmarshallingContext navigator,
+ String namespaceURI, String localName, Attributes attrs) {
+ Object child = null;
+
+ if ("mapping".equals(localName)) {
+ Mapping m = new Mapping();
+
+ String notificationType = attrs.getValue("notification-type");
+ String generic = attrs.getValue("generic");
+ String specific = attrs.getValue("specific");
+ String enterprise = attrs.getValue("enterprise");
+ String inform = attrs.getValue("inform");
+ String securityName = attrs.getValue("security-name");
+ m.setNotificationType(notificationType);
+ m.setGeneric(Integer.parseInt(generic));
+ m.setSpecific(Integer.parseInt(specific));
+ m.setEnterprise(enterprise);
+ m.setInform(Boolean.parseBoolean(inform));
+ m.setSecurityName(securityName);
+
+ child = m;
+ } else if ("var-bind-list".equals(localName)) {
+ VarBindList vblist = new VarBindList();
+ child = vblist;
+ if (attrs.getLength() > 0) {
+ for (int i = 0; i < attrs.getLength(); i++) {
+ if ("wrapper-class".equals(attrs.getLocalName(i))) {
+ vblist.setWrapperClass(attrs.getValue(i));
+ }
+ }
+ }
+ // check that wrapper-class is set
+ if (vblist.getWrapperClass() == null) {
+ throw new RuntimeException(
+ "'wrapper-class' must be set at 'var-bind-list' element");
+ }
+ } else if ("var-bind".equals(localName)) {
+ VarBind vb = new VarBind();
+ String oid = attrs.getValue("oid");
+ String tag = attrs.getValue("tag");
+ String type = attrs.getValue("type");
+ vb.setOid(oid);
+ vb.setTag(tag);
+ vb.setType(type);
+
+ child = vb;
+ }
+ return child;
+ }
+
+ public void addChild(Object parent, Object child,
+ UnmarshallingContext navigator, String namespaceURI,
+ String localName) {
+ if (parent instanceof ArrayList) {
+ ArrayList notifList = (ArrayList) parent;
+
+ if (child instanceof Mapping) {
+ notifList.add(child);
+ }
+ } else if (parent instanceof Mapping) {
+ Mapping m = (Mapping) parent;
+
+ if (child instanceof VarBindList) {
+ m.setVarBindList((VarBindList) child);
+ }
+ } else if (parent instanceof VarBindList) {
+ VarBindList vblist = (VarBindList) parent;
+
+ if (child instanceof VarBind) {
+ vblist.addVarBind((VarBind) child);
+ }
+ }
+ }
+
+ public void setValue(Object o, UnmarshallingContext navigator,
+ String namespaceURI, String localName, String value) {
+ if (o instanceof Mapping) {
+ Mapping m = (Mapping) o;
+
+ if ("notification-type".equals(localName)) {
+ m.setNotificationType(value);
+ } else if ("generic".equals(localName)) {
+ m.setGeneric(Integer.parseInt(value));
+ } else if ("specific".equals(localName)) {
+ m.setSpecific(Integer.parseInt(value));
+ } else if ("enterprise".equals(localName)) {
+ m.setEnterprise(value);
+ } else if ("inform".equals(localName)) {
+ m.setInform(Boolean.parseBoolean(value));
+ } else if ("security-name".equals(localName)) {
+ m.setSecurityName(value);
+ }
+ } else if (o instanceof VarBind) {
+ VarBind vb = (VarBind) o;
+
+ if ("tag".equals(localName)) {
+ vb.setTag(value);
+ } else if ("oid".equals(localName)) {
+ vb.setOid(value);
+ }
+ }
+ }
+
+ public Object completedRoot(Object root,
+ UnmarshallingContext navigator, String namespaceURI,
+ String localName) {
+ return root;
+ }
+ }
} // class TrapEmitter
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactory.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,8 +21,10 @@
import javax.management.Notification;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduTrap;
+import org.jboss.jmx.adaptor.snmp.config.notification.Mapping;
+import org.snmp4j.PDUv1;
+import org.snmp4j.PDU;
+import org.snmp4j.ScopedPDU;
/**
* <tt>TrapFactory </tt> takes care of translation of Notifications into
@@ -68,8 +70,10 @@
* Sets the name of the file containing the notification/trap mappings,
* the uptime clock and the trap counter
**/
- public void set(String notificationMapResName, Clock uptime, Counter count);
+ public void set(Clock uptime, Counter count);
+ public void set(Clock uptime, Counter count, RequestHandler rh);
+
/**
* Performs all the required initialisation in order for the mapper to
* commence operation (e.g. reading of the resource file)
@@ -77,20 +81,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, Mapping m, NotificationWrapper wrapper)
+ 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, Mapping m, NotificationWrapper wrapper)
+ 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, Mapping m, NotificationWrapper wrapper)
+ throws MappingFailedException;
} // TrapFactory
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/agent/TrapFactorySupport.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -19,15 +19,8 @@
**/
package org.jboss.jmx.adaptor.snmp.agent;
-import java.io.InputStream;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
import java.util.ArrayList;
-import java.util.Iterator;
import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.regex.PatternSyntaxException;
import javax.management.Notification;
@@ -36,13 +29,15 @@
import org.jboss.jmx.adaptor.snmp.config.notification.VarBindList;
import org.jboss.logging.Logger;
import org.jboss.xb.binding.GenericObjectModelFactory;
-import org.jboss.xb.binding.ObjectModelFactory;
-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.snmp4j.PDU;
+import org.snmp4j.PDUv1;
+import org.snmp4j.ScopedPDU;
+import org.snmp4j.mp.SnmpConstants;
+import org.snmp4j.smi.OID;
+import org.snmp4j.smi.Variable;
+import org.snmp4j.smi.TimeTicks;
+import org.snmp4j.smi.VariableBinding;
import org.xml.sax.Attributes;
/**
@@ -91,24 +86,15 @@
/** Reference to SNMP variable binding factory */
private SnmpVarBindFactory snmpVBFactory = null;
- /** File that contains notification mappings */
- private String notificationMapResName = null;
-
/** Uptime clock */
private Clock clock = null;
/** Trap counter */
- private Counter trapCount = null;
+ private Counter trapCount = null;
- /** Contains the read in mappings */
- private ArrayList notificationMapList = null;
-
- /** Contains the compiled regular expression type specifications */
- private ArrayList mappingRegExpCache = null;
+ /** Request handler ref */
+ private RequestHandler requestHandler = null;
- /** Contains instances of the notification wrappers */
- private ArrayList notificationWrapperCache = null;
-
/**
* Create TrapFactorySupport
**/
@@ -121,13 +107,17 @@
* Sets the name of the file containing the notification/trap mappings,
* the uptime clock and the trap counter
**/
- public void set(String notificationMapResName, Clock clock, Counter count)
+ public void set(Clock clock, Counter count)
{
- this.notificationMapResName = notificationMapResName;
this.clock = clock;
this.trapCount = count;
}
+ public void set(Clock clock, Counter count, RequestHandler rh){
+ this.clock = clock;
+ this.trapCount = count;
+ this.requestHandler = rh;
+ }
/**
* Populates the regular expression and wrapper instance collections. Note
* that a failure (e.g. to compile a regular expression or to instantiate a
@@ -140,169 +130,33 @@
public void start()
throws Exception
{
- log.debug("Reading resource: '" + notificationMapResName + "'");
- ObjectModelFactory omf = new NotificationBinding();
- InputStream is = null;
- try
- {
- // locate notifications.xml
- final String resName = notificationMapResName;
- is = SecurityActions.getThreadContextClassLoaderResource(resName);
-
- // create unmarshaller
- Unmarshaller unmarshaller = UnmarshallerFactory.newInstance().newUnmarshaller();
-
- // let JBossXB do it's magic using the MappingObjectModelFactory
- this.notificationMapList = (ArrayList)unmarshaller.unmarshal(is, omf, null);
- }
- catch (Exception e)
- {
- log.error("Accessing resource '" + notificationMapResName + "'");
- throw e;
- }
- finally
- {
- if (is != null)
- {
- // close the XML stream
- is.close();
- }
- }
- log.debug("Found " + notificationMapList.size() + " notification mappings");
-
- // Initialise the cache with the compiled regular expressions denoting
- // notification type specifications
- this.mappingRegExpCache =
- new ArrayList(notificationMapList.size());
-
- // Initialise the cache with the instantiated notification wrappers
- this.notificationWrapperCache =
- new ArrayList(notificationMapList.size());
-
- for (Iterator i = notificationMapList.iterator(); i.hasNext(); )
- {
- Mapping mapping = (Mapping)i.next();
-
- // Compile and add the regular expression
- String notificationType = mapping.getNotificationType();
-
- try
- {
- Pattern re = Pattern.compile(notificationType);
- this.mappingRegExpCache.add(re);
- }
- catch (PatternSyntaxException e)
- {
- // Fill the slot to keep index count correct
- this.mappingRegExpCache.add(null);
-
- log.warn("Error compiling notification mapping for type: " + notificationType, e);
- }
-
- // Instantiate and add the wrapper
- // Read wrapper class name
- String wrapperClassName = mapping.getVarBindList().getWrapperClass();
-
- log.debug("notification wrapper class: " + wrapperClassName);
-
- try
- {
- NotificationWrapper wrapper =
- (NotificationWrapper)Class.forName(wrapperClassName, true, this.getClass().getClassLoader()).newInstance();
-
- // Initialise it
- wrapper.set(this.clock, this.trapCount);
-
- // Add the wrapper to the cache
- this.notificationWrapperCache.add(wrapper);
- }
- catch (Exception e)
- {
- // Fill the slot to keep index count correct
- this.notificationWrapperCache.add(null);
-
- log.warn("Error compiling notification mapping for type: " + notificationType, e);
- }
- }
log.debug("Trap factory going active");
}
/**
- * Locate mapping applicable for the incoming notification. Key is the
- * notification's type
- *
- * @param n the notification to be examined
- * @return the index of the mapping
- * @throws IndexOutOfBoundsException if no mapping found
- **/
- private int findMappingIndex(Notification n)
- throws IndexOutOfBoundsException
- {
- // Sequentially check the notification type against the compiled
- // regular expressions. On first match return the coresponding mapping
- // index
- for (int i = 0; i < notificationMapList.size(); i++)
- {
- Pattern p = (Pattern) this.mappingRegExpCache.get(i);
-
- if (p != null)
- {
- Matcher m = p.matcher(n.getType());
-
- if (m.matches())
- {
- if (log.isTraceEnabled())
- log.trace("Match for '" + n.getType() + "' on mapping " + i);
- return i;
- }
- }
- }
- // Signal "no mapping found"
- throw new IndexOutOfBoundsException();
- }
-
- /**
* Traslates a Notification to an SNMP V1 trap.
**/
- public SnmpPduTrap generateV1Trap(Notification n)
+ public PDUv1 generateV1Trap(Notification n, Mapping m, NotificationWrapper wrapper)
throws MappingFailedException
{
if (log.isTraceEnabled())
- log.trace("generateV1Trap");
+ log.trace("generateV1Trap");
- // 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
- 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
- // values
-
- // Get the coresponding wrapper to get access to notification payload
- NotificationWrapper wrapper =
- (NotificationWrapper)this.notificationWrapperCache.get(index);
+ // values
if(wrapper != null)
{
@@ -316,14 +170,34 @@
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.addVarBind(
- this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+
+ if (vb.getTag().matches("^a:.*")){
+ OID oid = new OID(vb.getOid()+".0");
+ Variable var;
+ try{
+ var = requestHandler.getValueFor(oid);
+ }
+ catch (Exception e){
+ var = null;
+ }
+
+ if (var != null){
+ trapPdu.add(new VariableBinding(oid, var));
+ }
+ else { // we failed to find the variable with given oid here. we fall back onto the wrapper.
+ trapPdu.add(
+ this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ }
+ }
+ else{
+ // 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
@@ -336,42 +210,32 @@
}
/**
- * 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, Mapping m, NotificationWrapper wrapper)
throws MappingFailedException
{
if (log.isTraceEnabled())
- log.trace("generateV2Trap");
-
- // 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);
+ log.trace("generateV2cTrap");
// Create trap
- SnmpPduRequest trapPdu = new SnmpPduRequest(SnmpPduPacket.V2TRAP);
+ PDU trapPdu = new PDU();
+ if(m.isInform()) {
+ trapPdu.setType(ScopedPDU.INFORM);
+ } else {
+ trapPdu.setType(ScopedPDU.TRAP);
+ }
+ // Those 2 Variable Bindings are mandatory for v2c and v3 traps and inform
+ trapPdu.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(this.clock.uptime())));
+ // For generic traps, values are defined in RFC 1907, for vendor specific traps snmpTrapOID is essentially a concatenation of the SNMPv1 Enterprise parameter and two additional sub-identifiers, '0', and the SNMPv1 Specific trap code parameter.
+ trapPdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(m.getEnterprise() + ".0." + m.getSpecific())));
+
// 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
@@ -381,15 +245,35 @@
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.addVarBind(
- this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ VarBind vb = (VarBind)vbList.get(i);
+
+ if (vb.getTag().matches("^a:.*")){
+ OID oid = new OID(vb.getOid()+".0");
+ Variable var;
+ try{
+ var = requestHandler.getValueFor(oid);
+ }
+ catch (Exception e){
+ var = null;
+ }
+
+ if (var != null){
+ trapPdu.add(new VariableBinding(oid, var));
+ }
+ else { // we failed to find the variable with given oid here. we fall back onto the wrapper.
+ trapPdu.add(
+ this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ }
+ }
+ else{
+ // 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
@@ -401,147 +285,74 @@
}
/**
- * Utility class used by JBossXB to help parse notifications.xml
- */
- private static class NotificationBinding implements GenericObjectModelFactory
+ * 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, Mapping m, NotificationWrapper wrapper)
+ throws MappingFailedException
{
- // GenericObjectModelFactory implementation ----------------------
-
- public Object completeRoot(Object root, UnmarshallingContext ctx,
- String uri, String name)
- {
- return root;
- }
-
- public Object newRoot(Object root, UnmarshallingContext navigator, String namespaceURI,
- String localName, Attributes attrs)
- {
- ArrayList notifList;
-
- if (root == null)
- {
- root = notifList = new ArrayList();
- }
- else
- {
- notifList = (ArrayList) root;
- }
- return root;
- }
+ if (log.isTraceEnabled())
+ log.trace("generateV3Trap");
+
+ // Create trap
+ ScopedPDU trapPdu = new ScopedPDU();
+ if(m.isInform()) {
+ trapPdu.setType(ScopedPDU.INFORM);
+ } else {
+ trapPdu.setType(ScopedPDU.TRAP);
+ }
- public Object newChild(Object parent, UnmarshallingContext navigator, String namespaceURI,
- String localName, Attributes attrs)
- {
- Object child = null;
-
- if ("mapping".equals(localName))
- {
- Mapping m = new Mapping();
- child = m;
- }
- else if ("var-bind-list".equals(localName))
- {
- VarBindList vblist = new VarBindList();
- child = vblist;
- if (attrs.getLength() > 0)
- {
- for (int i = 0; i < attrs.getLength(); i++)
- {
- if ("wrapper-class".equals(attrs.getLocalName(i)))
- {
- vblist.setWrapperClass(attrs.getValue(i));
- }
- }
- }
- // check that wrapper-class is set
- if (vblist.getWrapperClass() == null)
- {
- throw new RuntimeException("'wrapper-class' must be set at 'var-bind-list' element");
- }
- }
- else if ("var-bind".equals(localName))
- {
- VarBind vb = new VarBind();
- child = vb;
- }
- return child;
- }
-
- public void addChild(Object parent, Object child, UnmarshallingContext navigator,
- String namespaceURI, String localName)
- {
- if (parent instanceof ArrayList)
- {
- ArrayList notifList = (ArrayList)parent;
-
- if (child instanceof Mapping)
- {
- notifList.add(child);
- }
- }
- else if (parent instanceof Mapping)
- {
- Mapping m = (Mapping)parent;
-
- if (child instanceof VarBindList)
- {
- m.setVarBindList((VarBindList)child);
- }
- }
- else if (parent instanceof VarBindList)
- {
- VarBindList vblist = (VarBindList)parent;
-
- if (child instanceof VarBind)
- {
- vblist.addVarBind((VarBind)child);
- }
- }
- }
-
- public void setValue(Object o, UnmarshallingContext navigator, String namespaceURI,
- String localName, String value)
- {
- if (o instanceof Mapping)
- {
- Mapping m = (Mapping)o;
-
- if ("notification-type".equals(localName))
- {
- m.setNotificationType(value);
- }
- else if ("generic".equals(localName))
- {
- m.setGeneric(Integer.parseInt(value));
- }
- else if ("specific".equals(localName))
- {
- m.setSpecific(Integer.parseInt(value));
- }
- else if ("enterprise".equals(localName))
- {
- m.setEnterprise(value);
- }
- }
- else if (o instanceof VarBind)
- {
- VarBind vb = (VarBind)o;
-
- if ("tag".equals(localName))
- {
- vb.setTag(value);
- }
- else if ("oid".equals(localName))
- {
- vb.setOid(value);
- }
- }
- }
-
- public Object completedRoot(Object root, UnmarshallingContext navigator, String namespaceURI, String localName)
- {
- return root;
- }
+ // Those 2 Variable Bindings are mandatory for v2c and v3 traps and inform
+ trapPdu.add(new VariableBinding(SnmpConstants.sysUpTime, new TimeTicks(this.clock.uptime())));
+ // For generic traps, values are defined in RFC 1907, for vendor specific traps snmpTrapOID is essentially a concatenation of the SNMPv1 Enterprise parameter and two additional sub-identifiers, '0', and the SNMPv1 Specific trap code parameter.
+ trapPdu.add(new VariableBinding(SnmpConstants.snmpTrapOID, new OID(m.getEnterprise() + ".0." + m.getSpecific())));
+
+ // Append the specified varbinds. Get varbinds from mapping and for
+ // each one of the former use the wrapper to get data from the
+ // notification
+ 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);
+
+ if (vb.getTag().matches("^a:.*")){
+ OID oid = new OID(vb.getOid()+".0");
+ Variable var;
+ try{
+ var = requestHandler.getValueFor(oid);
+ }
+ catch (Exception e){
+ var = null;
+ }
+
+ if (var != null){
+ trapPdu.add(new VariableBinding(oid, var));
+ }
+ else { // we failed to find the variable with given oid here. we fall back onto the wrapper.
+ trapPdu.add(
+ this.snmpVBFactory.make(vb.getOid(), wrapper.get(vb.getTag())));
+ }
+ }
+ else{
+ // 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;
}
} // class TrapFactorySupport
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/AttributeMappings.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/AttributeMappings.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/AttributeMappings.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -22,8 +22,6 @@
package org.jboss.jmx.adaptor.snmp.config.attribute;
import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
/**
* List of mbean attribute mappings to snmp oids.
@@ -31,22 +29,9 @@
* @author Heiko W. Rupp <pilhuhn at user.sf.net>
* @version $Revision$
*/
-public class AttributeMappings
-{
- private List mbeans = new ArrayList();
-
- public void addMonitoredMBean(ManagedBean mbean)
- {
- mbeans.add(mbean);
+public class AttributeMappings extends ArrayList<ManagedBean> {
+
+ public void addMonitoredMBean(ManagedBean mbean) {
+ add(mbean);
}
-
- public Iterator iterator()
- {
- return mbeans.iterator();
- }
-
- public int size()
- {
- return mbeans.size();
- }
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/ManagedBean.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/ManagedBean.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/ManagedBean.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,53 +21,69 @@
*/
package org.jboss.jmx.adaptor.snmp.config.attribute;
-import java.util.ArrayList;
import java.util.List;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
/**
* ManagedBean holding list of MappedAttributes
*
* @author Heiko W. Rupp <pilhuhn at user.sf.net>
* @version $Release:$
*/
-public class ManagedBean
-{
+public class ManagedBean {
private String name;
private String oidPrefix;
- private List attributes = new ArrayList();
-
- public List getAttributes()
- {
+ private String oidDefinition;
+ private List<MappedAttribute> attributes;
+
+ /**
+ * Default CTOR
+ */
+ public ManagedBean() {
+ // empty
+ }
+
+ public List<MappedAttribute> getAttributes() {
return attributes;
}
-
- public void setAttributes(List attributes)
- {
+
+ @XmlElement(name="attribute")
+ public void setAttributes(List<MappedAttribute> attributes) {
this.attributes = attributes;
}
-
- public String getName()
- {
+
+ public String getName() {
return name;
}
-
- public void setName(String name)
- {
+
+ @XmlAttribute(name="name")
+ public void setName(String name) {
this.name = name;
}
-
- public String getOidPrefix()
- {
+
+ public String getOidPrefix() {
return oidPrefix;
}
-
- public void setOidPrefix(String oid_prefix)
- {
+
+ @XmlAttribute(name="oid-prefix")
+ public void setOidPrefix(String oid_prefix) {
this.oidPrefix = oid_prefix;
}
- public String toString()
- {
+ public String getOidDefinition()
+ {
+ return oidDefinition;
+ }
+
+ @XmlAttribute(name="definition-name")
+ public void setOidDefinition(String oidDefinition)
+ {
+ this.oidDefinition = oidDefinition;
+ }
+
+ public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[name=").append(name);
buf.append(", oidPrefix=").append(oidPrefix);
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/attribute/MappedAttribute.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,53 +21,123 @@
*/
package org.jboss.jmx.adaptor.snmp.config.attribute;
+import javax.xml.bind.annotation.XmlAttribute;
+
/**
- * An attribute mapping, by default readonly.
+ * An attribute mapping, by default readonly, and a blank description
*
* @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 String mode;
+ private boolean isReadWrite = false;
+ private String table;
+ private boolean isAttributeTable = false;
+ private String mbName = ""; //the name of the mBean this MappedAttribute is associated with
+ private String snmpType = ""; //the type for the MIB we should use, if provided
+ private String oidPrefix = "";
+ private String oidDefName = "";
+
+ public MappedAttribute() {
+ }
+
/** Attribute name */
- public String getName()
- {
+ public String getName() {
return name;
}
-
- public void setName(String name)
- {
+
+ @XmlAttribute(name="name")
+ public void setName(String name) {
this.name = name;
}
-
+
/** Attribute oid */
- public String getOid()
- {
+ public String getOid() {
return oid;
}
-
- public void setOid(String oid)
- {
+
+ @XmlAttribute(name="oid")
+ public void setOid(String oid) {
this.oid = oid;
}
- /** Attribute mode (ro/rw) */
- public boolean isReadWrite()
- {
- return isReadWrite;
- }
-
- public void setReadWrite(boolean mode)
- {
- isReadWrite = mode;
- }
-
- public String toString()
- {
+ /** Attribute mode (ro/rw) */
+ public boolean isReadWrite() {
+ return isReadWrite;
+ }
+
+ /** Attribute mode (ro/rw) */
+ public String getMode() {
+ return mode;
+ }
+
+ @XmlAttribute(name="mode")
+ public void setMode(String mode) {
+ this.mode = mode;
+ if(mode != null && mode.equalsIgnoreCase("rw")) {
+ isReadWrite = true;
+ }
+ }
+ /** Attribute table */
+ public boolean isAttributeTable() {
+ return isAttributeTable;
+ }
+
+ /** Attribute table */
+ public String getTable() {
+ return table;
+ }
+
+ @XmlAttribute(name="table")
+ public void setTable(String table) {
+ this.table = table;
+ if(table != null && Boolean.valueOf(table)) {
+ isAttributeTable = true;
+ }
+ }
+
+ public String getMbean(){
+ return this.mbName;
+ }
+
+ @XmlAttribute(name="name")
+ public void setMbean(String mbName){
+ this.mbName = mbName;
+ }
+
+ public String getSnmpType(){
+ return this.snmpType;
+ }
+
+ public void setSnmpType(String snmpType){
+ this.snmpType=snmpType;
+ }
+
+ public String getOidPrefix(){
+ return this.oidPrefix;
+ }
+
+ public void setOidPrefix(String oidPrefix){
+ if (oidPrefix.charAt(0) == '.')
+ this.oidPrefix = oidPrefix.substring(1);
+ else
+ this.oidPrefix = oidPrefix;
+ }
+
+ public String getOidDefName(){
+ return this.oidDefName;
+ }
+
+ public void setOidDefName(String oidDefName){
+ this.oidDefName = oidDefName;
+ }
+
+ public String toString() {
StringBuffer buf = new StringBuffer();
buf.append("[name=").append(name);
buf.append(", oid=").append(oid);
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/manager/Manager.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -23,7 +23,11 @@
/**
* Simple POJO class to model XML data
+ * We need to have additional fields in this class for possible v3 support.
+ * A User Name and Password for the USM need to be added. see RFC-3414.
+ * Without this being added to the manager, v3 PDUs (ScopedPDU) will never be accepted by the agent.
*
+ *
* @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
*
* @version $Revision$
@@ -37,6 +41,7 @@
private String localAddress;
private int localPort;
private int version;
+ private String communityString;
// Constructors -------------------------------------------------
@@ -102,6 +107,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 +168,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 +190,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: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/Mapping.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/Mapping.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/Mapping.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,6 +21,9 @@
*/
package org.jboss.jmx.adaptor.snmp.config.notification;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
/**
* Simple POJO class to model XML data
*
@@ -30,90 +33,114 @@
*/
public class Mapping
{
- // Private Data --------------------------------------------------
+ private String notificationType;
+ private int generic;
+ private int specific;
+ private String enterprise;
+ private boolean inform;
+ private String securityName;
+ private VarBindList varBindList;
- private String notificationType;
- private int generic;
- private int specific;
- private String enterprise;
- private VarBindList varBindList;
+ // Constructors -------------------------------------------------
- // Constructors -------------------------------------------------
-
- /**
- * Default CTOR
- */
- public Mapping()
- {
- // empty
- }
+ /**
+ * Default CTOR
+ */
+ public Mapping() {
+ // empty
+ }
- // Accessors/Modifiers -------------------------------------------
-
- public String getEnterprise()
- {
- return enterprise;
- }
+ // Accessors/Modifiers -------------------------------------------
- public int getGeneric()
- {
- return generic;
- }
+ public String getEnterprise() {
+ return enterprise;
+ }
- public String getNotificationType()
- {
- return notificationType;
- }
+ public int getGeneric() {
+ return generic;
+ }
- public int getSpecific()
- {
- return specific;
- }
+ public String getNotificationType() {
+ return notificationType;
+ }
- public VarBindList getVarBindList()
- {
- return varBindList;
- }
+ public int getSpecific() {
+ return specific;
+ }
- public void setEnterprise(String enterprise)
- {
- this.enterprise = enterprise;
- }
+ public VarBindList getVarBindList() {
+ return varBindList;
+ }
+
+ @XmlAttribute(name="enterprise")
+ public void setEnterprise(String enterprise) {
+ this.enterprise = enterprise;
+ }
- public void setGeneric(int generic)
- {
- this.generic = generic;
- }
-
- public void setNotificationType(String notificationType)
- {
- this.notificationType = notificationType;
- }
+ @XmlAttribute(name="generic")
+ public void setGeneric(int generic) {
+ this.generic = generic;
+ }
- public void setSpecific(int specific)
- {
- this.specific = specific;
- }
+ @XmlAttribute(name="notification-type")
+ public void setNotificationType(String notificationType) {
+ this.notificationType = notificationType;
+ }
- public void setVarBindList(VarBindList varBindList)
- {
- this.varBindList = varBindList;
- }
-
- // Object overrides ----------------------------------------------
-
- public String toString()
- {
- StringBuffer sbuf = new StringBuffer(256);
-
- sbuf.append('[')
- .append("notificationType=").append(notificationType)
- .append(", generic=").append(generic)
- .append(", specific=").append(specific)
- .append(", enterprise=").append(enterprise)
- .append(", varBindList=").append(varBindList)
- .append(']');
-
- return sbuf.toString();
- }
+ @XmlAttribute(name="specific")
+ public void setSpecific(int specific) {
+ this.specific = specific;
+ }
+
+ @XmlElement(name="var-bind-list")
+ public void setVarBindList(VarBindList varBindList) {
+ this.varBindList = varBindList;
+ }
+
+ /**
+ * @param inform
+ * the inform to set
+ */
+ @XmlAttribute(name="inform")
+ public void setInform(boolean inform) {
+ this.inform = inform;
+ }
+
+ /**
+ * @return the inform
+ */
+ public boolean isInform() {
+ return inform;
+ }
+
+ /**
+ * @param securityName
+ * the securityName to set
+ */
+ @XmlAttribute(name="security-name")
+ public void setSecurityName(String securityName) {
+ this.securityName = securityName;
+ }
+
+ /**
+ * @return the securityName
+ */
+ public String getSecurityName() {
+ return securityName;
+ }
+
+ // Object overrides ----------------------------------------------
+
+ public String toString() {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[').append("notificationType=").append(notificationType)
+ .append(", generic=").append(generic).append(", specific=")
+ .append(specific).append(", enterprise=").append(enterprise)
+ .append(", inform=").append(inform).append(", securityName=")
+ .append(securityName).append(", varBindList=")
+ .append(varBindList).append(']');
+
+ return sbuf.toString();
+ }
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBind.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBind.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBind.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,6 +21,8 @@
*/
package org.jboss.jmx.adaptor.snmp.config.notification;
+import javax.xml.bind.annotation.XmlAttribute;
+
/**
* Simple POJO class to model XML data
*
@@ -28,56 +30,63 @@
*
* @version $Revision$
*/
-public class VarBind
-{
- // Private Data --------------------------------------------------
+public class VarBind {
+ // Private Data --------------------------------------------------
- private String tag;
- private String oid;
+ private String tag;
+ private String oid;
+ private String type;
- // Constructors -------------------------------------------------
-
- /**
- * Default CTOR
- */
- public VarBind()
- {
- // empty
- }
+ // Constructors -------------------------------------------------
- // Accessors/Modifiers -------------------------------------------
-
- public String getOid()
- {
- return oid;
- }
+ /**
+ * Default CTOR
+ */
+ public VarBind() {
+ // empty
+ }
- public String getTag()
- {
- return tag;
- }
+ // Accessors/Modifiers -------------------------------------------
- public void setOid(String oid)
- {
- this.oid = oid;
- }
-
- public void setTag(String tag)
- {
- this.tag = tag;
- }
+ public String getOid() {
+ return oid;
+ }
- // Object overrides ----------------------------------------------
-
- public String toString()
- {
- StringBuffer sbuf = new StringBuffer(256);
-
- sbuf.append('[')
- .append("tag=").append(tag)
- .append(", oid=").append(oid)
- .append(']');
-
- return sbuf.toString();
- }
+ public String getTag() {
+ return tag;
+ }
+
+ @XmlAttribute(name = "oid")
+ public void setOid(String oid) {
+ this.oid = oid;
+ }
+
+ @XmlAttribute(name = "tag")
+ public void setTag(String tag) {
+ this.tag = tag;
+ }
+
+ @XmlAttribute(name = "type")
+ public void setType(String type) {
+ this.type = type;
+ }
+
+ /**
+ * @return the type
+ */
+ public String getType() {
+ return type;
+ }
+
+ // Object overrides ----------------------------------------------
+
+ public String toString() {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[').append("tag=").append(tag).append(", oid=")
+ .append(oid).append(", type=")
+ .append(type).append(']');
+
+ return sbuf.toString();
+ }
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBindList.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBindList.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/config/notification/VarBindList.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -24,6 +24,9 @@
import java.util.ArrayList;
import java.util.List;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+
/**
* Simple POJO class to model XML data
*
@@ -31,61 +34,53 @@
*
* @version $Revision$
*/
-public class VarBindList
-{
- // Private Data --------------------------------------------------
+public class VarBindList {
+ // Private Data --------------------------------------------------
- private String wrapperClass;
- private List varBindList = new ArrayList();
+ private String wrapperClass = "org.jboss.jmx.adaptor.snmp.agent.NotificationWrapperSupport";
+ private List<VarBind> varBindList = new ArrayList<VarBind>();
- // Constructors -------------------------------------------------
-
- /**
- * Default CTOR
- */
- public VarBindList()
- {
- // empty
- }
+ // Constructors -------------------------------------------------
- // Accessors/Modifiers -------------------------------------------
+ /**
+ * Default CTOR
+ */
+ public VarBindList() {
+ // empty
+ }
- public String getWrapperClass()
- {
- return wrapperClass;
- }
-
- public List getVarBindList()
- {
- return varBindList;
- }
-
- public void setWrapperClass(String wrapperClass)
- {
- this.wrapperClass = wrapperClass;
- }
-
- public void setVarBindList(List varBindList)
- {
- this.varBindList = varBindList;
- }
-
- public void addVarBind(VarBind varBind)
- {
- varBindList.add(varBind);
- }
+ // Accessors/Modifiers -------------------------------------------
- // Object overrides ----------------------------------------------
-
- public String toString()
- {
- StringBuffer sbuf = new StringBuffer(256);
-
- sbuf.append('[')
- .append("wrapperClass=").append(wrapperClass)
- .append(", varBindList=").append(varBindList)
- .append(']');
-
- return sbuf.toString();
- }
+ public String getWrapperClass() {
+ return wrapperClass;
+ }
+
+ public List<VarBind> getVarBindList() {
+ return varBindList;
+ }
+
+ @XmlAttribute(name = "wrapper-class")
+ public void setWrapperClass(String wrapperClass) {
+ this.wrapperClass = wrapperClass;
+ }
+
+ @XmlElement(name = "var-bind")
+ public void setVarBindList(List<VarBind> varBindList) {
+ this.varBindList = varBindList;
+ }
+
+ public void addVarBind(VarBind child) {
+ this.varBindList.add(child);
+ }
+
+ // Object overrides ----------------------------------------------
+
+ public String toString() {
+ StringBuffer sbuf = new StringBuffer(256);
+
+ sbuf.append('[').append("wrapperClass=").append(wrapperClass)
+ .append(", varBindList=").append(varBindList).append(']');
+
+ return sbuf.toString();
+ }
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupService.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -27,8 +27,8 @@
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.snmp4j.smi.OID;
+import org.snmp4j.smi.TimeTicks;
/**
* An MBean service that defines the MIB-2 system group an agent
@@ -45,19 +45,21 @@
{
// Constants -----------------------------------------------------
- /** JBoss OID Prefix */
- public static final String JBOSS_PREFIX = "1.3.6.1.4.1.18016";
+ /** JBoss OID Prefix http://www.wtcs.org/snmp4tpc/snmp.htm
+ 2312 is red hat prefix from http://www.oid-info.com/get/1.3.6.1.4.1.2312
+ we define 100 arbitrary as the JBoss division
+ */
+
+ public static final String JBOSS_PREFIX = "1.3.6.1.4.1.2312.100";
- /** Product JBossAS */
- public static final String PRODUCT = ".1.1";
+ // Private Data --------------------------------------------------
+
+ // JBoss AS product is 1
+ private String product;
+ private String version;
- /** Version 4.0.x */
- public static final String VERSION = ".2";
-
- // 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
@@ -76,7 +78,39 @@
}
// Attributes ----------------------------------------------------
-
+
+ /**
+ * @param product the product to set
+ * @jmx:managed-attribute
+ */
+ public void setProduct(String product) {
+ this.product = product;
+ }
+
+ /**
+ * @return the product
+ * @jmx:managed-attribute
+ */
+ public String getProduct() {
+ return product;
+ }
+
+ /**
+ * @param version the product version to set
+ * @jmx:managed-attribute
+ */
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ /**
+ * @return the product version
+ * @jmx:managed-attribute
+ */
+ public String getVersion() {
+ return version;
+ }
+
/**
* @jmx:managed-attribute
*/
@@ -112,7 +146,7 @@
/**
* @jmx:managed-attribute
*/
- public SnmpObjectId getSysObjectId()
+ public OID getSysObjectId()
{
return sysObjectId;
}
@@ -121,14 +155,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 +170,7 @@
}
}
// fallback
- return new SnmpTimeTicks(System.currentTimeMillis() / 10);
+ return new TimeTicks(System.currentTimeMillis() / 10);
}
/**
@@ -205,11 +239,12 @@
String serverConfig = ServerConfigLocator.locate().getServerName();
ObjectName name = new ObjectName(ServerInfoMBean.OBJECT_NAME_STR);
String hostAddress = (String)server.getAttribute(name, "HostAddress");
-
+
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: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/system/MIB2SystemGroupServiceMBean.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -25,8 +25,8 @@
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.snmp4j.smi.OID;
+import org.snmp4j.smi.TimeTicks;
/**
* MIB2SystemGroupService MBean interface
@@ -41,7 +41,12 @@
ObjectName OBJECT_NAME = ObjectNameFactory.create("jboss.jmx:name=SnmpAgent,service=MIB2SystemGroup");
// Attributes ----------------------------------------------------
-
+ void setProduct(String product);
+ String getProduct();
+
+ void setVersion(String version);
+ String getVersion();
+
/** The snmp agent */
void setSnmpAgent(ObjectName agent);
ObjectName getSnmpAgent();
@@ -51,10 +56,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: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerService.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -19,9 +19,28 @@
**/
package org.jboss.jmx.adaptor.snmp.test;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Vector;
+
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 +59,12 @@
extends ServiceMBeanSupport
implements NotificationProducerServiceMBean
{
+
+ /** 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";
+
/**
* Sends a test Notification of type "V1"
*
@@ -48,8 +73,10 @@
public void sendV1()
throws Exception
{
- sendNotification(
- new Notification("V1", this, getNextNotificationSequenceNumber(),
+ log.debug("Sending SnmpV1 test notification");
+
+ sendNotification(
+ new Notification(V1_TEST_NOTIFICATION, this, getNextNotificationSequenceNumber(),
"V1 test notifications"));
}
@@ -61,10 +88,210 @@
public void sendV2()
throws Exception
{
- sendNotification(
- new Notification("V2", this, getNextNotificationSequenceNumber(),
+ log.debug("Sending SnmpV2 test notification");
+ sendNotification(
+ new Notification(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(V3_TEST_NOTIFICATION, this, getNextNotificationSequenceNumber(),
+ "V3 test notifications"));
+ }
+
+ public void getBulk(){
+ log.debug("Executing 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(2);
+ target.setTimeout(2000);
+
+ try {
+ DefaultUdpTransportMapping transport = new DefaultUdpTransportMapping();
+ transport.listen();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ 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 GETNEXT request
+ */
+ public void getNext(){
+ PDU pdu = new PDU();
+ pdu.setType(PDU.GETNEXT);
+ pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.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);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ 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.3.6.1.2.1.1.4")));
+
+ CommunityTarget target = new CommunityTarget();
+ target.setCommunity(new OctetString("public"));
+ 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);
+ ResponseEvent responseEvent = snmp.send(pdu, target);
+ 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 "+response);
+ }
+ System.out.println("Peer Address: "+responseEvent.getPeerAddress());
+ System.out.println("responsePdu = " + responsePDU);
+
+ } catch (UnknownHostException e1) {
+ e1.printStackTrace();
+ } catch (IOException e1) {
+ e1.printStackTrace();
+ } catch (Exception e) {
+ System.out.println("Some Other exception!!" + e);
+ }
+
+ }
+
+ /**
+ * Sends a test SET request
+ *
+ * @jmx:managed-operation
+ */
+ public void set(){
+ PDU pdu = new PDU();
+ pdu.add(new VariableBinding(new OID("1.3.6.1.2.1.1.1"), new OctetString("MBean Set Test")));
+
+ 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();
+ System.out.println("READY: "+System.currentTimeMillis());
+ Snmp snmp = new Snmp(transport);
+ ResponseEvent responseEvent = snmp.set(pdu, target);
+ 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!!");
+ }
+
+
+ }
+
} // class NotificationProducerService
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/test/NotificationProducerServiceMBean.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -35,5 +35,30 @@
* 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 GETBULK
+ */
+ void getBulk();
+
+ /**
+ * Sends a test SNMP GETNEXT
+ */
+ void getNext();
+ /**
+ * Sends a test SNMP SET
+ */
+ void set();
+
}
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapReceiver.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -22,13 +22,6 @@
import java.net.InetAddress;
import org.jboss.logging.Logger;
-import org.opennms.protocols.snmp.SnmpOctetString;
-import org.opennms.protocols.snmp.SnmpPduPacket;
-import org.opennms.protocols.snmp.SnmpPduRequest;
-import org.opennms.protocols.snmp.SnmpPduTrap;
-import org.opennms.protocols.snmp.SnmpTrapHandler;
-import org.opennms.protocols.snmp.SnmpTrapSession;
-import org.opennms.protocols.snmp.SnmpVarBind;
/**
* Implements an SNMP trap reception engine
@@ -39,7 +32,6 @@
* @author <a href="mailto:dimitris at jboss.org">Dimitris Andreadis</a>
**/
public class TrapReceiver
- implements SnmpTrapHandler
{
/** target logger */
protected final Logger log;
@@ -54,114 +46,114 @@
this.log = log;
}
- /**
- * Receives and logs information about SNMPv2 traps.
- *
- * @param session the trap session that received the PDU
- * @param agent the address of the remote sender
- * @param port the remote port where the pdu was transmitted from
- * @param community the decoded community string
- * @param pdu the decoded v2 trap pdu
- **/
- public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent,
- int port, SnmpOctetString community,
- SnmpPduPacket pdu)
- {
- StringBuffer sbuf = new StringBuffer();
-
- sbuf.append("V2 Trap from ").append(agent.toString());
- sbuf.append(" on port ").append(port);
- sbuf.append("\nPDU command......... ").append(pdu.getCommand());
- sbuf.append("\nPDU Length.......... ").append(pdu.getLength());
- sbuf.append("\nCommunity string.... ").append(community.toString());
-
- if(pdu instanceof SnmpPduRequest)
- {
- SnmpPduRequest spdu = (SnmpPduRequest) pdu;
-
- sbuf.append("\nPDU Error Status.... ").append(spdu.getErrorStatus());
- sbuf.append("\nPDU Error Index..... ").append(spdu.getErrorIndex());
- sbuf.append("\n");
- }
-
- for (int i = 0; i < pdu.getLength(); i++ )
- {
- SnmpVarBind vb = pdu.getVarBindAt(i);
-
- sbuf.append("Varbind[").append(i).append("] := ");
- sbuf.append(vb.getName().toString()).append(" --> ");
- sbuf.append(vb.getValue().toString()).append("\n");
- }
- log.debug(sbuf.toString());
- } // snmpReceivedTrap
-
- /**
- * Receives and logs information about SNMPv1 traps.
- *
- * @param session the trap session that received the PDU
- * @param agent the address of the remote sender
- * @param port the remote port where the pdu was transmitted from
- * @param community the decoded community string
- * @param pdu the decoded v1 trap pdu
- **/
- public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent,
- int port, SnmpOctetString community,
- SnmpPduTrap pdu)
- {
- StringBuffer sbuf = new StringBuffer();
-
- sbuf.append("V1 Trap from agent ").append(agent.toString());
- sbuf.append(" on port ").append(port);
- sbuf.append("\nIP Address......... ").append(pdu.getAgentAddress());
- sbuf.append("\nEnterprise Id...... ").append(pdu.getEnterprise());
- sbuf.append("\nGeneric ........... ").append(pdu.getGeneric());
- sbuf.append("\nSpecific .......... ").append(pdu.getSpecific());
- sbuf.append("\nTimeStamp ......... ").append(pdu.getTimeStamp());
- sbuf.append("\nLength............. ").append(pdu.getLength());
- sbuf.append("\nCommunity string... ").append(community.toString());
- sbuf.append("\n");
-
- for (int i = 0; i < pdu.getLength(); i++ )
- {
- SnmpVarBind vb = pdu.getVarBindAt(i);
-
- sbuf.append("Varbind[").append(i).append("] := ");
- sbuf.append(vb.getName().toString()).append(" --> ");
- sbuf.append(vb.getValue().toString()).append("\n");
- }
- log.debug(sbuf.toString());
- } // snmpReceivedTrap
-
- /**
- * Processes session errors.
- *
- * @param session the trap session in error
- * @param error the error condition
- * @param ref the reference object, if any
- **/
- public void snmpTrapSessionError(SnmpTrapSession session,
- int error, Object ref)
- {
- StringBuffer sbuf = new StringBuffer();
-
- if(ref != null) {
- sbuf.append("Session error (").append(error).append(") reference: ");
- sbuf.append(ref.toString());
- }
- else {
- sbuf.append("Session error (").append(error).append(")");
- }
-
- try {
- if(error == SnmpTrapSession.ERROR_EXCEPTION)
- session.raise();
- }
- catch (Throwable e) {
- sbuf.append(" <").append(e).append(">");
- }
-
- log.error(sbuf.toString());
-
- } // snmpTrapSessionError
+// /**
+// * Receives and logs information about SNMPv2 traps.
+// *
+// * @param session the trap session that received the PDU
+// * @param agent the address of the remote sender
+// * @param port the remote port where the pdu was transmitted from
+// * @param community the decoded community string
+// * @param pdu the decoded v2 trap pdu
+// **/
+// public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent,
+// int port, SnmpOctetString community,
+// SnmpPduPacket pdu)
+// {
+// StringBuffer sbuf = new StringBuffer();
+//
+// sbuf.append("V2 Trap from ").append(agent.toString());
+// sbuf.append(" on port ").append(port);
+// sbuf.append("\nPDU command......... ").append(pdu.getCommand());
+// sbuf.append("\nPDU Length.......... ").append(pdu.getLength());
+// sbuf.append("\nCommunity string.... ").append(community.toString());
+//
+// if(pdu instanceof SnmpPduRequest)
+// {
+// SnmpPduRequest spdu = (SnmpPduRequest) pdu;
+//
+// sbuf.append("\nPDU Error Status.... ").append(spdu.getErrorStatus());
+// sbuf.append("\nPDU Error Index..... ").append(spdu.getErrorIndex());
+// sbuf.append("\n");
+// }
+//
+// for (int i = 0; i < pdu.getLength(); i++ )
+// {
+// SnmpVarBind vb = pdu.getVarBindAt(i);
+//
+// sbuf.append("Varbind[").append(i).append("] := ");
+// sbuf.append(vb.getName().toString()).append(" --> ");
+// sbuf.append(vb.getValue().toString()).append("\n");
+// }
+// log.debug(sbuf.toString());
+// } // snmpReceivedTrap
+//
+// /**
+// * Receives and logs information about SNMPv1 traps.
+// *
+// * @param session the trap session that received the PDU
+// * @param agent the address of the remote sender
+// * @param port the remote port where the pdu was transmitted from
+// * @param community the decoded community string
+// * @param pdu the decoded v1 trap pdu
+// **/
+// public void snmpReceivedTrap(SnmpTrapSession session, InetAddress agent,
+// int port, SnmpOctetString community,
+// SnmpPduTrap pdu)
+// {
+// StringBuffer sbuf = new StringBuffer();
+//
+// sbuf.append("V1 Trap from agent ").append(agent.toString());
+// sbuf.append(" on port ").append(port);
+// sbuf.append("\nIP Address......... ").append(pdu.getAgentAddress());
+// sbuf.append("\nEnterprise Id...... ").append(pdu.getEnterprise());
+// sbuf.append("\nGeneric ........... ").append(pdu.getGeneric());
+// sbuf.append("\nSpecific .......... ").append(pdu.getSpecific());
+// sbuf.append("\nTimeStamp ......... ").append(pdu.getTimeStamp());
+// sbuf.append("\nLength............. ").append(pdu.getLength());
+// sbuf.append("\nCommunity string... ").append(community.toString());
+// sbuf.append("\n");
+//
+// for (int i = 0; i < pdu.getLength(); i++ )
+// {
+// SnmpVarBind vb = pdu.getVarBindAt(i);
+//
+// sbuf.append("Varbind[").append(i).append("] := ");
+// sbuf.append(vb.getName().toString()).append(" --> ");
+// sbuf.append(vb.getValue().toString()).append("\n");
+// }
+// log.debug(sbuf.toString());
+// } // snmpReceivedTrap
+//
+// /**
+// * Processes session errors.
+// *
+// * @param session the trap session in error
+// * @param error the error condition
+// * @param ref the reference object, if any
+// **/
+// public void snmpTrapSessionError(SnmpTrapSession session,
+// int error, Object ref)
+// {
+// StringBuffer sbuf = new StringBuffer();
+//
+// if(ref != null) {
+// sbuf.append("Session error (").append(error).append(") reference: ");
+// sbuf.append(ref.toString());
+// }
+// else {
+// sbuf.append("Session error (").append(error).append(")");
+// }
+//
+// try {
+// if(error == SnmpTrapSession.ERROR_EXCEPTION)
+// session.raise();
+// }
+// catch (Throwable e) {
+// sbuf.append(" <").append(e).append(">");
+// }
+//
+// log.error(sbuf.toString());
+//
+// } // snmpTrapSessionError
} // class TrapReceiver
Modified: trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java
===================================================================
--- trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/main/java/org/jboss/jmx/adaptor/snmp/trapd/TrapdService.java 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,11 +21,35 @@
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.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 +66,7 @@
**/
public class TrapdService
extends ServiceMBeanSupport
- implements TrapdServiceMBean
+ implements TrapdServiceMBean, CommandResponder
{
/** The listening port */
private int port;
@@ -51,7 +75,7 @@
private InetAddress bindAddress;
/** The snmp session used to receive the traps*/
- protected SnmpTrapSession trapSession;
+ protected Snmp snmp;
/**
* Empty CTOR
@@ -123,19 +147,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 +183,7 @@
protected void stopService()
throws Exception
{
- this.trapSession.close();
- this.trapSession = null; // gc
+ snmp.close();
}
/**
@@ -159,5 +197,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
Modified: trunk/varia/src/resources/services/snmp/config/Manager.xsd
===================================================================
--- trunk/varia/src/resources/services/snmp/config/Manager.xsd 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/config/Manager.xsd 2011-08-18 20:45:19 UTC (rev 112094)
@@ -33,6 +33,7 @@
<xsd:element name="local-address" type="xsd:string" />
<xsd:element name="local-port" type="xsd:integer" />
<xsd:element name="version" type="xsd:integer" />
+ <xsd:element name="community-string" type="xsd:string" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
Modified: trunk/varia/src/resources/services/snmp/config/Notification.xsd
===================================================================
--- trunk/varia/src/resources/services/snmp/config/Notification.xsd 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/config/Notification.xsd 2011-08-18 20:45:19 UTC (rev 112094)
@@ -21,6 +21,7 @@
3. Enterprise OID
4. The trap payload comprised of notification variables mapped
to specific OIDs.
+ 5. The name of the Notification to put into the generated MIB (optional)
</xsd:documentation>
</xsd:annotation>
@@ -30,23 +31,30 @@
<xsd:element name="mapping" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
- <xsd:element name="notification-type" type="xsd:string"/>
- <xsd:element name="generic" type="xsd:integer" />
- <xsd:element name="specific" type="xsd:integer" />
- <xsd:element name="enterprise" type="xsd:string" />
+ <xsd:attribute name="notification-type" type="xsd:string"/>
+ <xsd:attribute name="generic" type="xsd:integer" />
+ <xsd:attribute name="specific" type="xsd:integer" />
+ <xsd:attribute name="enterprise" type="xsd:string" />
+ <xsd:attribute name="inform" type="xsd:boolean" />
+ <xsd:attribute name="securityName" type="xsd:string" />
+ <xsd:attribute name="name" type="xsd:string" />
+ <xsd:attribute name="definition-name" type="xsd:string" />
+ <xsd:attribute name="description" type="xsd:string" />
<xsd:element name="var-bind-list">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="var-bind" maxOccurs="unbounded">
<xsd:complexType>
<xsd:sequence>
- <xsd:element name="tag" type="xsd:string" />
- <xsd:element name="oid" type="xsd:string" />
+ <xsd:attribute name="tag" type="xsd:string" />
+ <xsd:attribute name="oid" type="xsd:string" />
+ <xsd:attribute name="type" type="xsd:string" />
+ <xsd:attribute name="description" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
- <xsd:attribute name="wrapper-class" type="string" use="required"/>
+ <xsd:attribute name="wrapper-class" type="xsd:string" use="required"/>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
@@ -55,4 +63,4 @@
</xsd:sequence>
</xsd:complexType>
</xsd:element>
-</xsd:schema>
\ No newline at end of file
+</xsd:schema>
Modified: trunk/varia/src/resources/services/snmp/deploy/META-INF/jboss-service.xml
===================================================================
--- trunk/varia/src/resources/services/snmp/deploy/META-INF/jboss-service.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/deploy/META-INF/jboss-service.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -15,13 +15,14 @@
to SNMP traps.
SnmpAgentService is the main MBean that implements the SNMP agent.
- It is configured by means of 3 different configuration files, plus
+ It is configured by means of 4 different configuration files, plus
an inline notification subscription specification:
- attributes.xml, maps SNMP oids to MBean attribute get/set
- managers.xml, configures where to send traps
- notifications.xml, specifies the exact mapping of each notification type
to a corresponding SNMP trap
+ - users.xml, specifies the User names and passwords for v3 SNMP communication
For more information, see
http://www.jboss.org/wiki/Wiki.jsp?page=JBossSNMPAdapter
@@ -94,6 +95,7 @@
<attribute name="TrapFactoryClassName">org.jboss.jmx.adaptor.snmp.agent.TrapFactorySupport</attribute>
<attribute name="NotificationMapResName">/notifications.xml</attribute>
<attribute name="ManagersResName">/managers.xml</attribute>
+ <attribute name="UsersResName">/users.xml</attribute>
<attribute name="HeartBeatPeriod">0</attribute>
<attribute name="BindAddress">
<!-- Get the interface from the ServiceBindingManager -->
@@ -142,16 +144,19 @@
name="jboss.jmx:name=SnmpAgent,service=MIB2SystemGroup">
<attribute name="SysLocation">In The Matrix</attribute>
- <attribute name="SysDescr">Central Computer</attribute>
- <attribute name="SysContact">Agent Smith</attribute>
+ <attribute name="SysDescr">JBoss AS</attribute>
+ <attribute name="SysContact">Red Hat</attribute>
+ <!-- EAP IS 1, EPP is 2, SOAP is 3, ... JBCP is 9, JBCP Sip Servlets is 9.1 -->
+ <attribute name="Product">.1</attribute>
+ <!-- product version, MSS 1.6 here -->
+ <attribute name="Version">.5.1.1</attribute>
<!-- attribute name="SysName"></attribute> set internally to serverConfig at hostAddress-->
<depends optional-attribute-name="SnmpAgent">
jboss.jmx:name=SnmpAgent,service=snmp,type=adaptor
</depends>
</mbean>
- <!-- Used for internal testing - ignore
+<!-- Used for internal testing - ignore-->
<mbean code="org.jboss.jmx.adaptor.snmp.test.NotificationProducerService"
name="jboss.jmx:name=SnmpAgent,service=notification,type=producer"/>
- -->
-</service>
\ No newline at end of file
+</service>
Modified: trunk/varia/src/resources/services/snmp/deploy/attributes.mib
===================================================================
--- trunk/varia/src/resources/services/snmp/deploy/attributes.mib 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/deploy/attributes.mib 2011-08-18 20:45:19 UTC (rev 112094)
@@ -1,72 +1,254 @@
---
--- Example MIB for the delivered attributes.xml
--- $Revision$
---
+-- This MIB Generated by the JBoss MIB Generator
JBOSS-AS-MIB DEFINITIONS ::=BEGIN
--- Tree roots
-org OBJECT IDENTIFIER ::= { iso 2 } -- "iso" = 1
-jboss OBJECT IDENTIFIER ::= { org 3 }
-as OBJECT IDENTIFIER ::= { jboss 4 }
-system OBJECT IDENTIFIER ::= { as 1 } -- .1.2.3.4.1
-mgmt OBJECT IDENTIFIER ::= { as 5 }
-snmp OBJECT IDENTIFIER ::= { mgmt 6 }
-agent OBJECT IDENTIFIER ::= { snmp 7 }
+IMPORTS
+ OBJECT-TYPE,
+ NOTIFICATION-TYPE,
+ Counter32,
+ Gauge32,
+ Counter64,
+ TimeTicks
+ FROM SNMPv2-SMI
+ DisplayString,
+ TruthValue
+ FROM SNMPv2-TC;
--- system parameters
+jbossAsObjects OBJECT IDENTIFIER ::= { 1 3 6 1 4 1 2312 100 1 1 }
+testTableDefinition OBJECT IDENTIFIER ::= { 1 3 6 1 4 1 2312 100 1 301 }
+system OBJECT IDENTIFIER ::= { 1 3 6 1 2 1 1 }
+
activeThreadCount OBJECT-TYPE
SYNTAX INTEGER
- ACCESS read-only
- DESCRIPTION
- "The number of active Threads in the system"
- ::= { system 1 } -- .1.2.3.4.1.1
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ "The amount of active threads the server is handling."
+::= { jbossAsObjects 1 }
+
freeMemory OBJECT-TYPE
- SYNTAX INTEGER
+ SYNTAX OCTET STRING (SIZE(0..255))
ACCESS read-only
- DESCRIPTION
- "The free memory of the VM"
- ::= {system 2} -- .1.2.3.4.1.2
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 2 }
+
maxMemory OBJECT-TYPE
- SYNTAX INTEGER
+ SYNTAX OCTET STRING (SIZE(0..255))
ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 3 }
+
+inUseConnectionCount OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 9 }
+
+maxConnectionsInUseCount OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 10 }
+
+instantiationTime OBJECT-TYPE
+ SYNTAX DisplayString
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 7 }
+
+trapCount OBJECT-TYPE
+ SYNTAX DisplayString
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 11 }
+
+bindAddress OBJECT-TYPE
+ SYNTAX DisplayString
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { jbossAsObjects 12 }
+
+sysDescr OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-write
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 1 }
+
+sysObjectId OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 2 }
+
+sysUpTime OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 3 }
+
+sysContact OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 4 }
+
+sysName OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 5 }
+
+sysLocation OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 6 }
+
+sysServices OBJECT-TYPE
+ SYNTAX OCTET STRING (SIZE(0..255))
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { system 7 }
+
+webappDefaultMetricsTable OBJECT-TYPE
+ SYNTAX SEQUENCE OF WebappDefaultMetricsEntry
+ MAX-ACCESS not-accessible
+ STATUS current
+ DESCRIPTION
+ "Table containing standard metrics for any webapp deployed on JBossAS"
+::= { testTableDefinition 30 }
+
+webappDefaultMetricsEntry OBJECT-TYPE
+ SYNTAX WebappDefaultMetricsEntry
+ MAX-ACCESS not-accessible
+ STATUS current
DESCRIPTION
- "The max memory of the VM"
- ::= {system 3} -- .1.2.3.4.1.3
-threadPoolQueueSize OBJECT-TYPE
+ ""
+
+ INDEX {
+ IMPLIED webappDefaultMetricsObjectName
+ }
+::= { webappDefaultMetricsTable 1 }
+
+WebappDefaultMetricsEntry ::= SEQUENCE {
+ webappDefaultMetricsObjectName DisplayString,
+ webappDefaultMetricsDistributable INTEGER,
+ webappDefaultMetricsSessionCounter INTEGER,
+ webappDefaultMetricsActiveSessions INTEGER,
+ webappDefaultMetricsMaxActiveSessions INTEGER,
+ webappDefaultMetricsSessionAverageAliveTime INTEGER,
+ webappDefaultMetricsExpiredSessions INTEGER,
+ webappDefaultMetricsRejectedSessions INTEGER,
+ webappDefaultMetricsMaxInactiveInterval INTEGER,
+ webappDefaultMetricsSessionMaxAliveTime INTEGER
+}
+
+webappDefaultMetricsObjectName OBJECT-TYPE
+ SYNTAX DisplayString
+ ACCESS not-accessible
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 1 }
+
+webappDefaultMetricsDistributable OBJECT-TYPE
SYNTAX INTEGER
ACCESS read-only
- DESCRIPTION
- "The size of the thread pool queue"
- ::= {system 4 }
-requestCount8080 OBJECT-TYPE
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 2 }
+
+webappDefaultMetricsSessionCounter OBJECT-TYPE
SYNTAX INTEGER
ACCESS read-only
- DESCRIPTION
- "Number of requests served on port 8080"
- ::= {system 5}
-txCommitCount OBJECT-TYPE
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 3 }
+
+webappDefaultMetricsActiveSessions OBJECT-TYPE
SYNTAX INTEGER
ACCESS read-only
- DESCRIPTION
- "Number of commited transactions"
- ::= {system 6 }
-txRollbackCount OBJECT-TYPE
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 4 }
+
+webappDefaultMetricsMaxActiveSessions OBJECT-TYPE
SYNTAX INTEGER
+ ACCESS read-write
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 5 }
+
+webappDefaultMetricsSessionAverageAliveTime OBJECT-TYPE
+ SYNTAX INTEGER
ACCESS read-only
- DESCRIPTION
- "Number of transactions rolled back"
- ::= {system 7 }
-txActiveCount OBJECT-TYPE
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 6 }
+
+webappDefaultMetricsExpiredSessions OBJECT-TYPE
SYNTAX INTEGER
ACCESS read-only
- DESCRIPTION
- "The number of currently active transactions"
- ::= {system 8 }
-dbInUseCount OBJECT-TYPE
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 7 }
+
+webappDefaultMetricsRejectedSessions OBJECT-TYPE
SYNTAX INTEGER
- ACCES read-only
- DESCRIPTION
- "The number of db connections currently in use"
- ::= { system 9 }
-END
\ No newline at end of file
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 8 }
+
+webappDefaultMetricsMaxInactiveInterval OBJECT-TYPE
+ SYNTAX INTEGER
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 9 }
+
+webappDefaultMetricsSessionMaxAliveTime OBJECT-TYPE
+ SYNTAX INTEGER
+ ACCESS read-only
+ STATUS current
+ DESCRIPTION
+ ""
+::= { webappDefaultMetricsEntry 10 }
+
+END
Modified: trunk/varia/src/resources/services/snmp/deploy/attributes.xml
===================================================================
--- trunk/varia/src/resources/services/snmp/deploy/attributes.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/deploy/attributes.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -12,39 +12,48 @@
<attribute-mappings>
<!-- basic system information -->
- <mbean name="jboss.system:type=ServerInfo" oid-prefix=".1.2.3.4.1">
- <attribute name="ActiveThreadCount" oid=".1"/>
- <attribute name="FreeMemory" oid=".2"/>
- <attribute name="MaxMemory" oid=".3"/>
+ <mbean name="jboss.system:type=ServerInfo" oid-prefix=".1.3.6.1.4.1.2312.100.1.1" definition-name="jbossAsObjects">
+ <attribute name="ActiveThreadCount" oid=".1" snmp-type="INTEGER" max-access="read-only" description="The amount of active threads the server is handling." status="current"/>
+ <attribute name="FreeMemory" oid=".2" description="The amount of free memory on the server."/>
+ <attribute name="MaxMemory" oid=".3" description="The maximum usable amount of memory on the server."/>
</mbean>
<!-- tomcat global http request processing -->
- <mbean name="jboss.web:name=http-0.0.0.0-8080,type=GlobalRequestProcessor">
- <attribute name="requestCount" oid=".1.2.3.4.1.5"/>
- </mbean>
+ <!--<mbean name="jboss.web:name=http-0.0.0.0-8080,type=GlobalRequestProcessor">
+ <attribute name="requestCount" oid=".1.3.6.1.4.1.2312.100.1.1.5" snmp-type="INTEGER" description="Number of requests that have been processed." status="obsolete"/>
+ </mbean>-->
- <!-- Tx Manager statistics -->
- <mbean name="jboss:service=TransactionManager">
- <attribute name="CommitCount" oid=".1.2.3.4.1.6"/>
- <attribute name="RollbackCount" oid=".1.2.3.4.1.7"/>
- <attribute name="TransactionCount" oid=".1.2.3.4.1.8"/>
+ <mbean name="jboss.jmx:name=SnmpAgent,service=snmp,type=adaptor" oid-prefix="1.3.6.1.4.1.2312.100.1.1">
+ <attribute name="InstantiationTime" oid=".4" snmp-type="DisplayString" description="The start time of the SNMP agent."/>
+ <attribute name="TrapCount" oid=".5" snmp-type="DisplayString" description="The number of traps emitted by the agent."/>
+ <attribute name="BindAddress" oid=".6" snmp-type="DisplayString" description="The address to which the agent is bound."/>
</mbean>
-
<!-- DefaultDS statistics -->
- <mbean name="jboss.jca:name=DefaultDS,service=ManagedConnectionPool" oid-prefix=".1.2.3.4.1">
- <attribute name="InUseConnectionCount" oid=".9"/>
- <attribute name="MaxConnectionsInUseCount" oid=".10"/>
+ <mbean name="jboss.jca:name=DefaultDS,service=ManagedConnectionPool" oid-prefix="1.3.6.1.4.1.2312.100.1.1">
+ <attribute name="InUseConnectionCount" oid=".7" description="The amount of connections currently in use."/>
+ <attribute name="MaxConnectionsInUseCount" oid=".8" description="The maximum possible amount of connections available for use."/>
</mbean>
-
+
+ <mbean name="jboss.web:host=localhost,path=*,type=Manager" oid-prefix="1.3.6.1.4.1.2312.100.1.1.9.1" table-name="metrics" description="Table containing standard metrics for any webapp deployed on JBossAS" status="current">
+ <attribute name="distributable" oid=".2" snmp-type="INTEGER"/>
+ <attribute name="sessionCounter" oid=".3" snmp-type="INTEGER" description="The amount of sessions this web application has handled."/>
+ <attribute name="activeSessions" oid=".4" snmp-type="INTEGER" description="The amount of currently active sessions this web application is handling."/>
+ <attribute name="maxActiveSessions" oid=".5" mode="rw" snmp-type="INTEGER" description="The maximum amount of active sessions this web application can handle at once."/>
+ <attribute name="sessionAverageAliveTime" oid=".6" snmp-type="INTEGER" description="The average time a session is active on this web application."/>
+ <attribute name="expiredSessions" oid=".7" snmp-type="INTEGER" description="The amount of expired sessions related to this web application."/>
+ <attribute name="rejectedSessions" oid=".8" snmp-type="INTEGER" description="The amount of rejected sessions related to this web application."/>
+ <attribute name="maxInactiveInterval" oid=".9" snmp-type="INTEGER" description="The amount of time that must expire before a session is considered inactive."/>
+ <attribute name="sessionMaxAliveTime" oid=".10" snmp-type="INTEGER" description="The maximum amount of time a session can remain active."/>
+ </mbean>
<!-- system information group see RFC-1213 -->
- <mbean name="jboss.jmx:name=SnmpAgent,service=MIB2SystemGroup" oid-prefix=".1.3.6.1.2.1.1">
- <attribute name="SysDescr" oid=".1" mode="rw"/> <!-- can be modified over snmp -->
- <attribute name="SysObjectId" oid=".2"/>
- <attribute name="SysUpTime" oid=".3"/>
- <attribute name="SysContact" oid=".4"/>
- <attribute name="SysName" oid=".5"/>
- <attribute name="SysLocation" oid=".6"/>
- <attribute name="SysServices" oid=".7"/>
+ <mbean name="jboss.jmx:name=SnmpAgent,service=MIB2SystemGroup" oid-prefix="1.3.6.1.2.1.1" definition-name="system">
+ <attribute name="SysDescr" oid=".1" mode="rw" description="A description of this System."/> <!-- can be modified over snmp -->
+ <attribute name="SysObjectId" oid=".2" description="The OID Denoting this system."/>
+ <attribute name="SysUpTime" oid=".3" description="The time this system has been online."/>
+ <attribute name="SysContact" oid=".4" description="The person who is admin to this system."/>
+ <attribute name="SysName" oid=".5" description="The name this system is known by."/>
+ <attribute name="SysLocation" oid=".6" description="The physical location of this system."/>
+ <attribute name="SysServices" oid=".7" description="The services provided by this system."/>
</mbean>
-</attribute-mappings>
\ No newline at end of file
+</attribute-mappings>
Modified: trunk/varia/src/resources/services/snmp/deploy/managers.xml
===================================================================
--- trunk/varia/src/resources/services/snmp/deploy/managers.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/deploy/managers.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -10,7 +10,7 @@
- the listening port
- the local binding address (optional)
- the local binding port (optional)
- - the SNMP version to use (1 or 2)
+ - the SNMP version to use (1 or 2 or 3)
More than one managers may be specified.
@@ -26,11 +26,30 @@
"jboss.jmx:name=SnmpAgent,service=trapd,type=logger" MBean that
simply outputs received traps as log4j DEBUG messages
-->
+ <!-- v1 manager -->
<manager>
<address>localhost</address>
- <port>1162</port>
+ <port>162</port>
<local-address></local-address>
<local-port></local-port>
<version>1</version>
+ <community-string>public</community-string>
</manager>
+ <!-- v2c manager -->
+ <manager>
+ <address>localhost</address>
+ <port>162</port>
+ <local-address></local-address>
+ <local-port></local-port>
+ <version>2</version>
+ <community-string>public</community-string>
+ </manager>
+ <!-- v3 manager -->
+ <manager>
+ <address>localhost</address>
+ <port>162</port>
+ <local-address></local-address>
+ <local-port></local-port>
+ <version>3</version>
+ </manager>
</manager-list>
Modified: trunk/varia/src/resources/services/snmp/deploy/notifications.xml
===================================================================
--- trunk/varia/src/resources/services/snmp/deploy/notifications.xml 2011-08-18 20:17:00 UTC (rev 112093)
+++ trunk/varia/src/resources/services/snmp/deploy/notifications.xml 2011-08-18 20:45:19 UTC (rev 112094)
@@ -22,46 +22,19 @@
-->
<notification-map-list>
- <mapping>
- <notification-type>jboss.snmp.agent.heartbeat</notification-type>
- <generic>3</generic>
- <specific>0</specific>
- <enterprise>1.2.3.4.5.6.7</enterprise>
+ <mapping name="jbossAsHeartbeatNotification" notification-type="jboss.snmp.agent.heartbeat" generic="0" specific="3" enterprise="1.3.6.1.4.1.2312.100.1.2" definition-name="jbossAsTraps">
<var-bind-list wrapper-class="org.jboss.jmx.adaptor.snmp.agent.NotificationWrapperSupport">
- <var-bind>
- <tag>a:uptime</tag>
- <oid>1.2.3.4.5.6.7.5</oid>
- </var-bind>
- <var-bind>
- <tag>a:trapCount</tag>
- <oid>1.2.3.4.5.6.7.6</oid>
- </var-bind>
- <var-bind>
- <tag>n:message</tag>
- <oid>1.2.3.4.5.6.7.7</oid>
- </var-bind>
- <var-bind>
- <tag>n:sequenceNumber</tag>
- <oid>1.2.3.4.5.6.7.8</oid>
- </var-bind>
+ <var-bind tag="a:uptime" oid="1.3.6.1.2.1.1.3"/>
+ <var-bind tag="a:trapCount" oid="1.3.6.1.4.1.2312.100.1.1.5"/>
+ <var-bind tag="n:message" oid="1.3.6.1.4.1.2312.100.1.1.30"/>
+ <var-bind tag="n:sequenceNumber" oid="1.3.6.1.4.1.2312.100.1.1.31"/>
</var-bind-list>
</mapping>
- <mapping>
- <notification-type>jboss.snmp.agent.coldstart</notification-type>
- <generic>0</generic>
- <specific>0</specific>
- <enterprise>1.2.3.4.5.6.7</enterprise>
+ <mapping name="jbossAsColdstartNotification" notification-type="jboss.snmp.agent.coldstart" generic="0" specific="1" enterprise="1.3.6.1.4.1.2312.100.1.2" inform="false" security-name="TEST">
<var-bind-list wrapper-class="org.jboss.jmx.adaptor.snmp.agent.NotificationWrapperSupport">
- <var-bind>
- <tag>a:startTime</tag>
- <oid>1.2.3.4.5.6.7.9</oid>
- </var-bind>
- <var-bind>
- <tag>a:trapCount</tag>
- <oid>1.2.3.4.5.6.7.6</oid>
- </var-bind>
+ <var-bind tag="a:startTime" oid="1.3.6.1.4.1.2312.100.1.1.4"/>
+ <var-bind tag="a:trapCount" oid="1.3.6.1.4.1.2312.100.1.1.5"/>
</var-bind-list>
</mapping>
-
</notification-map-list>
More information about the jboss-cvs-commits
mailing list