普罗米修斯动态 metrics_path

prometheus dynamic metrics_path

Prometheus 允许我使用 file_sd_config 从 .json 文件动态加载目标

#prometheus.yaml
- job_name: 'kube-metrics'
  file_sd_configs:
  - files:
    - 'targets.json'
[
  {
    "labels": {
      "job": "kube-metrics"
    },
    "targets": [
      "http://node1:8080",
      "http://node2:8080"
    ]
  }
]

但是我的目标在 metrics_path 而不是主机(我想为 <kube-api-server>/api/v1/nodes/<node-name>/proxy/metrics/cadvisor 上的每个 kubernetes 节点抓取指标)但我只能设置 metrics_path 在工作级别而不是每个目标。这甚至可以通过 prometheus 实现,还是我必须编写自己的代码来抓取所有这些指标并将它们导出到单个目标。我也找不到所有支持的自动发现机制的列表,我是不是在文档中遗漏了什么?

您可以在 Prometheus 配置中使用 relabel_config 来更改 __metrics_path__ 标签配置。

原则是在你的目标中以 host:port/path/of/metrics 的形式提供指标路径(注意:删除 http://,它在 scrape_configscheme 参数中)

[
  {
    "targets": [
      "node1:8080/first-metrics",
      "node2:8080/second-metrics"
    ]
  }
]

然后将相关元标签替换成

- job_name: 'kube-metrics'
  file_sd_configs:
  - files:
    - 'targets.json'
  relabel_configs:
    - source_labels: [__address__]
      regex:  '[^/]+(/.*)'            # capture '/...' part
      target_label: __metrics_path__  # change metrics path
    - source_labels: [__address__]
      regex:  '([^/]+)/.*'            # capture host:port
      target_label: __address__       # change target

您可以在配置时已知的任何标签上重复使用此方法来修改抓取的配置。

在 Prometheus 上,使用服务发现页面检查您的配置是否已正确修改。

服务发现的官方列表在the configuration documentation:在索引中寻找*_sd_config

有一种稍微更优雅的方法可以做到这一点,它不涉及操纵地址。你可以有一个带有你的目标的标签,它可以作为你的“重新标记”动作的来源,像这样:

- labels:
    __meta_discovery_path: '/first-metrics'
  targets:
  - 'node1:8080'
- labels:
    __meta_discovery_path: '/second-metrics'
  targets:
  - 'node2:8080'

然后您的重新标记将只是:

  relabel_configs:
    - source_labels: [__meta_discovery_path]
      target_label: __metrics_path__  # change metrics path

由于正在使用的标签以“__”开头,它将从被拉取的指标中删除,使其美观干净。

我想要类似以下端点的东西并通过此配置实现

192.168.1.1:80/metrics/my-path1
192.168.1.2:80/metrics/my-path1

这会将 </code> 替换为 <code>_new_path 值。

- 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/
    action: replace
  static_configs:
  - targets:
    - 192.168.1.1:80
    labels:
      _new_path: my-path1
  - targets:
    - 192.168.1.2:80
    labels:
      _new_path: my-path2