Search code examples
prometheusgrafanacpu-usagepromql

Can I query by natural week in Grafana with Prometheus?


I want to make a grafana panel to show my cpu usage prometheus data weekly. To be specific, when I select time range here as Last 30 days:

enter image description here

I hope to write a PromQL to generate a bar plot with four bars:

  • CPU usage from the 1st Monday to the 1st Sunday in the last 30 days
  • CPU usage from the 2nd Monday to the 2nd Sunday in the last 30 days
  • CPU usage from the 3rd Monday to the 3rd Sunday in the last 30 days
  • CPU usage from the 4th Monday to now

The metric to compute CPU usage can be container_cpu_usage_seconds_total or something else.

Anyone knows can it and how to implement this with Grafana and Prometheus?


Solution

  • You can do this combining last_over_time and time functions like day_of_week.

    Your query will look something like this:

    last_over_time(
      ( increase(node_cpu_seconds_total[1w])
        and on() (day_of_week() == 1 and hour() == 0 and minute()>=0<5)
      )[1w:5m])
    

    Here we calculate increase of the counter over the week, filter out values other than 00:00 - 00:05 on Monday, and then stretch what's left overt the week with ``last_over_time(..[1w])`.

    Then you can specify min step in Query options as 1w, so you'll be shown 4 or 5 values.