prometheus 監控的部署


一、prometheus 介紹

1.1、prometheus 簡介

Prometheus(普羅米修斯)是由 SoundCloud 開源的監控告警解決方案,自2012年成為社區開源項目,擁有非常活躍的開發人員和用戶社區。同時為強調開源及獨立維護,Prometheus於2016年加入雲原生雲計算基金會(CNCF),成為繼Kubernetes之后的第二個托管項目。
官方網站:https://prometheus.io
項目托管:https://github.com/prometheus

1.2、Prometheus 特點

  • 多維數據模型:由度量名稱和鍵值對標識的時間序列數據。
  • PromSQL:一種靈活的查詢語言,可以利用多維數據完成復雜的查詢。
  • 不依賴分布式存儲,單個服務器節點可直接工作。
  • 基於HTTP的pull方式采集時間序列數據。
  • 推送時間序列數據通過PushGateway組件支持。
  • 通過服務發現或靜態配置發現目標。
  • 多種圖形模式及儀表盤支持(grafana)。

1.3、Prometheus 組件

  • Prometheus Server:用於抓取指標、存儲時間序列數據。
  • push gateway:對於那些生存時間很短的job工作,讓job主動把監控指標push到getway,Prometheus再從getway中拉取。
  • exporter:用於暴露已有的第三方服務的 metrics 給 Prometheusalertmanager。
  • alertmanager:告警組件,會將Prometheus Server的數據進行去除重復數據,分組,並路由到對收的接受方式,發出報警。
  • Web UI:Prometheus內置一個簡單的Web控制台,可以查詢指標,查看配置信息或者Service Discovery等,實際工作中,查看指標或者創建儀表盤通常使用Grafana,Prometheus作為Grafana的數據源。

1.4、Prometheus 工作原理

​ 通過HTTP周期性抓取被監控組件的狀態,任意組件只要提供對應的HTTP接口並符合Prometheus定義的數據格式,就可以接入Prometheus監控;Prometheus Server負責定時在目標上抓取metrics(指標)數據,每個抓取目標都需要暴露一個HTTP服務接口用於Prometheus定時抓取。這種調用被監控對象獲取監控數據的方式被稱為Pull(拉);Pull方式體現了Prometheus獨特的設計哲學與大多數采用Push(推)方式的監控不同。

二、部署 Prometheus

(1) 下載

mkdir -pv /usr/local/soft/package && cd /usr/local/soft/package
wget https://github.com/prometheus/prometheus/releases/download/v2.29.2/prometheus-2.29.2.linux-amd64.tar.gz

(2) 解壓並重命名

tar -xf prometheus-2.29.2.linux-amd64.tar.gz -C /usr/local/soft
cd /usr/local/soft
mv prometheus-2.29.2.linux-amd64 prometheus

(3) 配置

配置共分為三部分,分別是全局配置、告警配置、收集數據配置

vim /usr/local/soft/prometheus/prometheus.yml
#全局配置
global:
  scrape_interval: 15s #每隔15秒向目標抓取一次數,默認為一分鍾
  evaluation_interval: 15s #每隔15秒執行一次告警規則,默認為一分鍾
  # scrape_timeout: 600s  #抓取數據的超時時間,默認為10s

#告警配置
alerting:
  alertmanagers:
    - static_configs:
        - targets:
          # - alertmanager:9093	 #alertmanager所部署機器的ip和端口

#定義告警規則和閾值的yml文件
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

#收集數據配置
#以下是Prometheus自身的一個配置.
scrape_configs:
  #這個配置是表示在這個配置內的時間序例,每一條都會自動添加上這個{job_name:"prometheus"}的標簽.
  - job_name: "prometheus"
    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.
    static_configs:			#靜態配置
      - targets: ["localhost:9090"]

(4) 啟停

cd /usr/local/soft/prometheus

#校驗配置文件
./promtool check config ./prometheus.yml

#啟動
nohup ./prometheus --config.file=./prometheus.yml \
--web.listen-address=0.0.0.0:9090 \
--web.enable-lifecycle \
--storage.tsdb.retention=90d \
--storage.tsdb.path=./data &

##啟動參數介紹
--config.file      	   #加載prometheus的配置文件
--web.listen-address   #監聽prometheus的web地址和端口
--web.enable-lifecycle #熱啟動參數,可以在不中斷服務的情況下重啟加載配置文件
--storage.tsdb.retention   #數據持久化的時間                         
--storage.tsdb.path        #數據持久化的保存路徑

#停止
ps -ef | grep prometheus | grep  -v grep | awk '{print $2}' | xagrs kill -9
#或者
curl -XPOST http://localhost:9090/-/quit

#重載
curl -XPOST http://localhost:9090/-/reload

(5) 以 systemd 的方式管理 prometheus 的啟停(非必選)

cat > /usr/lib/systemd/system/prometheus.service <<EOF
[Unit]
Description=The Prometheus Server
After=network.target
[Service]
ExecStart=/usr/local/soft/prometheus/prometheus \
  --config.file=/usr/local/soft/prometheus/prometheus.yml \
  --web.listen-address=0.0.0.0:9090 \
  --web.enable-lifecycle \
  --storage.tsdb.retention=90d \
  --storage.tsdb.path="/usr/local/soft/prometheus/data/"
Restart=on-failure
RestartSec=15s
[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload && systemctl enable prometheus && systemctl restart prometheus

(6) web 訪問

通過瀏覽器訪問 http://IP:9090 即可

三、部署 node_exporter

(1) 下載

cd /usr/local/soft/package
wget https://github.com/prometheus/node_exporter/releases/download/v1.2.2/node_exporter-1.2.2.linux-amd64.tar.gz

(2) 解壓並重命名

tar -xf node_exporter-1.2.2.linux-amd64.tar.gz -C /usr/local/soft
cd /usr/local/soft
mv node_exporter-1.2.2.linux-amd64 node_exporter

(3) 啟停

#啟動
nohup ./node_exporter --web.listen-address=0.0.0.0:4220 &

##啟動參數介紹
注意:相關啟動的參數
--web.listen-address     #node_expoetrt暴露的端口
--collector.systemd	     #從systemd中收集
--collector.systemd.unit-whitelist   ##白名單,收集目標
		".+"         		      #從systemd中循環正則匹配單元
		"(docker|sshd|nginx).service"  #白名單,收集目標,收集參數node_systemd_unit_state
		
#停止
ps -ef | grep node_exporter | grep  -v grep | awk '{print $2}' | xagrs kill -9

(4) 以 systemd 的方式管理 node_exporter 的啟停(非必選)

cat > /usr/lib/systemd/system/node_exporter.service   <<EOF
[Unit]
Description=The node_exporter Server
After=network.target
[Service]
ExecStart=/usr/local/soft/node_exporter/node_exporter \
  --web.listen-address=0.0.0.0:4220 \
  --collector.systemd \
  --collector.systemd.unit-whitelist=(sshd|docker).service
Restart=on-failure
RestartSec=15s
SyslogIdentifier=node_exporter
[Install]
WantedBy=multi-user.target 
EOF

systemctl daemon-reload && systemctl enable node_exporter && systemctl restart node_exporter

四、部署 alertmanager

(1) 下載

cd /usr/local/soft/package
wget https://github.com/prometheus/alertmanager/releases/download/v0.23.0/alertmanager-0.23.0.linux-amd64.tar.gz

(2) 解壓並重命名

tar -xf alertmanager-0.23.0.linux-amd64.tar.gz -C /usr/local/soft
cd /usr/local/soft
mv alertmanager-0.23.0.linux-amd64 alertmanager

(3) 配置

配置共分為六部分,分別是global配置、templates配置、route配置、receivers配置、inhibit_rules配置、靜默配置

#global配置
global:
  resolve_timeout: 5m  #在報警恢復的時候不是立馬發送的,在接下來的這個時間內,如果沒有此報警信息觸發,才發送報警恢復消息
  smtp_smarthost: 'smtp.exmail.qq.com:465' #發件人對應郵件提供商的smtp地址,此處為騰訊企業郵箱stmp配置
  smtp_from: 'xxx@company.com'          #發件人郵箱地址
  smtp_auth_username: 'xxx@company.com' #發件人的登陸用戶名,默認和發件人地址一致
  smtp_auth_password: 'xxxxxxx'       #發件人的登陸密碼,也可以是授權碼。
  smtp_require_tls: false		      #是否需要tls協議,默認是true
#templates配置
templates:
- '/usr/local/soft/alertmanager/email.tmpl'	 #自定義通知的模板的目錄或者文件
#route配置
route:						#每個輸入警報進入根路由
  group_by: ['alertname','cluster','service']	#將傳入的報警中有這些標簽的分為一個組,比如, cluster=A 和 alertname=LatencyHigh 會分成一個組
  group_wait: 30s	#指分組創建多久后才可以發送壓縮的警報,也就是初次發警報的延時,這樣會確保第一次通知的時候, 有更多的報警被壓縮在一起
  group_interval: 5m	#當第一個通知發送,等待多久發送壓縮的警報
  repeat_interval: 1h	#如果報警發送成功, 等待多久重新發送一次
  receiver: 'email'	 #默認警報接收者
#receivers配置
receivers:
- name: 'email'		#警報名稱
  email_configs:
  - to: 'xxx@xxx.com'		#接收警報的email
    send_resolved: true		#是否發送警報解除郵件
    html: '{{ template "email.htm" . }}'	#模板
    headers: { Subject: "{{ .CommonLabels.severity }} {{ .CommonAnnotations.summary }}" }	#標題
#報警抑制規則
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']	#通過上面的配置,可以在alertname相同的情況下,critaical的報警會抑制warning級別的報警信息。
#靜默配置
#靜默配置是通過web界面配置的,通常用於服務升級或者長時間的服務故障,確保在接下來的時間內不會在收到同樣報警信息

(4) 啟停

#啟動
nohup ./alertmanager --config.file="alertmanager.yml" --web.listen-address=":9093" &

#停止
ps -ef |grep alertmanager |grep -v grep  |awk '{print $2}' | xargs kill -9

#重載
curl -XPOST http://localhost:9093/-/reload

(5) 以 systemd 的方式管理 alertmanager 的啟停(非必選)

cat > /usr/lib/systemd/system/alertmanager.service   <<EOF
[Unit]
Description=The Prometheus Server
After=network.target
[Service]
ExecStart=/usr/local/soft/alertmanager/alertmanager \
  --config.file=/usr/local/soft/alertmanager/alertmanager.yml \
  --web.listen-address=0.0.0.0:9093
Restart=on-failure
RestartSec=15s
[Install]
WantedBy=multi-user.target
EOF

systemctl daemon-reload && systemctl enable alertmanager && systemctl restart alertmanager

(6) web 訪問

通過瀏覽器訪問 http://IP:9093 即可

五、部署 grafana

(1) 下載

cd /usr/local/soft/package
wget https://dl.grafana.com/enterprise/release/grafana-enterprise-8.1.2.linux-amd64.tar.gz

(2) 解壓並重命名

tar -xf grafana-enterprise-8.1.2.linux-amd64.tar.gz -C /usr/local/soft
cd /usr/local/soft
mv grafana-enterprise-8.1.2.linux-amd64 grafana

(3) 啟動

#啟動
nohup /usr/local/soft/grafana/bin/grafana-server &

#停止
ps -ef |grep grafana-server |grep -v grep  |awk '{print $2}' | xargs kill -9

(4) 訪問

通過瀏覽器訪問 http://IP:3000 ,默認用戶名和密碼為admin/admin,第一次登陸系統會要求修改密碼

六、監控案例

6.1、監控mysql

6.1.1、安裝 mysqld_exporter

mysqld_exporter 安裝在 mysql 服務器上,或者單獨安裝均可

(1) 下載

mkdir -pv /usr/local/soft/package && cd /usr/local/soft/package
wget https://github.com/prometheus/mysqld_exporter/releases/download/v0.13.0/mysqld_exporter-0.13.0.linux-amd64.tar.gz

(2) 解壓並重命名

tar -xf mysqld_exporter-0.13.0.linux-amd64.tar.gz -C /usr/local/soft
cd  /usr/local/soft
mv mysqld_exporter-0.13.0.linux-amd64 mysqld_exporter

(3) 配置mysql的監控賬號

cd  /usr/local/soft/mysqld_exporter
vim my.cnf
[client]
user=root
password=123456
host=localhost
port=3306
#sock="/tmp/mysql_3306.sock"   #如果數據庫需要sock文件就配置上,否則不需要此配置

(4) 啟停

#啟動
nohup /usr/local/soft/mysqld_exporter/mysqld_exporter \
	--web.listen-address=":9104" \
	--config.my-cnf=/usr/local/soft/mysqld_exporter/my-38.cnf &

#停止
ps -ef | grep mysqld_exporter | grep -v grep | awk '{print $2}' | xargs kill -9  

如果在一台服務器上,啟動多個 mysqld_exporter ,可通過監聽不同端口實現:

nohup /usr/local/soft/mysqld_exporter/mysqld_exporter \
	--web.listen-address=":9104" \
	--config.my-cnf=/usr/local/soft/mysqld_exporter/my-38.cnf &
	
nohup /usr/local/soft/mysqld_exporter/mysqld_exporter \
	--web.listen-address=":9105" \
	--config.my-cnf=/usr/local/soft/mysqld_exporter/my-22.cnf &
	
nohup /usr/local/soft/mysqld_exporter/mysqld_exporter \
--web.listen-address=":9106" \
--config.my-cnf=/usr/local/soft/mysqld_exporter/my-245.cnf &

6.1.2、配置 prometheus

(1) 修改 prometheus 配置文件

vim /usr/local/soft/prometheus/prometheus.yml
global:
  scrape_interval: 15s .
  evaluation_interval: 15s

alerting:
  alertmanagers:
    - static_configs:
        - targets:
           - 172.16.16.18:9093	#alertmanager地址

rule_files:		#報警規則文件
  - "/usr/local/soft/prometheus/rules/mysql_rule.yml"

scrape_configs:
  - job_name: "prometheus"
    static_configs:
      - targets: ["localhost:9090"]
  
  - job_name: "node-exporter"
    static_configs:
      - targets: ["localhost:4220"]

  - job_name: "mysql"	#配置 mysql job
    file_sd_configs:	#配置文件自動發現
      - files: 
        - /usr/local/soft/prometheus/conf.d/mysql_export.json

(2) 配置文件自動發現

cd /usr/local/soft/prometheus
mkdir conf.d

vim conf.d/mysql_export.json
[
    {
        "labels":{						#配置自定義標簽
         	"desc": "172.16.16.38",
        	"group": "mysql",
        	"host_ip": "172.16.16.38",
        	"hostname": "mysql-master"
        },
        "targets": ["172.16.16.18:9104"]	#配置metrics地址
    },
    {
        "labels":{
            "desc": "172.16.16.22",
            "group": "mysql",
            "host_ip": "172.16.16.22",
            "hostname": "mysql-slave01"
        },
        "targets": ["172.16.16.18:9105"]
    },
    {
        "labels":{
            "desc": "172.16.16.245",
            "group": "mysql",
            "host_ip": "172.16.16.245",
            "hostname": "mysql-slave02"
        },
        "targets": ["172.16.16.18:9106"]
    }
]

(3) 配置告警規則

cd /usr/local/soft/prometheus
mkdir rules

vim rules/mysql_rule.yml
groups:
- name: mysqlAlerts
  rules:
  - alert: mysql告警
    expr: mysql_up{job="mysql"} == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "{{$labels.desc}} mysql已停止運行超過1m"
      description: "{{$labels.desc}} mysql中斷超過1m"
      message: "{{$labels.desc}} mysql已停止運行"
      console: "請檢查{{$labels.desc}}節點的mysql是否正常"
  - alert: mysql slave節點IO線程異常
    expr: mysql_slave_status_slave_io_running{job="mysql"} == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "{{$labels.desc}} mysql slave節點IO線程已停止運行超過1m"
      description: "{{$labels.desc}} mysql slave節點IO線程中斷超過1m"
      message: "{{$labels.desc}} mysql slave節點IO線程已停止運行"
      console: "請檢查{{$labels.desc}}節點的mysql是否正常"
  - alert: mysql slave節點SQL線程異常
    expr: mysql_slave_status_slave_sql_running{job="mysql"} == 0
    for: 1m
    labels:
      severity: critical
    annotations:
      summary: "{{$labels.desc}} mysql slave節點SQL線程已停止運行超過1m"
      description: "{{$labels.desc}} mysql slave節點SQL線程中斷超過1m"
      message: "{{$labels.desc}} mysql slave節點SQL線程已停止運行"
      console: "請檢查{{$labels.desc}}節點的mysql是否正常"

6.1.3、配置 alertmanager

6.1.3.1、配置郵件告警

(1) 修改 alertmanager 配置文件

cd /usr/local/soft/alertmanager

vim alertmanager.yml
global:
  resolve_timeout: 5m
  smtp_smarthost: "smtp.qq.com:465"			#配置郵件告警
  smtp_from: "xxxx@qq.com"
  smtp_auth_username: "xxxx@qq.com"
  smtp_auth_password: "fafafafafafafa"
  smtp_require_tls: false
templates:
- '/usr/local/soft/alertmanager/email.tmpl'		#配置模板
route:
  group_by: ['alertname']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 30m
  receiver: 'email'
receivers:
- name: 'email'
  email_configs:
  - to: 'xxx@company.com'					#配置郵件接收人
    send_resolved: true
    html: '{{ template "email.htm" . }}'	#模板
    headers: { Subject: "[{{ .Status }}]{{ .CommonLabels.severity }} {{ .CommonAnnotations.summary }}" }			 #標題
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

(2) 創建模板文件

vim email.tmpl
{{ define "email.htm" }}
{{ range .Alerts.Resolved }}
<pre>
告警已解除!

歷史告警信息如下:
</pre>
{{ end }}
{{ range .Alerts }}
<pre>
========start==========
告警程序: {{ .Labels.job }}
告警級別: {{ .Labels.severity }} 級別
告警類型: {{ .Labels.alertname }}
故障主機: {{ .Labels.desc }}
告警主題: {{ .Annotations.summary }}
告警詳情: {{ .Annotations.description }}
處理方法: {{ .Annotations.console }}
觸發時間: {{ (.StartsAt.Add 28800e9).Format "2006-01-02 15:04:05" }}
========end==========
</pre>
{{ end }}
{{ end }}
6.1.3.2、配置釘釘告警

(1) 下載釘釘告警插件

cd /usr/local/soft/package
wget https://github.com/timonwong/prometheus-webhook-dingtalk/releases/download/v2.0.0/prometheus-webhook-dingtalk-2.0.0.linux-amd64.tar.gz

(2) 解壓並重命名

tar -xf prometheus-webhook-dingtalk-2.0.0.linux-amd64.tar.gz -C /usr/local/soft/
cd /usr/local/soft/
mv prometheus-webhook-dingtalk-2.0.0.linux-amd64 prometheus-webhook-dingtalk

(3) 創建釘釘自定義機器人

在電腦端釘釘的任一個群點擊 群設置 --> 智能群助手 --> 添加機器人,進入后添加“自定義機器人”,然后按要求操作,獲取 Webhook 和 加密串。

(4) 修改釘釘告警插件的配置文件

cd /usr/local/soft/prometheus-webhook-dingtalk
cp config.example.yml config.yml

vim config.yml
## Request timeout
# timeout: 5s

## Uncomment following line in order to write template from scratch (be careful!)
#no_builtin_template: true

## Customizable templates path
#templates:
#  - contrib/templates/legacy/template.tmpl

## You can also override default template using `default_message`
## The following example to use the 'legacy' template from v0.3.0
#default_message:
#  title: '{{ template "legacy.title" . }}'
#  text: '{{ template "legacy.content" . }}'

## Targets, previously was known as "profiles"
##將webhook地址復制到url,加密串復制到secret
targets:
  webhook1:
    url: https://oapi.dingtalk.com/robot/send?access_token=b7a4392cacc6ac5962e8671486ffafa28aa14337e037455dbd11dc3e4a7b8db8
    # secret for signature
    secret: SEC4b4c021b752a0216ced1ba953a6ed78bf4202ca8c9106c6841a92ba502547a5f
    message:
      title: '{{ template "legacy.title" . }}'
      text: '{{ template "legacy.content" . }}'
      #mobiles: ['156xxxx8827', '189xxxx8325']

(5) 啟動釘釘告警插件

cd /usr/local/soft/prometheus-webhook-dingtalk
nohup ./prometheus-webhook-dingtalk --config.file=./config.yml &

(6) 測試

curl http://localhost:8060/dingtalk/webhook1/send -H 'Content-Type: application/json' -d '{"msgtype": "text","text": {"content": "監控告警"}}'

(7) 配置 alertmanager

cd /usr/local/soft/alertmanager/

vim alertmanager.yml
global:
  resolve_timeout: 5m

route:
  group_by: ['alertname']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 5m
  receiver: 'dingtalk'
receivers:						#配置釘釘告警
- name: 'dingtalk'
  webhook_configs:
  - url: 'http://localhost:8060/dingtalk/webhook1/send'
    send_resolved: true
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

結合兩種方式告警的示例如下:

global:
  resolve_timeout: 5m
  smtp_smarthost: "smtp.qq.com:465"
  smtp_from: "1954938301@qq.com"
  smtp_auth_username: "1954938301@qq.com"
  smtp_auth_password: "wgwgolvivcogfabj"
  smtp_require_tls: false
templates:
- '/usr/local/soft/alertmanager/email.tmpl'
route:
  group_by: ['alertname']
  group_wait: 30s
  group_interval: 5m
  repeat_interval: 5m
  receiver: 'dingtalk'			#默認告警接收者
  routes:						#子路由
  - receiver: 'email'			
    match:
      severity: 'critical'		#標簽severity為critical時觸發
receivers:
- name: 'email'
  email_configs:
  - to: 'huy@ktpis.com'
    send_resolved: true
    html: '{{ template "email.htm" . }}'
    headers: { Subject: "[{{ .Status | title }}]{{ .CommonLabels.severity }} {{ .CommonAnnotations.summary }}" }
- name: 'dingtalk'
  webhook_configs:
  - url: 'http://localhost:8060/dingtalk/webhook1/send'
    send_resolved: true
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM