Prometheus relabel实现动态metrics path
Prometheus 的 relabel 功能可以在目标的 label 被抓取之前重写它,每个采集配置可以配置多个 relabel,并按照配置的顺序来应用于每个 target 的 label。利用这个特性,我们可以实现动态的 metrics-path。
需求描述
现在 Alliot 有如下的 metrics endpoint 需要被监控:1
2
3http://192.168.1.1:80/payment-service/metrics
http://192.168.1.1:80/order-service/metrics
http://192.168.1.1:80/user-service/metrics
这种情况下,我们的 target 均为 192.168.1.1:80,不同的是 metrics_path,这样我们就不得不写3个 job 来监控,因为在 prometheus 的配置中,target 字段只能是 [host]:[ip] 不能包含路径。
https://github.com/prometheus/prometheus/issues/1852 官方仓库也有人提出了这样的需求,但是并没有被通过。
众所周知,Prometheus 在 scrape 的过程中,有个十分好用的 feature: relabel。 通过 relabel 可以将 scrape 到的标签进行修改、重打标签。通过 [prometheus URL]:9090/targets 下对各个 target 的查看,我们可以发现,endpoint 的 Before relabeling 中存在一个名为 __metrics_path__ 的 label, 因此,我们可以通过设置一个新的 relabel 作为动态的值,之后将其 relabel 重打标来达到我们的目的:
static config下的实现
静态配置下,通过为每个 target 指定一个新的 label 并将其 replace 为 __metrics_path__ 即可:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28- job_name: prometheus_dynamic_metrics_path
  honor_labels: true
  honor_timestamps: true
  scrape_interval: 15s
  scrape_timeout: 10s
  metrics_path: /metrics
  scheme: http
  follow_redirects: true
  relabel_configs:
  - source_labels: [_new_path]
    separator: ;
    regex: (.*)
    target_label: __metrics_path__
    replacement: /metrics/$1
    action: replace
  static_configs:
  - targets:
    - 192.168.1.1:80
    labels:
      _new_path: payment-service
  - targets:
    - 192.168.1.2:80
    labels:
      _new_path: order-service
  - targets:
    - 192.168.1.2:80
    labels:
      _new_path: user-service
在如上配置下,我们仅需要配置一个 Job 即可完成对多个 metric endpoint 的 scrape。
动态发现场景下
同样的,这种 relabel 的方式在自动发现等机制场景下,也能很方便的通过添加一个额外的 label 来达到简化配置的目的。1
2
3
4
5
6
7
8
9
10
11
12
13
14
15  - job_name: ecs_jvm_actuator
    scrape_interval: 30s
    scrape_timeout: 20s
    consul_sd_configs:
      - server: localhost:8500
        token: 'alliot,www.iots.vip'
    relabel_configs:
      - source_labels: ["__meta_consul_service_metadata_instance"]
        target_label: __address__
        action: replace
# 这里将 consul 配置的对象的 service_name 值作为 _metrics_path
      - source_labels: ["__meta_consul_service_metadata_service_name"]
        target_label: __metrics_path__
        action: replace