본문 바로가기

Today I Learned

prometheus

Prometheus 란?

메트릭 데이터 수집 -> 모니터링

  • Prometheus는 오픈소스 시스템 모니터링 및 경고 도구
  • SoundCloud에서 시작되어 현재는 Cloud Native Computing Foundation(CNCF)에서 호스팅하고 있습니다.
  • Prometheus는 시계열 데이터베이스를 사용하여 메트릭 데이터를 수집하고, 쿼리 및 시각화를 통해 시스템 상태를 모니터링하고 경고를 설정할 수 있습니다.

 

Prometheus의 주요 구성 요소

  • Prometheus 서버:
    • 메트릭 데이터를 수집하고 저장하는 핵심 컴포넌트입니다.
    • 각 타겟으로부터 데이터를 주기적으로 스크랩(scrape)하여 시계열 데이터베이스에 저장합니다.
    • 시계열 데이터베이스(Time Series Database, TSDB)는 시간에 따라 변화하는 데이터를 효율적으로 저장하고 조회할 수 있도록 최적화된 데이터베이스입니다.
  • Exporters:
    • Prometheus는 기본적으로 애플리케이션에서 메트릭 데이터를 수집합니다.
    • Exporter는 특정 애플리케이션이나 시스템의 메트릭 데이터를 Prometheus가 이해할 수 있는 형식으로 변환해주는 도구입니다.
    • 예시: Node Exporter (서버의 시스템 메트릭 수집), PostgreSQL Exporter (PostgreSQL 메트릭 수집), Spring boot의 micrometer-registry-prometheus 디펜던시
  • Pushgateway:
    • 짧은 수명의 작업(job)에서 메트릭을 수집하여 Prometheus 서버에 푸시(push)할 수 있습니다.
    • 일반적으로 지속적으로 실행되지 않는 작업에서 사용됩니다. 예를 들어 배치 작업, 스크립트 실행, 크론 작업 등이 있습니다.
  • Alertmanager:
    • Prometheus 서버에서 발생하는 경고(alert)를 처리하고, 이메일, PagerDuty, Slack 등 다양한 방법으로 알림을 보낼 수 있습니다.
  • Grafana:
    • Prometheus 데이터를 시각화하기 위해 자주 사용되는 대시보드 도구입니다.
    • Grafana를 사용하면 Prometheus에서 수집한 메트릭 데이터를 대시보드 형태로 시각화할 수 있습니다.

 

Actuator 보안

  • 엔드포인트 보호
    • actuator 접근 포트만 다른 포트로 설정하여 보호 할 수 있습니다.
    • Spring Security를 사용하여 민감한 엔드포인트에 접근 제어를 설정할 수 있다.
# 애플리케이션의 기본 포트를 8080으로 설정
server.port=8080

# Actuator 엔드포인트를 19090 포트에서 서비스하도록 설정
management.server.port=19090




import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
            .antMatchers("/actuator/**").authenticated()
            .and()
            .httpBasic();
    }
}

 

coopang 프로젝트에 적용 방법

 

1. http://localhost:9090

docker run -d --name=prometheus -p 9090:9090 -v 파일경로/prometheus.yml:/etc/prometheus/prometheus.yml prom/prometheus

도커로 프로메테우스:9090 를 실행 했기 때문에

http://localhost:9090에서 전체 서버의 프로메테우스 매트릭스를 확인할 수 있다.

 

 

2. application.yml prometheus 추가

eureka, gateway, user 서버의 application.yml 에 아래를 추가해라

management:
    endpoints:
        web:
            exposure:
                include: prometheus
    prometheus:
        metrics:
            export:
                enabled: true

 

 

3. prometheus.yml 생성

Prometheus가 모니터링할 타겟과 기타 설정을 정의하는 설정 파일(prometheus.yml)을 생성 해야 함

global:
    scrape_interval: 15s  # 모든 타겟의 기본 스크랩 간격

scrape_configs:
    - job_name: 'eureka'
      metrics_path: '/actuator/prometheus'
      static_configs:
          - targets: ['host.docker.internal:19090']  # Eureka 애플리케이션

    - job_name: 'gateway'
      metrics_path: '/actuator/prometheus'
      static_configs:
          - targets: ['host.docker.internal:19091']  # Gateway 애플리케이션

    - job_name: 'user'
      metrics_path: '/actuator/prometheus'
      static_configs:
          - targets: ['host.docker.internal:19092']  # User 애플리케이션

 

 

 

 

 

3개의 서버

 

 

프로메테우스에서 저렇게 3개의 서버가 up으로 뜨는게 간단하지 않았다

 

 

 

 

 

1. 로키 로그백을 설정했기때문에 user 서버에서 나는 오류가 보이지 않았다.

 

이를 보기 위해서 prometheus.yml 수정을 해줘야했다.

<configuration>
<!-- Console Appender: 콘솔로 로그 출력 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
	<encoder>
		<pattern>%d{yyyy-MM-dd HH:mm:ss} %-5level [%thread] %logger{36} - %msg%n</pattern>
	</encoder>
</appender>

<!-- Loki Appender: Loki로 로그 전송 -->
<appender name="LOKI" class="com.github.loki4j.logback.Loki4jAppender">
	<http>
		<url>http://localhost:3100/loki/api/v1/push</url>
	</http>
	<format>
		<label>
			<pattern>app=my-app,host=${HOSTNAME}</pattern>
		</label>
		<message class="com.github.loki4j.logback.JsonLayout" />
	</format>
</appender>

<!-- Root Logger: 두 개의 Appender를 모두 사용 -->
<root level="DEBUG">
	<appender-ref ref="CONSOLE" />  <!-- 콘솔로 출력 -->
	<appender-ref ref="LOKI" />     <!-- Loki로 전송 -->
</root>
</configuration>

 

 

2. 콘솔에서 오류가 보이게 되니 다른 오류를 해결 했다

// validation
		implementation 'org.springframework.boot:spring-boot-starter-validation'

이게 없어서 오류남

 

 

 

 

3. 스프링 시큐리티가 나를 쉽게 해주지 않았다

스프링 시큐리티를 쓸거라서 build.gradle에 추가해놨더니 자꾸 로그인 페이지로 나를 보내내

 

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)  적용해놔도

app에 무시한다고 해도 추가하라고 한다

@SpringBootApplication(exclude = SecurityAutoConfiguration.class) // Spring Security 인증 기능 제외
public class UserApplication {

    public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
    }

}

 

 

에러 내용

org.springframework.beans.factory.nosuchbeandefinitionexception: 
no qualifying bean of type 
'org.springframework.security.config.annotation.web.builders.httpsecurity'
available: expected at least 1 bean which qualifies as autowire candidate. 
dependency annotations: {}

 

 

그래서 아래처럼 다 인증 안함으로 코드를 추가했다.

이제야 로그인 페이지 안뜨네 휴!

@Configuration
@EnableWebSecurity // Spring Security 지원을 가능하게 함
public class WebSecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // CSRF 설정
        http.csrf((csrf) -> csrf.disable());

        http.authorizeHttpRequests((authorizeHttpRequests) ->
                authorizeHttpRequests
                        .anyRequest()
                        .permitAll());

        return http.build();
    }
}

 

 

그럼 이제 프로메테우스를 그나파다에 적용해볼까?

'Today I Learned' 카테고리의 다른 글

grafana slack 연동  (0) 2024.09.14
Grafana  (0) 2024.09.14
docker-compose.yml 네트워크 만든 후 실행 방법  (0) 2024.09.13
멀티모듈 프로젝트 설정  (0) 2024.09.12
쿠팡 프로젝트를 설계하면서..  (0) 2024.09.05