免规则采集器列表算法(*敏*感*词*招募|51CTO社区加盟指南什么是RulePrometheus规则)
优采云 发布时间: 2022-01-08 18:04免规则采集器列表算法(*敏*感*词*招募|51CTO社区加盟指南什么是RulePrometheus规则)
*敏*感*词*招聘 | 51CTO社区编辑加盟指南
什么是规则
Prometheus 支持用户自定义的 Rule 规则。Rule分为两类,一类是Recording Rule,一类是Alerting Rule。Recording Rule的主要目的是通过PromQL对Prometheus中的样本数据采集进行实时查询、聚合和其他各种操作。但是,当一些 PromQL 比较复杂,计算量很大时,直接使用 PromQL 可能会导致 Prometheus 响应超时。这时就需要一种类似于后台批处理的机制在后台完成这些复杂运算的计算,用户只需要查询这些运算的结果即可。Prometheus 通过 Recoding Rule 支持这种后端计算方式,可以优化复杂查询的性能,提高查询效率。
今天我们主要带来报警规则的分析。Prometheus 中的报警规则允许您根据 PromQL 表达式定义报警触发条件。Prometheus 后端会定期计算这些触发规则,当满足触发条件时,会触发告警通知。
什么是警报规则
警报是 prometheus 的一个重要功能。接下来,我们将从源码的角度来分析alering的执行过程。
如何定义报警规则
一个典型的警报规则如下:
groups: - name: example rules: - alert: HighErrorRate #指标需要在触发告警之前的10分钟内大于0.5。 expr: job:request_latency_seconds:mean5m{job="myjob"} > 0.5 for: 10m labels: severity: page annotations: summary: High request latency description: description info
在警报规则文件中,我们可以在一个组下定义一组相关的规则设置。在每个组中我们可以定义多个警报规则(rule)。一条告警规则主要由以下几部分组成:
规则管理器
根据配置的规则,规则管理器会根据规则PromQL表达式使用告警的触发条件来计算是否存在满足条件的时间序列。当条件满足时,将告警信息发送给告*敏*感*词*务。
type Manager struct { opts *ManagerOptions //外部的依赖 groups map[string]*Group //当前的规则组 mtx sync.RWMutex //规则管理器读写锁 block chan struct{} done chan struct{} restored bool logger log.Logger }
阅读规则组配置
在 Prometheus Server 启动过程中,会首先调用 Manager.Update() 方法来加载和解析 Rule 配置文件。一般流程如下。
<p>func (m *Manager) Update(interval time.Duration, files []string, externalLabels labels.Labels, externalURL string) error { m.mtx.Lock() defer m.mtx.Unlock() // 从当前文件中加载规则 groups, errs := m.LoadGroups(interval, externalLabels, externalURL, files...) if errs != nil { for _, e := range errs { level.Error(m.logger).Log("msg", "loading groups failed", "err", e) } return errors.New("error loading rules, previous rule set restored") } m.restored = true var wg sync.WaitGroup //循环遍历规则组 for _, newg := range groups { // If there is an old group with the same identifier, // check if new group equals with the old group, if yes then skip it. // If not equals, stop it and wait for it to finish the current iteration. // Then copy it into the new group. //根据新的rules.Group的信息获取规则组名 gn := GroupKey(newg.file, newg.name) //根据规则组名获取到老的规则组并删除原有的rules.Group实例 oldg, ok := m.groups[gn] delete(m.groups, gn) if ok && oldg.Equals(newg) { groups[gn] = oldg continue } wg.Add(1) //为每一个rules.Group实例启动一个goroutine go func(newg *Group) { if ok { oldg.stop() //将老的规则组中的状态信息复制到新的规则组 newg.CopyState(oldg) } wg.Done() // Wait with starting evaluation until the rule manager // is told to run. This is necessary to avoid running // queries against a bootstrapping storage.