Prometheus 및 Grafana를 사용해 Longhorn 모니터링하기
Longhorn을 제대로 운영하려면 상태를 눈으로 볼 수 있어야 하죠. 이 문서는 Longhorn 모니터링을 셋업하는 빠른 가이드예요.
Longhorn은 REST 엔드포인트 http://LONGHORN_MANAGER_IP:PORT/metrics에서 Prometheus 텍스트 포맷으로 메트릭을 기본 노출해요.
Prometheus, Graphite, Telegraf 같은 수집 도구로 이 메트릭을 스크랩한 뒤, Grafana 같은 도구로 수집한 데이터를 시각화할 수 있어요.
사용 가능한 메트릭은 Longhorn Metrics for Monitoring을 참고하세요.
출처: 문서
본문
개요 (High-level Overview)
이 모니터링 시스템은 데이터 수집과 알림에 Prometheus를, 수집한 데이터의 시각화/대시보드에 Grafana를 사용해요.
- Prometheus 서버: Longhorn 메트릭 엔드포인트에서 시계열 데이터를 스크랩하고 저장해요. 설정된 규칙과 수집한 데이터를 기반으로 알림을 생성하는 역할도 맡아요. Prometheus 서버는 알림을 Alertmanager로 보내요.
- AlertManager: 그 알림들을 관리해요. 침묵(silencing), 억제(inhibition), 집계(aggregation)와 이메일, 온콜 알림 시스템, 채팅 플랫폼 같은 방법으로 알림을 보내는 일을 포함해요.
- Grafana: Prometheus 서버에 데이터를 질의하고 시각화용 대시보드를 그려요.
아래 그림은 모니터링 시스템의 상세 아키텍처를 보여 줘요.
위 그림에 직접 언급되지 않은 구성 요소가 2개 있어요.
- Longhorn Backend 서비스: Longhorn manager 파드 집합을 가리키는 서비스예요. Longhorn의 메트릭은 Longhorn manager 파드의
http://LONGHORN_MANAGER_IP:PORT/metrics엔드포인트에서 노출돼요. - Prometheus operator: Kubernetes 위에서 Prometheus를 운영하는 일을 아주 쉽게 만들어 줘요. 이 오퍼레이터는 ServiceMonitor, Prometheus, AlertManager라는 3개의 커스텀 리소스를 감시해요.
이 커스텀 리소스들을 만들면 Prometheus Operator가 사용자가 지정한 설정으로 Prometheus 서버와 AlertManager를 배포하고 관리해요.
설치 (Installation)
이 문서는 모니터링 시스템에 기본 네임스페이스를 사용해요. 다른 네임스페이스에 설치하려면 매니페스트에서 namespace: <OTHER_NAMESPACE> 필드를 바꾸세요.
Prometheus Operator 설치 (Install Prometheus Operator)
Prometheus Operator - Quickstart의 지침을 따르세요.
참고: 클러스터의 Kubernetes 버전과 호환되는 릴리스를 골라야 할 수 있어요.
Longhorn ServiceMonitor 설치 (Install Longhorn ServiceMonitor)
kubectl로 Longhorn ServiceMonitor 설치 (Install Longhorn ServiceMonitor with Kubectl)
Longhorn Manager용 ServiceMonitor를 만들어요.
```yaml
apiVersion: monitoring.coreos.com/v1
kind: ServiceMonitor
metadata:
name: longhorn-prometheus-servicemonitor
namespace: default
labels:
name: longhorn-prometheus-servicemonitor
spec:
selector:
matchLabels:
app: longhorn-manager
namespaceSelector:
matchNames:
- longhorn-system
endpoints:
- port: manager
#### Helm으로 Longhorn ServiceMonitor 설치 (Install Longhorn ServiceMonitor with Helm)
- `longhorn/chart/values.yaml` YAML 파일을 수정해요.
metrics: serviceMonitor: # -- Setting that allows the creation of a Prometheus Operator ServiceMonitor resource for Longhorn Manager components. enabled: true
- Helm으로 Longhorn Manager용 ServiceMonitor를 만들어요.
helm upgrade longhorn longhorn/longhorn --namespace longhorn-system -f values.yaml
Longhorn ServiceMonitor는 Prometheus Operator 커스텀 리소스예요. 이 셋업 덕분에 Prometheus 서버가 모든 Longhorn Manager 파드와 각각의 엔드포인트를 디스커버리할 수 있어요.
참고: ServiceMonitor는 엔드포인트 디스커버리를 제공할 뿐, Longhorn Manager 파드로의 네트워크 트래픽을 자동으로 허용하지는 않아요.
v1.12.1의 중요한 변경 사항:
- `networkPolicies.restrictInternalTraffic`가 독립적으로 동작하고 기본값이 true예요. 명시적으로 허용하지 않으면 모니터링 트래픽이 막힐 수 있어요.
- `networkPolicies.enabled`는 이제 UI 프론트엔드 정책만 제어해요.
레이블 셀렉터 `app: longhorn-manager`를 사용하면 Longhorn Manager 파드 집합을 가리키는 longhorn-backend 서비스를 선택할 수 있어요.
### Prometheus AlertManager 설치 및 설정 (Install and configure Prometheus AlertManager)
- 인스턴스 3개로 고가용성 Alertmanager 배포를 만들어요.
apiVersion: monitoring.coreos.com/v1 kind: Alertmanager metadata: name: longhorn namespace: default spec: replicas: 3
- 유효한 설정이 주어지지 않으면 Alertmanager 인스턴스가 시작되지 않아요.
자세한 설명은 [Prometheus - Configuration](https://prometheus.io/docs/alerting/latest/configuration/)을 참고하세요.
global: resolve_timeout: 5m route: group_by: [alertname] receiver: email_and_slack receivers:
- name: email_and_slack
email_configs:
- to:
from:
smarthost:
SMTP authentication information.
auth_username: auth_identity: auth_password: headers: subject: 'Longhorn-Alert' text: |- {{ range .Alerts }} Alert: {{ .Annotations.summary }} -{{ .Labels.severity }}Description: {{ .Annotations.description }} Details: {{ range .Labels.SortedPairs }} - {{ .Name }}:{{ .Value }}{{ end }} {{ end }} slack_configs: - api_url:
channel:
text: |-
{{ range .Alerts }}
Alert: {{ .Annotations.summary }} -
{{ .Labels.severity }}Description: {{ .Annotations.description }} Details: {{ range .Labels.SortedPairs }} - {{ .Name }}:{{ .Value }}{{ end }} {{ end }}
- to:
from:
smarthost:
위 Alertmanager 설정을 `alertmanager.yaml`이라는 파일로 저장하고 kubectl로 시크릿을 만들어요.
Alertmanager 인스턴스는 시크릿 이름이 `alertmanager-<ALERTMANAGER_NAME>` 형식을 따라야 해요. 앞 단계에서 Alertmanager의 이름이 `longhorn`이었으니 시크릿 이름은 반드시 `alertmanager-longhorn`이어야 해요.
$ kubectl create secret generic alertmanager-longhorn --from-file=alertmanager.yaml -n default
- Alertmanager의 웹 UI를 보려면 Service로 노출해야 해요. 간단한 방법은 type이 NodePort인 Service를 쓰는 거예요.
apiVersion: v1 kind: Service metadata: name: alertmanager-longhorn namespace: default spec: type: NodePort ports:
- name: web nodePort: 30903 port: 9093 protocol: TCP targetPort: web selector: alertmanager: longhorn
위 서비스를 만든 뒤에는 노드 IP와 포트 30903으로 Alertmanager의 웹 UI에 접근할 수 있어요.
이 NodePort 서비스는 TLS 연결 없이 통신하기 때문에 빠른 검증 용도로만 사용하세요. TLS 연결로 Alertmanager 웹 UI를 노출하려면 서비스 타입을 ClusterIP로 바꾸고 Ingress 컨트롤러를 구성하는 편이 좋아요.
### Prometheus 서버 설치 및 설정 (Install and configure Prometheus server)
- 알림 조건을 정의하려고 PrometheusRule 커스텀 리소스를 만들어요. Longhorn 알림 규칙 예시는 [Longhorn Alert Rule Examples](https://longhorn.io/docs/1.14.0/monitoring/longhorn-alert-rule-examples/)를 참고하세요.
apiVersion: monitoring.coreos.com/v1 kind: PrometheusRule metadata: labels: prometheus: longhorn role: alert-rules name: prometheus-longhorn-rules namespace: default spec: groups:
- name: longhorn.rules
rules:
- alert: LonghornVolumeUsageCritical annotations: description: Longhorn volume {{$labels.volume}} on {{$labels.node}} is at {{$value}}% used for more than 5 minutes. summary: Longhorn volume capacity is over 90% used. expr: 100 * (longhorn_volume_usage_bytes / longhorn_volume_capacity_bytes) > 90 for: 5m labels: issue: Longhorn volume {{$labels.volume}} usage on {{$labels.node}} is critical. severity: critical
자세한 내용은 [Prometheus - Alerting rules](https://prometheus.io/docs/prometheus/latest/configuration/alerting_rules/)를 참고하세요.
- RBAC 인증이 활성화되어 있다면 Prometheus 파드용 ClusterRole과 ClusterRoleBinding을 만들어요.
apiVersion: v1 kind: ServiceAccount metadata: name: prometheus namespace: default
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: prometheus namespace: default rules:
- apiGroups: [""]
resources:
- nodes
- services
- endpoints
- pods verbs: ["get", "list", "watch"]
- apiGroups: [""]
resources:
- configmaps verbs: ["get"]
- nonResourceURLs: ["/metrics"] verbs: ["get"]
apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: prometheus roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: prometheus subjects:
- kind: ServiceAccount name: prometheus namespace: default
- Prometheus 커스텀 리소스를 만들어요. spec에서 Longhorn 서비스 모니터와 Longhorn 규칙을 선택하는 점에 주목하세요.
apiVersion: monitoring.coreos.com/v1 kind: Prometheus metadata: name: longhorn namespace: default spec: replicas: 2 podMetadata: labels: longhorn.io/metrics-scraper: "true" serviceAccountName: prometheus alerting: alertmanagers: - namespace: default name: alertmanager-longhorn port: web serviceMonitorSelector: matchLabels: name: longhorn-prometheus-servicemonitor ruleSelector: matchLabels: prometheus: longhorn role: alert-rules
- 문제: `networkPolicies.restrictInternalTraffic`가 활성화되면 Longhorn은 longhorn-manager로 들어오는 트래픽을 NetworkPolicy가 허용한 특정 Longhorn 컴포넌트로 제한해요. Prometheus와 다른 모니터링 에이전트는 이 허용 목록에 포함되지 않아서, 기본으로는 TCP 포트 9500에서 Longhorn Manager 파드를 스크랩하는 게 막혀요. ServiceMonitor는 엔드포인트를 디스커버리할 뿐 Longhorn Manager 파드로의 네트워크 트래픽을 승인하지는 않아요.
해결 방법: 모니터링 파드가 TCP 포트 9500에서 Longhorn Manager 파드에 접근할 수 있게, `longhorn-system`에 범위를 좁게 잡은 NetworkPolicy를 적용해요. 모니터링 환경에 맞게 네임스페이스와 파드 셀렉터를 커스터마이즈하려면 범위 지정 추가형(additive) NetworkPolicy 예시의 인라인 주석을 따르세요.
경고: 이 예시는 하나의 from 항목에 namespaceSelector와 podSelector를 결합하기 때문에 두 셀렉터가 모두 일치해야 해요. 포트 9500은 Longhorn API도 함께 서빙하므로, 그런 더 넓은 API 접근이 의도된 게 아니라면 결합된 셀렉터를 네임스페이스만 허용하는 설정으로 바꾸지 마세요. 자세한 내용은 [Network Policy 가이드](https://longhorn.io/docs/1.14.0/advanced-resources/deploy/network-policies/)를 참고하세요.
- Prometheus 서버의 웹 UI를 보려면 Service로 노출해야 해요. 간단한 방법은 type이 NodePort인 Service를 쓰는 거예요.
apiVersion: v1 kind: Service metadata: name: prometheus-longhorn namespace: default spec: type: NodePort ports:
- name: web nodePort: 30904 port: 9090 protocol: TCP targetPort: web selector: prometheus: longhorn
위 서비스를 만든 뒤에는 노드 IP와 포트 30904로 Prometheus 서버의 웹 UI에 접근할 수 있어요.
이 시점에서 Prometheus 서버 UI의 targets와 rules 섹션에서 모든 Longhorn manager 타깃과 Longhorn 규칙을 볼 수 있어야 해요.
이 NodePort 서비스는 TLS 연결 없이 통신하기 때문에 빠른 검증 용도로만 사용하세요. TLS 연결로 Prometheus 서버의 웹 UI를 노출하려면 서비스 타입을 ClusterIP로 바꾸고 Ingress 컨트롤러를 구성하는 편이 좋아요.
### Grafana 셋업 (Setup Grafana)
- Grafana 데이터소스 ConfigMap을 만들어요.
apiVersion: v1 kind: ConfigMap metadata: name: grafana-datasources namespace: default data: prometheus.yaml: |- { "apiVersion": 1, "datasources": [ { "access":"proxy", "editable": true, "name": "prometheus-longhorn", "orgId": 1, "type": "prometheus", "url": "http://prometheus-longhorn.default.svc:9090", "version": 1 } ] }
참고: 모니터링 스택을 다른 네임스페이스에 설치한다면 `url` 필드를 바꾸세요.
`http://prometheus-longhorn.<NAMESPACE>.svc:9090"`
- Grafana Deployment를 만들어요.
apiVersion: apps/v1 kind: Deployment metadata: name: grafana namespace: default labels: app: grafana spec: replicas: 1 selector: matchLabels: app: grafana template: metadata: name: grafana labels: app: grafana spec: containers: - name: grafana image: grafana/grafana:7.1.5 ports: - name: grafana containerPort: 3000 resources: limits: memory: "500Mi" cpu: "300m" requests: memory: "500Mi" cpu: "200m" volumeMounts: - mountPath: /var/lib/grafana name: grafana-storage - mountPath: /etc/grafana/provisioning/datasources name: grafana-datasources readOnly: false volumes: - name: grafana-storage emptyDir: {} - name: grafana-datasources configMap: defaultMode: 420 name: grafana-datasources
- Grafana Service를 만들어요.
apiVersion: v1 kind: Service metadata: name: grafana namespace: default spec: selector: app: grafana type: ClusterIP ports: - port: 3000 targetPort: 3000
- Grafana를 NodePort 32000으로 노출해요.
kubectl -n default patch svc grafana --type='json' -p '[{"op":"replace","path":"/spec/type","value":"NodePort"},{"op":"replace","path":"/spec/ports/0/nodePort","value":32000}]'
이 NodePort 서비스는 TLS 연결 없이 통신하기 때문에 빠른 검증 용도로만 사용하세요. TLS 연결로 Grafana를 노출하려면 서비스 타입을 ClusterIP로 바꾸고 Ingress 컨트롤러를 구성하는 편이 좋아요.
- 아무 노드 IP의 32000 포트로 Grafana 대시보드에 접속해요.
Default Credential
User: admin Pass: admin
- Longhorn 대시보드를 셋업해요.
Grafana에 들어가면 미리 만들어진 Longhorn 예시 대시보드를 임포트하세요.
Grafana 대시보드 임포트 방법은 [Grafana Lab - Export and import](https://grafana.com/docs/grafana/latest/dashboards/manage-dashboards/#export-and-import-dashboards) 지침을 참고하세요.
셋업에 성공하면 다음 같은 대시보드가 보여요.
## 더 알아보기 (Learn more)
- [Longhorn 문서 홈](https://longhorn.io/docs/1.14.0/)
- [Longhorn Metrics for Monitoring](https://longhorn.io/docs/1.14.0/monitoring/metrics/)
- [Longhorn Alert Rule Examples](https://longhorn.io/docs/1.14.0/monitoring/longhorn-alert-rule-examples/)
- [Network Policies](https://longhorn.io/docs/1.14.0/advanced-resources/deploy/network-policies/)