procs: an engine adopted by systemd --user is found as an orphan, and ending it waits on the start token until the process is really gone (PR #3254 by toel1234)

This commit is contained in:
toel1234 authored and Niko1221 committed 2026-10-26 18:19:05 +01:00
1 parent eb1c40038c
commit dc1fd367d3
2 files changed
+58 -4

No files matched your search

+8 -4
View File
@@ -309,10 +309,13 @@ def end_one(record: dict, *, grace: float = 8.0) -> str:
if not is_same(pid, record["token"], record["cmd"]):
drop_record(pid)
return "gone"
# once signalled, the start token alone says it still runs: an exiting process has an empty command line on Linux
def running():
return start_token(pid) == record["token"]
if not WINDOWS:
_signal_verified(record, signal.SIGTERM)
deadline = time.monotonic() + grace
while time.monotonic() < deadline and is_same(pid, record["token"], record["cmd"]):
while time.monotonic() < deadline and running():
time.sleep(0.1)
if is_same(pid, record["token"], record["cmd"]):
_signal_verified(record, signal.SIGKILL)
@@ -320,9 +323,9 @@ def end_one(record: dict, *, grace: float = 8.0) -> str:
if is_same(pid, record["token"], record["cmd"]):
subprocess.run(["taskkill", "/F", "/PID", str(pid)], capture_output=True) # one PID, verified just above
deadline = time.monotonic() + 10
while time.monotonic() < deadline and is_same(pid, record["token"], record["cmd"]):
while time.monotonic() < deadline and running():
time.sleep(0.1)
if is_same(pid, record["token"], record["cmd"]):
if running():
return "stuck"
drop_record(pid)
return "ended"
@@ -354,7 +357,8 @@ def orphans_of(engine_exe: str) -> list[Ident]:
return []
mine = {os.getpid()}
try:
mine.update(q.pid for q in psutil.Process().parents() if q.pid != 1) # pid 1 adopts orphans: it is not a starter
# pid 1 and a subreaper such as `systemd --user` (an ancestor of every desktop terminal) adopt orphans: they are not starters
mine.update(q.pid for q in psutil.Process().parents() if q.pid != 1 and q.name().lower() not in INIT_NAMES)
except psutil.Error:
pass
found = []
+50
View File
@@ -137,6 +137,56 @@ class Procs(unittest.TestCase):
self.assertIsNone(live.poll())
self.assertIsNone(procs.start_token(orphan_pid))
class SubreaperOrphans(unittest.TestCase):
"""An engine adopted by `systemd --user` is an orphan (#3254), and a dying process is waited for by its start token."""
class Gone(Exception):
pass
def fake_psutil(self, ancestors, parent_name):
class Err(Exception):
pass
class NoSuch(Err):
pass
def proc(pid, name, ppid=1):
return mock.Mock(pid=pid, **{"name.return_value": name, "exe.return_value": "/x/engine", "info": {
"pid": pid, "ppid": ppid, "cmdline": ["engine", "--serve"], "create_time": 100.0}})
me = mock.Mock(**{"parents.return_value": [proc(p, n) for p, n in ancestors]})
engine = proc(7000, "engine", ppid=5000)
parent = proc(5000, parent_name)
parent.create_time.return_value = 50.0
parent.status.return_value = "running"
fake = mock.Mock(Error=Err, NoSuchProcess=NoSuch, STATUS_ZOMBIE="zombie")
fake.Process.side_effect = lambda pid=None: me if pid is None else parent
fake.process_iter.return_value = [engine]
return fake
def found(self, ancestors, parent_name):
fake = self.fake_psutil(ancestors, parent_name)
with mock.patch.object(procs, "psutil", fake), mock.patch.object(procs, "same_file", return_value=True), \
mock.patch.object(procs, "identify", side_effect=lambda pid: ("ident", pid)):
return procs.orphans_of("/x/engine")
def test_an_engine_adopted_by_systemd_user_is_an_orphan_even_when_it_is_an_ancestor_of_the_terminal(self):
# systemd --user (pid 5000) is an ancestor of every desktop terminal and adopts what loses its parent
self.assertEqual(self.found([(5000, "systemd"), (6000, "bash")], "systemd"), [("ident", 7000)])
def test_an_engine_whose_parent_is_a_real_ancestor_is_not_an_orphan(self):
# started by this server's own shell: not touched
self.assertEqual(self.found([(5000, "bash"), (6000, "tmux")], "bash"), [])
def test_ending_waits_on_the_start_token_not_on_an_empty_command_line(self):
record = {"pid": 4242, "token": "t1", "cmd": ["engine", "--serve"]}
tokens = iter(["t1", "t1", None]) # still exiting twice, then gone
with mock.patch.object(procs, "WINDOWS", False), mock.patch.object(procs, "is_same", side_effect=[True, False, False]) as same, \
mock.patch.object(procs, "_signal_verified"), mock.patch.object(procs, "start_token", side_effect=lambda pid: next(tokens)), \
mock.patch.object(procs, "drop_record"), mock.patch.object(procs.time, "sleep"):
self.assertEqual(procs.end_one(record, grace=5), "ended")
self.assertGreaterEqual(same.call_count, 1)
if __name__ == "__main__":
unittest.main()