Java Dynamic Management Kit 5.1 Tutorial

17.2 Asynchronous Managers

The asynchronous SNMP manager lets you handle more requests in the same amount of time because the manager is not blocked waiting for responses. Instead, it creates a request handler object that runs as a separate thread and processes several responses concurrently. Otherwise, the initialization of peers, parameters, sessions, options, and dispatcher is identical to that of a synchronous manager. This applies to all three versions of SNMP.


Example 17–7 The AsyncManager Example

// read the command line parameters
String host = argv[0];
String port = argv[1];
   
// Use the OidTable generated by mibgen when compiling MIB-II.
final SnmpOidTableSupport oidTable = new RFC1213_MIBOidTable();
       
// Sample use of the OidTable.
SnmpOidRecord record = oidTable.resolveVarName("udpLocalPort");
java.lang.System.out.println(
    "AsyncManager::main: variable = " + record.getName() + 
        " oid = " + record.getOid() + " type = " + record.getType());

// Initialize the SNMP Manager API.
SnmpOid.setSnmpOidTable(oidTable);
  
// Create an SnmpPeer object for representing the agent 
final SnmpPeer agent = new SnmpPeer(host, Integer.parseInt(port));
     
// Create parameters for communicating with the agent
final SnmpParameters params = new SnmpParameters("public", "private");
agent.setSnmpParam(params);
     
// Build the session and assign its default peer
final SnmpSession session = new SnmpSession("AsyncManager session");
session.setDefaultPeer(agent);

	final DaemonTaskServer taskServer = new DaemonTaskServer();
	taskServer.start(Thread.NORM_PRIORITY);

// Same dispatcher and trap listener as in SyncManager example
SnmpEventReportDispatcher trapAgent =
    		new SnmpEventReportDispatcher(Integer.parseInt(port)+1,
					      null,taskServer,null);
trapAgent.addTrapListener(new TrapListenerImpl()); 
final Thread trapThread = new Thread(trapAgent);
	trapThread.setPriority(Thread.MAX_PRIORITY);
	trapThread.start();

// Build the list of variables to query
SnmpVarbindList list = new SnmpVarbindList("AsyncManager varbind list");
list.addVariable("sysDescr.0");
    
// Create a simple implementation of an SnmpHandler. 
AsyncRspHandler handler = new AsyncRspHandler();
       
// Make the SNMP walk request with our handler
final SnmpRequest request = session.snmpWalkUntil(
    handler, list, new  SnmpOid("sysServices"));
       
// Here you could do whatever processing you need.
// In the context of the example, we are just going to wait
// 4 seconds while the response handler displays the result.
Thread.sleep(4000);

[...] // Wait for user to type enter. Traps will be handled.
       
// End the session properly and we're done.
//
session.destroySession();
java.lang.System.exit(0);

The trap mechanism in this application is identical to the one presented in the SyncManager example. The event report dispatcher receives traps and calls the corresponding method of our SnmpTrapListener class.

In this example, the manager performs an snmpWalkUntil request that gives a response for each variable that it gets. The response handler is called to process each of these responses.

17.2.1 Response Handler

A response handler for an asynchronous manager is an implementation of the SnmpHandler interface. When a handler object is associated with a request, its methods are called when the agent returns an answer or fails to return an answer. In these methods, you implement whatever actions you want for processing the responses to a request. Typically, these methods extract the result of each request or the reason for its failure.

The timeout used by the request handler is the one specified by the SnmpPeer object representing the agent. The handler is also called to process any errors caused by the request in the session. This ensures that the manager application is never interrupted after issuing a request.


Example 17–8 The SnmpHandler Implementation

public class AsyncRspHandler implements SnmpHandler {
   
    // Empty constructor
    public AsyncRspHandler() {
    }

    // Called when the agent responds to a request
    public void processSnmpPollData( SnmpRequest request,
        int errStatus, int errIndex, SnmpVarbindList vblist) {

         // Check if a result is available.
        if (request.getRequestStatus() ==
              SnmpVarBindList result = request.getResponseVarBindList();
              println("Result = " + result.varBindListToString());

            // Extract the result for display
            SnmpVarbindList result = request.getResponseVbList();
            java.lang.System.out.println(
                "Result = " + result.vbListToString());
        }
    }

    // Called when the agent fails to respond to a request
    public void processSnmpPollTimeout(SnmpRequest request) {
        
        java.lang.System.out.println(
			"Request timed out: " + request.toString());
        
        if (request.getRequestStatus() == 
            SnmpRequest.stResultsAvailable) {

            // The result is empty and will display an error message
            SnmpVarbindList result = request.getResponseVbList();
            java.lang.System.out.println(
                "Result = " + result.vbListToString());
        }
    }

    // Called when there is an error in the session
    public void processSnmpInternalError(SnmpRequest request,
        String errmsg) {
        
        java.lang.System.out.println(
            "Session error: " + request.toString());
        java.lang.System.out.println("Error is: " + errmsg);
    }
}

To Run the AsyncManager Example
  1. If you have not done so already, start the simple SNMP agent in examplesDir/current/Snmp/Agent, after making sure that no other agent is running on port 8085.

    This manager also uses the OID table description (the SnmpOidTableSupport class) that we generated from the MIB for the synchronous manager. If you have not already done so, see To Run the SyncManager Example for instructions on how to do this.

  2. If you do not have an SNMP agent still running, make sure that no other agent is running on port 8085 and start one with the following command:


    $ cd examplesDir/current/Snmp/Agent
    $ java -classpath classpath Agent nbTraps
    
  3. Specify the number of traps to be sent to the manager in the nbTraps parameter.

    Wait until the manager is started to send the traps.

  4. In another terminal window, start the manager application 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 AsyncManager localhost 8085
    

    You should then see the output of the SnmpWalkUntil request: the response handler method is called for each variable that is returned.

  5. Press Enter in the agent's window to send traps and see the trap reports as they are received in the manager.

    When you have finished with the agent, do not forget to stop it by typing Control-C in its terminal window.