天天看點

【ZooKeeper】寫一個python的prometheus exporter來輸出名額值到Grafana

需求就是希望能在 Grafana 的 Dashboard 直接看到選主的資訊,也就是 Znode 對應的值,因為考慮到 ZK 裡存的值可能是字元串,而且 Prometheus 的名額都是數值型的,是以用 Counter, Summary 之類的難以實作把 ZK 的值直接通過 Metrics 直接 Export 出來,但是我們可以通過 Label 的方式,把 Znode 的值打到名額上,在 Grafana 展示的時候通過名額的标簽來構造圖表就可以了。

【ZooKeeper】寫一個python的prometheus exporter來輸出名額值到Grafana

代碼很簡單,本地通過

curl localhost:8000

就可以看到效果了。

import os
import time
 
from kazoo.client import KazooClient
from prometheus_client import Info
from prometheus_client import start_http_server
 
hosts = os.getenv('ZK_HOSTS', '127.0.0.1:2181')
master_path = os.getenv('MASTER_PATH', '/xxx/election')
exporter_port = os.getenv('EXPORTER_PORT', '8000')
 
 
# get master election ip
def get_master_ip():
  zk = KazooClient(hosts=hosts)
  zk.start()
  node = zk.get(master_path)[0]
  zk.stop()
  # tag master ip to metrics
  i = Info('election', 'master ip')
  i.info({'election_master_ip': node})
 
 
if __name__ == '__main__':
  # Start up the server to expose the metrics.
  get_master_ip()
  start_http_server(int(exporter_port))
  # Generate some requests.
  while True:
    time.sleep(30)           

複制

名額例子。

# HELP election_info woodpeckserver master ip
# TYPE election_info gauge
election_info{election_master_ip="xx.xx.15.139"} 1.0
# HELP python_info Python platform information
# TYPE python_info gauge
python_info{implementation="CPython",major="2",minor="7",patchlevel="5",version="2.7.5"} 1.0           

複制

圖就不做了,領悟一下就好了~