一:简介

随着prometheus的使用人群逐渐扩大,官方定义的client exporter虽然能满足我们的大部分需求,但是很多监控还是需要我们自定义开发,以下内容就是基于腾讯云SDK,对腾讯云CLB的流量进行监控(吐槽一下:腾讯云自身的监控项真是少,而且连接数还拿不到数据)。

二:脚本

# coding:utf-8

import argparse
import json
import time

import prometheus_client
from flask import Response, Flask
from ping3 import ping
from prometheus_client import Gauge
from prometheus_client.core import CollectorRegistry
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.monitor.v20180724 import monitor_client, models

app = Flask(__name__)

# 定义一个仓库
REGISTRY = CollectorRegistry(auto_describe=False)

class STATUS():
    # 进流量
    Intraffic = Gauge('clb_intraffic', 'clb in traffic(Mbps)', ['project', 'vip'], registry=REGISTRY)

    # 出流量
    Outtraffic = Gauge('clb_outtraffic', 'clb out traffic(Mbps)', ['project', 'vip'], registry=REGISTRY)

    # 连接数
    # Connum = Gauge('clb_Connum', 'Current number of clb connections', ['project'], registry=REGISTRY)

    # clb 存活性
    ClbStatus = Gauge('clb_status', 'check if clb is available', ['project', 'vip'], registry=REGISTRY)

    def __init__(self):
        self.project = args.project
        self.city = args.city
        self.vip = args.vip
        self.now_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time() - 300))

        self.cred = credential.Credential("腾讯云ID", "腾讯云Key")
        self.httpProfile = HttpProfile()
        self.httpProfile.endpoint = "monitor.tencentcloudapi.com"
        self.clientProfile = ClientProfile()
        self.clientProfile.httpProfile = self.httpProfile
        self.client = monitor_client.MonitorClient(self.cred, self.city, self.clientProfile)
        self.req = models.GetMonitorDataRequest()

    def get_info(self, metric):
        params = {"Namespace": "QCE/LB_PUBLIC",
                  "MetricName": metric,
                  "Period": 60,
                  "StartTime": self.now_time,
                  "EndTime": self.now_time,
                  "Instances": [
                      {"Dimensions": [
                          {"Name": "vip", "Value": self.vip}
                      ]
                      }
                  ]
                  }

        self.req.from_json_string(jsonStr=json.dumps(params))

        resp = self.client.GetMonitorData(self.req)

        return resp.to_json_string()

    def filter(self):
        self.Intraffic.labels(self.project, self.vip).set_function(
            lambda: json.loads(self.get_info("Intraffic"))['DataPoints'][0]['Values'][0])

        self.Outtraffic.labels(self.project, self.vip).set_function(
            lambda: json.loads(self.get_info("Outtraffic"))['DataPoints'][0]['Values'][0])

        # self.Outtraffic.labels(self.project).set_function(
        #    lambda: json.loads(self.get_info("Connum"))['DataPoints'][0]['Values'][0])

        self.ClbStatus.labels(self.project, self.vip).set_function(
            lambda: 0 if ping(self.vip, timeout=3) else 10)

@app.route("/metrics")
def Status():
    STATUS().filter()
    return Response(prometheus_client.generate_latest(registry=REGISTRY), mimetype="text/plain")

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.description = 'Get CLB traffic information'
    parser.add_argument("--project", help="web event name", required=True, type=str)
    parser.add_argument("--city", help="clb region", required=True, type=str)
    parser.add_argument("--vip", help="clb public ip", required=True, type=str)
    parser.add_argument("--port", help="flask port", required=True, type=int)
    args = parser.parse_args()

    app.run(host="0.0.0.0", port=args.port)

三:运行

/usr/bin/python36 /data/script/clb-exporter.py --project "项目名" --city "CLB所在地区" --vip "clb的VIP" --port 19992
05-11 22:36