Debian Codegraph @

test/lib/ansible_test/_internal/processes.py

raw
1 """Wrappers around `ps` for querying running processes."""
2
3 from __future__ import annotations
4
5 import collections
6 import dataclasses
7 import os
8 import pathlib
9 import shlex
10
11 from ansible_test._internal.util import raw_command
12
13
14 @dataclasses.dataclass(frozen=True)
15 class ProcessData:
16 """Data about a running process."""
17
18 pid: int
19 ppid: int
20 command: str
21
22
23 @dataclasses.dataclass(frozen=True)
24 class Process:
25 """A process in the process tree."""
26
27 pid: int
28 command: str
29 parent: Process | None = None
30 children: tuple[Process, ...] = dataclasses.field(default_factory=tuple)
31
32 @property
33 def args(self) -> list[str]:
34 """The list of arguments that make up `command`."""
35 return shlex.split(self.command)
36
37 @property
38 def path(self) -> pathlib.Path:
39 """The path to the process."""
40 return pathlib.Path(self.args[0])
41
42
43 def get_process_data(pids: list[int] | None = None) -> list[ProcessData]:
44 """Return a list of running processes."""
45 if pids:
46 args = ['-p', ','.join(map(str, pids))]
47 else:
48 args = ['-A']
49
50 lines = raw_command(['ps'] + args + ['-o', 'pid,ppid,command'], capture=True)[0].splitlines()[1:]
51 processes = [ProcessData(pid=int(pid), ppid=int(ppid), command=command) for pid, ppid, command in (line.split(maxsplit=2) for line in lines)]
52
53 return processes
54
55
56 def get_process_tree() -> dict[int, Process]:
57 """Return the process tree."""
58 processes = get_process_data()
59 pid_to_process: dict[int, Process] = {}
60 pid_to_children: dict[int, list[Process]] = collections.defaultdict(list)
61
62 for data in processes:
63 pid_to_process[data.pid] = process = Process(pid=data.pid, command=data.command)
64
65 if data.ppid:
66 pid_to_children[data.ppid].append(process)
67
68 for data in processes:
69 pid_to_process[data.pid] = dataclasses.replace(
70 pid_to_process[data.pid],
71 parent=pid_to_process.get(data.ppid),
72 children=tuple(pid_to_children[data.pid]),
73 )
74
75 return pid_to_process
76
77
78 def get_current_process() -> Process:
79 """Return the current process along with its ancestors and descendants."""
80 return get_process_tree()[os.getpid()]