Sun Microsystems
Products & Services
 
Support & Training
 
 

Previous Previous     Contents     Index     Next Next

The first instantiated session creates an engine. This engine can be accessed using the getEngine method. To avoid excessive engine creation for each instantiated session, the first engine can be shared between SNMP session objects. While sharing is possible, it should be avoided. It represents an unnecessary increase in overhead and limits the security possibilities because only one security file can be associated with an engine.

The engine is used by all the other classes in the application programming interface (API) to access the USM configuration, contained in the jdmk.security file associated with that session. In Example 17-3, when the peer p is created, it discovers its engineId, and then uses it as the SNMPv3 ContextEngineId. When the request is sent, this engine ID is included as a parameter by setContextEngineId.

In this example, the level of security is set as authentication without privacy. Consequently, this level of security is applied to all the requests between this manager and the peers associated with it, via the security parameters. This level of security must match the level specified in the engine's jdmk.security file.

It is also possible to access MIBs that have been registered in the scope of a context (see 16.2.3 Binding the MIB MBeans for details of contextualized MIBs). In this example, the context TEST-CONTEXT is used, and is set as a parameter in the request by setContextName.

Finally, before sending any requests, if authentication is activated, the timeliness parameters of the request are discovered, using processUsmTimelinessDiscovery.

17.1.4 SNMP Trap Handler

A trap handler for the SNMP manager is an object that implements the SnmpTrapListener interface in the com.sun.management.snmp.manager package. When this object is bound as a listener of an SnmpEventReportDispatcher object, its methods are called to handle trap PDUs.

A trap listener is not a notification listener because the dispatcher is not a notification broadcaster. The listener has callback methods that work in the same manner, but they are given objects that represent traps, not instances of the Notification class.

The interface defines three methods, one for processing SNMPv1 traps, another for SNMPv2 traps and a third for SNMPv3 traps. Trap PDU packets have already been decoded by the dispatcher, and these methods handle an object representation of the trap: SnmpPduTrap objects for SNMPv1, SnmpPduRequest objects for SNMPv2 and SnmpScopedPduRequest for SNMPv3.

Example 17-4 SnmpTrapListener Implementation

public class TrapListenerImpl implements SnmpTrapListener {

		public void processSnmpTrapV1(SnmpPduTrap trap) {
        println("NOTE: TrapListenerImpl received trap :");
        println("\tGeneric " + trap.genericTrap);
        println("\tSpecific " + trap.specificTrap);
        println("\tTimeStamp " + trap.timeStamp);
        println("\tAgent adress " + trap.agentAddr.stringValue());
    }

    public void processSnmpTrapV2(SnmpPduRequest trap) {
        println("NOTE: Trap V2 not of interest !!!");
    }

    public void processSnmpTrapV3(SnmpScopedPduRequest trap) {
			println("NOTE: TrapListenerImpl received trap V3:");
			println("\tContextEngineId : " + 
				SnmpEngineId.createEngineId(trap.contextEngineId));
			println("\tContextName : " + new String(trap.contextName));
			println("\tVarBind list :");
			for(int i = 0; i < trap.varBindList.length; i++)
	    		println("oid : " + trap.varBindList[i].oid + " val : " + 
		    		trap.varBindList[i].value);
	
    }

 }

ProcedureTo Run the SyncManager Example

  1. In the examplesDir/current/Snmp/Manager directory, generate the OID table description of MIB-II that our manager will access.

    $ mibgen -mo mib_II.txt

  2. Compile the example classes.

    To set up your environment, see "Directories and Classpath" in the Preface.

    $ javac -classpath classpath -d . *.java

  3. Make sure that no other agent is running on port 8085, and start the simple SNMP agent in examplesDir/current/Snmp/Agent.

    See To Run the SNMPv1/v2 Agent Example if you have not already built and run this example.

    Type the following command to start the Agent example:

    $ cd examplesDir/current/Snmp/Agent
    $ java -classpath classpath Agent nbTraps

    If you are also running the asynchronous manager example with this agent, omit the nbTraps parameter. The agent then sends traps continuously and they can be seen in both managers. Otherwise, specify the number of traps to be sent to the manager. Wait until the manager is started to send the traps.

  4. Start the manager application in another window to connect to this agent.

    If you want to run the manager on a different host, replace localhost with the name of the host where you started the agent.

    $ cd examplesDir/current/Snmp/Manager
    $ java -classpath classpath SyncManager localhost 8085
    SyncManager::main: Send get request to SNMP agent on localhost at port 8085
    Result: 
    [Object ID : 1.3.6.1.2.1.1.1.0  (Syntax : String)
    Value : SunOS sparc 5.7]

    Here we see the output of the SNMP request, it is the value of the sysDescr variable on the agent.

  5. Press Enter in the agent's window.

    You should see the manager receiving the traps it sends. Leave the agent running if you are going on to the next example, otherwise remember to stop it by pressing Control-C.

ProcedureTo Run the SyncManagerV3 Example

  1. In the examplesDir/current/Snmp/Manager directory, generate the OID table description of MIB-II that our manager will access.

    $ mibgen -mo mib_II.txt

  2. Compile the example classes.

    To set up your environment, see "Directories and Classpath" in the Preface.

    $ javac -classpath classpath -d . *.java

  3. Make sure that no other agent is running on port 8085, and start the simple SNMPv3 agent, AgentV3, in examplesDir/current/Snmp/Agent.

    See To Run the SMNPv3 AgentV3 Example if you have not already built and run this example.

    Type the following commands to start the AgentV3 example:

    $ cd examplesDir/current/Snmp/Agent
    $ java -classpath classpath -Djdmk.security.file=jdmk.security AgentV3

  4. Start the manager application in another window to connect to this agent.

    If you want to run the manager on a different host, replace localhost with the name of the host where you started the agent.

    $ cd examplesDir/current/Snmp/Manager
    $ java -classpath classpath -Djdmk.security.file=jdmk.security 
    SyncManagerV3 localhost 8085

    Be sure to run the manager in its directory, otherwise it cannot find its jdmk.security file.

  5. Press Enter in the agent's window.

    You should see the manager receiving the traps it sends. Stop the manager by typing Control-C.

17.1.5 Synchronous Managers Accessing Several Agents

The SNMP API enables you to configure a synchronous SNMPv3 manager that can access several agents. The SyncManagerMultiV3 example demonstrates a simple SNMPv3 manager API that makes requests on two SNMPv3 agents. For the sake of simplicity, this manager does not listen for traps.

Example 17-5 SNMPv3 SyncManagerMultiV3 Example

	//Check host and port arguments
	//
        final String host1 = argv[0];
        final String port1 = argv[1];
			  final String host2 = argv[2];
        final String port2 = argv[3];

           // Initialize the SNMP Manager API.
            // 
            final SnmpOidTableSupport oidTable = new RFC1213_MIBOidTable();
            SnmpOid.setSnmpOidTable(oidTable);
       
            [...]
	  
			    // Build the session. 
				//
	  			  try {
				// When instantiating a session, a new SNMP V3 engine is 
				// instantiated.
				//
					session= new SnmpSession("SyncManagerMultiV3 session");
	    		}catch(SnmpStatusException e) {
					println(e.getMessage());
					java.lang.System.exit(0);
			   }
	    		catch(IllegalArgumentException e) {
				// If the engine configuration is faulty
				//
				println(e.getMessage());
				java.lang.System.exit(0);
	    }
	
	    		// Get the SnmpEngine. 
			    //
			    final SnmpEngine engine = session.getEngine();
	    
	   			 // Create a SnmpPeer object for representing the first  
	    		 // entity to communicate with. 
	    	    //
	    		 final SnmpUsmPeer agent1 = 
				 new SnmpUsmPeer(engine, host1, Integer.parseInt(port1));
	    
	    		 //Create the second peer.
	    		 //
	   			final SnmpUsmPeer agent2 = 
				new SnmpUsmPeer(engine, host2, Integer.parseInt(port2));
	    
	    		// Create parameters to associate to the entity to  
	    		// communicate with.
	     	   //
	    		final SnmpUsmParameters p = 
				new SnmpUsmParameters(engine, "defaultUser");
	    
			   // Set security level to authNoPriv. 
			   //
		    	p.setSecurityLevel(SnmpDefinitions.authNoPriv);

	    		// Contextualize the send request
	    	   //
	    		p.setContextName("TEST-CONTEXT".getBytes());

	    		// Specify a contextEngineId 
		   		//
	    		p.setContextEngineId(agent1.getEngineId().getBytes());
	    
	    		// Associate the newly created parameter to the agent
		    	//
		    	agent1.setParams(p);
	
	    
	    		// Discover timeliness and boot
	    		agent1.processUsmTimelinessDiscovery();
	    
	    
	    		// Build the list of variables you want to query
	    		//
	    		final SnmpVarBindList list = 
				new SnmpVarBindList("SyncManagerMultiV3 varbind list");
	    
	    		// Read the "sysDescr" variable
	    		//
			   list.addVarBind("sysDescr.0");
	    
	    		// Make the SNMP get request on the first agent agent1 
	    		// and wait for the result
	    		//
	    		SnmpRequest request = 
				session.snmpGetRequest(agent1, null, list);
	    		println("SyncManagerMultiV3::main:" +
		    		" Send get request to SNMP agent on " + 
		    		host1 + " at port " + port1);
	    		boolean completed = request.waitForCompletion(10000);
	    
	    		// Check for a timeout
	    		//
            if (completed == false) {
                println("SyncManagerMultiV3::main:" +
						" Request timed out. Check if agent can 
						be reached");
		
                // Print request
                //
                println("Request: " + request.toString());
                java.lang.System.exit(0);
            }
	    
            // Check if the response contains an error 
	    		 //
            int errorStatus = request.getErrorStatus();
            if (errorStatus != SnmpDefinitions.snmpRspNoError) {
                println("Error status = " + 
						SnmpRequest.snmpErrorToString(errorStatus));
                println("Error index = " + 
						request.getErrorIndex());
                java.lang.System.exit(0);
            }
       
            // Display the content of the result
            //
            SnmpVarBindList result = request.getResponseVarBindList();
            println("Result: \n" + result);
       
            println("\n>> Press Enter if you want to send the request" +
		    " on the second agent.\n");
            java.lang.System.in.read();
            

	      		
			   // Repeat the process for the second agent agent2.
			   //
	    		SnmpUsmParameters p2 = 
				new SnmpUsmParameters(engine, "defaultUser");
	    
	    		p2.setSecurityLevel(SnmpDefinitions.authNoPriv);

	   			p2.setContextName("TEST-CONTEXT".getBytes());
	    
			   p2.setContextEngineId(agent2.getEngineId().getBytes());
	    
			   // Associate the updated parameters with agent2.
			   //
		      agent2.setParams(p2);
	    	    
	    		// Discover timeliness and boot
	    	   //
	    		agent2.processUsmTimelinessDiscovery();
	    
			  	// Make the request with agent2
			   //
	    		request = session.snmpGetRequest(agent2, null, list);
			    println("SyncManagerMultiV3::main:" +
		   			 " Send get request to SNMP agent on " + 
				    host2 + " at port " + port2);
				  completed = request.waitForCompletion(10000);
	    
	    		// Check for a timeout
	    		//
            if (completed == false) {
                println("SyncManagerMultiV3::main:" +
					" Request timed out. Check  if agent can be 
					reached");
		
                // Print request.
                //
                println("Request: " + request.toString());
                java.lang.System.exit(0);
            }
	    
           // Check if the response contains an error
	    		// 
	    		errorStatus = request.getErrorStatus();
           		 if (errorStatus != SnmpDefinitions.snmpRspNoError) {
               	 println("Error status = " + 
					SnmpRequest.snmpErrorToString(errorStatus));
               	 println("Error index = " + 
				request.getErrorIndex());
                java.lang.System.exit(0);
            }
       
            // Display the content of the result
            //
	    		result = request.getResponseVarBindList();
            println("Result: \n" + result);
       
            println("\n>> Press Enter if you want to stop " +
		    		"this manager.\n");
            java.lang.System.in.read();
	    
            // End the session
            //
            session.destroySession();
       
            
}

Previous Previous     Contents     Index     Next Next