經過python開發Prometheus的自定義exporter(通用版本)

背景

當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 #保證腳本一直處於運行之中

四、打開頁面驗證

經過python開發Prometheus的自定義exporter(通用版本)

相關文章
相關標籤/搜索