Kubernetes 中的所有资源限制和请求如何用 kubectl 汇总?

How can I summarize all the resource limits and requests in Kubernetes with kubectl?

我开始使用 Lens 并注意到当节点内的 pods 的限制高于实际容量时,它会向您发出一些警告。

所以我尝试使用 kubectl 获取此信息,但我是 jsonpath 的新手,我只是设法获取了原始信息使用这样的东西:

kubectl get pods -o=jsonpath='{.items..resources.limits}' -A

产生这样的东西:

{"cpu":"200m","memory":"1Gi"} {"cpu":"200m","memory":"1Gi"} {"cpu":"200m","memory":"512Mi"} {"cpu":"500m","memory":"250Mi"} {"memory":"170Mi"} {"memory":"170Mi"} {"cpu":"2","memory":"2Gi"} {"cpu":"2","memory":"2Gi"} {"cpu":"2","memory":"2Gi"} {"cpu":"1","memory":"1Gi"} {"cpu":"1","memory":"1Gi"} {"cpu":"2","memory":"2Gi"} {"cpu":"100m","memory":"128Mi"} {"cpu":"100m","memory":"128Mi"} {"cpu":"500m","memory":"600Mi"} {"cpu":"1","memory":"1Gi"} {"cpu":"100m","memory":"25Mi"} {"cpu":"100m","memory":"25Mi"}

所以,我的问题是,如何对所有这些值求和?这些值是否准确,或者我是否遗漏了任何其他查询?我使用 LimitRange 检查过,我得到的值似乎是正确的,结果包括 LimitRange 配置设置的限制。

不幸的是,仅使用 kubectl 是不可能的。

但是,您可以考虑使用:

  1. JSON $sum() function:

Returns the arithmetic sum of an array of numbers.

  1. Metrics-server, Grafana and Prometheus:

We’ll walk through steps necessary to monitor how much resources (CPU or memory) a Kubernetes pod is using. Hence we’ll look at:

  • CPU requests / limits / actual usage / throttling

  • Memory requests / limits / actual usage / termination

或者 monitor Kubernetes Node CPU and Memory Requests/Limits:

Node CPU requests/limits are a sum of the CPU requests/limits for all pods running on that node. Similarly, node memory requests/limits are a sum of memory requests/limits of all pods

  1. kube-state-metrics:

kube-state-metrics is a simple service that listens to the Kubernetes API server and generates metrics about the state of the objects. (See examples in the Metrics section below.) It is not focused on the health of the individual Kubernetes components, but rather on the health of the various objects inside, such as deployments, nodes and pods.

只用 kubectl 命令是不可能的。但是,您可以使用 kubectl 的输出并编写一个基本的 shell 脚本来计算总值。

以下 shell 脚本将输出所有命名空间中所有 pods 的总 CPU 限制(以 m 为单位)。

res=$(kubectl get pods -o=jsonpath='{.items[*]..resources.limits.cpu}' -A)
let tot=0
for i in $res
do
   if [[ $i =~ "m" ]]; then
      i=$(echo $i | sed 's/[^0-9]*//g')
      tot=$(( tot + i ))
   else
      tot=$(( tot + i*1000 ))
   fi
done
echo $tot

您可以扩展上述内容以计算 CPU 请求以及内存请求和限制值。

您可以使用 kubectl 插件 list/sort pods cpu 限制:

kubectl resource-capacity --sort cpu.limit --util --pods

https://github.com/robscott/kube-capacity