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

+161
View File
@@ -0,0 +1,161 @@
"""Starting and stopping the hardware service's parts: settings, the hardware loop, RAM lighting
and the pipe.
python -m kurgan.hw in a console (elevated), Ctrl+C to stop: for debugging, with the
real service stopped (only one copy runs)
As a Windows service it is started through hw_service.py (see kurgan/hw/winservice.py).
"""
from __future__ import annotations
import argparse
import ctypes
import logging
import logging.handlers
import os
import sys
import threading
import winreg
from kurgan import __version__, paths
log = logging.getLogger("kurgan.hw")
SERVICE_NAME = "KurganHw"
SERVICE_DISPLAY_NAME = "The Kurgan hardware"
PARAMETERS_KEY = rf"SYSTEM\CurrentControlSet\Services\{SERVICE_NAME}\Parameters"
INSTANCE_MUTEX = "Global\\KurganHw"
STOP_SECONDS = 30.0 # how long a stop may take: the loop's last pass plus handing the fans back
def setup_logging(console: bool, verbose: bool = False) -> None:
from kurgan.hw.settings import ensure_data_dir
ensure_data_dir()
handlers: list[logging.Handler] = [logging.handlers.RotatingFileHandler(
paths.HW_LOG_PATH, maxBytes=1_000_000, backupCount=3, encoding="utf-8")]
if console and sys.stderr is not None:
handlers.append(logging.StreamHandler())
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers, force=True,
format="%(asctime)s %(levelname)s %(threadName)s %(name)s: %(message)s")
def configured_user_sid() -> str | None:
"""The installing user's SID, from the service's Parameters key (written by setup.ps1)."""
from kurgan.hw.pipe import valid_sid
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, PARAMETERS_KEY) as key:
value, kind = winreg.QueryValueEx(key, "UserSid")
except OSError:
return None
if kind != winreg.REG_SZ or not valid_sid(value):
log.error("Ignoring the invalid UserSid %r in HKLM\\%s", value, PARAMETERS_KEY)
return None
return value
def user_appdata(sid: str | None) -> str | None:
"""That user's roaming AppData folder, from their profile's registry entry."""
if sid is None:
return None
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
rf"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}") as key:
profile = os.path.expandvars(winreg.QueryValueEx(key, "ProfileImagePath")[0])
except OSError:
return None
return os.path.join(profile, "AppData", "Roaming")
def single_instance():
"""A handle that keeps a second copy out, or None if one is already running."""
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateMutexW.restype = ctypes.c_void_p
k32.CloseHandle.argtypes = [ctypes.c_void_p]
handle = k32.CreateMutexW(None, False, INSTANCE_MUTEX)
if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED
if handle:
k32.CloseHandle(handle)
return None
return handle
def load_settings():
"""(settings, None), or (None, why) when hw-settings.json can't be used."""
from kurgan.hw import settings as hw_settings
from kurgan.settings import SettingsError
try:
return hw_settings.load(), None
except (OSError, SettingsError) as e:
log.error("hw-settings.json can't be used; holding every case fan at 100%%: %s", e)
return None, str(e)
def serve(stop: threading.Event, user_sid: str | None, *, service=None, pipe_name: str | None = None) -> None:
"""Run until `stop` is set. The fans are controlled whatever happens to the pipe."""
from kurgan.hw.pipe import PipeServer, pipe_sddl
from kurgan.hw.protocol import PIPE_NAME, Session
from kurgan.telemetry import sensors
if service is None:
from kurgan.hw.service import HardwareService
sensors.USER_APPDATA = user_appdata(user_sid)
service = HardwareService(*load_settings())
if user_sid is None:
log.warning("No user is configured for the pipe (HKLM\\%s UserSid); only SYSTEM and Administrators "
"can connect. Run setup.ps1 again.", PARAMETERS_KEY)
loop = threading.Thread(target=service.run, args=(stop,), name="hw-loop")
loop.start()
lighting = service.start_lighting(stop)
server = None
try:
server = PipeServer(pipe_name or PIPE_NAME, pipe_sddl(user_sid),
lambda: Session(service.dispatch, __version__))
server.start()
log.info("Listening on %s for %s", pipe_name or PIPE_NAME, user_sid or "SYSTEM and Administrators only")
except Exception:
log.exception("The pipe is unavailable; fan control carries on without it")
try:
while loop.is_alive() and not stop.wait(1.0):
pass
finally:
stop.set()
loop.join(STOP_SECONDS)
if server is not None:
server.close()
lighting.join(10)
if loop.is_alive():
log.error("The hardware loop didn't stop within %.0f s", STOP_SECONDS)
def main(argv: list[str] | None = None) -> int:
from kurgan.hw.pipe import current_user_sid, valid_sid
ap = argparse.ArgumentParser(prog="python -m kurgan.hw", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--user-sid", help="the user allowed on the pipe (default: the configured one, else you)")
ap.add_argument("-v", "--verbose", action="store_true")
args = ap.parse_args(argv)
setup_logging(console=True, verbose=args.verbose)
if args.user_sid is not None and not valid_sid(args.user_sid):
ap.error(f"not a SID: {args.user_sid}")
mutex = single_instance()
if mutex is None:
log.error("The hardware service is already running (Stop-Service %s first)", SERVICE_NAME)
return 1
log.info("Starting %s %s in a console (pid %s)", SERVICE_DISPLAY_NAME, __version__, os.getpid())
stop = threading.Event()
worker = threading.Thread(target=serve, args=(stop, args.user_sid or configured_user_sid() or current_user_sid()),
name="hw-serve")
worker.start()
try:
while worker.is_alive():
worker.join(0.5)
except KeyboardInterrupt:
log.info("Stopping")
stop.set()
worker.join(STOP_SECONDS + 15)
return 0