Python教程

python 通过openapi 获取nacos服务列表生成Prometheus的exporter配置文件

本文主要是介绍python 通过openapi 获取nacos服务列表生成Prometheus的exporter配置文件,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
# pip install uvicorn  
# pip install fastapi
# uvicorn main:app --reload
# pip install ruamel.yaml
from fastapi import FastAPI
from fastapi.responses import PlainTextResponse
import uvicorn , json, requests, os

from ruamel import yaml

curpath = os.path.dirname(os.path.realpath(__file__))
yamlpath = os.path.join(curpath, "test.yml")

app = FastAPI()

nacosurl = 'http://192.168.1.2:8848/nacos'
groupName = 'DEFAULT_GROUP'
namespaceId = 'test'

@app.get('/metrics', response_class=PlainTextResponse)
async def get_metrics():
    servicesQryData = {'pageNo':'1', 'pageSize':'1024', 'namespaceId': namespaceId, 'groupName': groupName}
    sqr = requests.get(url=nacosurl + "/v1/ns/service/list", params=servicesQryData)
    if sqr.status_code != 200:
        print('query service list error, ' + sqr.text)
        return
    serviceRspJson = json.loads(sqr.text)
    strbuf = []
    srvnode = {}
    for sn in serviceRspJson.get('doms'):
        itemQryData = {'serviceName':sn, 'namespaceId': namespaceId, 'groupName': groupName}
        snr = requests.get(url=nacosurl + '/v1/ns/instance/list', params=itemQryData)
        if snr.status_code != 200:
            print('query service instance error, ' + snr.text)
            continue
        service_nodes = json.loads(snr.text)['hosts'] 
        for srvn in service_nodes:
            srvnode["targets"] = [srvn['ip'] + ':' + str(srvn['port'])]
            srvnode["labels"] = {"servicename": sn + '_' +srvn['ip']}
            strbuf.append(srvnode)
    
    # print(strbuf)
    #  消除数据格式 否则出现 - *id001
    newdata = json.loads(json.dumps(strbuf))
    #stt = [{'targets': ['192.168.1.201:20023'], 'labels': {'servicename': 'svgauthentication_192.168.1.201'}}]
    with open(yamlpath, 'w', encoding='utf-8') as fp:
        yaml.dump(newdata, fp,Dumper=yaml.RoundTripDumper)

@app.on_event('startup')
def init_scheduler():
    pass

if __name__ == "__main__":
    uvicorn.run(app='get_nacos_service:app', host="127.0.0.1", port=8000,reload=True, debug=True)
这篇关于python 通过openapi 获取nacos服务列表生成Prometheus的exporter配置文件的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!