Privilege split 4/11: the kurgan.hw service process

- kurgan/hw/service.py, HardwareService: one loop a second reads the CPU
  package (PawnIO MSR: temperature and power) and the GPU (NVML), runs the
  fan curves, and publishes a state snapshot. It never depends on a client:
  the pipe side takes no lock the loop needs, every sensor read is guarded
  (a fault is a missing temperature, so those fans fail safe), and a bug in
  the loop fails the fans safe and retries. On exit the case fans are left at
  100% and the top fans go back to the BIOS curve.
- Without saved ports it only reads the Commander PRO's RPMs (for the app's
  power estimate). With an invalid hw-settings.json it holds every connected
  PWM fan at 100% (CommanderPro.full_speed) and says why in its state,
  instead of refusing to start and leaving the fans at their last duty.
- State carries the app's cooling snapshot unchanged (profile, groups, top,
  note, row) plus the CPU temperature and power, GPU temperature, the
  Commander PRO RPMs and the RAM lighting. NaN never reaches the pipe.
- RAM lighting runs in the service; its chase follows the app's clock
  (SyncedChase, fed by ram_chase) so it stays in step with the other chases.
- kurgan/hw/settings.py: %ProgramData%\Kurgan\hw-settings.json, the cooling
  and RAM lighting sections, as strict as settings.json (validate_cooling is
  shared). The folder is created SYSTEM/Administrators full, Users read.
- kurgan/hw/main.py: serve() wires the loop, the RAM lighting and the pipe
  (the fans run whatever happens to the pipe); `python -m kurgan.hw` runs it
  in a console. The pipe user comes from HKLM\...\Services\KurganHw\
  Parameters\UserSid; the OpenRGB check reads that user's %APPDATA%.
- control.py: CaseFanControl.step() (one guarded pass) and shutdown()
  replace run(); CpuTemperature also keeps the latest reading, the package
  power and why it has none. The fan CLI saves to hw-settings.json.
- sensors.py: the Commander PRO mutex is Global\KurganCommanderPro, so a
  console tool in the user's session sees the service's claim.
- The app still uses the old worker; it is rewired in step 6.
- Tests: 16 new or rewritten (202 pass), including the loop with no client
  and a stuck client that can't stop fan control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 19:28:32 +13:00
1 parent 73a424f6a8
commit 7190db733f
11 files changed
+971 -119

No files matched your search

+60 -54
View File
@@ -9,13 +9,12 @@ import argparse
import collections
import logging
import math
import threading
import time
from kurgan.cooling.board_fans import Nct6687, parse_channels
from kurgan.cooling.profiles import BALANCED, FanProfile
from kurgan.hardware.hid import HidError
from kurgan.telemetry.sensors import CommanderPro, GpuSensors, IntelPackage
from kurgan.telemetry.sensors import CommanderPro, IntelPackage
log = logging.getLogger(__name__)
# The Balanced profile's curves (the original ones); the active profile can replace them at runtime.
@@ -292,7 +291,10 @@ class CaseFanGroup:
class CpuTemperature:
"""CPU package temperature averaged over CPU_AVERAGE readings; None while unavailable."""
"""CPU package temperature, averaged over CPU_AVERAGE readings for the fans, and package power.
read() returns the average (None while unavailable); `temp` and `power` hold the latest
readings and `error` why there are none."""
RETRY_SECONDS = 15.0 # pause after a read failure, so a lost PawnIO device is not re-opened every poll
@@ -301,6 +303,9 @@ class CpuTemperature:
self.pkg: IntelPackage | None = None
self._retry_at = 0.0
self._recent: collections.deque[float] = collections.deque(maxlen=CPU_AVERAGE)
self.temp: float | None = None
self.power: float | None = None
self.error: str | None = "not read yet"
def read(self, now: float) -> float | None:
if self.pkg is None and now >= self._retry_at:
@@ -308,15 +313,20 @@ class CpuTemperature:
self.pkg = self._factory()
except Exception as e: # PawnIO missing, not admin, ...
log.warning("CPU temperature unavailable for fan control: %s", e)
self.error = str(e)
self._retry_at = now + 60
temp = None
temp = power = None
if self.pkg is not None:
try:
temp = self.pkg.temperature()
power = self.pkg.power()
self.error = None if temp is not None else "the package sensor reported no reading"
except OSError as e:
log.warning("CPU temperature read failed, will retry: %s", e)
self.error = str(e)
self.close()
self._retry_at = now + self.RETRY_SECONDS
self.temp, self.power = temp, power
if temp is None:
self._recent.clear()
return None
@@ -336,11 +346,12 @@ class CaseFanControl:
def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...],
cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None,
profile: FanProfile = BALANCED, sensors=None):
"""sensors: (GPU sensor factory, CPU temperature factory), for tests and --demo."""
profile: FanProfile = BALANCED):
"""Driven by the hardware service's loop (kurgan.hw.service): step() once a second with
fresh temperatures, shutdown() when it ends."""
self.commander = commander
self.profile = profile
self._sensors = sensors or (lambda: GpuSensors(load_source="nvml"), CpuTemperature)
self._reported: float | None = None # when the last unexpected error was logged
self.gpu = CaseFanGroup("GPU", profile.gpu_curve, commander, gpu_ports)
self.cpu = CaseFanGroup("CPU", profile.cpu_curve, commander, cpu_ports) if cpu_ports else None
if self.cpu is not None and set(self.cpu.ports) & set(self.gpu.ports):
@@ -385,50 +396,41 @@ class CaseFanControl:
for g in self.groups:
g.set_status(text, warning=True)
def run(self, stop: threading.Event) -> None:
gpu_factory, cpu_factory = self._sensors
cpu_temp = cpu_factory() if self.cpu is not None else None
gpu = None
reported: float | None = None # when the last unexpected error was logged
def _failsafe_top(self) -> None:
if self.top is not None:
try: # update() never raises for the board, but a bug must not stop the case fans' fail-safe
self.top.update(100, None, time.monotonic())
except Exception:
log.debug("Top fans: failsafe update failed", exc_info=True)
def step(self, gpu_temp: float | None, cpu_temp: float | None, now: float) -> float:
"""One control pass; never raises. Returns the seconds to wait before the next one.
A device error closes the Commander PRO (reopened on the next pass) and fails every fan
safe. So does any other error, a bug included: fan control must not end for the life of
the service. Those are logged at most once a minute."""
try:
while not stop.is_set():
now = time.monotonic()
retry_in = 1.0
try:
if gpu is None:
gpu = gpu_factory()
self.update(gpu.read().temp, now, cpu_temp.read(now) if cpu_temp else None)
except (OSError, HidError) as e:
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
self.commander.close()
if self.top is not None:
self.top.update(100, None, time.monotonic())
retry_in = self.ERROR_RETRY_SECONDS
except Exception as e:
# A sensor or control bug must not end fan control for the life of the
# process: fail safe, log at most once a minute, and retry with a freshly
# built sensor object.
if reported is None or now - reported >= 60:
reported = now
log.exception("Case fan control error; failing safe and retrying")
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
if self.top is not None:
try: # as the device-error path does; update() never raises for the board
self.top.update(100, None, time.monotonic())
except Exception:
log.debug("Top fans: failsafe update failed", exc_info=True)
gpu = None
retry_in = self.ERROR_RETRY_SECONDS
stop.wait(retry_in)
finally:
self.update(gpu_temp, now, cpu_temp)
return 1.0
except (OSError, HidError) as e:
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
self.commander.close()
if self.top is not None:
self.top.release()
if cpu_temp is not None:
cpu_temp.close()
except Exception as e:
if self._reported is None or now - self._reported >= 60:
self._reported = now
log.exception("Case fan control error; failing safe and retrying")
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
self._failsafe_top()
return self.ERROR_RETRY_SECONDS
def shutdown(self) -> None:
"""Leave the case fans at 100% and hand the top fans back to the BIOS curve."""
self.failsafe()
self.commander.close()
if self.top is not None:
self.top.release()
def main() -> int:
@@ -437,7 +439,7 @@ def main() -> int:
action.add_argument("--identify", type=parse_ports, metavar="1,2,3",
help="raise these three ports to 100%% to identify their physical side")
action.add_argument("--save-ports", type=parse_ports, metavar="4,5,6",
help="save identified GPU-side ports for dashboard startup")
help="save identified GPU-side ports (hw-settings.json; run elevated)")
action.add_argument("--save-cpu-ports", type=parse_ports, metavar="1,2,3",
help="save identified CPU-side ports (follow CPU temperature)")
action.add_argument("--save-top-channels", type=parse_channels, metavar="2,5",
@@ -445,10 +447,12 @@ def main() -> int:
args = ap.parse_args()
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
if args.save_ports or args.save_cpu_ports or args.save_top_channels:
from kurgan.settings import Settings, SettingsError
from kurgan.hw import settings as hw_settings
from kurgan.settings import SettingsError
try:
settings = Settings()
try: # the hardware service's file: only an elevated prompt can write it
hw_settings.ensure_data_dir()
settings = hw_settings.load()
if args.save_ports:
settings.update("cooling", gpu_ports=list(args.save_ports))
elif args.save_cpu_ports:
@@ -458,7 +462,8 @@ def main() -> int:
except (OSError, SettingsError):
log.exception("Cannot save fan configuration")
return 1
print(f"Saved {settings.section('cooling')} to {settings.path}. Restart The Kurgan to apply it.")
print(f"Saved {settings.section('cooling')} to {settings.path}.")
print("Restart the hardware service to apply it (elevated): Restart-Service KurganHw")
return 0
commander = CommanderPro()
try:
@@ -469,7 +474,8 @@ def main() -> int:
print("RPMs: " + ", ".join(f"{p}: {rpm}" for p, rpm in rpms.items()))
return 0
except (OSError, HidError) as e:
log.error("Identification failed: %s", e)
log.error("Identification failed: %s%s", e, " (stop the hardware service first, elevated: "
"Stop-Service KurganHw)" if "in use" in str(e) else "")
return 1
finally:
commander.close()