Skip to content

Commit b2d1dfa

Browse files
committed
add function to parse canonical quantities (e.g. resources)
This utility function is useful to parse values like the 200m or 300Gi memory and cpu resources stored in kubernetes manifests. The function only supports the "canonical form" which has no fractional digits.
1 parent c86e489 commit b2d1dfa

File tree

3 files changed

+142
-0
lines changed

3 files changed

+142
-0
lines changed

kubernetes/test/test_quantity.py

+71
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# coding: utf-8
2+
# Copyright 2019 The Kubernetes Authors.
3+
#
4+
# Licensed under the Apache License, Version 2.0 (the "License");
5+
# you may not use this file except in compliance with the License.
6+
# You may obtain a copy of the License at
7+
#
8+
# http://www.apache.org/licenses/LICENSE-2.0
9+
#
10+
# Unless required by applicable law or agreed to in writing, software
11+
# distributed under the License is distributed on an "AS IS" BASIS,
12+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
# See the License for the specific language governing permissions and
14+
# limitations under the License.
15+
16+
from __future__ import absolute_import
17+
18+
import unittest
19+
from kubernetes.utils import parse_quantity
20+
21+
22+
class TestQuantity(unittest.TestCase):
23+
def test_parse(self):
24+
self.assertEqual(parse_quantity(2), 2)
25+
self.assertEqual(parse_quantity(2.), 2)
26+
self.assertEqual(parse_quantity("123"), 123)
27+
self.assertEqual(parse_quantity("2"), 2)
28+
self.assertEqual(parse_quantity("2m"), 0.002)
29+
self.assertEqual(parse_quantity("223k"), 223000)
30+
self.assertEqual(parse_quantity("002M"), 2 * 1000**2)
31+
self.assertEqual(parse_quantity("2M"), 2 * 1000**2)
32+
self.assertEqual(parse_quantity("4123G"), 4123 * 1000**3)
33+
self.assertEqual(parse_quantity("2T"), 2 * 1000**4)
34+
self.assertEqual(parse_quantity("2P"), 2 * 1000**5)
35+
self.assertEqual(parse_quantity("2E"), 2 * 1000**6)
36+
37+
self.assertEqual(parse_quantity("2m"), 0.002)
38+
self.assertEqual(parse_quantity("223Ki"), 223 * 1024)
39+
self.assertEqual(parse_quantity("002Mi"), 2 * 1024**2)
40+
self.assertEqual(parse_quantity("2Mi"), 2 * 1024**2)
41+
self.assertEqual(parse_quantity("2Gi"), 2 * 1024**3)
42+
self.assertEqual(parse_quantity("4123Gi"), 4123 * 1024**3)
43+
self.assertEqual(parse_quantity("2Ti"), 2 * 1024**4)
44+
self.assertEqual(parse_quantity("2Pi"), 2 * 1024**5)
45+
self.assertEqual(parse_quantity("2Ei"), 2 * 1024**6)
46+
47+
def test_parse_invalid(self):
48+
self.assertRaises(ValueError, parse_quantity, "bla")
49+
self.assertRaises(ValueError, parse_quantity, "Ki")
50+
self.assertRaises(ValueError, parse_quantity, "M")
51+
self.assertRaises(ValueError, parse_quantity, "2ki")
52+
self.assertRaises(ValueError, parse_quantity, "2Ki ")
53+
self.assertRaises(ValueError, parse_quantity, "20Ki ")
54+
self.assertRaises(ValueError, parse_quantity, "2MiKi")
55+
self.assertRaises(ValueError, parse_quantity, "2MK")
56+
self.assertRaises(ValueError, parse_quantity, "2MKi")
57+
self.assertRaises(ValueError, parse_quantity, "234df")
58+
self.assertRaises(ValueError, parse_quantity, "df234")
59+
self.assertRaises(ValueError, parse_quantity, tuple())
60+
# canonical format has no fractional digits
61+
self.assertRaises(ValueError, parse_quantity, "2.34Ki ")
62+
self.assertRaises(ValueError, parse_quantity, "2.34B")
63+
self.assertRaises(ValueError, parse_quantity, "2.34Bi")
64+
self.assertRaises(ValueError, parse_quantity, "2.34")
65+
self.assertRaises(ValueError, parse_quantity, ".34")
66+
self.assertRaises(ValueError, parse_quantity, "34.")
67+
self.assertRaises(ValueError, parse_quantity, ".34M")
68+
69+
70+
if __name__ == '__main__':
71+
unittest.main()

kubernetes/utils/__init__.py

+1
Original file line numberDiff line numberDiff line change
@@ -15,3 +15,4 @@
1515
from __future__ import absolute_import
1616

1717
from .create_from_yaml import FailToCreateError, create_from_yaml
18+
from .quantity import parse_quantity

kubernetes/utils/quantity.py

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
# Copyright 2019 The Kubernetes Authors.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
import re
15+
16+
17+
def parse_quantity(quantity):
18+
"""
19+
Parse kubernetes canonical form quantity like 200Mi to an float number.
20+
Supported SI suffixes:
21+
base1024: Ki | Mi | Gi | Ti | Pi | Ei
22+
base1000: m | "" | k | M | G | T | P | E
23+
24+
Input:
25+
quanity: string. kubernetes canonical form quantity
26+
27+
Returns:
28+
float
29+
30+
Raises:
31+
ValueError on invalid or unknown input
32+
"""
33+
exponents = {"m": -1, "K": 1, "k": 1, "M": 2,
34+
"G": 3, "T": 4, "P": 5, "E": 6}
35+
pattern = r"^(\d+)([^\d]{1,2})?$"
36+
37+
if isinstance(quantity, (int, float)):
38+
return float(quantity)
39+
40+
quantity = str(quantity)
41+
42+
res = re.match(pattern, quantity)
43+
if not res:
44+
raise ValueError(
45+
"{} did not match pattern {}".format(quantity, pattern)
46+
)
47+
number, suffix = res.groups()
48+
number = float(number)
49+
50+
if suffix is None:
51+
return number
52+
53+
suffix = res.groups()[1]
54+
55+
if suffix.endswith("i"):
56+
base = 1024
57+
elif len(suffix) == 1:
58+
base = 1000
59+
else:
60+
raise ValueError("{} has unknown suffix".format(quantity))
61+
62+
# handly SI inconsistency
63+
if suffix == "ki":
64+
raise ValueError("{} has unknown suffix".format(quantity))
65+
66+
if suffix[0] not in exponents:
67+
raise ValueError("{} has unknown suffix".format(quantity))
68+
69+
exponent = exponents[suffix[0]]
70+
return number * (base ** exponent)

0 commit comments

Comments
 (0)