使用Docker部署Prometheus實現微信郵件報警

Prometheus組成及架構

1591330f85b0add2a5c3fa40e5e0d194.png


Prometheus生態圈中包含了多個組件,其中許多組件是可選的:
java

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

  • Client Library:客戶端庫,爲須要監控的服務生成相應的Metrics並暴露給Prometheus server。當Prometheus server來pull時,直接返回實時狀態的Metrics。git

  • Push Gateway:主要用於短時間的Jobs。因爲這類Jobs存在時間較短,可能在Prometheus來pull以前就消失了。爲此,此次Jobs能夠直接向Prometheus server端推送它們的Metrics。這種方式主要用於服務層面的Metrics,對於機器層面的Metrices,須要使用Node Exporter。github

  • Exporters:用於暴露已有的第三方服務的Metrics給Prometheus。web

  • Alertmanager:從Prometheus server端接收到alerts後,會進行去除重複數據,分組,並路由到對應的接收方式,發出報警。常見的接收方式有:電子郵件,PagerDuty,OpsGenie,webhook 等。docker


Prometheus官方文檔中的架構圖:

22796c59f5083174390718a25b6e7131.png


從上圖能夠看出,Prometheus的主要模塊包括:Prometheus server,exporters,Pushgateway,PromQL,Alertmanager以及圖形界面。
其大概的工做流程是:
  • Prometheus server按期從配置好的Jobs或者exporters中拉Metrics,或者接收來自Pushgateway發過來的Metrics,或者從其餘的Prometheus server中拉Metrics。centos

  • Prometheus server在本地存儲收集到的Metrics,並運行已定義好的alert.rules,記錄新的時間序列或者向Alertmanager推送警報。api

  • Alertmanager根據配置文件,對接收到的警報進行處理,發出告警。tomcat

  • 在圖形界面中,可視化採集數據。微信


Prometheus官網:https://prometheus.io/


Prometheus安裝及配置

1591330f85b0add2a5c3fa40e5e0d194.png


 
 

192.168.16.251      Prometheus,grafana,alertmanager,Node-exporter
192.168.16.252      Node-exporter,Jmx-exporter,cAdvisor

建立Prometheus配置文件prometheus.yml(本地宿主機/root/prometheus/conf/下建立):

 
 

global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
alerting:       #指定alertmanager報警組件地址
  alertmanagers:
  - static_configs:
    - targets: [ '192.168.16.251:9093']

rule_files:  #指定報警規則文件
  - "rules.yml"

scrape_configs:
  - job_name: 'nodehost'   
    static_configs:
      - targets: ['192.168.16.251:9100']
        labels:
          appname: 'Node1'
 static_configs:
      - targets: ['192.168.16.252:9100']
        labels:
          appname: 'Node2'
  - job_name: 'tomcat'
    static_configs:
      - targets: ['192.168.16.173:12345']
        labels:
          appname: 'mytest'
  - job_name: 'cadvisor'
    static_configs:
      - targets: [ '192.168.16.251:8080','192.168.16.252:8080','192.168.16.173:8080']
        labels:
          appname: 'cadvisor'
  - job_name: 'prometheus'
    static_configs:
      - targets: [ '192.168.16.251:9090']
        labels:
          appname: 'prometheus'

上面咱們使用靜態的方式指定了各Metris的地址,但後面應用數量愈來愈多,手動的添加就不太現實了,Prometheus支持服務發現等多種方式。
具體信息移步官網:https://prometheus.io/docs/prometheus/latest/configuration/configuration/
建立Prometheus規則文件rules.yml(本地宿主機/root/prometheus/conf/下建立)。
下面監控宿主機和容器的內存,CPU,磁盤等狀態。

 
 

groups:
- name: example #定義規則組
  rules:
  - alert: InstanceDown  #定義報警名稱
    expr: up == 0   #Promql語句,觸發規則
    for: 1m            # 一分鐘
    labels:       #標籤訂義報警的級別和主機
      name: instance
      severity: Critical
    annotations:  #註解
      summary: " {{ $labels.appname }}" #報警摘要,取報警信息的appname名稱
      description: " 服務中止運行 "   #報警信息
      value: "{{ $value }}%"  # 當前報警狀態值
- name: Host
  rules:
  - alert: HostMemory Usage
    expr: (node_memory_MemTotal_bytes - (node_memory_MemFree_bytes + node_memory_Buffers_bytes + node_memory_Cached_bytes)) / node_memory_MemTotal_bytes * 100 >  80
    for: 1m
    labels:
      name: Memory
      severity: Warning
    annotations:
      summary: " {{ $labels.appname }} "
      description: "宿主機內存使用率超過80%."
      value: "{{ $value }}"
  - alert: HostCPU Usage
    expr: sum(avg without (cpu)(irate(node_cpu_seconds_total{mode!='idle'}[5m]))) by (instance,appname) > 0.65
    for: 1m
    labels:
      name: CPU
      severity: Warning
    annotations:
      summary: " {{ $labels.appname }} "
      description: "宿主機CPU使用率超過65%."
      value: "{{ $value }}"
  - alert: HostLoad 
    expr: node_load5 > 4
    for: 1m
    labels:
      name: Load
      severity: Warning
    annotations:
      summary: "{{ $labels.appname }} "
      description: " 主機負載5分鐘超過4."
      value: "{{ $value }}"
  - alert: HostFilesystem Usage
    expr: 1-(node_filesystem_free_bytes / node_filesystem_size_bytes) >  0.8
    for: 1m
    labels:
      name: Disk
      severity: Warning
    annotations:
      summary: " {{ $labels.appname }} "
      description: " 宿主機 [ {{ $labels.mountpoint }} ]分區使用超過80%."
      value: "{{ $value }}%"
  - alert: HostDiskio
    expr: irate(node_disk_writes_completed_total{job=~"Host"}[1m]) > 10
    for: 1m
    labels:
      name: Diskio
      severity: Warning
    annotations:
      summary: " {{ $labels.appname }} "
      description: " 宿主機 [{{ $labels.device }}]磁盤1分鐘平均寫入IO負載較高."
      value: "{{ $value }}iops"
  - alert: Network_receive
    expr: irate(node_network_receive_bytes_total{device!~"lo|bond[0-9]|cbr[0-9]|veth.*|virbr.*|ovs-system"}[5m]) / 1048576  > 3 
    for: 1m
    labels:
      name: Network_receive
      severity: Warning
    annotations:
      summary: " {{ $labels.appname }} "
      description: " 宿主機 [{{ $labels.device }}] 網卡5分鐘平均接收流量超過3Mbps."
      value: "{{ $value }}3Mbps"
  - alert: Network_transmit
    expr: irate(node_network_transmit_bytes_total{device!~"lo|bond[0-9]|cbr[0-9]|veth.*|virbr.*|ovs-system"}[5m]) / 1048576  > 3
    for: 1m
    labels:
      name: Network_transmit
      severity: Warning
    annotations:
      summary: " {{ $labels.appname }} "
      description: " 宿主機 [{{ $labels.device }}] 網卡5分鐘內平均發送流量超過3Mbps."
      value: "{{ $value }}3Mbps"
- name: Container
  rules:
  - alert: ContainerCPU Usage
    expr: (sum by(name,instance) (rate(container_cpu_usage_seconds_total{image!=""}[5m]))*100) > 60
    for: 1m
    labels:
      name: CPU
      severity: Warning
    annotations:
      summary: "{{ $labels.name }} "
      description: " 容器CPU使用超過60%."
      value: "{{ $value }}%"
  - alert: ContainerMem Usage
 #    expr: (container_memory_usage_bytes - container_memory_cache)  / container_spec_memory_limit_bytes   * 100 > 10  
    expr:  container_memory_usage_bytes{name=~".+"}  / 1048576 > 1024
    for: 1m
    labels:
      name: Memory
      severity: Warning
    annotations:
      summary: "{{ $labels.name }} "
      description: " 容器內存使用超過1GB."
      value: "{{ $value }}G"


部署Prometheus

1591330f85b0add2a5c3fa40e5e0d194.png


 
 

docker run -d -p 9090:9090 --name=prometheus \
 -v  /root/prometheus/conf/:/etc/prometheus/  \
prom/prometheus

上面採用的官方鏡像,由於啓動參數沒有指定--web.enable-lifecycle,因此沒法使用熱加載,時區也是相差八個小時,咱們能夠經過官方提供的Dockerfile進行修改。
下載源碼包,製做Prometheus鏡像:https://github.com/prometheus/prometheus

 
 

FROM   centos:7
LABEL maintainer "The Prometheus Authors <prometheus-developers@googlegroups.com>, Custom by <leichen.china@gmail.com>"
COPY prometheus                             /bin/prometheus
COPY promtool                               /bin/promtool
COPY console_libraries/                     /usr/share/prometheus/console_libraries/
COPY consoles/                              /usr/share/prometheus/consoles/

WORKDIR    /prometheus
RUN ln -snf /usr/share/zoneinfo/Asia/Shanghai  /etc/localtime
ENTRYPOINT [ "/bin/prometheus" ]
CMD        [ "--config.file=/etc/prometheus/prometheus.yml", \
             "--storage.tsdb.path=/prometheus", \
             "--web.console.libraries=/usr/share/prometheus/console_libraries", \
             "--web.enable-lifecycle", \
             "--web.console.templates=/usr/share/prometheus/consoles" ]

建立容器並運行:

 
 

docker build  -t prometheus:latest .
docker run -d -p 9090:9090 --name prometheus   -v  /root/prometheus/conf/:/etc/prometheus/    prometheus:latest

訪問Prometheus的9090端口,能夠查看監控數據:

33a6698ac50213baeac93b84e953eb07.png


部署Node-exporter

1591330f85b0add2a5c3fa40e5e0d194.png


docker run -d -p 9100:9100   -v "/:/host:ro,rslave" quay.io/prometheus/node-exporter --path.rootfs /host


部署cadvisor-exporter

1591330f85b0add2a5c3fa40e5e0d194.png


docker run --volume=/:/rootfs:ro --volume=/var/run:/var/run:rw --volume=/sys:/sys:ro --volume=/var/lib/docker/:/var/lib/docker:ro --publish=8080:8080 --detach=true --name=cadvisor --net=host google/cadvisor:latest

訪問cAdvisor的8080端口,能夠看到容器的監控指標:

b3594feae13f98e7700bc9d9139085b2.png


部署jmx-exporter

1591330f85b0add2a5c3fa40e5e0d194.png


下載jar :https://github.com/prometheus/jmx_exporter(jmx_prometheus_javaagent-0.11.0.jar )
配置文件:https://github.com/prometheus/jmx_exporter/tree/master/example_configs
中間件啓動參數添加:
CATALINA_OPTS="-javaagent:/app/tomcat-8.5.23/lib/jmx_prometheus_javaagent-0.11.0.jar=1234:/app/tomcat-8.5.23/conf/config.yaml"

具體查看http://www.unmin.club


Grafana安裝及配置

1591330f85b0add2a5c3fa40e5e0d194.png


docker run -d -i -p 3000:3000 -e "GF_SERVER_ROOT_URL=http://grafana.server.name" -e "GF_SECURITY_ADMIN_PASSWORD=secret" --net=host grafana/grafana

Web訪問:192.168.16.251:3000
user:admin,passwd:secret
首先咱們添加數據源:

1591330f85b0add2a5c3fa40e5e0d194.png


import導入8919Node-exporter展現模板:

b01fed5e7bc27e6257a21f222ce08518.png


針對容器和JMX的監控模板,咱們能夠去https://grafana.com/dashboards自行查找。


配置報警Alertmanager

5878314be2e56fb1b1c0a63280b49ade.png


建立alertmanager.yml報警通知文件:
 
 

global:
  resolve_timeout: 2m
  smtp_smarthost: smtp.163.com:25
  smtp_from: 12345678@163.com
  smtp_auth_username: 12345678@163.com
  smtp_auth_password: 123456 (受權碼)

templates:     ##消息模板
  - '/etc/alertmanager/template/wechat.tmpl'
route:
  group_by: ['alertname_wechat']
  group_wait: 30s
  group_interval: 60s
  receiver: 'wechat'    # 優先使用wechat發送
  repeat_interval: 1h
  routes:  #子路由,使用email發送
  - receiver: email
    match_re: 
      serverity: email
receivers:
- name: 'email'
  email_configs:
  - to: '11111122@qq.com'
    send_resolved: true  # 發送已解決通知
- name: 'wechat'
  wechat_configs:
  - corp_id: 'wwd402ce40b1120f24' #企業ID
    to_party: '2'  # 通知組ID
    agent_id: '1000002'    
    api_secret: '9nmYa4pWq63sQ123kToCbh_oNc' # 生成的secret
    send_resolved: true

編寫微信通知模板:

 
 

{{ define "wechat.default.message" }}
{{ range $i$alert :=.Alerts }}
========監控報警==========
告警狀態:{{   .Status }}
告警級別:{{ $alert.Labels.severity }}
告警類型:{{ $alert.Labels.alertname }}
告警應用:{{ $alert.Annotations.summary }}
告警主機:{{ $alert.Labels.instance }}
告警詳情:{{ $alert.Annotations.description }}
觸發閥值:{{ $alert.Annotations.value }}
告警時間:{{ $alert.StartsAt.Format "2006-01-02 15:04:05" }}
========end=============
{{ end }}
{{ end }}

部署Alertmanager:

docker run -d -p 9093:9093 --name alertmanager  -v /root/alertmanager/alertmanager.yml:/etc/alertmanager/alertmanager.yml -v /root/alertmanager/template:/etc/alertmanager/template docker.io/prom/alertmanager:latest

訪問Alertmanager的9093端口,能夠看到當前報警狀態:

41eac0019223bfcf466afb4a7877ac5f.png

c179db7322ad3c7dea497dcff5f585bc.png

ce22ca92ef2e2b5984654e9791ac13c6.png

原文連接:https://www.jianshu.com/p/dfd6ba5206dc
相關文章
相關標籤/搜索