使用pushgateway监控需要上传文件的应用接口

背景简介

什么是Promethues

prometheus是一套开源的监控系统,可以非常全面地监测硬件服务器、存储、网络、API等监控对象。prometheus主要采用pull模式,即,prometheus服务器通过http get请求来获取各个监控对象的监控数据。当然,各监控对象需要安装相应的node expoter客户端。此外,由于一些特殊的监控和自定义监控,prometheus也提供了blackbox expoter黑盒监控和pushgateway等更灵活的获取监控数据的方式。

PUSHGW TOPO

什么是pushgateway

pushgateway是prometheus监控系统中的一个可选组成部分。它类似于一个反向代理,Prometheus正常从pushgateway拉取监控数据,pushgateway的数据来自于用户自定义的metric,用户将这些metric push到pushgateway,即自定义脚本推送的数据。

为什么使用pushgateway

通常pushgateway用于解决网络与Prometheus不通的区域充当代理的角色,也可以实现一些自定义的metrics。

pushgateway与blackbox有什么不同

blackbox expoter也是prometheus重要组成部分,blackbox exporter主要的功能是接口监控,内置了很多icmp,tcp,http等监控模板。black expoter可以满足大部分api监控需求,但一些复杂参数的api监控并没有办法实现。另外blackbox也能充当代理的角色,这点和pushgateway是相似的。但pushgateway内置api接口支持用户自定义的metrics,这是blackbox exporter做不到的。

使用pushgateway监控需要上传文件的接口

需求描述

需求是需要对一批接口进行http状态码监控,这批接口要求指定header参数,另外必须上传图片

根据需求首先想到的是blackbox,添加监控比较方便,有现成模板,但是由于接口需要上传文件,查了官网资料,没有发现blackbox exporter内模板支持post请求文件上传,于是只能使用pushgateway

获取监控数据

我们需要把监控到的数据发给pushgateway,监控数据是post请求的状态码,使用以下脚本实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#定义api路径和请求头host参数
path=('https://192.168.0.1/some/path1' 'https://192.168.0.1/some/path2' 'https://192.168.0.1/some/path3')
host=('host1' 'host2' 'host3' )

for (( i = 0; i < ${#host[@]}; ++i ))
do
#获取请求结果
result=`curl -s -w '%{http_code}\n' -o /dev/null --data-binary @/opt/pic.jpg --connect-timeout 5 -H "host: ${host[i]}" ${path[i]}`
if [ -z "$result" ]
then
value_code=0
else
value_code=$(echo $result)
#将结果发给pushgateway(本地)
echo "somejob_http_code ${value_code}" | curl --data-binary @- http://localhost:9091/metrics/job/somejob/instance/192.168.0.1/hostname/${host[i]}
fi
echo ${host[i]}"==="${path[i]}"==="$value_code
done

其中,

上传文件的路径需要以绝对路径引用,因为这个脚本将来是要被crontab执行的,工作目录并不是脚本所在目录

另外,可以先把push数据那句话注释掉验证请求结果

添加crontab任务

无误后,使用crontab定时45s执行

1
2
3
4
5
6
7
8
#打开crontab配置文件
sudo crontab -e

#添加定时任务
* * * * * sleep 45; bash /opt/shell.sh > /dev/null 2>&1

#验证定时任务是否成功添加
sudo crontab -l

定时任务配置完成后,pushgateway就会周期性收到监控数据并更新了,如果prometheus 已经有pushgateway的job的话,就可以查到metrics了

配置prometheus.yml

如果prometheus没有集成pushgateway,则需要在prometheus.yml添加如下job并重载

1
2
3
4
5
- job_name: 'pushgateway'
scrape_interval: 45s
honor_labels: true
static_configs:
- targets: ['1.1.1.1:9091']
1
2
#prometheus热重载
curl -X POST http://127.0.0.1:9090/-/reload

重载后可在prometheus查询到新的metrics

1
somejob_http_code{}