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)
标签:__,exporter,service,配置文件,get,python,app,groupName,namespaceId 来源: https://www.cnblogs.com/pgy674477230/p/16349132.html