Using WebLogic Server MBean Notifications and Monitors
To report changes in configuration and runtime information, all WebLogic Server MBeans emit JMX notifications. A notification is a JMX object that describes a state change or some other specific condition that has occurred in an underlying resource.
You can create Java classes called listeners that listen for these notifications. For example, your application can include a listener that receives notifications when applications are deployed, undeployed, or redeployed.
The following sections describe working with notifications and listeners:
- How Notifications are Broadcast and Received
- Monitoring Changes in MBeans
- Best Practices: Listening Directly Compared to Monitoring
- Best Practices: Commonly Monitored Attributes
- Listening for Notifications from WebLogic Server MBeans: Main Steps
- Using Monitor MBeans to Observe Changes: Main Steps
How Notifications are Broadcast and Received
All WebLogic Server MBeans implement the javax.management.NotificationBroadcaster interface, which enable them to emit different types of notification objects depending on the type of event that occurs. For example, MBeans emit notifications when the values of their attributes change.
To listen for these notifications, you create a listener class that implements javax.management.NotificationListener.
By default, your listener receives all notifications that the MBean emits. However, typically, you want your listener to retrieve only specific notifications. For example, the LogBroadCasterRuntime MBean emits a notification each time a WebLogic Server instance generates a log message. Usually you listen for only specific log messages, such as messages of specific severity level. To limit the notifications that your listener receives, you can create a notification filter.
After creating your listener and optional filter, you register the classes with the MBeans from which you want to receive notifications.
Figure 6-1 shows a basic system in which a NotificationListener receives only a subset of the notifications that an MBean broadcasts.
Figure 6-1 Receiving Notifications from an MBean
For a complete explanation of JMX notifications and how they work, download the JMX 1.0 specification from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html.
Monitoring Changes in MBeans
WebLogic Server includes a set of monitor MBeans that can be configured to periodically observe MBeans and emit JMX notifications only if a specific MBean attribute has changed beyond a specific threshold. A monitor MBean can observe the exact value of an attribute in an MBean, or optionally, the difference between two consecutive values of a numeric attribute. The value that a monitor MBean observes is called the derived gauge.
When the value of the derived gauge satisfies a set of conditions, the monitor MBean emits a specific notification type. Monitors can also send notifications when certain error cases are encountered while monitoring an attribute value.
To use monitor MBeans, you configure and register a monitor with a WebLogic Server MBean. Then you create a listener class and register the class with the monitor MBean. Because monitor MBeans emit only very specific types of notification, you usually do not use filters when listening for notifications from monitor MBeans.
Figure 6-2 shows a basic system in which a monitor MBean is registered with a WebLogic Server MBean. A NotificationListener is registered with the monitor MBean, and it receives notifications when the conditions within the monitor MBean are satisfied.
Best Practices: Listening Directly Compared to Monitoring
WebLogic Server provides two ways to be notified about changes in an MBean: you can create a listener and register it directly with an MBean (see Figure 6-1), or you can configure a monitor MBean that periodically observes an MBean and sends notifications when an attribute value satisfies criteria that you specify (see Figure 6-2). The method that you choose depends mostly on the complexity of the situations in which you want to receive notifications.
If your requirements are simple, registering a listener directly with an MBean is the preferred technique. The NotificationListener and NotificationFilter interfaces, which are classes that you implement in your listener and filter, provide few facilities for comparing values with thresholds and other values. You must create you own code to evaluate the data within notifications and respond accordingly. However, the advantage of registering a listener directly with an MBean is that the MBean pushes its notifications to your listener and you are notified of a change almost immediately.
If your notification requirements are sufficiently complex, or if you want to monitor some set of changes that are not directly associated with a single change in the value of an MBean attribute, use a monitor MBean. The monitor MBeans provide a rich set of tools for comparing data and sending notifications only under highly specific circumstances. However, the monitor periodically polls the observed MBean for changes in attribute value and you are notified of a change only as frequently as the polling interval that you specify.
Best Practices: Commonly Monitored Attributes
The attributes in Table 6-1 provide a general overview of the performance of WebLogic Server. You can monitor these attributes either by creating a listener and registering it directly with the MBeans that contain the attributes or by configuring monitor MBeans.
To create and register a listener or to configure monitor MBeans, provide the WebLogicObjectName of the MBean that contains the attributes you want to monitor. (See Registering a Notification Listener and Filter and Instantiating the Monitor and Listener.)
Use the information in Table 6-1 to construct the WebLogicObjectName for each MBean. In the table, domain refers to the name of the WebLogic Server domain, and server refers to the name of the WebLogic Server instance that hosts the MBean you want to monitor.
MBean and Attribute Names
Description
MBean Type: ServerRuntime Attribute Name: State WebLogicObjectName for the MBean:
domain:Location=server,Name=server,
Type=ServerRuntime For example:
medrec:Location=MedRecServer,Name=MedRe
cServer,Type=ServerRuntimeIndicates whether the server is in an Initializing, Suspended, Running, or ShuttingDown state. MBean Type: ServerRuntime Attribute Name: OpenSocketsCurrentCount WebLogicObjectName for the MBean:
See the previous row in this table.Use these two attributes together to compare the current activity on the server's listen ports to the total number of requests that can be backlogged on the ports.Note that the attributes are located in two separate MBeans:
- OpenSocketsCurrentCount is in the ServerRuntime MBean.
- AcceptBacklog is in the Server configuration MBean.
MBean Type: ServerAttribute Name: AcceptBacklog WebLogicObjectName for the MBean:
domain:Name=server,Type=Server For example:
medrec:Name=MedRecServer,Type=ServerMBean Type: ExecuteQueueRuntime Attribute Name: ExecuteThreadCurrentIdleCount WebLogicObjectName for the MBean:
domain:Location=server,Name=default,
ServerRuntime=server,Type=ExecuteQueueRuntime For example:
medrec:Location=MedRecServer,Name=
default,ServerRuntime=MedRecServer,
Type=ExecuteQueueRuntimeDisplays the number of threads in a server's default execute queue that are taking up memory space but are not being used to process data.You can create multiple execute queues on a server instance to optimize the performance of critical applications, but the default execute queue is available by default. For more information, refer to "Using Execute Queues to Control Thread Usage." MBean Type:ExecuteQueueRuntime Attribute Name: PendingRequestCurrentCount WebLogicObjectName for the MBean:
See the previous row in this table.Displays the number of requests waiting in a server's default execute queue. MBean Type: JVMRuntime Attribute Name: HeapSizeCurrent WebLogicObjectName for the MBean:
domain:Location=server,Name=server,
ServerRuntime=server,Type=JVMRuntime For example:
medrec:Location=MedRecServer,Name=
MedRecServer,ServerRuntime=MedRecServer
,Type=JVMRuntimeDisplays the amount of memory (in bytes) that is currently available in the server's JVM heap.For more information, refer to "Tuning Java Virtual Machines (JVMs)." MBean Type: JDBCConnectonPoolRuntime Attribute Name: ActiveConnectionsCurrentCount WebLogicObjectName for the MBean:
domain:Location=server,Name=poolName,
ServerRuntime=server,
Type=JDBCConnectionPoolRuntime where poolName is the name that you gave to the connection pool when you created it.For example:
medrec:Location=MedRecServer,Name=
MedRecPool-PointBase,ServerRuntime=
MedRecServer,Type=JDBCConnectionPoolRun
timeDisplays the current number of active connections in a JDBC connection pool.For more information, refer to "How JDBC Connection Pools Enhance Performance." MBean Type: JDBCConnectonPoolRuntime Attribute Name: ConnectionsHighCount WebLogicObjectName for the MBean:
See the previous row in this table.The high water mark of active connections in a JDBC connection pool. The count starts at zero each time the connection pool is instantiated. MBean Type: JDBCConnectonPoolRuntime Attribute Name: LeakedConnectionCount Notify a listener when the total number of leaked connections reaches a predefined threshold. Leaked connections are connections that have been checked out but never returned to the connection pool via a close() call; it is important to monitor the total number of leaked connections, as a leaked connection cannot be used to fulfill later connection requests. MBean Type: JDBCConnectonPoolRuntime Attribute Name: ActiveConnectionsCurrentCount
Notify a listener when the current number of active connections to a specified JDBC connection pool reaches a predefined threshold. MBean Type: JDBCConnectonPoolRuntime Attribute Name: ConnectionDelayTime Notify a listener when the average time to connect to a connection pool exceeds a predefined threshold. MBean Type: JDBCConnectonPoolRuntime Attribute Name: FailuresToReconnect Notify a listener when the connection pool fails to reconnect to its datastore. Applications may notify a listener when this attribute increments, or when the attribute reaches a threshold, depending on the level of acceptable downtime.
Listening for Notifications from WebLogic Server MBeans: Main Steps
To listen for the notifications that WebLogic Server MBeans emit directly:
- Determine which notification type you want to listen for. See WebLogic Server Notification Types.
- Create a listener class in your application. See Creating a Notification Listener.
- Optionally create a filter class, which specifies the types of notifications that the listener receives from the MBeans. See Creating a Notification Filter.
- Create an additional class that registers your listener and filter with the MBeans whose notifications you want to receive. See Registering a Notification Listener and Filter.
WebLogic Server Notification Types
WebLogic Server MBeans implement the javax.management.NotificationBroadcaster interface, which enable them to emit different types of notification objects depending on the type of event that occurs:
- When an MBean's attribute value changes, it emits a javax.management.AttributeChangeNotification object.
- When a WebLogic Server resource generates a log message, the server's LogBroadcasterRuntimeMBean emits a notification of type weblogic.management.WebLogicLogNotification. For more information about WebLogicLogNotification, refer to the WebLogic Server Javadoc.
- When MBeans are registered or unregistered, the WebLogic Server JMX services emit notifications of type javax.management.MBeanServerNotification.
- If an MBean attribute is an array, when you invoke the MBean's addAttributeName method to add an element to the array, the MBean emits a weblogic.management.AttributeAddNotification object. One example of an MBean that exposes addAttributeName methods is weblogic.management.configuration.XMLRegistryMBean. For more information, refer to the WebLogic Server Javadoc.
- If an MBean attribute is an array, when you invoke the MBean's removeAttributeName method to remove an element from the array, the MBean emits a weblogic.management.AttributeRemoveNotification object.
For more information about the javax.management notification types, refer to the JMX 1.0 API documentation, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.
For more information about the weblogic.management notification types, refer to the Javadoc for AttributeAddNotification and AttributeRemoveNotification.
Creating a Notification Listener
To create a notification listener:
- Create a class that implements one of the following:
- For a client that runs within the same JVM as WebLogic Server, implement javax.management.NotificationListener.
- For a client that runs in a remote JVM, implement weblogic.management.RemoteNotificationListener.
RemoteNotificationListener extends javax.management.NotificationListener and java.rmi.Remote, making MBean notifications available to external clients via RMI.
- Within the class, add one of the following:
- For a client that runs within the same JVM as WebLogic Server, add a NotificationListener.handleNotification(Notification notification, java.lang.Object handback) method.
- For a client that runs within the same JVM as WebLogic Server, add a RemoteNotificationListener.handleNotification(Notification notification, java.lang.Object handback) method.
Note: Your implementation of this method should return as soon as possible to avoid blocking its notification broadcaster.
- To retrieve data from the notification objects that the listener receives, within your handleNotification method, invoke javax.management.Notification methods on the notification objects.
For example, to retrieve the time stamp associated with the notification, invoke notification.getTimeStamp().
Because all notification types extend javax.management.Notification, the following Notification methods are available for all notifications:
- getMessage()
- getSequenceNumber()
- getTimeStamp()
- getType()
- getUserData()
For more information on Notification methods, refer to the javax.management.Notification Javadoc in the JMX 1.0 API documentation, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.
- Most notification types provide additional methods for retrieving data that is specific to the notification. For example, WebLogicLogNotification provides methods for retrieving specific attributes of WebLogic Server log messages, such as getSeverity(), which retrieves the severity level that the log message specifies.
If you want to retrieve data that is specific to a notification type (and therefore not retrievable through the standard javax.management.Notification methods):
- Add logic within the handleNotification method to filter through the notifications and select only notifications of a specific type.
- Invoke methods that the notification type provides to extract data from the notification object.
if(notification instanceof MonitorNotification) {
MonitorNotification monitorNotification = (MonitorNotification) notification;
System.out.println("This notification is a MonitorNotification");
System.out.println("Observed Attribute: " +
monitorNotification.getObservedAttribute() );
}In addition to the previous steps, consider the following while creating your NotificationListener class:
- Unless you create and use a notification filter, your listener receives all notifications (of all notification types) from the MBeans with which it is registered.
Instead of using one listener for all possible notifications that an MBean emits, the best practice is to use a combination of filters and listeners. While having multiple listeners adds to the amount of time for initializing the JVM, the trade-off is ease of code maintenance.
- If your WebLogic Server environment contains multiple instances of MBean types that you want to monitor, you can create one notification listener and then create as many registration classes as MBean instances that you want to monitor.
For example, if your WebLogic Server domain contains three JDBC connection pools, you can create one listener class that listens for AttributeChangeNotifications. Then, you create three registration classes. Each registration class registers the listener with a specific instance of a JDBCConnectionPoolRuntime MBean.
- While the handleNotification method signature includes an argument for a handback object, your listener does not need to retrieve data from or otherwise manipulate the handback object. It is an opaque object that helps the listener to associate information regarding the MBean emitter.
The following example creates a remote listener. Then the listener receives a AttributeChangeNotification object, it uses AttributeChangeNotification methods to retrieve the name of the attribute with a changed value, and the old and new values.
Listing 6-1 Notification Listener
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import weblogic.management.RemoteNotificationListener;
import javax.management.AttributeChangeNotification;public class MyListener implements RemoteNotificationListener {public void handleNotification(Notification notification, Object obj) {if(notification instanceof AttributeChangeNotification) {
AttributeChangeNotification attributeChange =
(AttributeChangeNotification) notification;
System.out.println("This notification is an
AttributeChangeNotification");
System.out.println("Observed Attribute: " +
attributeChange.getAttributeName() );
System.out.println("Old Value: " + attributeChange.getOldValue() );
System.out.println("New Value: " + attributeChange.getNewValue() );
}
}
}
Creating a Notification Filter
To create and register a filter:
- Create a serializable class that implements javax.management.NotificationFilter.
Optionally import the javax.management.NotificationFilterSupport class, which provides utility methods for filtering notifications. For more information about using these methods, refer to the JMX 1.0 API documentation, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.
The filter needs to be serializable only if it is used in a remote notification listener. A class that is used with RMI must be serializable so it can be deconstructed and reconstructed in remote JVMs.
- Use the isNotificationEnabled(Notification notification) method to indicate whether the serializable object returns a true value when a set of conditions are satisfied.
If the boolean returns true, then the filter forwards the notification to the listener with which the filter is registered.
- (Optional) You can include code that retrieves data from notifications and carries out actions based on the data in the notification. For example, your filter can use javax.management.AttributeChangeNotification methods to view the new value of a specific attribute. If the value is over a threshold that you specify, you can use JavaMail API to send e-mail to an administrator.
Listing 6-2 provides an example NotificationFilter that forwards only notifications of type AttributeChangeNotification.
Listing 6-2 Example Notification Filter
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.AttributeChangeNotification;public class MyHiCountFilter implements NotificationFilter,
java.io.Serializable {public boolean isNotificationEnabled(Notification notification) {
if (!(notification instanceof AttributeChangeNotification)) {
return false;
}
AttributeChangeNotification acn =
(AttributeChangeNotification)notification;
acn.getAttributeName().equals("ActiveConnectionsHighCount"); {
return true;
}
}
}
Adding Filter Classes to the Server Classpath
If you create a filter for a listener that runs in a remote JVM, you can add the filter's classes to the classpath of the server instance from which you are listening for notifications. Although the listener runs in the remote JVM, adding the filter's classes to the server' s classpath minimizes the transportation of serialized data between the filter and the listener. (See Figure 6-3.)
Figure 6-3 Filters Can Run on WebLogic Server
Registering a Notification Listener and Filter
After you implement a notification listener class and optional filter class, you create an additional class that registers your listener and filter with an MBean instance. You must create one registration class for each MBean instance that you want to monitor.
To register a notification listener and filter:
- Create a class that retrieves the MBeanHome interface and then uses MBeanHome to retrieve the MBeanServer interface.
If you want to register a listener and filter with an Administration MBean, retrieve the Administration MBeanHome, which resides only on the Administration Server. If you want to register with a Local Configuration MBean or a Runtime MBean, retrieve the Local MBeanHome for the server instance that hosts the MBean.
- Instantiates the listener class and filter class that you created.
- Constructs the WebLogicObjectName of the MBean with which you want to register.
For a list of commonly monitored MBeans and their WebLogicObjectName, refer to Table 6-1.
- Registers the listener and filter by passing the WebLogicObjectName, listener class, and filter class to the addNotificationListener() method of the MBeanServer interface.
While Figure 6-1 illustrates registering a listener and filter directly with an MBean (which you can do by calling the MBean's addNotificationListener() method), in practice it is preferable to use the addNotificationListener() method of the MBeanServer interface, which saves the trouble of looking up a particular MBean simply for registration purposes.
The following example is a registration class that runs in a remote JVM. If the class ran within the same JVM as a WebLogic Server instance, the code for retrieving the MBeanHome interface would be simpler. For more information, refer to Accessing an MBeanHome Interface.
The example class registers the listener from Listing 6-1 and filter from Listing 6-2 with the Server Administration MBean for a server instance named Server1. In the example, weblogic is a user who has permission to view and modify MBean attributes. For information about permissions to view and modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.
The example class also includes some code the keep the class active until it receives a notification. Usually this code is not necessary because a listener class runs in the context of some larger application that is responsible for invoking the class and keeping it active. It is included here so you can easily compile and see the example working.
Listing 6-3 Registering a Listener for an Administration MBean
import java.util.Set;
import java.util.Iterator;
import java.rmi.RemoteException;
import javax.naming.Context;
import javax.management.ObjectName;
import javax.management.Notification;import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.WebLogicObjectName;
import weblogic.management.RemoteMBeanServer;
import weblogic.management.configuration.ServerMBean;public class listener {public static void main(String[] args) {MBeanHome home = null;
RemoteMBeanServer rmbs = null;//domain variables
String url = "t3://localhost:7001";
String serverName = "Server1";
String username = "weblogic";
String password = "weblogic";//Using MBeanHome to get MBeanServer.
try {
Environment env = new Environment();
env.setProviderUrl(url);
env.setSecurityPrincipal(username);
env.setSecurityCredentials(password);
Context ctx = env.getInitialContext();//Getting the Administration MBeanHome.
home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
System.out.println("Got the Admin MBeanHome: " + home );
rmbs = home.getMBeanServer();
} catch (Exception e) {
System.out.println("Caught exception: " + e);
}try {
//Instantiating your listener class.
MyListener listener = new MyListener();
MyFilter filter = new MyFilter();//Constructing the WebLogicObjectName of the MBean that you want
//to listen to.
WebLogicObjectName mbeanName = new WebLogicObjectName(serverName,
"Server",home.getDomainName());
System.out.println("Created WebLogicObjectName: " + mbeanName);//Passing the name of the MBean and your listener class to the
//addNotificationListener method of MBeanServer.
rmbs.addNotificationListener(mbeanName, listener, filter, null);
System.out.println("\n[myListener]: Listener registered ...");//Keeping the remote client active.
System.out.println("pausing...........");
System.in.read();
} catch(Exception e) {
System.out.println("Exception: " + e);
}
}
}
Listening for Configuration Auditing Messages: Main Steps
By default, the Administration Server emits a log message when a user changes the configuration or invokes management operations on any resource within a domain. For example, if a user disables SSL on a Managed Server in a domain, the Administration Server emits a log message. These messages provide an audit trail of changes within a domain's configuration (configuration auditing). See "Configuration Auditing in Administration Console Online Help.
To create and use a JMX listener and filter that respond to configuration auditing messages:
- Create and compile a notification listener that extracts information from WebLogic Server log messages.
See Notification Listener for Configuration Auditing Messages.
- Create and compile a notification filter that selects only configuration auditing messages.
See Notification Filter for Configuration Auditing Messages.
- Create and compile a class that registers the listener and filter with the Administration Server's LogBroadcasterRuntime MBean. This is the MBean that a WebLogic Server instance uses to broadcast its log messages as JMX notifications.
- Add the notification filter to the classpath for the Administration Server.
If the notification listener runs within the Administration Server's JVM (for example, if it runs as a startup class), add the notification listener and registration class to the Administration Server's classpath as well.
- Invoke the registration class or configure it as a startup class for the Administration Server.
See "Startup and Shutdown Classes in Administration Console Online Help.
Notification Listener for Configuration Auditing Messages
Like the notification listener in Listing 6-1, the listener in Listing 6-4 implements RemoteNotificationListener and its handleNotification method.
Because all configuration auditing messages are of type WebLogicLogNotification, the listener in Listing 6-4 imports the WebLogicLogNotification interface and uses its methods to retrieve information within each configuration auditing message.
Listing 6-4 Notification Listener for Configuration Auditing Messages
import javax.management.Notification;
import javax.management.NotificationListener;
import weblogic.management.RemoteNotificationListener;
import weblogic.management.logging.WebLogicLogNotification;public class ConfigAuditListener implements RemoteNotificationListener { public void handleNotification(Notification notification, Object obj) { WebLogicLogNotification changeNotification = (WebLogicLogNotification) notification; System.out.println("A user has attempted to change the configuration of a WebLogic Server domain."); System.out.println("Admin Server Name: " + changeNotification.getServername() ); System.out.println("Time of attempted change:" + changeNotification.getTimeStamp() ); System.out.println("Message details:" + changeNotification.getMessage() ); System.out.println("Message ID string:" + changeNotification.getMessageId() ); }
}
Notification Filter for Configuration Auditing Messages
Without a notification filter, the listener in Listing 6-4 would print the Server Name, Timestamp, and Message Text for all messages that the Administration Server broadcast.
To forward only the configuration auditing message that indicates a resource has been modified, the filter in Listing 6-5 uses the WebLogicLogNotification.getMessageId method to retrieve the message ID of all incoming log notifications.
The resource-change configuration auditing message is identified by the message ID 159904 (see Configuration Auditing in Administration Console Online Help). If the message ID value in an incoming log notification matches the configuration auditing message ID, the filter evaluates as true and forwards the message to its registered listener.
Listing 6-5 Notification Filter for Configuration Auditing Messages
import javax.management.Notification;
import javax.management.NotificationFilter;
import weblogic.management.logging.WebLogicLogNotification;public class ConfigAuditFilter implements NotificationFilter , java.io.Serializable{ int configChangedId = 159904;public boolean isNotificationEnabled(Notification notification) { if (!(notification instanceof WebLogicLogNotification)) { return false;}WebLogicLogNotification wln = (WebLogicLogNotification)notification; int messageId = wln.getMessageId(); if (configChangedId == messageId) { return true;} else { return false; } }
}
Registration Class for Configuration Auditing Messages
The class in Listing 6-6 registers the notification listener and filter with the LogBroadcasterRuntime MBean of the Administration Server. This MBean is a singleton in each instance of WebLogic Server and is always named TheLogBroadcaster.
Listing 6-6 Registration Class for Configuration Auditing Messages
import java.util.Set;
import java.util.Iterator;
import java.rmi.RemoteException;
import javax.naming.Context;
import javax.management.ObjectName;
import javax.management.Notification;
import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.WebLogicObjectName;
import weblogic.management.RemoteMBeanServer;
import weblogic.management.configuration.ServerMBean;public class ListenRegistration { public static void main(String[] args) { MBeanHome home = null; RemoteMBeanServer rmbs = null;//domain variables String url = "t3://localhost:7001"; String serverName = "examplesServer"; String username = "weblogic"; String password = "weblogic";//Using MBeanHome to get MBeanServer. try { Environment env = new Environment(); env.setProviderUrl(url); env.setSecurityPrincipal(username); env.setSecurityCredentials(password); Context ctx = env.getInitialContext();//Getting the Administration MBeanHome. home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME); System.out.println("Got the Admin MBeanHome: " + home ); rmbs = home.getMBeanServer();} catch (Exception e) { System.out.println("Caught exception: " + e); }try { //Instantiating your listener class. ConfigAuditListener listener = new ConfigAuditListener(); ConfigAuditFilter filter = new ConfigAuditFilter();//Constructing the WebLogicObjectName of the MBean that you want //to listen to.WebLogicObjectName mbeanName = new WebLogicObjectName( "TheLogBroadcaster", "LogBroadcasterRuntime", home.getDomainName(), serverName ); System.out.println("Created WebLogicObjectName: " + mbeanName);//Passing the name of the MBean and your listener class to the //addNotificationListener method of MBeanServer. rmbs.addNotificationListener(mbeanName, listener, filter, null); System.out.println("\n[myListener]: Listener registered ...");//Keeping the remote client active. System.out.println("pausing..........."); System.in.read(); } catch(Exception e) { System.out.println("Exception: " + e);} }
}
Using Monitor MBeans to Observe Changes: Main Steps
To configure and use monitor MBeans:
- Choose a monitor MBean type that matches the type of data you want to observe. Choosing a Monitor MBean Type
- Create a listener class that can listen for notifications from monitor MBeans. See Creating a Notification Listener for a Monitor MBean.
- Create a class that configures a monitor MBean, registers your listener class with the monitor MBean, and then registers the monitor MBean with an observed MBean. Instantiating the Monitor and Listener
Choosing a Monitor MBean Type
WebLogic Server provides monitor MBeans that are specialized to observe changes in specific data types. You must configure and instantiate the type of monitor MBean that matches the type of the object that an MBean returns for an attribute value. For example, a monitor MBean based on the StringMonitor type can observe an attribute that is declared as an Object as long as actual values of the attributes are String instances, as determined by the instanceof operator.
To choose a monitor type:
- Determine the type of object that is returned by the MBean attribute that you want to observe by doing any of the following:
- Refer to the WebLogic Server Javadoc.
- Use the weblogic.Admin GET command, which provides information about the MBean that you specify. For more information, refer to "MBean Management Command Reference" in Configuring and Managing WebLogic Server.
- Use the javap command on the MBean you are monitoring. The javap command is a standard Java utility that disassembles a class file.
- Choose a monitor type from the following table.
A Monitor MBean of This Type Observes This Object Type CounterMonitor Integer GaugeMonitor Integer or floating-point (Byte, Integer, Short, Long, Float, Double) StringMonitor String
For more information about monitor types, refer to the JMX 1.0 specification, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.
Monitor Notification Types
Each type of monitor MBean emits specific types of javax.management.monitor.MonitorNotification notifications. For any given notification, you can use the MonitorNotification.getType() method to determine its type.
The following table describes the type of notifications that monitor MBeans emit.
A Monitor MBean of This Type
Emits This MonitorNotification Type
CounterMonitor A counter monitor emits a jmx.monitor.counter.threshold when the value of the counter reaches or exceeds a threshold known as the comparison level. GaugeMonitor
- If the observed attribute value is increasing and becomes equal to or greater than the high threshold value, the monitor emits a notification type of jmx.monitor.gauge.high. Subsequent crossings of the high threshold value do not cause further notifications unless the attribute value becomes equal to or less than the low threshold value.
- If the observed attribute value is decreasing and becomes equal to or less than the low threshold value, the monitor emits a notification type of jmx.monitor.gauge.low. Subsequent crossings of the low threshold value do not cause further notifications unless the attribute value becomes equal to or greater than the high threshold value.
StringMonitor
- If the observed attribute value matches the string to compare value, the monitor emits a notification type of jmx.monitor.string.matches. Subsequent matches of the string to compare values do not cause further notifications unless the attribute value differs from the string to compare value.
- If the attribute value differs from the string to compare value, the monitor emits a notification type of jmx.monitor.string.differs. Subsequent differences from the string to compare value do not cause further notifications unless the attribute value matches the string to compare value.
Error Notification Types
All monitors can emit the following notification types to indicate error cases:
- jmx.monitor.error.mbean, which indicates that the observed MBean is not registered in the MBean Server. The observed object name is provided in the notification.
- jmx.monitor.error.attribute, which indicates that the observed attribute does not exist in the observed object. The observed object name and observed attribute name are provided in the notification.
- jmx.monitor.error.type, which indicates that the object instance of the observed attribute value is null or not of the appropriate type for the given monitor. The observed object name and observed attribute name are provided in the notification.
- jmx.monitor.error.runtime, which contains exceptions that are thrown while trying to get the value of the observed attribute (for reasons other than the cases described above).
The counter and the gauge monitors can also emit the following jmx.monitor.error.threshold notification type under the following circumstances:
- For a counter monitor, when the threshold, the offset, or the modulus is not of the same type as the observed counter attribute.
- For a gauge monitor, when the low threshold or high threshold is not of the same type as the observed gauge attribute.
Creating a Notification Listener for a Monitor MBean
As any other MBean, monitor MBeans emit notifications by implementing javax.management.NotificationBroadcaster. To create a listener for notifications from a monitor MBean, create a class that does the following:
- Implements NotificationBroadcaster or weblogic.management.RemoteNotificationListener.
- Includes the NotificationListener.handleNotification() or the RemoteNotificationListener.handleNotification() method.
You can register the same notification listener with instances of LogBroadcasterMBean, monitor MBeans, or any other MBean.
The example below creates a listener object for an application that runs in a JVM outside the WebLogic Server JVM. It includes logic that outputs additional messages when it receives notifications from monitor MBeans. You could further refine the logic so that listener responds differently to the different types of monitor notifications described in Monitor Notification Types.
Listing 6-7 Listener for Monitor Notifications
import java.rmi.Remote;
import javax.management.Notification;
import javax.management.NotificationListener;
import javax.management.monitor.MonitorNotification;import weblogic.management.RemoteNotificationListener;
import weblogic.management.MBeanHome;public class CounterListener implements RemoteNotificationListener {public void handleNotification(Notification notification ,Object obj) {
System.out.println("\n\n Notification Received ...");
System.out.println("Type=" + notification.getType() );
System.out.println("SequenceNumber=" +
notification.getSequenceNumber());
System.out.println("Source=" + notification.getSource());
System.out.println("Timestamp=" + notification.getTimeStamp() + "\n" );
if(notification instanceof MonitorNotification) {
MonitorNotification monitorNotification = (MonitorNotification)
notification;
System.out.println("This notification is a MonitorNotification");
System.out.println("Observed Attribute: " +
monitorNotification.getObservedAttribute() );
System.out.println("Observed Object: " +
monitorNotification.getObservedObject() );
System.out.println("Trigger value: " +
monitorNotification.getTrigger() );
}
}
}
Instantiating the Monitor and Listener
The steps you take to register a monitor MBean with an observed MBean differ depending on whether you are registering the monitor MBean on a single server instance or on multiple server instances in a domain.
To register a monitor MBean on a single server instance:
- Instantiate and configure the monitor MBean.
- Retrieve the MBeanHome interface of the server instance that hosts the observed MBean.
- Register the monitor MBean with the observed MBean.
To register a monitor MBean on multiple server instances:
- Instantiate and configure the monitor MBean.
- Retrieve the MBeanHome interface of each server instance that hosts instances of the observed MBean.
- For each server instance, register the monitor MBean with the observed MBean instance.
The following sections provide examples for both tasks:
- Example: Monitoring an MBean on a Single Server
- Example: Monitoring Instances of an MBean on Multiple Servers
Example: Monitoring an MBean on a Single Server
The following example creates a counter monitor for the ServicedRequestTotalCount attribute of the ExecuteQueRuntimeMBean, which returns the number of requests that have been processed by the corresponding execution queue. WebLogic Server uses execute queues to optimize the performance of critical applications. For more information, refer to "Using Execute Queues to Control Thread Usage."
To create a counter monitor for an ExecuteQueRuntimeMBean on a single server instance, the example class in Listing 6-8:
- Instantiates a javax.management.monitor.CounterMonitor object.
- Configures the monitor object by doing the following:
- Assigns the JMX object name for the monitor object to a variable.
Listing 6-8 uses WebLogicObjectName(), but you can use javax.management.ObjectName for the monitor object. The object name must be unique throughout the entire WebLogic Server domain, and it must follow the JMX conventions:
- Uses WebLogicObjectName() to assign the JMX object name for the observed MBean to a variable.
If the observed MBean is a WebLogic Server MBean, use WebLogicObjectName() instead of javax.management.ObjectName. You can also use MBeanHome.getMBeansByType() or other WebLogic Server APIs to get the name of the observed MBean object.
For a list of commonly monitored MBeans and their WebLogicObjectName, refer to Table 6-1.
- Sets values for the monitor's threshold parameters.
The set of available parameters varies, depending on whether you are instantiating a CounterMonitor, GaugeMonitor, or StringMonitor.
- Configures the monitor object using the monitor's APIs.
For information about the parameters that you pass to configure monitors, refer to:
- Instantiates the listener object that you created in Creating a Notification Listener for a Monitor MBean.
- Registers the listener object using the monitor's addNotificationListener() method.
- (This step is needed only if your monitor class runs in a JVM that is outside the WebLogic Server JVM.) Pre-registers a reference to the MBean Server in the remote JVM by doing the following:
- Retrieve the MBeanServer interface using the Administration MBeanHome interface.
- Use the monitor's preRegister() method.
- Starts the monitor using the monitor's start() method.
In the example, weblogic is a user who has permission to view and modify MBean attributes. For information about permissions to view and modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.
Listing 6-8 Instantiating a Counter Monitor and Listener on a Single Server
import javax.management.monitor.CounterMonitor;
import javax.management.ObjectName;
import javax.naming.Context;import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.WebLogicObjectName;
import weblogic.management.RemoteMBeanServer;
import weblogic.management.configuration.ServerMBean;public class clientMonitor {// The name of the WebLogic domain, please change this to match the //
// name of your installation specific domain name //
private static String weblogicDomain = "mydomain";// The name of the WebLogic server, please change this to match the //
// name of your installation specific server name //
private static String weblogicServer = "myserver";public static void main (String Args[]) {try {
//Instantiate a CounterMonitor
CounterMonitor monitor = new CounterMonitor();// construct the objectName for your CounterMonitor object
WebLogicObjectName monitorObjectName = new
WebLogicObjectName("MyCounter",
"CounterMonitor",weblogicDomain);// Construct the objectName for the parent MBean
WebLogicObjectName pObjectName = new
WebLogicObjectName(weblogicServer,
"ServerRuntime",weblogicDomain);// Construct the objectName for the observed MBean
WebLogicObjectName qObjectName = new
WebLogicObjectName("default",
"ExecuteQueueRuntime",weblogicDomain,
weblogicServer, pObjectName);// Define variables to be used when configuring your CounterMonitor
// object.
Integer threshold = new Integer(10);
Integer offset = new Integer(1);//Configure your monitor object using the CounterMonitor APIs
monitor.setThreshold(threshold);
monitor.setNotify(true);
monitor.setOffset(offset);
monitor.setObservedObject(qObjectName);
monitor.setObservedAttribute("ServicedRequestTotalCount");//Instantiate and register your listener with the monitor
CounterListener listener = new CounterListener();
monitor.addNotificationListener(listener, null, null);//Use the Administration MBeanHome API to get the MBeanServer
//interface this is needed when you are registering a monitor from
// the client side.
String url = "t3://localhost:7001"; //URL of the Admin Server
String username = "weblogic";
String password = "weblogic";
MBeanHome home = null;
Environment env = new Environment();
env.setProviderUrl(url);
env.setSecurityPrincipal(username);
env.setSecurityCredentials(password);
Context ctx = env.getInitialContext();
home = (MBeanHome) ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);
RemoteMBeanServer rmbs = home.getMBeanServer();
monitor.preRegister(rmbs, monitorObjectName);//start the monitor
monitor.start();
}catch (Exception e) { e.printStackTrace(); }
}
}
Example: Monitoring Instances of an MBean on Multiple Servers
A WebLogic Server domain maintains a set of MBean instances for each server instance. For example, each server instance hosts its own ServerRuntimeMBean, LogMBean, and ExecuteQueueRuntimeMBean.
Some MBeans are instantiated only if a server instance hosts a specific service. For example, if you use the Java Messaging Service , each server instance that is defined as a JMS destination hosts its own JMSDestinationRuntimeMBean. For information about JMS destinations, refer to "Using Distributed Destinations in Programming WebLogic JMS.
To monitor instances of a JMSDestinationRuntimeMBean on each server instance in a domain, the example in Listing 6-9:
- Retrieves the domain's Administration MBeanHome.
- Invokes MBeanHome.getMBeansByType to retrieve all instances of JMSDestinationRuntimeMBean in the domain.
- For each JMSDestinationRuntimeMBean, the class instantiates and configures a GaugeMonitor object by doing the following:
- Instantiates a GaugeMonitor object using the default constructor of javax.management.monitor.GaugeMonitor.
- Configures the GaugeMonitor object.
To provide the value for the GaugeMonitor.setObservedObject method, the class casts the JMSDestinationRuntimeMBean as a WebLogicMBean. Then it invokes WebLogicMBean.getObjectName.
- For each GaugeMonitor object, the class instantiates a notification listener and registers the listener with the monitor by invoking the GaugeMonitor.addNotificationListener method.
To see an example notification listener, refer to Creating a Notification Listener for a Monitor MBean.
- For each GaugeMonitor object, the class registers a reference to the MBean Server in the host server's JVM by doing the following:
- Invokes the Context.lookup(MBeanHome.JNDI_NAME.serverName) method to retrieve the MBeanServer interface using the Administration MBeanHome interface.
To provide the serverName value in the lookup method, the class refers to the WebLogicMBean cast of the JMSDestinationRuntimeMBean and invokes its WebLogicMBean.getObjectName().getLocation() method.
- Invokes the monitor's preRegister() method.
- Starts the monitor using the monitor's start() method.
- Includes code that keep the class active. Usually this code is not necessary because a monitor runs in the context of some larger application that is responsible for invoking the class and keeping it active. It is included here so you can easily compile and see the example working.
- Includes code that stops the monitor (and thereby ends the thread that the JVM assigned to the monitor).
In the example, weblogic is a user who has permission to view and modify MBean attributes. For information about permissions to view and modify MBeans, refer to "Security Roles in the Securing WebLogic Resources guide.
Listing 6-9 Instantiating a Gauge Monitor on Multiple Server Instances
import java.util.Set;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import javax.naming.Context;import javax.management.monitor.GaugeMonitor;
import javax.management.ObjectName;
import weblogic.jndi.Environment;
import weblogic.management.MBeanHome;
import weblogic.management.WebLogicMBean;
import weblogic.management.RemoteMBeanServer;
import weblogic.management.runtime.JMSDestinationRuntimeMBean;
import weblogic.management.WebLogicObjectName;public class GaugeMonitorClient {public static void main (String Args[]) throws Exception {
//url of the Administration Server
String url = "t3://localhost:7001";
String username = "weblogic";
String password = "weblogic";
String domain = "medrec";try {
//retrieve the Administration MBeanHome
Environment env = new Environment();
env.setProviderUrl(url);
env.setSecurityPrincipal(username);
env.setSecurityCredentials(password);
Context ctx = env.getInitialContext();
MBeanHome home = (MBeanHome)
ctx.lookup(MBeanHome.ADMIN_JNDI_NAME);//retrieve all JMSDestinationRuntimeMBean instances in
//the domain
Set mbeanSet =
home.getMBeansByType("JMSDestinationRuntime");System.out.println("Retrieved the following mbeans");
Iterator iter = mbeanSet.iterator();
while (iter.hasNext()){
WebLogicMBean bean = (WebLogicMBean) iter.next();
System.out.println("Name = "+bean.getName());
System.out.println("WebLogicObjectName =
"+bean.getObjectName()+"\n");
}List list = Collections.synchronizedList(new ArrayList());
Iterator it = mbeanSet.iterator();
int i = 0;
while (it.hasNext()) {
//instantiate a Gauge monitor
GaugeMonitor monitor = new GaugeMonitor();
//configure the Gauge monitor
monitor.setThresholds(new Long("30"), new Long("4"));
monitor.setNotifyHigh(true);
monitor.setNotifyLow(true);
WebLogicMBean bean = (WebLogicMBean) it.next();
ObjectName myON = bean.getObjectName();
monitor.setObservedObject(myON);
monitor.setObservedAttribute("MessagesCurrentCount");//instantiate and register a notification listener
MyNotificationListener listener = new MyNotificationListener();
monitor.addNotificationListener(listener,null,null);
//pre-registering and starting the monitor
MBeanHome localhome = (MBeanHome)
ctx.lookup(MBeanHome.JNDI_NAME
+"."+bean.getObjectName().getLocation());
RemoteMBeanServer rmbs = localhome.getMBeanServer();
WebLogicObjectName monitorObjectName = new WebLogicObjectName
("myGaugeMonitor" + (++i), "GaugeMonitor", domain,
bean.getObjectName().getLocation());
monitor.preRegister(rmbs, monitorObjectName);
monitor.start();
System.out.println("Monitor waiting on event notification.");
list.add(monitor);
myON = null;
}//Keeping the monitor active.
System.out.println("pausing...........");
System.in.read();//stopping each monitor.
Iterator deregisterList = list.iterator();
while (deregisterList.hasNext()) {
GaugeMonitor gauge = (GaugeMonitor) deregisterList.next();
System.out.println("deregistering...");
gauge.preDeregister();
}
return;
}
catch (Exception e){
e.printStackTrace();
}
}
}
Configuring CounterMonitor Objects
CounterMonitor objects observe changes in MBean attributes that are expressed as integers. The following list describes groups of CounterMonitor operations that you use to achieve typical configurations of a CounterMonitor instance:
- Sends a notification when the observed attribute exceeds the threshold.
setThreshold(int threshold);
setNotify(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the observed attribute exceeds the threshold. Then it increases the threshold by the offset value. Each time the observed attribute exceeds the new threshold, the threshold is increased by the offset value. For example, if you set Threshold to 1000 and Offset to 2000, when the observed attribute exceeds 1000, the CounterMonitor object sends a notification and increases the threshold to 3000. When the observed attribute exceeds 3000, the CounterMonitor object sends a notification and increases the threshold again to 5000.
setThreshold(int threshold);
setNotify(true);
setOffset(int offset);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the observed attribute exceeds the threshold, and increases the threshold by the offset value. When the threshold reaches the value specified by the setModulus method, the threshold is returned to the value that was specified through the latest call to the monitor's setThreshold method, before any offsets were applied. For example, if the original Threshold is set to 1000 and the Modulus is set to 5000, when the Threshold exceeds 5000, the monitor sends a notification and resets the Threshold to 1000.
setThreshold(int threshold);
setNotify(true);
setOffset(int offset);
setModulus(int modulus);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the difference between two consecutive observations exceeds the threshold. For example, the Threshold is 20 and the monitor observes an attribute value of 2. If the next observation is greater than 22, then the monitor sends a notification. However, if the value is 10 at the next observation, and 25 at the following observation, then the monitor does not send a notification because the value has not changed by more than 20 for any two consecutive observations.
setThreshold(int threshold);
setNotify(true);
setDifferenceMode(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the difference between two consecutive observations exceeds the threshold, and increases the threshold by the offset value. When the threshold reaches the value specified by the setModulus method, the threshold is returned to the value that was specified through the latest call to the monitor's setThreshold method, before any offsets were applied.
setThreshold(int threshold);
setNotify(true);
setOffset(int offset);
setModulus(int modulus);
setDifferenceMode(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");To see all possible configurations of a CounterMonitor instance, refer to the JMX 1.0 API documentation, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.
Configuring GaugeMonitor Objects
GaugeMonitor objects observe changes in MBean attributes that are expressed as integers or floating-point. The following list describes groups of GaugeMonitor operations that you use to achieve typical configurations of a GaugeMonitor instance:
- Sends a notification when the observed attribute is beyond the high threshold.
setHighThreshold(int Highthreshold);
setNotifyHigh(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the observed attribute is outside the range of the high or low threshold.
setThresholds(int Highthreshold, Lowthreshold);
setNotifyHigh(true);
setNotifyLow(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the difference between two consecutive observations is outside the range of the high or low threshold.
setThresholds(int Highthreshold, Lowthreshold);
setNotifyHigh(true);
setNotifyLow(true);
setDifferenceMode(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");GaugeMonitor does not support an offset or modulus.
To see all possible configurations of a GaugeMonitor instance, refer to the JMX 1.0 API documentation, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.
Configuring StringMonitor Objects
StringMonitor objects observe changes in MBean attributes that are expressed as strings. The following list describes groups of StringMonitor operations that you use to achieve typical configurations of a StringMonitor instance:
- Sends a notification when the observed attribute matches the string specified in StringToCompare.
setStringToCompare(String);
setNotifyMatch(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");- Sends a notification when the observed attribute differs from the string specified in StringToCompare.
setStringToCompare(String);
setNotifyDiffer(true);
setObservedObject(ObjectName);
setObservedAttribute("AttributeName");To see all possible configurations of a StringMonitor instance, refer to the JMX 1.0 API documentation, which you can download from http://jcp.org/aboutJava/communityprocess/final/jsr003/index.html. The archive that you download includes the API documentation.