Prometheus alertmanager

2023. 8. 31. 18:54·Monitoring

Prometheus alert rule 추가

prometheusRules 라는 Custom resource로 정의 할 수 있습니다.

Custom resource는 자체적으로 만들어 내거나, helm values에서 additionalPrometheusRulesMap 에 정의하여 prometheus 세팅 시 함께 만들도록 할 수 있습니다.

prometheus rules로 alert rule과 recording rule을 정의할 수 있습니다. Alert rule은 말그대로 알람을 위한 룰이고, recording rule은 기존 metric을 이용하여 새로운 metric을 만들어 낼 때 사용하는 것입니다.

 

Custom resource 생성

(예시는 그룹 2개, 룰 4개만 적었고, 실제로 테스트 할 때에는 총 그룹 9개, 룰 76개를 추가해서 테스트했습니다.)

rule selector 확인

먼저, prometheus spec에서 prometheus rule selector 부분을 확인해서 만약 rule selector가 활성화되어 있는 경우에는 그에 맞는 label을 추가해야 합니다.

 

helm values에서 확인할 때는 prometheus.prometheusSpec 의 ruleNamespaceSelector 와 ruleSelectorNilUsesHelmValues , ruleSelector 을 보면 됩니다.

 

kube-prometheus-stack에서 default values에는 helm values를 기반으로 생성되는 라벨을 포함해야만 prometheusRule이 prometheus에 적용됩니다.

따라서, 라벨이나 네임스페이스 상관 없이 모든 prometheus rule을 적용하도록 하려면 helm value에 아래 내용이 추가되어야 합니다.

prometheus:
	prometheusSpec:
    ruleSelectorNilUsesHelmValues: false

rule selector 적용 여부는 prometheus라는 crd를 기반으로 생성된 custom resource에서도 확인 할 수 있습니다.

 

생성 방법

아래 코드처럼 PrometheusRule 을 정의한 파일을 생성하고 kubectl apply -f <파일명> 으로 리소스를 생성합니다.

apiVersion: monitoring.coreos.com/v1
kind: PrometheusRule
metadata:
  labels:
    app: kube-prometheus-stack
    tenant: test
  name: test-prometheus-alert-rule
  namespace: prometheus
spec:
  groups:
  - name: node-cpunmemory
    rules:
    - alert: HostOutOfMemory
      expr: node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes * 100 < 10
      for: 2m
      labels:
        tenant: test
        severity: warning
      annotations:
        summary: Host out of memory (instance {{ $labels.node }})
        description: "Node memory is filling up (< 10% left)"
    - alert: HostMemoryUnderMemoryPressure
      expr: rate(node_vmstat_pgmajfault[1m]) > 1000
      for: 2m
      labels:
        tenant: test
        severity: warning
      annotations:
        summary: Host memory under memory pressure (instance {{ $labels.node }})
        description: "The node is under heavy memory pressure. High rate of major page faults"
	- name: node-disknnetwork
    rules:
    - alert: HostUnusualNetworkThroughputIn
      expr: sum by (instance) (rate(node_network_receive_bytes_total[2m])) / 1024 / 1024 > 100
      for: 5m
      labels:
        tenant: test
        severity: warning
      annotations:
        summary: Host unusual network throughput in (instance {{ $labels.node }})
        description: "Host network interfaces are probably receiving too much data (> 100 MB/s)"
    - alert: HostUnusualNetworkThroughputOut
      expr: sum by (instance) (rate(node_network_transmit_bytes_total[2m])) / 1024 / 1024 > 100
      for: 5m
      labels:
        tenant: test
        severity: warning
      annotations:
        summary: Host unusual network throughput out (instance {{ $labels.node }})
        description: "Host network interfaces are probably sending too much data (> 100 MB/s)"

 

Helm values를 통한 생성

생성 방법

아래 코드처럼 helm의 values 파일에 내용을 추가하여 helm install | helm upgrade 하여 생성합니다.

아래 코드로 테스트 결과, kube-prometheus-stack-test-rules 라는 이름의 custom resource가 생성되었습니다.

additionalPrometheusRulesMap:
  test-rules:
    groups:
      - name: node-cpunmemory
        rules:
        - alert: HostOutOfMemory
          expr: node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes * 100 < 10
          for: 2m
          labels:
            tenant: test
            severity: warning
          annotations:
            summary: Host out of memory (instance {{ $labels.node }})
            description: "Node memory is filling up (< 10% left)"
        - alert: HostMemoryUnderMemoryPressure
          expr: rate(node_vmstat_pgmajfault[1m]) > 1000
          for: 2m
          labels:
            tenant: test
            severity: warning
          annotations:
            summary: Host memory under memory pressure (instance {{ $labels.node }})
            description: "The node is under heavy memory pressure. High rate of major page faults"
      - name: node-disknnetwork
        rules:
        - alert: HostUnusualNetworkThroughputIn
          expr: sum by (instance) (rate(node_network_receive_bytes_total[2m])) / 1024 / 1024 > 100
          for: 5m
          labels:
            tenant: test
            severity: warning
          annotations:
            summary: Host unusual network throughput in (instance {{ $labels.node }})
            description: "Host network interfaces are probably receiving too much data (> 100 MB/s)"
        - alert: HostUnusualNetworkThroughputOut
          expr: sum by (instance) (rate(node_network_transmit_bytes_total[2m])) / 1024 / 1024 > 100
          for: 5m
          labels:
            tenant: test
            severity: warning
          annotations:
            summary: Host unusual network throughput out (instance {{ $labels.node }})
            description: "Host network interfaces are probably sending too much data (> 100 MB/s)"

생성 결과

아래와 같이 prometheus에 접속하여 status/rules 에서 rule이 추가된 것을 확인할 수 있습니다.

 

마찬가지로, Grafana에 접속하여 Alerting/Alert rules 에서도 추가된 rule을 확인할 수 있습니다.

 

그러나, prometheus alertmanager UI에서는 현재 firing 상태인 Alert만 확인할 수 있습니다.

 

Prometheus alertmanager configuration 정의

💡 https://prometheus.io/docs/alerting/latest/configuration/ 위 링크를 참조하여 configuration 양식을 정의할 수 있습니다. 이 문서는 slack에 알람 전송을 기준으로 작성했습니다.

 

💡 alertmanagerConfig는 prometheusRule과는 달리 lint를 하지 않기 때문에 문법상 오류가 있는 경우 prometheus-operator의 log를 통해 error를 확인하는 것이 좋습니다.

 

alertmanagerConfig라는 Custom resource + secret 으로 정의 할 수 있습니다.

혹은 helm values에서 alertmanager.config에 정의하여 prometheus 세팅 시 해당 config로 적용되도록 하는 것도 가능합니다. (이 경우에는 alertmanager의 default secret에 config가 적용됩니다.)

Custom resource + secret으로 생성할 때, secret은 slack api url을 정의하기 위해 필요했습니다. 여기서의 secret과 helm으로 적용할 때 변경되는 secret은 다릅니다.

 

다른 type의 receiver를 적용한다면, kubectl explain alertmanagerconfig.spec.receivers 명령어를 통해 어떤 리소스가 더 필요한 지 확인 할 수 있습니다.

 

Custom resource, Secret 생성

Alertmanager selector 확인

kube-prometheus-stack의 default value는 따로 select 조건이 활성화되어 있지 않기 때문에, 추가 변경사항 없이도 alertmanagerConfig와 secret을 생성하면 바로 적용이 됩니다.

만약 select 조건을 추가하고 싶다면 helm values의 alertmanager 에서 alertmanagerConfigSelector 에 정의할 수 있습니다.

생성 방법

아래 코드처럼 AlertmanagerConfig 와 Secret을 정의한 파일을 생성하고 kubectl apply -f <파일명> 으로 리소스를 생성합니다.

이때, 변수명이 alertmanager의 configuration과 조금 다르다는 것을 주의하여 작성해야 합니다.

ex) group_by → groupBy , slack_config → slackConfigs

apiVersion: monitoring.coreos.com/v1alpha1
kind: AlertmanagerConfig
metadata:
  name: config-example
  namespace: prometheus
  labels:
    alertmanagerConfig: example
spec:
  route:
    groupBy: ['tenant']
    groupWait: 30s
    groupInterval: 5m
    repeatInterval: 12h
    receiver: 'test-slack'
  receivers:
  - name: 'test-slack'
    slackConfigs:
    - channel: 'slackbot_test'
      apiURL:
        key: test_slack
        name: config-example
      sendResolved: true
---
apiVersion: v1
data:
  test_slack: aHR0cHM6Ly9obhgjhjfdghnfhj2TkhwdUg2S3RaaUM2M2U2Cg==
kind: Secret
metadata:
  labels:
    alertmanagerConfig: example
  name: config-example
  namespace: prometheus
type: Opaque

 

Helm values를 통한 생성

생성 방법

아래 코드처럼 helm의 values 파일에 내용을 추가하여 helm install | helm upgrade 하여 생성합니다.

alertmanager:
  config:
    route:
      group_by: ['tenant']
      group_wait: 30s
      group_interval: 5m
      repeat_interval: 12h
      receiver: 'test-slack'
      routes:
      - receiver: 'test-slack'
        matchers:
          - namespace="prometheus"
    receivers:
    - name: 'test-slack'
      slack_configs:
      - channel: 'slackbot_test'
        api_url: '<https://hooks.slack.com/services/T03BTFC/B04KD8KF/H3NdNZiC63e6>'
        send_resolved: true

생성 결과

Alertmanager UI의 Status에서 추가된 configuration을 확인 할 수 있습니다.

Custom resource를 생성해서 적용한 것과 helm value를 이용하여 적용한 것은 receiver 이름 등이 다를 수 있습니다. 아래 결과는 custom resource를 생성해서 적용한 것의 결과입니다.

 

추가한 configuration을 기반으로 alert를 발생시켜서 slack으로 전송되는 것을 확인 할 수 있습니다.

 

Prometheus alert rule 예시

https://github.com/samber/awesome-prometheus-alerts/blob/master/_data/rules.yml

위 링크는 prometheus alert rule 정의를 여러 가지 application의 metric을 기반으로 여러 사용자들이 함께 정의한 것입니다.

 

'Monitoring' 카테고리의 다른 글

Metric Join  (0) 2023.09.04
LGTM 특장점  (0) 2023.09.04
Prometheus를 push 방식으로 쓰기  (0) 2023.08.31
Grafana-agent for uploading PrometheusRule to mimir  (0) 2023.08.31
Grafana mimir overview  (0) 2023.08.29
'Monitoring' 카테고리의 다른 글
  • Metric Join
  • LGTM 특장점
  • Prometheus를 push 방식으로 쓰기
  • Grafana-agent for uploading PrometheusRule to mimir
joeunvit
joeunvit
  • joeunvit
    joeun
    joeunvit
  • 전체
    오늘
    어제
    • 분류 전체보기 (28)
      • AWS (1)
      • Kubernetes (2)
      • IT Terminology (1)
      • Tools (1)
      • Monitoring (20)
      • kubeflow (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
    • IT Terminology
    • AWS
    • Kubernetes
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    ingress-nginx #validatingwebhook
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
joeunvit
Prometheus alertmanager
상단으로

티스토리툴바