Prometheus 自定义exporter 监控key

Prometheus 自定义exporter 监控key

当Prometheus的node_exporter中没有咱们须要的一些监控项时,就能够如zabbix同样定制一些key,让其支持咱们所须要的监控项。html

例如,我要根据 逻辑cpu核数 来肯定load的告警值,如今就要添加一个统计 逻辑cpu核数的 keynode

添加统计脚本

mkdir /usr/local/node_exporter-0.16/key
vim /usr/local/node_exporter-0.16/key/Logical_CPU_core_number
cat /proc/cpuinfo| grep "processor"| wc -l

添加key值实现脚本

vim /usr/local/node_exporter-0.16/key/key_runner
#!/bin/bash
# Runs a textfile collector.
textfile_dir=/usr/local/node_exporter-0.16/key
source /etc/profile.d/node_exporter.sh
metric="$1"
shift
script="$textfile_dir/$metric"
prom_file="$textfile_dir/$metric".prom

echo $textfile_dir $script


if [[ ! -x "$script" || -d "$script" ]]; then
  echo "ERROR: Can't find script for '$metric'. Aborting."
  exit 1
fi
VALUE=`"$script" "$@"`
if [[ ! -n $VALUE ]]; then
    exit 0
    # echo "ERROR: Can't get value for '$metric'. Aborting."
    # exit 1
else
    echo "# TYPE ${metric} gauge"> "$prom_file".$$
    echo "${metric} ${VALUE}" >> "$prom_file".$$ && mv "$prom_file".$$ "$prom_file"
fi

添加权限vim

chmod 755  /usr/local/node_exporter-0.16/key/*

运行脚本效果

运行命令$1参数不用加路径,以后会生成一个prom文件,exporter能够识别该文件,收集数据centos

bash /usr/local/node_exporter-0.16/key/key_runner  Logical_CPU_core_number
[root@centos3 key]# ll
total 12
-rwxr-xr-x 1 root root 641 Feb 21 11:50 key_runner
-rwxr-xr-x 1 root root  43 Feb 21 11:56 Logical_CPU_core_number
-rw-r--r-- 1 root root  69 Feb 21 11:54 Logical_CPU_core_number.prom
[root@centos3 key]# cat Logical_CPU_core_number.prom
# TYPE Logical_CPU_core_number gauge
Logical_CPU_core_number 1

启动node_exporter,指定新加key值的prom路径bash

./node_exporter --collector.textfile.directory=/usr/local/node_exporter-0.16/key

查看metrics值是否新增了该监控项curl

curl localhost:9100/metrics > aaa
vim aaa
TYPE Logical_CPU_core_number gauge
Logical_CPU_core_number 1

=======================================================ide

脚本优化

用一个脚本实现多个监控项key value的添加post

cat /usr/local/node_exporter/key/key_runner
#! /bin/bash
prom_file=/usr/local/node_exporter/key/key.prom

IFS=";"

export TERM=vt100

key_value="
Logical_CPU_core_total  `cat /proc/cpuinfo| grep "processor"| wc -l`;
logined_users_total     `who | wc -l`;
procs_total             `/bin/top -b -n 1|grep Tasks|sed 's/,/\n/g'|grep total|awk '{ print $(NF-1) }'`;
procs_zombie            `/bin/top -b -n 1|grep Tasks|sed 's/,/\n/g'|grep zombie|awk '{ print $(NF-1) }'`"

for i in $key_value
do
    IFS=" "
    j=(`echo $i`)
    key=${j[0]}
    value=${j[1]}
    echo $key $value >> "$prom_file".tmp
done

cat "$prom_file".tmp > $prom_file
rm -rf "$prom_file".tmp
IFS=$OLD_IFS

执行效果优化

[root@Prometheus key]# ll
total 8
-rw-r--r-- 1 root root  82 Mar 11 16:45 key.prom
-rwxr-xr-x 1 root root 628 Mar  1 19:23 key_runner
[root@Prometheus key]# cat key.prom
Logical_CPU_core_total 4
logined_users_total 2
procs_total 129
procs_zombie 0