Instrumented Spring Reference Guide

Jennifer Hickey

Beverley Talbott

Spring Instrumentation

Copies of this document may be made for your own use and for distribution to others, provided that you do not charge any fee for such copies and further provided that each copy contains this Copyright Notice, whether distributed in print or electronically.


Table of Contents

1. Copyright Notice
2. Introduction to Instrumented Spring Products
2.1. About This Guide
2.2. Audience
2.3. Requirements
2.4. JAR Components
2.5. How Spring Instrumentation Works
3. Managed Beans
3.1. Spring Framework Metrics
3.2. Spring Security Metrics
3.3. Spring Web Flow Metrics
3.4. Spring Web Services Metrics
4. Instrumenting Applications
4.1. Adding Instrumented JARs to Applications
4.2. Configuring Applications for Auto-Discovery
4.3. Configuring Applications for Remote JMX Access
4.4. Configuring Applications for Monitoring (Optional)
4.5. Enabling Discovery and Monitoring of Flow Executions (Optional)
4.6. Verifying Auto-Discovery of Deployed Applications
5. Managing Custom Components
5.1. Exporting Components to JMX
6. Integrating Instrumented Applications with Monitoring Systems

1. Copyright Notice

Copyright © 2010 VMware Inc. All rights reserved.

VMware Web Site Legal Notice

2. Introduction to Instrumented Spring Products

Instrumented Spring products are compile-time woven versions of the core Spring Framework, Web Services, Web Flow, and Security JARs, instrumented for management and monitoring. The instrumentation autodiscovers applications as managed resources and automatically exports application beans to JMX for management. It exposes comprehensive performance and utilization metrics out-of-the-box and gives you runtime control of resources. Performance data exposed by Spring instrumentation can be consumed by Hyperic HQ 4.2 and later, as well as other monitoring systems, to provide robust, production-ready management and monitoring solutions. The four Instrumented Spring products are separate downloads that are available as part of a tc Server Spring Edition 2.0 subscription or evaluation, which includes integration with Hyperic HQ 4.2 and later. Instrumented Spring products are also available to Spring Enterprise subscribers.

2.1. About This Guide

This guide documents the data collected and exposed by Spring instrumentation, describes how instrumentation works, and explains how to set up your application to use Spring instrumentation.

2.2. Audience

This document is for application developers who want to monitor performance and utilization and who want runtime control of their applications in all phases of the application lifecycle. The Managed Beans section is also for administrators and operators, as the exposed data can be used by management systems to provide more granular monitoring of applications in production.

2.3. Requirements

Instrumented Spring Framework, Web Services, Web Flow, and Security require Java 5.0 or later and the third-party JAR files included in the distribution lib directory for each product. Instrumented Web Services, Web Flow, and Security require Instrumented Spring Framework. However, you can use Instrumented Spring Framework with or without the other instrumented products. You can also use Instrumented Spring Framework with open source versions of Web Services, Web Flow, and Security. You cannot use both an Instrumented Spring product and its open source equivalent.

See Instrumented JAR Files for requirements to replace open source Spring JARs with their Instrumented Spring equivalents.

2.4. JAR Components

Instrumented Spring Framework, Web Flow, Web Services, and Security each contain instrumented JARs, instrumentation JARs, and the third-party JAR files included in their respective lib directories. In addition, Spring Framework contains Management API JARs. The following sections describe these components.

Instrumented JAR Files

The org.springframework.<module>.instrumented JARs are compile-time woven versions of their open-source counterparts. For example, the org.springframework.beans.instrumented JAR file is a drop-in replacement for the org.springframework.beans JAR distributed with open source Spring Framework.

[Note]Note

If you will be replacing open source JARs with instrumented JARs, your replacements must be of the same version as the corresponding open source JARs, that is, the first and second digits must be identical. For example, you can replace open source Spring Web Flow 2.0.0 with Instrumented Spring Web Flow 2.0.8. However, you cannot replace open source Spring Framework 2.5.x with Instrumented Spring Framework 3.0.0. You must first upgrade to Spring Framework 3.0.x. To do so, refer to the Spring Framework Upgrade Guide and the 3.0 Spring Framework Reference.

[Note]Note

The latest Instrumented Spring Security is version 2.0.6. If you need Spring Security 3.0.x functionality, use the open source Spring Security 3.0.x JARs instead of instrumented Spring Security. Spring Security 3.0.x requires Spring Framework 3.0.x.

The instrumented JARs have compile-time dependencies on the instrumentation JARs described in the next section. Spring Framework instrumented JARs may also have compile-time dependencies on Management API JARs described in Management API JARs.

Instrumentation JAR Files

The instrumentation JARs contain the AspectJ aspects used to weave the aforementioned instrumented JARs at compile time. Thus, an instrumented JAR will likely have a compile-time dependency on 0 to n of its corresponding instrumentation jars. Instrumentation JARs have the format com.springsource.management.instrumentation.<instrumentedproduct>.<module>-<version>.jar.

Spring Web Flow, Web Services, and Security instrumentation JARs have a dependency on Instrumented Spring Framework.

Management API JAR Files

All com.springsource.management.agent.<module> and com.springsource.management.adapter.<module> JARs distributed with instrumented Spring Framework contain the API used to auto-discover Spring beans, export them to JMX, and obtain and store monitoring data. Thus, a Spring Framework instrumentation JAR will likely have a compile-time dependency on 0 to n of these management API jars.

2.5. How Spring Instrumentation Works

Instrumented Spring Framework exposes performance and resource utilization metrics for the Spring container and gives you runtime control of the container. It provides comprehensive statistics for JDBC operations and transaction management, Hibernate and JPA metrics, Spring JEE integration components, and MVC performance. Instrumented Spring Framework works with the other instrumented components to discover and expose additional metrics specific to Web Services, Web Flow, and Security.

This section describes high-level functions of Instrumented Spring Framework. For more detail, see Managed Beans.

Auto-Discovery

Instrumented Spring Framework automatically discovers applications by advising the refresh method of the AbstractApplicationContext class. Any bean that is created through an AbstractApplicationContext will be discovered as a managed resource if the instrumented components know how to manage and monitor it. See Managed Beans for a list of recognized components. Some components created outside of ApplicationContexts (such as the DispatcherServlet) will also be auto-discovered. When an AbstractApplicationContext is closed, its associated managed resources are undeployed.

Export to JMX

After managed resources are auto-discovered, the Spring Framework instrumentation automatically creates JMX ModelMBeans representing each application resource it discovers, and registers these ModelMBeans in an auto-detected MBeanServer. These MBeans contain predetermined attributes that represent metrics or properties of the resource being managed and operations that provide runtime control of the resource being managed.

All MBeans are registered under the domain spring.application. They are segmented by application (using an "application" key property) and contain "type" and "name" key properties. The "type" key property value typically refers to the component class (for example, "DispatcherServlet") and the "name" key property value is usually set to the bean name.

JConsole View of MBeans Automatically Exported by Instrumented Pet Clinic Application

Monitoring

Instrumented Spring Framework monitors most of its managed resources by using a combination of compile-time woven aspects and hooks into existing Spring Framework code. It also uses Spring AOP proxies to monitor the method executions of stereotyped components in your application (marked with @Controller, @Transactional, @Service, @Repository or @Component). This means that Instrumented Spring Framework attempts to create a Java dynamic proxy around your stereotyped component, if your sterotyped component implements an interface. If your stereotyped component does not implement an interface, Instrumented Spring Framework attempts to create a CGLIB proxy around your component. See Spring Framework Reference for more details about Spring AOP proxies. If the component cannot be proxied, it is still exported as an MBean; however, its metrics are never updated.

3. Managed Beans

Instrumented Spring Framework works with the other instrumented Spring products to auto-discover Spring beans as managed resources, export them to JMX, and to obtain and store monitoring data. This chapter describes the data exposed by Spring beans with Instrumented Spring Framework, Web Services, Web Flow, and Security.

3.1. Spring Framework Metrics

The following sections describe data and control operations available to you out-of-the-box with Instrumented Spring Framework.

Spring Core

Instrumented Spring Framework provides visibility into the performance and resource utilization of the Spring container. For example, each ApplicationContext exposes execution time metrics for common operations such as refresh and getBean and provides the names of its bean definitions. Each BeanFactory provides the number of prototype and singleton beans created and the average execution time of the bean creations. Instrumented Spring Framework also provides runtime control of the Spring container. For example, ApplicationContexts allow runtime invocation of their refresh and close methods.

Components marked as @Component (stereotype indicating a generic Spring-managed component) or @Service (stereotype indicating a business service) are automatically exposed to the management model as well. As such, execution time of all the components' public methods will be monitored. This monitoring enables analysis of performance on a per use case basis.

Table 3.1. Spring Core

Spring Framework ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Abstract Application Context

Application Context

GetBean-AverageExecutionTime(ms)
GetBean-Executions
GetBean-FailedExecutions
GetBeanNamesForType-AverageExecutionTime(ms)
GetBeanNamesForType-Executions
GetBeanNamesForType-FailedExecutions
GetBeansOfType-AverageExecutionTime(ms)
GetBeansOfType-Executions
GetBeansOfType-FailedExecutions
Refresh-AverageExecutionTime(ms)

Active

Close
Refresh

Configurable Listable Bean Factory

Bean Factory

AverageElapsedTimePerPrototypeBeanCreation(ms)
AverageElapsedTimePerSingletonBeanCreation(ms)
PrototypeBeansCreated
SingletonBeansCreated
  

@Component

Component, subtype= Method

AverageElapsedExecutionTime(ms)
ExecutionsPerSecond
InvocationCount
MaximumExecutionTime(ms)
MinimumExecutionTime(ms)
ThrownExceptionCount
  

@Service

Service, subtype= Method

AverageElapsedExecutionTime(ms)
ExecutionsPerSecond
InvocationCount
MaximumExecutionTime(ms)
MinimumExecutionTime(ms)
ThrownExceptionCount
  


Spring DAO

Instrumented Spring Framework provides summary visibility into JDBC operations and transaction management. Spring DAO components expose metrics such as transaction commit and rollback rates, transaction throughput, and JDBC query execution throughput. Additionally, components marked as @Repository or @Transactional are exposed to the management model as services. As such, execution time of all the components' public methods will be monitored.

Table 3.2. Spring DAO

Spring Framework ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Jdbc Template

Jdbc Template

AverageExecutionTime(ms)
ExecutionsPerSecond
FailedExecutions
  

Abstract Platform Transaction Manager

Platform Transaction Manager

CommitsPerSecond
FailedCommits
FailedResumes
FailedRollbacks
FailedSuspends
ResumesPerSecond
RollbacksPerSecond
SuspendsPerSecond
  

Transaction Template

Transaction Template

AverageExecutionTime(ms)
ExecutionsPerSecond
FailedExecutions
  

@ Transactional

Transactional, subtype= Method

AverageElapsedExecutionTime(ms)
ExecutionsPerSecond
InvocationCount
MaximumExecutionTime(ms)
MinimumExecutionTime(ms)
ThrownExceptionCount
  

@Repository

Repository, subtype= Method

AverageElapsedExecutionTime(ms)
ExecutionsPerSecond
InvocationCount
MaximumExecutionTime(ms)
MinimumExecutionTime(ms)
ThrownExceptionCount
  


Spring ORM

The object-relational mapping (ORM) integration in Instrumented Spring Framework exposes ORM statistics in a manner consistent with the rest of the application model. Currently, Hibernate and JPA are the only ORMs whose metrics are exposed to the Instrumented Spring Framework model. A number of Hibernate SessionFactory metrics are available, including query execution count and entity fetch count. JPA metrics are currently only related to transaction management. The JpaTransactionManager exposes transaction commit, suspend, resume, and rollback rates.

Table 3.3. Spring ORM

Spring Framework ClassJMX MBean Type Key PropertyMetricsAttributesOperations

org.hibernate. Session Factory

Hibernate Session Factory

EntityInsertCount
EntityInsertCount1m
QueryExecutionMaxTime(ms)
EntityUpdateCount
EntityUpdateCount1m
CollectionUpdateCount
CollectionUpdateCount1m
EntityLoadCount
EntityLoadCount1m
EntityFetchCount
EntityFetchCount1m
EntityDeleteCount
EntityDeleteCount1m
CollectionRecreateCount
CollectionRecreateCount1m
QueryExecutionCount
QueryExecutionCount1m
FlushCount
FlushCount1m
CollectionLoadCount
CollectionLoadCount1m
SuccessfulTransactionCount
SuccessfulTransactionCount1m
QueryCacheHitCount
QueryCacheHitCount1m
CollectionRemoveCount
CollectionRemoveCount1m
ConnectCount
ConnectCount1m
StartTime
SecondLevelCachePutCount
SecondLevelCachePutCount1m
QueryCachePutCount
QueryCachePutCount1m
SessionOpenCount
SessionOpenCount1m
TransactionCount
TransactionCount1m
CollectionFetchCount
CollectionFetchCount1m
SessionCloseCount
SessionCloseCount1m
QueryCacheMissCount
QueryCacheMissCount1m
SecondLevelCacheMissCount
SecondLevelCacheMissCount
  


Spring JEE Integration

Instrumented Spring Framework provides visibility into Spring JMS, Java Mail, and thread-pooling integration components.

Instrumented Spring JMS provides data for JMS message senders and receivers. The MessageListenerContainers track the average execution time of message receipt and provide the number of failed message receipts. They expose the number of concurrent and/or scheduled consumer threads and allow you to modify the number of consumers, to help alleviate JMS queue backup at runtime. The JmsTemplate provides average time taken to send and receive messages and number of failed message sends and receipts. It allows runtime modification of the receive timeout.

Instrumented Spring JavaMailSender provides statistics on emails sent and allows you to configure the connection properties of the underlying mail server at runtime.

Instrumented Spring ThreadPoolTaskExecutor exposes thread pool utilization statistics and enables dynamic resizing of the pool and underlying queue at runtime.

Table 3.4. Spring JEE Integration

Spring Framework ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Default Message Listener Container

Default Message Listener Container

ActiveConsumers
AverageElapsedTimePerMessage(ms)
FailedMessages
MessagesPerSecond
MessagesReceived
ScheduledConsumers

Max Concurrent Consumers, Concurrent Consumers, Max Messages Per Task, Idle Task Execution Limit, Running

start, stop, set Concurrent Consumers, set Max Concurrent Consumers, scale Max Concurrent Consumers set Max Messages Per Task, set Idle Task Execution Limit

Server Session Message Listener Container

Server Session Message Listener Container

AverageElapsedTimePerMessage(ms)
FailedMessages
MessagesPerSecond
MessagesReceived

Max Messages Per Task, Running

start, stop, set Max Messages Per Task

Simple Message Listener Container

Simple Message Listener Container

AverageElapsedTimePerMessage(ms)
FailedMessages
MessagesPerSecond
MessagesReceived

Concurrent Consumers, Running

start, stop, set Concurrent Consumers

Jms Template

Jms Template

AverageElapsedTimePerMessageSent(ms)
FailedMessageSends
MessagesSent
MessagesSentPerSecond

Receive Timeout

set Receive Timeout

Java Mail Sender Impl

Java Mail Sender

AverageElapsedTimePerMessage(ms)
FailedMessages
MessagesSent
MessagesPerSecond
Host
Port
setHost
setPort

Thread Pool Task Executor

Thread Pool Task Executor

ActiveTasks
LargestPoolSize
PoolSize
QueueSize

Core Pool Size, Max Pool Size, Keep Alive Seconds

set Core Pool Size, set Max Pool Size, set Keep Alive Seconds


Spring MVC

Instrumented Spring MVC provides statistics for HTTP requests (via DispatcherServlet), view resolution, and view rendering, as well as Controller performance metrics. Most Spring MVC Controller implementations expose request statistics, and components annotated with @Controller will have execution time metrics exposed for each of their public methods. ViewResolvers and ViewRenderers provide throughput and failure data. DispatcherServlet exposes throughput of HTTP requests and also exposes the number of unhandled Exceptions, allowing you to track how often a stack trace is displayed to your application's end user.

Table 3.5. Spring MVC

Spring Framework ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Controller (Interface)

Controller

FailedRequests
RequestsHandled
RequestsHandledPerSecond
  

@Controller

Multi Action Controller, subtype= Method

AverageElapsedExecutionTime(ms)
ExecutionsPerSecond
InvocationCount
MaximumExecutionTime(ms)
MinimumExecutionTime(ms)
ThrownExceptionCount
  

Dispatcher Servlet

Dispatcher Servlet

AverageElapsedTimePerRequest(ms)
MaxRequestTime(ms)
MinRequestTime(ms)
RequestsProcessed
RequestsPerSecond
UnhandledExceptions
  

Abstract View

View

AverageElapsedTimePerViewRender(ms)
FailedViewRenders
ViewsRendered
ViewsRenderedPerSecond
  

View Resolver

View Resolver

AverageElapsedTimePerView(ms)
FailedViewResolutions
ViewsResolved
ViewsPerSecond
  


3.2. Spring Security Metrics

Instrumented Spring Framework works with Spring Security to automatically expose performance and utilization metrics related to both authentication and authorization. The following sections describe data and control operations available to you out-of-the-box with Instrumented Spring Security.

[Note]Note

The latest Instrumented Spring Security is version 2.0.6. If you need Spring Security 3.0.x functionality, use the open source Spring Security 3.0.x JARs instead of instrumented Spring Security 2.0.6. Spring Security 3.0.x requires Spring Framework 3.0.x.

Spring Security Authentication

Authentication metrics include the total number of successful and failed authentications, the number of "run as" operations, and the number of switched users. Instrumentation of the ExceptionTranslationFilter reveals the number of authentication entry point redirects and delegations to "Access Denied" handlers.

Instrumented Spring Security also provides visibility into user caches and the performance of user loading operations.

Table 3.6. Spring Security Authentication Instrumentation

Spring Security ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Provider Manager

Authentication Provider Manager

FailedAuthentications
SuccessfulAuthentications
  

Exception Translation Filter

Exception Translation Filter

AccessDeniedHandlerDelegations
AuthenticationEntryPointRedirects
ExceptionsThrown
  

Run As Manager Impl

Run As Manager

Run As Operations
  

User Details Service

User Details Service

AverageElapsedTimePerUserLoad(ms)
FailedUserLoads
UsernameNotFoundExceptions
UsersLoaded
  

User Cache

User Cache

AverageRetrievalExecutionTime(ms)
Hits
Misses
Removals
  

Switch User Processing Filter

Switch User Processing Filter

SwitchedUsers
  


Spring Security Authorization Instrumentation

During authorization, the SecurityInterceptor gives performance details for authorization requests. Instrumented Spring Security also provides visibility into the ACL entry cache.

Table 3.7. Spring Security Authorization Instrumentation

Spring Security ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Basic Acl Entry Cache

Basic Acl Entry Cache

AverageRetrievalExecutionTime(ms)
Hits
Misses
Removals
  

Null Acl Entry Cache

Null Acl Entry Cache

   

Abstract Security Interceptor

Security Interceptor

AverageAfterInvocationAuthorizationTime(ms)
AverageBeforeInvocationAuthorizationTime(ms)
FailedAuthorizationRequests
RequestsAuthorized
  


3.3. Spring Web Flow Metrics

Instrumented Spring Framework works with Instrumented Spring Web Flow to provide visibility into the performance and resource utilization of individual flow executions as well as summary performance and utilization data per Flow Definition and across the entire application. The following sections describe data and control operations available to you out-of-the-box with Instrumented Spring Web Flow.

Web Flow Summary Statistics

For each Flow Definition used in your application, Instrumented Spring Web Flow automatically tracks the average flow execution time, number of failed and successful flow executions, average flow execution start time, and more. The number of times a flow ended in each possible outcome is tracked as well, providing insight into how your application is used in production (for example, how many times users are starting a flow execution and then canceling before completion). Instrumented Spring Web Flow also monitors how often snapshots are taken during flow executions.

Instrumented Spring Web Flow provides application-level visibility into the Flow Definition Registry, allowing you to inspect its contents at runtime. Additionally, the Flow Execution Repository is instrumented for management and monitoring, exposing the maximum number of snapshots taken in a single flow execution and the maximum number of flow executions created in a single session across the entire application. Runtime controls allow you to adjust the maximum number of allowable snapshots and executions per session at runtime to scale your application in response to these metrics.

Table 3.8. Spring Web Flow Instrumentation

Spring Web Flow ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Flow Definition Registry Impl

Flow Definition Registry

FlowDefinitionCount

Flow Definition Ids

 

Flow

Flow Definition

ExecutionsExpired
MinSnapshotsTakenPerExecution
AverageSnapshotsTakenPerExecution
AverageExecutionStartTime(ms)
ExecutionsStarted
AverageExecutionTime(s)
MaxSnapshotsTakenPerExecution
ExecutionStartFailures
MaxExecutionTime(s)
LastExecutionStartTime
ExecutionsEnded
MinExecutionTime(s)
ActiveExecutions
LastExecutionEndTime
ExecutionsFailed
Caption
Description
 

Flow. Get Possible Outcomes

Flow Definition, subtype= Outcome

ExecutionsEnded
  


Web Flow Execution Statistics

If enabled, Instrumented Spring Web Flow exports individual Flow Executions and Flow Execution Snapshots to JMX. This provides a deep level of insight into the behavior of your application to assist in troubleshooting and diagnosing performance or utilization issues. Individual flow executions and their snapshots are represented as JMX MBeans until the flow execution ends or its corresponding HTTP session expires.

Instrumented Spring Web Flow allows you to inspect the current state of the Flow Execution, the execution start times, and the number of snapshots taken during the execution. Each Flow Execution Snapshot MBean exposes the flow state and snapshot creation time and allows you to inspect the entire contents of Flow Scope at the time of the snapshot.

Note to SpringSource AMS users: SpringSource AMS ignores any FlowExecution and FlowExecutionSnapshot MBeans found in the MBeanServer during auto-discovery. These MBeans will not be imported into the AMS inventory model.

Table 3.9. Spring Web Flow Instrumentation

Spring Web Flow ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Default Flow Execution Repository

Flow Execution Repository

MaxExecutionsCreatedPerSession
MaxSnapshotsTakenPerExecution

Max Executions, Max Snapshots

set Max Executions, set Max Snapshots

Flow Execution

Flow Execution

Snapshots
CurrentState
StartTime
 

Flow Execution Snapshot

Flow Execution, subtype= Snapshot

 
State
CreationTime
Flow Scope
 


3.4. Spring Web Services Metrics

Instrumented Spring Framework works with Instrumented Spring Web Services to expose a number of metrics, attributes,and runtime operations for Web Services application components.

Web Services Server Statistics

Instrumented Spring Web Services provides visibility into the MessageDispatcher as well as each registered endpoint to which messages are dispatched. The MessageDispatcher exposes dispatch throughput statistics. Each endpoint exposes execution time statistics, SOAP attachment size metrics, and SOAP fault information.

Instrumented Spring Web Services monitors most of its managed resources using a combination of compile-time woven aspects and hooks into existing Spring Web Services code. Instrumented Spring Web Services also uses Spring AOP proxies to monitor implementations of EndpointAdapter, the interface that must be implemented in order for each endpoint type to handle a message request. In most cases, Spring Web Services uses its own EndpointAdapter implementations, such as MessageEndpointAdapter or PayloadEndpointAdapter. Thus you should be able to monitor execution of any endpoint known to the MessageDispatcher with no additional configuration required. If you are using a custom EndpointAdapter, Instrumented Spring Web Services will attempt to create a Java dynamic proxy around your component. See Spring Framework Reference for more details about Spring AOP proxies. If the EndpointAdapter cannot be proxied, it is still exported as an MBean; however, its metrics are never updated.

Table 3.10. Spring Web Services Server Instrumentation

Spring Web Services ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Message Dispatcher

Message Dispatcher

AverageElapsedTimePerRequest(ms)
MaxRequestTime(ms)
MinRequestTime(ms)
Requests
RequestExceptions
RequestsPerSecond
  

Endpoint (determined by MessageDispatcher Endpoint Mappings)

Endpoint

MinRequestTime(ms)
Requests
RequestsPerSecond
MaxRequestTime(ms)
RequestExceptions
AverageElapsedTimePerRequest(ms)
MaxSOAPFaults
MinSOAPFaults
SOAPFaults
MaxAttachmentSize(B)
MinAttachmentSize(B)
AverageAttachmentSize(B)
AttachmentsProcessed
  

Soap Fault

SOAP Fault

SOAPFaults
MaxSOAPFaults
MinSOAPFaults
  


Web Services Client Statistics

Instrumented Spring Web Services provide information on request execution time per target URL when the URL is routed through the WebServiceTemplate. Each target URL is represented with its own JMX MBean containing request execution statistics. All JMX reserved characters such as ':' are stripped from the URL when the MBean ObjectName is created. The image below depicts a client application making a request to the Spring Travel sample application for hotel listings.

JConsole View of MBeans automatically exported by Web Services client application

Table 3.11. Spring Web Services Client Instrumentation

Spring Web Services ClassJMX MBean Type Key PropertyMetricsAttributesOperations

Web Service Connection. Get Uri() through Web Service Template send and receive

Web Service Template, subtype= Web Service Target

AverageElapsedTimePerRequest(ms)
MaxRequestTime(ms)
MinRequestTime(ms)
Requests
FailedRequests
RequestsPerSecond
  


4. Instrumenting Applications

This chapter describes how to set up your application to use Instrumented Spring Framework, Web Services, Web Flow, and Security. It outlines the necessary build and configuration steps that will allow Instrumented Spring products to automatically export their components to your application's JMX MBeanServer and enable automatic monitoring of those components. If you do not already use Spring Framework, you can learn more about it from Spring Framework Reference.

4.1. Adding Instrumented JARs to Applications

The JARs that you must add to your application are in the "dist" and "lib" directories of the unpacked spring-<instrumented product>-instrumented-management zip files for Instrumented Spring Framework, Web Services, Web Flow, and Security.

[Note]Note

If you will be replacing open source JARs with corresponding instrumented JARs, your replacements must be of the same maintenance release, that is, a release where the first and second digits of the release numbers are identical. For example, you can replace open source Spring Web Flow 2.0.0 with Instrumented Spring Web Flow 2.0.8. However, you cannot replace open source Spring Framework 2.5.x with Instrumented Spring Framework 3.0.0. You must first upgrade to Spring Framework 3.0.x. To do so, refer to the Spring Framework Upgrade Guide and the 3.0 Spring Framework Reference.

The JARs you need to use depend on the application you are instrumenting. For more information about these JARs, see JAR Components.

  • org.springframework.<module>.instrumented-<version>.jar: Instrumented JARs that are compile-time woven versions of their open source counterparts.

  • com.springsource.management.instrumentation.<instrumentedproduct>.<module>-<version>.jar: Instrumentation JARs that contain the AspectJ aspects used to weave the instrumented JARs at compile time.

  • com.springsource.management.agent.<module>-<version>.jar and com.springsource.management.adapter.<module>-version.jar: Spring Framework JARs that contain the API used to auto-discover Spring beans, export them to JMX, and obtain and store monitoring data.

Adding Instrumented Spring Framework JARs to Applications

Add the instrumented JAR files to your application classpath. If you are already using open source Spring Framework, replace each Spring Framework JAR in your application with the corresponding instrumented JAR in the dist directory. These jars are named org.springframework.<module>.instrumented-<version>.jar. See Mapping Maven Central JAR Names to EBR JAR Names if you originally obtained your non-instrumented Spring JAR files from the Maven Central repository.

[Note]Note

You cannot use both an instrumented JAR file and its open source equivalent. You must remove the open source JAR and add the corresponding instrumented JAR in its place.

For each instrumented JAR that you add to your application, include the matching instrumentation JAR, com.springsource.management.instrumentation.springframework.<module name>-<version>.jar. These instrumentation jars contain the aspects and Java classes used to manage and monitor the components in the instrumented JAR. Make sure you include com.springsource.management.instrumentation.springframework.applicationcontext.jar. It must be present to enable auto-discovery.

Some instrumentation JARs are shared among the instrumented Spring modules. For example, subclasses of AbstractPlatformTransactionManager exist in multiple jars. As such, all of these JARs may have a dependency on the com.springsource.management.instrumentation.springframework.transaction.manager.jar. When in doubt, consult the Import-Packages statement of the instrumented jar Manifest for the required dependencies.

Include the following Management API jars:

  • com.springsource.management.adapter.jmx-<version>.jar

  • com.springsource.management.agent.bootstrap-<version>.jar

  • com.springsource.management.agent.config-<version>.jar

  • com.springsource.management.agent.control-<version>.jar

  • com.springsource.management.agent.discovery.domain-<version>.jar

  • com.springsource.management.agent.discovery.resource-<version>.jar

  • com.springsource.management.agent.inventory-<version>.jar

  • com.springsource.management.agent.monitoring-<version>.jar

Include one of the following, depending on whether you are instrumenting a standalone application or a web application:

  • com.springsource.management.agent.discovery.application.standalone-<version>.jar OR

  • com.springsource.management.agent.discovery.application.web-<version>.jar

Adding Instrumented Spring Web Flow, Web Services, and Security JARs to Applications

Add the instrumented JAR files to your application classpath. If you are using open source versions of these products, replace the JARs in your application with the corresponding instrumented jars in the dist directory of the Instrumented Spring Web Flow, Web Services, and Security components. These jars are named org.springframework.<module>.instrumented-<version>.jar. See Mapping Maven Central JAR Names to EBR JAR Names if you originally obtained your non-instrumented Spring JAR files from the Maven Central repository.

[Note]Note

You cannot use both an instrumented JAR file and its open-source equivalent. You must remove the open-source JAR and add the corresponding instrumented JAR in its place.

[Note]Note

The latest Instrumented Spring Security (2.0.6) does not include instrumented versions of all jars distributed with open source Spring Security 3.0.x. Use the open source Spring Security 3.0 instead of instrumented Spring Security if you need these additional jars. (Spring Security 3.0.x requires Spring Framework 3.0.x.)

For each instrumented JAR that you add to your application, include the matching instrumentation JAR, com.springsource.management.instrumentation.<instrumentedproduct>.<module name>-<version>.jar. These instrumentation jars contain the aspects and Java classes used to manage and monitor the components in the instrumented JAR.

Mapping Maven Central JAR Names to EBR JAR Names

Typically, when you write your Spring applications, you obtain the Spring JAR files from one of the following two repositories:

  • Maven Central, which is the default repository for Maven queries.

  • Enterprise Bundle Repository (EBR), which is run by SpringSource and also hosts all the libraries that integrate with Spring.

However, it is important to note that each repository uses a different naming scheme for the JAR files. The Spring instrumented JAR files are all based on the naming in EBR. This means that if you originally obtained your non-instrumented Spring JAR files from Maven Central, and now want to replace them with instrumented JAR files, you will need to translate the JAR names appropriately.

For example, if your application uses the non-instrumented JAR file from Maven Central called spring-webmvc-version.jar and you want to replace it with the instrumented JAR, you would replace it with the following file: org.springframework.web.servlet.instrumented-version.jar.

The following table lists the most common Spring JAR names, first using their Maven Central names and then their corresponding EBR name.

Table 4.1. Mapping Between Maven Central and EBR JAR Names

Maven Central JAR NameEBR JAR Name
spring-aoporg.springframework.aop
spring-asmorg.springframework.asm
spring-aspectsorg.springframework.aspects
spring-beansorg.springframework.beans
spring-contextorg.springframework.context
spring-context-supportorg.springframework.context.support
spring-coreorg.springframework.core
spring-expressionorg.springframework.expression
spring-instrumentorg.springframework.instrument
spring-jdbcorg.springframework.jdbc
spring-jmsorg.springframework.jms
spring-ormorg.springframework.orm
spring-oxmorg.springframework.oxm
spring-testorg.springframework.test
spring-txorg.springframework.transaction
spring-weborg.springframework.web
spring-webmvcorg.springframework.web.servlet
spring-webmvc-portletorg.springframework.web.portlet

4.2. Configuring Applications for Auto-Discovery

Instrumented Spring Framework automatically discovers applications by advising the refresh method of the AbstractApplicationContext. Similarly, an application's managed resources are undeployed when all of its AbstractApplicationContexts have been closed.

Configuring Web Applications for Auto-Discovery

If a WebApplicationContext is detected, the ServletContext is obtained from it. The discovered application name is then set to the value of ServletContext.getServletContextName(), if the servlet context name is set through the display-name attribute of the web.xml. If the context name is not set, the discovered application name is set to the value of ServletContext.getRealPath("/").

Note: WebLogic does not return a value from ServletContext.getRealPath(). If you are using WebLogic, set the display-name attribute in your application's web.xml file to a logical name for your application. This MUST be done in order for the auto-discovery component to export any managed resources.

Application discovery using ServletContext.getRealPath() has been tested on SpringSource tc Server 2.0, the previous version of tc Server, Apache Tomcat 6.0, WebSphere 6.1, and JBoss 4.2; it should work without issue. If you do not see managed resources being exported, set the display-name attribute and redeploy the application. To troubleshoot auto-discovery, see Verifying Auto-Discovery of Deployed Applications.

Configuring Standalone Applications for Auto-Discovery

If any subclass of AbstractApplicationContext other than WebApplicationContext is detected, the application is assumed to be a standalone application. If you are running a standalone application, set the System property: "spring.managed.application.name=<application name>". If this property is not set, managed resources will not be exported.

Configuring Applications for Managed Resource Discovery

Any bean that is created through an AbstractApplicationContext is discovered as a managed resource if the instrumented components know how to manage and monitor it. When managed resources are exported, they are named using bean names, so make sure that all beans you want to manage are consistently named. An instance of an anonymous bean could have a different name each time the application is restarted, which causes inconsistencies in data persisted by external management systems such as SpringSource AMS.

A managed resource that represents an ApplicationContext or BeanFactory is named using the display name of the ApplicationContext. This is set consistently by Spring within web applications. However, if you are creating your own ApplicationContext (such as a new ClasspathXmlApplicationContext), it is recommended that you set "refresh" to false, then set the display name on the ApplicationContext before calling "refresh", as follows:

ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(new 
	String[] {"classpath:com/springsource/management/test-context.xml"},false);
applicationContext.setDisplayName("My Application's ApplicationContext");
applicationContext.refresh();

Taking this step ensures that your ApplicationContext and its BeanFactory are named the same each time the application is restarted.

4.3. Configuring Applications for Remote JMX Access

Instrumented Spring Framework automatically creates JMX ModelMBeans that represent each application resource it discovers, and registers these ModelMBeans in an auto-detected MBeanServer. If you are running your application in SpringSource tc Server, JBoss, WebLogic or WebSphere, Instrumented Spring Framework should be able to detect the container MBeanServer automatically and export the managed resources, with no additional configuration required.

JMX in tc Server

Remote monitoring through JMX is automatically enabled in SpringSource tc Server. Consult the server documentation for additional information.

JMX in WebLogic

If you deploy your application in WebLogic 9.1+, Instrumented Spring Framework automatically exports all managed resources to the WebLogic MBeanServer obtained through a JNDI lookup of "java:comp/env/jmx/runtime". See Configuration Properties for options related to WebLogic MBeanServer discovery.

JMX in WebSphere

If you deploy your application in WebSphere 5.1+, Instrumented Spring Framework automatically exports all managed resources to the WebSphere MBeanServer obtained through WebSphere's proprietary AdminServiceFactory API. See Configuration Properties for options related to WebSphere MBeanServer discovery.

JMX in Apache Tomcat

You need to configure Tomcat to create an MBeanServer and a JSR-160 connector. See http://tomcat.apache.org/tomcat-${product.version}-doc/monitoring.html for further information. The quick start method recommended by Tomcat is as follows:

Add the following properties to $CATALINA_HOME/bin/setenv.sh or setenv.bat:

						
CATALINA_OPTS="-Dcom.sun.management.jmxremote \
	-Dcom.sun.management.jmxremote.port=6969 \
	-Dcom.sun.management.jmxremote.ssl=false \
	-Dcom.sun.management.jmxremote.authenticate=false"
						

A full list of options for configuring JMX remote through these System properties can be found on Sun's website.

JMX in JBoss

If deploying your application in JBoss 3.2+, Instrumented Spring Framework automatically exports all managed resources to the JBoss MBeanServer obtained through lookup of the local MBeanServer. The exported MBeans are also visible from the JBoss JMX Console.

JMX in Standalone Applications

For standalone applications (or possibly other containers not listed above), Instrumented Spring Framework simply exports managed resources to any local MBeanServer it finds. For remote access to this MBeanServer, create a JSR-160 connector. Spring JMX can be used to create a local MBeanServer and JSR-160 connector in your application. See Spring Framework Reference for further information on Spring JMX.

Additionally, you can use the JMX remote system properties. The following system properties create a local MBeanServer and remote connector:

						
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=6969
-Dcom.sun.management.jmxremote.ssl=false
-Dcom.sun.management.jmxremote.authenticate=false"
						

For a full list of options for configuring JMX remote through these System properties, see Sun's website.

4.4. Configuring Applications for Monitoring (Optional)

Configure instrumented Spring applications by adding a properties file called "management.config" to a directory in your application's classpath (for example, WEB-INF/classes/management.config in a web application). Properties defined in this file will be read and applied by Instrumented Spring Framework when the instrumented application is deployed.

Table 4.2. Configuration Properties

PropertyDescription

monitor.proxyTargetClass

Specifies Spring AOP proxy behavior when you create monitoring proxies for user-defined components, such as those annotated with @Service, @Component, etc. Setting the value to true forces the use of CGLIB to proxy target classes for every component to which monitoring proxies are applied. The default value is false, which means that JDK proxies will be created for any component implementing an interface. CGLIB will only be used for components that do not implement interfaces.

jmx.discoverWeblogicServer

Determines whether the MBeanServer auto-detector should attempt to detect a WebLogic environment through classpath scanning. If discoverLocalServer is set to true (default) and a WebLogic environment is not detected, this component still attempts local MBean server discovery and/or local MBeanServer creation. Change this value if a classpath scan reveals a WebLogic environment, but you do not want to retrieve the WebLogic MBeanServer through JNDI lookup.

jmx.discoverWebSphereServer

Determines whether the MBeanServer auto-detector should attempt to detect a WebSphere environment through classpath scanning. If discoverLocalServer is set to true (default) and a WebLogic environment is not detected, this component still attempts local MBean server discovery and/or local MBeanServer creation. Change this value if a classpath scan reveals a WebSphere environment, but you do not wish to retrieve the WebSphere MBeanServer through AdminClient lookup.

jmx.discoverLocalServer

Determines whether MBeanServerFactory.findMBeanServer() should be used to locate an existing MBeanServer when a WebLogic or WebSphere MBeanServer is not found, or if discovery of WebLogic and WebSphere servers has been disabled. Default value is true.

jmx.agentId

Agent id of the MBeanServer to locate. Default is none. If specified, an automatic attempt is made to locate the attendant MBeanServer, and (importantly) if said MBeanServer cannot be located, no attempt is made to create a new MBeanServer.

jmx.defaultDomain

Default domain to be used by the MBeanServer, to be passed to MBeanServerFactory.createMBeanServer() or MBeanServerFactory.findMBeanServer(). Default is none.


4.5. Enabling Discovery and Monitoring of Flow Executions (Optional)

Most Spring Web Flow Managed Beans are automatically discovered and exported to JMX with no additional configuration required. However, Flow Execution and Flow Execution Snapshots are not exported to JMX unless you add the following is added to your application's web.xml file:



 <listener>
 	<listener-class>com.springsource.management.instrumentation.springwebflow.webflow.
 		event.HttpSessionEventPublisher</listener-class>
 </listener>

This listener must be registered in order to remove exported Flow Execution and Flow Execution Snapshot managed resources when an HTTP session expires. If this listener is not present, discovery of executions and snapshots is disabled by default.

If you want to enable discovery of flow executions and snapshots without registering the listener, you can do so at runtime by calling the setFlowExecutionDiscoveryEnabled control operation on an individual Flow Definition or across the application on the Flow Execution Repository.

4.6. Verifying Auto-Discovery of Deployed Applications

Now that the configuration is complete, you are ready to deploy your application and let Instrumented Spring Framework, Web Flow, Web Services, and Security begin automatically monitoring your application components.

Note for WebSphere users: WebSphere ships an older version of aspectjrt.jar in their lib directory than was used to weave the instrumented Spring JARs. As a result, the Instrumented Spring products will not work correctly unless you change the application classloader order to load classes from the application's classpath first. Change the application classloader order from the WebSphere Administrative Console by navigating to Enterprise Applications->${application name}->Manage Modules->Class Loader Order.

Verifying auto-discovery through logging

Instrumented Spring Framework, Web Flow, Web Services, and Security use Commons Logging. All logger names begin with "com.springsource.management". Use the log file to verify that your application was discovered on deployment. If the logging level is set to "Info", you should see a message in your log when an application is discovered. For example:

						
INFO [com.springsource.management.agent.discovery.application.DefaultApplicationDiscoverer] - 
	Discovered application: Spring PetClinic
						
						

You can also see each managed resource that is discovered and exported. For example:

						
INFO [com.springsource.management.adapter.jmx.ManagedResourceExporter] - Registered MBean: 
	spring.application:application=Spring PetClinic,type=PlatformTransactionManager,
	name=transactionManager 
						
						

Verifying Auto-Discovery Through JConsole

If your container supports it, you can use a tool such as JConsole to verify that Instrumented Spring Framework and Instrumented Spring Web Services, Security, or Web Flow have automatically discovered and exported your application resources. For example, the following is displayed in JConsole upon deploying the Spring Framework Pet Clinic sample application to Tomcat:

JConsole View of MBeans Automatically Exported by Instrumented Pet Clinic Application

You can also verify that your resources are being monitored by inspecting a metric that should be updated during application deployment, such as the Refresh-AverageExecutionTime(ms) metric depicted above.

5. Managing Custom Components

This chapter describes how to configure your custom application components for inclusion in the Instrumented Spring Framework management model. The chapter demonstrates how to use simple annotations to automatically export your components to JMX as ModelMBeans. These generated ModelMBeans contain information that enables discovery by monitoring systems.

5.1. Exporting Components to JMX

The recommended mechanism for exporting JMX MBeans is the Spring JMX annotations. Consult the JMX chapter of the Spring Framework Reference for additional information on Spring JMX.

Using Spring JMX to expose MBeans:

	
<beans>
    <bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
        <property name="assembler" ref="assembler"/>
        <property name="namingStrategy" ref="namingStrategy"/>
        <property name="autodetect" value="true"/>
    </bean>

    <bean id="jmxAttributeSource"
          class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/>

    <!-- will create management interface using annotation metadata -->
    <bean id="assembler"
          class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
        <property name="attributeSource" ref="jmxAttributeSource"/>
    </bean>

    <!-- will pick up the ObjectName from the annotation -->
    <bean id="namingStrategy"
          class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
        <property name="attributeSource" ref="jmxAttributeSource"/>
    </bean>
</beans>

The following accomplishes the same functionality as above by using the Spring 3.0 context namespace:

	
<beans>
	<context:mbean-export/>
</beans>

Source-Level Metadata Types

The following source level metadata types are available for use in Spring JMX.

Table 5.1. Source-level metadata types

PurposeAnnotationAnnotation Type

Mark all instances of a Class as JMX managed resources.

@ManagedResource

Class

Mark a method as a JMX operation.

@ManagedOperation

Method

Mark a getter or setter as one half of a JMX attribute.

@ManagedAttribute

Method (only getters and setters)

Mark a getter as a JMX attribute with JMX metricType and units descriptor values.

@ManagedMetric

Method (only getters)


The following configuration parameters are available for use on these source-level metadata types. They are translated to ModelMBeanInfo fields by the MetadataMBeanInfoAssembler.

Table 5.2. Configuration Parameters

ParameterDescriptionApplies ToModelMBean Field Translated To

objectName

Used by MetadataNamingStrategy to determine the ObjectName of a managed resource.

@ManagedResource

ModelMBean ObjectName

description

Sets the friendly description of the resource, attribute, metric or operation.

ManagedResource, ManagedAttribute, ManagedOperation, ManagedMetric

ModelMBeanInfo. getDescription(), ModelMBeanAttributeInfo. getDescription(), ModelMBeanOperationInfo. getDescription()

category

Sets the category of the metric.

ManagedMetric

ModelMBeanAttributeInfo. getDescriptor(). getField("metricCategory")

displayName

Sets the display name of the metric for possible use by external clients.

ManagedMetric

ModelMBeanAttributeInfo. getDescriptor(). getField("displayName")

metricType

A description of how the metric's values change over time.

ManagedMetric

ModelMBeanAttributeInfo. getDescriptor(). getField("metricType")

unit

The unit in which an attribute is measured, for example "B" or "ms".

ManagedMetric

ModelMBeanAttributeInfo. getDescriptor(). getField("units")


Example: Exporting a Custom Component

The following example uses annotations to automatically export JMX ModelMBeans:


package org.springframework.webflow.samples.booking.messaging;

import java.util.ArrayList;
import java.util.List;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.ObjectMessage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.webflow.samples.booking.Booking;
import org.springframework.webflow.samples.booking.mail.BookingMailService;


@ManagedResource(objectName = "spring.application:application=swf-booking-mvc,
	type=MessageListener,name=bookingQueueMessageListener")
public class BookingQueueMessageListener implements MessageListener {

	private List messageQueue = new ArrayList();

	private long messageQueueSize=0;

	private boolean sendConfirmationEmail = false;
	
	@ManagedMetric(category="utilization", displayName="Message Queue Size", 
		description="The size of the Message Queue", 
		metricType = MetricType.COUNTER, unit="messages")
	public long getMessageQueueSize() {
		return messageQueueSize;
	}

	@ManagedAttribute(description="Send a confirmation email")
	public boolean isSendConfirmationEmail() {
		return sendConfirmationEmail;
	}
	
	@ManagedOperation
	public void resetMessageQueue() {
		this.messageQueue.clear();
	}

	@ManagedAttribute(description = "Send a confirmation email")
	public void setSendConfirmationEmail(boolean sendConfirmationEmail) {
		this.sendConfirmationEmail = sendConfirmationEmail;
	}
}

6. Integrating Instrumented Applications with Monitoring Systems

tc Server 2.x Spring Edition is integrated with Hyperic HQ 4.2 and later. If you use tc Server 2.x Spring Edition or if you use another application server together with Hyperic HQ, you will integrate instrumented applications into the Hyperic HQ dashboard. Hyperic HQ monitors and manages web applications across a broad range of platforms and technologies, both on-premise and cloud-hosted. Use it to streamline operations, manage infrastructure complexity, and drive service level improvements.

If you are using tc Server 2.x Spring Edition, Hyperic HQ 4.2 should be able to discover and monitor your applications, once you implement the procedures in Instrumenting Applications and Managing Custom Components. (For additional information, see Instrumenting Java Applications for Management in the Hyperic HQ documentation.)

If you are using an application server other than tc Server 2.x Spring Edition and want to integrate your Spring applications with Hyperic HQ 4.2, refer to Instrumenting Java Applications for Management in the Hyperic HQ documentation.

If you use an earlier release of tc Server, refer to the tc Server documentation for that release and to SpringSource AMS (Powered by Hyperic HQ) Manual.

If you are using neither tc Server nor Hyperic HQ but still wish to receive application metrics from the instrumented Spring libraries, consult the manual for your monitoring solution provider on how to consume JMX from enterprise systems.