diff --git a/nixos/services/power-guard/power-guard.py b/nixos/services/power-guard/power-guard.py index 4eb2d178f..3269f6fa9 100644 --- a/nixos/services/power-guard/power-guard.py +++ b/nixos/services/power-guard/power-guard.py @@ -31,6 +31,7 @@ import os import subprocess import sys +import threading import time SYSFS = os.environ.get("POWER_GUARD_SYSFS", "/sys/class/power_supply") @@ -93,6 +94,10 @@ def timing_from_env(name, default): EDGE_CONFIRM = timing_from_env("POWER_GUARD_EDGE_CONFIRM", "60") NO_INHIBIT = os.environ.get("POWER_GUARD_NO_INHIBIT") == "1" SLEEP_CMD = os.environ.get("POWER_GUARD_SLEEP_CMD", "systemctl hybrid-sleep") +# #8183: how long release() may wait inline for a terminated child +# before the reap moves to a background thread. The full reap used +# to block the sampling loop for up to ~10s (wait 5s, kill, wait 5s). +REAP_GRACE = 0.5 def log(msg): @@ -149,10 +154,66 @@ def sample(): class Inhibitor: def __init__(self): self.proc = None + # #8183: in-flight background reap, {"proc", "event", "rc"}. + self._pending = None + + def _reap(self, proc, timeout=5): + """Wait for a child to exit so it does not remain a zombie. + + The child is already dead or has just been terminated; wait() + returns immediately in the common case. On timeout, escalate + to kill() so a wedged child cannot accumulate. + """ + try: + return proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + try: + proc.kill() + except Exception: + pass + try: + return proc.wait(timeout=timeout) + except Exception: + return proc.poll() + except Exception: + try: + return proc.poll() + except Exception: + return None + + def _dead_exit_code(self): + """Return the exit code if the real child is dead, else None. + + Never raises: a poll failure is treated as unknown, not alive, + so the caller reaps and re-engages loudly rather than + believing a lock it cannot verify. + """ + proc = self.proc + if proc is None or proc == "stub": + return None + try: + return proc.poll() + except Exception as exc: + log(f"INHIBIT child poll failed ({exc!r}); treating as dead") + return -1 def engage(self): + if self._pending is not None: + if not self._pending["event"].is_set(): + # A previous release is still reaping; the old child + # may still hold the lock, so do not stack a second + # inhibitor on top of it (#8183). + return + self._pending = None if self.proc is not None: - return + if self.proc == "stub": + return + rc = self._dead_exit_code() + if rc is None: + return + log(f"INHIBIT child died (exit={rc}); re-engaging") + self._reap(self.proc) + self.proc = None if NO_INHIBIT: log("INHIBIT(block sleep) [stubbed]") self.proc = "stub" @@ -168,27 +229,128 @@ def engage(self): "infinity", ], stdout=subprocess.DEVNULL, + # stderr is deliberately discarded (the child is `sleep + # infinity`, which is silent on success); the exit status + # is logged loudly on death in engage()/release() so the + # failure stays diagnosable from the journal. stderr=subprocess.DEVNULL, ) log("INHIBIT(block sleep) engaged") def release(self): + """Begin releasing the inhibitor; return True once settled. + + #8183: reaping a stalled child used to block the caller for + the full wait/kill/wait sequence (~10s) inside the sampling + loop. A live child now gets a short grace wait (REAP_GRACE) + inline; if it has not exited by then, the kill-escalation + reap finishes on a background thread while sampling + continues. "Settled" means the child was reaped, or the + escalation was exhausted and logged loudly as UNCONFIRMED -- + the release is never silently believed. The confirmed-sleep + path in main() waits for settled before issuing sleep. + """ if self.proc is None: - return - if self.proc != "stub": - self.proc.terminate() + return self.reap_settled() + if self.proc == "stub": + self.proc = None + log("INHIBIT released") + return True + proc = self.proc self.proc = None - log("INHIBIT released") + rc = None + try: + rc = proc.poll() + except Exception: + rc = None + if rc is not None: + self._reap(proc) + log(f"INHIBIT child already dead (exit={rc}); reaped") + log("INHIBIT released") + return True + try: + proc.terminate() + except Exception as exc: + log(f"INHIBIT terminate failed ({exc!r}); killing") + try: + proc.kill() + except Exception: + pass + try: + rc = proc.wait(timeout=REAP_GRACE) + log(f"INHIBIT released (child exit={rc})") + return True + except Exception: + pass + pending = {"proc": proc, "event": threading.Event(), "rc": None} + self._pending = pending + threading.Thread( + target=self._finish_reap, args=(pending,), daemon=True + ).start() + log( + "INHIBIT release pending: stalled child reap moved off " + "the sampling loop (#8183)" + ) + return False + + def _finish_reap(self, pending): + """Background reap: preserve the kill escalation + bounded wait.""" + proc = pending["proc"] + try: + proc.kill() + except Exception: + pass + rc = None + try: + rc = proc.wait(timeout=5) + except Exception: + try: + rc = proc.poll() + except Exception: + rc = None + pending["rc"] = rc + if rc is None: + log( + "INHIBIT release UNCONFIRMED: child still running " + "after kill escalation; not believed released (#8183)" + ) + else: + log(f"INHIBIT released (child exit={rc}, reaped in background)") + pending["event"].set() + + def reap_settled(self): + """True when no background reap is still in flight.""" + return self._pending is None or self._pending["event"].is_set() + + def poll_reap(self): + """Clear a finished background reap; called once per sample.""" + if self._pending is not None and self._pending["event"].is_set(): + self._pending = None @property def held(self): - return self.proc is not None + if self._pending is not None and not self._pending["event"].is_set(): + # Reap in flight: the child may still hold the lock. + try: + if self._pending["proc"].poll() is None: + return True + except Exception: + return True + if self.proc is None: + return False + if self.proc == "stub": + return True + try: + return self.proc.poll() is None + except Exception: + return False def main(): inh = Inhibitor() critical_since = None edge_since = None + sleep_pending = None log( f"started: poll={POLL}s low={LOW_PCT}% crit={CRITICAL_PCT}% " f"edge={EDGE_PCT}% confirm={CONFIRM}s edge_confirm={EDGE_CONFIRM}s " @@ -196,6 +358,7 @@ def main(): ) while True: on_ac, cap, status, tte = sample() + inh.poll_reap() now = time.monotonic() discharging = (not on_ac) and status == "Discharging" and cap is not None low = discharging and (cap <= LOW_PCT or (tte is not None and tte <= 900)) @@ -205,14 +368,26 @@ def main(): edge = discharging and cap <= EDGE_PCT if not low: - if inh.held: + # Log recovery whenever a child handle exists, not only + # while held: a child that died since the last sample + # reads held=False, but the recovery (and the release + # below, which reaps it) still happened and belongs in + # the journal with the battery readings (PR #8025 + # review, thread 4511572453). + if inh.held or inh.proc is not None: log( f"recovered (ac={on_ac} cap={cap} status={status} tte={tte}); releasing" ) inh.release() critical_since = edge_since = None + sleep_pending = None else: - inh.engage() + if sleep_pending is None: + inh.engage() + # While a sleep is pending on the inhibitor release + # settling, engaging would stack a fresh block lock + # directly in front of the sleep command once the reap + # settles (PR #8025 re-review, thread 4511572429). critical_since = critical_since if critical else None if critical and critical_since is None: critical_since = now @@ -226,12 +401,20 @@ def main(): fire = f"edge sustained {now - edge_since:.0f}s at cap={cap}" elif critical_since is not None and now - critical_since >= CONFIRM: fire = f"critical sustained {now - critical_since:.0f}s at cap={cap} tte={tte}" - if fire: - log(f"CONFIRMED: {fire}; releasing inhibitor and sleeping") + if fire and sleep_pending is None: + # #8183: start the release, but do not issue the + # sleep command until the release has settled -- a + # stalled reap no longer blocks this loop, and the + # samples above keep running while it drains. + log(f"CONFIRMED: {fire}; releasing inhibitor before sleep") + sleep_pending = fire inh.release() + if sleep_pending is not None and inh.reap_settled(): + log(f"CONFIRMED: {sleep_pending}; inhibitor release settled; sleeping") subprocess.run(SLEEP_CMD, shell=True) log("sleep command issued; cooling down") critical_since = edge_since = None + sleep_pending = None time.sleep(120) time.sleep(POLL) diff --git a/nixos/services/power-guard/test_power_guard.py b/nixos/services/power-guard/test_power_guard.py index 752bade4f..fe10f3073 100644 --- a/nixos/services/power-guard/test_power_guard.py +++ b/nixos/services/power-guard/test_power_guard.py @@ -21,8 +21,10 @@ import subprocess import sys import tempfile +import threading import time import unittest +import unittest.mock from pathlib import Path HERE = Path(__file__).resolve().parent @@ -246,5 +248,191 @@ def test_valid_small_confirm_still_fires_after_sustained_critical(self): self.assertTrue(self.marker.exists(), "sustained critical state never fired") +class FakeProc: + """Minimal Popen stand-in for Inhibitor unit tests (#6534).""" + + def __init__(self, poll_result=None): + self._poll_result = poll_result + self.terminated = False + self.killed = False + self.waited = 0 + self.wait_return = poll_result + + def poll(self): + return self._poll_result + + def wait(self, timeout=None): + self.waited += 1 + return self.wait_return + + def terminate(self): + self.terminated = True + # Simulate a clean exit after terminate for the live path. + if self._poll_result is None: + self._poll_result = -15 + self.wait_return = -15 + + def kill(self): + self.killed = True + + +class InhibitorDeadChildTests(unittest.TestCase): + """Oracle: issue #6534 acceptance — dead child detected/handled, + live child undisturbed, NO_INHIBIT stub unchanged, release reaps.""" + + def setUp(self): + self.logs = [] + self._orig_log = pg.log + pg.log = self.logs.append + self.addCleanup(setattr, pg, "log", self._orig_log) + + def test_dead_child_is_detected_and_reengaged_with_exit_logged(self): + # Repro from the issue: stub systemd-inhibit exits 1 at once. + dead = FakeProc(poll_result=1) + live = FakeProc(poll_result=None) + inh = pg.Inhibitor() + inh.proc = dead + # held must reflect poll(), not handle non-None. + self.assertFalse(inh.held) + with unittest.mock.patch.object( + pg.subprocess, "Popen", return_value=live + ) as popen: + inh.engage() + popen.assert_called_once() + self.assertIs(inh.proc, live) + self.assertTrue(inh.held) + self.assertGreaterEqual(dead.waited, 1, "dead child was not reaped") + self.assertTrue( + any("exit=1" in m for m in self.logs), + f"exit status not logged loudly: {self.logs}", + ) + + def test_live_child_is_not_disturbed(self): + live = FakeProc(poll_result=None) + inh = pg.Inhibitor() + inh.proc = live + self.assertTrue(inh.held) + with unittest.mock.patch.object(pg.subprocess, "Popen") as popen: + inh.engage() + popen.assert_not_called() + self.assertIs(inh.proc, live) + self.assertEqual(live.waited, 0) + + def test_stub_path_unchanged(self): + orig = pg.NO_INHIBIT + pg.NO_INHIBIT = True + try: + inh = pg.Inhibitor() + inh.engage() + self.assertEqual(inh.proc, "stub") + self.assertTrue(inh.held) + inh.engage() + self.assertEqual(inh.proc, "stub") + inh.release() + self.assertIsNone(inh.proc) + self.assertFalse(inh.held) + finally: + pg.NO_INHIBIT = orig + + def test_release_reaps_live_child(self): + live = FakeProc(poll_result=None) + inh = pg.Inhibitor() + inh.proc = live + inh.release() + self.assertIsNone(inh.proc) + self.assertFalse(inh.held) + self.assertTrue(live.terminated) + self.assertGreaterEqual(live.waited, 1) + + def test_release_reaps_already_dead_child(self): + dead = FakeProc(poll_result=3) + inh = pg.Inhibitor() + inh.proc = dead + inh.release() + self.assertIsNone(inh.proc) + self.assertFalse(dead.terminated, "terminate() must not run on a dead child") + self.assertGreaterEqual(dead.waited, 1) + self.assertTrue( + any("exit=3" in m for m in self.logs), + f"dead-child exit not logged on release: {self.logs}", + ) + + +class FakeStalledProc: + """Child that ignores terminate and kill (#8183 regression). + + wait() raises TimeoutExpired on the caller's grace wait, then + blocks inside the background reap until the test unblocks it, + then raises TimeoutExpired again (the kill did not work either). + """ + + def __init__(self): + self.terminated = False + self.killed = False + self.wait_calls = 0 + self.unblock = threading.Event() + + def poll(self): + return None + + def terminate(self): + self.terminated = True + + def kill(self): + self.killed = True + + def wait(self, timeout=None): + self.wait_calls += 1 + if self.wait_calls > 1: + self.unblock.wait(timeout=10) + raise subprocess.TimeoutExpired(cmd="fake-inhibit", timeout=timeout) + + +class InhibitorNonBlockingReapTests(unittest.TestCase): + """Oracle: issue #8183 acceptance -- a stalled reap must not block + the sampling loop for the full double-wait, the timeout/kill + safeguards are preserved, and the lock is not believed released + while the child is still running.""" + + def setUp(self): + self.logs = [] + self._orig_log = pg.log + pg.log = self.logs.append + self.addCleanup(setattr, pg, "log", self._orig_log) + + def test_stalled_child_reap_moves_off_the_calling_loop(self): + proc = FakeStalledProc() + inh = pg.Inhibitor() + inh.proc = proc + start = time.monotonic() + settled = inh.release() + elapsed = time.monotonic() - start + self.assertFalse(settled, "stalled reap reported settled synchronously") + self.assertLess( + elapsed, 2.0, "release() blocked on the stalled child (old path: ~10s)" + ) + self.assertTrue(proc.terminated) + self.assertIsNone(inh.proc) + self.assertFalse(inh.reap_settled(), "sleep could fire before release settles") + self.assertTrue(inh.held, "lock believed released while child still runs") + # Sampling continues while the reap is pending; once the + # background escalation finishes, the release settles, the + # kill safeguard has run, and the unconfirmed exit is loud. + proc.unblock.set() + deadline = time.time() + 5 + while not inh.reap_settled() and time.time() < deadline: + inh.poll_reap() + time.sleep(0.01) + self.assertTrue(inh.reap_settled()) + self.assertTrue(proc.killed, "kill escalation was not preserved") + self.assertGreaterEqual(proc.wait_calls, 2) + inh.poll_reap() + self.assertFalse(inh.held) + self.assertTrue( + any("UNCONFIRMED" in m for m in self.logs), + f"unconfirmed release not logged loudly: {self.logs}", + ) + + if __name__ == "__main__": unittest.main()