'Sum of a Prometheus metric over the current day

I want to have a metric that shows the total incoming bytes on an interface for the day so far. The closest I can get is having to specify the date in the query, but I was hoping to have something that would work for the current day without changing anything. What I have right now for a specific day seems to tail off at the end, but maybe that is a property of how the increase function is working? This is what I have so far:

(sum(increase(ifen02[2h])) and on () day_of_week() == 2)


Solution 1:[1]

Why don't you simply use this?

sum(increase(ifen02[2h]))

And from the visualization tools (i.e. Grafana or Prometheus graph) select last 1 day or last 24 hr, it will show the data of last 1 day relative to current time.

Solution 2:[2]

Prometheus doesn't provide the ability to query counter increase for the current day (e.g. since 00:00 of the current day). Prometheus provides the ability to query counter increase over the fixed lookbehind window (aka sliding window) though. For example, the following query returns the counter increase over the last 24 hours:

increase(ifen02[24h])

If you need counter increase since the beginning of the current day, then the following MetricsQL query can be used:

running_sum(
  increase(ifen02)
  if (
    time()+timezone_offset("Europe/Kiev")
    > (now() - now() % (24*3600))
  )
)

It is expected that this query is used for building a graph on a time range covering the current day.

This query works in the following way:

  1. It calculates the increase() for ifen02 between adjacent points on the graph. VictoriaMetrics automatically converts increase(ifen02) into the equivalent of increase(ifen02[$__interval])). See increase docs and implicit query conversion docs.

  2. Then it calculates time()+timezone_offset("Europe/Kiev") > (now() - now() % (24*3600)) . This query returns unix timestamps in Europe/Kiev time zone for the current day. It drops all the timestamp for the previous days. See docs for the used functions: now(), timezone_offset() and time().

  3. Then the if operator leaves the calculated increase() values only for the current day starting at 00:00 Europe/Kiev timezone, while dropping all the values for previous days. See docs about if operator here.

  4. Then the remaining increase() values are summed over the current day with running_sum function. Sometimes it is possible to use range_sum instead of running_sum.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kamol Hasan
Solution 2 valyala