Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 99 additions & 7 deletions nixos/services/power-guard/power-guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -149,6 +154,8 @@ 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.
Expand Down Expand Up @@ -191,6 +198,13 @@ def _dead_exit_code(self):
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:
if self.proc == "stub":
return
Expand Down Expand Up @@ -224,12 +238,24 @@ def engage(self):
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
return self.reap_settled()
if self.proc == "stub":
self.proc = None
log("INHIBIT released")
return
return True
proc = self.proc
self.proc = None
rc = None
Expand All @@ -241,7 +267,7 @@ def release(self):
self._reap(proc)
log(f"INHIBIT child already dead (exit={rc}); reaped")
log("INHIBIT released")
return
return True
try:
proc.terminate()
except Exception as exc:
Expand All @@ -250,11 +276,66 @@ def release(self):
proc.kill()
except Exception:
pass
rc = self._reap(proc)
log(f"INHIBIT released (child exit={rc})")
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):
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":
Expand All @@ -269,13 +350,15 @@ 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 "
f"sysfs={SYSFS} no_inhibit={NO_INHIBIT}"
)
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))
Expand All @@ -291,6 +374,7 @@ def main():
)
inh.release()
critical_since = edge_since = None
sleep_pending = None
else:
inh.engage()
critical_since = critical_since if critical else None
Expand All @@ -306,12 +390,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)

Expand Down
77 changes: 77 additions & 0 deletions nixos/services/power-guard/test_power_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import subprocess
import sys
import tempfile
import threading
import time
import unittest
import unittest.mock
Expand Down Expand Up @@ -357,5 +358,81 @@ def test_release_reaps_already_dead_child(self):
)


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()
Loading