有的时候需要在prometheus里面输出一些自定义的metrics。实现很容易,把这些自定义的值保存在一个prom文件里面,然后让node exporter加载这个文件就可以了。
下面看一个简单的例子。
我有一个DHCP Kea服务器,已经配置了API的功能。
比如说,我发送一个curl的请求,可以获得一个JSON的返回值,通过jq我可以获取一些子网的信息。
ubuntu@fortinetdhcp-bour-syd:~/api$ subnets=$(curl -s -X POST -H "Content-Type: application/json" -d '{ "command": "config-get", "service": [ "dhcp4" ] }' http://10.2.0.15:8000/ | jq -r .[].arguments.Dhcp4.subnet4[].subnet)
ubuntu@fortinetdhcp-bour-syd:~/api$ echo $subnets
115.70.209.12/31 115.70.234.24/31 115.70.244.24/31 115.70.231.4/31 115.70.193.188/31 220.233.145.26/31 58.96.57.40/29 115.70.162.158/31 115.70.162.178/31 58.96.22.228/31
稍微修改一下脚本,把这些子网的信息写入一个 prom文件中,注意prometheus支持的数据类型就4种,counter,gauge, histogram 和 summary。这里我指定的类型是 gauge
ubuntu@fortinetdhcp-bour-syd:~/api$ cat testapi.sh
#!/bin/bash
rm key/kea.prom
subnets=$(curl -s -X POST -H "Content-Type: application/json" -d '{ "command": "config-get", "service": [ "dhcp4" ] }' http://10.2.0.15:8000/ | jq -r .[].arguments.Dhcp4.subnet4[].subnet)
echo "# TYPE kea_bucket gauge" > key/kea.prom
for subnet in $subnets
do
echo $subnet
echo "kea_bucket{subnet=\"$subnet\"} 1" >> key/kea.prom
done
然后重新修改一下我的systemd的Unit文件,在ExecStart里面添加一个路径指向我的prom文件所在的目录
ubuntu@fortinetdhcp-bour-syd:/etc/systemd/system$ cat node_exporter.service
[Unit]
Description=Prometheus Node Exporter
Wants=network-online.target
After=network-online.target
[Service]
User=node_exporter
Group=node_exporter
Type=simple
ExecStart=/usr/local/bin/node_exporter --collector.systemd --collector.textfile.directory /tmp/key
[Install]
WantedBy=multi-user.target
ubuntu@fortinetdhcp-bour-syd:/etc/systemd/system$
重启一下
sudo sytemctl daemon-reload
sudo systemctl restart node_exporter
查询试试看
ubuntu@fortinetdhcp-bour-syd:/etc/systemd/system$ curl http://127.0.0.1:9100/metrics | grep subnet
% Total % Received % Xferd Average Speed Time Time Time Current
Dload Upload Total Spent Left Speed
100 3944 0 3944 0 0 69192 0 --:--:-- --:--:-- --:--:-- 68000kea_bucket{subnet="115.70.162.158/31"} 1
kea_bucket{subnet="115.70.162.178/31"} 1
kea_bucket{subnet="115.70.193.188/31"} 1
kea_bucket{subnet="115.70.209.12/31"} 1
kea_bucket{subnet="115.70.231.4/31"} 1
kea_bucket{subnet="115.70.234.24/31"} 1
kea_bucket{subnet="115.70.244.24/31"} 1
kea_bucket{subnet="220.233.145.26/31"} 1
kea_bucket{subnet="58.96.22.228/31"} 1
kea_bucket{subnet="58.96.57.40/29"} 1
在prometheus里面点开看看