2021-05-05 23:42:22 -07:00

1203 lines
47 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

[[actuator.endpoints]]
== Endpoints
Actuator endpoints let you monitor and interact with your application.
Spring Boot includes a number of built-in endpoints and lets you add your own.
For example, the `health` endpoint provides basic application health information.
Each individual endpoint can be <<actuator#actuator.endpoints.enabling, enabled or disabled>> and <<actuator#actuator.endpoints.exposing, exposed (made remotely accessible) over HTTP or JMX>>.
An endpoint is considered to be available when it is both enabled and exposed.
The built-in endpoints will only be auto-configured when they are available.
Most applications choose exposure via HTTP, where the ID of the endpoint along with a prefix of `/actuator` is mapped to a URL.
For example, by default, the `health` endpoint is mapped to `/actuator/health`.
TIP: To learn more about the Actuator's endpoints and their request and response formats, please refer to the separate API documentation ({spring-boot-actuator-restapi-docs}[HTML] or {spring-boot-actuator-restapi-pdfdocs}[PDF]).
The following technology-agnostic endpoints are available:
[cols="2,5"]
|===
| ID | Description
| `auditevents`
| Exposes audit events information for the current application.
Requires an `AuditEventRepository` bean.
| `beans`
| Displays a complete list of all the Spring beans in your application.
| `caches`
| Exposes available caches.
| `conditions`
| Shows the conditions that were evaluated on configuration and auto-configuration classes and the reasons why they did or did not match.
| `configprops`
| Displays a collated list of all `@ConfigurationProperties`.
| `env`
| Exposes properties from Spring's `ConfigurableEnvironment`.
| `flyway`
| Shows any Flyway database migrations that have been applied.
Requires one or more `Flyway` beans.
| `health`
| Shows application health information.
| `httptrace`
| Displays HTTP trace information (by default, the last 100 HTTP request-response exchanges).
Requires an `HttpTraceRepository` bean.
| `info`
| Displays arbitrary application info.
| `integrationgraph`
| Shows the Spring Integration graph.
Requires a dependency on `spring-integration-core`.
| `loggers`
| Shows and modifies the configuration of loggers in the application.
| `liquibase`
| Shows any Liquibase database migrations that have been applied.
Requires one or more `Liquibase` beans.
| `metrics`
| Shows '`metrics`' information for the current application.
| `mappings`
| Displays a collated list of all `@RequestMapping` paths.
|`quartz`
|Shows information about Quartz Scheduler jobs.
| `scheduledtasks`
| Displays the scheduled tasks in your application.
| `sessions`
| Allows retrieval and deletion of user sessions from a Spring Session-backed session store.
Requires a Servlet-based web application using Spring Session.
| `shutdown`
| Lets the application be gracefully shutdown.
Disabled by default.
| `startup`
| Shows the <<features#features.spring-application.startup-tracking,startup steps data>> collected by the `ApplicationStartup`.
Requires the `SpringApplication` to be configured with a `BufferingApplicationStartup`.
| `threaddump`
| Performs a thread dump.
|===
If your application is a web application (Spring MVC, Spring WebFlux, or Jersey), you can use the following additional endpoints:
[cols="2,5"]
|===
| ID | Description
| `heapdump`
| Returns an `hprof` heap dump file.
| `jolokia`
| Exposes JMX beans over HTTP (when Jolokia is on the classpath, not available for WebFlux).
Requires a dependency on `jolokia-core`.
| `logfile`
| Returns the contents of the logfile (if `logging.file.name` or `logging.file.path` properties have been set).
Supports the use of the HTTP `Range` header to retrieve part of the log file's content.
| `prometheus`
| Exposes metrics in a format that can be scraped by a Prometheus server.
Requires a dependency on `micrometer-registry-prometheus`.
|===
[[actuator.endpoints.enabling]]
=== Enabling Endpoints
By default, all endpoints except for `shutdown` are enabled.
To configure the enablement of an endpoint, use its `management.endpoint.<id>.enabled` property.
The following example enables the `shutdown` endpoint:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
shutdown:
enabled: true
----
If you prefer endpoint enablement to be opt-in rather than opt-out, set the configprop:management.endpoints.enabled-by-default[] property to `false` and use individual endpoint `enabled` properties to opt back in.
The following example enables the `info` endpoint and disables all other endpoints:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoints:
enabled-by-default: false
endpoint:
info:
enabled: true
----
NOTE: Disabled endpoints are removed entirely from the application context.
If you want to change only the technologies over which an endpoint is exposed, use the <<actuator#actuator.endpoints.exposing, `include` and `exclude` properties>> instead.
[[actuator.endpoints.exposing]]
=== Exposing Endpoints
Since Endpoints may contain sensitive information, careful consideration should be given about when to expose them.
The following table shows the default exposure for the built-in endpoints:
[cols="1,1,1"]
|===
| ID | JMX | Web
| `auditevents`
| Yes
| No
| `beans`
| Yes
| No
| `caches`
| Yes
| No
| `conditions`
| Yes
| No
| `configprops`
| Yes
| No
| `env`
| Yes
| No
| `flyway`
| Yes
| No
| `health`
| Yes
| Yes
| `heapdump`
| N/A
| No
| `httptrace`
| Yes
| No
| `info`
| Yes
| Yes
| `integrationgraph`
| Yes
| No
| `jolokia`
| N/A
| No
| `logfile`
| N/A
| No
| `loggers`
| Yes
| No
| `liquibase`
| Yes
| No
| `metrics`
| Yes
| No
| `mappings`
| Yes
| No
| `prometheus`
| N/A
| No
| `quartz`
| Yes
| No
| `scheduledtasks`
| Yes
| No
| `sessions`
| Yes
| No
| `shutdown`
| Yes
| No
| `startup`
| Yes
| No
| `threaddump`
| Yes
| No
|===
To change which endpoints are exposed, use the following technology-specific `include` and `exclude` properties:
[cols="3,1"]
|===
| Property | Default
| configprop:management.endpoints.jmx.exposure.exclude[]
|
| configprop:management.endpoints.jmx.exposure.include[]
| `*`
| configprop:management.endpoints.web.exposure.exclude[]
|
| configprop:management.endpoints.web.exposure.include[]
| `info, health`
|===
The `include` property lists the IDs of the endpoints that are exposed.
The `exclude` property lists the IDs of the endpoints that should not be exposed.
The `exclude` property takes precedence over the `include` property.
Both `include` and `exclude` properties can be configured with a list of endpoint IDs.
For example, to stop exposing all endpoints over JMX and only expose the `health` and `info` endpoints, use the following property:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoints:
jmx:
exposure:
include: "health,info"
----
`*` can be used to select all endpoints.
For example, to expose everything over HTTP except the `env` and `beans` endpoints, use the following properties:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoints:
web:
exposure:
include: "*"
exclude: "env,beans"
----
NOTE: `*` has a special meaning in YAML, so be sure to add quotes if you want to include (or exclude) all endpoints.
NOTE: If your application is exposed publicly, we strongly recommend that you also <<actuator#actuator.endpoints.security, secure your endpoints>>.
TIP: If you want to implement your own strategy for when endpoints are exposed, you can register an `EndpointFilter` bean.
[[actuator.endpoints.security]]
=== Securing HTTP Endpoints
You should take care to secure HTTP endpoints in the same way that you would any other sensitive URL.
If Spring Security is present, endpoints are secured by default using Spring Securitys content-negotiation strategy.
If you wish to configure custom security for HTTP endpoints, for example, only allow users with a certain role to access them, Spring Boot provides some convenient `RequestMatcher` objects that can be used in combination with Spring Security.
A typical Spring Security configuration might look something like the following example:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/security/typical/MySecurityConfiguration.java[]
----
The preceding example uses `EndpointRequest.toAnyEndpoint()` to match a request to any endpoint and then ensures that all have the `ENDPOINT_ADMIN` role.
Several other matcher methods are also available on `EndpointRequest`.
See the API documentation ({spring-boot-actuator-restapi-docs}[HTML] or {spring-boot-actuator-restapi-pdfdocs}[PDF]) for details.
If you deploy applications behind a firewall, you may prefer that all your actuator endpoints can be accessed without requiring authentication.
You can do so by changing the configprop:management.endpoints.web.exposure.include[] property, as follows:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoints:
web:
exposure:
include: "*"
----
Additionally, if Spring Security is present, you would need to add custom security configuration that allows unauthenticated access to the endpoints as shown in the following example:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/security/exposeall/MySecurityConfiguration.java[]
----
NOTE: In both the examples above, the configuration applies only to the actuator endpoints.
Since Spring Boot's security configuration backs off completely in the presence of any `SecurityFilterChain` bean, you will need to configure an additional `SecurityFilterChain` bean with rules that apply to the rest of the application.
[[actuator.endpoints.caching]]
=== Configuring Endpoints
Endpoints automatically cache responses to read operations that do not take any parameters.
To configure the amount of time for which an endpoint will cache a response, use its `cache.time-to-live` property.
The following example sets the time-to-live of the `beans` endpoint's cache to 10 seconds:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
beans:
cache:
time-to-live: "10s"
----
NOTE: The prefix `management.endpoint.<name>` is used to uniquely identify the endpoint that is being configured.
[[actuator.endpoints.hypermedia]]
=== Hypermedia for Actuator Web Endpoints
A "`discovery page`" is added with links to all the endpoints.
The "`discovery page`" is available on `/actuator` by default.
To disable the "`discovery page`", add the following property to your application properties:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoints:
web:
discovery:
enabled: false
----
When a custom management context path is configured, the "`discovery page`" automatically moves from `/actuator` to the root of the management context.
For example, if the management context path is `/management`, then the discovery page is available from `/management`.
When the management context path is set to `/`, the discovery page is disabled to prevent the possibility of a clash with other mappings.
[[actuator.endpoints.cors]]
=== CORS Support
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing[Cross-origin resource sharing] (CORS) is a https://www.w3.org/TR/cors/[W3C specification] that lets you specify in a flexible way what kind of cross-domain requests are authorized.
If you use Spring MVC or Spring WebFlux, Actuator's web endpoints can be configured to support such scenarios.
CORS support is disabled by default and is only enabled once the configprop:management.endpoints.web.cors.allowed-origins[] property has been set.
The following configuration permits `GET` and `POST` calls from the `example.com` domain:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoints:
web:
cors:
allowed-origins: "https://example.com"
allowed-methods: "GET,POST"
----
TIP: See {spring-boot-actuator-autoconfigure-module-code}/endpoint/web/CorsEndpointProperties.java[CorsEndpointProperties] for a complete list of options.
[[actuator.endpoints.implementing-custom]]
=== Implementing Custom Endpoints
If you add a `@Bean` annotated with `@Endpoint`, any methods annotated with `@ReadOperation`, `@WriteOperation`, or `@DeleteOperation` are automatically exposed over JMX and, in a web application, over HTTP as well.
Endpoints can be exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux.
If both Jersey and Spring MVC are available, Spring MVC will be used.
The following example exposes a read operation that returns a custom object:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/implementingcustom/MyEndpoint.java[tag=read]
----
You can also write technology-specific endpoints by using `@JmxEndpoint` or `@WebEndpoint`.
These endpoints are restricted to their respective technologies.
For example, `@WebEndpoint` is exposed only over HTTP and not over JMX.
You can write technology-specific extensions by using `@EndpointWebExtension` and `@EndpointJmxExtension`.
These annotations let you provide technology-specific operations to augment an existing endpoint.
Finally, if you need access to web-framework-specific functionality, you can implement Servlet or Spring `@Controller` and `@RestController` endpoints at the cost of them not being available over JMX or when using a different web framework.
[[actuator.endpoints.implementing-custom.input]]
==== Receiving Input
Operations on an endpoint receive input via their parameters.
When exposed via the web, the values for these parameters are taken from the URL's query parameters and from the JSON request body.
When exposed via JMX, the parameters are mapped to the parameters of the MBean's operations.
Parameters are required by default.
They can be made optional by annotating them with either `@javax.annotation.Nullable` or `@org.springframework.lang.Nullable`.
Each root property in the JSON request body can be mapped to a parameter of the endpoint.
Consider the following JSON request body:
[source,json,indent=0,subs="verbatim"]
----
{
"name": "test",
"counter": 42
}
----
This can be used to invoke a write operation that takes `String name` and `int counter` parameters, as shown in the following example:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/implementingcustom/MyEndpoint.java[tag=write]
----
TIP: Because endpoints are technology agnostic, only simple types can be specified in the method signature.
In particular declaring a single parameter with a `CustomData` type defining a `name` and `counter` properties is not supported.
NOTE: To allow the input to be mapped to the operation method's parameters, Java code implementing an endpoint should be compiled with `-parameters`, and Kotlin code implementing an endpoint should be compiled with `-java-parameters`.
This will happen automatically if you are using Spring Boot's Gradle plugin or if you are using Maven and `spring-boot-starter-parent`.
[[actuator.endpoints.implementing-custom.input.conversion]]
===== Input Type Conversion
The parameters passed to endpoint operation methods are, if necessary, automatically converted to the required type.
Before calling an operation method, the input received via JMX or an HTTP request is converted to the required types using an instance of `ApplicationConversionService` as well as any `Converter` or `GenericConverter` beans qualified with `@EndpointConverter`.
[[actuator.endpoints.implementing-custom.web]]
==== Custom Web Endpoints
Operations on an `@Endpoint`, `@WebEndpoint`, or `@EndpointWebExtension` are automatically exposed over HTTP using Jersey, Spring MVC, or Spring WebFlux.
If both Jersey and Spring MVC are available, Spring MVC will be used.
[[actuator.endpoints.implementing-custom.web.request-predicates]]
===== Web Endpoint Request Predicates
A request predicate is automatically generated for each operation on a web-exposed endpoint.
[[actuator.endpoints.implementing-custom.web.path-predicates]]
===== Path
The path of the predicate is determined by the ID of the endpoint and the base path of web-exposed endpoints.
The default base path is `/actuator`.
For example, an endpoint with the ID `sessions` will use `/actuator/sessions` as its path in the predicate.
The path can be further customized by annotating one or more parameters of the operation method with `@Selector`.
Such a parameter is added to the path predicate as a path variable.
The variable's value is passed into the operation method when the endpoint operation is invoked.
If you want to capture all remaining path elements, you can add `@Selector(Match=ALL_REMAINING)` to the last parameter and make it a type that is conversion compatible with a `String[]`.
[[actuator.endpoints.implementing-custom.web.method-predicates]]
===== HTTP method
The HTTP method of the predicate is determined by the operation type, as shown in the following table:
[cols="3, 1"]
|===
| Operation | HTTP method
| `@ReadOperation`
| `GET`
| `@WriteOperation`
| `POST`
| `@DeleteOperation`
| `DELETE`
|===
[[actuator.endpoints.implementing-custom.web.consumes-predicates]]
===== Consumes
For a `@WriteOperation` (HTTP `POST`) that uses the request body, the consumes clause of the predicate is `application/vnd.spring-boot.actuator.v2+json, application/json`.
For all other operations the consumes clause is empty.
[[actuator.endpoints.implementing-custom.web.produces-predicates]]
===== Produces
The produces clause of the predicate can be determined by the `produces` attribute of the `@DeleteOperation`, `@ReadOperation`, and `@WriteOperation` annotations.
The attribute is optional.
If it is not used, the produces clause is determined automatically.
If the operation method returns `void` or `Void` the produces clause is empty.
If the operation method returns a `org.springframework.core.io.Resource`, the produces clause is `application/octet-stream`.
For all other operations the produces clause is `application/vnd.spring-boot.actuator.v2+json, application/json`.
[[actuator.endpoints.implementing-custom.web.response-status]]
===== Web Endpoint Response Status
The default response status for an endpoint operation depends on the operation type (read, write, or delete) and what, if anything, the operation returns.
A `@ReadOperation` returns a value, the response status will be 200 (OK).
If it does not return a value, the response status will be 404 (Not Found).
If a `@WriteOperation` or `@DeleteOperation` returns a value, the response status will be 200 (OK).
If it does not return a value the response status will be 204 (No Content).
If an operation is invoked without a required parameter, or with a parameter that cannot be converted to the required type, the operation method will not be called and the response status will be 400 (Bad Request).
[[actuator.endpoints.implementing-custom.web.range-requests]]
===== Web Endpoint Range Requests
An HTTP range request can be used to request part of an HTTP resource.
When using Spring MVC or Spring Web Flux, operations that return a `org.springframework.core.io.Resource` automatically support range requests.
NOTE: Range requests are not supported when using Jersey.
[[actuator.endpoints.implementing-custom.web.security]]
===== Web Endpoint Security
An operation on a web endpoint or a web-specific endpoint extension can receive the current `java.security.Principal` or `org.springframework.boot.actuate.endpoint.SecurityContext` as a method parameter.
The former is typically used in conjunction with `@Nullable` to provide different behavior for authenticated and unauthenticated users.
The latter is typically used to perform authorization checks using its `isUserInRole(String)` method.
[[actuator.endpoints.implementing-custom.servlet]]
==== Servlet Endpoints
A `Servlet` can be exposed as an endpoint by implementing a class annotated with `@ServletEndpoint` that also implements `Supplier<EndpointServlet>`.
Servlet endpoints provide deeper integration with the Servlet container but at the expense of portability.
They are intended to be used to expose an existing `Servlet` as an endpoint.
For new endpoints, the `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible.
[[actuator.endpoints.implementing-custom.controller]]
==== Controller Endpoints
`@ControllerEndpoint` and `@RestControllerEndpoint` can be used to implement an endpoint that is only exposed by Spring MVC or Spring WebFlux.
Methods are mapped using the standard annotations for Spring MVC and Spring WebFlux such as `@RequestMapping` and `@GetMapping`, with the endpoint's ID being used as a prefix for the path.
Controller endpoints provide deeper integration with Spring's web frameworks but at the expense of portability.
The `@Endpoint` and `@WebEndpoint` annotations should be preferred whenever possible.
[[actuator.endpoints.health]]
=== Health Information
You can use health information to check the status of your running application.
It is often used by monitoring software to alert someone when a production system goes down.
The information exposed by the `health` endpoint depends on the configprop:management.endpoint.health.show-details[] and configprop:management.endpoint.health.show-components[] properties which can be configured with one of the following values:
[cols="1, 3"]
|===
| Name | Description
| `never`
| Details are never shown.
| `when-authorized`
| Details are only shown to authorized users.
Authorized roles can be configured using `management.endpoint.health.roles`.
| `always`
| Details are shown to all users.
|===
The default value is `never`.
A user is considered to be authorized when they are in one or more of the endpoint's roles.
If the endpoint has no configured roles (the default) all authenticated users are considered to be authorized.
The roles can be configured using the configprop:management.endpoint.health.roles[] property.
NOTE: If you have secured your application and wish to use `always`, your security configuration must permit access to the health endpoint for both authenticated and unauthenticated users.
Health information is collected from the content of a {spring-boot-actuator-module-code}/health/HealthContributorRegistry.java[`HealthContributorRegistry`] (by default all {spring-boot-actuator-module-code}/health/HealthContributor.java[`HealthContributor`] instances defined in your `ApplicationContext`).
Spring Boot includes a number of auto-configured `HealthContributors` and you can also write your own.
A `HealthContributor` can either be a `HealthIndicator` or a `CompositeHealthContributor`.
A `HealthIndicator` provides actual health information, including a `Status`.
A `CompositeHealthContributor` provides a composite of other `HealthContributors`.
Taken together, contributors form a tree structure to represent the overall system health.
By default, the final system health is derived by a `StatusAggregator` which sorts the statuses from each `HealthIndicator` based on an ordered list of statuses.
The first status in the sorted list is used as the overall health status.
If no `HealthIndicator` returns a status that is known to the `StatusAggregator`, an `UNKNOWN` status is used.
TIP: The `HealthContributorRegistry` can be used to register and unregister health indicators at runtime.
[[actuator.endpoints.health.auto-configured-health-indicators]]
==== Auto-configured HealthIndicators
The following `HealthIndicators` are auto-configured by Spring Boot when appropriate.
You can also enable/disable selected indicators by configuring `management.health.key.enabled`,
with the `key` listed in the table below.
[cols="2,4,6"]
|===
| Key | Name | Description
| `cassandra`
| {spring-boot-actuator-module-code}/cassandra/CassandraDriverHealthIndicator.java[`CassandraDriverHealthIndicator`]
| Checks that a Cassandra database is up.
| `couchbase`
| {spring-boot-actuator-module-code}/couchbase/CouchbaseHealthIndicator.java[`CouchbaseHealthIndicator`]
| Checks that a Couchbase cluster is up.
| `db`
| {spring-boot-actuator-module-code}/jdbc/DataSourceHealthIndicator.java[`DataSourceHealthIndicator`]
| Checks that a connection to `DataSource` can be obtained.
| `diskspace`
| {spring-boot-actuator-module-code}/system/DiskSpaceHealthIndicator.java[`DiskSpaceHealthIndicator`]
| Checks for low disk space.
| `elasticsearch`
| {spring-boot-actuator-module-code}/elasticsearch/ElasticsearchRestHealthIndicator.java[`ElasticsearchRestHealthIndicator`]
| Checks that an Elasticsearch cluster is up.
| `hazelcast`
| {spring-boot-actuator-module-code}/hazelcast/HazelcastHealthIndicator.java[`HazelcastHealthIndicator`]
| Checks that a Hazelcast server is up.
| `influxdb`
| {spring-boot-actuator-module-code}/influx/InfluxDbHealthIndicator.java[`InfluxDbHealthIndicator`]
| Checks that an InfluxDB server is up.
| `jms`
| {spring-boot-actuator-module-code}/jms/JmsHealthIndicator.java[`JmsHealthIndicator`]
| Checks that a JMS broker is up.
| `ldap`
| {spring-boot-actuator-module-code}/ldap/LdapHealthIndicator.java[`LdapHealthIndicator`]
| Checks that an LDAP server is up.
| `mail`
| {spring-boot-actuator-module-code}/mail/MailHealthIndicator.java[`MailHealthIndicator`]
| Checks that a mail server is up.
| `mongo`
| {spring-boot-actuator-module-code}/mongo/MongoHealthIndicator.java[`MongoHealthIndicator`]
| Checks that a Mongo database is up.
| `neo4j`
| {spring-boot-actuator-module-code}/neo4j/Neo4jHealthIndicator.java[`Neo4jHealthIndicator`]
| Checks that a Neo4j database is up.
| `ping`
| {spring-boot-actuator-module-code}/health/PingHealthIndicator.java[`PingHealthIndicator`]
| Always responds with `UP`.
| `rabbit`
| {spring-boot-actuator-module-code}/amqp/RabbitHealthIndicator.java[`RabbitHealthIndicator`]
| Checks that a Rabbit server is up.
| `redis`
| {spring-boot-actuator-module-code}/redis/RedisHealthIndicator.java[`RedisHealthIndicator`]
| Checks that a Redis server is up.
| `solr`
| {spring-boot-actuator-module-code}/solr/SolrHealthIndicator.java[`SolrHealthIndicator`]
| Checks that a Solr server is up.
|===
TIP: You can disable them all by setting the configprop:management.health.defaults.enabled[] property.
Additional `HealthIndicators` are available but not enabled by default:
[cols="3,4,6"]
|===
| Key | Name | Description
| `livenessstate`
| {spring-boot-actuator-module-code}/availability/LivenessStateHealthIndicator.java[`LivenessStateHealthIndicator`]
| Exposes the "Liveness" application availability state.
| `readinessstate`
| {spring-boot-actuator-module-code}/availability/ReadinessStateHealthIndicator.java[`ReadinessStateHealthIndicator`]
| Exposes the "Readiness" application availability state.
|===
[[actuator.endpoints.health.writing-custom-health-indicators]]
==== Writing Custom HealthIndicators
To provide custom health information, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/HealthIndicator.java[`HealthIndicator`] interface.
You need to provide an implementation of the `health()` method and return a `Health` response.
The `Health` response should include a status and can optionally include additional details to be displayed.
The following code shows a sample `HealthIndicator` implementation:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/health/writingcustomhealthindicators/MyHealthIndicator.java[]
----
NOTE: The identifier for a given `HealthIndicator` is the name of the bean without the `HealthIndicator` suffix, if it exists.
In the preceding example, the health information is available in an entry named `my`.
In addition to Spring Boot's predefined {spring-boot-actuator-module-code}/health/Status.java[`Status`] types, it is also possible for `Health` to return a custom `Status` that represents a new system state.
In such cases, a custom implementation of the {spring-boot-actuator-module-code}/health/StatusAggregator.java[`StatusAggregator`] interface also needs to be provided, or the default implementation has to be configured by using the configprop:management.endpoint.health.status.order[] configuration property.
For example, assume a new `Status` with code `FATAL` is being used in one of your `HealthIndicator` implementations.
To configure the severity order, add the following property to your application properties:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
health:
status:
order: "fatal,down,out-of-service,unknown,up"
----
The HTTP status code in the response reflects the overall health status.
By default, `OUT_OF_SERVICE` and `DOWN` map to 503.
Any unmapped health statuses, including `UP`, map to 200.
You might also want to register custom status mappings if you access the health endpoint over HTTP.
Configuring a custom mapping disables the defaults mappings for `DOWN` and `OUT_OF_SERVICE`.
If you want to retain the default mappings they must be configured explicitly alongside any custom mappings.
For example, the following property maps `FATAL` to 503 (service unavailable) and retains the default mappings for `DOWN` and `OUT_OF_SERVICE`:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
health:
status:
http-mapping:
down: 503
fatal: 503
out-of-service: 503
----
TIP: If you need more control, you can define your own `HttpCodeStatusMapper` bean.
The following table shows the default status mappings for the built-in statuses:
[cols="1,3"]
|===
| Status | Mapping
| `DOWN`
| `SERVICE_UNAVAILABLE` (`503`)
| `OUT_OF_SERVICE`
| `SERVICE_UNAVAILABLE` (`503`)
| `UP`
| No mapping by default, so HTTP status is `200`
| `UNKNOWN`
| No mapping by default, so HTTP status is `200`
|===
[[actuator.endpoints.health.reactive-health-indicators]]
==== Reactive Health Indicators
For reactive applications, such as those using Spring WebFlux, `ReactiveHealthContributor` provides a non-blocking contract for getting application health.
Similar to a traditional `HealthContributor`, health information is collected from the content of a {spring-boot-actuator-module-code}/health/ReactiveHealthContributorRegistry.java[`ReactiveHealthContributorRegistry`] (by default all {spring-boot-actuator-module-code}/health/HealthContributor.java[`HealthContributor`] and {spring-boot-actuator-module-code}/health/ReactiveHealthContributor.java[`ReactiveHealthContributor`] instances defined in your `ApplicationContext`).
Regular `HealthContributors` that do not check against a reactive API are executed on the elastic scheduler.
TIP: In a reactive application, The `ReactiveHealthContributorRegistry` should be used to register and unregister health indicators at runtime.
If you need to register a regular `HealthContributor`, you should wrap it using `ReactiveHealthContributor#adapt`.
To provide custom health information from a reactive API, you can register Spring beans that implement the {spring-boot-actuator-module-code}/health/ReactiveHealthIndicator.java[`ReactiveHealthIndicator`] interface.
The following code shows a sample `ReactiveHealthIndicator` implementation:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/health/reactivehealthindicators/MyReactiveHealthIndicator.java[]
----
TIP: To handle the error automatically, consider extending from `AbstractReactiveHealthIndicator`.
[[actuator.endpoints.health.auto-configured-reactive-health-indicators]]
==== Auto-configured ReactiveHealthIndicators
The following `ReactiveHealthIndicators` are auto-configured by Spring Boot when appropriate:
[cols="2,4,6"]
|===
| Key | Name | Description
| `cassandra`
| {spring-boot-actuator-module-code}/cassandra/CassandraDriverReactiveHealthIndicator.java[`CassandraDriverReactiveHealthIndicator`]
| Checks that a Cassandra database is up.
| `couchbase`
| {spring-boot-actuator-module-code}/couchbase/CouchbaseReactiveHealthIndicator.java[`CouchbaseReactiveHealthIndicator`]
| Checks that a Couchbase cluster is up.
| `elasticsearch`
| {spring-boot-actuator-module-code}/elasticsearch/ElasticsearchReactiveHealthIndicator.java[`ElasticsearchReactiveHealthIndicator`]
| Checks that an Elasticsearch cluster is up.
| `mongo`
| {spring-boot-actuator-module-code}/mongo/MongoReactiveHealthIndicator.java[`MongoReactiveHealthIndicator`]
| Checks that a Mongo database is up.
| `neo4j`
| {spring-boot-actuator-module-code}/neo4j/Neo4jReactiveHealthIndicator.java[`Neo4jReactiveHealthIndicator`]
| Checks that a Neo4j database is up.
| `redis`
| {spring-boot-actuator-module-code}/redis/RedisReactiveHealthIndicator.java[`RedisReactiveHealthIndicator`]
| Checks that a Redis server is up.
|===
TIP: If necessary, reactive indicators replace the regular ones.
Also, any `HealthIndicator` that is not handled explicitly is wrapped automatically.
[[actuator.endpoints.health.groups]]
==== Health Groups
It's sometimes useful to organize health indicators into groups that can be used for different purposes.
To create a health indicator group you can use the `management.endpoint.health.group.<name>` property and specify a list of health indicator IDs to `include` or `exclude`.
For example, to create a group that includes only database indicators you can define the following:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
health:
group:
custom:
include: "db"
----
You can then check the result by hitting `http://localhost:8080/actuator/health/custom`.
Similarly, to create a group that excludes the database indicators from the group and includes all the other indicators, you can define the following:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
health:
group:
custom:
exclude: "db"
----
By default groups will inherit the same `StatusAggregator` and `HttpCodeStatusMapper` settings as the system health, however, these can also be defined on a per-group basis.
It's also possible to override the `show-details` and `roles` properties if required:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
health:
group:
custom:
show-details: "when-authorized"
roles: "admin"
status:
order: "fatal,up"
http-mapping:
fatal: 500
out-of-service: 500
----
TIP: You can use `@Qualifier("groupname")` if you need to register custom `StatusAggregator` or `HttpCodeStatusMapper` beans for use with the group.
[[actuator.endpoints.health.datasource]]
==== DataSource Health
The `DataSource` health indicator shows the health of both standard data source and routing data source beans.
The health of a routing data source includes the health of each of its target data sources.
In the health endpoint's response, each of a routing data source's targets is named using its routing key.
If you prefer not to include routing data sources in the indicator's output, set configprop:management.health.db.ignore-routing-data-sources[] to `true`.
[[actuator.endpoints.kubernetes-probes]]
=== Kubernetes Probes
Applications deployed on Kubernetes can provide information about their internal state with https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes[Container Probes].
Depending on https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-startup-probes/[your Kubernetes configuration], the kubelet will call those probes and react to the result.
Spring Boot manages your <<features#features.spring-application.application-availability,Application Availability State>> out-of-the-box.
If deployed in a Kubernetes environment, actuator will gather the "Liveness" and "Readiness" information from the `ApplicationAvailability` interface and use that information in dedicated <<actuator#actuator.endpoints.health.auto-configured-health-indicators,Health Indicators>>: `LivenessStateHealthIndicator` and `ReadinessStateHealthIndicator`.
These indicators will be shown on the global health endpoint (`"/actuator/health"`).
They will also be exposed as separate HTTP Probes using <<actuator#actuator.endpoints.health.groups, Health Groups>>: `"/actuator/health/liveness"` and `"/actuator/health/readiness"`.
You can then configure your Kubernetes infrastructure with the following endpoint information:
[source,yml,indent=0,subs="verbatim"]
----
livenessProbe:
httpGet:
path: /actuator/health/liveness
port: <actuator-port>
failureThreshold: ...
periodSeconds: ...
readinessProbe:
httpGet:
path: /actuator/health/readiness
port: <actuator-port>
failureThreshold: ...
periodSeconds: ...
----
NOTE: `<actuator-port>` should be set to the port that the actuator endpoints are available on.
It could be the main web server port, or a separate management port if the `"management.server.port"` property has been set.
These health groups are only enabled automatically if the application is <<deployment#deployment.cloud.kubernetes,running in a Kubernetes environment>>.
You can enable them in any environment using the configprop:management.endpoint.health.probes.enabled[] configuration property.
NOTE: If an application takes longer to start than the configured liveness period, Kubernetes mention the `"startupProbe"` as a possible solution.
The `"startupProbe"` is not necessarily needed here as the `"readinessProbe"` fails until all startup tasks are done, see <<actuator#actuator.endpoints.kubernetes-probes.lifecycle,how Probes behave during the application lifecycle>>.
WARNING: If your Actuator endpoints are deployed on a separate management context, be aware that endpoints are then not using the same web infrastructure (port, connection pools, framework components) as the main application.
In this case, a probe check could be successful even if the main application does not work properly (for example, it cannot accept new connections).
[[actuator.endpoints.kubernetes-probes.external-state]]
==== Checking External State with Kubernetes Probes
Actuator configures the "liveness" and "readiness" probes as Health Groups; this means that all the <<actuator#actuator.endpoints.health.groups, Health Groups features>> are available for them.
You can, for example, configure additional Health Indicators:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
endpoint:
health:
group:
readiness:
include: "readinessState,customCheck"
----
By default, Spring Boot does not add other Health Indicators to these groups.
The "`liveness`" Probe should not depend on health checks for external systems.
If the <<features#features.spring-application.application-availability.liveness,Liveness State of an application>> is broken, Kubernetes will try to solve that problem by restarting the application instance.
This means that if an external system fails (e.g. a database, a Web API, an external cache), Kubernetes might restart all application instances and create cascading failures.
As for the "`readiness`" Probe, the choice of checking external systems must be made carefully by the application developers, i.e. Spring Boot does not include any additional health checks in the readiness probe.
If the <<features#features.spring-application.application-availability.readiness,Readiness State of an application instance>> is unready, Kubernetes will not route traffic to that instance.
Some external systems might not be shared by application instances, in which case they could quite naturally be included in a readiness probe.
Other external systems might not be essential to the application (the application could have circuit breakers and fallbacks), in which case they definitely should not be included.
Unfortunately, an external system that is shared by all application instances is common, and you have to make a judgement call: include it in the readiness probe and expect that the application is taken out of service when the external service is down, or leave it out and deal with failures higher up the stack, e.g. using a circuit breaker in the caller.
NOTE: If all instances of an application are unready, a Kubernetes Service with `type=ClusterIP` or `NodePort` will not accept any incoming connections.
There is no HTTP error response (503 etc.) since there is no connection.
A Service with `type=LoadBalancer` might or might not accept connections, depending on the provider.
A Service that has an explicit https://kubernetes.io/docs/concepts/services-networking/ingress/[Ingress] will also respond in a way that depends on the implementation - the ingress service itself will have to decide how to handle the "connection refused" from downstream.
HTTP 503 is quite likely in the case of both load balancer and ingress.
Also, if an application is using Kubernetes https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale/[autoscaling] it may react differently to applications being taken out of the load-balancer, depending on its autoscaler configuration.
[[actuator.endpoints.kubernetes-probes.lifecycle]]
==== Application Lifecycle and Probe States
An important aspect of the Kubernetes Probes support is its consistency with the application lifecycle.
There is a significant difference between the `AvailabilityState` which is the in-memory, internal state of the application
and the actual Probe which exposes that state: depending on the phase of application lifecycle, the Probe might not be available.
Spring Boot publishes <<features#features.spring-application.application-events-and-listeners,Application Events during startup and shutdown>>,
and Probes can listen to such events and expose the `AvailabilityState` information.
The following tables show the `AvailabilityState` and the state of HTTP connectors at different stages.
When a Spring Boot application starts:
[cols="2,2,2,3,5"]
|===
|Startup phase |LivenessState |ReadinessState |HTTP server |Notes
|Starting
|`BROKEN`
|`REFUSING_TRAFFIC`
|Not started
|Kubernetes checks the "liveness" Probe and restarts the application if it takes too long.
|Started
|`CORRECT`
|`REFUSING_TRAFFIC`
|Refuses requests
|The application context is refreshed. The application performs startup tasks and does not receive traffic yet.
|Ready
|`CORRECT`
|`ACCEPTING_TRAFFIC`
|Accepts requests
|Startup tasks are finished. The application is receiving traffic.
|===
When a Spring Boot application shuts down:
[cols="2,2,2,3,5"]
|===
|Shutdown phase |Liveness State |Readiness State |HTTP server |Notes
|Running
|`CORRECT`
|`ACCEPTING_TRAFFIC`
|Accepts requests
|Shutdown has been requested.
|Graceful shutdown
|`CORRECT`
|`REFUSING_TRAFFIC`
|New requests are rejected
|If enabled, <<features#features.graceful-shutdown,graceful shutdown processes in-flight requests>>.
|Shutdown complete
|N/A
|N/A
|Server is shut down
|The application context is closed and the application is shut down.
|===
TIP: Check out the <<deployment#deployment.cloud.kubernetes.container-lifecycle,Kubernetes container lifecycle section>> for more information about Kubernetes deployment.
[[actuator.endpoints.info]]
=== Application Information
Application information exposes various information collected from all {spring-boot-actuator-module-code}/info/InfoContributor.java[`InfoContributor`] beans defined in your `ApplicationContext`.
Spring Boot includes a number of auto-configured `InfoContributor` beans, and you can write your own.
[[actuator.endpoints.info.auto-configured-info-contributors]]
==== Auto-configured InfoContributors
The following `InfoContributor` beans are auto-configured by Spring Boot, when appropriate:
[cols="1,4"]
|===
| Name | Description
| {spring-boot-actuator-module-code}/info/EnvironmentInfoContributor.java[`EnvironmentInfoContributor`]
| Exposes any key from the `Environment` under the `info` key.
| {spring-boot-actuator-module-code}/info/GitInfoContributor.java[`GitInfoContributor`]
| Exposes git information if a `git.properties` file is available.
| {spring-boot-actuator-module-code}/info/BuildInfoContributor.java[`BuildInfoContributor`]
| Exposes build information if a `META-INF/build-info.properties` file is available.
|===
TIP: It is possible to disable them all by setting the configprop:management.info.defaults.enabled[] property.
[[actuator.endpoints.info.custom-application-information]]
==== Custom Application Information
You can customize the data exposed by the `info` endpoint by setting `+info.*+` Spring properties.
All `Environment` properties under the `info` key are automatically exposed.
For example, you could add the following settings to your `application.properties` file:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
info:
app:
encoding: "UTF-8"
java:
source: "11"
target: "11"
----
[TIP]
====
Rather than hardcoding those values, you could also <<howto#howto.properties-and-configuration.expand-properties,expand info properties at build time>>.
Assuming you use Maven, you could rewrite the preceding example as follows:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
info:
app:
encoding: "@project.build.sourceEncoding@"
java:
source: "@java.version@"
target: "@java.version@"
----
====
[[actuator.endpoints.info.git-commit-information]]
==== Git Commit Information
Another useful feature of the `info` endpoint is its ability to publish information about the state of your `git` source code repository when the project was built.
If a `GitProperties` bean is available, the `info` endpoint can be used to expose these properties.
TIP: A `GitProperties` bean is auto-configured if a `git.properties` file is available at the root of the classpath.
See "<<howto#howto.build.generate-git-info,Generate git information>>" for more details.
By default, the endpoint exposes `git.branch`, `git.commit.id`, and `git.commit.time` properties, if present.
If you don't want any of these properties in the endpoint response, they need to be excluded from the `git.properties` file.
If you want to display the full git information (that is, the full content of `git.properties`), use the configprop:management.info.git.mode[] property, as follows:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
info:
git:
mode: "full"
----
To disable the git commit information from the `info` endpoint completely, set the configprop:management.info.git.enabled[] property to `false`, as follows:
[source,yaml,indent=0,subs="verbatim",configprops,configblocks]
----
management:
info:
git:
enabled: false
----
[[actuator.endpoints.info.build-information]]
==== Build Information
If a `BuildProperties` bean is available, the `info` endpoint can also publish information about your build.
This happens if a `META-INF/build-info.properties` file is available in the classpath.
TIP: The Maven and Gradle plugins can both generate that file.
See "<<howto#howto.build.generate-info,Generate build information>>" for more details.
[[actuator.endpoints.info.writing-custom-info-contributors]]
==== Writing Custom InfoContributors
To provide custom application information, you can register Spring beans that implement the {spring-boot-actuator-module-code}/info/InfoContributor.java[`InfoContributor`] interface.
The following example contributes an `example` entry with a single value:
[source,java,indent=0,subs="verbatim"]
----
include::{docs-java}/actuator/endpoints/info/writingcustominfocontributors/MyInfoContributor.java[]
----
If you reach the `info` endpoint, you should see a response that contains the following additional entry:
[source,json,indent=0,subs="verbatim"]
----
{
"example": {
"key" : "value"
}
}
----