Chapter 3. Agents

Jolokia is an agent based approach to JMX, which requires that clients install an extra piece of software, the so-called agent. This software either needs to be deployed on the target server which should be accessed via remote JMX (Section 2.1, “Agent mode”), or it can be installed on a dedicated proxy server (Section 2.2, “Proxy Mode”). For both operational modes, there are four different kind of agents[1].

Webarchive (War) agent
This agent is packaged as a JEE Webarchive (War). It is the standard installation artifact for Java webapplications and probably one of the best known deployment formats. Jolokia ships with a war-agent which can be deployed like any other web application. This agent has been tested on many JEE servers, from well-known market leaders to rarer species.
OSGi agent
OSGi is a middleware specification focusing on modularity and a well defined dynamic lifecycle [2]. The Jolokia OSGi agent bundles comes in two flavors: a minimal one with a dependency on a running OSGi HttpService, and a all-in-one bundle including an embedded HttpService implementation (which is exported, too). The former is the recommended, puristic solution, the later is provided for a quick startup for initial testing the OSGi agent (but should be replaced with the minimal bundle for production setups).
Mule agent
Mule is one of the leading Open Source Enterprise Service Busses[3] (ESB). It provides a management API into which a dedicated Jolokia agent plugs in nicely. This agent includes an embedded Jetty for providing JMX HTTP access.
JVM agent
Starting with Java 6 the JDK provided by Oracle contains a lightweight HTTP-Server which is used e.g. for the reference WebService stack implementation included in Java 6. Using the Java-agent API (normally used by profilers and other development tools requiring the instrumentation during the class loading phase), the JVM 6 Jolokia agent is the most generic one. It is able to instrument any Java application running on a Oracle JDK 6[4]. This Jolokia agent variant is fully featured, however tends to be a bit slow since the provided HTTP-Server is not optimized for performance. However it is useful for servers like Hadoop or Teracotta, which do not provide convenient hooks for an HTTP-exporting agent on their own.

3.1. JEE Agent (WAR)

3.1.1. Installation and Configuration

The WAR agent is the most popular variant, and can be deployed in a servlet container just like any other JEE web application.

Often, installation is simply a matter of copying the agent WAR to a deployment directory. On other platforms an administrative Web GUI or a command line tool need to be used for deployment. Providing detailed installation instructions for every servlet container is out of scope for this document.

The servlet itself can be configured in two ways:

Servlet Init Parameters
Jolokia can be configured with init-param declarations within the servlet definition in WEB-INF/web.xml. The known parameters are described in Table 3.1, “Servlet init parameters”. The stock agent needs to be repackaged, though, in order to modify the internal web.xml.
Servlet Context Parameters
A more convenient possibility might be to use servlet context parameters, which can be configured outside the WAR archive. This is done differently for each servlet container but involves typically the editing of a configuration file. E.g. for Tomcat, the context for the Jolokia agent can be adapted by putting a file jolokia.xml below $TC/conf/Catalina/localhost/ with a content like:
<Context> 
   <Parameter name="maxDepth" value="1"/> 
</Context>

The configuration options discoveryEnabled and discoveryAgentUrl can be provied via environent variables or system properties, too. See the below for details.

Table 3.1. Servlet init parameters

Parameter Description Example
dispatcherClasses Classnames (comma separated) of RequestDispatcher used in addition to the LocalRequestDispatcher. Dispatchers are a technique used by the JSR-160 proxy to dispatch (or 'route') a request to a different destination. org.jolokia.jsr160.Jsr160RequestDispatcher (this is the dispatcher for the JSR-160 proxy)
policyLocation Location of the policy file to use. This is either a URL which can read from (like a file: or http: URL) or with the special protocol classpath: which is used for looking up the policy file in the web application's classpath. See Section 4.1.7, “Policy Location” for details about this parameter. file:///home/jolokia/jolokia-access.xml for a file based access to the policy file. Default is classpath:/jolokia-access.xml
debug Debugging state after startup. Can be changed via the config MBean during runtime. Default: false
historyMaxEntries Entries to keep in the history. Can be changed at runtime via the config MBean. Default: 10
debugMaxEntries Maximum number of entries to keep in the local debug history (if enabled). Can be changed via the config MBean at runtime. Default: 100
maxDepth Maximum depth when traversing bean properties. If set to 0, depth checking is disabled Default: 15
maxCollectionSize Maximum size of collections returned when serializing to JSON. When set to 0, collections are never truncated. Default: 1000
maxObjects Maximum number of objects which are traversed when serializing a single response. Use this as an airbag to avoid boosting your memory and network traffic. Nevertheless, when set to 0 no limit is imposed. Default: 0
mbeanQualifier Qualifier to add to the ObjectName of Jolokia's own MBeans. This can become necessary if more than one agent is active within a servlet container. This qualifier is added to the ObjectName of this agent with a comma. For example a mbeanQualifier with the value qualifier=own will result in Jolokia server handler MBean with the name jolokia:type=ServerHandler,qualifier=own
mimeType MIME to use for the JSON responses Default: text/plain
canonicalNaming This option specifies in which order the key-value properties within ObjectNames as returned by list or search are returned. By default this is the so called 'canonical order' in which the keys are sorted alphabetically. If this option is set to false, then the natural order is used, i.e. the object name as it was registered. This option can be overridden with a query parameter of the same name. Default: true
includeStackTrace Whether to include a stacktrace of an exception in case of an error. By default it it set to true in which case the stacktrace is always included. If set to false, no stacktrace is included. If the value is runtime a stacktrace is only included for RuntimeExceptions. This global option can be overridden with a query parameter. Default: true
serializeException When this parameter is set to true, then an exception thrown will be serialized as JSON and included in the response under the key error_value. No stacktrace information will be included, though. This global option can be overridden by a query parameter of the same name. Default: false
detectorOptions Extra options passed to an detector after successful detection of an application server. See below for an explanation.
discoveryEnabled Is set to true then this servlet will listen for multicast request (multicastgroup 239.192.48.84, port 24884). By default this option is disabled in order to avoid conflicts with an JEE standards (though this should't harm anyways). This option can also be switched on with an environment variable JOLOKIA_DISCOVERY or the system property jolokia.discoveryEnabled set to true. Default: false
discoveryAgentUrl Sets the URL to respond for multicast discovery requests. If given, discoveryEnabled is set implicetly to true. This URL can also be provied by an environment variable JOLOKIA_DISCOVERY_URL or the system property jolokia.discoveryUrl. Within the value you can use the placeholders ${host} and ${ip} which gets replaced by the autodetected local host name/address. Also with ${env:ENV_VAR} and ${sys:property} envirnoment and system properties can be referenced, respectively. http://10.9.11.87:8080/jolokia
agentId A unique ID for this agent. By default a unique id is calculated. If provided it should be ensured that this id is unique among all agent reachable via multicast requests used by the discovery mechanism. It is recommended not to set this value. my-unique-agent-id
agentDescription An optional description which can be used for clients to present a human readable label for this agent. Intranet Timebooking Server

Jolokia has various detectors which can detect the brand and version of an application server it is running in. This version is revealed with the version command. With the configuration parameter detectorOptions extra options can be passed to the detectors. These options take the form of a JSON object, where the keys are productnames and the values other JSON objects containing the specific configuration. This configuration is feed to a successful detector which can do some extra initialization on agent startup. Currently the following extra options are supported:

Table 3.2. Servlet init parameters

Product Option Description
glassfish bootAmx If false and the agent is running on Glassfish, this will cause the AMX subsystem not to be booted during startup. By default, AMX which contains all relevant MBeans for monitoring Glassfish is booted.

3.1.2. Security Setup

In order use JEE security within the war, some extrat configuration steps are required within web.xml.

There is a commented section which can serve as an example. All current client libraries are able to use BASIC HTTP authentication with user and password. The <login-config> should be set accordingly. The <security-constraint> specifies the URL pattern (which is in the default setup specify all resources provided by the Jolokia servlet) and a role name which is used to find the proper authentication credentials. This role must be referenced outside the agent WAR within the servlet container, e.g. for Tomcat the role definition can be found in $TOMCAT/config/tomcat-users.xml.

3.1.3. Programmatic usage of the Jolokia agent servlet

The Jolokia agent servlet can be integrated into one's own web-applications as well. Simply add a servlet with the servlet class org.jolokia.http.AgentServlet to your own web.xml. The following example maps the agent to the context /jolokia:

    <servlet>
      <servlet-name>jolokia-agent</servlet-name>
      <servlet-class>org.jolokia.http.AgentServlet</servlet-class>
      <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
      <servlet-name>jolokia-agent</servlet-name>
      <url-pattern>/jolokia/*</url-pattern>
    </servlet-mapping>
    

Of course, any init parameter as described in Table 3.1, “Servlet init parameters” can be used here as well.

In order for this servlet definition to find the referenced Java class, the JAR jolokia-core.jar must be included. This jar can be found in Jolokia's maven resository. Maven users will can declare a dependency on this jar artifact:

    <project>
      <!-- ....  --> 
      <dependencies>
        <dependency>
          <groupId>org.jolokia</groupId>
          <artifactId>jolokia-core</artifactId>
          <version>${jolokia.version}</version>
        </dependency>
      </dependencies>

      <!-- Maven repository hosting Jolokia -->
      <repositories>
        <repository>
          <id>labs-consol-release</id>
          <name>ConSol* Labs Repository (Releases)</name>
          <url>http://labs.consol.de/maven/repository</url>
        </repository>
      </repositories>
    </project>

The org.jolokia.http.Agent can be subclassed, too in order to provide a custom restrictor or a custom log handler. See Section 4.2, “Jolokia Restrictors” for details.[5]

Also, multiple Jolokia agents can be deployed in the same JVM without problem. However, since the agent deploys some Jolokia-specific MBeans on the single PlatformMBeansServer, for multi-agent deployments it is important to use the mbeanQualifier init parameter to distinguish multiple Jolokia MBeans by adding an extra propery to those MBeans' names. This also needs to be done if multiple webapps containing Jolokia agents are deployed on the same JEE server.

3.2. OSGi Agents

Jolokia agents are also available as OSGi bundles. There are two flavors of this agent: A nearly bare agent jolokia-osgi.jar declaring all its package dependencies as imports in its Manifest and an all-in-one bundle jolokia-osgi-bundle.jar with minimal dependecies. The pure bundle fits best with the OSGi philosophy and is hence the recommended bundle. The all-in-one monster is good for a quick start since normally no additional bundles are required.

3.2.1. jolokia-osgi.jar

This bundle depends mostly on a running OSGi HttpService which it uses for registering the agent servlet.

All package imports of this bundle are listed in Table 3.3, “Package Imports of jolokia-osgi.jar (SB: exported by system bundle)”. Note that the org.osgi.framework.* and javax.* packages are typically exported by the system bundle, so no extra installation effort is required here. Whether the org.osgi.service.* interfaces are available depends on your OSGi container. If they are not provided, they can be easily fetched and installed from e.g. maven central. Often the LogService interface is exported out of the box, but not the HttpService. You will notice any missing package dependency during the resolve phase while installing jolokia-osgi.jar.

Table 3.3. Package Imports of jolokia-osgi.jar (SB: exported by system bundle)

Package SB Package SB Package SB Package SB
org.osgi.framework X javax.servlet org.w3c.dom X javax.management X
org.osgi.service.http javax.servlet.http org.xml.sax X javax.management.openmbean X
org.osgi.service.log ? javax.naming X javax.xml.parsers X javax.management.remote X
org.osgi.util.tracker X

This agent bundle consumes two services by default: As stated above, an org.osgi.service.http.HttpService which is used to register (deregister) the Jolokia agent as a servlet under the context /jolokia by default as soon as the HttpService becomes available (unavailable). Secondly, an org.osgi.service.log.LogService is used for logging, if available. If such a service is not registered, the Jolokia bundle uses the standard HttpServlet.log() method for its logging needs.

The Jolokia OSGi bundle can be configured via the properties which typically can be configured in a global configuration file of the OSGi container. All properties start with the prefix org.jolokia and are listed in Table 3.4, “Jolokia Bundle Properties”. They are mostly the same as the init-param options for a Jolokia servlet when used in a JEE WAR artifact.

Table 3.4. Jolokia Bundle Properties

Property Default Description
org.jolokia.user User used for authentication with HTTP Basic Authentication. If not given, no authentication is used.
org.jolokia.password Password used for authentication with HTTP Basic Authentication.
org.jolokia.agentContext /jolokia Context path of the agent servlet
org.jolokia.agentId A unique ID for this agent. By default a unique id is calculated. If provided it should be ensured that this id is unique among all agent reachable via multicast requests used by the discovery mechanism. It is recommended not to set this value.
org.jolokia.agentDecription An optional description which can be used for clients to present a humand readable label for this agent.
org.jolokia.dispatcherClasses Class names (comma separated) of request dispatchers used in addition to the LocalRequestDispatcher. E.g using a value of org.jolokia.jsr160.Jsr160RequestDispatcher allows the agent to play the role of a JSR-160 proxy.
org.jolokia.debug false Debugging state after startup. This can be changed via the Config MBean (jolokia:type=Config) at runtime
org.jolokia.debugMaxEntries 100 Maximum number of entries to keep in the local debug history if switched on. This can be changed via the config MBean at runtime.
org.jolokia.maxDepth 0 Maximum depth when traversing bean properties. If set to 0, depth checking is disabled
org.jolokia.maxCollectionSize 0 Maximum size of collections returned when serializing to JSON. When set to 0, collections are not truncated.
org.jolokia.maxObjects 0 Maximum number of objects which are traversed when serializing a single response. Use this as an airbag to avoid boosting your memory and network traffic. Nevertheless, when set to 0 no limit is imposed.
org.jolokia.historyMaxEntries 10 Number of entries to keep in the history. This can be changed at runtime via the Jolokia config MBean.
org.jolokia.listenForHttpService true If true the bundle listens for an OSGi HttpService and if available registers an agent servlet to it.
org.jolokia.httpServiceFilter Can be any valid OSGi filter for locating a which org.osgi.service.http.HttpService is used to expose the Jolokia servlet. The syntax is that used by the org.osgi.framework.Filter which is in turn a RFC 1960 based filter. The use of this property is described in Section 3.2.2, “Running on Glassfish v3 upwards”
org.jolokia.useRestrictorService false If true the Jolokia agent will use any org.jolokia.restrictor.Restrictor service for applying access restrictions. If this option is false the standard method of looking up a security policy file is used, as described in Section 4.1, “Policy based security”.
org.jolokia.canonicalNaming true This option specifies in which order the key-value properties within ObjectNames as returned by list or search are returned. By default this is the so called 'canonical order' in which the keys are sorted alphabetically. If this option is set to false, then the natural order is used, i.e. the object name as it was registered. This option can be overridden with a query parameter of the same name.
org.jolokia.includeStackTrace true Whether to include a stacktrace of an exception in case of an error. By default it it set to true in which case the stacktrace is always included. If set to false, no stacktrace is included. If the value is runtime a stacktrace is only included for RuntimeExceptions. This global option can be overridden with a query parameter.
org.jolokia.serializeException false When this parameter is set to true, then an exception thrown will be serialized as JSON and included in the response under the key error_value. No stactrace infornmation will be included, though. This global option can be overridden by a query parameter of the same name.
org.jolokia.detectorOptions An optional JSON representation for application specific options used by detectors for post-initialization steps. See Table 3.1, “Servlet init parameters” for details.
org.jolokia.discoveryEnabled false Is set to true then this servlet will listen for multicast request (multicastgroup 239.192.48.84, port 24884). By default this option is disabled in order to avoid conflicts with an JEE standards (though this should't harm anyways). This option can also be switched on with an environment variable JOLOKIA_DISCOVERY or the system property jolokia.discoveryEnabled set to true.
org.jolokia.discoveryAgentUrl Sets the URL to respond for multicast discovery requests. If given, discoveryEnabled is set implicetly to true. This URL can also be provied by an environment variable JOLOKIA_DISCOVERY_URL or the system property jolokia.discoveryUrl
org.jolokia.realm jolokia Sets the security realm to use. If the authMode is set to jaas this is also used as value for the security domain. E.g. for Karaf 3 and later, this realm should be karaf since all JMX MBeans are guarded by this security domain.
org.jolokia.authMode basic Can be either basic (the default) or jaas. If jaas is used, the user and password given in the Authorization: header are used for loging in via JAAS and, if successful, the return subject is used for all Jolokia operation. This has only an effect, if user is set.

This bundle also exports the service org.jolokia.osgi.servlet.JolokiaContext which can be used to obtain context information of the registered agent like the context path under which this servlet can be reached. Additionally, it exports org.osgi.service.http.HttpContext, which is used for authentication. Note that this service is only available when the agent servlet is active (i.e. when an HttpService is registered).

3.2.2. Running on Glassfish v3 upwards

You have a couple of choices when running jolokia on Glassfish v3 and up, since Glassfish is a both a fully fledged JEE container and an OSGi container. If you choose to run the Section 3.1, “JEE Agent (WAR)” then it is completely straight forward just deploy the war in the normal way. If you choose to deploy the Section 3.2, “OSGi Agents” then you will need to configure the org.jolokia.httpServiceFilter option with a filter to select either the Admin HttpService (4848 by default) or the Default HttpService which is where WAR files are deployed to.

In Glassfish 3.1.2 the OSGi bundle configuration is done in glassfish/conf/osgi.properties in version's prior to this the configuration is by default in glassfish/osgi/felix/conf/config.properties or if you are using Equinox glassfish/osgi/equinox/configuration/config.ini

# Restrict the jolokia http service selection to the admin host
org.jolokia.httpServiceFilter=(VirtualServer=__asadmin)
# Or alternatively to the normal http service use : (VirtualServer=server)

Deploying the bundle can be either be done by coping the jolokia-osgi.jar into the domain glassfish/domains/<domain>/autodeploy/bundles directory or it can be added to all instances by copying the jar to glassfish/modules/autostart

By default the agent will be available on http://localhost:<port>/osgi/jolokia rather than http://localhost:<port>/jolokia as with WAR deployment.

3.2.3. jolokia-osgi-bundle.jar

The all-in-one bundle includes an implementation of org.osgi.service.http.HttpService, i.e. the Felix implementation. The HttpService will be registered as OSGi service during startup, so it is available for other bundles as well. The only package import requirement for this bundle is org.osgi.service.LogService, since the Felix Webservice requires this during startup. As mentioned above, normally the LogService interface gets exported by default in the standard containers, but if not, you need to install it e.g. from the OSGi compendium definitions.

This bundle can be configured the same way as the pure bundle as described in Section 3.2.1, “jolokia-osgi.jar”. Additionally, the embedded Felix HttpService can be configured as described in its documentation. e.g. setting the port to 9090 instead of the default port 8080, a property org.osgi.service.http.port=9090 needs to be set. This might be useful, if this bundle is used within containers which already occupy the default port (Glassfish, Eclipse Virgo) but don't expose an OSGi HttpService.

3.2.4. Programmatic servlet registration

It is also possible to register the Jolokia agent servlet manually instead of relying of the OSGi bundle activator which comes with the agents. For this use case jolokia-osgi.jar should be used. This bundle exports the package org.jolokia.osgi.servlet which includes the servlet class JolokiaServlet. This class has three constructors: A default constructor without arguments, one with a single BundleContext argument and finally one with an additional Restrictor (see Section 4.2, “Jolokia Restrictors” for details how access restrictions can be applied). The constructor with a BundleContext as its argument has the advantage that it will use an OSGi LogService if available and adds various OSGi server detectors which adds server information like product name and version to the version command. Refer to Section 6.2.6, “Getting the agent version (version)” for details about the server infos provided.

Please note that for this use case the bundle org.jolokia.osgi should not be started but left in the state resolved. Otherwise, as soon as an OSGi HttpService registers, this bundle will try to add yet another agent servlet to this service, which is probably not what you want. Alternatively, the bundle property org.jolokia.listenForHttpService can be set to false in which case there will be never an automatic servlet registration to an HttpService.

3.2.5. Restrictor service

As described in Section 4.2, “Jolokia Restrictors”, the Jolokia agent can use custom restrictors implementing the interface org.jolokia.restrictor.Restrictor. If the bundle property org.jolokia.useRestrictorService is set to true and no restrictor is configured by other means, the agent will use one or more OSGi service which register under the name org.jolokia.restrictor.Restrictor. If no such service is available, access to the agent is always denied. If one such restrictor service is available, the access decision is delegated to this service. When more than one restrictor service is available, access is ony granted if all of them individually grant access. A sample restrictor service as a maven project can be found in the Jolokia source at agent/osgi/restrictor-sample.

3.3. Mule Agent

Jolokia's Mule agent uses Mule's own agent interface for plugging into the ESB running in standalone mode.

The agent needs to be included into the Mule configuration as shown in the following example, which is the way how to configure the agent for Mule 3:

<mule xmlns="http://www.mulesoft.org/schema/mule/core"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:management="http://www.mulesoft.org/schema/mule/management"
    xmlns:spring="http://www.springframework.org/schema/beans" 
    xsi:schemaLocation="
       http://www.mulesoft.org/schema/mule/core 
             http://www.mulesoft.org/schema/mule/core/3.1/mule.xsd
       http://www.springframework.org/schema/beans 
             http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 
       http://www.mulesoft.org/schema/mule/management 
             http://www.mulesoft.org/schema/mule/management/3.1/mule-management.xsd">

   <!-- .... -->
   <custom-agent name="jolokia-agent" class="org.jolokia.mule.JolokiaMuleAgent">
      <spring:property name="port" value="8899"/>
   </custom-agent>
   <management:jmx-server/>
</mule>

For Mule 2, the configuration is slightly different since the <custom-agent> is contained in the management namespace for Mule 2 (<management:custom-agent>)

This agent knows about the following configuration parameters

Table 3.5. Mule agent configuration options

Parameter Description Example
host Hostaddress to which the HTTP server should bind to. InetAddress.getLocalHost()
port Port the HTTP server should listen to. 8888
user Use to authenticate against. This switches on security and requires a client to provide a user and password.
password Password to check against when security is switched on.
debug Debugging state after startup. Can be changed via the Section 7.1, “Configuration MBean” during runtime. false
historyMaxEntries Entries to keep in the history. Can be changed at runtime via the Section 7.1, “Configuration MBean”. 10
debugMaxEntries Maximum number of entries to keep in the local debug history (if enabled). Can be changed via the Section 7.1, “Configuration MBean” at runtime. 100
maxDepth Maximum depth when traversing bean properties. If set to 0, depth checking is disabled 5
maxCollectionSize Maximum size of collections returned when serializing to JSON. When set to 0, collections are never truncated. 0
maxObjects Maximum number of objects which are traversed when serializing a single response. Use this as an airbag to avoid boosting your memory and network traffic. Nevertheless, when set to 0 no limit is imposed. 10000
canonicalNaming This option specifies in which order the key-value properties within ObjectNames as returned by list or search are returned. By default this is the so called 'canonical order' in which the keys are sorted alphabetically. If this option is set to false, then the natural order is used, i.e. the object name as it was registered. This option can be overridden with a query parameter of the same name. true
includeStackTrace Whether to include a stacktrace of an exception in case of an error. By default it it set to true in which case the stacktrace is always included. If set to false, no stacktrace is included. If the value is runtime a stacktrace is only included for RuntimeExceptions. This global option can be overridden with a query parameter. true
serializeException When this parameter is set to true, then an exception thrown will be serialized as JSON and included in the response under the key error_value. No stactrace infornmation will be included, though. This global option can be overridden by a query parameter of the same name. false

The context under which the agent is reachable is fixed to /jolokia. As an alternative to this Mule agent, the Section 3.4, “JVM Agent” can be used for Mule, too. This agent also knows about SSL encryption and authentication.

3.4. JVM Agent

The JVM agent is right agent when it comes to instrument an arbitrary Java application which is not covered by the other agents. This agent can be started by any Java program by providing certain startup options to the JVM. Or it can be dynamically attached (and detached) to an already running Java process. This universal agent uses the JVM agent API and is available for every Sun/Oracle JVM 1.6 and later.

3.4.1. Jolokia as JVM Agent

The JVM agent uses the JVM Agent interface for linking into any JVM. Under the hood it uses an HTTP-Server, which is available on every Oracle/Sun JVM from verison 1.6 upwards.

3.4.1.1. Installation

This agent gets installed by providing a single startup option -javaagent when starting the Java process.

java -javaagent:agent.jar=port=7777,host=localhost

agent.jar is the filename of the Jolokia JVM agent. Options can be appended as a comma separated list. The available options are the same as described in Table 3.1, “Servlet init parameters” plus the one described in table Table 3.6, “JVM agent configuration options”. If an options contains a comma, an equal sign or a backslash, it must be escaped with a backslash.

Table 3.6. JVM agent configuration options

Parameter Description Example
agentContext Context under which the agent is deployed. The full URL will be protocol://host:port/agentContext. The default context is /jolokia. /j4p
agentId A unique ID for this agent. By default a unique id is calculated. If provided it should be ensured that this id is unique among all agent reachable via multicast requests used by the discovery mechanism. It is recommended not to set this value. my-unique-agent-id
agentDecription An optional description which can be used for clients to present a humand readable label for this agent. Intranet Timebooking Server
host Hostaddress to which the HTTP server should bind to. If "*" or "0.0.0.0" is given, the servers binds to every network interface. localhost
port Port the HTTP server should listen to. If set to 0, then an arbitrary free port will be selected. 8778
user User to be used for authentication (along with a password)
password Password used for authentication (user is then required, too)
realm Sets the security realm to use. If the authMode is set to jaas this is also used as value for the security domain. E.g. for Karaf 3 and later, this realm should be karaf since all JMX MBeans are guarded by this security domain. jolokia
authMode Can be either basic (the default) or jaas. If jaas is used, the user and password given in the Authorization: header are used for loging in via JAAS and, if successful, the return subject is used for all Jolokia operation. This has only an effect, if user is set. basic
authenticatorClass Fully qualified name of an authenticator class. Class must be on classpath and must extend com.sun.net.httpserver.Authenticator. Class can declare a constructor that takes one argument of a type org.jolokia.config.Configuration in which case Jolokia runtime configuration will be passed (useful in cases where authenticator requires additional configuration). If no such constructor is found, default (no-arg) constructor will be use to create an instance.
protocol HTTP protocol to use. Should be either http or https. For the SSL stack there are various additional configuration options. http
backlog Size of request backlog before requests get discarded. 10
executor Threading model of the HTTP server:
fixed

Thread pool with a fixed number of threads (see also threadNr)

cached

Cached thread pool which creates threads on demand

single

A single thread only

single
threadNr Number of threads to be used when the fixed execution model is chosen. 5
keystore Path to the SSL keystore to use (https only)
keystorePassword Keystore password (https only)
useSslClientAuthentication Whether client certificates should be used for authentication (https only). (true or false). false
secureSocketProtocol Secure protocol that will be used for establishing HTTPS connection (https only) TLS
keyStoreType SSL keystore type to use (https only) JKS
keyManagerAlgorithm Key manager algorithm (https only) SunX509
trustManagerAlgorithm Trust manager algorithm (https only) SunX509
bootAmx If set to true and if the agent is attached to a Glassfish server, then during startup the AMX subsystem is booted so that Glassfish specific MBeans are available. Otherwise, if set to false the AMX system is not booted. true
config Path to a properties file from where the configuration options should be read. Such a property file can contain the configuration options as described here as key value pairs (except for the config property of course :)
discoveryEnabled Is set to fakse then this agent will not listen for multicast request (multicastgroup 239.192.48.84, port 24884). By default this option is enabled Default: true
discoveryAgentUrl Sets the URL to respond for multicast discovery requests. If given, discoveryEnabled is set implicetly to true. Within the value you can use the placeholders ${host} and ${ip} which gets replaced by the autodetected local host name/address. Also with ${env:ENV_VAR} and ${sys:property} envirnoment and system properties can be referenced, respectively. http://10.9.11.87:8778/jolokia

Upon sucessful startup the agent will print out a success message with the full URL which can be used by clients for contacting the agent.

3.4.2. Attaching a Jolokia agent on the fly

A Jolokia agent can be attached to any running Java process as long as the user has sufficient access privileges for accessing the process. This agent uses the Java attach API for dynamically attaching and detaching to and from the process. It works similar to JConsole connecting to a local process. The Jolokia advantage is, that after the start of the agent, it can be reached over the network.

The JAR containing the JVM agent also contains a client application which can be reached via the -jar option. Call it with --help to get a short usage information:

$ java -jar jolokia-jvm-1.2.0-agent.jar --help

Jolokia Agent Launcher
======================

Usage: java -jar jolokia-jvm-1.2.0-agent.jar [options] <command> <pid/regexp>

where <command> is one of
    start     -- Start a Jolokia agent for the process specified
    stop      -- Stop a Jolokia agent for the process specified
    status    -- Show status of an (potentially) attached agent
    toggle    -- Toggle between start/stop (default when no command is given)
    list      -- List all attachable Java processes (default when no argument is given at all)

[options] are used for providing runtime information for attaching the agent:

    --host <host>                  Hostname or IP address to which to bind on
                                   (default: InetAddress.getLocalHost())
    --port <port>                  Port to listen on (default: 8778)
    --agentContext <context>       HTTP Context under which the agent is reachable (default: /jolokia)
    --agentId <agent-id>           VM unique identifier used by this agent (default: autogenerated)
    --agentDescription <desc>      Agent description
    --user <user>                  User used for Basic-Authentication
    --password <password>          Password used for Basic-Authentication
    --quiet                        No output. "status" will exit with code 0 if the agent is running, 
                                   1 otherwise
    --verbose                      Verbose output
    --executor <executor>          Executor policy for HTTP Threads to use (default: single)
                                    "fixed"  -- Thread pool with a fixed number of threads (default: 5)
                                    "cached" -- Cached Thread Pool, creates threads on demand
                                    "single" -- Single Thread
    --threadNr <nr threads>        Number of fixed threads if "fixed" is used as executor
    --backlog <backlog>            How many request to keep in the backlog (default: 10)
    --protocol <http|https>        Protocol which must be either "http" or "https" (default: http)
    --keystore <keystore>          Path to keystore (https only)
    --keystorePassword <pwd>       Password to the keystore (https only)
    --useSslClientAuthentication   Use client certificate authentication (https only)
    --secureSocketProtocol <name>  Secure protocol (https only, default: TLS)
    --keyStoreType <name>          Keystore type (https only, default: JKS)
    --keyManagerAlgorithm <name>   Key manager algorithm (https only, default: SunX509)
    --trustManagerAlgorithm <name> Trust manager algorithm (https only, default: SunX509)
    --discoveryEnabled <t|f>       Enable/Disable discovery multicast responses (default: true)
    --discoveryAgentUrl <url>      The URL to use for answering discovery requests. Will be autodetected 
                                   if not given.
    --debug                        Switch on agent debugging
    --debugMaxEntries <nr>         Number of debug entries to keep in memory which can be fetched from the 
                                   Jolokia MBean
    --maxDepth <depth>             Maximum number of levels for serialization of beans (default: null)
    --maxCollectionSize <size>     Maximum number of element in collections to keep when serializing the 
                                   response (default: null)
    --maxObjects <nr>              Maximum number of objects to consider for serialization 
                                   (default: maxObjects)
    --policyLocation <url>         Location of a Jolokia policy file
    --mbeanQualifier <qualifier>   Qualifier to use when registering Jolokia internal MBeans
    --canonicalNaming <t|f>        whether to use canonicalName for ObjectNames in 'list' or 'search' 
                                   (default: true)
    --includeStackTrace <t|f>      whether to include StackTraces for error messages (default: true)
    --serializeException <t|f>     whether to add a serialized version of the exception in the Jolokia 
                                   response (default: false)
    --config <configfile>          Path to a property file from where to read the configuration
    --help                         This help documentation
    --version                      Version of this agent

<pid/regexp> can be either a numeric process id or a regular expression. A regular expression is matched
against the processes' names (ignoring case) and must be specific enough to select exactly one process.

If no <command> is given but only a <pid> the state of the Agent will be toggled
between "start" and "stop"

If neither <command> nor <pid> is given, a list of Java processes along with their IDs
is printed

There are several possible reasons, why attaching to a process can fail:
   * The UID of this launcher must be the very *same*as the process to attach too. It not sufficient 
     to be root.
   * The JVM must have HotSpot enabled and be a JVM 1.6 or larger.
   * It must be a Java process ;-)

For more documentation please visit www.jolokia.org

Every option described in Table 3.6, “JVM agent configuration options” is reflected by a command line option for the launcher. Additionally, the option --quiet can be used to keep the launcher silent and --verbose for adding some extra logging.

The launcher knows various operational modes, which needs to be provided as a non-option argument and possibly require an extra argument.

start

Use this to attach an agent to an already running, local Java process. The additional argument is either the process id of the Java process to attach to or a regular expression which is matched against the Java processes names. In the later case, exactly one process must match, otherwise an exception is raised. The command will return with an return code of 0 if an agent has been started. If the agent is already running, nothing happens and the launcher returns with 1. The URL of the Agent will be printed to standard out on an extra line except when the --quiet option is used.

stop

Command for stopping an running and dynamically attached agent. The required argument is the Java process id or an regular expression as described for the start command. If the agent could be stopped, the launcher exits with 0, it exits with 1 if there was no agent running.

toggle

Starts or stops an dynamically attached agent, dependening on its current state. The Java process ID is required as an additional argument. If an agent is running, toggle will stop it (and vice versa). The launcer returns with an exit code of 0 except when the operation fails. When the agent is started, the full agent's URL is printed to standard out. toggle is the default command when only a numeric process id is given as argument or a regular expression which not the same as a known command.

status

Command for showing the current agent status for a given process. The process id or a regular expresssion is required. The launcer will return with 0 when the agent is running, otherwise with 1.

list

List all local Java processes in a table with the process id and the description as columns. This is the default command if no non-option argument is given at all. list returns with 0 upon normal operation and with 1 otherwise.

The launcher is especially suited for one-shot, local queries. For example, a simple shell script for printing out the memory usage of a local Java process, including (temporarily) attaching an Jolokia agent looks simply like in the following example. With a complete client library like Jmx4Perl even more one shot scripts are possible[6].

#!/bin/sh

url=`java -jar agent.jar start $1 | tail -1`

memory_url="${url}read/java.lang:type=Memory/HeapMemoryUsage"
used=`wget -q -O - "${memory_url}/used" | sed 's/^.*"value":\([0-9]*\).*$/\1/'`
max=`wget -q -O - "${memory_url}/max" | sed 's/^.*"value":\([0-9]*\).*$/\1/'`
usage=$((${used}*100/${max}))
echo "Memory Usage: $usage %"

java -jar agent.jar --quiet stop $1


[1] Although the proxy mode is available for all four agents, you are normally free to setup the proxy environment. The recommendation here is the war-agent for which very lightweight servlet container exists. Tomcat or Jetty are both a perfect choice for a Jolokia proxy server.

[2] Of course, there is much more to OSGi, a platform and programing model which I really like. This is my personal pet agent, so to speak ;-).

[4] You could even instrument a JEE application server this way, however this is not recommended.

[5] Replace org.jolokia.osgi.http.AgentServlet with org.jolokia.http.AgentServlet to use the servlet in a non-OSGi environment.

[6] And in fact, some support for launching this dynamic agent is planned for a forthcoming release of jmx4perl.