前面我們的資料大部分都是由節點上的agent端收集本地資料後暴露到/metrics,再由prometheus pull到本地進行存儲展示的
但是終歸這種名額收集的方法是有局限性的,并且有可能被其他如防火牆等安全機制攔截,又或者我們的client端并不能采集到我們想要的名額
那麼在這種情況下,我們可以通過一個工具Pushgateway 來進行代理,将其他區域或自定義的名額收集并送出到prometheus上
一. 部署pushgateway
#拉取軟體包
wget https://github.com/prometheus/pushgateway/releases/download/v1.4.0/pushgateway-1.4.0.linux-amd64.tar.gz
#我的包
連結:https://pan.baidu.com/s/1U2uhZB051KiUg_hsw5aS4A
提取碼:1111
#----------------------------------------------------------------------------------#
#解壓
tar -zxvf pushgateway-1.4.0.linux-amd64.tar.gz
#拷貝二進制檔案
cp pushgateway-1.4.0.linux-amd64/pushgateway /usr/bin/
#添加服務檔案
cat > /usr/lib/systemd/system/pushgateway.service <<EOF
[Unit]
Description=pushgateway
Documentation=https://github.com/prometheus/pushgateway
After=network.target
[Service]
ExecStart=/usr/bin/pushgateway
Restart=on-failure
[Install]
WantedBy=multi-user.target
EOF
啟動服務
systemctl daemon-reload
systemctl enable pushgateway
systemctl start pushgateway
systemctl status pushgateway
通路
http://192.168.1.20:9091/
二. 添加prometheus抓取
#添加監控配置
cat >> /etc/prometheus/prometheus.yml <<EOF
- job_name: pushgateway
honor_labels: true
file_sd_configs:
- files:
- targets/pushgateway/*.json
refresh_interval: 5m
EOF
#建立目錄
mkdir /etc/prometheus/targets/pushgateway -p
#添加監控節點
cat > /etc/prometheus/targets/pushgateway/test1.json <<EOF
[{
"targets": ["192.168.1.20:9091"]
}]
EOF
說明
#說明
1. honor_labels
#true #當為true時,prometheus在拉取時會使用pushgateway上的job名稱和instance的标簽
#false #當為false時,prometheus在拉取時會添加exported_的字首,并在伺服器上為這些标簽添加新值
2. refresh_interval #服務發現間隔
重載服務
systemctl restart prometheus
三. 資料推送
pushgateway僅僅起到了一個代理的作用,我們需要将名額"post"到pushgateway後再由prometheus去采集
格式
http://<ip>:9091/metrics/job/<JOBNAME>{/<LABEL_NAME>/<LABEL_VALUE>}
案例1 簡單推送
#格式
http://<ip>:9091/metrics/job/<JOBNAME>{/<LABEL_NAME>/<LABEL_VALUE>}
#我們推送一個名額做測試
echo 'metrics_name 1' | curl --data-binary @- http://192.168.1.20:9091/metrics/job/test1/
#metrics_name 1 #名額名稱:值 也就是我們送出上資料的值
#/job/test1/ #标簽的名稱和值,按照順序以/隔開會組成一對,可以設定多個标簽
我們可以看到,除了我們上傳的名額,還多了兩個名額 push_time_seconds 和 push_failure_time_seconds
他們的作用就是用來表示上一次抓取成功/失敗的時間。也會随之被promethues拉取到
案例2 推送時添加多個名額
#設定多個标簽推送
echo 'metrics_name2 2' | curl --data-binary @- http://192.168.1.20:9091/metrics/job/test1/instance/192.168.1.20/mode/test2/haha/test3
我們現在可以去prometheus檢視我們推送的值了
案例3 推送多個名額
#添加多個名額
cat <<EOF | curl --data-binary @- http://192.168.1.20:9091/metrics/job/test/instance/192.168.1.20
metrics_name10{code="200"} 1
metrics_name11{code="404"} 1
metrics_name12{code="503"} 1
EOF
案例4 基于檔案推送
#添加名額檔案
cat > test.json <<EOF
http_request_total{code="200"} 276683
http_request_total{code="301"} 232683
http_request_total{code="404"} 0
EOF
#推送
curl -XPOST --data-binary @test.json http://127.0.0.1:9091/metrics/job/test_2/instance/192.168.1.20
案例5 删除标簽
#需要寫上完整的标簽名稱
curl -X DELETE http://192.168.1.20:9091/metrics/job/test/instance/192.168.1.20