summaryrefslogtreecommitdiff
path: root/python/vyos
diff options
context:
space:
mode:
authorViacheslav Hletenko <v.gletenko@vyos.io>2022-10-28 23:33:15 +0300
committerGitHub <noreply@github.com>2022-10-28 23:33:15 +0300
commit0514a2b854634b9073719519b7da3049efca90ad (patch)
tree2f0817796f5d2e4b5b27b3c5721bd12681ba5368 /python/vyos
parent562c367e8877086bbc66005f441339b847f243a2 (diff)
parentb8b752d5b3503f2874a490582e212edd38c902fc (diff)
downloadvyos-1x-0514a2b854634b9073719519b7da3049efca90ad.tar.gz
vyos-1x-0514a2b854634b9073719519b7da3049efca90ad.zip
Merge pull request #1624 from dmbaturin/op-mode-bytes
T4779: output raw memory and storage values in bytes
Diffstat (limited to 'python/vyos')
-rw-r--r--python/vyos/util.py31
1 files changed, 31 insertions, 0 deletions
diff --git a/python/vyos/util.py b/python/vyos/util.py
index e4e2a44ec..a80584c5a 100644
--- a/python/vyos/util.py
+++ b/python/vyos/util.py
@@ -574,6 +574,37 @@ def bytes_to_human(bytes, initial_exponent=0):
size_string = "{0:.2f} {1}".format(value, suffix)
return size_string
+def human_to_bytes(value):
+ """ Converts a data amount with a unit suffix to bytes, like 2K to 2048 """
+
+ from re import match as re_match
+
+ res = re_match(r'^\s*(\d+(?:\.\d+)?)\s*([a-zA-Z]+)\s*$', value)
+
+ if not res:
+ raise ValueError(f"'{value}' is not a valid data amount")
+ else:
+ amount = float(res.group(1))
+ unit = res.group(2).lower()
+
+ if unit == 'b':
+ res = amount
+ elif (unit == 'k') or (unit == 'kb'):
+ res = amount * 1024
+ elif (unit == 'm') or (unit == 'mb'):
+ res = amount * 1024**2
+ elif (unit == 'g') or (unit == 'gb'):
+ res = amount * 1024**3
+ elif (unit == 't') or (unit == 'tb'):
+ res = amount * 1024**4
+ else:
+ raise ValueError(f"Unsupported data unit '{unit}'")
+
+ # There cannot be fractional bytes, so we convert them to integer.
+ # However, truncating causes problems with conversion back to human unit,
+ # so we round instead -- that seems to work well enough.
+ return round(res)
+
def get_cfg_group_id():
from grp import getgrnam
from vyos.defaults import cfg_group