Files
the_kurgan/kurgan/hw/client.py
T
paulandClaude Opus 5.5 8f91a38695 Privilege split 9/11: setup installs the hardware service and moves its settings
- kurgan/hw/install.py (run elevated by setup.ps1): checks the base
  interpreter can run hw_service.py, creates %ProgramData%\Kurgan or resets
  its owner and access (Administrators own it; SYSTEM and Administrators full
  control, users read), moves the fan and RAM settings there, then creates or
  updates KurganHw through the service manager API (pywin32; sc.exe's quoting
  from Windows PowerShell 5.1 isn't reliable): LocalSystem, automatic start,
  restart after 5 s, 10 s and 60 s, the user's SID for the pipe. A running
  service is stopped first; then it's started and must reach "running".
- kurgan/hw/migrate.py: "copy" (elevated) creates hw-settings.json from the
  user's cooling and lighting.memory, never overwriting an existing file;
  "strip" (as the user) removes them from settings.json once hw-settings.json
  exists, keeping a dated backup. An invalid file on either side stops it.
- setup.ps1: creates the .venv if needed (the service runs from it), passes
  the base interpreter, the user's SID and settings path to the elevated part,
  which installs the service; then strips settings.json, registers and starts
  the app's task, and prints the service's status.
- uninstall.ps1: also stops and deletes the service.
- python -m kurgan.hw.client prints the service's status (setup runs it).
- The pipe's "isn't running", "refused this user" and "closed the
  connection" errors no longer repeat the Windows error text.
- Tests: migration (move, re-run, defaults, invalid files) and the install
  module's parts that don't need admin rights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:51:42 +13:00

330 lines
13 KiB
Python

"""The app's side of the hardware service: a client that keeps reconnecting.
A background thread asks the service for its state once a second (and sends the app's chase
clock for the RAM lighting); the web UI's profile and RAM lighting changes are sent at once.
While the service can't be reached, every reading from it is None or empty, `error` says why,
and the changes raise HardwareUnavailable (the web API answers 503).
The service itself never depends on the app: it controls the fans whether or not anything is
connected. The app only shows what the service reports and asks it for changes.
client = HardwareClient(PipeTransport) the real service, over \\\\.\\pipe\\kurgan-hw
client = HardwareClient(lambda: LocalTransport(service.dispatch, version)) --demo, tests
"""
from __future__ import annotations
import itertools
import logging
import threading
import time
from typing import Callable
from kurgan import APP_NAME, __version__
from kurgan.cooling.profiles import PROFILES
from kurgan.hw import protocol
from kurgan.hw.protocol import PIPE_NAME, PROTOCOL_VERSION, ProtocolError, RemoteError, Unavailable
log = logging.getLogger(__name__)
POLL_SECONDS = 1.0
CALL_SECONDS = 2.0 # how long one request may take
STALE_SECONDS = 5.0 # no state received for this long: the service is unreachable
STALL_SECONDS = 15.0 # the service's own state this old: its loop is stuck (it waits 5 s after an error)
BUSY_SECONDS = 5.0 # how long a change waits for the connection
SERVICE_NAME = "hardware service" # the telemetry health source
class HardwareUnavailable(Unavailable):
"""The hardware service can't be reached, or can't do that right now."""
class PipeTransport:
"""One connection to the service's pipe, speaking the protocol."""
def __init__(self, name: str = PIPE_NAME, timeout: float = CALL_SECONDS, **pipe_options):
from kurgan.hw.pipe import PipeClient
self._pipe = PipeClient(name, timeout, **pipe_options) # checks the pipe's owner by default
self._ids = itertools.count(1)
def call(self, op: str, args: dict | None = None, timeout: float = CALL_SECONDS):
request_id = next(self._ids)
line = self._pipe.request(protocol.encode_request(op, args, request_id), timeout)
return protocol.decode_reply(line, request_id)
def close(self) -> None:
self._pipe.close()
class LocalTransport:
"""The same conversation, encoded and checked the same way, without a pipe: --demo and tests."""
def __init__(self, dispatch: Callable[[str, dict], object], service_version: str = __version__):
self._session = protocol.Session(dispatch, service_version)
self._ids = itertools.count(1)
self.closed = False
def call(self, op: str, args: dict | None = None, timeout: float = CALL_SECONDS):
if self.closed:
raise OSError("connection closed")
request_id = next(self._ids)
reply, close = self._session.handle(protocol.encode_request(op, args, request_id).rstrip(b"\n"))
if close:
self.closed = True
return protocol.decode_reply(reply.rstrip(b"\n"), request_id)
def close(self) -> None:
self.closed = True
# Error replies that mean the two sides don't understand each other: drop the connection.
_MISMATCH = (protocol.VERSION, protocol.BAD_REQUEST, protocol.UNKNOWN_OP, protocol.HELLO_FIRST, protocol.TOO_LARGE)
class HardwareClient:
def __init__(self, connect: Callable[[], object] = PipeTransport, *, poll_seconds: float = POLL_SECONDS,
chase: Callable[[], dict | None] | None = None):
"""connect() opens a transport (OSError if it can't). chase() gives the ram_chase
arguments to send with each poll, or None."""
self._connect = connect
self.poll_seconds = poll_seconds
self.chase = chase
self._lock = threading.Lock() # one request at a time on the connection
self._transport = None
self._state: dict | None = None
self._state_at = 0.0 # time.monotonic() of the last state received
self._error: str | None = "not connected yet"
self.service: dict | None = None # the service's hello reply
self._last_profile: str | None = None
self._last_ram_mode: str | None = None
# -- the connection
def _drop(self) -> None:
if self._transport is not None:
try:
self._transport.close()
except Exception:
pass
self._transport = None
def _call(self, op: str, args: dict | None = None):
"""One request; the caller holds self._lock. HardwareUnavailable or ValueError."""
try:
if self._transport is None:
transport = self._connect()
try:
hello = transport.call("hello", {"protocol": PROTOCOL_VERSION,
"client": f"{APP_NAME} {__version__}"})
except BaseException:
transport.close()
raise
self._transport, self.service = transport, hello
log.info("Connected to the hardware service (version %s)", hello.get("service"))
return self._transport.call(op, args)
except RemoteError as e:
if e.code == protocol.INVALID:
raise ValueError(str(e)) from None
if e.code in _MISMATCH:
self._drop()
hint = "; re-run setup.ps1 so the app and the service match" if e.code in (
protocol.VERSION, protocol.UNKNOWN_OP) else ""
raise HardwareUnavailable(f"the hardware service refused the request ({e}){hint}") from None
raise HardwareUnavailable(str(e)) from None # UNAVAILABLE, INTERNAL: still connected
except ProtocolError as e:
self._drop()
raise HardwareUnavailable(f"bad reply from the hardware service: {e}") from None
except OSError as e:
self._drop()
raise HardwareUnavailable(str(e) or type(e).__name__) from None
def _store(self, state) -> None:
if not isinstance(state, dict):
raise HardwareUnavailable("bad state from the hardware service")
self._state, self._state_at = state, time.monotonic()
self._last_profile = (state.get("cooling") or {}).get("profile", self._last_profile)
self._last_ram_mode = ((state.get("lighting") or {}).get("memory") or {}).get("mode", self._last_ram_mode)
def _set_error(self, error: str | None) -> None:
if error != self._error:
if error is None:
log.info("Hardware service reachable")
else:
log.warning("Hardware service unavailable: %s", error)
self._error = error
def poll(self) -> None:
"""Fetch the state (and send the chase clock); never raises."""
try:
chase = self.chase() if self.chase is not None else None
except Exception:
log.exception("Chase clock failed")
chase = None
try:
with self._lock:
state = self._call("state")
if chase is not None:
self._call("ram_chase", chase)
self._store(state)
age = time.time() - state["t"] if isinstance(state.get("t"), (int, float)) else 0.0
self._set_error(None if age <= STALL_SECONDS else
f"the hardware service's loop has stalled (its state is {age:.0f} s old)")
except (HardwareUnavailable, ValueError) as e:
self._set_error(str(e))
except Exception as e:
log.exception("Hardware service poll failed")
self._set_error(f"{type(e).__name__}: {e}")
def run(self, stop: threading.Event) -> None:
while not stop.is_set():
self.poll()
stop.wait(self.poll_seconds)
with self._lock:
self._drop()
def _command(self, op: str, args: dict) -> None:
if not self._lock.acquire(timeout=BUSY_SECONDS):
raise HardwareUnavailable("the hardware service is busy; try again")
try:
state = self._call(op, args)
finally:
self._lock.release()
self._store(state)
# -- what the app reads
@property
def error(self) -> str | None:
"""Why the service's readings can't be used now, or None."""
if self._error is None and time.monotonic() - self._state_at > STALE_SECONDS:
return "no state from the hardware service"
return self._error
@property
def state(self) -> dict | None:
"""The service's latest state while it's fresh, else None."""
return self._state if self.error is None else None
def snapshot(self) -> dict:
"""For the web UI's state."""
state = self.state
service = (state or {}).get("service") or {}
return {"available": state is not None, "error": self.error,
"version": service.get("version"), "pid": service.get("pid"), "uptime": service.get("uptime"),
"settings_error": service.get("settings_error")}
def cooling(self) -> dict:
"""The service's fan state, as the web UI shows it."""
state = self.state
if state is not None:
return state["cooling"]
return {"profile": self._last_profile, "groups": [], "top": None, "row": None,
"note": (f"Hardware service unavailable: {self.error}. The service controls the fans, "
"not this app: no fan readings or changes until it's back.")}
def cpu(self) -> dict:
state = self.state
if state is None:
return {"temp": None, "power": None, "error": f"hardware service unavailable: {self.error}"}
return state["cpu"]
def fan_rpms(self) -> list[int]:
state = self.state
return list(state["commander"]["rpms"]) if state is not None else []
def ram_lighting(self) -> dict:
state = self.state
if state is not None:
return state["lighting"]["memory"]
return {"mode": self._last_ram_mode, "status": f"Hardware service unavailable: {self.error}"}
# -- what the app changes
def set_profile(self, key: str) -> None:
if key not in PROFILES:
raise ValueError(f"Unknown fan profile {key!r}")
self._command("set_profile", {"profile": key})
def set_ram_lighting(self, mode: str) -> None:
self._command("set_ram_lighting", {"mode": mode})
class CpuPackage:
"""The CPU package temperature and power, read by the service (PawnIO needs it elevated);
stands in for kurgan.telemetry.sensors.IntelPackage in the app's CpuSensors."""
def __init__(self, client: HardwareClient):
self.client = client
def read(self) -> tuple[float | None, float | None]:
cpu = self.client.cpu()
return cpu.get("temp"), cpu.get("power")
@property
def status(self) -> str:
cpu = self.client.cpu()
return "ok" if cpu.get("temp") is not None else (cpu.get("error") or "no reading")
class CommanderReadings:
"""The Commander PRO's fan RPMs, read by the service; stands in for CommanderPro in the
app's power model (SystemPower)."""
controlled = True
def __init__(self, client: HardwareClient):
self.client = client
def read(self) -> list[int]:
return self.client.fan_rpms()
def close(self) -> None:
pass
class RamLighting:
"""The RAM lighting zone, driven by the service; the lighting service's memory zone."""
def __init__(self, client: HardwareClient):
self.client = client
@property
def mode(self) -> str | None:
return self.client.ram_lighting()["mode"]
@property
def status(self) -> str:
return self.client.ram_lighting()["status"]
def set_mode(self, mode: str) -> None:
self.client.set_ram_lighting(mode)
def main() -> int:
"""python -m kurgan.hw.client: is the hardware service reachable, and what is it doing?"""
logging.basicConfig(level=logging.ERROR, format="%(message)s")
client = HardwareClient()
client.poll()
if client.error is not None:
print(f"Hardware service unavailable: {client.error}")
return 1
service, cooling, cpu, ram = client.snapshot(), client.cooling(), client.cpu(), client.ram_lighting()
print(f"The Kurgan hardware {service['version']} (pid {service['pid']}, up {service['uptime']} s)")
if cooling["groups"]:
top = f", top {cooling['top']['duty']}%" if cooling["top"] else ""
groups = ", ".join(f"{g['name']} {g['duty']}%" for g in cooling["groups"])
print(f"Fans: {cooling['profile']} profile; {groups}{top}")
if cooling["note"]:
print(f"Fans: {cooling['note']}")
fmt = lambda v, unit: "--" if v is None else f"{v:.0f} {unit}"
print(f"CPU: {fmt(cpu['temp'], 'C')}, {fmt(cpu['power'], 'W')}" + (f" ({cpu['error']})" if cpu["error"] else ""))
print(f"RAM lighting: {ram['mode']} ({ram['status']})")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())