- 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>
245 lines
12 KiB
Python
245 lines
12 KiB
Python
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()
|