prometheus自定義監控指標——實戰

上一節介紹了pushgateway的做用、優劣以及部署使用,本機經過幾個實例來重溫一下自定義監控指標是如何使用的。python


1、監控容器啓動時間(shell)linux

  使用prometheus已經兩個月了,但從未找到容器運行時間的指標(有一個相似的指標是容器建立時間)。學會自定義監控指標後,第一個實例就應該來搞定它。web

  前提條件是,部署好pushagateway!docker

  在被監控機器上(linux),建立如下腳本shell

#!/bin/bash
  
allname=`docker ps --format "{{.Names}}"`              #獲取全部運行的容器名稱

function dockerruntime(){
    t=`docker inspect -f '{{.State.StartedAt}}' $1`          #獲取各個容器的啓動時間
    t1=`date +%s -d "$t"`                                    #將時間轉成時間戳
    t2=`date +%s`                                            #獲取當前時間的時間戳
    let tt=t2-t1                                             #計算運行時間
    echo $tt
}

sudo rm -f a
echo """# TYPE docker_runtime gauge
# HELP docker_runtime time sec""" >> a                       #將往pushgateway上傳的數據寫入a文件

for i in ${allname}
do
    t=`dockerruntime $i`
    echo "docker_runtime{name=\"$i\"} $t" >> a               #格式化寫入數據  不能使用單引號  會屏蔽$i的
done

curl --data-binary "@a" http://pushgatewayIP:9091/metrics/job/docker_runtime/instance/xa-lsr-billubuntu       #修改地址和參數名向特定的url上傳數據 數在a文件中

sudo rm -f a    #清空臨時文件

  給該腳本加執行權限,執行後,登錄pushgateway的webUIflask

能夠看到被監控機器給pushgateway,PUSH了數據,意思是在被監控機器上搜索到了三個容器,每一個job的名稱叫「docker_runtime」ubuntu

將該腳本加入週期性計劃任務中,每分鐘執行一次,若對時間有要求,能夠將上述腳本稍加修改,每15s或30s執行一次。windows

此時在prometheus中的query的查詢框中輸入「docker_runtime」即可獲取上述數據。bash

【注意】app

注意上傳數據的類型

若是上傳的數據類型是 UNTYPE 那麼 prometheus將沒法識別,致使整個pushgateway數據沒法接受!所以須要格外關注發送的數據格式。
數據類型只有四種 counter gauge summary histogram

2、python向pushgateway發送數據

安裝prometheus客戶端

  pip install prometheus_client

一、counter類型

#counter是可增加的,重啓時候會被置成0,用於任務個數,只增不減
#使用flask構建一個建議的網頁

     import prometheus_client
	from prometheus_client import Counter
	from prometheus_client.core import CollectorRegistry
	from flask import Response, Flask
	
	app = Flask(__name__)
	
	requests_total = Counter("request_count", "Total request cout of the host")
	
	@app.route("/metrics")
	def requests_count():
	    requests_total.inc()
	    # requests_total.inc(2)	每一次刷新會增長2
	    return Response(prometheus_client.generate_latest(requests_total),
	                    mimetype="text/plain")
	
	@app.route('/')
	def index():
	    requests_total.inc()
	    return "Hello World"
	
	if __name__ == "__main__":
	    app.run(host="0.0.0.0")

結果: 

 

二、gauage類型

	import prometheus_client
	from prometheus_client import Counter,Gauge
	from prometheus_client.core import CollectorRegistry
	from flask import Response, Flask
	
	app = Flask(__name__)
	
	g = Gauge("random_value", "Random value of the request")
	
	@app.route("/metrics")
	def s():
	    with open("a.txt",'r') as f:
	        num=f.read()
	    g.set(num)
	    return Response(prometheus_client.generate_latest(g),
	                    mimetype="text/plain")
	
	
	@app.route('/')
	def index():
	    requests_total.inc()
	    return "Hello World"
	
	if __name__ == "__main__":
    app.run(host="0.0.0.0")

結果: 

 

以上做用是在本地生成一個小型網站,下一步是將選定的數據發送到pushgateway 

#在被監控機上寫python代碼
#CollectorRegistry能夠同時註冊多個自定義指標並返回給prometheus

	
importprometheus_client
fromprometheus_clientimportGauge
fromprometheus_client.coreimportCollectorRegistry
importrequests

defv1(): #獲取監控數據的值
	return2.3

defv2():
	return3.60

n1=v1()
n2=v2()

REGISTRY=CollectorRegistry(auto_describe=False)
#自定義指標必須利用CollectorRegistry進行註冊,註冊後返回給prometheus
#CollectorRegistry必須提供register,一個指標收集器能夠註冊多個collectoryregistry


jin=Gauge("jin_kou","zhegezuoyongshijinkoudaxiao",["l1",'l2','instance'],registry=REGISTRY)
chu=Gauge("chu_kou","zhegezuoyongshichukoudaxiao",["l1",'l2','instance'],registry=REGISTRY)
	#「jin_kou」 指標名稱
	# "zhegezuoyongshichukoudaxiao"  指標的註釋信息
	# "[]"  定義標籤的類別及個數

jin.labels(l1="label1",l2="label2",instance="windows1").inc(n1)
chu.labels(l1="label1",l2="label2",instance="windows1").inc(n2)
	#「[]」中有幾個,就須要寫幾個個數要徹底一致

requests.post("http://pushgatewayIP:9091/metrics/job/python/",data=prometheus_client.generate_latest(REGISTRY))
	#向指定的API發送post信息,將註冊的信息發過去
	#API中的 「python」是 job的名字

 結果: