Prometheus 实战于源码分析之collector

2024-05-10 18:08

本文主要是介绍Prometheus 实战于源码分析之collector,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在prometheus里面有很多的exporter,每个exporter里面的都有一个collector,我在这里先写分析一下prometheus自身的监控系统,采集自己的监控数据。
先看接口

type Collector interface {Describe(chan<- *Desc)Collect(chan<- Metric)
}

有很多数据类型实现了这个接口

Gauge

type Gauge interface {MetricCollector// Set sets the Gauge to an arbitrary value.Set(float64)// Inc increments the Gauge by 1.Inc()// Dec decrements the Gauge by 1.Dec()// Add adds the given value to the Gauge. (The value can be// negative, resulting in a decrease of the Gauge.)Add(float64)// Sub subtracts the given value from the Gauge. (The value can be// negative, resulting in an increase of the Gauge.)Sub(float64)
}

Histogram

type Histogram interface {MetricCollector// Observe adds a single observation to the histogram.Observe(float64)
}

Counter

type Counter interface {MetricCollector// Set is used to set the Counter to an arbitrary value. It is only used// if you have to transfer a value from an external counter into this// Prometheus metric. Do not use it for regular handling of a// Prometheus counter (as it can be used to break the contract of// monotonically increasing values).//// Deprecated: Use NewConstMetric to create a counter for an external// value. A Counter should never be set.Set(float64)// Inc increments the counter by 1.Inc()// Add adds the given value to the counter. It panics if the value is <// 0.Add(float64)
}

Summary

type Summary interface {MetricCollector// Observe adds a single observation to the summary.Observe(float64)
}

这是Collector接口还有一个prometheus自己的一个实现selfCollector

type selfCollector struct {self Metric
}// init provides the selfCollector with a reference to the metric it is supposed
// to collect. It is usually called within the factory function to create a
// metric. See example.
func (c *selfCollector) init(self Metric) {c.self = self
}// Describe implements Collector.
func (c *selfCollector) Describe(ch chan<- *Desc) {ch <- c.self.Desc()
}// Collect implements Collector.
func (c *selfCollector) Collect(ch chan<- Metric) {ch <- c.self
}

当执行selfCollector的Collect方法就是返回本身的Metric。还记得第一篇说的注册吗?prometheus.MustRegister(configSuccess)注册这个configSuccess

configSuccess = prometheus.NewGauge(prometheus.GaugeOpts{Namespace: "prometheus",Name:      "config_last_reload_successful",Help:      "Whether the last configuration reload attempt was successful.",})

在NewGauge里面,本质上就创建一个value。这个value里面有selfCollector,就是上面的selfCollector

type value struct {valBits uint64selfCollectordesc       *DescvalType    ValueTypelabelPairs []*dto.LabelPair
}

创建完Gauge后就可以注册MustRegister(…Collector),具体看

func (r *Registry) MustRegister(cs ...Collector) {for _, c := range cs {if err := r.Register(c); err != nil {panic(err)}}
}

再深入看一下Register方法

    if len(newDescIDs) == 0 {return errors.New("collector has no descriptors")}if existing, exists := r.collectorsByID[collectorID]; exists {return AlreadyRegisteredError{ExistingCollector: existing,NewCollector:      c,}}// If the collectorID is new, but at least one of the descs existed// before, we are in trouble.if duplicateDescErr != nil {return duplicateDescErr}// Only after all tests have passed, actually register.r.collectorsByID[collectorID] = cfor hash := range newDescIDs {r.descIDs[hash] = struct{}{}}for name, dimHash := range newDimHashesByName {r.dimHashesByName[name] = dimHash}

就是注册到collectorsByID这map里面,collectorsByID map[uint64]Collector 它的key是descID,值就是我们注册的collector。
通过这个map去维护collector。取消注册的方法是删除

    r.mtx.RLock()if _, exists := r.collectorsByID[collectorID]; !exists {r.mtx.RUnlock()return false}r.mtx.RUnlock()r.mtx.Lock()defer r.mtx.Unlock()delete(r.collectorsByID, collectorID)for id := range descIDs {delete(r.descIDs, id)}

现在已经把collector的结构和注册讲完了,那么采集就变的顺理成章了,Gather()方法采集数据

    wg.Add(len(r.collectorsByID))go func() {wg.Wait()close(metricChan)}()for _, collector := range r.collectorsByID {go func(collector Collector) {defer wg.Done()collector.Collect(metricChan)}(collector)}

循环遍历执行collecto去采集,把结果放到metricChan,然后就参数解析封装了,这里涉及到了数据类型,和上面接口组合是对应的

        dtoMetric := &dto.Metric{}if err := metric.Write(dtoMetric); err != nil {errs = append(errs, fmt.Errorf("error collecting metric %v: %s", desc, err,))continue}...metricFamily.Metric = append(metricFamily.Metric, dtoMetric)    

上面的write方法在需要解释一下,如果是value类型

func (v *value) Write(out *dto.Metric) error {val := math.Float64frombits(atomic.LoadUint64(&v.valBits))return populateMetric(v.valType, val, v.labelPairs, out)
}func populateMetric(t ValueType,v float64,labelPairs []*dto.LabelPair,m *dto.Metric,
) error {m.Label = labelPairsswitch t {case CounterValue:m.Counter = &dto.Counter{Value: proto.Float64(v)}case GaugeValue:m.Gauge = &dto.Gauge{Value: proto.Float64(v)}case UntypedValue:m.Untyped = &dto.Untyped{Value: proto.Float64(v)}default:return fmt.Errorf("encountered unknown type %v", t)}return nil
}

如果是其它类型,在自己的
这里写图片描述
这里还有补充一下对于指标的定义

type Metric struct {
    Label            []*LabelPair `protobuf:"bytes,1,rep,name=label" json:"label,omitempty"`
    Gauge            *Gauge       `protobuf:"bytes,2,opt,name=gauge" json:"gauge,omitempty"`
    Counter          *Counter     `protobuf:"bytes,3,opt,name=counter" json:"counter,omitempty"`
    Summary          *Summary     `protobuf:"bytes,4,opt,name=summary" json:"summary,omitempty"`
    Untyped          *Untyped     `protobuf:"bytes,5,opt,name=untyped" json:"untyped,omitempty"`
    Histogram        *Histogram   `protobuf:"bytes,7,opt,name=histogram" json:"histogram,omitempty"`
    TimestampMs      *int64       `protobuf:"varint,6,opt,name=timestamp_ms" json:"timestamp_ms,omitempty"`
    XXX_unrecognized []byte       `json:"-"`
}

这篇关于Prometheus 实战于源码分析之collector的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/977174

相关文章

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

MyBatis Plus 中 update_time 字段自动填充失效的原因分析及解决方案(最新整理)

《MyBatisPlus中update_time字段自动填充失效的原因分析及解决方案(最新整理)》在使用MyBatisPlus时,通常我们会在数据库表中设置create_time和update... 目录前言一、问题现象二、原因分析三、总结:常见原因与解决方法对照表四、推荐写法前言在使用 MyBATis

Python主动抛出异常的各种用法和场景分析

《Python主动抛出异常的各种用法和场景分析》在Python中,我们不仅可以捕获和处理异常,还可以主动抛出异常,也就是以类的方式自定义错误的类型和提示信息,这在编程中非常有用,下面我将详细解释主动抛... 目录一、为什么要主动抛出异常?二、基本语法:raise关键字基本示例三、raise的多种用法1. 抛

github打不开的问题分析及解决

《github打不开的问题分析及解决》:本文主要介绍github打不开的问题分析及解决,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、找到github.com域名解析的ip地址二、找到github.global.ssl.fastly.net网址解析的ip地址三

Mysql的主从同步/复制的原理分析

《Mysql的主从同步/复制的原理分析》:本文主要介绍Mysql的主从同步/复制的原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录为什么要主从同步?mysql主从同步架构有哪些?Mysql主从复制的原理/整体流程级联复制架构为什么好?Mysql主从复制注意

java -jar命令运行 jar包时运行外部依赖jar包的场景分析

《java-jar命令运行jar包时运行外部依赖jar包的场景分析》:本文主要介绍java-jar命令运行jar包时运行外部依赖jar包的场景分析,本文给大家介绍的非常详细,对大家的学习或工作... 目录Java -jar命令运行 jar包时如何运行外部依赖jar包场景:解决:方法一、启动参数添加: -Xb

Java Spring 中的监听器Listener详解与实战教程

《JavaSpring中的监听器Listener详解与实战教程》Spring提供了多种监听器机制,可以用于监听应用生命周期、会话生命周期和请求处理过程中的事件,:本文主要介绍JavaSprin... 目录一、监听器的作用1.1 应用生命周期管理1.2 会话管理1.3 请求处理监控二、创建监听器2.1 Ser

Apache 高级配置实战之从连接保持到日志分析的完整指南

《Apache高级配置实战之从连接保持到日志分析的完整指南》本文带你从连接保持优化开始,一路走到访问控制和日志管理,最后用AWStats来分析网站数据,对Apache配置日志分析相关知识感兴趣的朋友... 目录Apache 高级配置实战:从连接保持到日志分析的完整指南前言 一、Apache 连接保持 - 性

Linux中的more 和 less区别对比分析

《Linux中的more和less区别对比分析》在Linux/Unix系统中,more和less都是用于分页查看文本文件的命令,但less是more的增强版,功能更强大,:本文主要介绍Linu... 目录1. 基础功能对比2. 常用操作对比less 的操作3. 实际使用示例4. 为什么推荐 less?5.

MQTT SpringBoot整合实战教程

《MQTTSpringBoot整合实战教程》:本文主要介绍MQTTSpringBoot整合实战教程,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考... 目录MQTT-SpringBoot创建简单 SpringBoot 项目导入必须依赖增加MQTT相关配置编写