當前位置:首頁 > IT技術(shù) > Web編程 > 正文

prometheus基于http的target動態(tài)發(fā)現(xiàn)
2021-10-27 14:47:31



??https://github.com/prometheus/prometheus/blob/main/CHANGELOG.md??

在2.28.0 / 2021-06-21 這個版本里面,引入了http的動態(tài)發(fā)現(xiàn)



fastapi寫個接口,代碼如下:


main.py?

from fastapi import FastAPI,Response

app = FastAPI()

es_body = [
{
"targets":[
"172.30.11.87:9924",
"172.30.11.87:9142"
],
"labels":{
"__meta_datacenter":"nanjing",
"__meta_prometheus_job":"ElasticSearch"
}
}
]

ecs_body = [
{
"targets":[
"172.30.12.15:9100",
"172.30.12.14:9100",
],
"labels":{
"__meta_datacenter":"nanjing",
"__meta_prometheus_job":"ECS"
}
}
]

@app.get("/ecs")
async def ecs_list():
print(json.dumps(ecs_body))
return Response(content=json.dumps(ecs_body),media_type="application/json")

@app.get("/es")
async def es_list():
print(json.dumps(es_body))
return Response(content=json.dumps(es_body),media_type="application/json")


啟動服務(wù)

uvicorn main:app --reload --host 0.0.0.0 --port 8000



prometheus配置如下:


$ cat prometheus.yml 
global:
scrape_interval: 15s
evaluation_interval: 15s

alerting:
alertmanagers:
- static_configs:
- targets:
# - alertmanager:9093

rule_files:
# - "first_rules.yml"
# - "second_rules.yml"

scrape_configs:
- job_name: "prometheus"
static_configs:
- targets: ["localhost:9090"]

- job_name: "es"
http_sd_configs:
- url: "http://172.17.8.148:8000/es"
refresh_interval: 30s
- job_name: "ecs"
http_sd_configs:
- url: "http://172.17.8.148:8000/ecs"
refresh_interval: 30s


啟動prometheus:

./prometheus --web.listen-address="0.0.0.0:9191" --log.level=


最終效果如下:

prometheus基于http的target動態(tài)發(fā)現(xiàn)_prometheus





上面這種寫法,有個不好的地方,就是我們?nèi)绻枰黾觠ob,還是需要改prometheus的配置文件。


這里想到了一種折中的方法:

全部target都通過http sd config來自動發(fā)現(xiàn),在http接口里面,我們給target加上label(類似? "__meta_prometheus_job":"ECS"),通過label來區(qū)分屬于哪個job,這樣就只用維護 http接口的數(shù)據(jù)準確性就可以了。 http接口數(shù)據(jù)我們可以跟 cmdb那邊聯(lián)動獲取到(新增主機或服務(wù)會在cmdb插入記錄,我們http接口服務(wù)可以定期撈最新的主機列表 然后渲染成json提供給prometheus去拉?。?/p>




本文摘自 :https://blog.51cto.com/l

開通會員,享受整站包年服務(wù)立即開通 >