grafana結合prometheus提供了大量的模板,雖然這些模板幾乎監控到了常見的監控指標,但是有些特殊的指標還是沒能提供(也可能是我沒找到指標名稱)。受zabbix的影響,自然而然想到了自定義監控項,promethues同樣也支持。
一、簡介
Pushgateway是prometheus的一個重要組件,利用該組件可以實現自動以監控指標,從字面意思來看,該部件不是將數據push到prometheus,而是作為一個中間組件收集外部push來的數據指標,prometheus會定時從pushgateway上pull數據。
pushgateway並不是將Prometheus的pull改成了push,它只是允許用戶向他推送指標信息,並記錄。而Prometheus每次從 pushgateway拉取的數據並不是期間用戶推送上來的所有數據,而是client端最后一次push上來的數據。因此需設置client端向pushgateway端push數據的時間小於等於prometheus去pull數據的時間,這樣一來可以保證prometheus的數據是最新的。
【注意】如果client一直沒有推送新的指標到pushgateway,那么Prometheus獲取到的數據是client最后一次push的數據,直到指標消失(默認5分鍾)。
Prometheus本身是不會存儲指標的,但是為了防止pushgateway意外重啟、工作異常等情況的發送,在pushgateway處允許指標暫存,參數--persistence.interval=5m,默認保存5分鍾,5分鍾后,本地存儲的指標會刪除。
使用pushgateway的理由:
1、prometheus默認采用pull模式,由於不在一個網絡或者防火牆的問題,導致prometheus 無法拉取各個節點的數據。
2、監控業務數據時,需要將不同數據匯總,然后由prometheus統一收集
pushgateway的缺陷:
1、多個節點的數據匯總到pushgateway,當它宕機后影響很大
2、pushgateway可以持續化推送所有的監控數據,即使監控已經下線,還會獲取舊的監控數據。需手動清理不需要的數據
3、重啟后數據丟失
二、啟動
1、docker 啟動pushgateway
首先需要登錄dockerhub
docker login 輸入用戶名密碼即可
docker pull prom/pushgateway
docker run -d --name pushgateway -p 9091:9091 --restart=always prom/pushgateway
2、訪問9091端口(http://pushgatewayIP:9091)
證明pushgateway部署成功
3、在prometheus中添加pushgateway節點
打開prometheus的配置文件
- job_name: 'pushgateway' static_configs: - targets: ['pushgatewayIP:9091'] honor_labels: true #作用:如果沒有設置instance標簽,Prometheus服務器也會附加標簽,否則instance標簽值會為空
重啟prometheus后,登陸web UI,查看prometheus的targets
4、測試
向pushgateway發送數據
echo "test 123" | curl --data-binary @- http://pushgatewayIP:9091/metrics/job/test
上述測試的目的是,在被監控的機器上,想pushgateway發送了一條數據,內容是“test 123”,指標名稱是“test”,指標值是“123”;
http://pushgatewayIP:9091/metrics/job/test,此次也聲名了,在pushgateway處建立一個job為test的指標。
推送的API路徑
所有的推送都是通過HTTP完成的,API路徑如下:
/metrics/job/<JOBNAME>{/<LABEL_NAME>/<LABEL_VALUE>}
JOBNAME:job標簽的值
/ 是轉義符
登陸prometheus webUI查詢指標是否生成
三、pushgateway發送數據的API格式
API格式:
http://pustgatewayIP/metrices/job/job名/標簽名/標簽值(一般 標簽名 采用 instance)
例子:
http://pustgatewayIP/metrics/job/
/sb/instance/si
/testjob/abc/pushgateway1
/testjob/yyy/pushgateway1
分別觸發上述三個API,打開pushgateway的web UI
四、發送的數據類型
1、發送counter類型
可以一次發送單個,也可以發送多個數據
cat <<EOF | curl --data-binary @- http://pushgatewayIP:9091/metrics/job/docker_runtime/instance/xa-lsr-billubuntu
# TYPE docker_runtime counter
docker_runtime{name="cadvisor"} 33
docker_runtime{name="nginx"} 331
docker_runtime{name="abc"} 332
EOF
2、發送gauage類型
可以一次發送單個,也可以發送多個數據
cat <<EOF | curl --data-binary @- http://pushgatewayIP:9091/metrics/job/docker_runtime/instance/xa-lsr-billubuntu
# TYPE docker_runtime gauge
# HELP docker_runtime time sec
docker_runtime{name="nginx"} 22
docker_runtime{name="cadvisor"} 22
docker_runtime{name="bbc"} 22
EOF
3、curl的另一種發送形式
--data-binary <data> 與-d, --data類似,如果以@開頭,則后面必須跟着文件名,並且文件中的換行符,回車符會保留,也不會做
將要發送的數據寫入文件“a”,作用是將文件中的數據發送到指定地方
curl --data-binary "@a" http://pushgatewayIP:9091/metrics/job/docker_runtime/instance/xa-lsr-billubuntu