计算 Prometheus 指标具有特定值的持续时间?

Calculate the duration in which a Prometheus metric had a certain value?

Prometheus 是否可以计算指标具有特定值的持续时间(例如以秒为单位)?

一个简单的示例是 up 指标,它可以有两个值:10 以指示系统是否为 运行。想象一下,自上周以来,系统上下波动了好几次。

我希望能够计算出那段时间系统停机的总秒数。

这是解决方案。要查找最后一天的停机时间(以秒为单位):

(1 - avg_over_time(up[1d])) * 60 * 60 * 24

以下是如何在 Grafana 中使用该查询来根据选定的时间范围计算停机时间:

(1 - avg_over_time(up[$__range])) * $__range_s

works only for up-like metrics, which can have either 0 or 1 values. If the metric can have other values, then the solution doesn't work :( In this case it is possible to use subqueries中提供的解决方案。例如,以下查询 returns 过去一天指标 temperature 的值大于 20 时的大致持续时间(以秒为单位):

avg_over_time((temperature >bool 20)[1d:1m]) * 24 * 3600

此解决方案对 > 操作使用 bool 修饰符 - 有关详细信息,请参阅 these docs

P.S。 VictoriaMetrics 提供 share_gt_over_time function, which simplifies the query above to the following MetricsQL 查询:

share_gt_over_time(temperature[1d], 20) * 1d