0

Lab 8.2 - Thiết lập Alerting - Alert Rule hoạt động thế nào?

Ở phần trước, chúng ta đã hoàn thành việc:

  • Làm quen với giao diện Alertmanager
  • Kiểm tra Prometheus đã kết nối tới Alertmanager.

1. 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

2. 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. 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:

  • Metric kube-state-metricsnà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ả là 4 lần restart >3 nên 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.

Thêm 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% trong5 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.

Thêm 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=5xx

Nếu >1 lỗi mỗi giây trong 2 phútthì 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.

Thêm 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


4. 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.

Nội dung file alert hoàn chỉnh:

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.

      - 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.

      - 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.

      - 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.

      - 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.

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.


Tổng kết

Đến thời điểm này, chúng ta mới chỉ tạo file Alert Rule trên máy tính.

Prometheus chưa biết đến các Rule này.

Trong phần tiếp theo, chúng ta sẽ:

  • Đưa file Alert Rule vào Prometheus.
  • Cập nhật cấu hình Helm.
  • Thực hiện helm upgrade.
  • Kiểm tra Prometheus đã nạp Alert Rule thành công hay chưa.
  • Quan sát Alert xuất hiện trong giao diện Prometheus.

Sau khi hoàn thành phần tiếp theo, Prometheus sẽ bắt đầu đánh giá các Alert Rule theo chu kỳsẵn sàng gửi cảnh báo tới Alertmanager khi phát hiện sự cố.


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí