I am writing an API which takes inputs for kubernetes container resources. The API takes only the 4 values as string inputs and not the entire resources
block.
Examples:
For memory inputs: 4Gi
, 8G
, 512M
For cpu limits: 1
, 250m
, 0.5
I will use this string value input received in the API to configure one of the deployment's container(s) during the course of processing the request.
I need to validate the string inputs received in the API so that I can make sure at an early stage that my k8s deployment will not fail because of bad input strings and also I want to put a maximum limit on what configurations can be specified by the requester.
I would like to know if there exists a library in python that can easily convert these strings to lowest unit and help me compare it with a max_threshold
In the official Kubernetes Python client library, the kubernetes.utils.quantity
package includes a parse_quantity()
function that turns a string resource value into a number.
>>> from kubernetes.utils import parse_quantity
>>> parse_quantity('4Gi')
Decimal('4294967296')
>>> parse_quantity('8G')
Decimal('8000000000')
>>> parse_quantity('250m')
Decimal('0.250')
The arbitrary-precision decimal.Decimal
type is part of the standard Python library, and you can use it like a normal number.
>>> parse_quantity('8G') > parse_quantity('4Gi')
True
>>> parse_quantity('250m') > 2.0
False