prometheus


說明

視頻講解通過鏈接網易雲課堂·IT技術快速入門學院進入,更多關於Prometheus的文章

Prometheus是最近幾年開始流行的一個新興監控告警工具,特別是kubernetes的流行帶動了prometheus的應用。

Prometheus是一套完整的監控告警系統:

Prometheus系統組成

Prometheus的主要特點有:

1. a multi-dimensional data model with time series data identified by metric name and key/value pairs
2. a flexible query language to leverage this dimensionality
3. no reliance on distributed storage; single server nodes are autonomous
4. time series collection happens via a pull model over HTTP
5. pushing time series is supported via an intermediary gateway
6. targets are discovered via service discovery or static configuration
7. multiple modes of graphing and dashboarding support

influxdb、openTSDB等,是專門時間序列數據庫,不是一套完整的監控告警系統,缺少告警功能。

Prometheus系統的服務發現功能很強大,可以直接通過Kubernetes等系統的接口,發現要監控的目標,不需要人員干預,不需要做系統對接方面的開發。

Prometheus系統的三部分:prometheus、alertmanager、*_exporter(多個),下文將分別講解。

這里使用的機器IP為:192.168.88.10。

Prometheus

prometheus是最主要的組件,負責采集數據,將告警發送到alertmanager,alertmanager再將告警以各種形式送出。

命名規則

2018-09-25 15:28:47 補充:

prometheus data model中介紹了數據模型。時間序列以metric的名字命名,可以附帶有多個label,label是一個鍵值對。

metric的命名規則為[a-zA-Z_:][a-zA-Z0-9_:]*,其中:被保留用於用戶定義的記錄規則。

label的命名規則為[a-zA-Z_][a-zA-Z0-9_]*,以__開頭的label名稱被保留用於內部label。

每個采樣點叫做sample,它是float64的數值或者精確到毫秒的時間戳。

通過metric名稱和label查詢samples,語法如下:

<metric name>{<label name>=<label value>, ...}

例如:

api_http_requests_total{method="POST", handler="/messages"}

metric類型

2018-09-25 15:29:02 補充:

metric有CounterGaugeHistogramSummary四種類型。在指標生成端,也就是應用程序中,調用prometheus的sdk創建metrics的時候,必須要明確是哪一種類型的metrics。 見:使用Prometheus SDK輸出Prometheus格式的Metrics

Counter是累計數值,只能增加或者在重啟時被歸零。

Gauge是瞬時值。

Histogram(直方圖)對采集的指標進行分組計數,會生成多個指標,分別帶有后綴_bucket(僅histogram)、_sum_count,其中_bucket是區間內計數:

<basename>_bucket{le="<upper inclusive bound>"}

名為rpc_durations_secondshistogram生成的metrics:

# TYPE rpc_durations_histogram_seconds histogram
rpc_durations_histogram_seconds_bucket{le="-0.00099"} 0
rpc_durations_histogram_seconds_bucket{le="-0.00089"} 0
rpc_durations_histogram_seconds_bucket{le="-0.0007899999999999999"} 0
rpc_durations_histogram_seconds_bucket{le="-0.0006899999999999999"} 1
rpc_durations_histogram_seconds_bucket{le="-0.0005899999999999998"} 1
rpc_durations_histogram_seconds_bucket{le="-0.0004899999999999998"} 1
rpc_durations_histogram_seconds_bucket{le="-0.0003899999999999998"} 10
rpc_durations_histogram_seconds_bucket{le="-0.0002899999999999998"} 26
rpc_durations_histogram_seconds_bucket{le="-0.0001899999999999998"} 64
rpc_durations_histogram_seconds_bucket{le="-8.999999999999979e-05"} 117
rpc_durations_histogram_seconds_bucket{le="1.0000000000000216e-05"} 184
rpc_durations_histogram_seconds_bucket{le="0.00011000000000000022"} 251
rpc_durations_histogram_seconds_bucket{le="0.00021000000000000023"} 307
rpc_durations_histogram_seconds_bucket{le="0.0003100000000000002"} 335
rpc_durations_histogram_seconds_bucket{le="0.0004100000000000002"} 349
rpc_durations_histogram_seconds_bucket{le="0.0005100000000000003"} 353
rpc_durations_histogram_seconds_bucket{le="0.0006100000000000003"} 356
rpc_durations_histogram_seconds_bucket{le="0.0007100000000000003"} 357
rpc_durations_histogram_seconds_bucket{le="0.0008100000000000004"} 357
rpc_durations_histogram_seconds_bucket{le="0.0009100000000000004"} 357
rpc_durations_histogram_seconds_bucket{le="+Inf"} 357
rpc_durations_histogram_seconds_sum -0.000331219501489902
rpc_durations_histogram_seconds_count 357

Summary同樣產生多個指標,分別帶有后綴_bucket(僅histogram)、_sum_count,可以直接查詢分位數:

<basename>{quantile="<φ>"}

名為rpc_durations_secondssummary生成到metrics:

# TYPE rpc_durations_seconds summary
rpc_durations_seconds{service="exponential",quantile="0.5"} 7.380919552318622e-07
rpc_durations_seconds{service="exponential",quantile="0.9"} 2.291519677915514e-06
rpc_durations_seconds{service="exponential",quantile="0.99"} 4.539723552933882e-06
rpc_durations_seconds_sum{service="exponential"} 0.0005097984764772547
rpc_durations_seconds_count{service="exponential"} 532

Histogram和Summary都可以獲取分位數。

通過Histogram獲得分位數,要將直方圖指標數據收集prometheus中, 然后用prometheus的查詢函數histogram_quantile()計算出來。 Summary則是在應用程序中直接計算出了分位數。

Histograms and summaries中闡述了兩者的區別,特別是Summary的的分位數不能被聚合。

注意,這個不能聚合不是說功能上不支持,而是說對分位數做聚合操作通常是沒有意義的。

LatencyTipOfTheDay: You can’t average percentiles. Period中對“分位數”不能被相加平均的做了很詳細的說明:分位數本身是用來切分數據的,它們的平均數沒有同樣的分位效果。

Job和Instance

2018-09-25 15:37:09 補充:

被監控的具體目標是instance,監控這些instances的任務叫做job。每個job負責一類任務,可以為一個job配置多個instance,job對自己的instance執行相同的動作。

隸屬於job的instance可以直接在配置文件中寫死。也可以讓job自動從consul、kuberntes中動態獲取,這個過程就是下文說的服務發現。

部署、啟動

prometheus負責根據配置文件發現監控目標,主動收集數據指標,並檢查是否觸發告警規則,是整個系統的核心。

可以直接使用Prometheus提供二進制文件:prometheus download

先下載下來,簡單試用一下:

wget https://github.com/prometheus/prometheus/releases/download/v2.3.2/prometheus-2.3.2.linux-amd64.tar.gz
tar -xvf prometheus-2.3.2.linux-amd64.tar.gz

解壓以后得到下面的文件:

$ ls
console_libraries  consoles  LICENSE  NOTICE  prometheus  prometheus.yml  promtool

如果想要學習源代碼,可以自己從代碼編譯:

go get github.com/prometheus/prometheus
cd $GOPATH/src/github.com/prometheus/prometheus
git checkout <需要的版本>
make build

然后直接運行prometheus程序即可:

 ./prometheus
level=info ts=2018-08-18T12:57:33.232435663Z caller=main.go:222 msg="Starting Prometheus" version="(version=2.3.2, branch=HEAD, revision=71af5e29e815795e9dd14742ee7725682fa14b7b)"
level=info ts=2018-08-18T12:57:33.235107465Z caller=main.go:223 build_context="(go=go1.10.3, user=root@5258e0bd9cc1, date=20180712-14:02:52)"
...

通過192.168.88.10:9090,可以打開promtheus的網頁。

prometheus的配置文件

使用prometheus最關鍵的還是搞清楚它的配置文件,仔細定制了配置文件,才能發揮出它的功能。

略微不幸的是,prometheus的配置文件有一些復雜,官方文檔也不是很好:prometheus configuration

配置文件是yaml格式,結構如下:

$  cat prometheus.yml
# my global config
global:
  scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
  evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
  # scrape_timeout is set to the global default (10s).

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

# Load rules once and periodically evaluate them according to the global 'evaluation_interval'.
rule_files:
  # - "first_rules.yml"
  # - "second_rules.yml"

# A scrape configuration containing exactly one endpoint to scrape:
# Here it's Prometheus itself.
scrape_configs:
  # The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
  - job_name: 'prometheus'

    # metrics_path defaults to '/metrics'
    # scheme defaults to 'http'.

    static_configs:
    - targets: ['localhost:9090']

其中global是一些常規的全局配置,這里只列出了兩個參數:

  scrape_interval:     15s      #每15s采集一次數據
  evaluation_interval: 15s      #每15s做一次告警檢測

rule_files指定加載的告警規則文件,告警規則放到下一節講。

scrape_configs指定prometheus要監控的目標,這部分是最復雜的。

在scrape_config中每個監控目標是一個job,但job的類型有很多種。可以是最簡單的static_config,即靜態地指定每一個目標,例如上面的:

  - job_name: prometheus
    static_configs:
      - targets: ['localhost:9090']

也可以使用服務發現的方式,動態發現目標,例如將kubernetes中的node作為監控目標:

  - job_name: 'kubernetes-nodes'
    kubernetes_sd_configs:
    - role: node
      api_server: https://192.168.88.10
      tls_config:
        ca_file:   /opt/app/k8s/admin/cert/ca/ca.pem
        cert_file: /opt/app/k8s/admin/cert/apiserver-client/cert.pem
        key_file:  /opt/app/k8s/admin/cert/apiserver-client/key.pem
    bearer_token_file: /opt/app/k8s/apiserver/cert/token.csv
    scheme: https
    tls_config:
      ca_file:   /opt/app/k8s/admin/cert/ca/ca.pem
      cert_file: /opt/app/k8s/admin/cert/apiserver-client/cert.pem
      key_file:  /opt/app/k8s/admin/cert/apiserver-client/key.pem

使用這個新的配置文件,啟動prometheus:

./prometheus --config.file=./prometheus.k8s.yml

prometheus運行時會自動探測kubernetes中的node變化,自動將kubernetes中的node作為監控目標。

在prometheus的頁面中可以看到自動生成的監控目標。這里就不貼圖了,可以自己試一下,或者看一下演示視頻。

當前@2018-08-10 17:14:05,prometheus中與服務發現有關的配置有以下幾項(前綴就是支持的系統,sd表示service discovery):

    azure_sd_config
    consul_sd_config
    dns_sd_config
    ec2_sd_config
    openstack_sd_config
    file_sd_config
    gce_sd_config
    kubernetes_sd_config
    marathon_sd_config
    nerve_sd_config
    serverset_sd_config
    triton_sd_config

服務發現是prometheus最強大的功能之一,這個功能配合relabel_config*_exporter可以做成很多事情。

使用relabel_config擴展采集能力

relabel_config,顧名思義,可以用來重新設置標簽。標簽是附屬在每個監控目標的每個指標上的。

但有些標簽是雙下划線開頭的,例如__address__,這樣的標簽是內置的有特殊意義的,不會附着在監控指標上。

這樣的標簽有:

__address__         : 檢測目標的地址 
__scheme__          : http、https等
__metrics_path__    : 獲取指標的路徑

上面的三個標簽將被組合成一個完整url,這個url就是監控目標,可以通過這個url讀取到指標。

relabel_config提供了標簽改寫功能,通過標簽改寫,可以非常靈活地定義url。

另外在每個服務發現配置中,還會定義與服務相關的內置指標,例如kubernetes_sd_confignode的類型中又定義了:

__meta_kubernetes_node_name: The name of the node object.
__meta_kubernetes_node_label_<labelname>: Each label from the node object.
__meta_kubernetes_node_annotation_<annotationname>: Each annotation from the node object.
__meta_kubernetes_node_address_<address_type>: The first address for each node address type, if it exists.

在上一節中,是直接從默認的地址http://< NODE IP>/metrics中采集到每個node數據的,這里用relabel修改一下,改成從apiserver中獲取:

  - job_name: 'kubernetes-nodes'
    kubernetes_sd_configs:
    - role: node
      api_server: https://192.168.88.10
      tls_config:
        ca_file:   /opt/app/k8s/admin/cert/ca/ca.pem
        cert_file: /opt/app/k8s/admin/cert/apiserver-client/cert.pem
        key_file:  /opt/app/k8s/admin/cert/apiserver-client/key.pem
    bearer_token_file: /opt/app/k8s/apiserver/cert/token.csv
    scheme: https
    tls_config:
      ca_file:   /opt/app/k8s/admin/cert/ca/ca.pem
      cert_file: /opt/app/k8s/admin/cert/apiserver-client/cert.pem
      key_file:  /opt/app/k8s/admin/cert/apiserver-client/key.pem
    relabel_configs:
    - action: labelmap
      regex: __meta_kubernetes_node_label_(.+)
    - target_label: __address__
      replacement: 192.168.88.10
    - source_labels: [__meta_kubernetes_node_name]
      regex: (.+)
      target_label: __metrics_path__
      replacement: /api/v1/nodes/${1}/proxy/metrics

其實就是在原先的配置后面增加了一節relabel_configs的配置。

重新加載配置文件,過一小會兒,就會發現target的url發生了變化。

relabel_config是一個很強大的功能,除了修改標簽,還可以為采集的指標添加上新標簽:

    - source_labels: [__meta_kubernetes_node_name]
      regex: (.+)
      replacement: hello_${1}
      target_label: label_add_by_me

在配置文件中加上上面的內容后,為每個指標都將被添加了一個名為label_add_by_me的標簽。

使用relabel_config過濾目標

2018-08-20 16:22:01補充,視頻中沒有這一節

還可以通過relabel_config將不需要的target過濾:

  - job_name: "user_server_icmp_detect"
    consul_sd_configs:
    - server: "127.0.0.1:8500"
    scheme: http
    metrics_path: /probe
    params:
      module: [icmp]
    relabel_configs:
    - action: keep
      source_labels: [__meta_consul_tags]        #如果__meta_consul_tags匹配正則,則保留該目標
      regex: '.*,icmp,.*'
    - source_labels: [__meta_consul_service]
      regex: '(.+)@(.+)@(.+)'
      replacement: ${2}
      target_label: type
    - source_labels: [__meta_consul_service]
      regex: '(.+)@(.+)@(.+)'
      replacement: ${1}
      target_label: user
    - source_labels: [__address__]
      regex: (.+):(.+)
      replacement: ${1}
      target_label: __param_target
    - target_label: __address__
      replacement:  10.10.199.154:9115
    - source_labels: [__param_target]
      target_label: instance

prometheus的查詢語句

prometheus的查詢語句也是很重要的內容,除了用來查詢數據,后面將要講的告警規則也要用查詢語句描述。

查詢語句直接就是指標的名稱:

go_memstats_other_sys_bytes

但是可以通過標簽篩選:

go_memstats_other_sys_bytes{instance="192.168.88.10"}

標簽屬性可以使用4個操作符:

=: Select labels that are exactly equal to the provided string.
!=: Select labels that are not equal to the provided string.
=~: Select labels that regex-match the provided string (or substring).
!~: Select labels that do not regex-match the provided string (or substring).

並且可以使用多個標簽屬性,用“,”間隔,彼此直接是與的關系,下面是prometheus文檔中的一個例子:

http_requests_total{environment=~"staging|testing|development",method!="GET"}

甚至只有標簽:

{instance="192.168.88.10"}

對查詢出來的結果進行運算也是可以的:

# 時間范圍截取,Range Vector Selectors
http_requests_total{job="prometheus"}[5m]

# 時間偏移
http_requests_total offset 5m

# 時間段內數值累加
sum(http_requests_total{method="GET"} offset 5m) 

還可以進行多元運算:Operators,以及使用函數:Functions

prometheus的告警規則配置

alert rules在單獨的文件中定義,然后在prometheus.yml中引用:

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

rules文件格式如下:

$ cat first_rules.yml
groups:
- name: rule1-http_requst_total
  rules:
  - alert:  HTTP_REQUEST_TOTAL
    expr: http_requests_total > 100
    for: 1m
    labels:
      severity: page
    annotations:
      summary: Http request total reach limit

需要注意,還要在prometheus.yml中配置alertmanager的地址:

# Alertmanager configuration
alerting:
  alertmanagers:
  - static_configs:
    - targets:
      - 127.0.0.1:9093

重新加載配置文件后,可以在prometheus的rule頁面看到告警規則,在alert頁面看到觸發的告警,

現在alertmanager還沒有部署,在下一節部署了alertmanager之后,告警可以在alertmanager中看到。

alertmanager

alertmanager是用來接收prometheus發出的告警,然后按照配置文件的要求,將告警用對應的方式發送出去。

將告警集中到alertmanager,可以對告警進行更細致的管理。

alertmanager部署啟動

wget https://github.com/prometheus/alertmanager/releases/download/v0.15.2/alertmanager-0.15.2.linux-amd64.tar.gz
tar -xvf alertmanager-0.15.2.linux-amd64.tar.gz

解壓以后會得到下面這些文件:

alertmanager  alertmanager.yml  amtool  LICENSE  NOTICE

直接運行alertmanager就可以啟動,然后通過http://IP地址:9093/#/alerts可以打開alertmanager的頁面。

alertmanager的配置文件

alertmanager的配置文件格式如下:

global:
  resolve_timeout: 5m

route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 1h
  receiver: 'web.hook'
receivers:
- name: 'web.hook'
  webhook_configs:
  - url: 'http://127.0.0.1:5001/'
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

其中最主要的是receivers,它定義了告警的處理方式,這里是webhook_config,意思是alertmananger將告警轉發到這個url。

alertmanager configuration提供多種告警處理方式,webhook_configs只是其中一種:

email_config
hipchat_config
pagerduty_config
pushover_config
slack_config
opsgenie_config
victorops_config
webhook_config
wechat_config 

alertmanager配置郵件通知

這里給出一個用郵件通知告警的例子,發件郵箱用的是網易郵箱:

global:
  resolve_timeout: 5m
route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 1h
  receiver: 'mail'
receivers:
- name: 'web.hook'
  webhook_configs:
  - url: 'http://127.0.0.1:5001/'
- name: 'mail'
  email_configs:
  - to: 接收告警用的郵箱 
    from: 你的發件用的網易郵箱
    smarthost:  smtp.163.com:25
    auth_username: 網易郵箱賬號
    auth_password: 網易郵箱密碼
    # auth_secret:
    # auth_identity:
inhibit_rules:
  - source_match:
      severity: 'critical'
    target_match:
      severity: 'warning'
    equal: ['alertname', 'dev', 'instance']

注意這里有web.hookmail兩個reciver,使用哪個receive是在上面的router中配置的:

route:
  group_by: ['alertname']
  group_wait: 10s
  group_interval: 10s
  repeat_interval: 1h
  receiver: 'mail'

重新加載配置后,就可以收到告警郵件了。

alertmanager集群模式

alertmanager可以配置成集群模式,即多個alaertmanager一起運行,彼此之間通過gossip協議獲知告警的處理狀態,防止告警重復發出。

這種模式通常用在prometheus需要做高可用的場景中。

prometheus ha deploy的高可用部署通常至少會有兩套prometheus獨立工作,它們會執行各自的告警檢查。

與之相伴的通常也要部署多個alaertmanager,這時候這些alertmanager之間就需要同步信息,防止告警重復發出。

由於使用的是gossip協議,alermanager的集群模式配置很簡單,只需要啟動時指定另一個或多個alertmanager的地址即可:

--cluster.peer=192.168.88.10:9094

*_exporter

exporter是一組程序,它們分別被用來采集物理機、中間件的信息。有prometheus官方實現的,還有更多第三方實現的:

Databases
    Aerospike exporter
    ClickHouse exporter
    Consul exporter (official)
    CouchDB exporter
    ElasticSearch exporter
    EventStore exporter
...
Hardware related
    apcupsd exporter
    Collins exporter
    IoT Edison exporter
...
Messaging systems
    Beanstalkd exporter
    Gearman exporter
    Kafka exporter
...
Storage

    Ceph exporter
    Ceph RADOSGW exporter
...
HTTP

    Apache exporter
    HAProxy exporter (official)
...
APIs
    AWS ECS exporter
    AWS Health exporter
    AWS SQS exporter
Logging

    Fluentd exporter
    Google's mtail log data extractor
...
Other monitoring systems
    Akamai Cloudmonitor exporter
    AWS CloudWatch exporter (official)
    Cloud Foundry Firehose exporter
    Collectd exporter (official)
...
Miscellaneous

    ACT Fibernet Exporter
    Bamboo exporter
    BIG-IP exporter
...

這些exporter分別采集對應系統的指標,並將其以prometheus的格式呈現出來,供prometheus采集。

blackbox_exporter

blackbox_exporter是一個用來探測url、domain等聯通、響應情況的exporter。

blackbox_exporter部署啟動

wegt https://github.com/prometheus/blackbox_exporter/releases/download/v0.12.0/blackbox_exporter-0.12.0.linux-amd64.tar.gz
tar -xvf blackbox_exporter-0.12.0.linux-amd64.tar.gz

解壓后得到:

blackbox_exporter  blackbox.yml  LICENSE  NOTICE

直接運行,默認監聽地址是:9115:

./blaxkbox_exporter

blackbox_exporter配置文件與工作原理

prometheus/blackbox_exporter是一個用來探測HTTP、HTTPS、DNS、TCP和ICMP等網絡狀態的工具。

在blockbox_exporter中配置的一個個工作模塊,prometheus/blackbox_exporter config

配置文件如下:

$ cat blackbox.yml
modules:
  http_2xx:
    prober: http
    http:
  http_post_2xx:
    prober: http
    http:
      method: POST
  tcp_connect:
    prober: tcp
  pop3s_banner:
    prober: tcp
    tcp:
      query_response:
      - expect: "^+OK"
      tls: true
      tls_config:
        insecure_skip_verify: false
  ssh_banner:
    prober: tcp
    tcp:
      query_response:
      - expect: "^SSH-2.0-"
  irc_banner:
    prober: tcp
    tcp:
      query_response:
      - send: "NICK prober"
      - send: "USER prober prober prober :prober"
      - expect: "PING :([^ ]+)"
        send: "PONG ${1}"
      - expect: "^:[^ ]+ 001"
  icmp:
    prober: icmp

例如下面的配置中,有兩個工作模塊http_2xxhttp_post_2xx

modules:
  http_2xx:
    prober: http
    http:
  http_post_2xx:
    prober: http
    timeout: 5s
    http:
      method: POST
      headers:
        Content-Type: application/json
    body: '{}'

模塊可以根據需要設置更多的參數和判斷條件:

http_2xx_example:
  prober: http
  timeout: 5s
  http:
    valid_http_versions: ["HTTP/1.1", "HTTP/2"]
    valid_status_codes: []  # Defaults to 2xx
    method: GET
    headers:
      Host: vhost.example.com
      Accept-Language: en-US
    no_follow_redirects: false
    fail_if_ssl: false
    fail_if_not_ssl: false
    fail_if_matches_regexp:
      - "Could not connect to database"
    fail_if_not_matches_regexp:
      - "Download the latest version here"
    tls_config:
      insecure_skip_verify: false
    preferred_ip_protocol: "ip4" # defaults to "ip6"

通過blackbox_exporter的服務地址調用這些模塊,並傳入參數。

例如要獲取域名www.baidu.com的指標,要用http_2xx模塊,傳入參數 http://www.baidu.com :

http://192.168.88.10:9115/probe?module=http_2xx&target=http%3A%2F%2Fwww.baidu.com%2F

blackbox_exporter將按照http_2xx中的配置探測目標網址http://www.baidu.com, 並返回探測到的指標:

# HELP probe_dns_lookup_time_seconds Returns the time taken for probe dns lookup in seconds
...<省略>....
probe_http_version 1.1
# HELP probe_ip_protocol Specifies whether probe ip protocol is IP4 or IP6
# TYPE probe_ip_protocol gauge
probe_ip_protocol 4
# HELP probe_success Displays whether or not the probe was a success
# TYPE probe_success gauge
probe_success 1

通過這種方式,prometheus就可以采集到域名、dns、ip等虛擬資源的指標。

可以借助relabel_configs將__address__替換為blackbox_exporter的地址,使帶有指定參數的blackbox_exporter的url成為prometheus的監控目標。

示例:監測kubernetes的集群node的ping的情況

在blackbox的配置文件中配置icmp模塊:

  icmp:
    prober: icmp

在prometheus.yml中配置服務發現,將__address__改寫為blackbox_exporter的地址,並帶上相關參數:

  - job_name: 'kubernetes-nodes-ping'
    kubernetes_sd_configs:
    - role: node
      api_server: https://192.168.88.10
      tls_config:
        ca_file:   /opt/app/k8s/admin/cert/ca/ca.pem
        cert_file: /opt/app/k8s/admin/cert/apiserver-client/cert.pem
        key_file:  /opt/app/k8s/admin/cert/apiserver-client/key.pem
    bearer_token_file: /opt/app/k8s/apiserver/cert/token.csv
    scheme: http
    metrics_path: /probe
    params:
      module: [icmp]
    relabel_configs:
    - source_labels: [__address__]
      regex: (.+):(.+)
      replacement: ${1}
      target_label: __param_target
    - target_label: __address__
      replacement: 192.168.88.10:9115
    - action: labelmap
      regex: __meta_kubernetes_node_label_(.+)

重新加載配置后,就可以在prometheus的頁面中可以看到新增的target,而它們的地址是blackbox的地址。

可以在prometheus中搜索指標probe_success:

http://10.10.199.154:9090/graph?g0.range_input=1h&g0.expr=probe_success&g0.tab=0

可以編寫下面的告警規則,如果持續2分鍾ping不通,觸發告警:

- name: node_icmp_avaliable
  rules:
  - alert: NODE_ICMP_UNREACHABLE
    expr: probe_success{job="kubernetes-nodes-ping"} == 0
    for: 2m
    labels:
      level: 1
    annotations:
      summary: node is {{ $labels.instance }}

更改標簽的時機:抓取前修改、抓取后修改、告警時修改

prometheus支持修改標簽。metric的標簽可以在采集端采集的時候直接打上,這是最原始的標簽。

除此之外,還可以在prometheus的配置文件里,對metric的label進行修改。

修改的時機有兩個:采集數據之前,通過relabel_config;采集數據之后,寫入存儲之前,通過metric_relabel_configs

兩個的配置方式是相同的:

relabel_configs:
- source_labels: [__meta_kubernetes_pod_label_app]
  regex: 'rabbitmq01-exporter'
  replacement: 'public-rabbitmq01.paas.production:5672'
  target_label: instance

metric_relabel_configs:
- source_labels: [node]
  regex: 'rabbit01@rabbit01'
  replacement: 'public-rabbitmq01.paas.production:5672'
  target_label: node_addr

第一個是采集之前通過已有的標簽,采集之前的標簽通常是服務發現時設置的,生成新的標簽instance。

第一個是采集之后,檢查采集的指標,如果標簽node匹配正則,生成新的標簽node_addr。

如果要修改標簽,target_label指定同名的標簽。

另外alert_relabel_configs可以在告警前修改標簽。

參考:relabel_configs vs metric_relabel_configs

雜項

下面是學習過程中,查詢的一些資料,直接羅列,沒有做整理。

規則檢查:

promtool check rules /etc/prometheus/alert-rules.yml
./promtool check rules alert_rule_test.yml

監測cpu:

https://stackoverflow.com/questions/49083348/cadvisor-prometheus-integration-returns-container-cpu-load-average-10s-as-0

In order to get the metric “container_cpu_load_average_10s” the cAdvisor must run with the option “–enable_load_reader=true”

設置kubelet的參數:–enable-load-reader

container_spec_cpu_quota

cadvisro指標

alertmanager-webhook-receiver

Write a bash shell script that consumes a constant amount of RAM for a user defined time

Cadvisor metric “container_network_tcp_usage_total” always “0”

Cadvisor常用容器監控指標

prometheus-book

Relabeling is a powerful tool to dynamically rewrite the label set of a target before it gets scraped.

運算Operators

# 容器CPU負載告警
# container_cpu_load_average_10s, container_spec_cpu_quota, container_spec_cpu_shares, container_spec_cpu_quota
# 容器CPU limit: container_spec_cpu_quota / container_spec_cpu_period
# 計算空間的CPU使用率:sum(rate(container_cpu_usage_seconds_total{namespace=~".+"}[1m])) by (namespace) * 100
# 計算容器CPU使用率:sum(rate(container_cpu_usage_seconds_total{name=~".+"}[1m])) by (name) * 100
# rate(container_cpu_usage_seconds_total{name=~".+"}[1m])

計算容器的內存使用率:

container_memory_usage_bytes{container_name!="", pod_name!=""} / container_spec_memory_limit_bytes{container_name!="", pod_name!=""}

container_memory_usage_bytes{instance="prod-k8s-node-155-171",container_name!="", pod_name!=""} / container_spec_memory_limit_bytes{instance="prod-k8s-node-155-171",container_name!="", pod_name!=""}

container_memory_usage_bytes{container_name!="", pod_name!=""} / container_spec_memory_limit_bytes{container_name!="", pod_name!=""} > 0.98

container_memory_rss{container_name!="", pod_name!=""}/container_spec_memory_limit_bytes{container_name!="", pod_name!=""} >0.98

參考

  1. prometheus documents
  2. prometheus configuration
  3. prometheus download
  4. prometheus first_steps
  5. prometheus relabel_config
  6. prometheus exporters
  7. prometheus/blackbox_exporter
  8. prometheus/blackbox_exporter config
  9. Promtheus Remote Storage使用案例:多Kubernetes集群監控方案
  10. Operators
  11. Functions
  12. alerting rules
  13. alertmanager configuration
  14. prometheus ha deploy
  15. prometheus exporter
  16. prometheus data model
  17. prometheus metric types
  18. prometheus Histograms and summaries
  19. LatencyTipOfTheDay: You can’t average percentiles. Period.
  20. relabel_configs vs metric_relabel_configs


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM