PromQL 内置函数

计算 Counter 指标的增长率

increase 函数

increase(v range-vector) 函数是 PromQL 中提供的众多内置函数之一。其中参数 v 是一个区间向量, increase 函数获取区间向量中的第一个和最后一个样本并返回其增长量

因此,可以通过以下表达式计算 Counter 类型指标的增长率:

increase(node_cpu[2m]) / 120

这里通过 node_cpu[2m] 获取时间序列最近两分钟的所有样本,increase 计算出最近两分钟的增长量,最后除以时间 120 秒得到 node_cpu 样本在最近两分钟的平均增长率。

rate 函数

rate(v range-vector) 函数可以直接计算区间向量 v 在时间窗口内的平均增长速率。因此,通过以下表达式可以得到与 increase 函数相同的结果:

rate(node_cpu[2m])

使用 rate 或者 increase 函数去计算样本的平均增长速率,容易陷入 “长尾问题” 当中,其无法反应在时间窗口内样本数据的突发变化。

例如,对于主机而言,在 2 分钟的时间窗口内,可能存在某一个由于访问量或者其它问题导致 CPU 占用 100% 的情况,但是通过计算在时间窗口内的平均增长率却无法反应出该问题。

irate 函数

为了解决 “长尾问题”,PromQL 提供了另外一个灵敏度更高的函数 irate(v range-vector)。irate 同样用于计算区间向量的增长率,但是其反应出的是瞬时增长率。irate 函数是通过区间向量中最后两个样本数据来计算区间向量的增长速率。

这种方式可以避免在时间窗口范围内的“长尾问题”,并且体现出更好的灵敏度,通过 irate 函数绘制的图标能够更好的反应样本数据的瞬时变化状态。

irate 函数相比于 rate 函数提供了更高的灵敏度,不过当需要分析长期趋势或者在告警规则中, irate 的这种灵敏度反而容易造成干扰。因此在长期趋势分析或者告警中更推荐使用 rate 函数。

预测 Gauge 指标变化趋势

PromQL 中内置的 predict_linear(v range-vector, t scalar) 函数可以预测时间序列 v 在 t 秒后的值。它基于简单线性回归的方式,对时间窗口内的样本数据进行统计,从而可以对时间序列的变化趋势做出预测。

例如,基于 2 小时的样本数据,来预测主机可用磁盘空间是否会在 4 个小时后被占满,可以使用如下表达式:

predict_linear(node_filesystem_free{job="node"}[2h], 4 * 3600) < 0

统计 Histogram 指标的分位数

Histogram 和 Summary 都可以用于统计和分析数据的分布情况,区别在于:Summary 是直接在客户端计算了数据分布的分位数情况,而 Histogram 的分位数计算需要通过 histogram_quantile(φ float, b instant-vector) 函数进行计算,其中 φ(0 < φ < 1)表示需要计算的分位数,如果需要计算中位数 φ 取值为 0.5。

以指标 http_request_duration_seconds_bucket 为例:

# HELP http_request_duration_seconds request duration histogram
# TYPE http_request_duration_seconds histogram
http_request_duration_seconds_bucket{le="0.5"} 0
http_request_duration_seconds_bucket{le="1"} 1
http_request_duration_seconds_bucket{le="2"} 2
http_request_duration_seconds_bucket{le="3"} 3
http_request_duration_seconds_bucket{le="5"} 3
http_request_duration_seconds_bucket{le="+Inf"} 3
http_request_duration_seconds_sum 6
http_request_duration_seconds_count 3

当计算 9 分位数时,使用如下表达式:

histogram_quantile(0.5, http_request_duration_seconds_bucket)

需要注意的是通过 histogram_quantile 计算的分位数,并非为精确值,而是通过 http_request_duration_seconds_bucket 和 http_request_duration_seconds_sum 近似计算的结果。

动态标签替换

可以通过 label_replace 函数为时间序列添加额外的标签。

label_replace 的具体参数如下:

label_replace(v instant-vector, dst_label string, replacement string, src_label string, regex string)

该函数会依次对 v 中的每一条时间序列进行处理,通过 regex 匹配 src_label 的值,并将匹配部分 replacement 写入到 dst_label 标签中。

除了 label_replace 以外,Prometheus 还提供了 label_join 函数,该函数可以将时间序列 v 中多个标签 src_label 的值,通过 separator 作为连接符写入到一个新的标签 dst_label 中:

label_join(v instant-vector, dst_label string, separator string, src_label_1 string, src_label_2 string, ...)

最后更新于