如何计算Kubernetes容器内存限制的字节秒数(Grafana计费面板)
Kubernetes容器内存限制字节秒数计算方案
针对你用Grafana基于kube_pod_container_resource_limits{resource="memory"}计算指定范围(如一个月)内字节秒数的需求,以下是具体实现方案:
1. 计算容器在查询范围内的运行时长
由于容器终止后对应指标会停止上报,我们需要结合容器启动时间和指标的最后活跃时间来计算实际运行时长:
- 对于运行中容器:时长为当前时间减去启动时间
- 对于已终止容器:时长为指标最后一次上报的时间戳减去启动时间
- 同时要确保时长不超过查询范围(避免容器启动早于范围起始点的情况)
对应的PromQL片段:
# 获取每个容器在查询范围内的最后活跃时间戳 last_active_time = last_over_time(kube_pod_container_resource_limits{resource="memory"}[$__range]) # 计算运行时长,用clamp限制在0到查询范围秒数内 run_seconds = clamp( max( time() - container_start_time_seconds, last_active_time - on(namespace, pod, container) group_left() container_start_time_seconds ), 0, $__range_s )
2. 计算内存限制的字节秒数
将容器的内存限制与运行时长相乘,并按需要的维度(如命名空间、Pod、容器)聚合:
sum by (namespace, pod, container) ( # 获取时间范围内最后有效的内存限制值 last_over_time(kube_pod_container_resource_limits{resource="memory"}[$__range]) * # 关联计算运行时长 clamp( max( time() - container_start_time_seconds{namespace=~"$namespace", pod=~"$pod", container=~"$container"}, last_over_time(kube_pod_container_resource_limits{resource="memory"}[$__range]) - on(namespace, pod, container) group_left() container_start_time_seconds ), 0, $__range_s ) )
关键说明
last_over_time:确保获取的是容器在查询范围内有效的内存限制值(避免容器中途修改限制的情况)on(...) group_left():通过命名空间、Pod、容器标签关联内存限制和启动时间指标,保证计算对应同一个容器clamp:防止容器启动时间早于查询范围起始点时,计算出超出范围的时长- 若需按客户维度聚合(如命名空间对应客户),可修改
sum by的维度为sum by (namespace)
单位转换(可选)
如果需要将字节秒转换为更易读的GB秒,只需将结果除以1024^3(即1073741824):
sum by (namespace, pod, container) ( last_over_time(kube_pod_container_resource_limits{resource="memory"}[$__range]) * clamp( max( time() - container_start_time_seconds{namespace=~"$namespace", pod=~"$pod", container=~"$container"}, last_over_time(kube_pod_container_resource_limits{resource="memory"}[$__range]) - on(namespace, pod, container) group_left() container_start_time_seconds ), 0, $__range_s ) ) / 1073741824
内容的提问来源于stack exchange,提问作者kyrofa
相关产品推荐
相关产品推荐

