From 57e17265415ca6e1c8bac75985cf61be20dd5a05 Mon Sep 17 00:00:00 2001 From: David Slusser Date: Sat, 17 Feb 2024 17:56:14 -0800 Subject: [PATCH] updating process count logic --- src/djangoaddicts/hostutils/views/gui.py | 24 +++++++++++++++--------- tests/unit/test_gui.py | 2 +- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/djangoaddicts/hostutils/views/gui.py b/src/djangoaddicts/hostutils/views/gui.py index 4e1a16d..8e40716 100644 --- a/src/djangoaddicts/hostutils/views/gui.py +++ b/src/djangoaddicts/hostutils/views/gui.py @@ -139,16 +139,22 @@ def get(self, request, *args, **kwargs): context["title"] = self.title context["now"] = datetime.datetime.now() context["subtitle"] = psutil.os.uname()[1] - process_list = list(psutil.process_iter()) + counts = {"running": 0, "sleeping": 0, "idle": 0, "stopped": 0, "zombie": 0, "dead": 0, "disk-sleep": 0} + process_list = [] + for process in psutil.process_iter(): + try: + counts[process.status()] += 1 + process_list.append( + { + "pid": process.pid, + "name": process.name(), + "status": process.status(), + "create_time": process.create_time(), + } + ) + except (psutil.NoSuchProcess, psutil.AccessDenied): + continue context["process_list"] = process_list - counts = { - "running": len([i for i in process_list if i.status() == "running"]), - "sleeping": len([i for i in process_list if i.status() == "sleeping"]), - "idle": len([i for i in process_list if i.status() == "idle"]), - "stopped": len([i for i in process_list if i.status() == "stopped"]), - "zombie": len([i for i in process_list if i.status() == "zombie"]), - "dead": len([i for i in process_list if i.status() == "dead"]), - } context["counts"] = counts filter_form = {} filter_form["form"] = HostProcessFilterForm(request.GET or None) diff --git a/tests/unit/test_gui.py b/tests/unit/test_gui.py index 7103097..ccad831 100644 --- a/tests/unit/test_gui.py +++ b/tests/unit/test_gui.py @@ -74,8 +74,8 @@ def test_get(self): def test_get_with_invalid(self): """verify page is redered if psutil.NoSuchProcess is raised""" url = reverse("hostutils:host_process") - process_list = psutil.process_iter() with patch("psutil.process_iter") as mocked_process_list: + process_list = psutil.process_iter() p = subprocess.Popen("ls", stdout=subprocess.PIPE) mp = iter((psutil.Process(p.pid), psutil.Process(p.pid))) p.communicate()