Improvements to the Jetty server documentation.

Added section on JMX.

Signed-off-by: Simone Bordet <simone.bordet@gmail.com>
This commit is contained in:
Simone Bordet 2020-05-03 21:19:10 +02:00
parent f154151016
commit 267039f3f5
12 changed files with 855 additions and 31 deletions

View File

@ -33,6 +33,26 @@
<groupId>org.eclipse.jetty.toolchain</groupId> <groupId>org.eclipse.jetty.toolchain</groupId>
<artifactId>jetty-servlet-api</artifactId> <artifactId>jetty-servlet-api</artifactId>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-alpn-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jmx</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-rewrite</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId> <artifactId>jetty-server</artifactId>
@ -48,36 +68,21 @@
<artifactId>jetty-servlets</artifactId> <artifactId>jetty-servlets</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-rewrite</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty</groupId> <groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-webapp</artifactId> <artifactId>jetty-webapp</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-alpn-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>http2-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-client</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty.fcgi</groupId> <groupId>org.eclipse.jetty.fcgi</groupId>
<artifactId>fcgi-client</artifactId> <artifactId>fcgi-client</artifactId>
<version>${project.version}</version> <version>${project.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.eclipse.jetty.http2</groupId>
<artifactId>http2-server</artifactId>
<version>${project.version}</version>
</dependency>
<dependency> <dependency>
<groupId>org.eclipse.jetty.http2</groupId> <groupId>org.eclipse.jetty.http2</groupId>
<artifactId>http2-http-client-transport</artifactId> <artifactId>http2-http-client-transport</artifactId>

View File

@ -31,8 +31,9 @@ The end result is that an application based on the Jetty libraries is a _tree_ o
In server application the root of the component tree is a `Server` instance, while in client applications the root of the component tree is an `HttpClient` instance. In server application the root of the component tree is a `Server` instance, while in client applications the root of the component tree is an `HttpClient` instance.
Having all the Jetty components in a tree is beneficial in a number of use cases. Having all the Jetty components in a tree is beneficial in a number of use cases.
It makes possible to register the components in the tree as JMX MBeans (TODO: xref the JMX section) so that a JMX console can look at the internal state of the components. It makes possible to register the components in the tree as xref:eg-arch-jmx[JMX MBeans] so that a JMX console can look at the internal state of the components.
It also makes possible to dump the component tree (and therefore each component's internal state) to a log file or to the console for troubleshooting purposes (TODO: xref troubleshooting section). It also makes possible to xref:eg-troubleshooting-component-dump[dump the component tree] (and therefore each component's internal state) to a log file or to the console for xref:eg-troubleshooting[troubleshooting purposes].
// TODO: add a section on Dumpable?
[[eg-arch-bean-lifecycle]] [[eg-arch-bean-lifecycle]]
==== Jetty Component Lifecycle ==== Jetty Component Lifecycle
@ -40,7 +41,7 @@ It also makes possible to dump the component tree (and therefore each component'
Jetty components typically have a life cycle: they can be started and stopped. Jetty components typically have a life cycle: they can be started and stopped.
The Jetty components that have a life cycle implement the `org.eclipse.jetty.util.component.LifeCycle` interface. The Jetty components that have a life cycle implement the `org.eclipse.jetty.util.component.LifeCycle` interface.
Jetty components that contain other components extend the `org.eclipse.jetty.util.component.ContainerLifeCycle` class. Jetty components that contain other components implement the `org.eclipse.jetty.util.component.Container` interface and typically extend the `org.eclipse.jetty.util.component.ContainerLifeCycle` class.
`ContainerLifeCycle` can contain these type of components, also called __bean__s: `ContainerLifeCycle` can contain these type of components, also called __bean__s:
* _managed_ beans, `LifeCycle` instances whose life cycle is tied to the life cycle of their container * _managed_ beans, `LifeCycle` instances whose life cycle is tied to the life cycle of their container
@ -94,8 +95,72 @@ include::{doc_code}/embedded/ComponentDocs.java[tags=restart]
`Service` can be stopped independently of `Root`, and re-started. `Service` can be stopped independently of `Root`, and re-started.
Starting and stopping a non-root component does not alter the structure of the component tree, just the state of the subtree starting from the component that has been stopped and re-started. Starting and stopping a non-root component does not alter the structure of the component tree, just the state of the subtree starting from the component that has been stopped and re-started.
`Container` provides an API to find beans in the component tree:
[source,java,indent=0]
----
include::{doc_code}/embedded/ComponentDocs.java[tags=getBeans]
----
You can add your own beans to the component tree at application startup time, and later find them from your application code to access their services.
[TIP]
====
The component tree should be used for long-lived or medium-lived components such as thread pools, web application contexts, etc.
It is not recommended adding to, and removing from, the component tree short-lived objects such as HTTP requests or TCP connections, for performance reasons.
If you need component tree features such as automatic xref:eg-arch-jmx[export to JMX] or xref:eg-troubleshooting-component-dump[dump capabilities] for short-lived objects, consider having a long-lived container in the component tree instead.
You can make the long-lived container efficient at adding/removing the short-lived components using a data structure that is not part of the component tree, and make the long-lived container handle the JMX and dump features for the short-lived components.
====
[[eg-arch-bean-listener]] [[eg-arch-bean-listener]]
==== Jetty Component Listeners ==== Jetty Component Listeners
// TODO: LifeCycle.Listener A component that extends `AbstractLifeCycle` inherits the possibility to add/remove event _listeners_ for various events emitted by components.
// TODO: Container.Listener + InheritedListener
A component that implements `java.util.EventListener` that is added to a `ContainerLifeCycle` is also registered as an event listener.
The following sections describe in details the various listeners available in the Jetty component architecture.
[[eg-arch-bean-listener-lifecycle]]
===== LifeCycle.Listener
A `LifeCycle.Listener` emits events for life cycle events such as starting, stopping and failures:
[source,java,indent=0]
----
include::{doc_code}/embedded/ComponentDocs.java[tags=lifecycleListener]
----
For example, a life cycle listener attached to a `Server` instance could be used to create (for the _started_ event) and delete (for the _stopped_ event) a file containing the process ID of the JVM that runs the `Server`.
[[eg-arch-bean-listener-container]]
===== Container.Listener
A component that implements `Container` is a container for other components and `ContainerLifeCycle` is the typical implementation.
A `Container` emits events when a component (also called _bean_) is added to or removed from the container:
[source,java,indent=0]
----
include::{doc_code}/embedded/ComponentDocs.java[tags=containerListener]
----
A `Container.Listener` added as a bean will also be registered as a listener:
[source,java,indent=0]
----
include::{doc_code}/embedded/ComponentDocs.java[tags=containerSiblings]
----
[[eg-arch-bean-listener-inherited]]
===== Container.InheritedListener
A `Container.InheritedListener` is a listener that will be added to all descendants that are also ``Container``s.
Listeners of this type may be added to the component tree root only, but will be notified of every descendant component that is added to or removed from the component tree (not only first level children).
The primary use of `Container.InheritedListener` within the Jetty Libraries is `MBeanContainer` from the xref:eg-arch-jmx[Jetty JMX support].
`MBeanContainer` listens for every component added to the tree, converts it to an MBean and registers it to the MBeanServer; for every component removed from the tree, it unregisters the corresponding MBean from the MBeanServer.

View File

@ -0,0 +1,306 @@
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
[[eg-arch-jmx]]
== Jetty JMX Support
The Java Management Extensions (JMX) APIs are standard API for managing and monitoring resources such as applications, devices, services, and the Java Virtual Machine itself.
The JMX API includes remote access, so a remote management console such as link:https://openjdk.java.net/projects/jmc/[Java Mission Control] can interact with a running application for these purposes.
Jetty architecture is based on xref:eg-arch-bean[components] organized in a tree. Every time a component is added to or removed from the component tree, an event is emitted, and xref:eg-arch-bean-listener-container[Container.Listener] implementations can listen to those events and perform additional actions.
`org.eclipse.jetty.jmx.MBeanContainer` listens to those events and registers/unregisters the Jetty components as MBeans into the platform MBeanServer.
The Jetty components are annotated with xref:eg-arch-jmx-annotation[Jetty JMX annotations] so that they can provide specific JMX metadata such as attributes and operations that should be exposed via JMX.
Therefore, when a component is added to the component tree, `MBeanContainer` is notified, it creates the MBean from the component POJO and registers it to the `MBeanServer`.
Similarly, when a component is removed from the tree, `MBeanContainer` is notified, and unregisters the MBean from the `MBeanServer`.
The Maven coordinates for the Jetty JMX support are:
[source,xml,subs=normal]
----
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-jmx</artifactId>
<version>{version}</version>
</dependency>
----
=== Enabling JMX Support
Enabling JMX support is always recommended because it provides valuable information about the system, both for monitoring purposes and for troubleshooting purposes in case of problems.
To enable JMX support on the server:
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=server]
----
Similarly on the client:
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=client]
----
[NOTE]
====
The MBeans exported to the platform MBeanServer can only be accessed locally (from the same machine), not from remote machines.
This means that this configuration is enough for development, where you have easy access (with graphical user interface) to the machine where Jetty runs, but it is typically not enough when the machine where Jetty runs is remote, or only accessible via SSH or otherwise without graphical user interface support.
In these cases, you have to enable xref:eg-arch-jmx-remote[JMX Remote Access].
====
// TODO: add a section about how to expose logging once #4830 is fixed.
[[eg-arch-jmx-remote]]
=== Enabling JMX Remote Access
There are two ways of enabling remote connectivity so that JMC can connect to the remote JVM to visualize MBeans.
* Use the `com.sun.management.jmxremote` system property on the command line.
Unfortunately, this solution does not work well with firewalls and is not flexible.
* Use Jetty's `ConnectorServer` class.
`org.eclipse.jetty.jmx.ConnectorServer` will use by default RMI to allow connection from remote clients, and it is a wrapper around the standard JDK class `JMXConnectorServer`, which is the class that provides remote access to JMX clients.
Connecting to the remote JVM is a two step process:
* First, the client will connect to the RMI _registry_ to download the RMI stub for the `JMXConnectorServer`; this RMI stub contains the IP address and port to connect to the RMI server, i.e. the remote `JMXConnectorServer`.
* Second, the client uses the RMI stub to connect to the RMI _server_ (i.e. the remote `JMXConnectorServer`) typically on an address and port that may be different from the RMI registry address and port.
The host and port configuration for the RMI registry and the RMI server is specified by a `JMXServiceURL`.
The string format of an RMI `JMXServiceURL` is:
[source,screen]
----
service:jmx:rmi://<rmi_server_host>:<rmi_server_port>/jndi/rmi://<rmi_registry_host>:<rmi_registry_port>/jmxrmi
----
Default values are:
[source,screen]
----
rmi_server_host = localhost
rmi_server_port = 1099
rmi_registry_host = localhost
rmi_registry_port = 1099
----
With the default configuration, only clients that are local to the server machine can connect to the RMI registry and RMI server - this is done for security reasons.
With this configuration it would still be possible to access the MBeans from remote using a xref:eg-arch-jmx-remote-ssh-tunnel[SSH tunnel].
By specifying an appropriate `JMXServiceURL`, you can fine tune the network interfaces the RMI registry and the RMI server bind to, and the ports that the RMI registry and the RMI server listen to.
The RMI server and RMI registry hosts and ports can be the same (as in the default configuration) because RMI is able to multiplex traffic arriving to a port to multiple RMI objects.
If you need to allow JMX remote access through a firewall, you must open both the RMI registry and the RMI server ports.
`JMXServiceURL` common examples:
[source,screen]
----
service:jmx:rmi:///jndi/rmi:///jmxrmi
rmi_server_host = local host address
rmi_server_port = randomly chosen
rmi_registry_host = local host address
rmi_registry_port = 1099
service:jmx:rmi://0.0.0.0:1099/jndi/rmi://0.0.0.0:1099/jmxrmi
rmi_server_host = any address
rmi_server_port = 1099
rmi_registry_host = any address
rmi_registry_port = 1099
service:jmx:rmi://localhost:1100/jndi/rmi://localhost:1099/jmxrmi
rmi_server_host = loopback address
rmi_server_port = 1100
rmi_registry_host = loopback address
rmi_registry_port = 1099
----
[NOTE]
====
When `ConnectorServer` is started, its RMI stub is exported to the RMI registry.
The RMI stub contains the IP address and port to connect to the RMI object, but the IP address is typically the machine host name, not the host specified in the `JMXServiceURL`.
To control the IP address stored in the RMI stub you need to set the system property `java.rmi.server.hostname` with the desired value.
This is especially important when binding the RMI server host to the loopback address for security reasons. See also xref:eg-arch-jmx-remote-ssh-tunnel[JMX Remote Access via SSH Tunnel.]
====
To allow JMX remote access, create and configure a `ConnectorServer`:
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=remote]
----
[[eg-arch-jmx-remote-authorization]]
==== JMX Remote Access Authorization
The standard `JMXConnectorServer` provides several options to authorize access, for example via JAAS or via configuration files.
For a complete guide to controlling authentication and authorization in JMX, see https://docs.oracle.com/en/java/javase/11/management/[the official JMX documentation].
In the sections below we detail one way to setup JMX authentication and authorization, using configuration files for users, passwords and roles:
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=remoteAuthorization]
----
The `users.access` file format is defined in the `$JAVA_HOME/conf/management/jmxremote.access` file.
A simplified version is the following:
.users.access
[source,screen]
----
user1 readonly
user2 readwrite
----
The `users.password` file format is defined in the `$JAVA_HOME/conf/management/jmxremote.password.template` file.
A simplified version is the following:
.users.password
[source,screen]
----
user1 password1
user2 password2
----
CAUTION: The `users.access` and `users.password` files are not standard `*.properties` files -- the user must be separated from the role or password by a space character.
===== Securing JMX Remote Access with TLS
The JMX communication via RMI happens by default in clear-text.
It is possible to configure the `ConnectorServer` with a `SslContextFactory` so that the JMX communication via RMI is encrypted:
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=tlsRemote]
----
It is possible to use the same `SslContextFactory.Server` used to configure the Jetty `ServerConnector` that supports TLS also for the JMX communication via RMI.
The keystore must contain a valid certificate signed by a Certification Authority.
The RMI mechanic is the usual one: the RMI client (typically a monitoring console) will connect first to the RMI registry (using TLS), download the RMI server stub that contains the address and port of the RMI server to connect to, then connect to the RMI server (using TLS).
This also mean that if the RMI registry and the RMI server are on different hosts, the RMI client must have available the cryptographic material to validate both hosts.
Having certificates signed by a Certification Authority simplifies by a lot the configuration needed to get the JMX communication over TLS working properly.
If that is not the case (for example the certificate is self-signed), then you need to specify the required system properties that allow RMI (especially when acting as an RMI client) to retrieve the cryptographic material necessary to establish the TLS connection.
For example, trying to connect using the JDK standard `JMXConnector` with both the RMI server and the RMI registry via TLS to `domain.com` with a self-signed certificate:
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=tlsJMXConnector]
----
Similarly, to launch JMC:
[source,screen]
----
$ jmc -vmargs -Djavax.net.ssl.trustStore=/path/to/trustStore -Djavax.net.ssl.trustStorePassword=secret
----
IMPORTANT: These system properties are required when launching the `ConnectorServer` too, on the server, because it acts as an RMI client with respect to the RMI registry.
[[eg-arch-jmx-remote-ssh-tunnel]]
===== JMX Remote Access with Port Forwarding via SSH Tunnel
You can access JMX MBeans on a remote machine when the RMI ports are not open, for example because of firewall policies, but you have SSH access to the machine using local port forwarding via an SSH tunnel.
In this case you want to configure the `ConnectorServer` with a `JMXServiceURL` that binds the RMI server and the RMI registry to the loopback interface only: `service:jmx:rmi://localhost:1099/jndi/rmi://localhost:1099/jmxrmi`.
Then you setup the local port forwarding with the SSH tunnel:
[source,screen]
----
$ ssh -L 1099:localhost:1099 <user>@<machine_host>
----
Now you can use JConsole or JMC to connect to `localhost:1099` on your local computer.
The traffic will be forwarded to `machine_host` and when there, SSH will forward the traffic to `localhost:1099`, which is exactly where the `ConnectorServer` listens.
When you configure `ConnectorServer` in this way, you must set the system property `-Djava.rmi.server.hostname=localhost`, on the server.
This is required because when the RMI server is exported, its address and port are stored in the RMI stub. You want the address in the RMI stub to be `localhost` so that when the RMI stub is downloaded to the remote client, the RMI communication will go through the SSH tunnel.
[[eg-arch-jmx-annotation]]
=== Jetty JMX Annotations
The Jetty JMX support, and in particular `MBeanContainer`, is notified every time a bean is added to the component tree.
The bean is scanned for Jetty JMX annotations to obtain JMX metadata: the JMX attributes and JMX operations.
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=jmxAnnotation]
----
The JMX metadata and the bean are wrapped by an instance of `org.eclipse.jetty.jmx.ObjectMBean` that exposes the JMX metadata and, upon request from JMX consoles, invokes methods on the bean to get/set attribute values and perform operations.
You can provide a custom subclass of `ObjectMBean` to further customize how the bean is exposed to JMX.
The custom `ObjectMBean` subclass must respect the following naming convention: `<package>.jmx.<class>MBean`.
For example, class `com.acme.Foo` may have a custom `ObjectMBean` subclass named `com.acme.**jmx**.Foo**MBean**`.
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=jmxCustomMBean]
----
The custom `ObjectMBean` subclass is also scanned for Jetty JMX annotations and overrides the JMX metadata obtained by scanning the bean class.
This allows to annotate only the custom `ObjectMBean` subclass and keep the bean class free of the Jetty JMX annotations.
[source,java,indent=0]
----
include::{doc_code}/embedded/JMXDocs.java[tags=jmxCustomMBeanOverride]
----
The scan for Jetty JMX annotations is performed on the bean class and all the interfaces implemented by the bean class, then on the super-class and all the interfaces implemented by the super-class and so on until `java.lang.Object` is reached.
For each type -- class or interface, the corresponding `+*.jmx.*MBean+` is looked up and scanned as well with the same algorithm.
For each type, the scan looks for the class-level annotation `@ManagedObject`.
If it is found, the scan looks for method-level `@ManagedAttribute` and `@ManagedOperation` annotations; otherwise it skips the current type and moves to the next type to scan.
==== @ManagedObject
The `@ManagedObject` annotation is used on a class at the top level to indicate that it should be exposed as an MBean.
It has only one attribute to it which is used as the description of the MBean.
==== @ManagedAttribute
The `@ManagedAttribute` annotation is used to indicate that a given method is exposed as a JMX attribute.
This annotation is placed always on the getter method of a given attribute.
Unless the `readonly` attribute is set to `true` in the annotation, a corresponding setter is looked up following normal naming conventions.
For example if this annotation is on a method called `String getFoo()` then a method called `void setFoo(String)` would be looked up, and if found wired as the setter for the JMX attribute.
==== @ManagedOperation
The `@ManagedOperation` annotation is used to indicate that a given method is exposed as a JMX operation.
A JMX operation has an _impact_ that can be `INFO` if the operation returns a value without modifying the object, `ACTION` if the operation does not return a value but modifies the object, and "ACTION_INFO" if the operation both returns a value and modifies the object.
If the _impact_ is not specified, it has the default value of `UNKNOWN`.
==== @Name
The `@Name` annotation is used to assign a name and description to parameters in method signatures so that when rendered by JMX consoles it is clearer what the parameter meaning is.

View File

@ -21,5 +21,6 @@
== Jetty Architecture == Jetty Architecture
include::arch-bean.adoc[] include::arch-bean.adoc[]
include::arch-jmx.adoc[]
include::arch-listener.adoc[] include::arch-listener.adoc[]
include::arch-io.adoc[] include::arch-io.adoc[]

View File

@ -245,8 +245,7 @@ Server
* Number of responses grouped by HTTP code (i.e. how many `2xx` responses, how many `3xx` responses, etc.) * Number of responses grouped by HTTP code (i.e. how many `2xx` responses, how many `3xx` responses, etc.)
* Total response content bytes * Total response content bytes
Server applications can read these values and use them internally, or expose them via some service, or export them via JMX. Server applications can read these values and use them internally, or expose them via some service, or xref:eg-arch-jmx[export them to JMX].
// TODO: xref to the JMX section.
`StatisticsHandler` can be configured at the server level or at the context level. `StatisticsHandler` can be configured at the server level or at the context level.

View File

@ -20,6 +20,13 @@
[[eg-troubleshooting]] [[eg-troubleshooting]]
== Troubleshooting Jetty == Troubleshooting Jetty
TODO: introduction
// TODO: explain the process to troubleshoot Jetty:
// TODO: #1 enable JMX
// TODO: #2 enable GC logs
// TODO: #3 take jvm/component dumps
// TODO: #4 enable debug logging if you can
[[eg-troubleshooting-logging]] [[eg-troubleshooting-logging]]
=== Logging === Logging
@ -66,6 +73,24 @@ If you want to enable DEBUG logging but only for the HTTP/2 classes:
java -Dorg.eclipse.jetty.http2.LEVEL=DEBUG --class-path ... java -Dorg.eclipse.jetty.http2.LEVEL=DEBUG --class-path ...
---- ----
[[eg-troubleshooting-thread-dump]]
=== JVM Thread Dump
TODO
[[eg-troubleshooting-component-dump]]
=== Jetty Component Tree Dump
Jetty components are organized in a xref:eg-arch-bean[component tree].
At the root of the component tree there is typically a `ContainerLifeCycle` instance -- typically a `Server` instance on the server and an `HttpClient` instance on the client.
`ContainerLifeCycle` has built-in _dump_ APIs that can be invoked either directly or xref:eg-arch-jmx[via JMX].
// TODO: images from JMC?
// TODO: Command line JMX will be in JMX section.
TIP: You can get more details from a Jetty's `QueuedThreadPool` dump by enabling detailed dumps via `queuedThreadPool.setDetailedDump(true)`.
[[eg-troubleshooting-debugging]] [[eg-troubleshooting-debugging]]
=== Debugging === Debugging

View File

@ -18,11 +18,19 @@
package embedded; package embedded;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.component.AbstractLifeCycle; import org.eclipse.jetty.util.component.AbstractLifeCycle;
import org.eclipse.jetty.util.component.Container;
import org.eclipse.jetty.util.component.ContainerLifeCycle; import org.eclipse.jetty.util.component.ContainerLifeCycle;
import org.eclipse.jetty.util.component.LifeCycle;
import static java.lang.System.Logger.Level.INFO;
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class ComponentDocs public class ComponentDocs
@ -140,4 +148,142 @@ public class ComponentDocs
service.start(); service.start();
// end::restart[] // end::restart[]
} }
public void getBeans() throws Exception
{
// tag::getBeans[]
class Root extends ContainerLifeCycle
{
}
class Service extends ContainerLifeCycle
{
private ScheduledExecutorService scheduler;
@Override
protected void doStart() throws Exception
{
scheduler = Executors.newSingleThreadScheduledExecutor();
addBean(scheduler);
super.doStart();
}
@Override
protected void doStop() throws Exception
{
super.doStop();
removeBean(scheduler);
scheduler.shutdown();
}
}
Root root = new Root();
Service service = new Service();
root.addBean(service);
// Start the Root component.
root.start();
// Find all the direct children of root.
Collection<Object> children = root.getBeans();
// children contains only service
// Find all descendants of root that are instance of a particular class.
Collection<ScheduledExecutorService> schedulers = root.getContainedBeans(ScheduledExecutorService.class);
// schedulers contains the service scheduler.
// end::getBeans[]
}
public void lifecycleListener()
{
// tag::lifecycleListener[]
Server server = new Server();
// Add an event listener of type LifeCycle.Listener.
server.addEventListener(new LifeCycle.Listener()
{
@Override
public void lifeCycleStarted(LifeCycle lifeCycle)
{
System.getLogger("server").log(INFO, "Server {0} has been started", lifeCycle);
}
@Override
public void lifeCycleFailure(LifeCycle lifeCycle, Throwable failure)
{
System.getLogger("server").log(INFO, "Server {0} failed to start", lifeCycle, failure);
}
@Override
public void lifeCycleStopped(LifeCycle lifeCycle)
{
System.getLogger("server").log(INFO, "Server {0} has been stopped", lifeCycle);
}
});
// end::lifecycleListener[]
}
public void containerListener()
{
// tag::containerListener[]
Server server = new Server();
// Add an event listener of type LifeCycle.Listener.
server.addEventListener(new Container.Listener()
{
@Override
public void beanAdded(Container parent, Object child)
{
System.getLogger("server").log(INFO, "Added bean {1} to {0}", parent, child);
}
@Override
public void beanRemoved(Container parent, Object child)
{
System.getLogger("server").log(INFO, "Removed bean {1} from {0}", parent, child);
}
});
// end::containerListener[]
}
public void containerSiblings()
{
// tag::containerSiblings[]
class Parent extends ContainerLifeCycle
{
}
class Child
{
}
// The older child takes care of its siblings.
class OlderChild extends Child implements Container.Listener
{
private Set<Object> siblings = new HashSet<>();
@Override
public void beanAdded(Container parent, Object child)
{
siblings.add(child);
}
@Override
public void beanRemoved(Container parent, Object child)
{
siblings.remove(child);
}
}
Parent parent = new Parent();
Child older = new OlderChild();
// The older child is a child bean _and_ a listener.
parent.addBean(older);
Child younger = new Child();
// Adding a younger child will notify the older child.
parent.addBean(younger);
// end::containerSiblings[]
}
} }

View File

@ -0,0 +1,276 @@
//
// ========================================================================
// Copyright (c) 1995-2020 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under
// the terms of the Eclipse Public License 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0
//
// This Source Code may also be made available under the following
// Secondary Licenses when the conditions for such availability set
// forth in the Eclipse Public License, v. 2.0 are satisfied:
// the Apache License v2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//
package embedded;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.rmi.ssl.SslRMIClientSocketFactory;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.jmx.ConnectorServer;
import org.eclipse.jetty.jmx.MBeanContainer;
import org.eclipse.jetty.jmx.ObjectMBean;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.annotation.ManagedAttribute;
import org.eclipse.jetty.util.annotation.ManagedObject;
import org.eclipse.jetty.util.annotation.ManagedOperation;
import org.eclipse.jetty.util.annotation.Name;
import org.eclipse.jetty.util.ssl.SslContextFactory;
@SuppressWarnings("unused")
public class JMXDocs
{
public void server()
{
// tag::server[]
Server server = new Server();
// Create an MBeanContainer with the platform MBeanServer.
MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
// Add MBeanContainer to the root component.
server.addBean(mbeanContainer);
// end::server[]
}
public void client()
{
// tag::client[]
HttpClient httpClient = new HttpClient();
// Create an MBeanContainer with the platform MBeanServer.
MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
// Add MBeanContainer to the root component.
httpClient.addBean(mbeanContainer);
// end::client[]
}
public void remote() throws Exception
{
// tag::remote[]
Server server = new Server();
// Setup Jetty JMX.
MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbeanContainer);
// Setup ConnectorServer.
// Bind the RMI server to the wildcard address and port 1999.
// Bind the RMI registry to the wildcard address and port 1099.
JMXServiceURL jmxURL = new JMXServiceURL("rmi", null, 1999, "/jndi/rmi:///jmxrmi");
ConnectorServer jmxServer = new ConnectorServer(jmxURL, "org.eclipse.jetty.jmx:name=rmiconnectorserver");
// Add ConnectorServer as a bean, so it is started
// with the Server and also exported as MBean.
server.addBean(jmxServer);
server.start();
// end::remote[]
}
public static void main(String[] args) throws Exception
{
new JMXDocs().remote();
}
public void remoteAuthorization() throws Exception
{
// tag::remoteAuthorization[]
Server server = new Server();
// Setup Jetty JMX.
MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbeanContainer);
// Setup ConnectorServer.
JMXServiceURL jmxURL = new JMXServiceURL("rmi", null, 1099, "/jndi/rmi:///jmxrmi");
Map<String, Object> env = new HashMap<>();
env.put("com.sun.management.jmxremote.access.file", "/path/to/users.access");
env.put("com.sun.management.jmxremote.password.file", "/path/to/users.password");
ConnectorServer jmxServer = new ConnectorServer(jmxURL, env, "org.eclipse.jetty.jmx:name=rmiconnectorserver");
server.addBean(jmxServer);
server.start();
// end::remoteAuthorization[]
}
public void tlsRemote() throws Exception
{
// tag::tlsRemote[]
Server server = new Server();
// Setup Jetty JMX.
MBeanContainer mbeanContainer = new MBeanContainer(ManagementFactory.getPlatformMBeanServer());
server.addBean(mbeanContainer);
// Setup SslContextFactory.
SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
sslContextFactory.setKeyStorePath("/path/to/keystore");
sslContextFactory.setKeyStorePassword("secret");
// Setup ConnectorServer with SslContextFactory.
JMXServiceURL jmxURL = new JMXServiceURL("rmi", null, 1099, "/jndi/rmi:///jmxrmi");
ConnectorServer jmxServer = new ConnectorServer(jmxURL, null, "org.eclipse.jetty.jmx:name=rmiconnectorserver", sslContextFactory);
server.addBean(jmxServer);
server.start();
// end::tlsRemote[]
}
public void tlsJMXConnector() throws Exception
{
// tag::tlsJMXConnector[]
// System properties necessary for an RMI client to trust a self-signed certificate.
System.setProperty("javax.net.ssl.trustStore", "/path/to/trustStore");
System.setProperty("javax.net.ssl.trustStorePassword", "secret");
JMXServiceURL jmxURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://domain.com:1100/jmxrmi");
Map<String, Object> clientEnv = new HashMap<>();
// Required to connect to the RMI registry via TLS.
clientEnv.put(ConnectorServer.RMI_REGISTRY_CLIENT_SOCKET_FACTORY_ATTRIBUTE, new SslRMIClientSocketFactory());
try (JMXConnector client = JMXConnectorFactory.connect(jmxURL, clientEnv))
{
Set<ObjectName> names = client.getMBeanServerConnection().queryNames(null, null);
}
// end::tlsJMXConnector[]
}
public void jmxAnnotation() throws Exception
{
// tag::jmxAnnotation[]
// Annotate the class with @ManagedObject and provide a description.
@ManagedObject("Services that provide useful features")
class Services
{
private final Map<String, Object> services = new ConcurrentHashMap<>();
private boolean enabled = true;
// A read-only attribute with description.
@ManagedAttribute(value = "The number of services", readonly = true)
public int getServiceCount()
{
return services.size();
}
// A read-write attribute with description.
// Only the getter is annotated.
@ManagedAttribute(value = "Whether the services are enabled")
public boolean isEnabled()
{
return enabled;
}
// There is no need to annotate the setter.
public void setEnabled(boolean enabled)
{
this.enabled = enabled;
}
// An operation with description and impact.
// The @Name annotation is used to annotate parameters
// for example to display meaningful parameter names.
@ManagedOperation(value = "Retrieves the service with the given name", impact = "INFO")
public Object getService(@Name(value = "serviceName") String n)
{
return services.get(n);
}
}
// end::jmxAnnotation[]
}
public void jmxCustomMBean()
{
// tag::jmxCustomMBean[]
//package com.acme;
@ManagedObject
class Service
{
}
//package com.acme.jmx;
class ServiceMBean extends ObjectMBean
{
ServiceMBean(Object service)
{
super(service);
}
}
// end::jmxCustomMBean[]
}
public void jmxCustomMBeanOverride()
{
// tag::jmxCustomMBeanOverride[]
//package com.acme;
// No Jetty JMX annotations.
class CountService
{
private int count;
public int getCount()
{
return count;
}
public void addCount(int value)
{
count += value;
}
}
//package com.acme.jmx;
@ManagedObject("the count service")
class CountServiceMBean extends ObjectMBean
{
public CountServiceMBean(Object service)
{
super(service);
}
private CountService getCountService()
{
return (CountService)super.getManagedObject();
}
@ManagedAttribute("the current service count")
public int getCount()
{
return getCountService().getCount();
}
@ManagedOperation(value = "adds the given value to the service count", impact = "ACTION")
public void addCount(@Name("count delta") int value)
{
getCountService().addCount(value);
}
}
// end::jmxCustomMBeanOverride[]
}
}

View File

@ -34,6 +34,7 @@ import org.eclipse.jetty.io.SelectorManager;
import org.eclipse.jetty.util.BufferUtil; import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.Callback; import org.eclipse.jetty.util.Callback;
@SuppressWarnings("unused")
public class SelectorManagerDocs public class SelectorManagerDocs
{ {
// tag::connect[] // tag::connect[]

View File

@ -66,7 +66,7 @@ public class ConnectorServer extends AbstractLifeCycle
private JMXServiceURL _jmxURL; private JMXServiceURL _jmxURL;
private final Map<String, Object> _environment; private final Map<String, Object> _environment;
private final String _objectName; private final String _objectName;
private final SslContextFactory _sslContextFactory; private final SslContextFactory.Server _sslContextFactory;
private int _registryPort; private int _registryPort;
private int _rmiPort; private int _rmiPort;
private JMXConnectorServer _connectorServer; private JMXConnectorServer _connectorServer;
@ -98,7 +98,7 @@ public class ConnectorServer extends AbstractLifeCycle
this(svcUrl, environment, name, null); this(svcUrl, environment, name, null);
} }
public ConnectorServer(JMXServiceURL svcUrl, Map<String, ?> environment, String name, SslContextFactory sslContextFactory) public ConnectorServer(JMXServiceURL svcUrl, Map<String, ?> environment, String name, SslContextFactory.Server sslContextFactory)
{ {
this._jmxURL = svcUrl; this._jmxURL = svcUrl;
this._environment = environment == null ? new HashMap<>() : new HashMap<>(environment); this._environment = environment == null ? new HashMap<>() : new HashMap<>(environment);

View File

@ -60,7 +60,7 @@ public class MBeanContainer implements Container.InheritedListener, Dumpable, De
private final MBeanServer _mbeanServer; private final MBeanServer _mbeanServer;
private final boolean _useCacheForOtherClassLoaders; private final boolean _useCacheForOtherClassLoaders;
private final ConcurrentMap<Class, MetaData> _metaData = new ConcurrentHashMap<>(); private final ConcurrentMap<Class<?>, MetaData> _metaData = new ConcurrentHashMap<>();
private final ConcurrentMap<Object, Container> _beans = new ConcurrentHashMap<>(); private final ConcurrentMap<Object, Container> _beans = new ConcurrentHashMap<>();
private final ConcurrentMap<Object, ObjectName> _mbeans = new ConcurrentHashMap<>(); private final ConcurrentMap<Object, ObjectName> _mbeans = new ConcurrentHashMap<>();
private String _domain = null; private String _domain = null;

View File

@ -231,7 +231,7 @@ public class ConnectorServerTest
@Test @Test
public void testJMXOverTLS() throws Exception public void testJMXOverTLS() throws Exception
{ {
SslContextFactory sslContextFactory = new SslContextFactory.Server(); SslContextFactory.Server sslContextFactory = new SslContextFactory.Server();
String keyStorePath = MavenTestingUtils.getTestResourcePath("keystore.p12").toString(); String keyStorePath = MavenTestingUtils.getTestResourcePath("keystore.p12").toString();
String keyStorePassword = "storepwd"; String keyStorePassword = "storepwd";
sslContextFactory.setKeyStorePath(keyStorePath); sslContextFactory.setKeyStorePath(keyStorePath);