Raspberry pi

라즈베리파이 쿠버네티스에 Prometheus + Grafana 올리기

[혜안] 2022. 8. 25. 12:04
728x90

라즈베리파이에 쿠버네티스 클러스터링 구성을 완료했습니다.

틈틈히 하다보니 약 한달이 걸렸네요.

2022.08.17 - [Raspberry pi] - 라즈베리파이 2대 쿠버네티스 클러스터링 구성 완료

 

라즈베리파이 2대 쿠버네티스 클러스터링 구성 완료

1차 목표는 완료했습니다. 기존에 라즈베리파이2에 잡다한 어플리케이션이 돌고 있었고, 라즈베리파이4 한대를 더 영입하면서 쿠버네티스 구성을 계획했었습니다. 오늘 부로 딱 3주되었는데, 이

viewise.tistory.com

 

그리고 쿠버네티스에 최적화된 모니터링 툴인 Prometheus를 도입했습니다.

뭐 따로 yaml 작성없이도 바로 적용할 수 있는 훌륭한 자료가 있어서 그대로 따라만 했습니다.

 

Prometheus 설치

https://devopscube.com/setup-prometheus-monitoring-on-kubernetes/

 

How To Setup Prometheus Monitoring On Kubernetes [Tutorial]

This Prometheus kubernetes tutorial will guide you through setting up Prometheus on a Kubernetes cluster for monitoring the Kubernetes cluster.

devopscube.com

 

사이트 내용은 클라우드에 구축했을 경우 등 몇가지 케이스와 내용설명이 있어 좀 장황한데,

딱 제가 실행한 커맨드만 나열하면 아래와 같습니다.

 

1. git에서 yaml 파일을 받아옵니다.

git clone https://github.com/bibinwilson/kubernetes-prometheus

 

2. 그리고 하나씩 실행합니다.

cd kubernetes-prometheus/

kubectl create namespace monitoring

kubectl create -f clusterRole.yaml

kubectl create -f config-map.yaml

kubectl create -f prometheus-deployment.yaml 

kubectl create -f prometheus-service.yaml --namespace=monitoring

설치 끝

 

다만, 2가지 선택지가 있습니다.

첫번째는, prometheus-deployment.yaml 를 실행하기 전에, 퍼시스턴스 볼륨을 설정할 지 결정해야 합니다. 기본으로 그냥 실행하면, Pod 내에 Prometheus 모니터링 이력이 기록되기 때문에, 만약 Pod가 재기동되면 그동안 쌓인 모니터링 이력은 사라집니다. 저는 이력이 별로 중요하지 않아 기본으로 실행했습니다.

두번째는, Prometheus 포털을 오픈하는 방법입니다. port forwading 등의 옵션이 있는데, 이것 또한 기본으로 실행했습니다. 기본은 NodePort로 오픈이고, 별다른 수정 없이, prometheus-service.yaml를 실행하면 됩니다.

 

그러면 아래와 같이 Prometeus 포털에 접근할 수 있습니다. 포트는 30000 이고, NoePort라 어느 노드의 IP든 30000포트로 접근이 됩니다.

하지만 모양이 별로 이쁘지 않아서 Grafana를 추가로 설치할 계획입니다. Grafana를 설치하면 Prometheus 포털은 들어올 일이 별로 없습니다.

 

Grafana 설치

https://devopscube.com/setup-grafana-kubernetes/

 

How To Setup Grafana On Kubernetes - Beginners Guide

This tutorial explains the Grafana setup on a Kubernetes cluster. You can create dashboards on Grafana for all the Kubernetes metrics through Prometheus.

devopscube.com

마찬가지로 사이트에서 안내하는대로 따라만 하면 쉽게 설치됩니다.

 

1. yaml 파일을 받아옵니다.

git clone https://github.com/bibinwilson/kubernetes-grafana.git

 

2. 그리고 실행합니다.

cd kubernetes-grafana

kubectl create -f grafana-datasource-config.yaml

kubectl create -f deployment.yaml

kubectl create -f service.yaml

설치 끝

 

마찬가지로 deployment.yaml을 실행하기 전에 퍼시스턴스 볼륨을 설정할 지 결정필요하긴 합니다.

사실 Prometheus의 CPU, Memory와 같은 이력 데이터는 날라가도 별로 상관이 없지만,

Grafana는 대시보드를 이래저래 설정한 정보이기 때문에, 날라가면 좀 피곤합니다. 다시 설정해야 하니까요.

 

그래서 Grafana의 경우는 퍼시스턴스 볼륨을 설정했습니다.

 

여기서부터는 위 사이트와는 별개로 제가 설정한 내용들입니다.

 

pv-grafana.yaml 생성

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-grafana
  namespace: monitoring
  labels:
    type: local
spec:
  capacity:
    storage: 1Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/dataspace/pv-grafana"

pvc-grafana.yaml 생성

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-grafana
  namespace: monitoring
spec:
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi

deployment.yaml 변경

apiVersion: apps/v1
kind: Deployment
metadata:
  name: grafana
  namespace: monitoring
spec:
  replicas: 1
  selector:
    matchLabels:
      app: grafana
  template:
    metadata:
      name: grafana
      labels:
        app: grafana
    spec:
      containers:
      - name: grafana
        image: grafana/grafana:latest
        ports:
        - name: grafana
          containerPort: 3000
        resources:
          limits:
            memory: "1Gi"
            cpu: "1000m"
          requests:
            memory: 500M
            cpu: "500m"
        volumeMounts:
          - mountPath: /var/lib/grafana
            name: grafana-storage
          - mountPath: /etc/grafana/provisioning/datasources
            name: grafana-datasources
            readOnly: false
      volumes:
        - name: grafana-storage
          persistentVolumeClaim:
            claimName: pvc-grafana
        - name: grafana-datasources
          configMap:
              defaultMode: 420
              name: grafana-datasources
      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: dataspace/grafana
                operator: In
                values:
                - "true"

설명을 좀 덧붙이면,

pv-grafana.yaml에서는, 로컬 볼륨 /dataspace/pv-grafana를 설정했습니다.

이 경로를 nas 공유로 설정하려 했으나 권한에서 난관에 부딪쳐 그냥 로컬볼륨으로 할당했습니다.

난관에 부딪친 내용은 삽질과정이라 별도 포스팅 예정입니다.

deployment.yaml에서는 volume 관련 내용과 affinity를 추가했습니다.

 

volume 설정 변경

      volumes:
        - name: grafana-storage
          persistentVolumeClaim:
            claimName: pvc-grafana

앞서 생성한 퍼시스턴스볼륨클레임을 연결하는 부분입니다. 원래는 empty 볼륨으로 되어 있습니다.

 

Affinity 설정 추가

      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
            - matchExpressions:
              - key: dataspace/grafana
                operator: In
                values:
                - "true

Grafana 설정을 저장할 DB를 로컬볼륨으로 지정한 관계로, 로컬볼륨을 가지고 있는 노드를 특정하기 위한 afinity입니다.

다른 노드에서 생성되면 곤란하니까요.

dataspace/grafana라는 라벨을 가진 노드에서만 Pod를 실행하라는 내용입니다.

그리고 dataspace/grafana 라벨을 raspberrypi4 노드에 생성해줍니다.

kubectl label nodes raspberrypi4 dataspace/grafana=true

 

마지막으로 raspberrypi4 에서는  /dataspace/pv-grafana 경로를 생성해줍니다.

mkdir -p /dataspace/pv-grafana

이렇게하면, Grafana Pod는 무조건 raspberrypi4 에서만 생성이되고, DB 파일은 /dataspace/pv-grafana 에 생성 및 보관됩니다.

 

이제 앞서 생성/변경한 yaml 파일을 실행하면 됩니다.

kubectl create -f pv-grafana.yaml

kubectl create -f pvc-grafana.yaml

kubectl -n monitoring delete deployment grafana

kubectl create -f deployment.yaml

 

Grafana 포털에 접근해봅니다.

포트는 32000, 최초 로그인 계정은 admin / admin 입니다.

NodePort로 설정했기 때문에, IP는 어떤 노드의 IP를 넣어도 상관없이 접근이 됩니다.

 

Prometheus 보나든 훨씬 디자인된 화면이 나옵니다.

좌측 아래 톱니 아이콘을 클릭하면, 설치했던 Prometheus가 이미 Data source로 지정되어 있습니다.

자동으로 된 것 같지만, 맨 처음 실행한 grafana-datasource-config.yaml 에서 설정한대로 적용된 것 뿐입니다.

 

대시보드는 직접 만들어도 되지만,

이미 너무 잘 만들어놓은 대시보드들을 전시하는 Grafana Dashboards 사이트가 있습니다.

그냥 import만 하면 쉽고 편하게 대시보드를 구성할 수 있습니다.

https://grafana.com/grafana/dashboards/

 

Dashboards

 

grafana.com

 

가장 많이 쓰이는게 Node Exporter Full 입니다.

그런데, 이걸 사용하기 위해서는 각 노드마다 node exporter를 설치해야 합니다.

살짝 귀찮아지려고 하는데요...

 

하지만 마찬가지로 잘 설명된 사이트가 있어서 그대로 따라했습니다. 쉽게 적용됩니다.

https://ooeunz.tistory.com/145

 

[Prometheus] Exporter 배포하기 (node-exporter, kube-state-metrics, actuator)

전 포스팅에서 봤듯이 prometheus는 exporter를 배포하지 않더라도 이미 많은 metric을 수집하고 있다는 것을 알 수 있었습니다. 특히 kubernetes 안에 배포된 container와 기본적인 node에 관한 metric도 수집되

ooeunz.tistory.com

 

아래는 위 사이트를 참고해서 제가 실행한 내용입니다.

node-exporter.yaml 작성

apiVersion: v1
kind: Service
metadata:
  annotations:
    prometheus.io/scrape: "true"
  name: node-exporter-http
  namespace: monitoring
  labels:
    app: node-exporter
spec:
  type: ClusterIP
  selector:
    app: node-exporter
  ports:
    - name: scrape
      port: 9100
      protocol: TCP
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-exporter
  namespace: monitoring
  labels:
    app: node-exporter
spec:
  selector:
    matchLabels:
      app: node-exporter
  template:
    metadata:
      labels:
        app: node-exporter
    spec:
      hostNetwork: true
      hostIPC: true
      hostPID: true
      containers:
        - name: node-exporter
          image: prom/node-exporter:v1.0.1
          imagePullPolicy: IfNotPresent
          args:
            - --path.procfs=/host/proc
            - --path.sysfs=/host/sys
          resources:
            requests:
              cpu: 10m
              memory: 100Mi
            limits:
              cpu: 100m
              memory: 100Mi
          ports:
            - name: scrape
              containerPort: 9100
              hostPort: 9100
          volumeMounts:
            - mountPath: /host/proc
              name: proc
              readOnly: true
            - mountPath: /host/sys
              name: sys
              readOnly: true
      volumes:
        - name: proc
          hostPath:
            path: /proc
            type: ""
        - name: sys
          hostPath:
            path: /sys
            type: ""

노드마다 실행되어야 하므로 데몬셋으로 설정되어 있습니다.

실행합니다.

 kubectl create -f node-exporter.yaml

 

이제 다 설치한 것 같은데, 제대로 돌고 있는지 확인해봐야겠죠.

$ kubectl get pod -n monitoring -o wide
NAME                                    READY   STATUS    RESTARTS   AGE    IP             NODE           NOMINATED NODE   READINESS GATES
grafana-7cf86c94b8-dh4k5                1/1     Running   0          35h    10.244.0.129   raspberrypi4   <none>           <none>
node-exporter-mmf7j                     1/1     Running   0          126m   192.168.0.49   raspberrypi4   <none>           <none>
node-exporter-zq4bz                     1/1     Running   0          126m   192.168.0.20   raspberrypi2   <none>           <none>
prometheus-deployment-5978c4f57-fm2fz   1/1     Running   0          37h    10.244.1.20    raspberrypi2   <none>           <none>

모니터링 관련해서 총 4개의 Pod 가 보입니다.

 

다시 Grafana로 가서 node exporter 대시보드를 생성해보겠습니다.

화면 좌측 네번째 아이콘을 클릭하면 대시보드 화면이 나옵니다. 

거기서 다시 우측의 파란색 New 버튼을 클릭하면 아래로 3개의 메뉴가 펼쳐지는데요.

그 중에 import를 선택합니다.

 

대시보드 ID를 넣는 화면이 나옵니다.

 

여기에 넣을 대시보드 ID를 찾기위해, Grafana 대시보드 사이트에 접속합니다.

뭐 찾을 것도 없이 맨 위에 나옵니다. 가장 인기있으니까요.

클릭해서 들어가면 샘플 화면하고 설명이 좀 있습니다.

우측 중간에 [Copy ID to clipboard] 를 클릭하면, ID가 클립보드에 저장됩니다.

 

이제 Grafana 포털로 돌아와서 ID를 붙여넣기 하시고, Load 합니다.

 

바뀐 화면에서 다 기본값으로 두고, 맨 아래 data source 만 Prometeus로 선택해줍니다.

Import를 누르면 대시보드를 가져옵니다.

참 편하죠?

노드에 대해서 가져올 수 있는 데이터는 모조리 가져와서 보여주고 있습니다.

그리고 새로운 대시보드를 꾸민다면, 정보들을 어떻게 가져왔는지 이 대시보드에서서 참고하면 유용합니다.

한가지만 예를 들어보면,

맨 위에 CPU Busy라는 이름 부분을 클릭합니다.

그러면 이렇게 서브 메뉴들이 나오는데요.

이중에 Edit를 선택하면, 설정화면을 들어갈 수 있습니다.

CPU Busy라는 값을 가져오기 위해 아주 긴 쿼리를 사용했네요. 

나만의 대시보드를 꾸밀때에 이 쿼리를 참고하면 좀 수월합니다.

 

대시보드 꾸미는 방법은 다음 포스팅에서 더 얘기해보도록 하죠.

 

728x90