프로메테우스 PromQL

프로메테우스 가이드북
이민석's avatar
Jun 06, 2024
프로메테우스 PromQL

프로메테우스 가이드북은 A to Z Metnros (Udemy) — Prometheus | The Complete Hands-On for Monitoring & Alerting를 듣고 작성한 가이드북입니다.

가이드북의 전체 목차 및 인덱싱은 프로메테우스 가이드북 — 소개 페이지를 참고해주세요.

PromQL

Promethues에서는 PromQL을 이용해서 TSDB(Time Series Database)를 제어할 수 있습니다.

PromQL은 단순히 시계열을 선택하는 것 뿐만 아니라 복잡한 쿼리 집계 및 분석과 관련한 기능을 제공합니다.

자료형(Data Type)

PromQL에서는 다음과 같은 자료형들을 제공하고 있습니다.

  1. Instant Vector

  2. Range Vector

  3. Scalar

  4. String

Instance Vector

  • A set of time series containing a single sample for each time series, all sharing the same timestamp

Prometheus UI에서 prometheus_http_requests_total을 조회하면 각각의 HTTPS ENDPOINT에 대한 요청값 통계를 볼 수 있습니다.

각각의 요청값들 하나하나가 Instance Vector라고 할 수 있습니다.

Range Vector

  • A set of time series containing a range of data points over time for each time series.

Prometheus UI에서 prometheus_http_requests_total[1m]을 조회하면 각각의 HTTPS ENDPOINT에 대한 요청값의 1m에 대한 범위값을 조회할 수 있습니다.

각각의 요청값들 하나하나가 Instance Vector라고 할 수 있습니다.

Scalar, String

  • Scalar is a simple numeric floating point vaule.

String is a simple string value; currently unused.

Scalar, String은 각각 15.21, hello와 같은 형태의 값입니다.

그 중에서 String은 Prometheus Official Documents따르면, 많이 사용되지 않는다고 알려져 있습니다.

Selectors & Matchers

특정 매트릭에 실행되는 PromQL 질의는 매우 광범위한 조회를 실행합니다. 따라서 유용한 정보의 조회를 위해서 그 대상과 범위를 제한할 필요가 있습니다.

이러한 기능을 제공해주는 것이 selectormatcher입니다.

Selector 알아보기

  1. 기본 PromQL

  2. 단일 Selector 사용

  3. 복수 Selector 사용

기본 PromQL

process_cpu_seconds_total 을 통해서 사용자의 CPU 관련 매트릭을 조회할 수 있습니다.

예를 들어 다음과 같이 Element=Value 을 반환 받을 수 있습니다.

Elements

Value

process_cpu_seconds_total{

instance=”localhost:9090”,

job=”prometheus”

}

28.32

process_cpu_seconds_total{

instance=”localhost:9100”,

job=”prometheus”

}

0.29

단일 Selector 사용

혹은 selector를 활용한 process_cpu_seconds_total{job=”node_exporter”} 이런 구문으로, 더욱 구체적인 Elements=Value 를 반환 받을 수 있습니다.

Elements

Value

process_cpu_seconds_total{
instance=”localhost:9090”,
job=”node_exporter”
}

1.04

복수 Selector 사용

혹은 복수의 selector를 활용한 process_cpu_seconds_total{job=”node_exporter”, instance=”localhost:8080”} 과 같은 구문을 사용할 수도 있을 것입니다.

하지만 매칭되는 대상이 없는 경우에는 no_data를 반환할 것입니다.

Matcher 알아보기

Matcher는 selector와 함께 사용하며, 다양한 조건으로 PromQL에서 작동합니다.

  1. Equality Matchers =
    process_cpu_seconds_total{job="node_exporter"}

  2. Negative Equality Matcher !=

    process_cpu_seconds_total{job!='“node_exporter”}

  3. Regular Expression Matcher =~

    prometheus_http_requests_total{handler=~”/api.*”}

  4. Negative Regular Expression Matchers !~

    prometheus_http_requests_total{handler!~”/api.*”

Selector, Matcher 활용

지금까지 Selector, Matcher를 사용하여 다양한 매트릭 정보를 조회하였습니다. 그리고 이 데이터들은 모두 Instant Vector 에 해당하는 값입니다.

저희는 다음과 같이 Range Vector를 조회할 수도 있을 것입니다.

proemtheus_http_requests_total{handler=~”/api.*’}[5m]

Operators

PromQL에는 2종류의 Operator가 존재합니다.

  • Binary Operators

    • Binary Operators는 두 피연산 대상들에 대한 지정된 계산을 진행하는 Operator입니다.

      • Arithmetic binary operator

      • Comparison binary operators

      • Logical/set binary operators

  • Aggregation Operators

    • Aggregation Operators는 수많은 집계 대상들을 합쳐서 집계 연산을 진행하는 Operator입니다.

Arithmetic Binary Operator

아래와 같이 6개의 Arithmetic Binary Operator가 존재합니다.

목적

연산자(Operator)

addition

+

substraction

-

multiplication

*

division

/

modulo

%

power/exponentitation

^

Arithmetic operator are the symbols that represent arithmetic math operations.

Binary arithmetic operators are defined between scalar/scalar, vector/scalar, vector/vectorvalue pairs.

e.g. node_memory_Active_bytes / 8

Comparison Binary Operators

아래와 같이 6개의 Comparison Binary Operators가 존재합니다.

목적

연산자(Operator)

equal

=

non-equal

!=

greater-than

>

less-than

<

greator-or-equal

>=

less-or-equal

<=

A comparison operator is a mathematical symbol which is used for comparison.

Comparison operators are defined between scalar/scalar, vector/scalar, vector/vector value pairs.

e.g. process_open_fds > 12

Logical/set Binary Operator

아래와 같이 3개의 Logical/set Binary Operator가 존재합니다.

목적

연산자(Operator)

intersection

and

union

or

complement

unless

The logical operators are used to combine simple relational expressions into more complex expressions.

Logical operators are defined only instant vector.

Aggregation Operators

아래와 같이 11개의 Aggregation Operators가 존재합니다.

목적

연산자(Operator)

calculate sum over dimensions

sum

select minimum over dimensions

min

select maximum over dimensions

max

calculate the average over dimensions

avg

calculate population standard deviation over dimensions

stddev

calculate population standard variance over dimensions

stdvar

count number of elements in the vector

count

count number of elements with the same value

count_values

smallest k elements by same value

bottomk

largest k elements by sample value

topk

calculate quantile over dimensions

quantile

Functions

프로메테우스에는 다양한 내장 함수(Built-in Function)이 있어서 다양한 매트릭 연산을 손쉽게 진행할 수 있습니다.

가장 대표적인 Aggreagtion Operators 외에도 Rate Functions, Predict Function, Time Functions, Transformation Functions, Vector Matching Function 등이 존재합니다.

Rate Function - rate()

rate() - calculates the per-second average rate of increase of the time series in the range vector

  1. Instance Vector 조회

    prometheus_http_request_total
  2. Range Vector 조회

    prometheus_http_request_total[1m]
  3. Rate(Range Vector) 조회

    rate(prometheus_http_request_total[1m])

Rate Function - irate()

irate() - calculates the instant rate of increase of the time series in the range vector

  1. Instance Vector 조회

    prometheus_http_request_total
  2. Range Vector 조회

    prometheus_http_request_total[1m]
  3. Rate(Range Vector) 조회

    irate(prometheus_http_request_total[1m])

Predict Function - change

시작부터 현재까지 node_exporter가 재시작한 횟수 조회하기

change(process_start_time_seconds{job="node_exporter"}[1h])

Predict Function - deriv

프로메테우스 서버(job=“prometheus”)의 물리적 메모리 사용량의 1시간 당 변화율 계산

deriv(process_resident_memory_bytes{job="prometheus"}[1h])

Predict Function - linear

노드 익스포터(job=“node_exporter”)에서 1시간 동안 메모리 사용량 데이터를 기반으로 2시간 후의 예상 메모리 사용량을 메가바이트(MiB) 단위로 예측

predict_linear(
   predict_linear(node_memory_MemFree_byes{job="node_exporter"}[1h],
   (2 * 60 * 60)/1024/1024
)

OverTime Function - (max|min|avg)_over_time

Aggreagtion Operators에서 배운 여러 연산자들을 *_over_time 앞에 붙여서 사용하는 것으로 각종 Time Function을 사용할 수 있습니다.

max_over_time(node_cpu_seconds_total[1h])
min_over_time(node_cpu_seconds_total[1h])
avg_over_time(node_cpu_seconds_total[1h])

Sort Function - sort, sort_desc

아래와 같이 정렬을 할 수도 있습니다.

sort(node_cpu_seconds_total)
sort_desc(node_cpu_seconds_total)

Time Function - time

아래와 같이 시간 정보를 손쉽게 활용할 수도 있습니다.

time() - process_start_time_seconds{job="node_exporter"}

day_of_week()
day_of_month()

Share article
RSSPowered by inblog