Prometheus+Grafana+Alertmanager搭建全方位的監控告警系統

prometheus安裝和配置

prometheus組件介紹

1.Prometheus Server: 用於收集和存儲時間序列數據。node

2.Client Library: 客戶端庫,檢測應用程序代碼,當Prometheus抓取實例的HTTP端點時,客戶端庫會將全部跟蹤的metrics指標的當前狀態發送到prometheus server端。linux

3.Exporters: prometheus支持多種exporter,經過exporter能夠採集metrics數據,而後發送到prometheus server端git

4.Alertmanager: 從 Prometheus server 端接收到 alerts 後,會進行去重,分組,並路由到相應的接收方,發出報警,常見的接收方式有:電子郵件,微信,釘釘, slack等。github

5.Grafana:監控儀表盤web

6.pushgateway: 各個目標主機可上報數據到pushgatewy,而後prometheus server統一從pushgateway拉取數據。docker

prometheus架構圖

img

  從上圖可發現,Prometheus整個生態圈組成主要包括prometheus server,Exporter,pushgateway,alertmanager,grafana,Web ui界面,Prometheus server由三個部分組成,Retrieval,Storage,PromQL 。數據庫

  • retrieval負責在活躍的target主機上抓取監控指標數據
  • storage主要是把採集到的數據存儲到磁盤中
  • promQL是prometheus提供的查詢語言模塊

prometheus工做流程

  1. Prometheus server可按期從活躍的(up)目標主機上(target)拉取監控指標數據,目標主機的監控數據可經過配置靜態job或者服務發現的方式被prometheus server採集到,這種方式默認的pull方式拉取指標;也可經過pushgateway把採集的數據上報到prometheus server中;還可經過一些組件自帶的exporter採集相應組件的數據;
  2. Prometheus server把採集到的監控指標數據保存到本地磁盤或者數據庫;
  3. Prometheus採集的監控指標數據按時間序列存儲,經過配置報警規則,把觸發的報警發送到alertmanager
  4. Alertmanager經過配置報警接收方,發送報警到郵件,微信或者釘釘等
  5. Prometheus 自帶的web ui界面提供PromQL查詢語言,可查詢監控數據
  6. Grafana可接入prometheus數據源,把監控數據以圖形化形式展現出

安裝node-exporter組件

​ node-exporter是採集機器(物理機、虛擬機、雲主機等)的監控指標數據,可以採集到的指標包括CPU, 內存,磁盤,網絡,文件數等信息。json

實驗環境

​ 一個master節點,一個node節點。c#

在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

經過node-exporter採集數據

curl http://主機ip:9100/metrics

在k8s集羣中部署promethues

  1. 建立namespace、sa帳號,在k8s集羣的master節點操做api

    kubectl create ns monitor-sa
    kubectl create serviceaccount monitor -n monitor-sa
    #把sa帳號monitor經過clusterrolebing綁定到clusterrole上
    kubectl create clusterrolebinding moniror-clusterrolebinding -n monitor-sa --clusterrole=cluster-admin --serviceaccount=monitor-sa:monitor
  2. 建立數據目錄

    # 在k8s集羣的任何一個node節點操做,本實驗在node1上操做
    mkdir /data
    chmod 777 /data/
  3. 安裝prometheus,在master節點操做

    #建立一個configmap存儲卷,用來存放prometheus配置信息
    #prometheus-cfg.yaml
    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: ':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//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: :
          - 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 
    ---
    #經過deployment部署prometheus
    #prometheus-deploy.yaml
    apiVersion: apps/v1
    kind: Deployment
    metadata:
      name: prometheus-server
      namespace: monitor-sa
      labels:
        app: prometheus
    spec:
      replicas: 1
      selector:
        matchLabels:
          app: prometheus
          component: server
      template:
        metadata:
          labels:
            app: prometheus
            component: server
          annotations:
            prometheus.io/scrape: 'false'
        spec:
          nodeName: node1
          serviceAccountName: monitor
          containers:
          - name: prometheus
            image: prom/prometheus:v2.2.1
            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

    注意:經過上面命令生成的promtheus-cfg.yaml文件會有一些問題,$1和$2這種變量在文件裏沒有,須要在k8s的master1節點打開promtheus-cfg.yaml文件,手動把$1和$2這種變量寫進文件裏,promtheus-cfg.yaml文件須要手動修改部分以下:

    22行的replacement: ':9100'變成replacement: '${1}:9100'
    42行的replacement: /api/v1/nodes//proxy/metrics/cadvisor變成
                  replacement: /api/v1/nodes/${1}/proxy/metrics/cadvisor
    73行的replacement:  變成replacement: $1:$2

    給prometheus pod 建立一個service

    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
    #查看service在物理機映射的端口
    kubectl	get svc -n monitor-sa
    
    #訪問prometheus web ui 界面
    http://172.16.9.3:30426/graph
    #點擊頁面的Status->Targets,可看到以下,說明咱們配置的服務發現能夠正常採集數據

    prometheus熱更新

    #爲了每次修改配置文件能夠熱加載prometheus,也就是不中止prometheus,就可使配置生效,如修改prometheus-cfg.yaml,想要使配置生效可用以下熱加載命令:
    curl -X POST http://10.244.1.125:9090/-/reload

    #10.244.1.66是prometheus的pod的ip地址

    #熱加載速度比較慢,能夠暴力重啓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

    注意:

    線上最好熱加載,暴力刪除可能形成監控數據的丟失

Grafana安裝和配置

下載安裝Grafana須要的鏡像

上傳heapster-grafana-amd64_v5_0_4.tar.gz鏡像到k8s的各個master節點和k8s的各個node節點,而後在各個節點手動解壓:
docker load -i heapster-grafana-amd64_v5_0_4.tar.gz

鏡像所在的百度網盤地址以下:

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

在k8s的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

經過kubectl get sac -n cube-system看到grafana暴漏的蘇主機端口是32351,咱們能夠訪問k8s集羣的master節點ip:32351便可訪問grafana的web界面

Grafana界面接入prometheus數據源

  1. 登陸Grafana,172.16.9.3:32351,帳號密碼都是admin

  2. 配置grafana界面,選擇create your first data source

    Name:Prometheus
    Type:Prometheus
    HTTP出的URL:http://prometheus.monitor-sa.svc:9090

    點擊左下角Save&Test,出現Data source is working,說明prometheus數據源成功的被grafana接入了。

    導入監控模板,可在以下連接搜索
    https://grafana.com/dashboards?dataSource=prometheus&search=kubernetes
    也可直接導入node_exporter.json監控模板,這個能夠把node節點指標顯示出來,node_exporter.json在百度網盤地址以下:

    連接:https://pan.baidu.com/s/1vF1kAMRbxQkUGPlZt91MWg 提取碼:kyd6

    還可直接導入docker_rev1.json,能夠把容器相關的數據展現出來
    docker_rev1.json在百度網盤地址以下

    連接:https://pan.baidu.com/s/17o_nja5N2R-g9g5PkJ3aFA 提取碼:vinv

    導入監控模版步驟:點擊左側+號下面的Import,選擇Upload json file,選擇一個本地的json文件便可。

安裝配置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在運行中。

安裝kube-state-metrics組件

  1. 建立sa,並對sa受權,在master節點操做

    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
  2. 安裝cube-state-metrics組件,在master節點操做

    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:v1.9.0
            ports:
            - containerPort: 8080
    EOF
  3. 建立service,在master節點操做

    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

    在Grafana web界面導入kubernetes Cluster和kubernetes cluster monitoring

    連接:https://pan.baidu.com/s/1QAMqT8scsXx-lzEPI6MPgA 
    提取碼:i4yd

安裝和配置Alertmanager-發送報警到qq郵箱

在k8s的master節點建立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.163.com:25'
      smtp_from: '15011572657@163.com'
      smtp_auth_username: '15011572657'
      smtp_auth_password: 'BDBPRMLNZGKWRFJP'
      smtp_require_tls: false
    route:
      group_by: [alertname]
      group_wait: 10s
      group_interval: 10s
      repeat_interval: 10m
      receiver: default-receiver
    receivers:
    - name: 'default-receiver'
      email_configs:
      - to: 'y1486170457@qq.com'
        send_resolved: true
EOF

Alertmanager配置文件解釋說明:

smtp_smarthost: 'smtp.163.com:25'
#用於發送郵件的郵箱的SMTP服務器地址+端口
smtp_from: '15011572657@163.com'
#這是指定從哪一個郵箱發送報警
smtp_auth_username: '15011572657'
#這是發送郵箱的認證用戶,不是郵箱名
smtp_auth_password: 'BDBPRMLNZGKWRFJP'
#這是發送郵箱的受權碼而不是登陸密碼
email_configs:
   - to: 'y1486170457@qq.com'
#to後面指定發送到哪一個郵箱,我發送到個人qq郵箱,你們須要寫本身的郵箱地址,不該該跟smtp_from的郵箱名字重複

在master節點從新生成prometheus-cfg.yaml文件

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: ['172.16.9.3:10251']
    - job_name: 'kubernetes-controller-manager'
      scrape_interval: 5s
      static_configs:
      - targets: ['172.16.9.3:10252']
    - job_name: 'kubernetes-kube-proxy'
      scrape_interval: 5s
      static_configs:
      - targets: ['172.16.9.3:10249','172.16.9.4: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: ['172.16.9.3:2379']
  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: "{{$lables.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}}%)"

一樣須要手動添加$的變量。

在k8smaster節點從新生成一個prometheus-deploy.yaml文件

cat >prometheus-deploy.yaml <<EOF
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: prometheus-server
  namespace: monitor-sa
  labels:
    app: prometheus
spec:
  replicas: 1
  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:
      nodeName: node1
      serviceAccountName: monitor
      containers:
      - name: prometheus
        image: prom/prometheus:v2.2.1
        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:v0.14.0
        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

生成一個etch-certs,這個在部署prometheus須要

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

更新yaml文件,查看部署是否成功。

在k8smaster節點上從新生成一個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

#查看service在物理機映射的端口

kubectl get svc -n monitor-sa

訪問prometheus界面,點擊alerts,把controller-manager的cpu使用率大於90%展開,可看到status爲FIRING,表示prometheus已經將告警發給alertmanager,在Alertmanager 中能夠看到有一個 alert。

登陸alertmanager web界面查看

配置alertmanager報警-發送報警到釘釘

  1. 建立釘釘機器人

    打開電腦版釘釘,建立一個羣,建立自定義機器人,按以下步驟建立
    https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
    
    我建立的機器人以下:
    羣設置-->智能羣助手-->添加機器人-->自定義-->添加
    
    機器人名稱:kube-event
    接收羣組:釘釘報警測試
    
    安全設置:
    自定義關鍵詞:cluster1
    
    上面配置好以後點擊完成便可,這樣就會建立一個kube-event的報警機器人,建立機器人成功以後怎麼查看webhook,按以下:
    
    點擊智能羣助手,能夠看到剛纔建立的kube-event這個機器人,點擊kube-event,就會進入到kube-event機器人的設置界面
    出現以下內容:
    機器人名稱:kube-event
    接受羣組:釘釘報警測試
    消息推送:開啓
    webhook:https://oapi.dingtalk.com/robot/send?access_token=9c03ff1f47b1d15a10d852398cafb84f8e81ceeb1ba557eddd8a79e5a5e5548e
    安全設置:
    自定義關鍵詞:cluster1
  2. 安裝釘釘的webhook插件,在master節點操做

    tar zxvf prometheus-webhook-dingtalk-0.3.0.linux-amd64.tar.gz
    #壓縮包地址
    #連接:https://pan.baidu.com/s/1_HtVZsItq2KsYvOlkIP9DQ 
    #提取碼:d59o
    cd prometheus-webhook-dingtalk-0.3.0.linux-amd64
    
    #啓動釘釘報警插件
    nohup ./prometheus-webhook-dingtalk --web.listen-address="0.0.0.0:8060" --ding.profile="cluster1=https://oapi.dingtalk.com/robot/send?access_token=4372b6419ff1f198a9732dfb9f469f8c7eb7310dec00ede726a7ecd9d235c9b9" &
    
    #對原來的文件作備份
    cp alertmanager-cm.yaml alertmanager-cm.yaml.bak
    
    #從新生成一個新的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.163.com:25'
          smtp_from: '15011572657@163.com'
          smtp_auth_username: '15011572657'
          smtp_auth_password: 'BDBPRMLNZGKWRFJP'
          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.124.16:8060/dingtalk/cluster1/send'
            send_resolved: true
    EOF
    
    #經過kubectl apply使配置生效
    kubectl delete -f alertmanager-cm.yaml
    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
    #經過上面步驟,就能夠實現釘釘報警了

    參考連接:https://mp.weixin.qq.com/s/I1-xfxuny_S8DHchkXHSpQ

相關文章
相關標籤/搜索