背景
当Prometheus自带的exporter没法知足实际需求时,须要咱们自定义开发监控项,本篇文章介绍经过python开发自定义的exporter
1.环境准备
yum install gcc libffi-devel python-devel openssl-devel -y
# CentOS7 操做系统,自带python2.7 没有pip,须要手动安装
setuptools-41.1.0.post1.tar.gz
tar -zxvf setuptools-41.1.0.post1.tar.gz
cd setuptools-41.1.0.post1
python setup.py install
pip-19.2.2.tar.gz
tar -zxvf pip-19.2.2.tar.gz
cd pip-19.2.2
python setup.py install
pip install psutil -i https://pypi.tuna.tsinghua.edu.cn/simple/
pip install prometheus_client -i https://pypi.tuna.tsinghua.edu.cn/simple/
二、exporter脚本编写
# -*- coding:utf-8 -*-
import time
import commands
import os
import sys
from prometheus_client import Gauge
from prometheus_client import start_http_server
reload(sys)
sys.setdefaultencoding('utf-8')
g = Gauge('HLY_custom_test_metric', 'Description of gauge', ['itemkey'])
def get_shell_valve():
commands.getoutput('bash /opt/test.sh') #多个脚本执行的结果输出到一个文件b.txt中(第一列为key值,第二列为数据)
def del_valvue():
commands.getoutput('1>/opt/b.txt 2>&1')##为下一次获得最新数据,须要在本次清空文本内容
if __name__ == '__main__':
start_http_server(8006) # 8006端口启动
while True:
get_shell_valve()
ff = open("/opt/b.txt","r")
ffs = ff.readlines()
for lines in ffs:
if lines:
line = lines.split()
itemkey = line[0]
valve = line[1]
g.labels(itemkey).set(valve)
ff.close()
del_valvue()
time.sleep(10)
ps:上述脚本中文件及shell脚本的解释
#cat /opt/test.sh
#!/bin/sh
bash c1.sh >>/opt/b.txt
bash c2.sh >>/opt/b.txt
#b.txt内容为:
#cat /opt/b.txt
CPU 12
MEMORY 15
三、启动脚本
启动:python python_exporter.py
能够作成定时任务:
* * * * * sleep 10; python /opt/python_exporter.py #保证脚本一直处于运行之中
四、打开页面验证
