From b513512551107074072d650bd562874c88fe89cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Joakim=20S=C3=B8rensen?= Date: Tue, 20 Oct 2020 22:26:09 +0200 Subject: [PATCH] Normalize CPU stats (#2154) * Normalize CPU stats * Change fixture to make it clearer * guard for 0 * Update supervisor/docker/stats.py Co-authored-by: Pascal Vizeli * Update stats.py * Update stats.py Co-authored-by: Pascal Vizeli --- supervisor/docker/stats.py | 7 +++---- tests/docker/test_stats.py | 20 ++++++++++++++++++++ tests/fixtures/container_stats.json | 20 ++++++++++++++++++++ 3 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 tests/docker/test_stats.py create mode 100644 tests/fixtures/container_stats.json diff --git a/supervisor/docker/stats.py b/supervisor/docker/stats.py index 9c630fd69..6ada7b277 100644 --- a/supervisor/docker/stats.py +++ b/supervisor/docker/stats.py @@ -45,12 +45,11 @@ class DockerStats: stats["cpu_stats"]["system_cpu_usage"] - stats["precpu_stats"]["system_cpu_usage"] ) - online_cpu = stats["cpu_stats"]["online_cpus"] - if online_cpu == 0.0: - online_cpu = len(stats["cpu_stats"]["cpu_usage"]["percpu_usage"]) if system_delta > 0.0 and cpu_delta > 0.0: - self._cpu = (cpu_delta / system_delta) * online_cpu * 100.0 + self._cpu = (cpu_delta / system_delta) * 100.0 + else: + self._cpu = 0.0 def _calc_network(self, networks): """Calculate Network IO stats.""" diff --git a/tests/docker/test_stats.py b/tests/docker/test_stats.py new file mode 100644 index 000000000..02ffe5423 --- /dev/null +++ b/tests/docker/test_stats.py @@ -0,0 +1,20 @@ +"""Test docker stats.""" +from supervisor.docker.stats import DockerStats + +from tests.common import load_json_fixture + + +def test_cpu_presentage(docker): + """Test CPU presentage.""" + stats_fixtrue = load_json_fixture("container_stats.json") + stats = DockerStats(stats_fixtrue) + + stats._calc_cpu_percent(stats_fixtrue) # pylint: disable=protected-access + assert stats.cpu_percent == 90.0 + + stats_fixtrue["cpu_stats"]["cpu_usage"]["total_usage"] = 0 + stats_fixtrue["precpu_stats"]["cpu_usage"]["total_usage"] = 0 + stats_fixtrue["cpu_stats"]["system_cpu_usage"] = 0 + stats_fixtrue["precpu_stats"]["system_cpu_usage"] = 0 + stats._calc_cpu_percent(stats_fixtrue) # pylint: disable=protected-access + assert stats.cpu_percent == 0.0 diff --git a/tests/fixtures/container_stats.json b/tests/fixtures/container_stats.json new file mode 100644 index 000000000..f7131bf21 --- /dev/null +++ b/tests/fixtures/container_stats.json @@ -0,0 +1,20 @@ +{ + "cpu_stats": { + "cpu_usage": { + "total_usage": 190 + }, + "system_cpu_usage": 200, + "online_cpus": 24 + }, + "precpu_stats": { + "cpu_usage": { + "total_usage": 100 + }, + "system_cpu_usage": 100, + "online_cpus": 24 + }, + "memory_stats": { + "usage": 250000000, + "limit": 330000000000 + } +}