关于prometheus:promethues的honorlabels使用及源码分析

46次阅读

共计 2208 个字符,预计需要花费 6 分钟才能阅读完成。

一.honor_labels 的应用

- job_name: monitoring/kubelet/0
  honor_labels: true
  scrape_interval: 30s
  scrape_timeout: 5s
  metrics_path: /metrics
  scheme: https

honor_labels 用于解决 <scrape 的指标 label> 与 <target 的 label> 的抵触,比方 job、instance 等:

  • honor_labels=true 时,当 labelKey 抵触时,间接应用 scrape 的指标 label,不顾及 target 的 label;

    • 通常用于联邦集群或 pushgateway 的场景,因为该状况下,所有原始的 labels 须要保留;
  • honor_labels=false 时,当 labelKey 抵触时,将 scrape 的 label 批改为:exported_labelKey—>lableValue;
  • 默认 honor_labels=false;

honor_labels controls how Prometheus handles conflicts between labels that are
already present in scraped data and labels that Prometheus would attach
server-side (“job” and “instance” labels, manually configured target
labels, and labels generated by service discovery implementations).

If honor_labels is set to “true”, label conflicts are resolved by keeping label
values from the scraped data and ignoring the conflicting server-side labels.

If honor_labels is set to “false”, label conflicts are resolved by renaming
conflicting labels in the scraped data to “exported_<original-label>” (for
example “exported_instance”, “exported_job”) and then attaching server-side
labels.

Setting honor_labels to “true” is useful for use cases such as federation and
scraping the Pushgateway, where all labels specified in the target should be
preserved.

Note that any globally configured “external_labels” are unaffected by this
setting. In communication with external systems, they are always applied only
when a time series does not have a given label yet and are ignored otherwise.
[honor_labels: <boolean> | default = false]

二.honor_labels 的源码

prometheus 的源码中:

// scrape/scrape.go
func mutateSampleLabels(lset labels.Labels, target *Target, honor bool, rc []*relabel.Config) labels.Labels {lb := labels.NewBuilder(lset)    
    // 解决 scrape.label 与 target.label 的抵触                 
    if honor {    // honor=true 时,,当 labelKey 抵触时,间接应用 scrape 的 label,不顾及 target 的 label
        for _, l := range target.Labels() {if !lset.Has(l.Name) {lb.Set(l.Name, l.Value)
            }
        }
    } else {    // 默认 honor=false 时,当 labelKey 抵触时,将 scrape 的 label 批改为:exported_labelKey,lableValue
        for _, l := range target.Labels() {
            // existingValue will be empty if l.Name doesn't exist.
            existingValue := lset.Get(l.Name)
            if existingValue != "" {lb.Set(model.ExportedLabelPrefix+l.Name, existingValue)    // exported_前缀
            }
            // It is now safe to set the target label.
            lb.Set(l.Name, l.Value)
        }
    }

    res := lb.Labels()                              // 输入 Builder 结构实现的 Labels
    if len(rc) > 0 {                                // 执行 relabel 操作
        res = relabel.Process(res, rc...)
    }
    return res
}

参考:

1. 官网 doc: https://prometheus.io/docs/pr…

正文完
 0