From 7ebe3b61c001b89c10e3370adb5d073c8f4a3582 Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Mon, 17 Feb 2020 13:26:07 +0100 Subject: [PATCH 1/2] Retrieve database usage --- musician/models.py | 35 ++++++++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 7 deletions(-) diff --git a/musician/models.py b/musician/models.py index f3cbfc1..70a8d42 100644 --- a/musician/models.py +++ b/musician/models.py @@ -153,16 +153,37 @@ class DatabaseService(OrchestraModel): if 'users' in data: users = [DatabaseUser.new_from_json(user_data) for user_data in data['users']] - # TODO(@slamora) retrieve database usage - usage = { - 'usage': 250, - 'total': 500, - 'unit': 'MB', - 'percent': 50, - } + usage = cls.get_usage(data) return super().new_from_json(data=data, users=users, usage=usage) + @classmethod + def get_usage(self, data): + try: + resources = data['resources'] + resource_disk = {} + for r in resources: + if r['name'] == 'disk': + resource_disk = r + break + + details = { + 'usage': float(resource_disk['used']), + 'total': resource_disk['allocated'], + 'unit': resource_disk['unit'], + } + except (IndexError, KeyError): + return {} + + + percent = get_bootstraped_percent( + details['usage'], + details['total'] + ) + details['percent'] = percent + + return details + class Domain(OrchestraModel): api_name = 'domain' From a03714364c361df90c23f023bd040c1103d47b3d Mon Sep 17 00:00:00 2001 From: Santiago Lamora Date: Mon, 17 Feb 2020 13:26:18 +0100 Subject: [PATCH 2/2] Handle ZeroDivisionError --- musician/tests.py | 3 +++ musician/utils.py | 5 ++++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/musician/tests.py b/musician/tests.py index 13c365e..fe0215c 100644 --- a/musician/tests.py +++ b/musician/tests.py @@ -67,3 +67,6 @@ class GetBootstrapedPercentTest(TestCase): value = get_bootstraped_percent(-10, 100) self.assertIn(value, self.BS_WIDTH) self.assertEqual(value, 0) + + def test_invalid_total_is_zero(self): + value = get_bootstraped_percent(25, 0) diff --git a/musician/utils.py b/musician/utils.py index 7b029c1..affc93f 100644 --- a/musician/utils.py +++ b/musician/utils.py @@ -4,8 +4,11 @@ def get_bootstraped_percent(value, total): Useful to set progress bar width using CSS classes (e.g. w-25) """ + try: + percent = value / total + except ZeroDivisionError: + return 0 - percent = value / total bootstraped = round(percent * 4) * 100 // 4 # handle min and max boundaries