Skip to content

Commit d974044

Browse files
committed
fix(tests/cpu-monitor): handle errors in case process or thread dies
The logic I've added to monitor the CPU wasn't handling the error when the process or thread died. This change adds the required error handling. In case a process terminates, the get_cpu_times will return an empty dict and the get_cpu_utilization will also return an empty dict. In case a thread dies, the cpu usage of that thread will be omitted from get_cpu_times and get_cpu_utilization (due to the set intersection). In all cases, track_cpu_utilization will only add to the list of values the threads that are returned, if any. Signed-off-by: Riccardo Mancini <[email protected]>
1 parent 283e574 commit d974044

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

tests/framework/utils.py

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -58,18 +58,35 @@ def set_cpu_affinity(pid: int, cpulist: list) -> list:
5858

5959
def get_thread_name(pid: int, tid: int) -> str:
6060
"""Return thread name from pid and tid pair."""
61-
return Path("/proc", str(pid), "task", str(tid), "comm").read_text("utf-8").strip()
61+
try:
62+
return (
63+
Path("/proc", str(pid), "task", str(tid), "comm").read_text("utf-8").strip()
64+
)
65+
except FileNotFoundError as exc:
66+
raise psutil.NoSuchProcess(tid) from exc
6267

6368

6469
CpuTimes = namedtuple("CpuTimes", ["user", "system"])
6570

6671

6772
def get_cpu_times(pid: int) -> Dict[str, CpuTimes]:
6873
"""Return a dict mapping thread name to CPU usage (in seconds) since start."""
74+
threads = []
75+
try:
76+
threads = psutil.Process(pid).threads()
77+
except psutil.NoSuchProcess as exc:
78+
logging.warning("Process %d does not exist", pid, exc_info=exc)
79+
return {}
80+
6981
cpu_times = {}
70-
for thread in psutil.Process(pid).threads():
71-
thread_name = get_thread_name(pid, thread.id)
72-
cpu_times[thread_name] = CpuTimes(thread.user_time, thread.system_time)
82+
for thread in threads:
83+
try:
84+
thread_name = get_thread_name(pid, thread.id)
85+
cpu_times[thread_name] = CpuTimes(thread.user_time, thread.system_time)
86+
except psutil.NoSuchProcess as exc:
87+
logging.warning("Thread %d no longer exists", thread.id, exc_info=exc)
88+
continue
89+
7390
return cpu_times
7491

7592

0 commit comments

Comments
 (0)