ibm labs in haifa java management extensions (jmx) tal cohen [email protected]
Post on 21-Dec-2015
230 views
TRANSCRIPT
IBM Labs in Haifa
Outline
What is JMX What is JMX used for
MBeans MBean Features Static MBeans Dynamic MBeans Model MBeans
Using MBeans Adapters and Connectors MBean Services
Conclusion
IBM Labs in Haifa
Resource Management
JMX -- Java Management Extensions -- is designed for enabling Resource Management of/with Java applications
Managed resources include: Hardware (PCs, routers, printers, etc.) Operating systems Software
Management is used for: Monitoring platform health Collecting statistics Remote configuration at runtime
Including for debug usage (enabling/disabling logs, etc.)
IBM Labs in Haifa
Why JMX?
The industry-standard for resource management is SNMP Simple Network Management Protocol If only it was really simple... JMX can co-exist with SNMP
Details later At the moment, many remotely-manageable resources have their own
management interfaces "Management consoles", normally accessible via HTTP
JMX can be used to consolidate manageability features of multiple components into a single management console
IBM Labs in Haifa
Before JMX
Firewall hardware
Server
Web server software
Server Application
DB server software
Management console
Management console
Management console
Management console
Management console
IBM Labs in Haifa
Before JMX
Each management console is vendor-specific Normally, can be accessed via a web browser
But each has its own GUI, terminology, etc. Each has its own security management
Redundant and hard to control
IBM Labs in Haifa
With JMX
Firewall hardware
Server
Web server software
Server Application
DB server softwareManagement
console
JMX Agent
Adapter
= JMX MBean
IBM Labs in Haifa
With JMX
Each resource is managed using an MBean All MBeans on a given JMX Agent (or group of agents) can be managed
using a single management console
IBM Labs in Haifa
In Practice
While JMX can be used as pictured before, its main use at the moment is simple enabling the management of Java applications
Many Java applications ship with MBeans that allow user to remotely manage them at runtime BEA's WebLogic App Server JBoss App Server HP's Bluestone App Server and OpenView IBM's Tivoli and WebSphere software ...and more
IBM Labs in Haifa
MBeans and Related Terminology
An MBean is a Managed Bean Not related to Enterprise JavaBeans Somewhat similar to regular JavaBeans
An MBean can (but does not have to) be a JavaBean Normally used as a proxy for accessing a manageable resource MBeans are contained in MBean Server objects MBean Server objects are contained in JMX Agent objects Clients (management applications) can access JMX Agents via adapters
or connectors
More details will follow...
IBM Labs in Haifa
Components of an MBean
Every MBean can have:
Zero or more Attributes Read-only, write-only, or read/write
Zero or more Operations Zero or more Generated Notifications
Similar to Java events One or more Public Constructors
Collectively, these are called the MBean's features.
IBM Labs in Haifa
Standard MBeans
A standard MBean is a concrete Java class Must implement an interface called XMBean "X" is either the class's name, or (rare) the name of one of its
superclasses Both X and the XMBean interface must be public Both must be defined in the same package
IBM Labs in Haifa
Standard MBean Features
Most MBean's features are found using reflection Similar to JavaBeans without BeanInfo classes
The server uses reflection on the XMBean interface Except for constructors So only those methods that are defined in the interface are
considered MBean features Additional methods in X are ignored, even if public
public type getA() defines a readable attribute A public void setA(type) defines a writable attribute A All other public methods are operations Constructors are any public constructors define in the bean class (We'll get to notifications later.)
IBM Labs in Haifa
For Example...
public interface LoggerMBean {public int getLogLevel();public void setLogLevel(int level);public void log(int level, String line);
}
IBM Labs in Haifa
For Example... (cont.)
public class Logger implements LoggerMBean {int logLevel;String logFilename;
public Logger(String filename) { ... }public int getLogLevel() { ... }public void setLogLevel(int level) { ... }public void log(int level, String line) {
if (level >= logLevel) { ... }}public String getLogFilename() { ... }
}
A R/W attribute called LogLevel
One public constructor
One operation
Not an attribute or an operation
IBM Labs in Haifa
Class and Interface Relationships
In most common cases, the MBean class directly implements the similarly-named MBean interface The interface name equals the class's name + "MBean" e.g., class Printer implements PrinterMBean
However, there are other possibilities Indirect implementation:
class ColorPrinter extends Printer Still managed via the PrinterMBean interface
Same features, except for constructors New methods defined in ColorPrinter are not accessible for the
MBean server
IBM Labs in Haifa
Class and Interface Relationships (cont.)
Independent interface: class ColorPrinter extends Printer implements ColorPrinterMBean
Managed via ColorPrinterMBean Only features defined in ColorPrinterMBean are considered Even though PrinterMBean is also implemented, its features are
ignored Independent interface that extends another interface:
interface ColorPrinterMBean extends PrinterMBean Now ColorPrinterMBean includes all PrinterMBean methods So ColorPrinter has all features gathered from both interfaces
IBM Labs in Haifa
MBean Notifications
A standard MBean can be a source for notifications Must implement the NotificationBroadcaster interface
(All classes are from the javax.management package) Uses the publish/subscribe pattern The interface methods are:
addNotificationListener(listener, filter, handback)
Filter class can be used for filtering unwanted events per listener The handback object is passed to the listener with every event
So if it listens to several MBeans, it can identify the source Both can be null
removeNotificationListener(listener) getNotificationInfo()
IBM Labs in Haifa
MBean Notifications (cont.)
getNotificationInfo returns an array of MBeanNotificationInfo objects Each such object contains information about one type of notification
that the MBean can generate Information include type and a human-readable description
If your class has no superclass, you can simply extend the NotificationBroadcasterSupport class Provides a simple implementation for the NotificationBroadcaster interface
Includes a service method, sendNotification You must still override the getNotificationInfo method
IBM Labs in Haifa
MBean Notifications (cont.)
To generate a notification, the MBean must send a Notification object to all registered listeners After checking, for each listener, if its filter would accept this
notification type Each notification object is an instance of Notification or some
subclass thereof Information stored in each notification includes:
Type (a String; not a Java type), used for filtering SequenceNumber (an integer; optionally used for numbering
notification in a sequence) TimeStamp (long) UserData (an object ref) and Message (a String) Source (identifies the generating MBean)
IBM Labs in Haifa
Notification Listeners
To accept MBean notifications, a class must implement NotificationListener One method:
handleNotification(notification, handback) Handle it quickly -- default notification dispatching is synchronous
Or implement your own sendNotification method on the broadcasting MBean to be asynchronous
IBM Labs in Haifa
Maintaining Notification History
In many scenarios, notifications cannot be pushed to clients i.e., clients cannot be notification listeners e.g., web browsers as clients
Due to HTTP being stateless, etc. To make notifications available to such clients, they must pull notification
info Thus, you might want your MBean to maintain a notification history that
can be queried e.g., stored in a database If stored in memory, only the last n notifications should be kept
IBM Labs in Haifa
Dynamic MBeans
Just like standard MBeans, dynamic MBeans have attributes, operations, public constructors and notifications
However, unlike standard MBeans, these features are not located using reflection
Instead, a dynamic MBean implements the DynamicMBean interface: getAttribute(String attrName) setAttribute(Attribute attr)
The Attribute class simple contains a name + value pair getAttributes/setAttributes
Work with arrays to get/set all attributes at once invoke(actionName, params, signature) getMBeanInfo()
IBM Labs in Haifa
MBeanInfo
The MBeanInfo class is used by dynamic MBeans to describe themselves
Fields include an array each of MBeanConstructorInfo, MBeanAttributeInfo, MBeanOperationInfo and MBeanNotificationInfo All inherit from MBeanFeatureInfo
Allows you to dynamically build the features of an MBean The same MBean class can be used to manage different resources Useful for resources with an unstable interface (changes with every
release, etc.)
IBM Labs in Haifa
Standard MBeans and MBeanInfo
A little implementation secret: when handling standard MBeans, the server simply uses reflection to create an MBeanInfo object for the MBean
With dynamic MBeans, you simply provide this MBeanInfo object directly.
IBM Labs in Haifa
Model MBeans
Model MBeans are "dynamic dynamic MBeans" An implementation is provided as part the JMX Implements the DynamicMBean interface Includes methods for changing the MBeanInfo at runtime, as part of the
managed interface Can be used to model a resource by describing its management
interface at runtime.
IBM Labs in Haifa
MBean Names
Every MBean instance has a name Represented using the ObjectName class The name format is:
domainName:keyValueList "domainName" (unrelated to Internet domain names) is used for logically
grouping MBeans "keyValueList" is a list of comma-separated key=value pairs
Unrelated to the bean's attributes or parameters Sample MBean names:
Tools:name=Printer3 Tools:name=ProxyServer,port=8080
Each MBean instance name must be unique within the server
IBM Labs in Haifa
MBean Servers
An MBean server is a Java object used to contain and manipulate MBeans
Each server has a domain name Created using a factory
MBeanServer mbs = MBeanServerFactory.createMBeanServer("Tools");
IBM Labs in Haifa
Registering MBeans on a Server
Given an MBean and a server:
mbs.registerMBean(new Printer(...), new ObjectName("Tools:name=Printer3"));
The provided object must be a compliant MBean (implement an XMBean interface or DynamicMBean)
Given an ObjectName, you can also use isRegistered(name) and unregisterMBean(name)
IBM Labs in Haifa
Letting the Server Create the Instance
The MBean object must exist in the MBean server's JVM If you access the server remotely, you can simply ask it to create an
instance
mbs.createMBean(className, objName); or
mbs.createMBean(className, objName, params, sig); params is an Object array; sig is a String array, identifying the
arguments types of the constructor
You can specify a particular class-loader to use, if that class loader is available as an MBean on the same server:
mbs.createMBean(className, objName, loaderObjName);
IBM Labs in Haifa
Manipulating MBeans in a Server
If you have a reference to the MBean, you can manipulate it directly Alternatively, all manipulation actions are possible via the server
All you need is the MBean's name
Accessing attributes:
mbs.getAttribute(objName, attrName);mbs.setAttribute(objName, attribute);
Accessing attributes en-masse:
mbs.getAttributes(objName);mbs.setAttributes(objName, attributeList);
IBM Labs in Haifa
Manipulating MBeans in a Server (cont.)
Invoking operations:
mbs.invoke(objName, methodName, params, sig); methodName is just a String
Registering for notifications:
mbs.addNotificationListener(objName, listener, filter, handback); or
mbs.addNotificationListener(objName, listenerObjName, filter, handback);
Here the listener is itself an MBean on the same server
IBM Labs in Haifa
Obtaining Information about MBeans
You can get the MBean meta-data:
mbs.getMBeanInfo(objName); Works for Dynamic as well as Standard MBeans
And you can also run a type-check:
mbs.isInstanceOf(objName, className)
IBM Labs in Haifa
Finding MBeans in a Server
Finding an MBean is easy if you know its name But what if you need "all MBeans of a given type"? Or perhaps "all MBeans with an attribute called 'count' that equals 10 or
more"? We need a query language for MBeans
"MBeans QL"? Queries are built using QueryExp objects Each QueryExp represents a boolean predicate relating to MBean
attributes QueryExps can be combined using logical operators
IBM Labs in Haifa
Building MBean Queries
QueryExp exp = Query.gt(Query.attr("count"), Query.value(10)) "count > 10"
QueryExp prob1 = Query.eq(Query.attr("inkLevel"), Query.value("LOW"));QueryExp prob2 = Query.lt(Query.attr("paperCount"), Query.value(50));QueryExp exp = Query.or(prob1, prob2); "(inkLevel = LOW) or (paperCount < 50)"
IBM Labs in Haifa
Building MBean Queries (cont.)
Boolean operator methods included in the Query class: gt (greater than), lt (less than), eq (=), geq (≥), leq (≤), match (wildcard matching), initialSubString, anySubString, finalSubString, between
Query methods that can be used to construct values: plus, minus, div, times, value (used to generate constants; overloaded for all primitive types)
Query methods that can be used to combine QueryExp elements: and, or, not
IBM Labs in Haifa
Running MBean Queries
After building the required query, you can execute it on the MBean server:
mbs.queryMBeans(objName, query);
The provided ObjectName object can represent a partial object name, using wildcards A few examples:
DomainName:* -- all MBeans from a given domain *:key=val -- all MBeans with a key that equals the given value,
regardless of the domain Tools???:key=val *:*
IBM Labs in Haifa
Connecting to MBean Servers
All those MBean server methods are nice, but how do you access the server?
If you create the MBean server yourself (using the MBeanServerFactory), you can simply invoke methods on the server object
But how can you use an MBean server you did not create? The server does not listen on any communication port The server does not speak any communication protocol
We need connectors or adapters.
IBM Labs in Haifa
Connectors and Adapters
An adapter is an MBean that, once registered in an MBean server, listens on a particular port and speaks particular protocol For example, an HTML adapter accepts HTTP requests and
generates HTML output You can use industry-standard tools (e.g., a browser) to talk with an
adapter A connector is an MBean that, once registered in an MBean server, can
co-operate with a peer on a client machine The peer is specifically-written It is, in fact, considered part of the MBean For example, an RMI adapter
IBM Labs in Haifa
Example: Registering an Adapter
An adapter (or a connector) should be registered on the server just like any other MBean
Registration is normally performed by the code that creates the server Sample code:
MBeanServer mbs = MBeanServerFactory.createMBeanServer("Tools");HtmlAdaptorServer adapter = new HtmlAdaptorServer();adapter.setPort(9092);ObjectName adaptorName = new ObjectName("Tools:name=htmladapter,port=9092");mbs.registerMBean(adapter, adapterName);adapter.start();
(exception handling code removed for simplicity)
IBM Labs in Haifa
The HtmlAdaptorServer class
HtmlAdaptorServer is not a standard part of JMX It is provided in Sun's JMX Reference Implementation
In the unsupported package com.sun.jdmk.comm Equivalent classes exist in all commercial JMX implementations Once put in an MBean server and started, the adaptor listens on the
specified port Can be accessed using any web browser Provides a generic interface that allows you to manipulate any MBean
attribute, invoke MBean operations, create and register new MBeans, etc. Limitation: only primitive and String parameters can be used
IBM Labs in Haifa
Example: Registering a Connector
The server-side is rather similar:
MBeanServer mbs = MBeanServerFactory.createMBeanServer("Tools");RmiConnectorServer connector = new RmiConnectorServer();connector.setPort(2099);ObjectName connectorName = new ObjectName("Tools:name=RMIConnector");mbs.registerMBean(connector, connectorName);connector.start();
The same server can include multiple adapters and/or connectors After all, they're just MBeans
IBM Labs in Haifa
Example: Registering a Connector (Cont.)
The client side:
RmiConnectorClient = new RmiConnectorClient();RmiConnectorAddress address = new RmiConnectorAddress(IPAddr);address.setPort(2099);client.connect(address);
The client now acts as a delegate to the remote server You can use it to create, lookup, and manipulate MBeans on that server
Again, the RMI connector is not a standard part of JMX, but an equivalent exists in any JMX implementation
IBM Labs in Haifa
Other Adapters and Connectors
Jini connector SNMP adapter
Roll your own... Customized HTML adapters (non-generic interface) TCP connectors
IBM Labs in Haifa
Resulting View of the JMX Architecture
MBean server(instrumentation layer)
Agent Layer Distributed
LayerServices (timer,
monitoring, etc.)
Adapters/
connectors
Managed Resources
Management
Console
IBM Labs in Haifa
Services Provided by the JMX Agent Layer
The agent layer is simply the environment in which MBean serve resides Created automatically when you create an MBean server Runs in its own thread
The agent layer provides several services that MBeans (or MBean clients) can use M-let service: Advanced MBean loading Relation service Monitoring services Timer services
IBM Labs in Haifa
The M-let Service
Say you have a running MBean server, and you need to load a new MBean New resource to manage
In most cases, you just use the registerMBean(...) or createMBean(...) methods
But what if the new MBean's class (or classes) is not in the server's classpath?
Trivial solution: stop the server's JVM, update the classpath, restart Sometimes, this is not an option
The other MBeans on that server could be crucial...
Advanced solution: Use the M-let MBean
IBM Labs in Haifa
The M-let Service (cont.)
The M-let service is provided by an MBean, implemented in the class javax.management.loading.MLet
This class extends java.net.URLClassLoader Created like any other MBean; for example:
mbs.createMBean("javax.management.loading.MLet", new ObjectName("Tools:name=mlet"));
MLet's MBean operations include getMBeansFromURL(url) Loads MBeans specified in a special XML-like "MLET" file, with tags
about MBean classes and the JARs in which they are stored The MLet can also be used for loading MBeans with the special
createMBean variant that accepts a class loader MBean as an extra parameter:
mbs.createMBean(className, objName, loaderObjName);
IBM Labs in Haifa
The Relation Service
A Relation MBean is an MBean that manages a relation between two or more MBeans
The "service" provided by the JMX agent layer is simply a superclass for your own relation MBeans, plus several support classes
Basically, a relation MBean is used to implement a façade pattern The relation MBean can provide operations that are delegated to
numerous other MBeans on the same server The actual MBeans to which the operations are delegated can be
changed at runtime
IBM Labs in Haifa
The Monitoring Service
A monitor in a JMX agent is an MBean which is used to monitor an attribute of some other MBean
All monitors extend javax.management.monitor.Monitor Monitor attributes:
GranularityPeriod (R/W, long) -- the interval in which the monitored attribute is examined
ObservedAttribute (R/W, String) ObservedObject (R/W, ObjectName) Active (RO, boolean)
Monitor operations: start() stop()
IBM Labs in Haifa
The Monitoring Service (cont.)
Subclasses of Monitor define when will the monitor MBean generate a notification e.g., CounterMonitor can send a notification when the observed
(integer) attribute is above/below a given value, or outside a given range, etc.
StringMonitor can send a notification when the observed (String) attribute equals/does not equal a given String value
The generated notifications are instances of MonitorNotification Includes information about the monitored object's identity, the
observed attribute, and the value that caused the notification to fire
IBM Labs in Haifa
The Timer Service
The timer service is (surprise) an MBean that generates and sends notifications at pre-determined times
Can be configured to send specific notifications Can be configured to send the notification once, repeatedly (at a given
interval), or a bound number of times
IBM Labs in Haifa
Services Provided by the MBean Server
In addition to the Agent Layer services, there are also services provided by the MBean server object
These are basically an information registry, notification services for the loading/unloading of MBeans
The services include: Notifications for MBeans about their own registration/unregistration The server delegate bean
IBM Labs in Haifa
The MBean Notification Service
Any MBean class can choose to implement the MBeanRegistration interface
The interface includes four methods, which the server invokes at the appropriate time if the interface is implemented: preRegister(server, objName) postRegister(success) preDeregister() postDeregister()
The most important is preRegister, which notifies the MBean of the name under which it was registered, and allows it to maintain a reference to its containing server So it can find other MBeans in the same server
IBM Labs in Haifa
The Server Delegate MBean
Every MBean server automatically registers one MBean that is not created by user code
This MBean is stored in a separate domain, and it is called JMImplementation:type=MBeanServerDelegate
The bean contains several read-only attributes: The implementation name, vendor, and version The specification name, vendor and version The MBean server's unique ID
IBM Labs in Haifa
Conclusion
MBeans are a nice way to make configuration parameters and resource health information available to external monitoring tools / management consoles
Most natural use: adding management capabilities to Java applications Each application can create an MBean server with one or more
MBeans exposing parameters and status info In actual use by most Java application servers
Additional use: as wrapper to other management services or manageable resources Allows for a consolidated management console
IBM Labs in Haifa
MBeans and Other J2EE Technologies
MBeans can be used with JMS As message receivers Can translate messages to log information visible from outside Lets you add a health monitor to existing JMS-based applications
without changing the application You just add another listener
MBeans can be used with EJBs MBeans can be woven into EJB-based applications, for generating
notifications to 3rd parties or for making history/health information visible externally
Differenciate application configuration from the application model
IBM Labs in Haifa
For More Information...
JMX in Action by Sullins and Whipple Good introduction to the API, and some sample usage
Includes an example for using JMX with EJBs Java Management Extensions
by J. S. Perry Great introduction to the API, little usage examples/advice
Java and JMX by Kreger, Harold and Williamson