From 6405188a983a83c333b219ea6cdab8b5193e9745 Mon Sep 17 00:00:00 2001 From: Roland Date: Wed, 16 Aug 2023 15:41:55 -0600 Subject: [PATCH] Reading system load from /proc/loadavg. --- wrolpi/status.py | 29 +++++++++-------------------- wrolpi/test/test_status.py | 15 ++++----------- 2 files changed, 13 insertions(+), 31 deletions(-) diff --git a/wrolpi/status.py b/wrolpi/status.py index 0618a559..fee55570 100755 --- a/wrolpi/status.py +++ b/wrolpi/status.py @@ -48,27 +48,16 @@ def get_load_psutil() -> SystemLoad: return load +LOAD_AVG_FILE = pathlib.Path('/proc/loadavg') + + async def get_load() -> SystemLoad: - try: - return get_load_psutil() - except Exception as e: - warn_once(e) - - # Fallback to using `uptime` to fetch load information. - proc = await asyncio.subprocess.create_subprocess_shell( - str(UPTIME_BIN), - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - stdout, stderr = await proc.communicate() - - stdout = stdout.strip() - if proc.returncode != 0 or not stdout: - logger.warning(f'{UPTIME_BIN} exited with {proc.returncode} or was empty') - return SystemLoad() - - stdout = stdout.decode() - load = SystemLoad(*[Decimal(i) for i in LOAD_REGEX.search(stdout).groups()]) + """Read loadavg file and return the 1, 5, and 15 minute system loads.""" + # Read load information from proc file. + # Example: 0.99 1.06 1.02 1/2305 43879 + loadavg = LOAD_AVG_FILE.read_text() + load_1, load_5, load_15, *_ = loadavg.split(' ') + load = SystemLoad(Decimal(load_1), Decimal(load_5), Decimal(load_15)) return load diff --git a/wrolpi/test/test_status.py b/wrolpi/test/test_status.py index d6cd52cf..f4dc60a4 100644 --- a/wrolpi/test/test_status.py +++ b/wrolpi/test/test_status.py @@ -8,20 +8,13 @@ from wrolpi import status @pytest.mark.asyncio async def test_get_load(): - """Minimum laod testing because this will fail in docker, etc.""" + """Test reading load information from /proc/loadavg.""" load = await status.get_load() assert isinstance(load, status.SystemLoad) - assert load.minute_1 is not None and isinstance(load.minute_1, Decimal) - assert load.minute_5 is not None and isinstance(load.minute_5, Decimal) - assert load.minute_15 is not None and isinstance(load.minute_15, Decimal) - with mock.patch('wrolpi.status.get_load_psutil') as mock_get_load_psutil: - # Fallback to subprocess when psutil is not available. - mock_get_load_psutil.side_effect = Exception('testing no psutil') - load = await status.get_load() - assert isinstance(load, status.SystemLoad) - assert load.minute_1 is not None - assert isinstance(load.minute_1, Decimal) + assert isinstance(load.minute_1, Decimal) and load.minute_1 >= 0 + assert isinstance(load.minute_5, Decimal) and load.minute_5 >= 0 + assert isinstance(load.minute_15, Decimal) and load.minute_15 >= 0 @pytest.mark.asyncio