-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
add function to parse canonical quantities (e.g. resources) #855
Merged
k8s-ci-robot
merged 1 commit into
kubernetes-client:master
from
juliantaylor:parse-quantity
Aug 26, 2019
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,112 @@ | ||
# coding: utf-8 | ||
# Copyright 2019 The Kubernetes Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
from __future__ import absolute_import | ||
|
||
import unittest | ||
from kubernetes.utils import parse_quantity | ||
from decimal import Decimal | ||
|
||
|
||
class TestQuantity(unittest.TestCase): | ||
def test_parse(self): | ||
self.assertIsInstance(parse_quantity(2.2), Decimal) | ||
# input, expected output | ||
tests = [ | ||
(0, 0), | ||
(2, 2), | ||
(2, Decimal("2")), | ||
(2., 2), | ||
(Decimal("2.2"), Decimal("2.2")), | ||
(2., Decimal(2)), | ||
(Decimal("2."), 2), | ||
("123", 123), | ||
("2", 2), | ||
("2n", Decimal("2") * Decimal(1000)**-3), | ||
("2u", Decimal("0.000002")), | ||
("2m", Decimal("0.002")), | ||
("0m", Decimal("0")), | ||
("0M", Decimal("0")), | ||
("223k", 223000), | ||
("002M", 2 * 1000**2), | ||
("2M", 2 * 1000**2), | ||
("4123G", 4123 * 1000**3), | ||
("2T", 2 * 1000**4), | ||
("2P", 2 * 1000**5), | ||
("2E", 2 * 1000**6), | ||
|
||
("223Ki", 223 * 1024), | ||
("002Mi", 2 * 1024**2), | ||
("2Mi", 2 * 1024**2), | ||
("2Gi", 2 * 1024**3), | ||
("4123Gi", 4123 * 1024**3), | ||
("2Ti", 2 * 1024**4), | ||
("2Pi", 2 * 1024**5), | ||
("2Ei", 2 * 1024**6), | ||
|
||
("2.34n", Decimal("2.34") * Decimal(1000)**-3), | ||
("2.34u", Decimal("2.34") * Decimal(1000)**-2), | ||
("2.34m", Decimal("2.34") * Decimal(1000)**-1), | ||
("2.34Ki", Decimal("2.34") * 1024), | ||
("2.34", Decimal("2.34")), | ||
(".34", Decimal("0.34")), | ||
("34.", 34), | ||
(".34M", Decimal("0.34") * 1000**2), | ||
|
||
("2e2K", Decimal("2e2") * 1000), | ||
("2e2Ki", Decimal("2e2") * 1024), | ||
("2e-2Ki", Decimal("2e-2") * 1024), | ||
("2.34E1", Decimal("2.34E1")), | ||
(".34e-2", Decimal("0.34e-2")), | ||
] | ||
|
||
for inp, out in tests: | ||
self.assertEqual(parse_quantity(inp), out) | ||
if isinstance(inp, (int, float, Decimal)): | ||
self.assertEqual(parse_quantity(-1 * inp), -out) | ||
else: | ||
self.assertEqual(parse_quantity("-" + inp), -out) | ||
self.assertEqual(parse_quantity("+" + inp), out) | ||
|
||
def test_parse_invalid(self): | ||
self.assertRaises(ValueError, parse_quantity, []) | ||
self.assertRaises(ValueError, parse_quantity, "") | ||
self.assertRaises(ValueError, parse_quantity, "-") | ||
self.assertRaises(ValueError, parse_quantity, "i") | ||
self.assertRaises(ValueError, parse_quantity, "2i") | ||
self.assertRaises(ValueError, parse_quantity, "2mm") | ||
self.assertRaises(ValueError, parse_quantity, "2mmKi") | ||
self.assertRaises(ValueError, parse_quantity, "2KKi") | ||
self.assertRaises(ValueError, parse_quantity, "2e") | ||
self.assertRaises(ValueError, parse_quantity, "2.2i") | ||
self.assertRaises(ValueError, parse_quantity, "bla") | ||
self.assertRaises(ValueError, parse_quantity, "Ki") | ||
self.assertRaises(ValueError, parse_quantity, "M") | ||
self.assertRaises(ValueError, parse_quantity, "2ki") | ||
self.assertRaises(ValueError, parse_quantity, "2Ki ") | ||
self.assertRaises(ValueError, parse_quantity, "20Ki ") | ||
self.assertRaises(ValueError, parse_quantity, "20B") | ||
self.assertRaises(ValueError, parse_quantity, "20Bi") | ||
self.assertRaises(ValueError, parse_quantity, "20.2Bi") | ||
self.assertRaises(ValueError, parse_quantity, "2MiKi") | ||
self.assertRaises(ValueError, parse_quantity, "2MK") | ||
self.assertRaises(ValueError, parse_quantity, "2MKi") | ||
self.assertRaises(ValueError, parse_quantity, "234df") | ||
self.assertRaises(ValueError, parse_quantity, "df234") | ||
self.assertRaises(ValueError, parse_quantity, tuple()) | ||
|
||
|
||
if __name__ == '__main__': | ||
unittest.main() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,75 @@ | ||
# Copyright 2019 The Kubernetes Authors. | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
from decimal import Decimal, InvalidOperation | ||
|
||
|
||
def parse_quantity(quantity): | ||
""" | ||
Parse kubernetes canonical form quantity like 200Mi to a decimal number. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could you add a link to the quantity code in k/k repo? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. done |
||
Supported SI suffixes: | ||
base1024: Ki | Mi | Gi | Ti | Pi | Ei | ||
base1000: n | u | m | "" | k | M | G | T | P | E | ||
|
||
See https://github.com/kubernetes/apimachinery/blob/master/pkg/api/resource/quantity.go | ||
|
||
Input: | ||
quanity: string. kubernetes canonical form quantity | ||
|
||
Returns: | ||
Decimal | ||
|
||
Raises: | ||
ValueError on invalid or unknown input | ||
""" | ||
if isinstance(quantity, (int, float, Decimal)): | ||
return Decimal(quantity) | ||
|
||
exponents = {"n": -3, "u": -2, "m": -1, "K": 1, "k": 1, "M": 2, | ||
"G": 3, "T": 4, "P": 5, "E": 6} | ||
|
||
quantity = str(quantity) | ||
number = quantity | ||
suffix = None | ||
if len(quantity) >= 2 and quantity[-1] == "i": | ||
if quantity[-2] in exponents: | ||
number = quantity[:-2] | ||
suffix = quantity[-2:] | ||
elif len(quantity) >= 1 and quantity[-1] in exponents: | ||
number = quantity[:-1] | ||
suffix = quantity[-1:] | ||
|
||
try: | ||
number = Decimal(number) | ||
except InvalidOperation: | ||
raise ValueError("Invalid number format: {}".format(number)) | ||
|
||
if suffix is None: | ||
return number | ||
|
||
if suffix.endswith("i"): | ||
base = 1024 | ||
elif len(suffix) == 1: | ||
base = 1000 | ||
else: | ||
raise ValueError("{} has unknown suffix".format(quantity)) | ||
|
||
# handly SI inconsistency | ||
if suffix == "ki": | ||
raise ValueError("{} has unknown suffix".format(quantity)) | ||
|
||
if suffix[0] not in exponents: | ||
raise ValueError("{} has unknown suffix".format(quantity)) | ||
|
||
exponent = Decimal(exponents[suffix[0]]) | ||
return number * (base ** exponent) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
https://github.com/kubernetes/kubernetes/blob/master/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_test.go#L219
some cases are missing here.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
yes this function currently only parse the canonical form of the quantities, which is what you get in the api objects. It is not intended to re-implement the quantities in kubernetes.
it is probably reasonably straightforward to do by returning decimal objects instead of floats.
Imo that is not unreasonable, but it means user have to work fully in decimals or convert to float/integer as you cannot mix both in computations.
Should I change it to decimals and be able to parse all number representations, also those that will never be in api objects?