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

相关文章

Springboot中分析SQL性能的两种方式详解

《Springboot中分析SQL性能的两种方式详解》文章介绍了SQL性能分析的两种方式:MyBatis-Plus性能分析插件和p6spy框架,MyBatis-Plus插件配置简单,适用于开发和测试环... 目录SQL性能分析的两种方式:功能介绍实现方式:实现步骤:SQL性能分析的两种方式:功能介绍记录

使用 sql-research-assistant进行 SQL 数据库研究的实战指南(代码实现演示)

《使用sql-research-assistant进行SQL数据库研究的实战指南(代码实现演示)》本文介绍了sql-research-assistant工具,该工具基于LangChain框架,集... 目录技术背景介绍核心原理解析代码实现演示安装和配置项目集成LangSmith 配置(可选)启动服务应用场景

最长公共子序列问题的深度分析与Java实现方式

《最长公共子序列问题的深度分析与Java实现方式》本文详细介绍了最长公共子序列(LCS)问题,包括其概念、暴力解法、动态规划解法,并提供了Java代码实现,暴力解法虽然简单,但在大数据处理中效率较低,... 目录最长公共子序列问题概述问题理解与示例分析暴力解法思路与示例代码动态规划解法DP 表的构建与意义动

在Java中使用ModelMapper简化Shapefile属性转JavaBean实战过程

《在Java中使用ModelMapper简化Shapefile属性转JavaBean实战过程》本文介绍了在Java中使用ModelMapper库简化Shapefile属性转JavaBean的过程,对比... 目录前言一、原始的处理办法1、使用Set方法来转换2、使用构造方法转换二、基于ModelMapper

Java实战之自助进行多张图片合成拼接

《Java实战之自助进行多张图片合成拼接》在当今数字化时代,图像处理技术在各个领域都发挥着至关重要的作用,本文为大家详细介绍了如何使用Java实现多张图片合成拼接,需要的可以了解下... 目录前言一、图片合成需求描述二、图片合成设计与实现1、编程语言2、基础数据准备3、图片合成流程4、图片合成实现三、总结前

通过prometheus监控Tomcat运行状态的操作流程

《通过prometheus监控Tomcat运行状态的操作流程》文章介绍了如何安装和配置Tomcat,并使用Prometheus和TomcatExporter来监控Tomcat的运行状态,文章详细讲解了... 目录Tomcat安装配置以及prometheus监控Tomcat一. 安装并配置tomcat1、安装

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

nginx-rtmp-module构建流媒体直播服务器实战指南

《nginx-rtmp-module构建流媒体直播服务器实战指南》本文主要介绍了nginx-rtmp-module构建流媒体直播服务器实战指南,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有... 目录1. RTMP协议介绍与应用RTMP协议的原理RTMP协议的应用RTMP与现代流媒体技术的关系2

C语言小项目实战之通讯录功能

《C语言小项目实战之通讯录功能》:本文主要介绍如何设计和实现一个简单的通讯录管理系统,包括联系人信息的存储、增加、删除、查找、修改和排序等功能,文中通过代码介绍的非常详细,需要的朋友可以参考下... 目录功能介绍:添加联系人模块显示联系人模块删除联系人模块查找联系人模块修改联系人模块排序联系人模块源代码如下

Go中sync.Once源码的深度讲解

《Go中sync.Once源码的深度讲解》sync.Once是Go语言标准库中的一个同步原语,用于确保某个操作只执行一次,本文将从源码出发为大家详细介绍一下sync.Once的具体使用,x希望对大家有... 目录概念简单示例源码解读总结概念sync.Once是Go语言标准库中的一个同步原语,用于确保某个操