Pyohwan / english-study

0 stars 0 forks source link

Spring Boot Actuator: Production-ready Features #28

Open Pyohwan opened 4 years ago

Pyohwan commented 4 years ago

https://docs.spring.io/spring-boot/docs/2.2.2.RELEASE/reference/html/production-ready-features.html#production-ready-enabling

1. Enabling Production-ready Features

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.
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.
threaddump Performs a thread dump.
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.

2.1. Enabling Endpoints

2.2 Exposing Endpoints

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
scheduledtasks Yes No
sessions Yes No
shutdown Yes No
threaddump Yes No
Property Default
management.endpoints.jmx.exposure.exclude  
management.endpoints.jmx.exposure.include *
management.endpoints.web.exposure.exclude  
management.endpoints.web.exposure.include info, health

* 는 YAML 에서 특별한 의미가 있으므로, 따옴표를 추가 해야 함

management:
endpoints:
web:
exposure:
include: "*"

엔드포인트가 public 하게 expose 되어 있다면 엔드포인트 보안이 필요하다

엔드포인트에 대한 별도 전략이 필요하면 EndpointFilter bean 을 등록 해라

2.3. Securing HTTP Endpoints

}


## 2.4. Configuring Endpoints
* 엔드포인트는 파라미터 없는  읽기 작업은 자동으로 캐싱한다
  * `cache.time-to-live` 로 응답 캐시 시간을 설정 가능
  * 다음 예제는 10초 캐싱

management.endpoint.beans.cache.time-to-live=10s

> `management.endpoint.<name>` 는 고유하게 식별하는데 사용된다.
> 인증된 HTTP 요청 시, `Principal` 이 엔드포인트 입력에 사용되므로, 캐시 되지 않는다

## 2.5. Hypermedia for Actuator Web Endpoints
* 모든 엔드포인트의 "discovery page" 링크가 추가된다. 
  * 기본적으로 `/actuator` 에서 이용 가능
* 커스텀 management context path 가 구성되면 "discovery page" 가 자동으로 `/actuator` 에서 root management context 로 이동한다. 
  * context path 가 `/management` 이면, discovery page 는 `/management` 에서 이용 가능
  * context path 가 `/` 면 다른 매핑과의 충돌 방지를 위해 disabled 된다.

## 2.6. CORS Support
* Cross-origin resource sharing (CORS) 는 W3C 스펙으로, cross-domain 요청이 승인 되는지 유연하게 지정할 수 있다
* Spring MVC or Spring WebFlux 의 액츄에이터에서는 이러한 시나리오를 구성할 수 있는 웹 엔드포인트가 있다
* CORS 는 기본적으로 disabled 다. `management.endpoints.web.cors.allowed-origins` 로 활성화 가능. 
* 다음 구성은 example.com 도메인에서 GET 및 POST 호출을 허용합니다.

management.endpoints.web.cors.allowed-origins=https://example.com management.endpoints.web.cors.allowed-methods=GET,POST


## 2.7. Implementing Custom Endpoints
* @Bean 과 @Endpoint 을 함께 붙히고, @ReadOperation, @WriteOperation, or @DeleteOperation 중에 하나 있으면, JMX 나 웹 HTTP 로 expose 된다
  * @JmxEndpoint or @WebEndpoint 로 JMX or Web 으로만 expose 가능
* @EndpointWebExtension and @EndpointJmxExtension 으로 더 확장 가능 하다.
* web-framework-specific 기능에 접근해야 하면, Spring @Controller and @RestController 엔드포인트를 구현하면 된다.

### 2.7.1. Receiving Input
* 엔드포인트 조작은 파라미터를 입력받아서 한다
  * 웹으로 expose 할때, URL 쿼리 파라미터 및 JSON 본문으로 전달 함
  * JMX 로 expose 할때에는, MBean 파라미터로 조작
* 기본적으로 파라미터가 필수로 요구되는데, `@org.springframework.lang.Nullable` 로 선택적으로 만들 수 있다
* JSON 요청 바디
```json
{
    "name": "test",
    "counter": 42
}

메소드 구조는 단순한 타입(int, String 등)만 가능. 커스텀타입으로 namecounter 프로퍼티를 사용할 수 없다. 매핑된 input 파라미터를 조작하려면 엔드포인트 구현체를 -parameters 로 컴파일 해야 한다 (Kotlin 은 -java-parameters) Gradle, Maven 에서 spring-boot-starter-parent 를 쓰고 있다면 자동으로 사용된다

Input type conversion

2.7.2. Custom Web Endpoints

Web Endpoint Request Predicates

Path

HTTP method

Operation HTTP method
@ReadOperation GET
@WriteOperation POST
@DeleteOperation DELETE

Consumes

Produces

Web Endpoint Response Status

Web Endpoint Range Requests

Web Endpoint Security

2.7.3. Servlet endpoints

2.7.4. Controller endpoints

2.8. Health Information

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.

always 를 사용하여 secured 애플리케이션을 가졌다면, 인증사용자와 미인증사용자 둘다 health 엔드포인트에 접근 가능해야만 한다(must)

HealthContributorRegistry 는 런타임으로 health indicator 를 등록 및 해제할때 쓴다

2.8.1. Auto-configured HealthIndicators

Name Description
CassandraHealthIndicator Checks that a Cassandra database is up.
CouchbaseHealthIndicator Checks that a Couchbase cluster is up.
DiskSpaceHealthIndicator Checks for low disk space.
ElasticSearchRestHealthContributorAutoConfiguration Checks that an Elasticsearch cluster is up.
HazelcastHealthIndicator Checks that a Hazelcast server is up.
InfluxDbHealthIndicator Checks that an InfluxDB server is up.
JmsHealthIndicator Checks that a JMS broker is up.
LdapHealthIndicator Checks that an LDAP server is up.
MailHealthIndicator Checks that a mail server is up.
MongoHealthIndicator Checks that a Mongo database is up.
Neo4jHealthIndicator Checks that a Neo4j database is up.
PingHealthIndicator Always responds with UP.
RabbitHealthIndicator Checks that a Rabbit server is up.
RedisHealthIndicator Checks that a Redis server is up.
SolrHealthIndicator Checks that a Solr server is up.

management.health.defaults.enabled 로 모두 diable 할 수 있음

2.8.2. Writing Custom HealthIndicators

@Component public class MyHealthIndicator implements HealthIndicator {

@Override
public Health health() {
    int errorCode = check(); // perform some specific health check
    if (errorCode != 0) {
        return Health.down().withDetail("Error Code", errorCode).build();
    }
    return Health.up().build();
}

}

> 주어진 `HealthIndicator` ID 는 HealthIndicator suffix 를 뺀 bean 이다. 위의 경우 `my`

* Spring Boot 는 이미 정의된 `Status` 타입 말고도 사용자 정의 가능함
  * `StatusAggregator` 를 구현하거나, `management.endpoint.health.status.order` 를 설정해라
* 예를 들어, FATAL Status 를 가진 `HealthIndicator` 구현체가 있을때, severity 우선순위 대로 적으면 된다

management.endpoint.health.status.order=fatal,down,out-of-service,unknown,up

* 전체 health 의 응답 HTTP status 코드를 반영한다. (ex UP 은 200, OUT_OF_SERVICE and DOWN 는 503)
  * 사용자 정의 가능함. FATAL 을 503 으로 설정

management.endpoint.health.status.http-mapping.fatal=503

> 더 많이 조절해야 하면, HttpCodeStatusMapper Bean 을 정의해라

* 내장된 기본 status 매핑

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

### 2.8.3. Reactive Health Indicators
* Spring WebFlux 에서 ReactiveHealthContributor 은 non-blocking 으로 health 접근 가능
  * `ReactiveHealthContributorRegistry` (기본적으로 HealthContributor and ReactiveHealthContributor 객체) 에서 컨텐츠 수집 함
* reactive API 를 하지 않는 일반적인 `HealthContributors` 는 스케쥴러로 실행 함

> `ReactiveHealthContributorRegistry` 로 health indicator를 실시간으로 등록, 안등록

* `ReactiveHealthIndicator` 인터페이스 구현 가능. 다음은 `ReactiveHealthIndicator` 구현체를 보여줌

@Component public class MyReactiveHealthIndicator implements ReactiveHealthIndicator {

@Override
public Mono<Health> health() {
    return doHealthCheck() //perform some specific health check that returns a Mono<Health>
        .onErrorResume(ex -> Mono.just(new Health.Builder().down(ex).build()));
}

}

> 오류를 자동으로 처리하려면 `AbstractReactiveHealthIndicator` 를 확장해라

### 2.8.4. Auto-configured ReactiveHealthIndicators
* 자동구성되는 `ReactiveHealthIndicators`

Name | Description
-- | --
CassandraReactiveHealthIndicator | Checks that a Cassandra database is up.
CouchbaseReactiveHealthIndicator | Checks that a Couchbase cluster is up.
MongoReactiveHealthIndicator | Checks that a Mongo database is up.
RedisReactiveHealthIndicator | Checks that a Redis server is up.

> 필요한 경우, reactive indicator 는 regular 로 대체된다. 명시적으로 처리 되지 않은 `HealthIndicator` 은 자동 래핑된다

### 2.8.5. Health Groups
* health indicators 를 그룹핑 할 수 있다
  * Kubernetes 에 배포할때에는 “liveness” and “readiness” probes health 세트가 필요할 수 있다
* Health indicator 그룹을 만들려면 `management.endpoint.health.group.<name>` 를 써라
  * include or exclude 설정 가능

management.endpoint.health.group.custom.include=db

* `localhost:8080/actuator/health/custom` 에서 확인 해봐라
* 기본 그룹은 StatusAggregator and HttpCodeStatusMapper 설정을 상속 받음
  * show-details and roles 로 재정의도 가능함

management.endpoint.health.group.custom.show-details=when-authorized management.endpoint.health.group.custom.roles=admin management.endpoint.health.group.custom.status.order=fatal,up management.endpoint.health.group.custom.status.http-mapping.fatal=500


> 커스텀 StatusAggregator or HttpCodeStatusMapper 를 그룹으로 등록해야 하면, `@Qualifier("groupname")` 를 써라

## 2.9. Application Information
* `ApplicationContext` 에 정의된 모든 `InfoContributor` 빈에서 수집된 다양한 정보를 expose 한다
  * 여러가지 자동구성된것도 있고, 직접 작성도 가능
### 2.9.1. Auto-configured InfoContributors
* 적절하게 알아서 자동구성

Name | Description
-- | --
EnvironmentInfoContributor | Exposes any key from the Environment under the info key.
GitInfoContributor | Exposes git information if a git.properties file is available.
BuildInfoContributor | Exposes build information if a META-INF/build-info.properties file is available.

> management.info.defaults.enabled 로 모두 비활성 가능

### 2.9.2. Custom Application Information
* `info.*` 으로 설정 가능
* `info` 아래 모든 `Environment ` properties 가 자동으로 expose 된다.

info.app.encoding=UTF-8 info.app.java.source=1.8 info.app.java.target=1.8

> 이렇게 hardcoding 말고, 빌드시 주입 가능

info.app.encoding=@project.build.sourceEncoding@ info.app.java.source=@java.version@ info.app.java.target=@java.version@


### 2.9.3. Git Commit Information
* 빌드 될때 `git` 소스 코드 레파지터리에 대한 상태도 게시한다
* `GitProperties` 빈이 사용 가능하면 git.branch, git.commit.id, and git.commit.time 가 expose 된다
> `git.properties` 파일이 사용 가능하면 `GitProperties` 빈은 자동구성 됨
* 전체 git 정보 표시를 원하면 이렇게 해라

management.info.git.mode=full


### 2.9.4. Build Information
* `BuildProperties` 빈이 사용 가능하면, `info` 엔드포인트가 빌드 정보를 게시한다. `META-INF/build-info.properties` 파일이 classpath 에 있어야 한다

> Gradle, Maven 플러그인으로 지원

### 2.9.5. Writing Custom InfoContributors
* `InfoContributor` 인터페이스를 구현하면 커스텀 가능

import java.util.Collections;

import org.springframework.boot.actuate.info.Info; import org.springframework.boot.actuate.info.InfoContributor; import org.springframework.stereotype.Component;

@Component public class ExampleInfoContributor implements InfoContributor {

@Override
public void contribute(Info.Builder builder) {
    builder.withDetail("example",
            Collections.singletonMap("key", "value"));
}

}

* 응답은?

{ "example": { "key" : "value" } }

Pyohwan commented 4 years ago

3. Monitoring and Management over HTTP

3.1. Customizing the Management Endpoint Paths

3.2. Customizing the Management Server Port

3.3. Configuring Management-specific SSL

Pyohwan commented 4 years ago

4. Monitoring and Management over JMX

4.3.1. Customizing Jolokia

Pyohwan commented 4 years ago

5. Loggers

Pyohwan commented 4 years ago

6. Metrics

}

* 스프링부트는 설정과 애너테이션으로 bulit-in instrumentation (i.e. MeterBinder implementations) 을 구성한다.

## 6.2. Supported monitoring systems
### 6.2.1. AppOptics
* 기본적으로 AppOptics registry 는 `api.appoptics.com/v1/measurements` 로 메트릭을 주기적으로 push 한다.
  * API token 은 필수다

management.metrics.export.appoptics.api-token=YOUR_TOKEN

### 6.2.5. Elastic
* 기본적으로 메트릭은 로컬머신에서 실행중인 `Elastic` 으로 export 된다. 
* 사용할 Elastic 서버는 다음과 같이 사용한다.

management.metrics.export.elastic.host=https://elastic.example.com:8086

### 6.2.13. Prometheus
* Prometheus 는 개별 앱 인스턴스의 메트릭을 poll 할것으로 기대한다.
* Spring Boot 는 `/actuator/prometheus` 액츄에이터 엔드포인트를 제공하고, Prometheus 가 scrape(긁어) 해갈수 있다
> 엔드포인트는 기본적으로 사용할 수 없기 때문에, expose 시켜야 한다
* `prometheus.yml` 에 `scrape_config` 을 추가한 예제이다.

scrape_configs:

6.2.15. Simple

6.3. Supported Metrics

}

* 컨트롤러로 들어오는 모든 요청의 timings 을 활성화
* 개별적인 엔드포인트 활성화. 
* long task 일 경우 `longTask = true` 붙힘
  * Long task timers 는 별도의 메트릭 이름이 필요하고, short 태스크 타이머도 쌓일 수 있음

* 기본적으로 메트릭 이름은 `http.server.requests` 로 생성 됨
  * `management.metrics.web.server.request.metric-name` 로 커스텀 가능
* 기본적인 Spring MVC-related 메트릭 정보는 다음의 표처럼 tag 됨

Tag | Description
-- | --
exception | Simple class name of any exception that was thrown while handling the request.
method | Request’s method (for example, GET or POST)
outcome | Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR
status | Response’s HTTP status code (for example, 200 or 500)
uri | Request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})

* `WebMvcTagsProvider` 구현해서 커스터마이징 가능

### 6.3.2. Spring WebFlux Metrics
* 자동구성으로 WebFlux 컨트롤러나 functional 핸들러를 통한 모든 요청을 계측 가능하다
* 기본적으로 메트릭 이름은 `http.server.requests` 로 생성 됨
  * `management.metrics.web.server.request.metric-name` 로 커스텀 가능
* 기본적인 WebFlux-related 메트릭 정보는 다음의 표처럼 tag 됨

Tag | Description
-- | --
exception | Simple class name of any exception that was thrown while handling the request.
method | Request’s method (for example, GET or POST)
outcome | Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR
status | Response’s HTTP status code (for example, 200 or 500)
uri | Request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})

* `WebFluxTagsProvider` 구현해서 커스터마이징 가능

### 6.3.3. Jersey Server Metrics
* 생략
### 6.3.4. HTTP Client Metrics
* Spring Boot Actuator 는 `RestTemplate` 와 `WebClient` 의 계측도 관리한다
  * 이를 위해 자동구성된 빌더를 inject 하고 객체를 만들어야 한다
    * RestTemplateBuilder for RestTemplate
    * WebClient.Builder for WebClient
  * `MetricsRestTemplateCustomizer` 나 `MetricsWebClientCustomizer` 로 수동으로 커스터마이징 가능
* 기본적으로 메트릭 이름은 `http.server.requests` 로 생성 됨
  * `management.metrics.web.server.request.metric-name` 로 커스텀 가능
* 기본적인 메트릭 정보는 다음의 표처럼 tag 됨

Tag | Description
-- | --
clientName | Host portion of the URI
method | Request’s method (for example, GET or POST)
outcome | Request’s outcome based on the status code of the response. 1xx is INFORMATIONAL, 2xx is SUCCESS, 3xx is REDIRECTION, 4xx CLIENT_ERROR, and 5xx is SERVER_ERROR, UNKNOWN otherwise
status | Response’s HTTP status code if available (for example, 200 or 500), or IO_ERROR in case of I/O issues, CLIENT_ERROR otherwise
uri | Request’s URI template prior to variable substitution, if possible (for example, /api/person/{id})

* 태그 커스터마이징을 하기 위해선 `RestTemplateExchangeTagsProvider` 나 `WebClientExchangeTagsProvider` 를 구현면 됨
  * 또한 편리한 static functions 가 `RestTemplateExchangeTags` 와 `WebClientExchangeTags` 에 있음

### 6.3.5. Cache Metrics
* 자동구성으로 startup 시 `cache` prefix 붙은 사용가능한 모든 `Cache` 를 계측 가능하다
* 캐시 계측은 기본 메트릭 세트로 표준화 되었음
* 추가적인 캐시 라이브리리들
  * Caffeine
  * EhCache 2
  * Hazelcast
  * Any compliant JCache (JSR-107) implementation
* 메트릭은 태그는 `CacheManager` 에 있는 cacheName 으로 된다
> 오로지 startup 시에 이용가능한 캐시만 bound 된다. on-the-fly 혹은 startup 이후 프로그래밍적으로 만들려면, 명시적으로 등록해라. `CacheMetricsRegistrar` bean 은 프로세스를 보다 쉽게 해준다

### 6.3.6. DataSource Metrics
* 자동구성으로 시 `jdbc.connections ` prefix 붙은 사용가능한 모든 `DataSource ` 를 계측 가능하다
* Data source 계측으로 currently active, idle, maximum allowed, and minimum allowed connections in the pool 을 알 수 있다
* 메트릭은 `DataSource`  의 bean 이름 기반으로 태그 된다
> 기본적으로 스프링부트가 제공하는 모든 data sources 의 메타데이터를 제공한다. 별도로 추가하려면 `DataSourcePoolMetadataProvider` bean 을 만들어라. `DataSourcePoolMetadataProvidersConfiguration` 에 예제 있음

* Hikari-specific metrics 은 `hikaricp` prefix 로 expose 된다. 각 메트릭은 풀 이름으로 태그 된다. (`spring.datasource.name` 로 조절 가능)

### 6.3.7. Hibernate Metrics
* 자동구성으로 이용가능한 Hibernate `EntityManagerFactory` 객체를 `hibernate` 란 이름으로 계측 된다
* 메트릭은 `EntityManagerFactory` bean 이름으로 태그된다
* 표준 JPA 설정을 enable 해야 한다. `hibernate.generate_statistics`
* 다음 예제처럼 자동구성된 `EntityManagerFactory` 를 활성화 한다

spring.jpa.properties.hibernate.generate_statistics=true


### 6.3.8. RabbitMQ Metrics
* 자동구성으로 이용가능한 모든 RabbitMQ 커넥션 팩토리를 `rabbitmq` 란 이름으로 계측가능하다

## 6.4. Registering custom metrics
* 커스텀 메트릭을 등록하려면 `MeterRegistry` 를 컨포넌트로 주입하라
```java
class Dictionary {

    private final List<String> words = new CopyOnWriteArrayList<>();

    Dictionary(MeterRegistry registry) {
        registry.gaugeCollectionSize("dictionary.size", Tags.empty(), this.words);
    }

    // …

}

6.5. Customizing individual metrics

6.5.1. Common tags

6.5.2. Per-meter properties

Table 1. Per-meter customizations

Property Description
management.metrics.enable Whether to deny meters from emitting any metrics.
management.metrics.distribution.percentiles-histogram Whether to publish a histogram suitable for computing aggregable (across dimension) percentile approximations.
management.metrics.distribution.minimum-expected-value, management.metrics.distribution.maximum-expected-value Publish less histogram buckets by clamping the range of expected values.
management.metrics.distribution.percentiles Publish percentile values computed in your application
management.metrics.distribution.sla Publish a cumulative histogram with buckets defined by your SLAs.

6.6. Metrics endpoint

여기에서 사용하는 이름은 코드와 일치해야 한다. Prometheus 에서는 jvm.memory.maxjvm_memory_max 로 나타내므로, 엔드포인트에서 meter 를 검사할때 jvm.memory.max 를 사용 해야 한다

reported 된 측정치는 미터 이름, 태그와 일치하는 모든 통계의 합(sum) 이다. 따라서 위 응답의 "Value" 는 "Code Cache", "Compressed Class Space", and "Metaspace" areas of the heap 의 합이다. 메타스페이스의 최대 크기를 알고 싶다면 tag=id:Metaspace 를 추가해라. i.e. /actuator/metrics/jvm.memory.max?tag=area:nonheap&tag=id:Metaspace

Pyohwan commented 4 years ago

7. Auditing

7.1. Custom Auditing

8. HTTP Tracing

9. Process Monitoring

10. Cloud Foundry Support