Grafana에서 Alert 생성 (2) - 설치 및 설정

Installation

우선은 이미 다운로드 받아 둔 Istio를 쓰기 때문에 Istio 설치 폴더에 있는 것을 사용할 수도 있다.

cd istio-1.24.1/samples/addons
kubectl apply -f .

 

위 폴더에 들어가면 kiali, jaeger, loki, prometheus, grafana 설치 파일들이 있다.
설치를 해보았지만 버전은 최신이지만, 폴더명 samples처럼 말 그대로 가볍게 테스트해보는 용도의 설치 파일이었다.
Default로 설정된 dashboard들도 별로 없다. 그래서 helm chart로 설치하는 것이 낫다.

Add helm chart

helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo update

 

SMTP와 PV 설정을 위해서 설치를 할 때 helm install prometheus prometheus-community/kube-prometheus-stack -f ./smtp-values.yaml 이런 식으로 values값을 수정해 설치를 하려고 했는데 자꾸 에러가 난다.
그래서 helm repo에서 직접 설치 파일을 pull 받아서 values.yaml을 수정해서 설치하는 방법을 택했다.

> helm pull prometheus-community/kube-prometheus-stack --untar
> cd kube-proemtheus-stack
> ls
Chart.lock  Chart.yaml  charts  templates  values.yaml

 

여기 있는 values.yaml 파일을 수정한다.
이유는

  1. Email 알림 설정을 위해서 SMTP 설정이 필요하다.
  2. 처음에 설치를 하고 그 다음날 Grafana에 접속을 해보았더니 설정해놓았던 custom dashboard도 사라져서 Persistent Volume이 필요.
grafana:
  grafana.ini:
    smtp:
      enabled: "true"
      host: "gw.example.com:465"
      user: "cm@example.co.kr"
      password: "1234"
      skip_verify: "true"
      from_address: "cm@example.co.kr"
      from_name: "아이스크림몰"
  persistence:
    enabled: true
    accessModes:
      - ReadWriteOnce
    size: 10Gi
    storageClassName: default

 

namespace 생성

kubectl create ns monitoring

 

이 namespace에 istio-injection하면 동작하지 않는다. (위처럼 namespace만 생성한다.)

Prometheus와 Grafana 설치 (위 폴더에 있는 상태에서)

helm install prometheus . \
  --namespace monitoring \
  --set prometheus.prometheusSpec.serviceMonitorSelectorNilUsesHelmValues=false \
  --set prometheus.prometheusSpec.podMonitorSelectorNilUsesHelmValues=false \
    --set grafana.assertNoLeakedSecrets=false \
  -f ./values.yaml

 

위 설치 과정에서 3, 4번째줄은 개발자들이 대부분 설치시 false로 해놓는다. 이는 Prometheus가 labelling된 서비스모니터만 가져오게 된다. 이것을 true로하면 필요없는 서비스모니터도 전부 가져오려고 시도한다.
5번째 줄이 없으면 SMTP 패스워드를 K8s Secret으로 저장하라고 에러가 나는데 이 방법을 써도 설치 오류가 나서 일단 bypass시켰다.

PV가 설치되었는지 확인

 

k get pvc -n monitoring
NAME                 STATUS   VOLUME                                     CAPACITY   ACCESS MODES   STORAGECLASS   VOLUMEATTRIBUTESCLASS   AGE
prometheus-grafana   Bound    pvc-d4c212d3-d575-4df6-8c56-41e076c87ae6   10Gi       RWO            default        <unset>                 19s

 

Istio가 설치되어있으니 VirtualService로 외부 접속을 설정한다.

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
    name: grafana-vs
    namespace: monitoring
spec:
    hosts:
  - grafana.example.co.kr
    gateways:
  - istio-system/istio-gateway
    http:
  - route:
    - destination:
                host: prometheus-grafana.monitoring.svc.cluster.local
                port:
                    number: 80

 

Azure DNS에서도 record를 추가해준다

az network dns record-set a add-record \
  --resource-group azure_dns_group \
  --zone-name example.co.kr \
  --record-set-name "grafana" \
  --ipv4-address [Load Balancer IP] \
  --ttl 600

 

초기 admin password를 다음과 같이 조회할 수 있지만, 초기 패스워드는 무조건 prom-operator라고 보면 된다.

> kubectl --namespace monitoring get secrets prometheus-grafana -o jsonpath="{.data.admin-password}" | base64 -d ; echo
prom-operator

접속 후 바로 패스워드를 변경해준다.

Grafana data source

  • 왼쪽 메뉴 → Configuration > Data Sources
  • 오른쪽 위 → 'Add data source' > 여러 개 중 'Azure Monitor' 검색 > 선택
    (참고: 이는 Azure Monitor 서비스를 생성하는 것이 아니고, Azure Monitor는 Azure Subscription에 내재된 built-in service이다.)
  • 아래처럼 Azure CLI로 정보 조회

아래는 command 한 방에 위에서 필요한 모든 필요한 정보를 Azure CLI로 볼 수 있는 방법
one shot command

SUBSCRIPTION_ID=$(az account show --query "id" -o tsv)

az ad sp create-for-rbac \
  --name "GrafanaMonitorReader" \
  --role "Monitoring Reader" \
  --scopes /subscriptions/$SUBSCRIPTION_ID \
  --sdk-auth \
  --query "{subscriptionId:'$SUBSCRIPTION_ID', tenantId:tenant, clientId:appId, clientSecret:password}" \
  -o json

결과

{
  "clientId": "87x25a1f-976e-4784-8ee7-0000000000",
  "clientSecret": "XXr8Q~FB.LDOym78_axbZT9FxjNm-xmL_XXXXxxxx",
  "subscriptionId": "xx602b0c-a25e-4198-91f5-11xxxxxxxxx",
  "tenantId": "xx8ea633-d985-45c6-a078-7fc11111111",
  "activeDirectoryEndpointUrl": "https://login.microsoftonline.com",
  "resourceManagerEndpointUrl": "https://management.azure.com/",
  "activeDirectoryGraphResourceId": "https://graph.windows.net/",
  "sqlManagementEndpointUrl": "https://management.core.windows.net:8443/",
  "galleryEndpointUrl": "https://gallery.azure.com/",
  "managementEndpointUrl": "https://management.core.windows.net/"
}

맞는 값 입력 후 Save하고 dashboard를 새로 생성

Grafana Dashboard

Custom Dashboard를 만들고 싶은데 우선은 자동으로 scale-out이 되는 worker node을 개수를 모니터링하고 싶다.

 

우선 왼쪽 메뉴 'Explore'에 metric을 테스트 해 볼 수 있다.

여기에는 PromQL이라는 이름의 Prometheus Query Language이다.

kube_node_info

를 조회해보면 K8s node가 모두 보인다.

 

그렇다면 `count(kube_node_info)`로 노드 개수를 모니터링 할 수 있다.

 

왼쪽 메뉴 Dashboard로 와서 New dashboard > Add visualization

Worker Node Count

아래와 같이 설정

Database CPU usage

아래와 같이 panel을 새로 생성하면 Database의 CPU 사용률도 그래프 형태로 볼 수 있다.

 

Microsoft Teams 설정

Grafana 왼쪽 메뉴에 Alerting > Contact pointsCreate contant point를 눌러 위 Microsoft Teams를 선택하고, 앞 글에서 복사한 Webhook URL을 붙이면 된다.

 

Grafana Alert 설정

Grafana 좌측 메뉴에서 Alerting > Alert rules에서 

 

처음에 Reduce를 선택하고 B로 저장
Threshold로 만들고 C로 비교

C 값을 Alert condition으로 세팅해준다 (작은 글씨 클릭)

 

알림이 이메일로 가건, Slack으로 가건, Teams로 가건 

어떤 내용인지 아래와 같이 변수를 사용해 적용해준다.

Alert rule설정에서 6번에서 

6. Configure notification message

Database CPU 사용율 50% 초과

 

Description

The CPU usage for resource {{ $labels.resourceName }} is at {{ $values.B.Value }}%, exceeding our 50% threshold.

Node 개수에 대해서는 위와 마찬가지로 설정한다.

 

 

좌측 메뉴에서 Alerting > Alert rules에서 설정 확인

Slack

  • Slack에 로그인하고 채널을 새로 만든다. (예: 'grafana알림')
  • https://api.slack.com/apps 에 접속
    → 'Create New App' 클릭 → 'From Scratch' 선택 → App Name 입력 (예: 'Grafana Alerts'), Workspace 선택 → 'Create App' 클릭
  • 좌측메뉴에서 'Incoming Webhooks' 선택 → 우측 위에 'Activate Incoming Webhooks' on으로 토글 변경 → 'Add New Webhook to Workspace' 버튼 클릭 → 채널 선택 ('grafana알림') → 허용 클릭

Webhook URL을 복사한다.

https://hooks.slack.com/services/T08F8R7XXX/XXXF8TG3014/XxxxxXXXXxxxXXXXX

입력 칸이 3개 있지만, Recipient, Token은 안 넣고 Webhook URL 하나만 입력하면 된다.

 

 

  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유