Chapter 5. Model MBeans

Model MBeans are an extension of the Dynamic MBean. They provide a generic, configurable template for the developer to easily instrument a resource for management. The JMX agent provides a Model MBean implementation that can be configured with the management interface of the instrumented resource and additional behavioral properties for the MBean.

Model MBeans can be easily configured and created by the resource classes on-the-fly when needed. All compliant JMX agent implementations offer at least one Model MBean implementation in the form of specification mandated RequiredModelMBean class. All Model MBean metadata classes also implement a DescriptorAccess interface that adds the ability to add custom properties to each element of the metadata.

ModelMBean Interface

The ModelMBean interface (see Listing 5.1) extends the DynamicMBean interface, the PersistentMBean interface, and the ModelMBeanNotificationBroadcaster interface. The DynamicMBean interface is familiar from the previous chapter, the PersistentMBean (shown in Listing 5.2) adds methods for persisting the MBean's state, and the ModelMBeanNotificationBroadcaster interface provides the methods required by a notification broadcaster MBean.

Example 5.1. ModelMBean Interface

package javax.management.modelmbean;

public interface ModelMBean extends
    DynamicMBean, PersistentMBean, ModelMBeanNotificationBroadcaster {

    public void setModelMBeanInfo(ModelMBeanInfo inModelMBeanInfo)
        throws MBeanException,
               RuntimeOperationsException;

    public void setManagedResource(Object mr, String mr_type)
        throws MBeanException,
               RuntimeOperationsException,
               InstanceNotFoundException,
               InvalidTargetObjectTypeException;

}

The ModelMBean interface allows you to describe the management interface of the Model MBean using the metadata classes. The metadata for Model MBeans is extended from the corresponding Dynamic MBean classes by introducing descriptor classes. The descriptors are used for adding behavioral properties to each element of the metadata. These behavioral properties can include the persistence policy of an MBean, transactional behavior, attribute caching policy, security policies, and so on.

Example 5.2. PersistentMBean Interface

package javax.management;

public interface PersistentMBean {

   public void load() throws  MBeanException,
                              RuntimeOperationsException,
                              InstanceNotFoundException;

   public void store() throws MBeanException,
                              RuntimeOperationsException,
                              InstanceNotFoundException;

}

Because the Model MBean instances are provided by the agent, the support for behavioral properties depends on the agent implementation. All agents must provide the RequiredModelMBean class, but there is no guarantee what behavioral properties are supported by this implementation. In fact, it is more than likely that JMX agents working in different environments, such as J2ME and J2EE, will have differing implementations of the RequiredModelMBean class.

All Model MBean implementations are broadcaster MBeans. Model MBeans automatically send attribute change notifications on any changes to management attributes for all interested listeners.

Descriptors

The descriptor objects are used in the Model MBean metadata to add behavioral policies to the managed bean. These policies vary from persistence to caching to transactional properties, depending on the JMX Agent implementation that provides the Model MBean implementation. The JMX specification defines some standard policies that the Model MBean can implement. The Model MBean implementation can also support custom policies that are not defined in the specification.

A descriptor is a collection of key-value pairs. When defining the management interface for an MBean attribute it is possible to add, for example, a descriptor that describes which caching and persistence policies should be implemented for that attribute. The Model MBean implementation will try to adapt to match the required MBean behavior. It is also possible that the behavioral descriptors are changed at run-time, via a management application or by the managed resource itself.

All descriptor objects must implement the Descriptor interface. All descriptors are also made available to management applications by exposing getDescriptor() and setDescriptor() methods in the Model MBean's metadata classes.

Table 5.1 describes the relevant methods of the Descriptor interface.

Table 5.1. Relevant Methods of the Descriptor Interface

Method Description
getFieldNames() Returns an array of strings that contain all of the field names in the descriptor.
getFieldValues(String[] names) Returns an object array of field values. If the given array of field names is null, all the values in the descriptor are returned. If an array of field names is supplied as a parameter, the returned object array will contain only the values for the named fields in the order defined by the names argument. If a named field does not exist, a null reference is returned in its place.
getFieldValue(String name) Returns the value of a given field. If the field is not found in the descriptor, a null reference is returned.
getFields()

Returns an array of strings representing the field and value pairs in the descriptor. The format of the strings is as follows:

fieldName1=fieldValue
fieldName2=fieldValue

If the type of the field class is not String, a toString() method is called on the object to retrieve a string representation of the value.

setField(String name, Object value) Sets a field in the descriptor to a given value. If the given field already exists in the descriptor, its value is replaced with the new value; otherwise, a new field is added to the descriptor.
setFields(String[] names, Object[] values) Sets all the field name and value pairs in the descriptor.
removeField(String name) Removes the given field from the descriptor.

The metadata classes of MBean constructors, attributes, operations, and notifications implement the DescriptorAccess interface. This interface contains two methods that allow you to retrieve the descriptor objects and set them—getDescriptor() and setDescriptor(). The getDescriptor() method returns a copy of the descriptor of a management interface element. The setDescriptor() allows you to set a new descriptor for the Model MBean. Notice that the setDescriptor() replaces the existing descriptor completely.

Notification Logging Policy

The Model MBean implementation can be configured to log the notifications that are broadcast by setting a notification logging policy. The notification logging policy can be set either at the MBean level or explicitly per notification type. The notification logging is enabled by setting a log field in the MBean or notification descriptors. The details of the log field are given in the section Model MBean Metadata.

Persistence Policy

The MBean descriptor and management attribute descriptors allow the setting of persistence policies for the MBean's attributes. The MBean's attributes can be persisted periodically to a file system, database, LDAP server, or a custom high-performance cache. Persistence policy can be set at the MBean level for all its attributes or set individually per attribute.

The JMX specification defines some persistence policies that can be implemented by the JMX agent. The four predefined persistence policies are OnUpdate, OnTimer, NoMoreOftenThan and Never. On update persistence is performed every time the attribute's value changes. A timer based persistence is performed at given checkpoints. The persistence operations can also be limited to a maximum amount per time interval; for example, once every five seconds at most.

You will also see the different persistence policies discussed in the Model MBean Metadata section where the descriptor fields are discussed in detail.

Notice that the JMX agent is not required to implement persistence. If the agent is designed to run in an environment where persistence is not supported, its Model MBean implementation can ignore any requests to persist the MBean's state.

Value Caching Policy

The attribute and operation descriptors allow caching of management attribute and management operation return values. The descriptor keeps track of the last invocation times and stores the last known attribute values and operation return values. When a request to retrieve an attribute value is made, the value in the descriptor is checked for its currency and can be returned instead of accessing the managed resource directly, as shown in Figure 5.1. This will help reduce the impact of management operations on managed resources.

An attribute value can be returned from a descriptor directly.

Figure 5.1. An attribute value can be returned from a descriptor directly.

The descriptor can also contain default values for attributes and a method mapping to the operations that should be invoked to access the managed resource when the cached value is considered stale.

Export Policy

The Model MBean descriptors allow you to set an export policy on your MBeans. If the JMX agent supports lookup services, for example through JNDI, the MBeans can be located by exporting a serialized object to a lookup service. This allows an MBean a degree of location transparency because the address of the host JMX agent does not have to be known to other agents or management applications beforehand.

Model MBean Metadata

The metadata classes of Model MBeans extend from the metadata classes used with Dynamic MBeans. For each of the metadata class defined in the javax.management package, there is an equivalent in the javax.management.modelmbean package. The ModelMBean interface extends the DynamicMBean interface, so it must also implement the getMBeanInfo() method. The returned MBeanInfo instance of the Model MBean must implement the ModelMBeanInfo interface to support the extended metadata provided by the descriptor classes (see Figure 5.2).

Class diagram of the ModelMBeanInfo implementation.

Figure 5.2. Class diagram of the ModelMBeanInfo implementation.

When you invoke the getMBeanInfo() method on a Model MBean, you need to cast the returned value to ModelMBeanInfo type to access the Model MBean descriptors. This also applies to the other metadata classes that describe the attributes, operations, constructors, and notifications of the management interface. The corresponding Model MBean metadata classes are

  • ModelMBeanAttributeInfo

  • ModelMBeanOperationInfo

  • ModelMBeanConstructorInfo

  • ModelMBeanNotificationInfo

Each of these classes extend the matching metadata class in the javax.management package. In addition, they all implement the DescriptorAccess interface (shown in Listing 5.3), which allows the management applications to access the descriptors. You will take a brief look into each of the Model MBean metadata classes next.

Example 5.3. DescriptorAccess Interface

package javax.management.*;

public interface DescriptorAccess {

    public Descriptor getDescriptor();
    public void setDescriptor(Descriptor descr);

}

ModelMBeanInfo

The ModelMBeanInfo interface declares all the methods that are included in the MBeanInfo class. The getAttributes(), getConstructors(), getOperations(), and getNotifications() methods are declared to return the corresponding metadata classes MBeanAttributeInfo, MBeanConstructorInfo, MbeanOperationInfo, and MBeanNotificationInfo, respectively, to match the MBeanInfo class declaration. However, in case of the ModelMBeanInfo implementation, the actual returned object types are the corresponding Model MBean metadata classes.

In addition to the methods identical to the MBeanInfo class declaration, the ModelMBeanInfo interface declares several accessor methods for handling MBean descriptors. These are listed in the next section.

getMBeanDescriptor and setMBeanDescriptor

The getMBeanDescriptor() method returns a descriptor object that contains the behavioral policies that apply to the MBean instance. Accordingly, the setMBeanDescriptor() method sets a new policy descriptor to the MBean. Note that setting a new descriptor completely replaces the previous one in the MBean. Any merging or additions to the existing policies must be processed manually.

The policies set in the MBean descriptor can be overridden by any individual descriptor objects associated with the MBean's attributes, constructors, operations, or notifications.

The additional methods in the ModelMBeanInfo interface you should be aware of are shown in Table 5.2.

Table 5.2. Partial List of the Methods of the ModelMBeanInfo Interface

Method Description
getDescriptors(String type)

Returns the descriptors defined in the management interface matching to a given type. The type can be

mbean
attribute
constructor
operation
notification

If the type is a null reference, this method returns all the descriptors in the MBean.

setDescriptors(Descriptor[]descriptors)

Adds or replaces the descriptors in the array.

Notice that all descriptors must have at least the name and descriptorType values.

getDescriptor(String name,String type) Returns a descriptor based on a name and type.
getMBeanDescriptor() Returns the descriptor for the entire MBean. This descriptor contains the default policies for all elements of the management interface. The default values can be overridden by individual management interface elements with descriptors in their own specific metadata classes.
setMBeanDescriptor(Descriptor d) Sets a new descriptor for the MBean. Notice that this is a full replacement of the existing MBean descriptor; no merging is done.

Predefined MBean Descriptor Fields

The JMX specification declares predefined descriptor field names that can be used to configure a Model MBean instance. Note that many predefined descriptor fields are optional and, therefore, may be ignored by the Model MBean implementation. In general, different agents support different sets of descriptor fields in their RequiredModelMBean implementation. The documentation for a specific JMX implementation should list the properties that are implemented. As an example, the Sun Reference Implementation supports simple file-based persistence for the MBean, whereas the Tivoli JMX implementation, at the time of this writing, did not support persistent management attributes.

For all descriptors, the name and descriptorType fields are mandatory. In addition, the field role also must be included for the management operation and MBean constructor descriptors.

The MBean descriptor sets policies that are applied to all management attributes and operations in an MBean, such as persistence and value caching. Setting these policies will affect each individual management element, unless it is overridden by associating a specific descriptor for the single attribute or operation. This way, it is easy to set the behavioral properties to all attributes, and then only override the properties for those attributes that require different behaviors from the default.

The following list is not conclusive. The Model MBean implementations are allowed to support any number of custom descriptor fields. The following list contains all the fields described in the JMX specification.

  • nameThe case sensitive name of the MBean. This is a required field for all Model MBeans descriptors.

  • descriptorTypeFor descriptors associated with the MBean, this field's value must contain the string “MBean”. This is a required field for all Model MBeans descriptors.

  • displayNameThe displayName field can be used to indicate to the management applications to use a string representation other than the MBean's object name in the user interface. This field can be used for localized representation of the MBean name, for example.

  • persistPolicyBy defining a persistence policy, the management attributes can be persisted by the Model MBean implementation. Defining a persistence policy at the MBean level will affect all the attributes in the MBean. The MBean persistence policy can be overwritten by individual attributes by setting their own policy at the attribute level.

    The JMX specification defines four different kinds of persistence policies. Specific Model MBean implementations can provide policies other than mentioned here.

    The standardized values for the persistPolicy field are as follows:

    • Never

    • OnUpdate

    • OnTimer

    • NoMoreOftenThan

    The Never policy implies that the attribute values are transient and its state is never persisted. The OnUpdate policy indicates that the Model MBean implementation should persist the state whenever it is updated. The OnTimer policy means that the state of management attributes is persisted based on a time interval. The time interval is set by adding a persistPeriod field to the descriptor. Finally, the NoMoreOftenThan policy tells the Model MBean implementation to persist the state of the management attributes every time they are updated, unless they were already persisted once within a given time limit.

    The persistPeriod field is used to set the time interval. The NoMoreOftenThan policy allows you to control the persistence frequency for attributes that may potentially change very often within a short period of time. In such cases, the performance penalty of persisting the attributes on every update can be avoided with the use of NoMoreOftenThan policy.

    The persistPolicy field is optional and may not be supported by the JMX implementation.

  • persistPeriodThis field is only valid if the persistPolicy field contains the OnTimer or NoMoreOftenThan policies. If the OnTimer value has been set, this field's value indicates the time interval that is used to persist the state of the management attributes. If the NoMoreOftenThan value has been set, this field's value indicates the minimum time interval between two persistence operations.

    The persistPeriod field along with persistPolicy is an optional field for the JMX implementation and, therefore, may not be supported by all agents.

  • persistLocationThe persistLocation field can be used to configure the persistence store for the MBean. This field can contain a directory path where the MBean's state should be persisted; it can contain DataSource reference, table names, and so on. It depends on the JMX implementation which types of persistence locations are supported.

  • persistNameThe persistName field can be used in conjunction with the persistLocation field. The persistName field can contain a filename, in case a file based persistence is being used, a column names in the database table that should be used to store the MBean's state, and so on. Again, it depends on the JMX implementation how the value of this descriptor field is interpreted.

  • logThe log field contains a Boolean value. If the value is set to true, all notifications sent by the Model MBean will be logged. This can be used, for example, to log all AttributeChangeNotification objects in the agent to provide a simple audit track for attribute updates.

  • logFileThe logFile field contains the full file path and filename to the log file the JMX agent uses to write the notification logs. This field must be declared when the log field equals true or no logging will be performed.

  • currencyTimeLimitThe currencyTimeLimit field sets the caching policy for the MBean's attributes. The field value defines, in seconds, how long the attribute value remains current after the last time it was retrieved from the managed resource. If the attribute value stored in the attribute's descriptor is determined to still be current, the managed resource is not invoked to retrieve the value.

    The currencyTimeLimit value can be overridden by individual attributes by declaring the field in their corresponding descriptors. The attribute descriptors also allow you to control the operations that are used to retrieve and update the attribute values in managed resource via getMethod and setMethod descriptor fields. The section “Attribute Caching” gives a more detailed description of the use of these fields.

    The value 0 in the currencyTimeLimit field means that the attribute retrieval is never cached and an up-to-date value is always returned. Value -1 indicates the attribute value should always be considered valid, and consecutive calls to read the attribute value will always be returned from the cache.

    The currencyTimeLimit field is an optional field for Model MBeans. Attribute value caching may not be implemented by the JMX agent.

  • exportThe value of the export field can be a serialized object that is used to export a handle to the MBean. The handle should contain the information necessary for the management applications or other JMX agents to be able to locate and connect to the JMX agent. The indirection provided by the agent or MBean handle allows for location transparency of the agents and MBeans.

  • visibilityThe visibility field allows you to set the level of granularity for the managed beans. This field can act as an indicator to the management applications on how the MBeans should be displayed or grouped in the user interface, or how their importance relates to other MBeans in the same management domain or agent.

    The value of this field is an integer ranging from 1 to 4. A visibility value of 1 indicates the most significant, or large granularity, MBeans, whereas a visibility value of 4 indicates the least significant, or small granularity, MBeans.

    The visibility field is optional and, therefore, may be ignored by the JMX agent.

  • presentationStringThe presentationString field can be used to associate additional presentation data to the MBean. The content of the presentationString is an XML encoded string that can store information such as how to present and build the user interface for the MBean.

    There are no standard DTDs or XML schemas defined for presenting the user interface of an MBean. It is up to the specific protocol adapter and management tool implementations to decide how to interpret the presentation information.

ModelMBeanAttributeInfo

The ModelMBeanAttributeInfo class describes the management attribute of a Model MBean. It extends the MBeanAttributeInfo class and adds the descriptor support by implementing the DescriptorAccess interface (see Figure 5.3).

Class structure of the ModelMBeanAttributeInfo.

Figure 5.3. Class structure of the ModelMBeanAttributeInfo.

When associating a descriptor to the Model MBean attribute, the descriptor object must have its descriptorType field set to string value "attribute". The descriptor's name, defined by the name field, must match the name of the attribute defined in the MBeanFeatureInfo class, which is the ancestor class to ModelMBeanAttributeInfo. Note that the descriptor name and the management attribute names are case sensitive.

Predefined Management Attribute Descriptor Fields

The JMX specification defines descriptor field names for the management attributes that may be supported by the agent's Model MBean implementation. The specification allows customized field names as well, so, depending on the JMX agent implementation, other field names may also be supported. The following field names are standardized by the specification.

  • nameThe name field must contain the name of the attribute with which the descriptor is associated. The name value is case sensitive. The name of the attribute can be retrieved by calling the getName() method of the ModelMBeanAttributeInfo class.

    This field is required for all valid attribute descriptor objects.

  • descriptorTypeFor descriptors associated with management attributes, this field's value must contain the string value "attribute".

    This field is required for all valid attribute descriptor objects.

  • valueThe value field in the descriptor represents the attribute's current value. If attribute caching is enabled, the value object of this field is returned. If the cached attribute value has gone stale, the managed resource is accessed to retrieve an up-to-date value. The retrieved value is stored into the value field in the descriptor. The value caching and descriptor field interactions are covered later in the “Attribute Caching” section.

  • defaultThe attribute descriptor allows you to set a default value for the management attribute. The value of the default field is returned if the value field has not been set and the attribute has not been associated with an operation that would retrieve the value from the managed resource.

  • displayNameThe displayName field can be used to indicate to the management applications to use a string representation other than the attribute's programmatic name in the user interface. This field can be used for localized representation of the attribute name, for example.

  • getMethodThe getMethod field is used to associate a read operation to the attribute's value. When the agent retrieves the attribute value, and the value is not cached or the cached value has gone stale, the managed resource is accessed to retrieve an up-to-date value. The method used for retrieving the value can be mapped to a management operation declared by the getMethod field of the attribute's descriptor. The value of this field must contain the name field of the management operation used for value retrieval. When a value is retrieved, it is stored in this descriptor's value field.

  • setMethodThe setMethod field associates the corresponding write operation for the attribute's value. As with getMethod, this field's value must contain the name of the management operation that is used to write an attribute's value to the managed resource. When a new attribute value is being written, it is also stored to the descriptors value field.

  • protocolMapThe value of this field must be another Descriptor object that contains a name-value map useful for protocol adaptors. This field allows the management attribute to be associated with a protocol specific identifier or schema.

  • persistPolicyThe Model MBean persistence can be defined at the attribute level. Any persistence policy set in the descriptor of a ModelMBeanAttributeInfo object will automatically override the persistence policies set at the Model MBean level. The JMX specification defines four different kinds of persistence policies. Specific Model MBean implementations may provide policies other than those mentioned here.

    The standardized values for the persistPolicy field are as follows:

    • Never

    • OnUpdate

    • OnTimer

    • NoMoreOftenThan

    The Never policy implies that the attribute's value is transient and its state is never persisted. The OnUpdate policy indicates that the Model MBean implementation should persist the state whenever it is updated. The OnTimer policy means that the attribute's state is persisted based on a time interval. The time interval is set by adding a persistPeriod field to the descriptor. Finally, the NoMoreOftenThan policy tells the Model MBean implementation to persist the attribute's state every time it is updated, unless the last update was persisted within a given time limit. The time limit is set by adding a persistPeriod field to the descriptor. The NoMoreOftenThan policy allows you to control the persistence frequency for attributes that may potentially change very often within a short time frame. In such cases, the performance penalty of the attribute's persistence can become an issue and can be avoided with the use of this policy.

  • persistPeriodThis field is only valid if the persistPolicy field contains the OnTimer or NoMoreOftenThan policies. If the OnTimer policy has been set, this field's value indicates the time interval that is used to persist the attribute's state. If the NoMoreOftenThan policy has been set, this field's value indicates the minimum time interval between two persistence operations.

  • currencyTimeLimitThe currencyTimeLimit field indicates to the Model MBean implementation how long the attribute's value can be cached before it should be considered stale. The value of this field defines the number of seconds the value field is considered valid. If the time limit set in this field has passed since the last update of the value field, the value is considered stale and is retrieved from the managed resource on the next request.

    If the value of the currencyTimeLimit field is set to 0, the retrieval of the attribute's value is directed to the managed resource on every request. A value of -1 indicates to the Model MBean that the attribute's value is never stale.

  • lastUpdatedTimeStampThe lastUpdatedTimeStamp field is set every time the value field is updated. This is used in accordance with the currencyTimeLimit field to determine whether the value field is valid or stale.

  • iterableThe iterable field can contain a Boolean value that indicates if the contents of the value field is an enumerable object.

  • visibilityThe visibility field allows you to set the level of granularity for your management attributes. This field can act as an indicator to the management applications on how the attributes should be displayed or grouped in the user interface, or how their importance relates to other attributes in the MBean.

    The value of this field is an integer ranging from 1 to 4. A visibility value of 1 indicates the most significant management attributes, whereas a visibility value of 4 indicates the least significant management attribute.

  • presentationStringThe presentationString field can be used to associate additional presentation data to this attribute. The content of the presentationString is an XML encoded string that can store information such as how to present and access the management attribute and how to render the user interface.

ModelMBeanOperationInfo

The ModelMBeanOperationInfo class describes the management operations of a Model MBean. As with other Model MBean metadata classes, it too extends from its corresponding MBeanOperationInfo class. In addition, the ModelMBeanOperationInfo class implements the DescriptorAccess interface to add the support of descriptors to associate behavioral properties to management operations (see Figure 5.4).

Class diagram of the ModelMBeanOperationInfo.

Figure 5.4. Class diagram of the ModelMBeanOperationInfo.

The descriptors associated with Model MBean operations must contain a descriptorType field with the string "operation" as its value. In addition, the role field in the Model MBean operation descriptor must contain one of the following three strings:

  • "operation"

  • "getter"

  • "setter"

The role field is used to indicate the operations role, whether it is a management operation or used to access the MBean attributes.

The third required descriptor field is the name field, which must contain the name of the management operation with which the descriptor is associated. The management operation's name is defined in the MBeanFeatureInfo class and is accessible through the getName() method.

Predefined Management Operation Descriptor Fields

The predefined descriptor field names for Model MBean operations are listed next. Again, the specification defines these names in an effort to increase the portability of the managed resources from one JMX implementation to another, but the required Model MBean implementation offered by the JMX agent is allowed to support other descriptor fields as well.

  • nameThe name field must contain the name of the operation the descriptor is associated with. Also, note that the value is case sensitive. You can find the name of a management operation by calling the getName() method of the ModelMBeanOperationInfo class. This field is mandatory on all descriptors.

  • descriptorTypeThe descriptorType field must always contain the string "operation" for descriptors associated with Model MBean operation metadata. This field is mandatory on all descriptors.

  • displayNameThe displayName field can be used to indicate to the management applications to use a string representation other than the operation's programmatic name in the user interface. This field can be used for localized representation of the operation name, for example.

  • lastReturnedValueAs with the attribute values, the operation return values can also be cached in the Model MBean operation descriptor. The lastReturnedValue field contains the return value of the last invocation of the Model MBean's management operation. The period of time the cached return value remains valid depends on the currencyTimeLimit field value in the same descriptor.

  • currencyTimeLimitThe currencyTimeLimit is the time period in seconds that the cached return value of the management operation is valid. If the return value caching is enabled and the time limit has not been exceeded, the management operation is not invoked on the managed resource. The validity of the cached return value is checked against the time stamp stored in the lastReturnedTimeStamp field.

    If the value of the currencyTimeLimit field is 0, the management operation is always invoked on the managed resource and the return value is not cached. If the currencyTimeLimit field has a -1 value, the return value stored in lastReturnedValue is always returned.

  • lastReturnedTimeStampThe lastReturnedTimeStamp field is updated every time the management operation is invoked on the managed resource. This field is used with currencyTimeLimit and lastReturnedValue fields to determine whether the cached return value has gone stale.

  • visibilityThe visibility field allows you to set the level of granularity for your management operations. The management applications can use this field as an indicator on how to display the operations in their user interface, how to group the operations, which operations are accessed more often than others, and so on.

    The value of this field is an integer ranging from 1 to 4. A visibility value of 1 indicates the most significant management operations, whereas the visibility value of 4 indicates the least significant management operation.

  • presentationStringThe presentationString field can be used to associate additional presentation data to this attribute. The content of the presentationString is an XML encoded string that can store information on how to present and access the management operation, its attributes, and return type. The management application can use the information stored in the XML to decide how to render the user interface.

ModelMBeanNotificationInfo

The ModelMBeanNotificationInfo describes the notifications emitted by a Model MBean. As with the previously discussed metadata classes, the ModelMBeanNotificationInfo class also extends its corresponding MBeanNotificationInfo class (see Figure 5.5).

Class diagram of the ModelMBeanNotificationInfo.

Figure 5.5. Class diagram of the ModelMBeanNotificationInfo.

The mandatory name field in the notification descriptor must contain the name of the notification class available via the superclass getName() method. The descriptorType field must contain the string value "notification".

The predefined descriptor field names for Model MBean notifications are as follows:

  • nameThe name field must contain the name of the notification class. This field is mandatory on all descriptors.

  • descriptorTypeThe descriptorType field must always contain the string "notification" for descriptors associated with Model MBean notification metadata. This field is mandatory on all descriptors.

  • severityThe severity field can be used to describe the different levels of severity assigned to the notification. The specification defines seven levels of severity:

    0—Unknown, Indeterminate

    1—Non recoverable

    2—Critical, Failure

    3—Major, Severe

    4—Minor, Marginal, or Error

    5—Warning

    6—Normal, Cleared, or Informative

    The value of the severity field is an integer in the range of 0 to 6.

  • messageIdThe messageId field allows additional identifier to be added to the notification.

  • logThis is a Boolean value that can be used to indicate whether the notification should be logged. The log field set in a notification descriptor can override the log setting in the MBean descriptor.

  • logFilelogFile is the filename where log entries should be recorded. This descriptor field overrides the MBean-wide log setting.

  • presentationStringThe presentationString field can be used to associate additional presentation data to the notification. The content of the presentationString is an XML encoded string that can store information on how to present and access the management operation, its attributes, and return type. The management application can use the information stored in the XML to decide how to render the user interface.

ModelMBeanConstructorInfo

The ModelMBeanConstructorInfo class describes the constructor of an MBean. It extends the MBeanConstructorInfo class and adds the descriptor support by implementing the DescriptorAccess interface (see Figure 5.6).

Class diagram of the ModelMBeanConstructorInfo.

Figure 5.6. Class diagram of the ModelMBeanConstructorInfo.

When associating a descriptor to the constructor metadata, the descriptor object must have its descriptorType field set to string value "operation". The role field must contain the string value "constructor".

In addition to the name, descriptorType, and role fields, the constructor descriptor can contain the displayName, class, visibility, and presentationString fields. The class field must contain the fully-qualified name of the class where the constructor is defined. The name field must contain the name returned by the MBeanConstructorInfo.getName() method. The semantics of the displayName, visibility, and presentationString fields are equal to those defined for Model MBean operation descriptors.

Attribute Caching

The metadata for Model MBean attributes allows you to set a caching policy for attributes and operation return values. One of the properties defined in the descriptor of a management attribute is the management operation that can be invoked to either retrieve the attribute's value or set the attribute value in the resource. This is achieved by declaring the getMethod and setMethod fields in the attribute's descriptor.

It is also possible to not set any methods as a management attribute's accessors. In practice, this means that all of the attribute's state is kept in the Model MBean instance. Both the set and get operations access only the attribute's descriptor and never directly invoke any methods on the managed resource. The value of the attribute is stored in the descriptor and can be persisted if the Model MBean implementation supports attribute persistence. The sequence of calls is shown in Figure 5.7.

Management attribute with no setMethod field will store its state in the attribute descriptor.

Figure 5.7. Management attribute with no setMethod field will store its state in the attribute descriptor.

This attribute behavior allows the management of resources that have no knowledge of the management attributes. It is possible to extend existing resources with new management attributes. It also allows managed resources that are unable to maintain their own state, transient resources, to delegate the state management to their Model MBean. The state will be held in the descriptors and managed by the agent.

For managed resources that do maintain their own state, the getMethod and setMethod fields in the attribute descriptors can be used to map the attribute invocations to operations that access the managed resource.

The following attribute descriptor fields act a part in the attribute value caching in Model MBeans.

  • value

  • default

  • getMethod

  • setMethod

  • currencyTimeLimit

  • lastUpdatedTimeStamp

The value field is used by the agent to store the current value of an attribute. This field is updated whenever a new attribute value is written. If the setMethod field in the attribute descriptor has been set, the corresponding method in the managed resource is called. If no setMethod value has been defined, the attribute state is stored in the descriptor and the value field is updated directly. After the value field has been updated, the lastUpdatedTimeStamp field in the descriptor is reset with the current time. The sequence of descriptor field updates with setMethod is shown in Figure 5.8.

Management attribute with setMethod mapping.

Figure 5.8. Management attribute with setMethod mapping.

The getAttribute() operation in a Model MBean works in a similar fashion as setAttribute(). If the caching of management attributes is enabled, the descriptor for the attribute is accessed with each getAttribute() call to check the validity of cached values.

If the value field for an attribute is not declared in its descriptor, the existence of getMethod field is checked. If the getMethod declaration is found in the descriptor, the management operation declared in the getMethod field will be invoked. The return value of the operation invocation will be taken as the attribute's value. If getMethod field was not declared in the descriptor, and value field was not available, the descriptor is checked for default field. If the default field is found, its value is returned as the attribute's value.

When the attribute's value is retrieved via the operation declared in the getMethod field, the return value is stored in the value field. If value caching has been enabled by setting a non-zero value to the currencyTimeLimit field in the descriptor, the validity of the attribute value is checked each time getAttribute() is called and before the getMethod operation of the managed resource is invoked. The sequence of calls to retrieve a management attribute that has a cache lifetime of five seconds is shown in Figure 5.9.

Retrieval of management attribute where descriptor cache has gone stale after five seconds.

Figure 5.9. Retrieval of management attribute where descriptor cache has gone stale after five seconds.

The value cache validity is checked by comparing the values of lastUpdatedTimeStamp field and currencyTimeLimit field. If currencyTimeLimit field is set to -1, the contents of the value field are always valid. If the currencyTimeLimit is set to 0, the value caching is disabled. Any positive integer stored as a value of the currencyTimeLimit descriptor field is interpreted as the number of seconds the attribute value stored in the value field should be considered valid. If the cached value is valid, the getMethod operation of the managed resource will not be invoked.

Model MBean Example

The next example will use a Model MBean to add management features to an existing class. The example shows how an existing class, Printer, can be managed using the generic management template provided by the Model MBean.

The Printer class itself is not aware of its manageability. It could implement methods that control the printer through a parallel or USB port for general printing functions, but it doesn't really contain the kind of management information that is required for a specific management task.

The Printer class in Listing 5.4 has only one method for demonstrating purposes called isActive(). It always returns a Boolean value true and prints a message to the console indicating it has been called. It will serve as a mock-up of an object that represents a printer. The more interesting part of this example is that you can add management domain-specific attributes to the Model MBean without affecting the original class. For this example, you will add a management attribute RoomName to show the name or number of the office the printer is located in and the attribute Active, which indicates if the printer is currently online waiting for printing tasks to be queued.

Adding a room name to the Printer class might be too specific and not really relevant to a class that implements basic printer functionality itself. You could subclass the printer and create a MyOfficePrinter class and have it implement a corresponding Standard MBean interface. However, you do not have to declare and implement new classes or interfaces at all with a Model MBean. You can configure the Model MBean with the relevant management information and keep the Printer class untouched. You will separate the management implementation from the resource class and only provide a reference of the printer resource to the Model MBean.

Listing 5.5 shows a Model MBean creation and configuration for the Printer resource. The Model MBean will be configured with a management attribute RoomName that is stored by the agent in the attribute's descriptor. The Active attribute has to access the Printer resource to retrieve the status of the printer. You will map the getter method of the Active attribute to an isActive() management operation. You will cache the state of the Active attribute to remain in the descriptor cache for 10 seconds, so that each query for the printer's state does not have to access the printer itself.

Example 5.4. Printer.java

package book.jmx.examples;

public class Printer {

  public boolean isActive() {
    System.out.println("isActive() called");
    return true;
  }

}

Example 5.5. ModelExample.java

package book.jmx.examples;

import javax.management.*;
import javax.management.modelmbean.*;

public class ModelExample {

  final static boolean READABLE = true;
  final static boolean WRITABLE = true;
  final static boolean BOOLEAN  = true;

  public static void main(String[] args) {

    MBeanServer server =
        MBeanServerFactory.createMBeanServer();


    // build 'RoomName' read-write attribute
    Descriptor descr1 = new DescriptorSupport();
    descr1.setField("name", "Room");
    descr1.setField("descriptorType", "attribute");
    descr1.setField("displayName", "Room Number");
    descr1.setField("default", "D325");

    ModelMBeanAttributeInfo roomNameInfo =
        new ModelMBeanAttributeInfo(
          "Room",                        // attribute name
          String.class.getName(),        // attribute type
          "Room name or number.",        // description
          READABLE, WRITABLE, !BOOLEAN,  // read write
          descr1                         // descriptor
        );


    // build 'Active' read-only attribute
    Descriptor descr2 = new DescriptorSupport();
    descr2.setField("name", "Active");
    descr2.setField("descriptorType", "attribute");
    descr2.setField("getMethod", "isActive");
    descr2.setField("currencyTimeLimit", "10");

    ModelMBeanAttributeInfo activeInfo =
        new ModelMBeanAttributeInfo(
          "Active",
          boolean.class.getName(),
          "Printer state.",
          READABLE, !WRITABLE, !BOOLEAN,
          descr2
        );

    // build 'isActive' getter operation
    Descriptor descr3 = new DescriptorSupport();
    descr3.setField("name", "isActive");
    descr3.setField("descriptorType", "operation");
    descr3.setField("role", "getter");

    ModelMBeanOperationInfo isActiveInfo =
        new ModelMBeanOperationInfo(
          "isActive",                   // name & description
          "Checks if the printer is currently active.",
          null,                         // signature
          boolean.class.getName(),      // return type
          MBeanOperationInfo.INFO,      // impact
          descr3                        // descriptor
        );

     // MBean descriptor
     Descriptor descr4 = new DescriptorSupport();
     descr4.setField("name", "Printer");
     descr4.setField("descriptorType", "mbean");

     // create ModelMBeanInfo
     ModelMBeanInfo info = new ModelMBeanInfoSupport(
       RequiredModelMBean.class.getName(),  // class name
       "Printer",                           // description
       new ModelMBeanAttributeInfo[] {      // attributes
           roomNameInfo,
           activeInfo
       } ,
       null,                                // constructors
       new ModelMBeanOperationInfo[] {      // operations
           isActiveInfo
       } ,
       null,                                // notifications
       descr4                               // descriptor
     );

    try {
      // create and configure model mbean
      RequiredModelMBean model = new RequiredModelMBean();
      model.setManagedResource(new Printer(), "ObjectReference");
      model.setModelMBeanInfo(info);
      server.registerMBean(model, new ObjectName("example:name=model"));

      // create the adaptor
      com.tivoli.jmx.http_pa.Listener adaptor =
          new com.tivoli.jmx.http_pa.Listener();

      server.registerMBean(adaptor,
          new ObjectName("adaptor:protocol=HTTP"));

      adaptor.startListener();
    }
    catch (Exception e) {
      e.printStackTrace();
    }

  }

}

To compile and run the example, execute the following commands (using the Tivoli JMX implementation):

C: Examples> javac -d . -classpath tmx4j base lib jmxx.jar; tmx4j base lib jmxc
ModelExample.java.jar;tmx4j base lib log.jar;tmx4j ext lib jmxext.jar Printer.java ModelExample.java
C: Examples> java -classpath .;tmx4j base lib jmxx.jar; tmx4j base lib jmxc
ModelExample.java.jar;tmx4j base lib log.jar; tmx4j ext lib jmxext.jar book.jmx.examples.ModelExample

If you now browse the management view created by the HTTP adaptor (http://localhost:6969) and query for the example:name=model MBean, you should see a Web page, as shown in Figure 5.10.

Management view of the Printer resource.

Figure 5.10. Management view of the Printer resource.

Notice that you now have a management attribute RoomName, even though the Printer resource itself is not aware of it. You also expose the Active attribute that you cache at the JMX agent, more specifically in the descriptor of the Model MBean. When you select and reload the management view of the MBean and the Active attribute, you will notice that approximately every 10 seconds, the Printer resource is actually accessed to retrieve an up-to-date value of the Active attribute. You will know when the resource is accessed when you see the following message printed on the console

The HTTP Adaptor started on port number 6969
isActive() called
isActive() called
isActive() called

Invoking the isActive() management operation explicitly will always access the Printer resource and return the current status.

Summary

Model MBeans provide a generic template for creating the management implementation for resources. You can easily separate the management implementation from the resource implementation, which often leads to a cleaner design of two separate problem domains.

Model MBeans allow you to extend the metadata to include behavioral properties in all the elements of the management interface—attributes, operations, constructors, and notifications. The behavioral properties can include caching properties, security properties, transactional properties, persistence properties, presentation properties, and so on. The JMX specification defines some common field names that can be used to provide some degree of interoperability between JMX agent implementations.

All JMX agents must provide at least one implementation of the Model MBean in the javax.management.modelmbean.RequiredModelMBean class. The functionality of the RequiredModelMBean may vary depending on the run-time environment the agent has been designed for. Some of the implementation details of Model MBeans will be discussed in Chapter 8, “Extended Services.”

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.136.233.153