自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

通過Exporter收集一切指標

安全 應用安全
Exporter 是一個采集監(jiān)控數(shù)據并通過 Prometheus 監(jiān)控規(guī)范對外提供數(shù)據的組件,它負責從目標系統(tǒng)(Your 服務)搜集數(shù)據,并將其轉化為 Prometheus 支持的格式。

[[420791]]

本文轉載自微信公眾號「運維開發(fā)故事」,作者沒有文案的夏老師。轉載本文請聯(lián)系運維開發(fā)故事公眾號。

Exporter介紹

Exporter 是一個采集監(jiān)控數(shù)據并通過 Prometheus 監(jiān)控規(guī)范對外提供數(shù)據的組件,它負責從目標系統(tǒng)(Your 服務)搜集數(shù)據,并將其轉化為 Prometheus 支持的格式。Prometheus 會周期性地調用 Exporter 提供的 metrics 數(shù)據接口來獲取數(shù)據。那么使用 Exporter 的好處是什么?舉例來說,如果要監(jiān)控 Mysql/Redis 等數(shù)據庫,我們必須要調用它們的接口來獲取信息(前提要有),這樣每家都有一套接口,這樣非常不通用。所以 Prometheus 做法是每個軟件做一個 Exporter,Prometheus 的 Http 讀取 Exporter 的信息(將監(jiān)控指標進行統(tǒng)一的格式化并暴露出來)。簡單類比,Exporter 就是個翻譯,把各種語言翻譯成一種統(tǒng)一的語言。

對于Exporter而言,它的功能主要就是將數(shù)據周期性地從監(jiān)控對象中取出來進行加工,然后將數(shù)據規(guī)范化后通過端點暴露給Prometheus,所以主要包含如下3個功能。

  • 封裝功能模塊獲取監(jiān)控系統(tǒng)內部的統(tǒng)計信息。
  • 將返回數(shù)據進行規(guī)范化映射,使其成為符合Prometheus要求的格式化數(shù)據。
  • Collect模塊負責存儲規(guī)范化后的數(shù)據,最后當Prometheus定時從Exporter提取數(shù)據時,Exporter就將Collector收集的數(shù)據通過HTTP的形式在/metrics端點進行暴露。

介紹Primetheus client

本文將介紹Primetheus client的使用,基于golang語言,golang client 是當pro收集所監(jiān)控的系統(tǒng)的數(shù)據時,用于響應pro的請求,按照一定的格式給pro返回數(shù)據,說白了就是一個http server, 源碼參見github,相關的文檔參見GoDoc,讀者可以直接閱讀文檔進行開發(fā),本文只是幫助理解。以下是簡化流程圖:

四種數(shù)據類型

prometheus將所有數(shù)據保存為timeseries data,用metric name和label區(qū)分,label是在metric name上的更細維度的劃分,其中的每一個實例是由一個float64和timestamp組成,只不過timestamp是隱式加上去的,有時候不會顯示出來。如下面所示(數(shù)據來源于prometheus暴露的監(jiān)控數(shù)據,訪問http://localhost:9090/metrics 可得),其中go_gc_duration_seconds是metrics name,quantile="0.5"是key-value pair的label,而后面的值是float64 value。

  1. # HELP go_gc_duration_seconds A summary of the GC invocation durations. 
  2. # TYPE go_gc_duration_seconds summary 
  3. go_gc_duration_seconds{quantile="0.5"} 0.000107458 
  4. go_gc_duration_seconds{quantile="0.75"} 0.000200112 
  5. go_gc_duration_seconds{quantile="1"} 0.000299278 
  6. go_gc_duration_seconds_sum 0.002341738 
  7. go_gc_duration_seconds_count 18 
  8. # HELP go_goroutines Number of goroutines that currently exist. 
  9. # TYPE go_goroutines gauge 
  10. go_goroutines 107 

這些信息有一個共同點,就是采用了不同于JSON或者Protocol Buffers的數(shù)據組織形式——文本形式。在文本形式中,每個指標都占用一行,#HELP代表指標的注釋信息,#TYPE用于定義樣本的類型注釋信息,緊隨其后的語句就是具體的監(jiān)控指標(即樣本)。#HELP的內容格式如下所示,需要填入指標名稱及相應的說明信息。

  1. HELP <metrics_name> <doc_string> 

#TYPE的內容格式如下所示,需要填入指標名稱和指標類型(如果沒有明確的指標類型,需要返回untyped)。

  1. TYPE <metrics_name> <metrics_type> 

監(jiān)控樣本部分需要滿足如下格式規(guī)范。

  1. metric_name [ "{" label_name "=" " label_value " { "," label_name "=" " label_value " } [ "," ] "}" ] value [ timestamp ] 

其中,metric_name和label_name必須遵循PromQL的格式規(guī)范。value是一個f loat格式的數(shù)據,timestamp的類型為int64(從1970-01-01 00:00:00開始至今的總毫秒數(shù)),可設置其默認為當前時間。具有相同metric_name的樣本必須按照一個組的形式排列,并且每一行必須是唯一的指標名稱和標簽鍵值對組合。Prometheus為了方便client library的使用提供了四種數(shù)據類型:

Counter:Counter是一個累加的數(shù)據類型。一個Counter類型的指標只會隨著時間逐漸遞增(當系統(tǒng)重啟的時候,Counter指標會被重置為0)。記錄系統(tǒng)完成的總任務數(shù)量、系統(tǒng)從最近一次啟動到目前為止發(fā)生的總錯誤數(shù)等場景都適合使用Counter類型的指標。

  • Gauge:Gauge指標主要用于記錄一個瞬時值,這個指標可以增加也可以減少,比如CPU的使用情況、內存使用量以及硬盤當前的空間容量等。
  • Histogram:Histogram表示柱狀圖,主要用于統(tǒng)計一些數(shù)據分布的情況,可以計算在一定范圍內的數(shù)據分布情況,同時還提供了指標值的總和。在大多數(shù)情況下,用戶會使用某些指標的平均值作為參考,例如,使用系統(tǒng)的平均響應時間來衡量系統(tǒng)的響應能力。這種方式有個明顯的問題——如果大多數(shù)請求的響應時間都維持在100ms內,而個別請求的響應時間需要1s甚至更久,那么響應時間的平均值體現(xiàn)不出響應時間中的尖刺,這就是所謂的“長尾問題”。為了更加真實地反映系統(tǒng)響應能力,常用的方式是按照請求延遲的范圍進行分組,例如在上述示例中,可以分別統(tǒng)計響應時間在[0,100ms]、[100,1s]和[1s,∞]這3個區(qū)間的請求數(shù),通過查看這3個分區(qū)中請求量的分布,就可以比較客觀地分析出系統(tǒng)的響應能力。
  • Summary:Summary與Histogram類似,也會統(tǒng)計指標的總數(shù)(以_count作為后綴)以及sum值(以_sum作為后綴)。兩者的主要區(qū)別在于,Histogram指標直接記錄了在不同區(qū)間內樣本的個數(shù),而Summary類型則由客戶端計算對應的分位數(shù)。例如下面展示了一個Summary類型的指標,其中quantile=”0.5”表示中位數(shù),quantile=”0.9”表示九分位數(shù)。

廣義上講,所有可以向Prometheus提供監(jiān)控樣本數(shù)據的程序都可以被稱為一個Exporter,Exporter的一個實例被稱為target,Prometheus會通過輪詢的形式定期從這些target中獲取樣本數(shù)據。

自己動手編寫一個Exporter

一般來說,絕大多數(shù)Exporter都是基于Go語言編寫的,一小部分是基于Python語言編寫的,還有很小一部分是使用Java語言編寫的。比如官方提供的Consul Metrics自定義采集器Exporter,如果是在Go語言的運行環(huán)境下,需要按照如下所示代碼運行這個Exporter。

  1. package main 
  2.   
  3. import ( 
  4.     "log" 
  5.     "net/http" 
  6.   
  7.     "github.com/prometheus/client_golang/prometheus" 
  8.     "github.com/prometheus/client_golang/prometheus/promhttp" 
  9.   
  10. var ( 
  11.     cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{ 
  12.         NameSpace: "our_idc"
  13.         Subsystem: "k8s" 
  14.         Name"cpu_temperature_celsius"
  15.         Help: "Current temperature of the CPU."
  16.     }) 
  17.     hdFailures = prometheus.NewCounterVec( 
  18.         prometheus.CounterOpts{ 
  19.             NameSpace: "our_idc"
  20.             Subsystem: "k8s" 
  21.             Name"hd_errors_total"
  22.             Help: "Number of hard-disk errors."
  23.         }, 
  24.         []string{"device"}, 
  25.     ) 
  26.   
  27. func init() { 
  28.     // Metrics have to be registered to be exposed: 
  29.     prometheus.MustRegister(cpuTemp) 
  30.     prometheus.MustRegister(hdFailures) 
  31.   
  32. func main() { 
  33.     cpuTemp.Set(65.3) 
  34.     hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc() 
  35.   
  36.     // The Handler function provides a default handler to expose metrics 
  37.     // via an HTTP server. "/metrics" is the usual endpoint for that. 
  38.     http.Handle("/metrics", promhttp.Handler()) 
  39.     log.Fatal(http.ListenAndServe(":8888", nil)) 

其中創(chuàng)建了一個gauge和CounterVec對象,并分別指定了metric name和help信息,其中CounterVec是用來管理相同metric下不同label的一組Counter,同理存在GaugeVec,可以看到上面代碼中聲明了一個lable的key為“device”,使用的時候也需要指定一個lable: hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()。變量定義后進行注冊,最后再開啟一個http服務的8888端口就完成了整個程序,Prometheus采集數(shù)據是通過定期請求該服務http端口來實現(xiàn)的。啟動程序之后可以在web瀏覽器里輸入http://localhost:8888/metrics 就可以得到client暴露的數(shù)據,其中有片段顯示為:

  1. # HELP our_idc_k8s_cpu_temperature_celsius Current temperature of the CPU. 
  2. # TYPE our_idc_k8s_cpu_temperature_celsius gauge 
  3. our_idc_k8s_cpu_temperature_celsius 65.3 
  4. # HELP our_idc_k8s_hd_errors_total Number of hard-disk errors. 
  5. # TYPE our_idc_k8s_hd_errors_total counter 
  6. our_idc_k8s_hd_errors_total{device="/dev/sda"} 1 

上圖就是示例程序所暴露出來的數(shù)據,并且可以看到counterVec是有l(wèi)abel的,而單純的gauage對象卻不用lable標識,這就是基本數(shù)據類型和對應Vec版本的差別。此時再查看http://localhost:9090/graph 就會發(fā)現(xiàn)服務狀態(tài)已經變?yōu)閁P了。上面的例子只是一個簡單的demo,因為在prometheus.yml配置文件中我們指定采集服務器信息的時間間隔為60s,每隔60s Prometheus會通過http請求一次自己暴露的數(shù)據,而在代碼中我們只設置了一次gauge變量cupTemp的值,如果在60s的采樣間隔里將該值設置多次,前面的值就會被覆蓋,只有Prometheus采集數(shù)據那一刻的值能被看到,并且如果不再改變這個值,Prometheus就始終能看到這個恒定的變量,除非用戶顯式通過Delete函數(shù)刪除這個變量。使用Counter,Gauage等這些結構比較簡單,但是如果不再使用這些變量需要我們手動刪,我們可以調用resetfunction來清除之前的metrics。

自定義Collector

直接使用Collector,go client Colletor只會在每次響應Prometheus請求的時候才收集數(shù)據。需要每次顯式傳遞變量的值,否則就不會再維持該變量,在Prometheus也將看不到這個變量。Collector是一個接口,所有收集metrics數(shù)據的對象都需要實現(xiàn)這個接口,Counter和Gauage等不例外。它內部提供了兩個函數(shù),Collector用于收集用戶數(shù)據,將收集好的數(shù)據傳遞給傳入參數(shù)Channel就可;Descirbe函數(shù)用于描述這個Collector。

當收集系統(tǒng)收集的數(shù)據太多時時,就可以自定義Collector收集的方式,優(yōu)化流程,并且在某些情況下如果已經有了一個成熟的metrics,就不需要使用Counter,Gauage等這些數(shù)據結構,直接在Collector內部實現(xiàn)一個代理的功能即可。

基本上所有的export都是通過自定義Collector實現(xiàn)。一個簡單的Collector的實現(xiàn)export的代碼如下:

  1. package main 
  2.  
  3. import ( 
  4.  "github.com/prometheus/client_golang/prometheus" 
  5.  "github.com/prometheus/client_golang/prometheus/promhttp" 
  6.  "net/http" 
  7.  "sync" 
  8.  
  9. type ClusterManager struct { 
  10.  sync.Mutex 
  11.  Zone              string 
  12.  metricMapCounters map[string]string 
  13.  metricMapGauges   map[string]string 
  14.  
  15. //Simulate prepare the data 
  16. func (c *ClusterManager) ReallyExpensiveAssessmentOfTheSystemState() ( 
  17.  metrics map[string]float64, 
  18. ) { 
  19.  metrics = map[string]float64{ 
  20.   "oom_crashes_total": 42.00, 
  21.   "ram_usage":         6.023e23, 
  22.  } 
  23.  return 
  24. //通過NewClusterManager方法創(chuàng)建結構體及對應的指標信息,代碼如下所示。 
  25. // NewClusterManager creates the two Descs OOMCountDesc and RAMUsageDesc. Note 
  26. // that the zone is set as a ConstLabel. (It's different in each instance of the 
  27. // ClusterManager, but constant over the lifetime of an instance.) Then there is 
  28. // a variable label "host", since we want to partition the collected metrics by 
  29. // host. Since all Descs created in this way are consistent across instances, 
  30. // with a guaranteed distinction by the "zone" label, we can register different 
  31. // ClusterManager instances with the same registry. 
  32. func NewClusterManager(zone string) *ClusterManager { 
  33.  return &ClusterManager{ 
  34.   Zone: zone, 
  35.   metricMapGauges: map[string]string{ 
  36.    "ram_usage""ram_usage_bytes"
  37.   }, 
  38.   metricMapCounters: map[string]string{ 
  39.    "oom_crashes""oom_crashes_total"
  40.   }, 
  41.  } 
  42. //首先,采集器必須實現(xiàn)prometheus.Collector接口,也必須實現(xiàn)Describe和Collect方法。實現(xiàn)接口的代碼如下所示。 
  43. // Describe simply sends the two Descs in the struct to the channel. 
  44. // Prometheus的注冊器調用Collect來抓取參數(shù)  
  45. // 將收集的數(shù)據傳遞到Channel中并返回  
  46. // 收集的指標信息來自Describe,可以并發(fā)地執(zhí)行抓取工作,但是必須要保證線程的安全  
  47.  
  48. func (c *ClusterManager) Describe(ch chan<- *prometheus.Desc) { 
  49.  // prometheus.NewDesc(prometheus.BuildFQName(namespace, "", metricName), docString, labels, nil) 
  50.  for _, v := range c.metricMapGauges { 
  51.   ch <- prometheus.NewDesc(prometheus.BuildFQName(c.Zone, "", v), v, nil, nil) 
  52.  } 
  53.  
  54.  for _, v := range c.metricMapCounters { 
  55.   ch <- prometheus.NewDesc(prometheus.BuildFQName(c.Zone, "", v), v, nil, nil) 
  56.  } 
  57.  
  58. //Collect方法是核心,它會抓取你需要的所有數(shù)據,根據需求對其進行分析,然后將指標發(fā)送回客戶端庫。 
  59. // 用于傳遞所有可能指標的定義描述符  
  60. // 可以在程序運行期間添加新的描述,收集新的指標信息  
  61. // 重復的描述符將被忽略。兩個不同的Collector不要設置相同的描述符  
  62. func (c *ClusterManager) Collect(ch chan<- prometheus.Metric) { 
  63.  c.Lock() 
  64.  defer c.Unlock() 
  65.  m := c.ReallyExpensiveAssessmentOfTheSystemState() 
  66.  for k, v := range m { 
  67.   t := prometheus.GaugeValue 
  68.   if c.metricMapCounters[k] != "" { 
  69.    t = prometheus.CounterValue 
  70.   } 
  71.   c.registerConstMetric(ch, k, v, t) 
  72.  } 
  73. // 用于傳遞所有可能指標的定義描述符給指標 
  74. func (c *ClusterManager) registerConstMetric(ch chan<- prometheus.Metric, metric string, val float64, valType prometheus.ValueType, labelValues ...string) { 
  75.  descr := prometheus.NewDesc(prometheus.BuildFQName(c.Zone, "", metric), metric, nil, nil) 
  76.  if m, err := prometheus.NewConstMetric(descr, valType, val, labelValues...); err == nil { 
  77.   ch <- m 
  78.  } 
  79.  
  80. func main() { 
  81.  workerCA := NewClusterManager("xiaodian"
  82.  reg := prometheus.NewPedanticRegistry() 
  83.  reg.MustRegister(workerCA) 
  84.     //當promhttp.Handler()被執(zhí)行時,所有metric被序列化輸出。題外話,其實輸出的格式既可以是plain text,也可以是protocol Buffers。 
  85.  http.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{})) 
  86.  http.ListenAndServe(":8888", nil) 

此時就可以去http://localhost:8888/metrics 看到傳遞過去的數(shù)據了。

高質量Exporter的編寫原則與方法

主要方法

參考鏈接:https://prometheus.io/docs/instrumenting/writing_exporters/。1.在訪問Exporter的主頁(即http://yourExporter/這樣的根路徑)時,它會返回一個簡單的頁面,這就是Exporter的落地頁(Landing Page)。落地頁中可以放文檔和幫助信息,包括監(jiān)控指標項的說明。落地頁上還包括最近執(zhí)行的檢查列表、列表的狀態(tài)以及調試信息,這對故障排查非常有幫助。

2.一臺服務器或者容器上可能會有許多Exporter和Prometheus組件,它們都有自己的端口號。因此,在寫Exporter和發(fā)布Exporter之前,需要檢查新添加的端口是否已經被使用[1],建議使用默認端口分配范圍之外的端口。

3.我們應該根據業(yè)務類型設計好指標的#HELP#TYPE的格式。這些指標往往是可配置的,包括默認開啟的指標和默認關閉的指標。這是因為大部分指標并不會真正被用到,設計過多的指標不僅會消耗不必要的資源,還會影響整體的性能。

其他方法

對于如何寫高質量Exporter,除了合理分配端口號、設計落地頁、梳理指標這3個方面外,還有一些其他的原則。

  • 記錄Exporter本身的運行狀態(tài)指標。
  • 可配置化進行功能的啟用和關閉。
  • 推薦使用YAML作為配置格式。
  • 遵循度量標準命名的最佳實踐[2],特別是_count、_sum、_total、_bucket和info等問題。
  • 為度量提供正確的單位。
  • 標簽的唯一性、可讀性及必要的冗余信息設計。
  • 通過Docker等方式一鍵配置Exporter。
  • 盡量使用Collectors方式收集指標,如Go語言中的MustNewConstMetric。
  • 提供scrapes刮擦失敗的錯誤設計,這有助于性能調試。
  • 盡量不要重復提供已有的指標,如Node Exporter已經提供的CPU、磁盤等信息。
  • 向Prometheus公開原始的度量數(shù)據,不建議自行計算,Exporter的核心是采集原始指標。

Redis Exporter源碼解析

在本章中,讀者可以發(fā)現(xiàn)開源領域有著不計其數(shù)的Exporter,阿里巴巴開源的Exporter就有RocketMQ Exporter、Sentinel Exporter、Sentry Exporter、Alibaba Cloud Exporter等多種。編寫Exporter和編寫Spring Boot Starter一樣,可以多參考其他優(yōu)秀的開源軟件的代碼。本節(jié)就來簡單分析一下運維工作中用到的Redis Exporter源碼。在使用Redis Exporter時,可以通過redis_exporter--help命令查看完整的參數(shù)列表。默認情況下,它在端口9192上運行,并在路徑/metrics上暴露指標??梢酝ㄟ^--web.listen-addres和--web.telemetry-path命令來設置端口和路徑,代碼如下所示。

  1. redis_exporter -web.listen-address=":8888" -web.telemetry-path="/node_metrics" 

上述代碼將修改redis Exporter綁定到端口8888并在路徑/node_metrics上暴露指標。這個邏輯是在源碼redis_exporter.go中實現(xiàn)的.Redis Exporter[3]主要通過Redis原生的命令獲取Redis所有的信息,它支持2.x、3.x、4.x、5.x和6.x版本。在源碼中,可以看到多處使用了doRedisCmd方法發(fā)送命令以獲取性能指標,代碼如下所示。主要是通過原生的INFO命令獲取所有性能信息。該命令的返回結果詳情參考[4]。

  1. infoAll, err := redis.String(doRedisCmd(c, "INFO""ALL")) 

生成的infoAll信息通過func (e *Exporter) extractInfoMetrics(ch chan<- prometheus.Metric, info string, dbCount int)繼續(xù)處理。它的主要目的是遍歷查詢到的結果,根據指標生成一個hash值。源代碼如下所示:

  1. func (e *Exporter) extractInfoMetrics(ch chan<- prometheus.Metric, info string, dbCount int) { 
  2.  keyValues := map[string]string{} 
  3.  handledDBs := map[string]bool{} 
  4.  
  5.  fieldClass := "" 
  6.     //以換行符進行分割 
  7.  lines := strings.Split(info, "\n"
  8.  masterHost := "" 
  9.  masterPort := "" 
  10.     //遍歷查詢到的結果,根據指標生成一個hash值 
  11.  for _, line := range lines { 
  12.   line = strings.TrimSpace(line) 
  13.   log.Debugf("info: %s", line) 
  14.         //去除帶#的注釋文件 
  15.   if len(line) > 0 && strings.HasPrefix(line, "# ") { 
  16.    fieldClass = line[2:] 
  17.    log.Debugf("set fieldClass: %s", fieldClass) 
  18.    continue 
  19.   } 
  20.         //去除不帶:的或者字符小于2的 
  21.   if (len(line) < 2) || (!strings.Contains(line, ":")) { 
  22.    continue 
  23.   } 
  24.         //以冒號進行分割 
  25.   split := strings.SplitN(line, ":", 2) 
  26.   fieldKey := split[0] 
  27.   fieldValue := split[1] 
  28.         //將指標名稱與值存到hash中 
  29.   keyValues[fieldKey] = fieldValue 
  30.  
  31.   if fieldKey == "master_host" { 
  32.    masterHost = fieldValue 
  33.   } 
  34.  
  35.   if fieldKey == "master_port" { 
  36.    masterPort = fieldValue 
  37.   } 
  38.         //按照集群和副本和哨兵模式進行處理 
  39.   switch fieldClass { 
  40.  
  41.   case "Replication"
  42.    if ok := e.handleMetricsReplication(ch, masterHost, masterPort, fieldKey, fieldValue); ok { 
  43.     continue 
  44.    } 
  45.  
  46.   case "Server"
  47.    e.handleMetricsServer(ch, fieldKey, fieldValue) 
  48.  
  49.   case "Commandstats"
  50.    e.handleMetricsCommandStats(ch, fieldKey, fieldValue) 
  51.    continue 
  52.  
  53.   case "Keyspace"
  54.    if keysTotal, keysEx, avgTTL, ok := parseDBKeyspaceString(fieldKey, fieldValue); ok { 
  55.     dbName := fieldKey 
  56.  
  57.     e.registerConstMetricGauge(ch, "db_keys", keysTotal, dbName) 
  58.     e.registerConstMetricGauge(ch, "db_keys_expiring", keysEx, dbName) 
  59.  
  60.     if avgTTL > -1 { 
  61.      e.registerConstMetricGauge(ch, "db_avg_ttl_seconds", avgTTL, dbName) 
  62.     } 
  63.     handledDBs[dbName] = true 
  64.     continue 
  65.    } 
  66.  
  67.   case "Sentinel"
  68.    e.handleMetricsSentinel(ch, fieldKey, fieldValue) 
  69.   } 
  70.  
  71.   if !e.includeMetric(fieldKey) { 
  72.    continue 
  73.   } 
  74.         //將收集到信息進行按照一定規(guī)則進行處理 
  75.   e.parseAndRegisterConstMetric(ch, fieldKey, fieldValue) 
  76.  } 
  77.  
  78.  for dbIndex := 0; dbIndex < dbCount; dbIndex++ { 
  79.   dbName := "db" + strconv.Itoa(dbIndex) 
  80.   if _, exists := handledDBs[dbName]; !exists { 
  81.    e.registerConstMetricGauge(ch, "db_keys", 0, dbName) 
  82.    e.registerConstMetricGauge(ch, "db_keys_expiring", 0, dbName) 
  83.   } 
  84.  } 
  85.        
  86.  e.registerConstMetricGauge(ch, "instance_info", 1, 
  87.   keyValues["role"], 
  88.   keyValues["redis_version"], 
  89.   keyValues["redis_build_id"], 
  90.   keyValues["redis_mode"], 
  91.   keyValues["os"], 
  92.   keyValues["maxmemory_policy"], 
  93.   keyValues["tcp_port"], keyValues["run_id"], keyValues["process_id"], 
  94.  ) 
  95.  
  96.  if keyValues["role"] == "slave" { 
  97.   e.registerConstMetricGauge(ch, "slave_info", 1, 
  98.    keyValues["master_host"], 
  99.    keyValues["master_port"], 
  100.    keyValues["slave_read_only"]) 
  101.  } 

然后通過e.parseAndRegisterConstMetric(ch, fieldKey, fieldValue)方法,將收集到hash中的信息,按照一定的規(guī)則生成prometheus.Metric。核心代碼如下:

  1. func (e *Exporter) registerConstMetric(ch chan<- prometheus.Metric, metric string, val float64, valType prometheus.ValueType, labelValues ...string) { 
  2.  descr := e.metricDescriptions[metric] 
  3.  if descr == nil { 
  4.   descr = newMetricDescr(e.options.Namespace, metric, metric+" metric", labelValues) 
  5.  } 
  6.  
  7.  if m, err := prometheus.NewConstMetric(descr, valType, val, labelValues...); err == nil { 
  8.   ch <- m 
  9.  } 

最后*Exporter.Collect的方法調用registerConstMetric方法,就完成了redis的info指標的收集。其他指標的收集原來也是相同的,有興趣的讀者可以自行閱讀。

總結

本文介紹了Exporter的概念。Exporter的來源主要有兩個:一個是社區(qū)提供的,一個是用戶自定義的。在實際生產中,官方提供的Exporter主要涵蓋數(shù)據庫、硬件、問題跟蹤及持續(xù)集成、消息系統(tǒng)、存儲、HTTP、API、日志、其他監(jiān)控系統(tǒng)等,這些已有的Exporter可以滿足絕大多數(shù)開發(fā)人員及運維人員的需求。對于系統(tǒng)、軟件沒有Exporter的情況,本章也從數(shù)據規(guī)范、數(shù)據采集方式、代碼案例撰寫等方面帶領讀者體驗了Exporter的設計與實踐,一步步指導讀者打造定制化Exporter。為了幫助讀者形成良好的代碼風格并能夠真正編寫高質量Exporter,本章還給出了編寫高質量Exporter的建議,并結合 Redis Exporter的原理進行了實戰(zhàn)解析。通過對本章的學習,讀者可以掌握使用和定制Exporter的能力。

[1] Exporter端口列表:https://github.com/prometheus/prometheus/wiki/Default-port-allocations。

[2] 標準命名最佳實踐:https://prometheus.io/docs/practices/naming。

[3] Redis Exporter地址:https://github.com/oliver006/redis_Exporter。

 

[4] Redis INFO命令地址:https://redis.io/commands/info。

 

責任編輯:武曉燕 來源: 運維開發(fā)故事
相關推薦

2011-11-30 09:28:37

iCloud信息圖云計算

2014-11-20 17:46:08

2016-08-31 17:24:05

大數(shù)據分析

2012-12-31 11:22:58

開源開放

2020-09-11 10:55:10

useState組件前端

2021-02-28 09:47:54

軟件架構軟件開發(fā)軟件設計

2012-11-05 15:22:59

康普光纜DCD

2018-11-23 11:17:24

負載均衡分布式系統(tǒng)架構

2021-02-19 23:08:27

軟件測試軟件開發(fā)

2025-03-10 13:11:00

2018-02-25 05:45:35

2020-10-14 08:04:28

JavaScrip

2020-09-16 11:46:05

AI

2021-05-28 07:12:59

Python閉包函數(shù)

2015-07-17 09:59:18

2023-04-27 09:27:44

視頻AI

2015-08-17 10:47:54

網絡安全技術

2012-03-16 17:19:28

2015-12-08 10:50:46

戴爾云計算

2020-01-09 09:13:34

UnixLinux協(xié)議
點贊
收藏

51CTO技術棧公眾號