基於 Prometheus+Grafana+Alertmanager 搭建 K8S 雲監控告警平臺(附配置告警至QQ、釘釘)

misakivv發表於2024-10-07

目錄
  • 一、機器規劃
  • 二、部署安裝 node-exporter、prometheus、Grafana、kube-state-metrics
    • 1、建立 monitor-sa 名稱空間
    • 2、安裝node-exporter元件
      • 2.1、說明
      • 2.2、應用資源清單
      • 2.3、透過node-exporter採集資料
    • 3、k8s 叢集中部署 prometheus
      • 3.1、建立一個 sa 賬號
      • 3.2、將 sa 賬號 monitor 透過 clusterrolebing 繫結到 clusterrole 上
      • 3.3、建立資料目錄
      • 3.4、安裝prometheus
        • 3.4.1、將 prometheus.yml 檔案以 ConfigMap 的形式進行管理
        • 3.4.2、應用 cm 資源清單
        • 3.4.3、透過 Deployment 部署 prometheus
        • 3.4.4、應用 prometheus 資源清單
        • 3.4.5、給 prometheus 的 pod 建立一個 svc
        • 3.4.6、應用 svc 資源清單
      • 3.5、訪問prometheus UI介面
      • 3.6、檢視配置的服務發現
    • 4、prometheus熱更新
      • 4.1、熱載入 prometheus
      • 4.2、暴力重啟 prometheus
    • 5、Grafana安裝和配置
      • 5.1、下載 Grafana 需要的映象
      • 5.2、在 k8s 叢集各個節點匯入 Grafana 映象
      • 5.3、master 節點建立 grafana.yaml
      • 5.4、檢視 Grafana 的 pod 和 svc
      • 5.5、檢視 Grafana UI 介面
      • 5.6、給 Grafana 接入 Prometheus 資料來源
      • 5.7、獲取監控模板
      • 5.8、匯入監控模板
    • 6、安裝配置 kube-state-metrics 元件
      • 6.1、什麼是 kube-state-metrics
      • 6.2、建立 sa ,並進行授權
      • 6.3、建立並應用 kube-state-metrics-deploy.yaml 檔案
      • 6.4、建立並應用 kube-state-metrics-svc.yaml 檔案
      • 6.5、獲取 kube-state-metrics json 檔案
      • 6.6、向 Grafana 匯入 kube-state-metrics json 檔案
  • 三、安裝和配置 Alertmanager -- 傳送告警到 QQ 郵箱
    • 1、將 alertmanager-cm.yaml 檔案以 cm 形式進行管理
      • 1.1、alertmanager配置檔案說明
    • 2、重新生成並應用 prometheus-cfg.yaml 檔案
    • 3、重新生成 prometheus-deploy.yaml 檔案
      • 3.1、建立一個名為 etcd-certs 的 Secret
      • 3.2、應用 prometheus-deploy.yaml 檔案
    • 4、重新生成並建立 alertmanager-svc.yaml 檔案
    • 5、訪問 prometheus UI 介面
      • 5.1、【error】kube-controller-manager、etcd、kube-proxy、kube-scheduler 元件 connection refused
        • 5.1.1、kube-proxy
        • 5.1.2、kube-controller-manager
        • 5.1.3、kube-schedule
        • 5.1.4、etcd
    • 6、點選Alerts,檢視
    • 7、把controller-manager的cpu使用率大於90%展開
    • 8、登入 alertmanager UI
    • 9、登入 QQ 郵箱檢視告警資訊
  • 四、配置 Alertmanager 報警 -- 傳送告警到釘釘
    • 1、手機端拉群
    • 2、建立自定義機器人
    • 3、獲取釘釘的 Webhook 外掛
    • 4、啟動釘釘告警外掛
    • 5、對 alertmanager-cm.yaml 檔案做備份
    • 6、重新生成新的 alertmanager-cm.yaml 檔案
    • 7、重建資源以生效
    • 8、效果

一、機器規劃

角色 主機名 ip 地址
master k8s-master1 192.168.112.10
node k8s-node1 192.168.112.20
node k8s-node2 192.168.112.30
平臺 VMware Workstation
作業系統 CentOS Linux release 7.9.2009 (Core)
記憶體、CPU 4C4G
磁碟大小 20G SCSI

二、部署安裝 node-exporter、prometheus、Grafana、kube-state-metrics

1、建立 monitor-sa 名稱空間

master 節點操作

kubectl create ns monitor-sa

2、安裝node-exporter元件

master 節點操作

cat >> node-export.yaml  <<EOF
apiVersion: apps/v1
kind: DaemonSet
metadata:
  name: node-exporter
  namespace: monitor-sa
  labels:
    name: node-exporter
spec:
  selector:
    matchLabels:
     name: node-exporter
  template:
    metadata:
      labels:
        name: node-exporter
    spec:
      hostPID: true
      hostIPC: true
      hostNetwork: true
      containers:
      - name: node-exporter
        image: prom/node-exporter:v0.16.0
        ports:
        - containerPort: 9100
        resources:
          requests:
            cpu: 0.15
        securityContext:
          privileged: true
        args:
        - --path.procfs
        - /host/proc
        - --path.sysfs
        - /host/sys
        - --collector.filesystem.ignored-mount-points
        - '"^/(sys|proc|dev|host|etc)($|/)"'
        volumeMounts:
        - name: dev
          mountPath: /host/dev
        - name: proc
          mountPath: /host/proc
        - name: sys
          mountPath: /host/sys
        - name: rootfs
          mountPath: /rootfs
      tolerations:
      - key: "node-role.kubernetes.io/master"
        operator: "Exists"
        effect: "NoSchedule"
      volumes:
        - name: proc
          hostPath:
            path: /proc
        - name: dev
          hostPath:
            path: /dev
        - name: sys
          hostPath:
            path: /sys
        - name: rootfs
          hostPath:
            path: /
EOF

2.1、說明

  • 主機名稱空間共享 (hostPID, hostIPC, hostNetwork)
    • hostPID: true: 允許 Pod 使用主機的 PID 名稱空間。Pod 可以看到主機上的所有程序
    • hostIPC: true: 允許 Pod 使用主機的 IPC 名稱空間。Pod 可以與其他在主機上執行的程序共享 IPC 資源(如訊號量、訊息佇列等)。
    • hostNetwork: true: 允許 Pod 使用主機的網路名稱空間。Pod 將使用主機的網路介面
  • 命令列引數 (args)
  • --path.procfs /host/proc: 指定 node-exporter 應該從 /host/proc 路徑讀取程序檔案系統的資料。這使得 node-exporter 可以訪問宿主機的程序資訊。
  • --path.sysfs /host/sys: 指定 node-exporter 應該從 /host/sys 路徑讀取系統檔案系統的資料。這使得 node-exporter 可以訪問宿主機的系統資訊。
  • --collector.filesystem.ignored-mount-points "^/(sys|proc|dev|host|etc)($|/)": 指定哪些檔案系統的掛載點應該被忽略,不被 node-exporter 收集。這裡忽略了 /sys, /proc, /dev, /host, 和 /etc 這些掛載點,避免收集不必要的資料。
  • 掛載點 (volumeMountsvolumes)
    • /proc 掛載
      • 宿主機路徑: /proc
      • 容器內路徑: /host/proc
      • 作用:node-exporter 訪問宿主機的程序檔案系統。
    • /dev 掛載
      • 宿主機路徑: /dev
      • 容器內路徑: /host/dev
      • 作用:node-exporter 訪問宿主機的裝置檔案。
    • /sys 掛載
      • 宿主機路徑: /sys
      • 容器內路徑: /host/sys
      • 作用:node-exporter 訪問宿主機的系統檔案系統。
    • / 掛載
      • 宿主機路徑: /
      • 容器內路徑: /rootfs
      • 作用:node-exporter 訪問宿主機的根檔案系統。
  • 容忍度 (tolerations)
    • key: "node-role.kubernetes.io/master": 指定容忍的汙點鍵。
    • operator: "Exists": 表示只要存在該汙點鍵,無論值是什麼,都予以容忍。
    • effect: "NoSchedule": 表示即使節點上有這種汙點,也不會阻止 Pod 被排程到該節點上。

2.2、應用資源清單

kubectl apply -f node-export.yaml

kubectl get pods -n monitor-sa -l name=node-exporter

image-20241005214533113

2.3、透過node-exporter採集資料

node-export預設的監聽埠是9100,可以看到當前主機獲取到的所有監控資料

# curl http://<master-ip>:9100/metrics

curl http://192.168.112.10:9100/metrics

image-20241005214626996

3、k8s 叢集中部署 prometheus

3.1、建立一個 sa 賬號

kubectl create serviceaccount monitor -n monitor-sa

3.2、將 sa 賬號 monitor 透過 clusterrolebing 繫結到 clusterrole 上

kubectl create clusterrolebinding monitor-clusterrolebinding -n monitor-sa --clusterrole=cluster-admin  --serviceaccount=monitor-sa:monitor

3.3、建立資料目錄

所有 node 節點

mkdir /data && chmod 777 /data/

3.4、安裝prometheus

master 節點操作

3.4.1、將 prometheus.yml 檔案以 ConfigMap 的形式進行管理

cat  >> prometheus-cfg.yaml << 'EOF'
---
kind: ConfigMap
apiVersion: v1
metadata:
  labels:
    app: prometheus
  name: prometheus-config
  namespace: monitor-sa
data:
  prometheus.yml: |
    global:
      scrape_interval: 15s
      scrape_timeout: 10s
      evaluation_interval: 1m
    scrape_configs:
    - job_name: 'kubernetes-node'
      kubernetes_sd_configs:
      - role: node
      relabel_configs:
      - source_labels: [__address__]
        regex: '(.*):10250'
        replacement: '${1}:9100'
        target_label: __address__
        action: replace
      - action: labelmap
        regex: __meta_kubernetes_node_label_(.+)
    - job_name: 'kubernetes-node-cadvisor'
      kubernetes_sd_configs:
      - role:  node
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - action: labelmap
        regex: __meta_kubernetes_node_label_(.+)
      - target_label: __address__
        replacement: kubernetes.default.svc:443
      - source_labels: [__meta_kubernetes_node_name]
        regex: (.+)
        target_label: __metrics_path__
        replacement: '/api/v1/nodes/${1}/proxy/metrics/cadvisor'
    - job_name: 'kubernetes-apiserver'
      kubernetes_sd_configs:
      - role: endpoints
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
        action: keep
        regex: default;kubernetes;https
    - job_name: 'kubernetes-service-endpoints'
      kubernetes_sd_configs:
      - role: endpoints
      relabel_configs:
      - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]
        action: replace
        target_label: __scheme__
        regex: (https?)
      - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]
        action: replace
        target_label: __metrics_path__
        regex: (.+)
      - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]
        action: replace
        target_label: __address__
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: '$1:$2'
      - action: labelmap
        regex: __meta_kubernetes_service_label_(.+)
      - source_labels: [__meta_kubernetes_namespace]
        action: replace
        target_label: kubernetes_namespace
      - source_labels: [__meta_kubernetes_service_name]
        action: replace
        target_label: kubernetes_name 
EOF

3.4.2、應用 cm 資源清單

kubectl apply -f prometheus-cfg.yaml

kubectl get cm prometheus-config -n monitor-sa -o yaml

需要確保 cm 正確解析了變數 $1、$2

不然 prometheus 獲取不到對應的 IP 地址會無法正常監控

image-20241005215107744

3.4.3、透過 Deployment 部署 prometheus

cat >> prometheus-deploy.yaml << EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus-server
  namespace: monitor-sa
  labels:
    app: prometheus
spec:
  replicas: 2
  selector:
    matchLabels:
      app: prometheus
      component: server
    #matchExpressions:
    #- {key: app, operator: In, values: [prometheus]}
    #- {key: component, operator: In, values: [server]}
  template:
    metadata:
      labels:
        app: prometheus
        component: server
      annotations:
        prometheus.io/scrape: 'false'
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - prometheus
              - key: component
                operator: In
                values:
                - server
            topologyKey: kubernetes.io/hostname
      serviceAccountName: monitor
      containers:
      - name: prometheus
        image: quay.io/prometheus/prometheus:latest
        imagePullPolicy: IfNotPresent
        command:
          - prometheus
          - --config.file=/etc/prometheus/prometheus.yml
          - --storage.tsdb.path=/prometheus
          - --storage.tsdb.retention=720h
        ports:
        - containerPort: 9090
          protocol: TCP
        volumeMounts:
        - mountPath: /etc/prometheus/prometheus.yml
          name: prometheus-config
          subPath: prometheus.yml
        - mountPath: /prometheus/
          name: prometheus-storage-volume
      volumes:
        - name: prometheus-config
          configMap:
            name: prometheus-config
            items:
              - key: prometheus.yml
                path: prometheus.yml
                mode: 0644
        - name: prometheus-storage-volume
          hostPath:
           path: /data
           type: Directory
EOF

3.4.4、應用 prometheus 資源清單

kubectl apply -f prometheus-deploy.yaml

image-20241005215357542

3.4.5、給 prometheus 的 pod 建立一個 svc

cat  > prometheus-svc.yaml << EOF
---
apiVersion: v1
kind: Service
metadata:
  name: prometheus
  namespace: monitor-sa
  labels:
    app: prometheus
spec:
  type: NodePort
  ports:
    - port: 9090
      targetPort: 9090
      protocol: TCP
  selector:
    app: prometheus
    component: server
EOF

3.4.6、應用 svc 資源清單

kubectl get svc -n monitor-sa -o wide

image-20241005215425028

透過上面可以看到service在宿主機上對映的埠是30172,這樣我們訪問k8s叢集的k8s-master1節點的ip:30172,就可以訪問到prometheus的web ui介面了

3.5、訪問prometheus UI介面

# <k8s-master1 IP>:32032
192.168.112.10:32032

image-20241005215529171

3.6、檢視配置的服務發現

點選頁面的Status->Targets,可看到如下,說明我們配置的服務發現可以正常採集資料

image-20241005221024862

4、prometheus熱更新

4.1、熱載入 prometheus

#為了每次修改配置檔案可以熱載入prometheus,也就是不停止prometheus,就可以使配置生效,如修改prometheus-cfg.yaml,想要使配置生效可用如下熱載入命令:

curl -X POST http://<prometheus-pod-ip>:9090/-/reload
kubectl get pods -n monitor-sa -l app=prometheus -o wide

image-20241005221822766

4.2、暴力重啟 prometheus

熱載入速度比較慢,可以暴力重啟prometheus

如修改上面的prometheus-cfg.yaml檔案之後,可執行如下強制刪除

kubectl delete -f prometheus-cfg.yaml

kubectl delete -f prometheus-deploy.yaml

# 然後再透過apply更新

kubectl apply -f prometheus-cfg.yaml

kubectl apply -f prometheus-deploy.yaml

線上最好熱載入,暴力刪除可能造成監控資料的丟失

5、Grafana安裝和配置

5.1、下載 Grafana 需要的映象

連結:https://pan.baidu.com/s/1TmVGKxde_cEYrbjiETboEA 
提取碼:052u

5.2、在 k8s 叢集各個節點匯入 Grafana 映象

docker load -i heapster-grafana-amd64_v5_0_4.tar.gz

docker images | grep grafana

image-20241005231752018

image-20241005231829736

image-20241005231844131

5.3、master 節點建立 grafana.yaml

cat >> grafana.yaml << EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: monitoring-grafana
  namespace: kube-system
spec:
  replicas: 1
  selector:
    matchLabels:
      task: monitoring
      k8s-app: grafana
  template:
    metadata:
      labels:
        task: monitoring
        k8s-app: grafana
    spec:
      containers:
      - name: grafana
        image: k8s.gcr.io/heapster-grafana-amd64:v5.0.4
        ports:
        - containerPort: 3000
          protocol: TCP
        volumeMounts:
        - mountPath: /etc/ssl/certs
          name: ca-certificates
          readOnly: true
        - mountPath: /var
          name: grafana-storage
        env:
        - name: INFLUXDB_HOST
          value: monitoring-influxdb
        - name: GF_SERVER_HTTP_PORT
          value: "3000"
          # The following env variables are required to make Grafana accessible via
          # the kubernetes api-server proxy. On production clusters, we recommend
          # removing these env variables, setup auth for grafana, and expose the grafana
          # service using a LoadBalancer or a public IP.
        - name: GF_AUTH_BASIC_ENABLED
          value: "false"
        - name: GF_AUTH_ANONYMOUS_ENABLED
          value: "true"
        - name: GF_AUTH_ANONYMOUS_ORG_ROLE
          value: Admin
        - name: GF_SERVER_ROOT_URL
          # If you're only using the API Server proxy, set this value instead:
          # value: /api/v1/namespaces/kube-system/services/monitoring-grafana/proxy
          value: /
      volumes:
      - name: ca-certificates
        hostPath:
          path: /etc/ssl/certs
      - name: grafana-storage
        emptyDir: {}
---
apiVersion: v1
kind: Service
metadata:
  labels:
    # For use as a Cluster add-on (https://github.com/kubernetes/kubernetes/tree/master/cluster/addons)
    # If you are NOT using this as an addon, you should comment out this line.
    kubernetes.io/cluster-service: 'true'
    kubernetes.io/name: monitoring-grafana
  name: monitoring-grafana
  namespace: kube-system
spec:
  # In a production setup, we recommend accessing Grafana through an external Loadbalancer
  # or through a public IP.
  # type: LoadBalancer
  # You could also use NodePort to expose the service at a randomly-generated port
  # type: NodePort
  ports:
  - port: 80
    targetPort: 3000
  selector:
    k8s-app: grafana
  type: NodePort
EOF

5.4、檢視 Grafana 的 pod 和 svc

image-20241005232832195

5.5、檢視 Grafana UI 介面

# <master-ip>:<grafana-svc-port>

192.168.112.10:31455

image-20241006150242320

5.6、給 Grafana 接入 Prometheus 資料來源

選擇 Create your first data source
image-20241006150534861
image-20241006150624325
Name: Prometheus |Type: Prometheus|HTTP 處的URL寫 如下:http://prometheus.monitor-sa.svc:9090
image-20241006151022903
點選左下角 Save & Test,出現如下 Data source is working,說明 prometheus 資料來源成功的被 grafana 接入了
image-20241006151134680
image-20241006151148648

5.7、獲取監控模板

  • 可以在 Grafana Dashboard 官網搜尋需要的

Grafana dashboards | Grafana Labs

  • 也可以直接克隆 Github 倉庫,獲取 node_exporter.json 、 docker_rev1.json 監控模板
git clone git@github.com:misakivv/Grafana-Dashboard.git

5.8、匯入監控模板

依次點選左側欄的 + 號下方的 Import
image-20241006152716109
選擇 Upload json file,選擇一個本地的node_exporter.json 檔案
image-20241006153035574
匯入後 Options 選項中會出現 Name 是自動生成的,Prometheus 是需要我們選擇 Prometheus的
image-20241006153231878
點選 Import 即可出現如下介面
image-20241006153455006
按照如上操作,匯入docker_rev1.json監控模板
image-20241006153635176
image-20241006153710723

6、安裝配置 kube-state-metrics 元件

6.1、什麼是 kube-state-metrics

kube-state-metrics透過監聽API Server生成有關資源物件的狀態指標,比如Deployment、Node、Pod,需要注意的是kube-state-metrics只是簡單的提供一個metrics資料,並不會儲存這些指標資料,所以我們可以使用Prometheus來抓取這些資料然後儲存,主要關注的是業務相關的一些後設資料,比如Deployment、Pod、副本狀態等;排程了多少個replicas?現在可用的有幾個?多少個Pod是running/stopped/terminated狀態?Pod重啟了多少次?有多少job在執行中。

6.2、建立 sa ,並進行授權

k8s-master1 節點編寫一個 kube-state-metrics-rbac.yaml 檔案

cat >> kube-state-metrics-rbac.yaml << EOF
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: kube-state-metrics
  namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: kube-state-metrics
rules:
- apiGroups: [""]
  resources: ["nodes", "pods", "services", "resourcequotas", "replicationcontrollers", "limitranges", "persistentvolumeclaims", "persistentvolumes", "namespaces", "endpoints"]
  verbs: ["list", "watch"]
- apiGroups: ["extensions"]
  resources: ["daemonsets", "deployments", "replicasets"]
  verbs: ["list", "watch"]
- apiGroups: ["apps"]
  resources: ["statefulsets"]
  verbs: ["list", "watch"]
- apiGroups: ["batch"]
  resources: ["cronjobs", "jobs"]
  verbs: ["list", "watch"]
- apiGroups: ["autoscaling"]
  resources: ["horizontalpodautoscalers"]
  verbs: ["list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: kube-state-metrics
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: kube-state-metrics
subjects:
- kind: ServiceAccount
  name: kube-state-metrics
  namespace: kube-system
EOF
kubectl get sa,clusterrole,clusterrolebinding -n kube-system | grep kube-state-metrics

image-20241006155708266

6.3、建立並應用 kube-state-metrics-deploy.yaml 檔案

k8s-master1 節點操作

cat > kube-state-metrics-deploy.yaml <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: kube-state-metrics
  namespace: kube-system
spec:
  replicas: 1
  selector:
    matchLabels:
      app: kube-state-metrics
  template:
    metadata:
      labels:
        app: kube-state-metrics
    spec:
      serviceAccountName: kube-state-metrics
      containers:
      - name: kube-state-metrics
#        image: gcr.io/google_containers/kube-state-metrics-amd64:v1.3.1
        image: quay.io/coreos/kube-state-metrics:latest
        ports:
        - containerPort: 8080
EOF
kubectl apply -f kube-state-metrics-deploy.yaml

kubectl get pods -n kube-system -l app=kube-state-metrics -w

image-20241006162620908

拉取 kube-state-metrics 指定映象版本失敗時可以選擇在叢集各個節點上

docker pull quay.io/coreos/kube-state-metrics:latest

拉取最新 tag 版本

image-20241006162304963

6.4、建立並應用 kube-state-metrics-svc.yaml 檔案

k8s-master1 節點操作

cat >> kube-state-metrics-svc.yaml <<EOF
apiVersion: v1
kind: Service
metadata:
  annotations:
    prometheus.io/scrape: 'true'
  name: kube-state-metrics
  namespace: kube-system
  labels:
    app: kube-state-metrics
spec:
  ports:
  - name: kube-state-metrics
    port: 8080
    protocol: TCP
  selector:
    app: kube-state-metrics
EOF
kubectl apply -f kube-state-metrics-svc.yaml

kubectl get svc -n kube-system -l app=kube-state-metrics

image-20241006163135415

6.5、獲取 kube-state-metrics json 檔案

git clone git@github.com:misakivv/Grafana-Dashboard.git

image-20241006163929057

6.6、向 Grafana 匯入 kube-state-metrics json 檔案

點選左側欄 + 號的 Import
image-20241006163710887
點選 Upload .json File,上傳 Kubernetes Cluster (Prometheus)-1577674936972.json
image-20241006164143527
image-20241006164305915
檢視
image-20241006165042653
**同樣的匯入 Kubernetes cluster monitoring (via Prometheus) (k8s 1.16)-1577691996738.json **
image-20241006165253781
image-20241006165821679
image-20241006165850539
image-20241006165912093
image-20241006165931820
image-20241006165949255
image-20241006170018099
image-20241006170044368

三、安裝和配置 Alertmanager -- 傳送告警到 QQ 郵箱

1、將 alertmanager-cm.yaml 檔案以 cm 形式進行管理

k8s-master1 節點操作

cat >> alertmanager-cm.yaml << EOF
kind: ConfigMap
apiVersion: v1
metadata:
  name: alertmanager
  namespace: monitor-sa
data:
  alertmanager.yml: |-
    global:
      resolve_timeout: 1m
      smtp_smarthost: 'smtp.qq.com:465'
      smtp_from: '2830909671@qq.com'
      smtp_auth_username: '2830909671@qq.com'
      smtp_auth_password: 'ajjgpgwwfkpcdgih'
      smtp_require_tls: false
    route:
      group_by: [alertname]
      group_wait: 5s
      group_interval: 5s
      repeat_interval: 5m
      receiver: default-receiver
    receivers:
    - name: 'default-receiver'
      email_configs:
      - to: 'misakikk@qq.com'
        send_resolved: true
EOF
kubectl apply -f alertmanager-cm.yaml

kubectl get cm alertmanager -n monitor-sa

image-20241006174637564

1.1、alertmanager配置檔案說明

smtp_smarthost: 'smtp.qq.com:465'
#用於傳送郵件的郵箱的SMTP伺服器地址+埠。QQ 郵箱 SMTP 服務地址,官方地址為 smtp.qq.com 埠為 465 或 587,同時要設定開啟 POP3/SMTP 服務。
smtp_from: '2830909671@qq.com'
#這是指定從哪個郵箱傳送報警
smtp_auth_password: 'ajjgpgwwfkpcdgih'
#這是傳送郵箱的授權碼而不是登入密碼
email_configs:
   - to: 'misakikk@qq.com'
#to後面指定傳送到哪個郵箱

2、重新生成並應用 prometheus-cfg.yaml 檔案

k8s-master1 節點操作

cat > prometheus-cfg.yaml << 'EOF'
kind: ConfigMap
apiVersion: v1
metadata:
  labels:
    app: prometheus
  name: prometheus-config
  namespace: monitor-sa
data:
  prometheus.yml: |
    rule_files:
    - /etc/prometheus/rules.yml
    alerting:
      alertmanagers:
      - static_configs:
        - targets: ["localhost:9093"]
    global:
      scrape_interval: 15s
      scrape_timeout: 10s
      evaluation_interval: 1m
    scrape_configs:
    - job_name: 'kubernetes-node'
      kubernetes_sd_configs:
      - role: node
      relabel_configs:
      - source_labels: [__address__]
        regex: '(.*):10250'
        replacement: '${1}:9100'
        target_label: __address__
        action: replace
      - action: labelmap
        regex: __meta_kubernetes_node_label_(.+)
    - job_name: 'kubernetes-node-cadvisor'
      kubernetes_sd_configs:
      - role:  node
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - action: labelmap
        regex: __meta_kubernetes_node_label_(.+)
      - target_label: __address__
        replacement: kubernetes.default.svc:443
      - source_labels: [__meta_kubernetes_node_name]
        regex: (.+)
        target_label: __metrics_path__
        replacement: '/api/v1/nodes/${1}/proxy/metrics/cadvisor'
    - job_name: 'kubernetes-apiserver'
      kubernetes_sd_configs:
      - role: endpoints
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
      bearer_token_file: /var/run/secrets/kubernetes.io/serviceaccount/token
      relabel_configs:
      - source_labels: [__meta_kubernetes_namespace, __meta_kubernetes_service_name, __meta_kubernetes_endpoint_port_name]
        action: keep
        regex: default;kubernetes;https
    - job_name: 'kubernetes-service-endpoints'
      kubernetes_sd_configs:
      - role: endpoints
      relabel_configs:
      - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scrape]
        action: keep
        regex: true
      - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_scheme]
        action: replace
        target_label: __scheme__
        regex: (https?)
      - source_labels: [__meta_kubernetes_service_annotation_prometheus_io_path]
        action: replace
        target_label: __metrics_path__
        regex: (.+)
      - source_labels: [__address__, __meta_kubernetes_service_annotation_prometheus_io_port]
        action: replace
        target_label: __address__
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: '$1:$2'
      - action: labelmap
        regex: __meta_kubernetes_service_label_(.+)
      - source_labels: [__meta_kubernetes_namespace]
        action: replace
        target_label: kubernetes_namespace
      - source_labels: [__meta_kubernetes_service_name]
        action: replace
        target_label: kubernetes_name 
    - job_name: 'kubernetes-pods'
      kubernetes_sd_configs:
      - role: pod
      relabel_configs:
      - action: keep
        regex: true
        source_labels:
        - __meta_kubernetes_pod_annotation_prometheus_io_scrape
      - action: replace
        regex: (.+)
        source_labels:
        - __meta_kubernetes_pod_annotation_prometheus_io_path
        target_label: __metrics_path__
      - action: replace
        regex: ([^:]+)(?::\d+)?;(\d+)
        replacement: '$1:$2'
        source_labels:
        - __address__
        - __meta_kubernetes_pod_annotation_prometheus_io_port
        target_label: __address__
      - action: labelmap
        regex: __meta_kubernetes_pod_label_(.+)
      - action: replace
        source_labels:
        - __meta_kubernetes_namespace
        target_label: kubernetes_namespace
      - action: replace
        source_labels:
        - __meta_kubernetes_pod_name
        target_label: kubernetes_pod_name
    - job_name: 'kubernetes-schedule'
      scrape_interval: 5s
      static_configs:
      - targets: ['192.168.112.10:10259']
    - job_name: 'kubernetes-controller-manager'
      scrape_interval: 5s
      static_configs:
      - targets: ['192.168.112.10:10257']
    - job_name: 'kubernetes-kube-proxy'
      scrape_interval: 5s
      static_configs:
      - targets: ['192.168.112.10:10249','192.168.112.20:10249','192.168.112.30:10249']
    - job_name: 'kubernetes-etcd'
      scheme: https
      tls_config:
        ca_file: /var/run/secrets/kubernetes.io/k8s-certs/etcd/ca.crt
        cert_file: /var/run/secrets/kubernetes.io/k8s-certs/etcd/server.crt
        key_file: /var/run/secrets/kubernetes.io/k8s-certs/etcd/server.key
      scrape_interval: 5s
      static_configs:
      - targets: ['192.168.112.10:2381']
  rules.yml: |
    groups:
    - name: example
      rules:
      - alert: kube-proxy的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-kube-proxy"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過80%"
      - alert:  kube-proxy的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-kube-proxy"}[1m]) * 100 > 90
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過90%"
      - alert: scheduler的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-schedule"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過80%"
      - alert:  scheduler的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-schedule"}[1m]) * 100 > 90
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過90%"
      - alert: controller-manager的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-controller-manager"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過80%"
      - alert:  controller-manager的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-controller-manager"}[1m]) * 100 > 0
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過90%"
      - alert: apiserver的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-apiserver"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過80%"
      - alert:  apiserver的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-apiserver"}[1m]) * 100 > 90
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過90%"
      - alert: etcd的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-etcd"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過80%"
      - alert:  etcd的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{job=~"kubernetes-etcd"}[1m]) * 100 > 90
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}元件的cpu使用率超過90%"
      - alert: kube-state-metrics的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{k8s_app=~"kube-state-metrics"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.k8s_app}}元件的cpu使用率超過80%"
          value: "{{ $value }}%"
          threshold: "80%"      
      - alert: kube-state-metrics的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{k8s_app=~"kube-state-metrics"}[1m]) * 100 > 0
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.k8s_app}}元件的cpu使用率超過90%"
          value: "{{ $value }}%"
          threshold: "90%"      
      - alert: coredns的cpu使用率大於80%
        expr: rate(process_cpu_seconds_total{k8s_app=~"kube-dns"}[1m]) * 100 > 80
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.k8s_app}}元件的cpu使用率超過80%"
          value: "{{ $value }}%"
          threshold: "80%"      
      - alert: coredns的cpu使用率大於90%
        expr: rate(process_cpu_seconds_total{k8s_app=~"kube-dns"}[1m]) * 100 > 90
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.k8s_app}}元件的cpu使用率超過90%"
          value: "{{ $value }}%"
          threshold: "90%"      
      - alert: kube-proxy開啟控制代碼數>600
        expr: process_open_fds{job=~"kubernetes-kube-proxy"}  > 600
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>600"
          value: "{{ $value }}"
      - alert: kube-proxy開啟控制代碼數>1000
        expr: process_open_fds{job=~"kubernetes-kube-proxy"}  > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>1000"
          value: "{{ $value }}"
      - alert: kubernetes-schedule開啟控制代碼數>600
        expr: process_open_fds{job=~"kubernetes-schedule"}  > 600
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>600"
          value: "{{ $value }}"
      - alert: kubernetes-schedule開啟控制代碼數>1000
        expr: process_open_fds{job=~"kubernetes-schedule"}  > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>1000"
          value: "{{ $value }}"
      - alert: kubernetes-controller-manager開啟控制代碼數>600
        expr: process_open_fds{job=~"kubernetes-controller-manager"}  > 600
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>600"
          value: "{{ $value }}"
      - alert: kubernetes-controller-manager開啟控制代碼數>1000
        expr: process_open_fds{job=~"kubernetes-controller-manager"}  > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>1000"
          value: "{{ $value }}"
      - alert: kubernetes-apiserver開啟控制代碼數>600
        expr: process_open_fds{job=~"kubernetes-apiserver"}  > 600
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>600"
          value: "{{ $value }}"
      - alert: kubernetes-apiserver開啟控制代碼數>1000
        expr: process_open_fds{job=~"kubernetes-apiserver"}  > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>1000"
          value: "{{ $value }}"
      - alert: kubernetes-etcd開啟控制代碼數>600
        expr: process_open_fds{job=~"kubernetes-etcd"}  > 600
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>600"
          value: "{{ $value }}"
      - alert: kubernetes-etcd開啟控制代碼數>1000
        expr: process_open_fds{job=~"kubernetes-etcd"}  > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "{{$labels.instance}}的{{$labels.job}}開啟控制代碼數>1000"
          value: "{{ $value }}"
      - alert: coredns
        expr: process_open_fds{k8s_app=~"kube-dns"}  > 600
        for: 2s
        labels:
          severity: warnning 
        annotations:
          description: "外掛{{$labels.k8s_app}}({{$labels.instance}}): 開啟控制代碼數超過600"
          value: "{{ $value }}"
      - alert: coredns
        expr: process_open_fds{k8s_app=~"kube-dns"}  > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          description: "外掛{{$labels.k8s_app}}({{$labels.instance}}): 開啟控制代碼數超過1000"
          value: "{{ $value }}"
      - alert: kube-proxy
        expr: process_virtual_memory_bytes{job=~"kubernetes-kube-proxy"}  > 2000000000
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 使用虛擬記憶體超過2G"
          value: "{{ $value }}"
      - alert: scheduler
        expr: process_virtual_memory_bytes{job=~"kubernetes-schedule"}  > 2000000000
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 使用虛擬記憶體超過2G"
          value: "{{ $value }}"
      - alert: kubernetes-controller-manager
        expr: process_virtual_memory_bytes{job=~"kubernetes-controller-manager"}  > 2000000000
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 使用虛擬記憶體超過2G"
          value: "{{ $value }}"
      - alert: kubernetes-apiserver
        expr: process_virtual_memory_bytes{job=~"kubernetes-apiserver"}  > 2000000000
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 使用虛擬記憶體超過2G"
          value: "{{ $value }}"
      - alert: kubernetes-etcd
        expr: process_virtual_memory_bytes{job=~"kubernetes-etcd"}  > 2000000000
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 使用虛擬記憶體超過2G"
          value: "{{ $value }}"
      - alert: kube-dns
        expr: process_virtual_memory_bytes{k8s_app=~"kube-dns"}  > 2000000000
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "外掛{{$labels.k8s_app}}({{$labels.instance}}): 使用虛擬記憶體超過2G"
          value: "{{ $value }}"
      - alert: HttpRequestsAvg
        expr: sum(rate(rest_client_requests_total{job=~"kubernetes-kube-proxy|kubernetes-kubelet|kubernetes-schedule|kubernetes-control-manager|kubernetes-apiservers"}[1m]))  > 1000
        for: 2s
        labels:
          team: admin
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): TPS超過1000"
          value: "{{ $value }}"
          threshold: "1000"   
      - alert: Pod_restarts
        expr: kube_pod_container_status_restarts_total{namespace=~"kube-system|default|monitor-sa"} > 0
        for: 2s
        labels:
          severity: warnning
        annotations:
          description: "在{{$labels.namespace}}名稱空間下發現{{$labels.pod}}這個pod下的容器{{$labels.container}}被重啟,這個監控指標是由{{$labels.instance}}採集的"
          value: "{{ $value }}"
          threshold: "0"
      - alert: Pod_waiting
        expr: kube_pod_container_status_waiting_reason{namespace=~"kube-system|default"} == 1
        for: 2s
        labels:
          team: admin
        annotations:
          description: "空間{{$labels.namespace}}({{$labels.instance}}): 發現{{$labels.pod}}下的{{$labels.container}}啟動異常等待中"
          value: "{{ $value }}"
          threshold: "1"   
      - alert: Pod_terminated
        expr: kube_pod_container_status_terminated_reason{namespace=~"kube-system|default|monitor-sa"} == 1
        for: 2s
        labels:
          team: admin
        annotations:
          description: "空間{{$labels.namespace}}({{$labels.instance}}): 發現{{$labels.pod}}下的{{$labels.container}}被刪除"
          value: "{{ $value }}"
          threshold: "1"
      - alert: Etcd_leader
        expr: etcd_server_has_leader{job="kubernetes-etcd"} == 0
        for: 2s
        labels:
          team: admin
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 當前沒有leader"
          value: "{{ $value }}"
          threshold: "0"
      - alert: Etcd_leader_changes
        expr: rate(etcd_server_leader_changes_seen_total{job="kubernetes-etcd"}[1m]) > 0
        for: 2s
        labels:
          team: admin
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 當前leader已發生改變"
          value: "{{ $value }}"
          threshold: "0"
      - alert: Etcd_failed
        expr: rate(etcd_server_proposals_failed_total{job="kubernetes-etcd"}[1m]) > 0
        for: 2s
        labels:
          team: admin
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}): 服務失敗"
          value: "{{ $value }}"
          threshold: "0"
      - alert: Etcd_db_total_size
        expr: etcd_debugging_mvcc_db_total_size_in_bytes{job="kubernetes-etcd"} > 10000000000
        for: 2s
        labels:
          team: admin
        annotations:
          description: "元件{{$labels.job}}({{$labels.instance}}):db空間超過10G"
          value: "{{ $value }}"
          threshold: "10G"
      - alert: Endpoint_ready
        expr: kube_endpoint_address_not_ready{namespace=~"kube-system|default"} == 1
        for: 2s
        labels:
          team: admin
        annotations:
          description: "空間{{$labels.namespace}}({{$labels.instance}}): 發現{{$labels.endpoint}}不可用"
          value: "{{ $value }}"
          threshold: "1"
    - name: 物理節點狀態-監控告警
      rules:
      - alert: 物理節點cpu使用率
        expr: 100-avg(irate(node_cpu_seconds_total{mode="idle"}[5m])) by(instance)*100 > 90
        for: 2s
        labels:
          severity: ccritical
        annotations:
          summary: "{{ $labels.instance }}cpu使用率過高"
          description: "{{ $labels.instance }}的cpu使用率超過90%,當前使用率[{{ $value }}],需要排查處理" 
      - alert: 物理節點記憶體使用率
        expr: (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) / node_memory_MemTotal_bytes * 100 > 90
        for: 2s
        labels:
          severity: critical
        annotations:
          summary: "{{ $labels.instance }}記憶體使用率過高"
          description: "{{ $labels.instance }}的記憶體使用率超過90%,當前使用率[{{ $value }}],需要排查處理"
      - alert: InstanceDown
        expr: up == 0
        for: 2s
        labels:
          severity: critical
        annotations:   
          summary: "{{ $labels.instance }}: 伺服器當機"
          description: "{{ $labels.instance }}: 伺服器延時超過2分鐘"
      - alert: 物理節點磁碟的IO效能
        expr: 100-(avg(irate(node_disk_io_time_seconds_total[1m])) by(instance)* 100) < 60
        for: 2s
        labels:
          severity: critical
        annotations:
          summary: "{{$labels.mountpoint}} 流入磁碟IO使用率過高!"
          description: "{{$labels.mountpoint }} 流入磁碟IO大於60%(目前使用:{{$value}})"
      - alert: 入網流量頻寬
        expr: ((sum(rate (node_network_receive_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*'}[5m])) by (instance)) / 100) > 102400
        for: 2s
        labels:
          severity: critical
        annotations:
          summary: "{{$labels.mountpoint}} 流入網路頻寬過高!"
          description: "{{$labels.mountpoint }}流入網路頻寬持續5分鐘高於100M. RX頻寬使用率{{$value}}"
      - alert: 出網流量頻寬
        expr: ((sum(rate (node_network_transmit_bytes_total{device!~'tap.*|veth.*|br.*|docker.*|virbr*|lo*'}[5m])) by (instance)) / 100) > 102400
        for: 2s
        labels:
          severity: critical
        annotations:
          summary: "{{$labels.mountpoint}} 流出網路頻寬過高!"
          description: "{{$labels.mountpoint }}流出網路頻寬持續5分鐘高於100M. RX頻寬使用率{{$value}}"
      - alert: TCP會話
        expr: node_netstat_Tcp_CurrEstab > 1000
        for: 2s
        labels:
          severity: critical
        annotations:
          summary: "{{$labels.mountpoint}} TCP_ESTABLISHED過高!"
          description: "{{$labels.mountpoint }} TCP_ESTABLISHED大於1000%(目前使用:{{$value}}%)"
      - alert: 磁碟容量
        expr: 100-(node_filesystem_free_bytes{fstype=~"ext4|xfs"}/node_filesystem_size_bytes {fstype=~"ext4|xfs"}*100) > 80
        for: 2s
        labels:
          severity: critical
        annotations:
          summary: "{{$labels.mountpoint}} 磁碟分割槽使用率過高!"
          description: "{{$labels.mountpoint }} 磁碟分割槽使用大於80%(目前使用:{{$value}}%)"
EOF

注意:

除了kube-proxy 預設在每個節點的 10249 埠上暴露其指標

其餘的 kubernetes-schedulekubernetes-controller-managerkubernetes-etcd 這些元件Pod 的容器需要根據自己的 k8s 叢集情況進行修改

kubectl apply -f prometheus-cfg.yaml

kubectl get cm prometheus-config -n monitor-sa -o yaml

同樣的還是需要檢查 cm 檔案中是否正確解析了 $1 $2

image-20241006191724613

3、重新生成 prometheus-deploy.yaml 檔案

k8s-master1 節點操作

cat > prometheus-deploy.yaml << EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus-server
  namespace: monitor-sa
  labels:
    app: prometheus
spec:
  replicas: 2
  selector:
    matchLabels:
      app: prometheus
      component: server
    #matchExpressions:
    #- {key: app, operator: In, values: [prometheus]}
    #- {key: component, operator: In, values: [server]}
  template:
    metadata:
      labels:
        app: prometheus
        component: server
      annotations:
        prometheus.io/scrape: 'false'
    spec:
      affinity:
        podAntiAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
          - labelSelector:
              matchExpressions:
              - key: app
                operator: In
                values:
                - prometheus
              - key: component
                operator: In
                values:
                - server
            topologyKey: kubernetes.io/hostname
      serviceAccountName: monitor
      containers:
      - name: prometheus
        image: quay.io/prometheus/prometheus:latest
        imagePullPolicy: IfNotPresent
        command:
        - "/bin/prometheus"
        args:
        - "--config.file=/etc/prometheus/prometheus.yml"
        - "--storage.tsdb.path=/prometheus"
        - "--storage.tsdb.retention=24h"
        - "--web.enable-lifecycle"
        ports:
        - containerPort: 9090
          protocol: TCP
        volumeMounts:
        - mountPath: /etc/prometheus
          name: prometheus-config
        - mountPath: /prometheus/
          name: prometheus-storage-volume
        - name: k8s-certs
          mountPath: /var/run/secrets/kubernetes.io/k8s-certs/etcd/
      - name: alertmanager
        image: prom/alertmanager:latest
        imagePullPolicy: IfNotPresent
        args:
        - "--config.file=/etc/alertmanager/alertmanager.yml"
        - "--log.level=debug"
        ports:
        - containerPort: 9093
          protocol: TCP
          name: alertmanager
        volumeMounts:
        - name: alertmanager-config
          mountPath: /etc/alertmanager
        - name: alertmanager-storage
          mountPath: /alertmanager
        - name: localtime
          mountPath: /etc/localtime
      volumes:
        - name: prometheus-config
          configMap:
            name: prometheus-config
        - name: prometheus-storage-volume
          hostPath:
           path: /data
           type: Directory
        - name: k8s-certs
          secret:
           secretName: etcd-certs
        - name: alertmanager-config
          configMap:
            name: alertmanager
        - name: alertmanager-storage
          hostPath:
           path: /data/alertmanager
           type: DirectoryOrCreate
        - name: localtime
          hostPath:
           path: /usr/share/zoneinfo/Asia/Shanghai
EOF

3.1、建立一個名為 etcd-certs 的 Secret

kubectl -n monitor-sa create secret generic etcd-certs --from-file=/etc/kubernetes/pki/etcd/server.key  --from-file=/etc/kubernetes/pki/etcd/server.crt --from-file=/etc/kubernetes/pki/etcd/ca.crt

image-20241006194149381

3.2、應用 prometheus-deploy.yaml 檔案

kubectl apply -f prometheus-deploy.yaml

kubectl get pods -n monitor-sa

image-20241006211236948

4、重新生成並建立 alertmanager-svc.yaml 檔案

cat >alertmanager-svc.yaml <<EOF
---
apiVersion: v1
kind: Service
metadata:
  labels:
    name: prometheus
    kubernetes.io/cluster-service: 'true'
  name: alertmanager
  namespace: monitor-sa
spec:
  ports:
  - name: alertmanager
    nodePort: 30066
    port: 9093
    protocol: TCP
    targetPort: 9093
  selector:
    app: prometheus
  sessionAffinity: None
  type: NodePort
EOF
kubectl apply -f alertmanager-svc.yaml

kubectl get svc alertmanager -n monitor-sa

image-20241006211627124

5、訪問 prometheus UI 介面

image-20241007102819517

5.1、【error】kube-controller-manager、etcd、kube-proxy、kube-scheduler 元件 connection refused

5.1.1、kube-proxy

預設情況下,該服務監聽埠只提供給127.0.0.1,需修改為0.0.0.0

 kubectl edit cm/kube-proxy -n kube-system
  • 編輯檔案,將檔案修改允許0.0.0.0即可,儲存
    metricsBindAddress: 0.0.0.0:10249

image-20241007121231980

  • 刪除重建 kube-proxy 的 pod
kubectl delete pod -l k8s-app=kube-proxy -n kube-system

image-20241007121419636

  • 效果

image-20241007121111763

5.1.2、kube-controller-manager

事先說明:到這一步我試過網上很多方法都沒有成功獲取到資料,所以我重新建立了 sa 慎用,僅供參考

  • 修改 kube-controller-manager 的 yaml 檔案

預設監聽本地修改為 0.0.0.0

- --bind-address=127.0.0.1
# 修改為
- --bind-address=0.0.0.0
  • 建立ServiceAccount

建立一個新的ServiceAccount,用於Prometheus訪問 kube-controller-manager

cat > prom-sa << EOF
apiVersion: v1
kind: ServiceAccount
metadata:
  name: prometheus-sa
  namespace: monitor-sa
EOF
  • 建立ClusterRole

建立一個ClusterRole,定義Prometheus所需的許可權。

cat > porm-role << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: prometheus-role
rules:
- nonResourceURLs:
  - "/metrics"
  verbs:
  - get
EOF
  • 建立ClusterRoleBinding

將ServiceAccount繫結到ClusterRole。

cat > prom-bind.yaml << EOF
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: prometheus-binding
subjects:
- kind: ServiceAccount
  name: prometheus-sa
  namespace: monitor-sa
roleRef:
  kind: ClusterRole
  name: prometheus-role
  apiGroup: rbac.authorization.k8s.io
EOF
  • 獲取ServiceAccount的Token

獲取ServiceAccount的Token,以便在Prometheus配置中使用。

TOKEN=$(kubectl get secret $(kubectl get sa prometheus-sa -n monitor-sa -o json | jq -r '.secrets[].name') -n monitor-sa -o json | jq -r '.data.token' | base64 --decode)
  • 修改Prometheus配置檔案(cm)
- job_name: 'kubernetes-controller-manager'
      scheme: https
      tls_config:
        insecure_skip_verify: true  # 禁用證書驗證
      authorization:
        credentials: eyJhbGciOiJSUzI1NiIsImtpZCI6IkFEWVNqaWlueWVDMzBUcTZvQk9MRkpxQ0diLWRGWkNoaWlpZkgwR21NcEkifQ.eyJpc3MiOiJrdWJlcm5ldGVzL3NlcnZpY2VhY2NvdW50Iiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9uYW1lc3BhY2UiOiJtb25pdG9yLXNhIiwia3ViZXJuZXRlcy5pby9zZXJ2aWNlYWNjb3VudC9zZWNyZXQubmFtZSI6InByb21ldGhldXMtc2EtdG9rZW4tbnQ5bm4iLCJrdWJlcm5ldGVzLmlvL3NlcnZpY2VhY2NvdW50L3NlcnZpY2UtYWNjb3VudC5uYW1lIjoicHJvbWV0aGV1cy1zYSIsImt1YmVybmV0ZXMuaW8vc2VydmljZWFjY291bnQvc2VydmljZS1hY2NvdW50LnVpZCI6IjQ4YTA5NDExLTAwMmYtNDE0Ni05YzY4LTBiNmVjOWYzYWZlZCIsInN1YiI6InN5c3RlbTpzZXJ2aWNlYWNjb3VudDptb25pdG9yLXNhOnByb21ldGhldXMtc2EifQ.DNgCjTVxsrGDltvQZG-x7qPQrh369SO_e0faGrrhjgkBLS4q2sh85wkaBNNZcIjxZcVk7ZU9gQmQkM3AIgGIcIURpQGDMgVVI_xF1JV8iQWe-nL1yHnQAXDjyMAd1826wVvMH8LSKqdKfPVaMHN8t0LScX5yHonSJUqoevxi7Mm7tiUd33IlMQ6xH6M8Tu8bsg-fOVmL6nnGpC1tPgaZy8M_GA_Kh9j8SwHXi4Yd9r75eOSa3J6N4KF6n-EPKxnGmXDooA60G94YptsDFCQMi1t4TLAFR1FKraycWHwPbIwviUZTvA1WXbkiHnh0R6q-y0hHJVbAi_ZXagVXKZFBaw  # 替換為實際的Token值
      scrape_interval: 5s
      static_configs:
      - targets: ['192.168.112.10:10257']
  • 重啟Prometheus

更新配置後,重啟Prometheus以應用新的配置。

kubectl rollout restart deployment/prometheus-server -n monitor-sa
  • 效果

image-20241007173313086

5.1.3、kube-schedule

和 kube-controller-manager 操作一致

  • 效果

image-20241007174612964

5.1.4、etcd

  • 修改建立 etcd 的 yaml 檔案

新增 master 節點 ip + etcd port

vim /etc/kubernetes/manifests/etcd.yaml

- --listen-metrics-urls=http://127.0.0.1:2381,http://192.168.112.10:2381

image-20241007175408503

  • 修改 prometheus.yaml 檔案
改為 http

image-20241007175613604

  • 效果

image-20241007175150365

6、點選Alerts,檢視

image-20241007175925889

7、把controller-manager的cpu使用率大於90%展開

FIRING表示prometheus已經將告警發給alertmanager

在Alertmanager 中可以看到有 alert。

image-20241007180133147

8、登入 alertmanager UI

<master-ip>:svc-alertmanager-port

192.168.112.10:30066

image-20241007180525364

image-20241007180341995

9、登入 QQ 郵箱檢視告警資訊

image-20241007180724123

四、配置 Alertmanager 報警 -- 傳送告警到釘釘

1、手機端拉群

因為 PC 端不好操作

IMG_20241007_185306

2、建立自定義機器人

自定義機器人安全設定 - 釘釘開放平臺 (dingtalk.com)

群設定
image-20241007185813640
機器人
image-20241007190002110
新增機器人
image-20241007190053622
自定義
image-20241007190125011
新增
image-20241007190214813
機器人名字、安全設定
image-20241007190915612
保管好 Webhook
image-20241007191221897

3、獲取釘釘的 Webhook 外掛

master 節點操作

git clone git@github.com:misakivv/prometheus-webhook-dingtalk.git

cd prometheus-webhook-dingtalk

tar zxvf prometheus-webhook-dingtalk-0.3.0.linux-amd64.tar.gz

cd prometheus-webhook-dingtalk-0.3.0.linux-amd64

image-20241007192418023

4、啟動釘釘告警外掛

nohup ./prometheus-webhook-dingtalk --web.listen-address="0.0.0.0:8060" --ding.profile="cluster1=https://oapi.dingtalk.com/robot/send?access_token=feb3df2c6a987c8c1466c16eb90f4c2d3817c481aacf15cecc46f588f2716f25" &

image-20241007202305558

5、對 alertmanager-cm.yaml 檔案做備份

cp alertmanager-cm.yaml alertmanager-cm.yaml.bak

6、重新生成新的 alertmanager-cm.yaml 檔案

cat >alertmanager-cm.yaml <<EOF
kind: ConfigMap
apiVersion: v1
metadata:
  name: alertmanager
  namespace: monitor-sa
data:
  alertmanager.yml: |-
    global:
      resolve_timeout: 1m
      smtp_smarthost: 'smtp.qq.com:465'
      smtp_from: '2830909671@qq.com'
      smtp_auth_username: '2830909671@qq.com'
      smtp_auth_password: 'ajjgpgwwfkpcdgih'
      smtp_require_tls: false
    route:
      group_by: [alertname]
      group_wait: 10s
      group_interval: 10s
      repeat_interval: 10m
      receiver: cluster1
    receivers:
    - name: cluster1
      webhook_configs:
      - url: 'http://192.168.112.10:8060/dingtalk/cluster1/send'
        send_resolved: true
EOF

7、重建資源以生效

kubectl delete cm alertmanager -n monitor-sa

kubectl apply -f alertmanager-cm.yaml

kubectl delete -f prometheus-cfg.yaml

kubectl apply -f prometheus-cfg.yaml

kubectl delete -f prometheus-deploy.yaml

kubectl apply -f prometheus-deploy.yaml

image-20241007203234415

8、效果

image-20241007203102485
image-20241007203427726
image-20241007203454338
image-20241007203613020
image-20241007203905132
image-20241007203933639

暫時先這樣,其實 alertmanager 還有靜默、去重、抑制等功能,下一篇再共同學習

相關文章