0

Lab 8.2 - Thiết lập Alerting với Prometheus và Alertmanager

3. Alert Rule là gì?

Alert Rule là tập hợp các điều kiện được viết bằng PromQL.

Prometheus sẽ thực hiện các bước sau:

  1. Thu thập Metrics.
  2. Chạy các Alert Rule theo chu kỳ.
  3. Nếu biểu thức PromQL trả về kết quả và duy trì trong khoảng thời gian for, Alert sẽ chuyển sang trạng thái Firing.
  4. Gửi Alert tới Alertmanager.

Ví dụ:

CPU > 80%
↓
duy trì 5 phút
↓
Alert Firing
↓
Alertmanager
↓
Email / Slack

3.1 Cấu trúc một Alert Rule

Một Alert Rule thường có cấu trúc như sau:

groups:
- name: kubernetes-alerts
  rules:
  - alert: HighCPUUsage
    expr: ...
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: ...
      description: ...

Trong đó:

Thuộc tính Ý nghĩa
alert Tên Alert
expr Biểu thức PromQL
for Điều kiện phải duy trì trong bao lâu
labels Thông tin bổ sung để phân loại Alert
annotations Nội dung hiển thị trong Alertmanager và Email

3.2 Tạo file Alert Rules

Trong Lab này, chúng ta sẽ quản lý toàn bộ Alert trong một file.

Tạo file:

monitoring/alert-rules.yml

Alert 1 - Ứng dụng không còn phản hồi

Đây là Alert quan trọng nhất.

Nếu Prometheus không còn scrape được Metrics của ứng dụng, rất có thể:

  • Pod bị Crash
  • Ứng dụng bị treo
  • Service lỗi
  • Network gặp sự cố

Thêm Rule:

groups:
- name: todo-alerts
  rules:
  - alert: TodoApiDown
    expr: up{job="todo-api"} == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: Todo API is down
      description: Prometheus cannot scrape metrics from Todo API for more than 1 minute.

Giải thích PromQL

up{job="todo-api"} == 0

Metric:

up

được Prometheus tự sinh ra.

Giá trị:

1

nghĩa là:

Prometheus scrape thành công.

Giá trị:

0

nghĩa là:

Prometheus không thể kết nối tới endpoint.

Đây là Alert phổ biến nhất trong mọi hệ thống Prometheus.


Alert 2 - Pod Restart liên tục

Pod Restart nhiều lần thường là dấu hiệu của:

  • CrashLoopBackOff
  • Out Of Memory
  • Lỗi ứng dụng
  • Sai cấu hình

Thêm Rule:

  - alert: PodRestartTooManyTimes
    expr: increase(
      kube_pod_container_status_restarts_total{
      namespace="todo-app"
      }[5m]) > 3
    for: 2m
    labels:
      severity: warning
    annotations:
      summary: Pod restarted too many times
      description: A Pod in namespace todo-app restarted more than three times within five minutes.

Giải thích PromQL

Metric:

kube_pod_container_status_restarts_total

được cung cấp bởi:

kube-state-metrics

Metric này là Counter.

Ví dụ:

10
↓
11
↓
12

Hàm:

increase(...[5m])

tính số lần Counter tăng trong 5 phút gần nhất.

Ví dụ:

10
↓
14

Kết quả:

4 lần restart

Nếu:

> 3

Alert sẽ được kích hoạt.


Alert 3 - Memory sử dụng quá cao

Nếu Pod sử dụng gần hết Memory được cấp, Kubernetes có thể thực hiện OOMKill.

Rule:

  - alert: HighMemoryUsage
    expr: (
      container_memory_working_set_bytes{
      namespace="todo-app",
      container!="",
      image!=""
      }
      /
      container_spec_memory_limit_bytes{
      namespace="todo-app",
      container!="",
      image!=""
      }
    ) > 0.9
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: Pod memory usage is above 90%
      description: Memory usage exceeded 90 percent for more than five minutes.

Giải thích

Biểu thức:

Memory đang sử dụng
───────────────
Memory Limit

Nếu:

95%

trong:

5 phút

Alert sẽ chuyển sang Firing.


Alert 4 - HTTP 5xx tăng bất thường

Sau Lab 7, chúng ta đã có:

http_server_requests_seconds_count

Từ Metric này có thể phát hiện số lượng HTTP 5xx.

Rule:

  - alert: HighHttp5xxRate
    expr: |
      sum(
        rate(
          http_server_requests_seconds_count{
            application="todo-api",
            status=~"5.."
          }[5m]
        )
      ) > 1
    for: 2m
    labels:
      severity: critical
    annotations:
      summary: High HTTP 5xx rate
      description: Todo API is returning more than one HTTP 5xx response per second.

Giải thích

Biểu thức:

rate(http_server_requests_seconds_count[5m])

tính:

Request / second

Sau đó chỉ lấy:

status=500

501

502

503

504

Nếu:

>1 lỗi mỗi giây

trong:

2 phút

Alert sẽ được gửi.


Alert 5 - Request Latency tăng cao

CPU thấp không đồng nghĩa ứng dụng hoạt động tốt.

Nếu Request Latency tăng mạnh, rất có thể:

  • Database chậm.
  • External API phản hồi chậm.
  • Deadlock.
  • Thread Pool bị đầy.

Rule:

  - alert: HighRequestLatency
    expr: |
      (
        rate(
          http_server_requests_seconds_sum{
          application="todo-api"
          }[5m]
        )
      )
      /
      (
        rate(
          http_server_requests_seconds_count{
          application="todo-api"
          }[5m]
        )
      )
      > 0.5
    for: 5m
    labels:
      severity: warning
    annotations:
      summary: High request latency
      description: Average request latency is higher than 500 ms.

Giải thích

Latency trung bình được tính bằng:

Tổng thời gian xử lý
──────────────────
Tổng số Request

Nếu kết quả:

0.5

nghĩa là:

500 ms

3.3 Hoàn chỉnh file Alert Rule

Sau khi thêm các Rule trên, file monitoring/alert-rules.yml sẽ gồm một nhóm Alert dành cho ứng dụng Todo.

Các Alert bao gồm:

Alert Mục đích
TodoApiDown Phát hiện ứng dụng không còn phản hồi
PodRestartTooManyTimes Phát hiện Pod Restart bất thường
HighMemoryUsage Phát hiện Pod sử dụng quá nhiều Memory
HighHttp5xxRate Phát hiện API trả về nhiều lỗi HTTP 5xx
HighRequestLatency Phát hiện ứng dụng phản hồi chậm

Đây là những Alert cơ bản nhưng rất phổ biến trong hầu hết các hệ thống Production.


4. Prometheus quản lý Alert Rule như thế nào?

Prometheus sử dụng file cấu hình:

prometheus.yml

Trong file này có một phần quan trọng:

rule_files:
  - /etc/config/alert-rules/*.yaml

rule_files khai báo nơi Prometheus tìm kiếm các Alert Rule.

Khi Prometheus khởi động, nó sẽ:

  1. Đọc file prometheus.yml.
  2. Tìm các file được khai báo trong rule_files.
  3. Load các Alert Rule.
  4. Bắt đầu đánh giá các biểu thức PromQL theo chu kỳ.

Luồng hoạt động:

alert-rules.yaml

        |
        ▼

Prometheus Config

        |
        ▼

Prometheus Rule Engine

        |
        ▼

Evaluate PromQL

        |
        ▼

Alertmanager

Kiểm tra Helm Chart đang sử dụng

Trong Lab trước, chúng ta đã triển khai:

helm list -n monitoring

Kết quả:

NAME          NAMESPACE
grafana       monitoring
prometheus    monitoring

Chart:

prometheus-community/prometheus

Đây không phải là:

kube-prometheus-stack

nên chúng ta sẽ không sử dụng:

PrometheusRule

hoặc:

kubectl apply -f prometheusrule.yaml

Cách đó chỉ dành cho Prometheus Operator.

Với chart hiện tại, chúng ta sẽ quản lý Alert Rule thông qua:

serverFiles

trong Helm values.


Bước 1. Tạo file Alert Rule

Tạo thư mục:

mkdir monitoring

Tạo file:

touch monitoring/alert-rules.yml

Nội dung:

groups:

- name: todo-alerts

  rules:

  - alert: TodoApiDown

    expr: up{job="todo-api"} == 0

    for: 1m

    labels:

      severity: critical

    annotations:

      summary: Todo API is down

      description: Prometheus cannot scrape Todo API.

Đây là Alert Rule đầu tiên.

Ý nghĩa:

Nếu:

up{job="todo-api"} == 0

trong:

for: 1m

thì Alert sẽ được kích hoạt.


Bước 2. Kiểm tra Prometheus values hiện tại

Trước khi chỉnh sửa, kiểm tra cấu hình hiện tại:

helm get values prometheus \
-n monitoring

Hiện tại bạn đang có:

extraScrapeConfigs: |
  - job_name: todo-api

Đây là cấu hình của Lab 7 để Prometheus scrape Spring Boot Actuator.

Chúng ta cần giữ nguyên cấu hình này.


Bước 3. Cập nhật file prometheus-values.yaml

Mở:

prometheus-values.yaml

Hiện tại:

extraScrapeConfigs: |
  - job_name: todo-api

    metrics_path: /actuator/prometheus

    static_configs:

      - targets:

          - todo-backend-service.todo-app.svc.cluster.local:8080

Thêm phần:

serverFiles:

  alert-rules.yml: |

    groups:

    - name: todo-alerts

      rules:

      - alert: TodoApiDown

        expr: up{job="todo-api"} == 0

        for: 1m

        labels:

          severity: critical

        annotations:

          summary: Todo API is down

          description: Prometheus cannot scrape Todo API.

Sau khi hoàn chỉnh:

extraScrapeConfigs: |
  - job_name: todo-api

    metrics_path: /actuator/prometheus

    static_configs:

      - targets:

          - todo-backend-service.todo-app.svc.cluster.local:8080


serverFiles:

  alert-rules.yml: |

    groups:

    - name: todo-alerts

      rules:

      - alert: TodoApiDown

        expr: up{job="todo-api"} == 0

        for: 1m

        labels:

          severity: critical

        annotations:

          summary: Todo API is down

          description: Prometheus cannot scrape Todo API.

Bước 4. Khai báo Rule File cho Prometheus

Bây giờ Prometheus cần biết file:

alert-rules.yml

nằm ở đâu.

Thêm tiếp:

serverFiles:

  prometheus.yml:

    rule_files:

      - /etc/config/alert-rules.yml

Tuy nhiên cần chú ý.

Trong chart prometheus-community/prometheus, prometheus.yml mặc định đã có rất nhiều cấu hình.

Vì vậy không nên ghi đè toàn bộ file.

Cách an toàn hơn là sử dụng:

serverFiles:
  prometheus.yml:

với đầy đủ nội dung hiện tại.

Để tránh mất cấu hình scrape của Lab 7.


Cách đơn giản hơn (khuyến nghị)

Với chart bạn đang dùng, cách tốt hơn là dùng:

serverFiles:
  alerts:

Ví dụ:

serverFiles:
  alerts:
    todo-alerts.yml: |
      groups:
      - name: todo-alerts
        rules:
        - alert: TodoApiDown
          expr: up{job="todo-api"} == 0
          for: 1m
          labels:
            severity: critical
          annotations:
            summary: Todo API is down

Chart sẽ tự mount file Alert vào Prometheus.


Bước 5. Upgrade Helm

Sau khi chỉnh sửa:

helm upgrade prometheus \
prometheus-community/prometheus \
-f prometheus-values.yaml \
-n monitoring

Kết quả:

Release "prometheus" has been upgraded

Bước 6. Kiểm tra Prometheus Pod

Kiểm tra:

kubectl get pods -n monitoring

Ví dụ:

prometheus-server-xxxx   2/2   Running

Nếu Pod restart:

kubectl describe pod \
prometheus-server-xxxx \
-n monitoring

Kiểm tra lỗi mount config.


Bước 7. Kiểm tra Alert Rule trong Prometheus UI

Port-forward:

kubectl port-forward \
svc/prometheus-server \
9090:80 \
-n monitoring

Truy cập:

http://localhost:9090

Vào:

Status
    ↓
Rules

Bạn sẽ thấy:

todo-alerts

TodoApiDown

Bước 8. Kiểm tra trạng thái Alert

Vào:

Alerts

Ban đầu:

TodoApiDown

State:
Inactive

Điều này đúng.

Vì hiện tại:

up{job="todo-api"}

đang bằng:

1

nghĩa là Backend vẫn hoạt động.


Bước 9. Kiểm tra bằng PromQL

Trong Prometheus:

Chạy:

up{job="todo-api"}

Kết quả:

1

Có nghĩa:

Prometheus
    |
    |
    ▼
todo-backend-service
    |
    |
    ▼
/actuator/prometheus

OK

Bước 10. Test Alert Rule

Để thử Alert, tạm thời làm cho Backend không scrape được.

Ví dụ scale Deployment về 0:

kubectl scale deployment todo-backend \
--replicas=0 \
-n todo-app

Sau khoảng 1 phút:

Prometheus:

Alerts

sẽ thấy:

TodoApiDown

Pending

Sau khi đủ:

for: 1m

sẽ chuyển:

Firing

Sau đó Alert sẽ được gửi sang Alertmanager.



All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.