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

+7
View File
@@ -0,0 +1,7 @@
"""python -m kurgan.hw: the hardware service in a console (see kurgan/hw/main.py)."""
import sys
from kurgan.hw.main import main
sys.exit(main())
+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
+306
View File
@@ -0,0 +1,306 @@
"""The hardware service's work: fan control on its own temperature readings, RAM lighting, and
the state snapshot the app reads over the pipe.
One loop, once a second (HardwareService.run):
read the CPU package (PawnIO MSR: temperature and power) and the GPU (NVML: temperature)
run the fan curves (CaseFanControl.step), or, while the port mapping isn't saved, only read
the Commander PRO's RPMs, or, while hw-settings.json is invalid, hold every fan at 100%
publish a snapshot for the pipe
Nothing on the pipe side takes a lock the loop needs, and every read the loop makes is guarded,
so neither a client nor a sensor fault can stop it. When it ends, the case fans are left at 100%
and the top fans go back to the BIOS curve, as The Kurgan always did on exit.
"""
from __future__ import annotations
import logging
import math
import os
import threading
import time
from kurgan import __version__
from kurgan.cooling.board_fans import Nct6687
from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve
from kurgan.cooling.profiles import PROFILES
from kurgan.hw.protocol import PROTOCOL_VERSION, Unavailable
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP
log = logging.getLogger(__name__)
ERROR_RETRY_SECONDS = 5.0
LOG_EVERY = 60.0 # seconds between repeats of the same failure in the log
def _clean(value):
"""JSON-safe copy: NaN and infinities become None (the protocol refuses them)."""
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, dict):
return {str(k): _clean(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_clean(v) for v in value]
return value
class SyncedChase:
"""The RAM chase's clock in the service, a stand-in for the app's ChaseTiming.
The app sends its clock (phase, rate) about once a second (ram_chase); in between, and when
the app is gone, the phase runs on at the last rate. Both processes read time.monotonic(),
which on Windows is the system-wide performance counter, so no offset needs translating."""
IDLE_RATE = 1 / 0.15 # LEDs per second: the app's default idle pace (--rgb-chase-step-ms 150)
def __init__(self):
self._lock = threading.Lock()
self.phase = float(SIDE_CHASE_BOTTOM_STEP)
self.rate = self.IDLE_RATE
self.last_time: float | None = None
def sync(self, phase: float, rate: float, now: float) -> None:
with self._lock:
self.phase, self.rate, self.last_time = phase, rate, now
def reset(self, phase: float = 0.0) -> None:
with self._lock:
self.phase, self.last_time = phase, None
def set_power(self, total_watts: float | None) -> None:
pass # the pace comes with the phase
def rate_for(self, total_watts: float | None) -> float:
return self.rate
def sample(self, now: float) -> tuple[float, float]:
with self._lock:
if self.last_time is None:
self.last_time = now
self.phase += self.rate * max(0.0, now - self.last_time)
self.last_time = max(now, self.last_time)
return self.phase, self.rate
class HardwareService:
def __init__(self, settings, settings_error: str | None = None, *, commander=None,
board_factory=Nct6687, gpu_factory=None, cpu=None, memory=None):
"""settings: kurgan.hw.settings.load(), or None when hw-settings.json is invalid
(settings_error says why). The rest replace the real hardware in tests and --demo."""
from kurgan.telemetry.sensors import CommanderPro, GpuSensors
self.started = time.time()
self.settings = settings
self.settings_error = settings_error
self.commander = commander if commander is not None else CommanderPro()
self.cpu = cpu if cpu is not None else CpuTemperature()
self._gpu_factory = gpu_factory or (lambda: GpuSensors(load_source="nvml"))
self._gpu = None
self.gpu_temp: float | None = None
self.gpu_error: str | None = "not read yet"
self.chase = SyncedChase()
if memory is None:
from kurgan.lighting.memory import MemoryLighting
from kurgan.theme import Theme
memory = MemoryLighting(Theme(), chase_timing=self.chase)
self.memory = memory
self._memory_events = {"temperature": threading.Event(), "chase": threading.Event()}
self._memory_mode = "off"
self._lock = threading.Lock() # settings changes (pipe threads); the loop never takes it
self._failures: dict[str, float] = {} # what -> when it was last logged
self._rpms: list[int] = []
self._seq = 0
self.fans: CaseFanControl | None = None
self.note: str | None = None
# Kept here so neither the loop nor `state` ever waits on the settings file's lock.
self._profile: str | None = None if settings is None else settings.get("cooling", "profile")
if settings is None:
self.note = (f"hw-settings.json is invalid, so every case fan is held at 100%: {settings_error}. "
"Fix the file, then restart the hardware service.")
else:
cooling = settings.section("cooling")
if cooling.get("gpu_ports"):
top = None
if cooling.get("top_channels"):
top = TopFanCurve(tuple(cooling["top_channels"]), board_factory=board_factory)
self.fans = CaseFanControl(self.commander, tuple(cooling["gpu_ports"]),
tuple(cooling.get("cpu_ports") or ()) or None, top,
profile=PROFILES[cooling["profile"]])
self.commander.controlled = True
else:
self.note = "Fan control isn't set up: save the Commander PRO ports first (see README)."
self._apply_memory(settings.get("lighting", "memory"))
self._snapshot = self._build(time.time())
# -- the loop
def _logged(self, what: str, now: float) -> bool:
"""True when a failure of `what` should be logged now (at most once a LOG_EVERY)."""
last = self._failures.get(what)
if last is None or now - last >= LOG_EVERY:
self._failures[what] = now
return True
return False
def _read_gpu(self, now: float) -> float | None:
try:
if self._gpu is None:
self._gpu = self._gpu_factory()
temp = self._gpu.read().temp
self.gpu_error = None if temp is not None else "no GPU temperature (driver unavailable?)"
return temp
except Exception as e: # rebuilt on the next pass
if self._logged("gpu", now):
log.warning("GPU temperature read failed; the GPU-side fans fail safe: %s", e, exc_info=True)
self.gpu_error = f"{type(e).__name__}: {e}"
self._gpu = None
return None
def _read_cpu(self, now: float) -> float | None:
try:
return self.cpu.read(now)
except Exception as e:
if self._logged("cpu", now):
log.warning("CPU temperature read failed; the CPU-side fans fail safe: %s", e, exc_info=True)
self.cpu.temp = self.cpu.power = None
self.cpu.error = f"{type(e).__name__}: {e}"
return None
def _full_speed(self, now: float) -> float:
try:
self._rpms = sorted(self.commander.full_speed().values())
return 1.0
except Exception as e:
if self._logged("full-speed", now):
log.error("Can't hold the case fans at 100%%: %s", e)
self.commander.close()
self._rpms = []
return ERROR_RETRY_SECONDS
def tick(self, now: float) -> float:
"""One pass of the loop; never raises. Returns the seconds until the next."""
delay = 1.0
try:
self.gpu_temp = self._read_gpu(now)
cpu_average = self._read_cpu(now)
if self.fans is not None:
delay = self.fans.step(self.gpu_temp, cpu_average, now)
self._rpms = self.commander.read()
elif self.settings is None:
delay = self._full_speed(now)
else:
self._rpms = self.commander.read() # read-only, for the app's power estimate
self.memory.set_temperature(self.cpu.temp, self.gpu_temp)
except Exception:
if self._logged("loop", now):
log.exception("Hardware loop error; failing safe and retrying")
if self.fans is not None:
self.fans.failsafe()
delay = ERROR_RETRY_SECONDS
try:
self._snapshot = self._build(time.time())
except Exception:
if self._logged("snapshot", now):
log.exception("Can't build the state snapshot")
return delay
def run(self, stop: threading.Event) -> None:
log.info("Hardware loop started (%s)", "fan control on" if self.fans is not None
else "fans held at 100%" if self.settings is None else "fan control not set up")
try:
while not stop.is_set():
stop.wait(self.tick(time.monotonic()))
finally:
if self.fans is not None:
self.fans.shutdown()
else:
self.commander.close()
self.cpu.close()
log.info("Hardware loop stopped; case fans at 100%%, top fans on the BIOS curve")
def start_lighting(self, stop: threading.Event) -> threading.Thread:
e = self._memory_events
thread = threading.Thread(target=self.memory.run, args=(stop, e["temperature"], e["chase"]),
name="memory-lighting", daemon=True)
thread.start()
return thread
# -- state
def _build(self, t: float) -> dict:
fans = self.fans
if fans is not None:
cooling = {**fans.snapshot(), "note": None,
"row": [round(t, 1), fans.gpu.duty, None if fans.cpu is None else fans.cpu.duty,
None if fans.top is None else fans.top.duty]}
else:
cooling = {"profile": self._profile, "groups": [], "top": None, "note": self.note, "row": None}
self._seq += 1
return _clean({
"service": {"version": __version__, "protocol": PROTOCOL_VERSION, "pid": os.getpid(),
"uptime": round(t - self.started), "settings_error": self.settings_error},
"seq": self._seq, "t": round(t, 3),
"cpu": {"temp": self.cpu.temp, "power": self.cpu.power, "error": self.cpu.error},
"gpu": {"temp": self.gpu_temp, "error": self.gpu_error},
"commander": {"rpms": list(self._rpms)},
"cooling": cooling,
"lighting": {"memory": {"mode": self._memory_mode, "status": self.memory.status}},
})
def snapshot(self) -> dict:
"""The latest published state, with the current profile and RAM lighting (a change made
over the pipe shows at once, not at the next pass)."""
state = dict(self._snapshot)
state["cooling"] = {**state["cooling"], "profile": self._profile}
state["lighting"] = {"memory": {"mode": self._memory_mode, "status": self.memory.status}}
return state
# -- operations (from the pipe; arguments already checked by the protocol)
def _apply_memory(self, mode: str) -> None:
for name, event in self._memory_events.items(): # clear the old pattern before setting the new
if name != mode:
event.clear()
if mode != "off":
self._memory_events[mode].set()
self._memory_mode = mode
def _save(self, section: str, **changes) -> None:
if self.settings is None:
raise Unavailable(f"hw-settings.json is invalid ({self.settings_error}); fix it and restart "
"the hardware service")
try:
self.settings.update(section, **changes)
except OSError as e:
raise Unavailable(f"couldn't save hw-settings.json: {e}") from None
def set_profile(self, key: str) -> None:
with self._lock:
self._save("cooling", profile=key)
self._profile = key
if self.fans is not None:
self.fans.apply_profile(PROFILES[key])
log.info("Fan profile set to %s by the app", key)
def set_ram_lighting(self, mode: str) -> None:
with self._lock:
self._save("lighting", memory=mode)
self._apply_memory(mode)
log.info("RAM lighting set to %s by the app", mode)
def dispatch(self, op: str, args: dict):
if op == "state":
return self.snapshot()
if op == "set_profile":
self.set_profile(args["profile"])
return self.snapshot()
if op == "set_ram_lighting":
self.set_ram_lighting(args["mode"])
return self.snapshot()
if op == "ram_chase":
self.chase.sync(args["phase"], args["rate"], time.monotonic())
self.memory.set_power(args["power"])
return None
raise ValueError(f"unknown operation {op!r}")
+89
View File
@@ -0,0 +1,89 @@
"""The hardware service's settings: %ProgramData%\\Kurgan\\hw-settings.json.
{
"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3],
"top_channels": [2, 5]},
"lighting": {"memory": "off"}
}
The cooling section is checked exactly as settings.json's was (kurgan.settings.validate_cooling);
the lighting section holds the RAM zone only, which the service drives. The folder is writable
by SYSTEM and Administrators only, and readable by users: the service writes the file when the
app changes the profile or the RAM lighting, and the port mapping is saved from an elevated
`python -m kurgan.cooling.control --save-ports ...`.
An invalid file doesn't stop the service: it holds every case fan at 100% and says why in its
state, so the app can show it (see kurgan.hw.service).
"""
from __future__ import annotations
import copy
import ctypes
import ctypes.wintypes as wt
import os
from kurgan import paths
from kurgan.cooling.profiles import DEFAULT_PROFILE
from kurgan.settings import LIGHTING_MODES, Settings, SettingsError, validate_cooling
DEFAULTS = {
"cooling": {"profile": DEFAULT_PROFILE},
"lighting": {"memory": "off"},
}
_OPTIONAL = {"cooling": {"gpu_ports", "cpu_ports", "top_channels"}, "lighting": set()}
# The data folder: SYSTEM and Administrators full control, users read, nothing inherited.
DATA_DIR_SDDL = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)"
def validate(data: object) -> dict:
"""A normalised copy with defaults filled in, or SettingsError."""
if not isinstance(data, dict):
raise SettingsError("settings must be a JSON object")
unknown = set(data) - set(DEFAULTS)
if unknown:
raise SettingsError(f"unknown section(s): {', '.join(sorted(unknown))}")
out = copy.deepcopy(DEFAULTS)
for section, values in data.items():
if not isinstance(values, dict):
raise SettingsError(f"{section} must be an object")
bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section]
if bad:
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
out[section].update(values)
validate_cooling(out["cooling"])
if out["lighting"]["memory"] not in LIGHTING_MODES["memory"]:
raise SettingsError(f"lighting.memory must be one of {', '.join(LIGHTING_MODES['memory'])}")
return out
def load(path: str = paths.HW_SETTINGS_PATH) -> Settings:
"""The service's settings (created with the defaults if missing); OSError or SettingsError."""
return Settings(path, legacy_dir=None, validator=validate)
class _SecurityAttributes(ctypes.Structure):
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)]
def ensure_data_dir(path: str = paths.HW_DATA_DIR) -> None:
"""Create the data folder, if missing, with DATA_DIR_SDDL (setup.ps1 also resets it)."""
if os.path.isdir(path):
return
os.makedirs(os.path.dirname(path), exist_ok=True)
adv = ctypes.WinDLL("advapi32", use_last_error=True)
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
descriptor = ctypes.c_void_p()
adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wt.LPCWSTR, wt.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
k32.CreateDirectoryW.argtypes = [wt.LPCWSTR, ctypes.POINTER(_SecurityAttributes)]
k32.LocalFree.argtypes = [ctypes.c_void_p]
if not adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(DATA_DIR_SDDL, 1, ctypes.byref(descriptor), None):
raise ctypes.WinError(ctypes.get_last_error())
try:
attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
if not k32.CreateDirectoryW(path, ctypes.byref(attributes)) and not os.path.isdir(path):
raise ctypes.WinError(ctypes.get_last_error())
finally:
k32.LocalFree(descriptor)