Debian Codegraph @

tests/linux_kernel/helpers/test_pid.py

raw
1 # Copyright (c) Meta Platforms, Inc. and affiliates.
2 # SPDX-License-Identifier: LGPL-2.1-or-later
3
4 from multiprocessing import Barrier, Process
5 import os
6 from threading import Condition, Thread
7
8 from drgn.helpers.linux.pid import (
9 find_pid,
10 find_task,
11 for_each_pid,
12 for_each_task,
13 for_each_task_in_group,
14 )
15 from tests.linux_kernel import LinuxKernelTestCase
16
17
18 class TestPid(LinuxKernelTestCase):
19 def test_find_pid(self):
20 pid = os.getpid()
21 self.assertEqual(find_pid(self.prog, pid).numbers[0].nr, pid)
22
23 def test_for_each_pid(self):
24 pid = os.getpid()
25 self.assertTrue(
26 any(
27 pid_struct.numbers[0].nr == pid
28 for pid_struct in for_each_pid(self.prog)
29 )
30 )
31
32 def test_find_task(self):
33 pid = os.getpid()
34 with open("/proc/self/comm", "rb") as f:
35 comm = f.read()[:-1]
36 task = find_task(self.prog, os.getpid())
37 self.assertEqual(task.pid, pid)
38 self.assertEqual(task.comm.string_(), comm)
39
40 def test_for_each_task(self):
41 NUM_PROCS = 12
42 barrier = Barrier(NUM_PROCS + 1)
43
44 try:
45 procs = [Process(target=barrier.wait) for _ in range(NUM_PROCS)]
46 for proc in procs:
47 proc.start()
48 pids = {task.pid.value_() for task in for_each_task(self.prog)}
49 for proc in procs:
50 self.assertIn(proc.pid, pids)
51 self.assertIn(os.getpid(), pids)
52 self.assertNotIn(0, pids)
53 barrier.wait()
54 except BaseException:
55 barrier.abort()
56 for proc in procs:
57 proc.terminate()
58 raise
59
60 def test_for_each_task_idle(self):
61 self.assertTrue(
62 any(task.pid.value_() == 0 for task in for_each_task(self.prog, idle=True))
63 )
64
65 def test_for_each_task_in_group(self):
66 NUM_THREADS = 12
67 condition = Condition()
68 this_task = find_task(self.prog, os.getpid())
69
70 def thread_func():
71 with condition:
72 condition.wait()
73
74 try:
75 threads = [Thread(target=thread_func) for _ in range(NUM_THREADS)]
76 for thread in threads:
77 thread.start()
78
79 actual = {
80 t.pid.value_()
81 for t in for_each_task_in_group(this_task, include_self=False)
82 }
83 for thread in threads:
84 self.assertIn(thread.native_id, actual)
85 self.assertNotIn(os.getpid(), actual)
86 finally:
87 with condition:
88 condition.notify_all()
89 for thread in threads:
90 thread.join()