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
+960 -108

No files matched your search

+50 -44
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)
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.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
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()
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._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()
if cpu_temp is not None:
cpu_temp.close()
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()
+13 -1
View File
@@ -57,6 +57,9 @@ class FakeCommander:
self.duty[p] = duty
return {p: self._rpm(p) for p in ports}
def full_speed(self) -> dict[int, int]:
return self.set_duty(range(1, 7), 100)
def close(self) -> None:
pass
@@ -98,8 +101,17 @@ class FakeBoard:
class FakeCpuTemperature:
"""Stands in for cooling.control.CpuTemperature (the service's PawnIO reader)."""
error = None
def __init__(self):
self.temp = self.power = None
def read(self, now: float) -> float:
return FakeCpu().read().temp
reading = FakeCpu().read()
self.temp, self.power = reading.temp, reading.power
return reading.temp
def close(self) -> None:
pass
+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)
+7
View File
@@ -12,5 +12,12 @@ SETTINGS_PATH = os.path.join(DATA_DIR, "settings.json")
# The TT LCD Dashboard's folder; its fan and lighting settings are imported once on first start.
LEGACY_DIR = os.path.join(_LOCAL, "TTLcdDashboard")
# The hardware service's settings and log (kurgan.hw, LocalSystem): writable by SYSTEM and
# Administrators only, readable by users. KURGAN_HW_DATA_DIR moves them (tests, a console run).
HW_DATA_DIR = (os.environ.get("KURGAN_HW_DATA_DIR")
or os.path.join(os.environ.get("ProgramData", r"C:\ProgramData"), "Kurgan"))
HW_SETTINGS_PATH = os.path.join(HW_DATA_DIR, "hw-settings.json")
HW_LOG_PATH = os.path.join(HW_DATA_DIR, "kurgan-hw.log")
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.dirname(PACKAGE_DIR)
+27 -21
View File
@@ -73,23 +73,8 @@ def _port_number(value, where: str) -> int:
return value
def validate(data: object) -> dict:
"""Return a normalised copy with defaults filled in, or raise 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)
cooling = out["cooling"]
def validate_cooling(cooling: dict) -> dict:
"""Check and normalise a cooling section in place (also used for the hardware service's)."""
if cooling["profile"] not in PROFILES:
raise SettingsError(f"cooling.profile must be one of {', '.join(PROFILES)}")
if ("cpu_ports" in cooling or "top_channels" in cooling) and "gpu_ports" not in cooling:
@@ -109,7 +94,26 @@ def validate(data: object) -> dict:
cooling["top_channels"] = list(parse_channels(",".join(map(str, value))))
except argparse.ArgumentTypeError as e:
raise SettingsError(f"cooling.top_channels: {e}") from None
return cooling
def validate(data: object) -> dict:
"""Return a normalised copy with defaults filled in, or raise 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"])
for zone, modes in LIGHTING_MODES.items():
if out["lighting"][zone] not in modes:
raise SettingsError(f"lighting.{zone} must be one of {', '.join(modes)}")
@@ -179,9 +183,11 @@ class Settings:
"""Thread-safe: the web server, the tray and the CLI all go through update()."""
def __init__(self, path: str = paths.SETTINGS_PATH, legacy_dir: str | None = paths.LEGACY_DIR,
seed: dict | None = None):
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags)."""
seed: dict | None = None, validator=None):
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags).
validator: the file's validate() (default: this module's, for settings.json)."""
self.path = path
self._validate = validator or validate
self._lock = threading.RLock()
self.created = False
try:
@@ -195,7 +201,7 @@ class Settings:
except ValueError as e:
raise SettingsError(f"{path}: {e}") from None
try:
self._data = validate(raw)
self._data = self._validate(raw)
except SettingsError as e:
raise SettingsError(f"{path}: {e}") from None
if self.created:
@@ -215,6 +221,6 @@ class Settings:
with self._lock:
data = copy.deepcopy(self._data)
data[section].update(changes)
data = validate(data)
data = self._validate(data)
write_json_atomic(self.path, data)
self._data = data
+26 -4
View File
@@ -529,6 +529,11 @@ def _process_names() -> list[str]:
return names
# Whose %APPDATA% holds the OpenRGB settings to check. The hardware service runs as LocalSystem,
# so it points this at the installing user's profile (kurgan.hw.service.user_appdata).
USER_APPDATA: str | None = None
def corsair_software_running(openrgb_detector: str, fan_tools: bool = True) -> bool:
"""True if iCUE (or, with `fan_tools`, FanControl) runs, or a running OpenRGB may drive the device.
@@ -541,7 +546,7 @@ def corsair_software_running(openrgb_detector: str, fan_tools: bool = True) -> b
return True
if not any("openrgb" in n for n in names):
return False
configs = [os.path.join(os.environ.get("APPDATA", ""), "OpenRGB", "OpenRGB.json"),
configs = [os.path.join(USER_APPDATA or os.environ.get("APPDATA", ""), "OpenRGB", "OpenRGB.json"),
os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "OpenRGB",
"service_config", "OpenRGB.json")]
try:
@@ -657,12 +662,13 @@ class CommanderPro:
if self.ch is not None:
return
ctypes.set_last_error(0)
mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdCommanderPro")
# Global: the hardware service runs in session 0, a console tool in the user's session.
mutex = _k32.CreateMutexW(None, False, "Global\\KurganCommanderPro")
err = ctypes.get_last_error()
if not mutex or err == 183:
if not mutex or err == 183: # exists already, or exists and belongs to SYSTEM (access denied)
if mutex:
_k32.CloseHandle(mutex)
raise OSError("Commander PRO is in use by another dashboard/sensor process")
raise OSError("Commander PRO is in use by another process (the hardware service?)")
self._mutex = mutex
try:
paths = hid_device_paths(self.VID, self.PID)
@@ -699,6 +705,22 @@ class CommanderPro:
self._read_at = time.monotonic()
return {p + 1: rpm for p, rpm in self.rpm.items()}
def full_speed(self) -> dict[int, int]:
"""Every port with a PWM fan to 100%: the fail-safe while the port mapping is unknown."""
with self._lock:
if self._corsair_software_running():
self.close()
raise OSError("Commander PRO busy: exit iCUE/FanControl, or disable OpenRGB's "
"Corsair Commander Pro detector and restart OpenRGB")
self._open()
modes = self._cmd(self.CMD_FAN_MODES)
if len(modes) < 8:
raise OSError("Incomplete Commander PRO fan modes reply")
ports = tuple(p + 1 for p in range(self.PORTS) if modes[2 + p] == 2)
if not ports:
raise OSError("no PWM fans connected to the Commander PRO")
return self.set_duty(ports, 100)
def _fresh_rpms(self) -> bool:
return time.monotonic() - self._read_at <= self.RPM_STALE
+30 -38
View File
@@ -1,6 +1,5 @@
import argparse
import contextlib
import threading
import unittest
from unittest.mock import Mock, call, mock_open, patch
@@ -186,10 +185,7 @@ class TopFanCurveTest(unittest.TestCase):
control = CaseFanControl(commander, (4, 5, 6), None, self.top)
control.update(40, 0) # startup runs the case fans at 100%
self.assertTrue(self.top.boosted)
stop = threading.Event()
stop.set()
with patch("kurgan.cooling.control.GpuSensors"):
control.run(stop)
control.shutdown()
self.assertEqual(self.mask, 0)
self.board.close.assert_called()
@@ -228,12 +224,23 @@ class TopFanCurveTest(unittest.TestCase):
def test_cpu_temperature_is_averaged_and_gaps_are_not(self):
pkg = Mock()
pkg.temperature.side_effect = [50, 90, None, 60]
pkg.power.return_value = 35.0
cpu = CpuTemperature(factory=lambda: pkg)
self.assertEqual(cpu.read(0), 50)
self.assertEqual(cpu.read(1), 70)
self.assertEqual((cpu.temp, cpu.power, cpu.error), (90, 35.0, None)) # the latest, for the app
self.assertIsNone(cpu.read(2))
self.assertIsNotNone(cpu.error)
self.assertEqual(cpu.read(3), 60)
def test_cpu_temperature_failures_say_why_and_back_off(self):
cpu = CpuTemperature(factory=Mock(side_effect=OSError("Cannot open PawnIO")))
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.assertIsNone(cpu.read(0))
self.assertEqual((cpu.temp, cpu.power, cpu.error), (None, None, "Cannot open PawnIO"))
cpu.read(30) # within the minute: not re-opened
self.assertEqual(cpu._factory.call_count, 1)
class Nct6687ControlTest(unittest.TestCase):
def test_override_uses_config_handshake_and_keeps_other_channels(self):
@@ -305,50 +312,35 @@ class FanWorkerTest(unittest.TestCase):
self.assertIn("FAILSAFE", self.control.status)
self.assertIn("[5]", self.control.status)
def test_exit_leaves_selected_ports_at_full_speed_even_without_lcd(self):
stop = threading.Event()
stop.set()
with patch("kurgan.cooling.control.GpuSensors"):
self.control.run(stop)
def test_shutdown_leaves_selected_ports_at_full_speed(self):
self.control.shutdown()
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
self.commander.close.assert_called_once()
def test_worker_survives_unexpected_errors_and_keeps_failing_safe(self):
stop = threading.Event()
gpu = Mock()
reads = []
def read():
reads.append(1)
if len(reads) >= 3:
stop.set()
raise RuntimeError("sensor failure")
gpu.read.side_effect = read
with patch("kurgan.cooling.control.GpuSensors", return_value=gpu), \
patch.object(CaseFanControl, "ERROR_RETRY_SECONDS", 0):
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.control.run(stop)
self.assertEqual(len(reads), 3) # retried instead of dying on the first error
def test_a_device_error_fails_safe_reopens_and_backs_off(self):
self.commander.set_duty.side_effect = [OSError("no reply to command 0x20"), {4: 900, 5: 900, 6: 900}]
self.assertEqual(self.control.step(50, None, 0), CaseFanControl.ERROR_RETRY_SECONDS)
self.assertIn("CONTROL ERROR", self.control.status)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.commander.close.assert_called_once() # reopened on the next pass
def test_a_control_bug_fails_safe_and_the_next_pass_runs(self):
ok = {p: 900 for p in range(1, 7)}
self.commander.set_duty.side_effect = [RuntimeError("bug"), ok, ok]
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.assertEqual(self.control.step(50, None, 0), CaseFanControl.ERROR_RETRY_SECONDS)
self.assertIn("CONTROL ERROR", self.control.status)
self.assertEqual(self.commander.set_duty.call_args_list[1], call((4, 5, 6), 100))
self.assertEqual(self.control.step(50, None, 5), 1.0) # not dead: the next pass works
def test_unexpected_errors_fail_the_top_fans_safe_too(self):
top = Mock(spec=TopFanCurve)
self.control.top = top
stop = threading.Event()
gpu = Mock()
def read():
stop.set()
raise RuntimeError("sensor failure")
gpu.read.side_effect = read
with patch("kurgan.cooling.control.GpuSensors", return_value=gpu), \
patch.object(CaseFanControl, "ERROR_RETRY_SECONDS", 0):
self.commander.set_duty.side_effect = [RuntimeError("bug"), {p: 900 for p in range(1, 7)}]
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.control.run(stop)
self.control.step(50, None, 0)
self.assertEqual(top.update.call_args.args[:2], (100, None))
self.control.shutdown()
top.release.assert_called_once()
+244
View File
@@ -0,0 +1,244 @@
import json
import os
import tempfile
import threading
import time
import unittest
import uuid
from unittest.mock import Mock, patch
from kurgan import demo
from kurgan.hw import settings as hw_settings
from kurgan.hw.main import serve
from kurgan.hw.pipe import PipeClient, PipeError, current_user_sid
from kurgan.hw.protocol import PROTOCOL_VERSION, Unavailable, decode_reply, encode_request
from kurgan.hw.service import HardwareService, SyncedChase
from kurgan.settings import SettingsError
def write(path, data):
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f)
class Fakes:
"""The demo's simulated hardware, with a few knobs for failures."""
def __init__(self):
self.commander = demo.FakeCommander()
self.board = demo.FakeBoard()
self.gpu = demo.FakeGpu()
self.cpu = demo.FakeCpuTemperature()
self.memory = demo.FakeLights("RAM")
def service(self, settings, error=None):
return HardwareService(settings, error, commander=self.commander, board_factory=lambda: self.board,
gpu_factory=lambda: self.gpu, cpu=self.cpu, memory=self.memory)
class ServiceTest(unittest.TestCase):
def setUp(self):
self.dir = tempfile.mkdtemp()
self.path = os.path.join(self.dir, "hw-settings.json")
write(self.path, {"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3],
"top_channels": [2, 5]},
"lighting": {"memory": "chase"}})
self.fakes = Fakes()
self.service = self.fakes.service(hw_settings.load(self.path))
def saved(self):
with open(self.path, encoding="utf-8") as f:
return json.load(f)
def test_the_loop_controls_the_fans_with_no_client(self):
stop = threading.Event()
original = self.service.tick
self.service.tick = lambda now: (original(now), 0.01)[1] # passes 10 ms apart, not 1 s
thread = threading.Thread(target=self.service.run, args=(stop,))
thread.start()
time.sleep(0.3)
stop.set()
thread.join(5)
self.assertFalse(thread.is_alive())
state = self.service.snapshot()
self.assertGreater(state["seq"], 1)
self.assertEqual([g["name"] for g in state["cooling"]["groups"]], ["GPU", "CPU"])
self.assertIsNotNone(state["cpu"]["temp"])
self.assertIsNotNone(state["cpu"]["power"])
self.assertIsNotNone(state["gpu"]["temp"])
self.assertEqual(len(state["commander"]["rpms"]), 6) # the power model's case fan speeds
self.assertEqual(state["lighting"]["memory"]["mode"], "chase")
# The loop's exit: case fans at 100%, top fans back on the BIOS curve.
self.assertEqual(set(self.fakes.commander.duty.values()), {100})
self.assertEqual(self.fakes.board.mask, 0)
def test_the_snapshot_has_the_fields_the_app_shows(self):
self.service.tick(0)
state = self.service.snapshot()
self.assertEqual(set(state["cooling"]), {"profile", "groups", "top", "note", "row"})
self.assertEqual(state["cooling"]["row"][1:], [100, 100, 100]) # startup: everything at 100%
self.assertEqual(state["service"]["protocol"], PROTOCOL_VERSION)
json.dumps(state, allow_nan=False)
def test_sensor_faults_fail_safe_and_the_loop_carries_on(self):
self.fakes.gpu.read = Mock(side_effect=RuntimeError("NVML exploded"))
for now in range(40): # settle at the curve, then lose the GPU
self.fakes.gpu.read.side_effect = None if now < 35 else RuntimeError("NVML exploded")
self.fakes.gpu.read.return_value = demo.Readings(temp=40.0)
if now == 35:
with self.assertLogs("kurgan", level="WARNING") as logs:
self.service.tick(now)
self.assertTrue(any("NVML exploded" in line for line in logs.output))
self.assertTrue(any("GPU case fans: FAILSAFE" in line for line in logs.output))
else:
self.service.tick(now)
state = self.service.snapshot()
self.assertIn("NVML exploded", state["gpu"]["error"])
gpu = state["cooling"]["groups"][0]
self.assertEqual((gpu["duty"], gpu["failsafe"]), (100, True))
def test_a_loop_bug_fails_safe_and_is_retried(self):
self.service.memory.set_temperature = Mock(side_effect=RuntimeError("bug"))
with self.assertLogs("kurgan.hw.service", level="ERROR"):
self.assertEqual(self.service.tick(0), 5.0)
self.assertEqual(self.fakes.commander.duty[4], 100)
def test_nan_readings_never_reach_the_pipe(self):
self.fakes.cpu.read = lambda now: setattr(self.fakes.cpu, "temp", float("nan"))
with self.assertLogs("kurgan.cooling.control", level="WARNING"): # the CPU side fails safe
self.service.tick(0)
self.assertIsNone(self.service.snapshot()["cpu"]["temp"])
def test_set_profile_saves_and_applies(self):
state = self.service.dispatch("set_profile", {"profile": "full"})
self.assertEqual(state["cooling"]["profile"], "full")
self.assertEqual(self.service.fans.profile.key, "full")
self.assertEqual(self.saved()["cooling"]["profile"], "full")
self.assertEqual(hw_settings.load(self.path).get("cooling", "profile"), "full") # survives a restart
def test_set_ram_lighting_saves_and_switches_the_pattern(self):
events = self.service._memory_events
self.assertTrue(events["chase"].is_set())
self.service.dispatch("set_ram_lighting", {"mode": "temperature"})
self.assertEqual((events["temperature"].is_set(), events["chase"].is_set()), (True, False))
self.assertEqual(self.saved()["lighting"], {"memory": "temperature"})
self.service.dispatch("set_ram_lighting", {"mode": "off"})
self.assertFalse(any(e.is_set() for e in events.values()))
def test_a_failed_save_changes_nothing(self):
with patch("kurgan.settings.write_json_atomic", side_effect=OSError("disk full")):
with self.assertRaisesRegex(Unavailable, "disk full"):
self.service.dispatch("set_profile", {"profile": "quiet"})
self.assertEqual(self.service.fans.profile.key, "balanced")
self.assertEqual(self.saved()["cooling"]["profile"], "balanced")
def test_ram_chase_follows_the_app_clock(self):
with patch("kurgan.hw.service.time.monotonic", return_value=100.0):
self.assertIsNone(self.service.dispatch("ram_chase", {"phase": 42.0, "rate": 10.0, "power": 300.0}))
self.assertEqual(self.service.chase.sample(100.5), (47.0, 10.0))
def test_fan_control_not_set_up_only_reads_the_rpms(self):
write(self.path, {"cooling": {"profile": "quiet"}})
service = self.fakes.service(hw_settings.load(self.path))
service.tick(0)
state = service.snapshot()
self.assertIsNone(service.fans)
self.assertIn("isn't set up", state["cooling"]["note"])
self.assertEqual(state["cooling"]["profile"], "quiet")
self.assertEqual(len(state["commander"]["rpms"]), 6)
self.assertEqual(set(self.fakes.commander.duty.values()), {100}) # untouched since power-on
def test_invalid_settings_hold_every_fan_at_full_speed(self):
write(self.path, {"cooling": {"profile": "turbo"}})
with self.assertRaises(SettingsError):
hw_settings.load(self.path)
self.fakes.commander.duty = {p: 30 for p in range(1, 7)}
service = self.fakes.service(None, "cooling.profile must be one of ...")
service.tick(0)
self.assertEqual(set(self.fakes.commander.duty.values()), {100})
state = service.snapshot()
self.assertIn("held at 100%", state["cooling"]["note"])
self.assertEqual(state["service"]["settings_error"], "cooling.profile must be one of ...")
for op, args in (("set_profile", {"profile": "quiet"}), ("set_ram_lighting", {"mode": "off"})):
with self.assertRaises(Unavailable):
service.dispatch(op, args)
class SettingsFileTest(unittest.TestCase):
def test_created_with_defaults_and_strict(self):
path = os.path.join(tempfile.mkdtemp(), "hw-settings.json")
settings = hw_settings.load(path)
self.assertEqual(settings.section("cooling"), {"profile": "balanced"})
self.assertTrue(os.path.exists(path))
for bad in ({"ai": {}}, {"cooling": {"profile": "balanced", "speed": 3}},
{"lighting": {"memory": "rainbow"}}, {"lighting": {"case_fans": "off"}},
{"cooling": {"cpu_ports": [1, 2, 3]}}, {"cooling": {"gpu_ports": [4, 5, 5]}}, []):
with self.subTest(bad=bad):
with self.assertRaises(SettingsError):
hw_settings.validate(bad)
class SyncedChaseTest(unittest.TestCase):
def test_runs_on_at_the_last_rate_between_syncs(self):
chase = SyncedChase()
self.assertEqual(chase.sample(10.0), (6.0, SyncedChase.IDLE_RATE)) # idle pace until the app speaks
chase.sync(100.0, 20.0, 11.0)
self.assertEqual(chase.sample(11.25), (105.0, 20.0))
self.assertEqual(chase.sample(11.0), (105.0, 20.0)) # never backwards
class ServeTest(unittest.TestCase):
"""The service's parts together, with a real pipe and the demo's hardware."""
def test_a_stuck_client_cannot_stop_fan_control(self):
directory = tempfile.mkdtemp()
path = os.path.join(directory, "hw-settings.json")
write(path, {"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6]}})
fakes = Fakes()
service = fakes.service(hw_settings.load(path))
ticks = []
original = service.tick
service.tick = lambda now: (ticks.append(now), original(now))[1] and 0.05
stuck = threading.Event()
save = service.settings.update
def slow_update(*args, **kwargs):
stuck.wait(5) # a save that hangs, e.g. a wedged disk
return save(*args, **kwargs)
service.settings.update = slow_update
name = rf"\\.\pipe\kurgan-hw-test-{os.getpid()}-{uuid.uuid4().hex[:8]}"
stop = threading.Event()
me = current_user_sid()
with patch("kurgan.hw.pipe.pipe_sddl", return_value=f"D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{me})"):
server = threading.Thread(target=serve, args=(stop, me), kwargs={"service": service, "pipe_name": name})
server.start()
try:
client = None
deadline = time.monotonic() + 3
while client is None:
try:
client = PipeClient(name, trusted_owners=None)
except PipeError:
if time.monotonic() > deadline:
raise
time.sleep(0.05)
hello = encode_request("hello", {"protocol": PROTOCOL_VERSION}, 0)
self.assertEqual(decode_reply(client.request(hello, 2), 0)["protocol"], PROTOCOL_VERSION)
blocked = encode_request("set_profile", {"profile": "full"}, 1)
with self.assertRaises(PipeError):
client.request(blocked, 0.3) # its reply is stuck behind the hung save ...
before = len(ticks)
time.sleep(0.4)
self.assertGreater(len(ticks) - before, 3) # ... while the fan loop keeps running
stuck.set()
client.close()
finally:
stop.set()
server.join(10)
self.assertFalse(server.is_alive())
self.assertEqual(set(fakes.commander.duty[p] for p in (4, 5, 6)), {100}) # stopped: fail-safe
if __name__ == "__main__":
unittest.main()