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

相关文章

Java MQTT实战应用

《JavaMQTT实战应用》本文详解MQTT协议,涵盖其发布/订阅机制、低功耗高效特性、三种服务质量等级(QoS0/1/2),以及客户端、代理、主题的核心概念,最后提供Linux部署教程、Sprin... 目录一、MQTT协议二、MQTT优点三、三种服务质量等级四、客户端、代理、主题1. 客户端(Clien

MySQL中的表连接原理分析

《MySQL中的表连接原理分析》:本文主要介绍MySQL中的表连接原理分析,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录1、背景2、环境3、表连接原理【1】驱动表和被驱动表【2】内连接【3】外连接【4编程】嵌套循环连接【5】join buffer4、总结1、背景

在Spring Boot中集成RabbitMQ的实战记录

《在SpringBoot中集成RabbitMQ的实战记录》本文介绍SpringBoot集成RabbitMQ的步骤,涵盖配置连接、消息发送与接收,并对比两种定义Exchange与队列的方式:手动声明(... 目录前言准备工作1. 安装 RabbitMQ2. 消息发送者(Producer)配置1. 创建 Spr

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实

python中Hash使用场景分析

《python中Hash使用场景分析》Python的hash()函数用于获取对象哈希值,常用于字典和集合,不可变类型可哈希,可变类型不可,常见算法包括除法、乘法、平方取中和随机数哈希,各有优缺点,需根... 目录python中的 Hash除法哈希算法乘法哈希算法平方取中法随机数哈希算法小结在Python中,

MySQL中的索引结构和分类实战案例详解

《MySQL中的索引结构和分类实战案例详解》本文详解MySQL索引结构与分类,涵盖B树、B+树、哈希及全文索引,分析其原理与优劣势,并结合实战案例探讨创建、管理及优化技巧,助力提升查询性能,感兴趣的朋... 目录一、索引概述1.1 索引的定义与作用1.2 索引的基本原理二、索引结构详解2.1 B树索引2.2

Java Stream的distinct去重原理分析

《JavaStream的distinct去重原理分析》Javastream中的distinct方法用于去除流中的重复元素,它返回一个包含过滤后唯一元素的新流,该方法会根据元素的hashcode和eq... 目录一、distinct 的基础用法与核心特性二、distinct 的底层实现原理1. 顺序流中的去重

从入门到精通MySQL 数据库索引(实战案例)

《从入门到精通MySQL数据库索引(实战案例)》索引是数据库的目录,提升查询速度,主要类型包括BTree、Hash、全文、空间索引,需根据场景选择,建议用于高频查询、关联字段、排序等,避免重复率高或... 目录一、索引是什么?能干嘛?核心作用:二、索引的 4 种主要类型(附通俗例子)1. BTree 索引(

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.