0

如何在 Prometheus 中创建记录规则

 2 years ago
source link: http://dockone.io/question/1593251
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

我们为什么需要记录规则以及如何创建它们?

各位开发者好,在上一篇文章中我们已经了解了如何使用 PrometheusGrafana 来监控节点,每当我们使用 Prometheus 时,我们不仅仅直接使用它的指标,而且会根据我们的需求和要求创建复杂的查询,这些表达式可能非常庞大且不会频繁使用。如果我们可以像使用其他指标一样呢?让我们看看如何实现。

什么是记录规则

记录规则允许我们预先计算经常使用的或计算量大的表达式,并将它们的结果保存为一组新的时间序列。查询预先计算的结果通常比每次需要时执行原始表达式要快得多。

这对于仪表板特别有用,仪表板每次刷新时都需要重复查询相同的表达式。记录和警报规则保存在规则组中。

举个例子,如果我想经常监控空闲节点内存的百分比,它的表达式有点复杂,如下所示:
100 - (100 * node_memory_MemFree_bytes / node_memory_MemTotal_bytes)


我不可能在每次想使用表达式时去复制粘贴这个庞大的表达式。我需要一种更简单的方法来获取这个表达式的值,这就是记录规则发挥作用的地方。

如何创建记录规则?

假设 Prometheus 和节点 exporter 已经在运行,我们创建一个包含必要规则语句的 prometheus_rules.yml,然后让 Prometheus 通过 prometheus 配置中的 rule_files 字段加载文件,即 prometheus.yml

我们首先导航到 prometheus 文件夹,创建一个规则文件并在该文件中添加记录规则。
cd /usr/local/bin/prometheus
nano prometheus_rules.yml
groups:
- name: custom_rules
rules:
  - record: node_memory_MemFree_percent
    expr: 100 - (100 * node_memory_MemFree_bytes / node_memory_MemTotal_bytes)

- record: node_filesystem_free_percent
    expr: 100 * node_filesystem_free_bytes{mountpoint="/"} / node_filesystem_size_bytes{mountpoint="/"} 

规则字段指定添加的所有记录规则,我添加了 2 个记录规则,一个用于计算空闲节点内存百分比,另一个用于计算空闲节点文件系统百分比。expr 字段保存实际表达式。

一旦我们创建了记录规则,我们需要检查规则是否有任何错误或语法错误或锁进问题,我们可以执行此命令进行验证。
./promtool check rules  prometheus_rules.yml
./promtool check rules  prometheus_rules.yml


一旦我们看到成功信息,我们需要在 Prometheus 配置文件中添加规则配置。这非常简单直接,我们只需在 prometheus.yml 文件中的 rule_files 字段下添加记录规则文件的名称,如下图所示。
# my global config
global:
scrape_interval:     15s # Set the scrape interval to every 15 seconds. Default is every 1 minute.
evaluation_interval: 15s # Evaluate rules every 15 seconds. The default is every 1 minute.
# scrape_timeout is set to the global default (10s).

rule_files:
- "prometheus_rules.yml"

scrape_configs:
# The job name is added as a label `job=<job_name>` to any timeseries scraped from this config.
- job_name: 'prometheus'

# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.

static_configs:
- targets: ['localhost:9090']
- job_name: 'node_exporter'

# metrics_path defaults to '/metrics'
# scheme defaults to 'http'.

static_configs:
- targets: ['localhost:9100','18.237.17.50:9100','34.221.251.128:9100'] 

添加 prometheus.yml 文件后,我们需要重新启动 Prometheus 服务才能完成在仪表板中添加并显示规则。
sudo systemctl daemon-reload
sudo service prometheus restart

我们可以在仪表板的状态规则下看到我们添加的规则。

现在我们可以只使用 node_memory_MemFree_percent 查询空闲节点内存百分比,无需在使用那个庞大的表达式,空闲文件系统百分比也是如此,我们只需使用 node_filesystem_free_percent


这个不仅用于 Prometheus 查询,而且我们还可以使用在 Grafana 中创建的这个记录规则来绘制图形或创建更复杂的表达式。


本文总结了记录规则的基础知识以及我们如何使用它们,我将删除我之前关于如何设置 Prometheus 和 Grafana 来可视化 Node 节点指标的文章链接。

原文链接:Create Recording Rules in Prometheus(翻译:xiebo)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK