??https://github.com/prometheus/prometheus/blob/main/CHANGELOG.md??
在2.28.0 / 2021-06-21 這個(gè)版本里面,引入了http的動(dòng)態(tài)發(fā)現(xiàn)
fastapi寫(xiě)個(gè)接口,代碼如下:
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")
啟動(dòng)服務(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
啟動(dòng)prometheus:
./prometheus --web.listen-address="0.0.0.0:9191" --log.level=
最終效果如下:
上面這種寫(xiě)法,有個(gè)不好的地方,就是我們?nèi)绻枰黾觠ob,還是需要改prometheus的配置文件。
這里想到了一種折中的方法:
全部target都通過(guò)http sd config來(lái)自動(dòng)發(fā)現(xiàn),在http接口里面,我們給target加上label(類(lèi)似? "__meta_prometheus_job":"ECS"),通過(guò)label來(lái)區(qū)分屬于哪個(gè)job,這樣就只用維護(hù) http接口的數(shù)據(jù)準(zhǔn)確性就可以了。 http接口數(shù)據(jù)我們可以跟 cmdb那邊聯(lián)動(dòng)獲取到(新增主機(jī)或服務(wù)會(huì)在cmdb插入記錄,我們http接口服務(wù)可以定期撈最新的主機(jī)列表 然后渲染成json提供給prometheus去拉取)
本文摘自 :https://blog.51cto.com/l