From b4e6ee894364f01c2f4210b63cebd29351096b6b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Mon, 10 Jan 2022 17:31:50 +0100 Subject: [PATCH 1/2] Fix formatting of zero bytes Previously, that would raise a ValueError (math domain error), because log(0) is undefined. --- snikket_web/infra.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/snikket_web/infra.py b/snikket_web/infra.py index e31c480..c17f01b 100644 --- a/snikket_web/infra.py +++ b/snikket_web/infra.py @@ -53,7 +53,10 @@ def circle_name(c: typing.Any) -> str: def format_bytes(n: float) -> str: - scale = math.floor(math.log(n, 1024)) + try: + scale = max(math.floor(math.log(n, 1024)), 0) + except ValueError: + scale = 0 try: unit = BYTE_UNIT_SCALE_MAP[scale] factor = 1024**scale From 51f2ebbd1323f64011b7845ec95c90da33b45a89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Sch=C3=A4fer?= Date: Mon, 10 Jan 2022 17:32:11 +0100 Subject: [PATCH 2/2] Handle the correct exception when formatting extremely high amounts of bytes Found in production. Yes really. Due to some borked LXC integration, my snikket host reports ``` MemTotal: 9007199254740991 kB MemFree: 9007199254690591 kB MemAvailable: 9007199254690591 kB ``` That is more than 1024 TiB, so it tries to go further up in the scale, which then causes a Guru Meditation because of the uncaught IndexError. --- snikket_web/infra.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/snikket_web/infra.py b/snikket_web/infra.py index c17f01b..c5e9ef0 100644 --- a/snikket_web/infra.py +++ b/snikket_web/infra.py @@ -60,7 +60,7 @@ def format_bytes(n: float) -> str: try: unit = BYTE_UNIT_SCALE_MAP[scale] factor = 1024**scale - except ValueError: + except IndexError: unit = "TiB" factor = 1024**4 if factor > 1: