Home > OS >  How to express the CPU and memory request and limit values in one consistent unit?
How to express the CPU and memory request and limit values in one consistent unit?

Time:09-23

When doing a kubectl describe nodes command, they CPU and memory request and limit values can come in varied units, as unbelievable as that sounds.

In the example below:

  example                     example-85cdb9b4cc-xvpn2              500m (2%)     2 (8%)       256Mi (0%)       512Mi (0%)        2d
  example                     example-zk-0                          1 (4%)        2 (8%)       2Gi (3%)         4Gi (7%)          7d8h
  example                     example-6f54cd4967-jzhxp              2 (8%)        0 (0%)       1500M (2%)       1500M (2%)        2d

we can see 2 different units for the CPU values:

500m 
1 which translates as 1000m

And 3 different units for the memory values:

M
Gi
Mi

It makes scripting on these values unnecessarily cumbersome.

Is there any way to have these values expressed in one consistent unit ?

CodePudding user response:

There's no way to make kubectl describe do this, which makes sense because describe is intended for human consumption, but there's also no way I can find to do it from kubectl get -o json, which is annoying. The k8s Go library has a resource package which can manipulate resource values, which is probably your best bet for reliably scripting anything involving the k8s API.

If you aren't interested in using Go (or another language with a k8s API library), I did run across a little tool called kube-resource-unit-converter which uses that package to normalize units. It doesn't work so well for millicore values, so I opened a PR to add a -m flag for printing out the milli-value of a resource. Mix it with jq and you can use it in scripts fairly easily:

# for a container with a 600m cpu limit
$ kubectl get pods -o json | jq -r '.items[0].spec.containers[0].resources.limits.cpu' | ./kube-resource-unit-converter -m
600

Alternatively, an approach I've seen in DataDog is just to have a case statement that parses the unit and multiplies the value accordingly. A bit cludgy but not likely to ever fail or need to change.

  • Related