Privilege split 6/11: the app reads and drives the hardware through the service
- kurgan/hw/client.py: HardwareClient polls the service's state once a second on its own thread, reconnecting (and greeting again) whenever the pipe breaks, and sends the app's chase clock with each poll. Profile and RAM lighting changes are sent at once: bad values are ValueError before anything is sent; an unreachable or refusing service is HardwareUnavailable. A state that stops arriving (5 s) or a service loop that stops publishing (15 s) counts as unavailable. PipeTransport for the real pipe, LocalTransport (same encoding and checks, no pipe) for --demo and tests. - Telemetry: the CPU package temperature and power (CpuSensors(package=...)) and the Commander PRO RPMs for the power model (SystemPower(fans=...)) come from the service; the app opens neither PawnIO nor the Commander PRO. "hardware service" is its own health source, and while it's down the missing CPU temperature isn't reported a second time. - The fan UI, profile buttons and fan history come from the service's state; the RAM lighting zone goes through it (LightingService(ram=...)), and the case fan and GPU zones stay local. The alert monitor balloons "Hardware service unavailable"; the header shows a hardware service pill instead of the admin-rights one (and warns if the app itself runs elevated); the tray lines read the service's fans. POSTs answer 503 while it's unavailable. - Removed --gpu-fan-ports, --no-gpu-fan-control and --rgb-memory-*: the service owns those now. - settings.json: cooling and lighting.memory are legacy. Old files keep them (still validated), nothing reads them, and defaults no longer add them. - --demo runs the real HardwareService in-process on the demo fakes, with its settings in demo-hw-settings.json, through the same client. - --preview reads the CPU temperature and fan power from the service too. - Tests: 13 for the client (including a real pipe end to end); the alert, lighting, settings and web tests follow the new shapes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3e84ab1322
commit
eb771656fb
15 files changed
+803
-179
No files matched your search
+68
-83
@@ -1,12 +1,13 @@
|
||||
"""The Kurgan: one process for the LCD, fans, lighting, the local LLM servers and the web UI.
|
||||
"""The Kurgan: one process for the LCD, lighting, the local LLM servers and the web UI.
|
||||
|
||||
Run: python -m kurgan (console, Ctrl+C to stop)
|
||||
Hidden: pythonw -m kurgan (what the "The Kurgan" startup task runs, elevated)
|
||||
Hidden: pythonw -m kurgan (what the "The Kurgan" startup task runs)
|
||||
Preview: python -m kurgan --preview x.png (render one LCD frame from live sensors and exit)
|
||||
|
||||
Needs admin rights for PawnIO (CPU temperature/power, motherboard top fans, RAM lighting);
|
||||
without them those parts show "--" or stay idle and everything else works. The LLM servers
|
||||
are always started without admin rights (see kurgan/ai/launcher.py).
|
||||
The fans, the CPU package temperature and power, and the RAM lighting belong to the hardware
|
||||
service (kurgan.hw, the "The Kurgan hardware" Windows service): this app shows what it reports
|
||||
and asks it for changes, over a named pipe. While the service is unavailable those parts show
|
||||
"--" and everything else works; the fans never depend on this app.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -70,21 +71,28 @@ def _parse_color(text: str) -> tuple[int, int, int]:
|
||||
ALERT_SECONDS = 5.0 # how often the alert monitor looks for things starting to go wrong
|
||||
|
||||
|
||||
def alert_states(fans, ai, telemetry) -> dict[str, str]:
|
||||
"""What is wrong right now: key -> message, for the things worth one balloon each."""
|
||||
def alert_states(cooling: dict | None, ai, telemetry) -> dict[str, str]:
|
||||
"""What is wrong right now: key -> message, for the things worth one balloon each.
|
||||
cooling: the hardware service's fan state (HardwareClient.cooling())."""
|
||||
from kurgan.telemetry.service import SERVICE_SOURCE
|
||||
|
||||
states = {}
|
||||
if fans is not None:
|
||||
for group in fans.groups:
|
||||
if group.status.startswith(("FAILSAFE", "CONTROL ERROR")):
|
||||
states[f"fans/{group.name}"] = f"{group.name} case fans: {group.status}"
|
||||
if fans.top is not None and fans.top.status.startswith(("FAILSAFE", "UNAVAILABLE")):
|
||||
states["fans/top"] = f"Top fans: {fans.top.status}"
|
||||
if cooling is not None:
|
||||
for group in cooling.get("groups") or ():
|
||||
if group["status"].startswith(("FAILSAFE", "CONTROL ERROR")):
|
||||
states[f"fans/{group['name']}"] = f"{group['name']} case fans: {group['status']}"
|
||||
top = cooling.get("top")
|
||||
if top is not None and top["status"].startswith(("FAILSAFE", "UNAVAILABLE")):
|
||||
states["fans/top"] = f"Top fans: {top['status']}"
|
||||
if ai is not None:
|
||||
for backend in ai.snapshot()["backends"]:
|
||||
if backend["error"]:
|
||||
states[f"ai/{backend['key']}"] = f"{backend['label']}: {backend['error']}"
|
||||
for name, info in telemetry.health().items():
|
||||
states[f"telemetry/{name}"] = f"{name} read failed ({info['error']}); continuing without it"
|
||||
if name == SERVICE_SOURCE:
|
||||
states["hw"] = f"Hardware service unavailable: {info['error']}"
|
||||
else:
|
||||
states[f"telemetry/{name}"] = f"{name} read failed ({info['error']}); continuing without it"
|
||||
return states
|
||||
|
||||
|
||||
@@ -125,8 +133,6 @@ def balloon(messages: list[str]) -> tuple[str, str]:
|
||||
|
||||
|
||||
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
from kurgan.cooling.control import parse_ports
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m kurgan", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--port", type=int, help="web UI port (default: settings.json web.port, 8080)")
|
||||
@@ -150,14 +156,11 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
ap.add_argument("--load-hot", type=float, default=80.0)
|
||||
ap.add_argument("--gpu-load", choices=("windows", "nvml"), default="windows")
|
||||
ap.add_argument("--same-direction", action="store_true", help=argparse.SUPPRESS)
|
||||
# Lighting: these override the saved mode for this run only (the web UI saves it).
|
||||
# Lighting: these override the saved mode for this run only (the web UI saves it). The RAM
|
||||
# has none: the hardware service drives it, and only the web UI changes it.
|
||||
fans = ap.add_mutually_exclusive_group()
|
||||
fans.add_argument("--rgb-temperature", action="store_true", help="case fan LEDs: temperature (this run)")
|
||||
fans.add_argument("--rgb-side-chase", action="store_true", help="case fan LEDs: red side chase (this run)")
|
||||
memory = ap.add_mutually_exclusive_group()
|
||||
memory.add_argument("--rgb-memory-temperature", action="store_true", help="RAM: temperature (this run)")
|
||||
memory.add_argument("--rgb-memory-side-chase", action="store_true", help="RAM: red side chase (this run)")
|
||||
memory.add_argument("--rgb-memory-off", action="store_true", help="RAM: off (this run)")
|
||||
gpu = ap.add_mutually_exclusive_group()
|
||||
gpu.add_argument("--rgb-gpu-side-chase", action="store_true", help="GPU LEDs: red side chase (this run)")
|
||||
gpu.add_argument("--rgb-gpu-off", action="store_true", help="GPU LEDs: off (this run)")
|
||||
@@ -165,12 +168,6 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
ap.add_argument("--rgb-chase-fast-ms", type=float, default=25.0, help="ms per chase LED at full power")
|
||||
ap.add_argument("--rgb-chase-idle-watts", type=float, default=150.0)
|
||||
ap.add_argument("--rgb-chase-full-watts", type=float, default=550.0)
|
||||
# Cooling
|
||||
fan_options = ap.add_mutually_exclusive_group()
|
||||
fan_options.add_argument("--gpu-fan-ports", type=parse_ports, metavar="1,2,3",
|
||||
help="override the saved GPU-side Commander PRO ports for this run")
|
||||
fan_options.add_argument("--no-gpu-fan-control", action="store_true",
|
||||
help="disable case/top fan control for this run")
|
||||
ap.add_argument("-v", "--verbose", action="store_true")
|
||||
args = ap.parse_args(argv)
|
||||
for name in ("rgb_chase_step_ms", "rgb_chase_fast_ms"):
|
||||
@@ -181,8 +178,6 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
||||
if not (math.isfinite(args.rgb_chase_idle_watts) and math.isfinite(args.rgb_chase_full_watts)
|
||||
and args.rgb_chase_full_watts > args.rgb_chase_idle_watts):
|
||||
ap.error("--rgb-chase-full-watts must be above --rgb-chase-idle-watts")
|
||||
if args.preview and args.gpu_fan_ports:
|
||||
ap.error("--preview cannot be combined with --gpu-fan-ports")
|
||||
args.interval = max(0.25, min(2.0, args.interval))
|
||||
return args
|
||||
|
||||
@@ -191,9 +186,6 @@ def lighting_overrides(args: argparse.Namespace) -> dict[str, str]:
|
||||
overrides = {}
|
||||
if args.rgb_temperature or args.rgb_side_chase:
|
||||
overrides["case_fans"] = "temperature" if args.rgb_temperature else "chase"
|
||||
if args.rgb_memory_temperature or args.rgb_memory_side_chase or args.rgb_memory_off:
|
||||
overrides["memory"] = ("temperature" if args.rgb_memory_temperature else
|
||||
"chase" if args.rgb_memory_side_chase else "off")
|
||||
if args.rgb_gpu_side_chase or args.rgb_gpu_off:
|
||||
overrides["gpu"] = "chase" if args.rgb_gpu_side_chase else "off"
|
||||
return overrides
|
||||
@@ -203,10 +195,10 @@ class Kurgan:
|
||||
"""Owns the capabilities and answers the web UI and the tray."""
|
||||
|
||||
def __init__(self, args: argparse.Namespace, settings):
|
||||
from kurgan.cooling.control import CaseFanControl, TopFanCurve
|
||||
from kurgan.cooling.profiles import PROFILES
|
||||
from kurgan.display.renderer import DashboardRenderer
|
||||
from kurgan.display.service import DisplayService
|
||||
from kurgan.hw.client import (CommanderReadings, CpuPackage, HardwareClient, LocalTransport,
|
||||
PipeTransport, RamLighting)
|
||||
from kurgan.lighting.service import LightingService
|
||||
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
|
||||
from kurgan.telemetry.service import Telemetry
|
||||
@@ -221,13 +213,19 @@ class Kurgan:
|
||||
temp_warn=args.temp_warn, temp_hot=args.temp_hot,
|
||||
load_warn=args.load_warn, load_hot=args.load_hot)
|
||||
hw = None
|
||||
self.hw_service = None # the hardware service, when it runs in-process (--demo)
|
||||
if args.demo:
|
||||
from kurgan import demo
|
||||
hw = demo.hardware()
|
||||
self.system = hw["system"] if hw else SystemPower()
|
||||
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(),
|
||||
self.hw_service = demo.hardware_service(os.path.join(paths.DATA_DIR, "demo-hw-settings.json"))
|
||||
self.hw = HardwareClient(lambda: LocalTransport(self.hw_service.dispatch))
|
||||
self.system = demo.FakeSystem(CommanderReadings(self.hw))
|
||||
else:
|
||||
self.hw = HardwareClient(PipeTransport)
|
||||
self.system = SystemPower(fans=CommanderReadings(self.hw))
|
||||
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(package=CpuPackage(self.hw)),
|
||||
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
|
||||
self.system, args.interval)
|
||||
self.system, args.interval, hw=self.hw)
|
||||
self.recorder = None
|
||||
if not args.demo: # simulated samples must not mix into the real records
|
||||
from kurgan.telemetry.record import Recorder
|
||||
@@ -236,28 +234,12 @@ class Kurgan:
|
||||
self.display = None if (args.no_lcd or hw) else DisplayService(
|
||||
DashboardRenderer(self.theme, rotate180=args.rotate180), self.telemetry, args.brightness)
|
||||
|
||||
cooling = settings.section("cooling")
|
||||
self.fan_note = None
|
||||
self.fans: CaseFanControl | None = None
|
||||
gpu_ports = None if args.no_gpu_fan_control else (args.gpu_fan_ports or cooling.get("gpu_ports"))
|
||||
if gpu_ports:
|
||||
top = cooling.get("top_channels")
|
||||
top_curve = None
|
||||
if top:
|
||||
top_curve = TopFanCurve(tuple(top), board_factory=hw["board"]) if hw else TopFanCurve(tuple(top))
|
||||
self.fans = CaseFanControl(self.system.fans, tuple(gpu_ports),
|
||||
tuple(cooling.get("cpu_ports") or ()) or None, top_curve,
|
||||
profile=PROFILES[cooling["profile"]], sensors=hw["fan_sensors"] if hw else None)
|
||||
self.system.fans.controlled = True
|
||||
else:
|
||||
self.fan_note = ("Fan control is off for this run (--no-gpu-fan-control)." if args.no_gpu_fan_control
|
||||
else "Fan control isn't set up: save the Commander PRO ports first (see README).")
|
||||
|
||||
self.lighting = LightingService(
|
||||
settings, self.theme,
|
||||
(args.rgb_chase_step_ms / 1000, args.rgb_chase_fast_ms / 1000,
|
||||
args.rgb_chase_idle_watts, args.rgb_chase_full_watts),
|
||||
lighting_overrides(args), **(hw["lighting"] if hw else {}))
|
||||
lighting_overrides(args), ram=RamLighting(self.hw), **(hw["lighting"] if hw else {}))
|
||||
self.hw.chase = self.lighting.chase_clock # keeps the RAM chase in step with the others
|
||||
self.ai = None
|
||||
if not args.no_ai:
|
||||
from kurgan.ai.service import AiService
|
||||
@@ -270,15 +252,12 @@ class Kurgan:
|
||||
|
||||
# -- lifecycle
|
||||
|
||||
def _fan_row(self, t: float) -> tuple:
|
||||
cpu, top = self.fans.cpu, self.fans.top
|
||||
return (round(t, 1), self.fans.gpu.duty, None if cpu is None else cpu.duty, None if top is None else top.duty)
|
||||
|
||||
def _on_sample(self, sample) -> None:
|
||||
p = sample.power
|
||||
self.lighting.on_telemetry(sample.cpu.temp, sample.gpu.temp, p.total)
|
||||
if self.fans is not None:
|
||||
self.fan_history.append(self._fan_row(sample.t))
|
||||
row = self.hw.cooling()["row"] # (t, gpu duty, cpu duty, top duty), from the service's last pass
|
||||
if row and (not self.fan_history or row[0] > self.fan_history[-1][0]):
|
||||
self.fan_history.append(tuple(row))
|
||||
if self.tray is not None:
|
||||
fmt = lambda v: "--" if v is None else f"{v:.0f}"
|
||||
self.tray.set_tooltip(f"{APP_NAME}\nTotal {fmt(p.total)} W: CPU {fmt(p.cpu)}, "
|
||||
@@ -292,9 +271,11 @@ class Kurgan:
|
||||
def start(self, port: int, tray: bool) -> None:
|
||||
from kurgan.web.server import WebServer
|
||||
|
||||
if self.hw_service is not None: # --demo
|
||||
self._thread("hw-loop", self.hw_service.run, self.stop)
|
||||
self._threads.append(self.hw_service.start_lighting(self.stop))
|
||||
self._thread("hw-client", self.hw.run, self.stop)
|
||||
self._thread("telemetry", self.telemetry.run, self.stop)
|
||||
if self.fans is not None:
|
||||
self._thread("case-fans", self.fans.run, self.stop)
|
||||
self.lighting.start(self.stop)
|
||||
if self.display is not None:
|
||||
self._thread("display", self.display.run, self.stop)
|
||||
@@ -319,7 +300,7 @@ class Kurgan:
|
||||
if self.tray is None:
|
||||
continue # no icon, no balloons -- and no baseline burnt before the icon exists
|
||||
try:
|
||||
states = alert_states(self.fans, self.ai, self.telemetry)
|
||||
states = alert_states(self.hw.cooling(), self.ai, self.telemetry)
|
||||
except Exception:
|
||||
log.exception("Alert check failed")
|
||||
continue
|
||||
@@ -371,7 +352,6 @@ class Kurgan:
|
||||
if self.recorder is not None:
|
||||
self.recorder.close() # after the telemetry thread has stopped writing
|
||||
self.lighting.join()
|
||||
self.system.fans.close()
|
||||
|
||||
# -- the web UI's API
|
||||
|
||||
@@ -395,10 +375,8 @@ class Kurgan:
|
||||
"pid": os.getpid(), "token": me},
|
||||
"telemetry": self.telemetry.snapshot(),
|
||||
"display": self.display.snapshot() if self.display else {"status": "Off (--no-lcd)", "connected": False},
|
||||
"cooling": ({**self.fans.snapshot(), "note": None, "row": self.fan_history[-1] if self.fan_history else None}
|
||||
if self.fans is not None
|
||||
else {"profile": self.settings.get("cooling", "profile"), "groups": [], "top": None,
|
||||
"note": self.fan_note, "row": None}),
|
||||
"hardware": self.hw.snapshot(),
|
||||
"cooling": self.hw.cooling(),
|
||||
"lighting": self.lighting.snapshot(),
|
||||
"ai": self.ai.snapshot() if self.ai else None,
|
||||
}
|
||||
@@ -418,13 +396,8 @@ class Kurgan:
|
||||
self.lighting.set_mode(zone, mode)
|
||||
|
||||
def set_fan_profile(self, key: str) -> None:
|
||||
from kurgan.cooling.profiles import PROFILES
|
||||
|
||||
if key not in PROFILES:
|
||||
raise ValueError(f"Unknown fan profile {key!r}")
|
||||
self.settings.update("cooling", profile=key)
|
||||
if self.fans is not None:
|
||||
self.fans.apply_profile(PROFILES[key])
|
||||
"""The hardware service applies and saves it; ValueError or HardwareUnavailable."""
|
||||
self.hw.set_profile(key)
|
||||
|
||||
def set_ai(self, backend: str | None, variant: str | None) -> None:
|
||||
if self.ai is None:
|
||||
@@ -439,15 +412,20 @@ class Kurgan:
|
||||
# -- tray
|
||||
|
||||
def tray_lines(self) -> list[str]:
|
||||
from kurgan.cooling.profiles import PROFILES
|
||||
|
||||
lines = []
|
||||
if self.display is not None:
|
||||
lines.append(self.display.status)
|
||||
if self.fans is not None:
|
||||
profile = self.fans.profile.name
|
||||
groups = ", ".join(f"{g.name} {g.duty}%" for g in self.fans.groups)
|
||||
top = f", top {self.fans.top.duty}%" if self.fans.top is not None else ""
|
||||
cooling = self.hw.cooling()
|
||||
if cooling["groups"]:
|
||||
profile = PROFILES[cooling["profile"]].name if cooling["profile"] in PROFILES else cooling["profile"]
|
||||
groups = ", ".join(f"{g['name']} {g['duty']}%" for g in cooling["groups"])
|
||||
top = f", top {cooling['top']['duty']}%" if cooling["top"] is not None else ""
|
||||
lines.append(f"Fans: {profile} ({groups}{top})")
|
||||
elif self.fan_note:
|
||||
elif self.hw.error is not None:
|
||||
lines.append("Fans: hardware service unavailable")
|
||||
else:
|
||||
lines.append("Fans: not controlled")
|
||||
modes = {z["key"]: z["mode"] for z in self.lighting.snapshot()["zones"]}
|
||||
lines.append(f"Lighting: case fans {modes['case_fans']}, RAM {modes['memory']}, GPU {modes['gpu']}")
|
||||
@@ -470,14 +448,21 @@ def main(argv: list[str] | None = None) -> int:
|
||||
|
||||
if args.preview:
|
||||
from kurgan.display.renderer import DashboardRenderer
|
||||
from kurgan.hw.client import CommanderReadings, CpuPackage, HardwareClient
|
||||
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
|
||||
from kurgan.telemetry.service import Telemetry
|
||||
from kurgan.theme import Theme
|
||||
|
||||
from kurgan.telemetry.service import Telemetry
|
||||
telemetry = Telemetry(CpuSensors(), GpuSensors(load_source=args.gpu_load), SystemPower())
|
||||
hw = HardwareClient()
|
||||
hw.poll()
|
||||
telemetry = Telemetry(CpuSensors(package=CpuPackage(hw)), GpuSensors(load_source=args.gpu_load),
|
||||
SystemPower(fans=CommanderReadings(hw)), hw=hw)
|
||||
telemetry.read()
|
||||
time.sleep(1.0) # let counters and the energy meter accumulate
|
||||
hw.poll()
|
||||
sample = telemetry.read()
|
||||
if hw.error is not None:
|
||||
log.warning("Hardware service unavailable, so no CPU temperature or fan power: %s", hw.error)
|
||||
theme = Theme(accent=_parse_color(args.accent), psu_watts=max(100.0, args.psu_watts))
|
||||
DashboardRenderer(theme, rotate180=args.rotate180).render(sample.cpu, sample.gpu, sample.power).save(
|
||||
args.preview)
|
||||
|
||||
+27
-9
@@ -1,8 +1,9 @@
|
||||
"""Simulated sensors and devices for `python -m kurgan --demo`.
|
||||
|
||||
Lets the web UI and the AI swapping be worked on while the real Kurgan owns the hardware:
|
||||
nothing here touches USB, PawnIO, the SMBus or NVAPI. Run it with its own data folder and
|
||||
web port, e.g.
|
||||
nothing here touches USB, PawnIO, the SMBus or NVAPI. The hardware service runs in-process on
|
||||
these fakes (hardware_service), and the app talks to it through the same client and protocol
|
||||
as to the real one, just without the pipe. Run it with its own data folder and web port, e.g.
|
||||
|
||||
$env:KURGAN_DATA_DIR = "$env:TEMP\\kurgan-demo"; python -m kurgan --demo --port 18080 --no-tray
|
||||
"""
|
||||
@@ -65,8 +66,8 @@ class FakeCommander:
|
||||
|
||||
|
||||
class FakeSystem:
|
||||
def __init__(self):
|
||||
self.fans = FakeCommander()
|
||||
def __init__(self, fans=None):
|
||||
self.fans = fans if fans is not None else FakeCommander() # the app passes the service's RPMs
|
||||
|
||||
def read(self, cpu: Readings, gpu: Readings) -> PowerReadings:
|
||||
parts = {"Motherboard & chipset": 15.0, "Memory (4 modules)": 10 + 0.1 * (cpu.load or 0),
|
||||
@@ -139,8 +140,25 @@ class FakeLights:
|
||||
|
||||
|
||||
def hardware() -> dict:
|
||||
return {
|
||||
"cpu": FakeCpu(), "gpu": FakeGpu(), "system": FakeSystem(), "board": FakeBoard,
|
||||
"fan_sensors": (FakeGpu, FakeCpuTemperature),
|
||||
"lighting": {"rgb": FakeLights("case fans"), "memory": FakeLights("RAM"), "gpu": FakeLights("GPU")},
|
||||
}
|
||||
"""The app's own devices."""
|
||||
return {"cpu": FakeCpu(), "gpu": FakeGpu(),
|
||||
"lighting": {"rgb": FakeLights("case fans"), "gpu": FakeLights("GPU")}}
|
||||
|
||||
|
||||
# The demo's hardware service has its fans set up: GPU side on ports 4-6, CPU side on 1-3, top 2 and 5.
|
||||
DEMO_COOLING = {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]}
|
||||
|
||||
|
||||
def hardware_service(settings_path: str):
|
||||
"""A kurgan.hw.service.HardwareService on the fakes, with its settings in settings_path."""
|
||||
from kurgan.hw import settings as hw_settings
|
||||
from kurgan.hw.service import HardwareService
|
||||
from kurgan.settings import Settings, SettingsError
|
||||
|
||||
try:
|
||||
settings, error = Settings(settings_path, None, seed={"cooling": DEMO_COOLING},
|
||||
validator=hw_settings.validate), None
|
||||
except (OSError, SettingsError) as e:
|
||||
settings, error = None, str(e)
|
||||
return HardwareService(settings, error, commander=FakeCommander(), board_factory=FakeBoard,
|
||||
gpu_factory=FakeGpu, cpu=FakeCpuTemperature(), memory=FakeLights("RAM"))
|
||||
@@ -0,0 +1,301 @@
|
||||
"""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)
|
||||
+38
-24
@@ -1,21 +1,26 @@
|
||||
"""Lighting service: one worker per device, one mode per zone, saved in settings.json.
|
||||
"""Lighting service: one worker per device, one mode per zone.
|
||||
|
||||
Zones and their modes (see kurgan.settings.LIGHTING_MODES):
|
||||
case_fans Lighting Node CORE QL120 LEDs: off (hardware effect), temperature, chase
|
||||
memory Dominator DDR5: off (held dark while running), temperature, chase
|
||||
gpu ASUS RTX 4090 LED row: off (its own effect), chase
|
||||
|
||||
The three chases share one power-paced clock, so they stay in step.
|
||||
The case fan and GPU zones run here and are saved in settings.json. The RAM is on the SMBus,
|
||||
which needs PawnIO and so admin rights: the hardware service drives it and keeps its mode in
|
||||
hw-settings.json; this service only shows it and asks for changes (kurgan.hw.client.RamLighting).
|
||||
|
||||
The three chases share one power-paced clock, so they stay in step: the RAM's in the hardware
|
||||
service is kept in step by sending it this clock once a second (chase_clock).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
import time
|
||||
|
||||
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP, ChaseTiming, RGBLighting
|
||||
from kurgan.lighting.gpu import GpuLighting
|
||||
from kurgan.lighting.memory import MemoryLighting
|
||||
from kurgan.settings import LIGHTING_MODES, Settings
|
||||
from kurgan.theme import Theme
|
||||
|
||||
@@ -23,19 +28,22 @@ log = logging.getLogger(__name__)
|
||||
|
||||
ZONE_LABELS = {"case_fans": "Case fan LEDs", "memory": "RAM", "gpu": "GPU"}
|
||||
MODE_LABELS = {"off": "Off", "temperature": "Temperature", "chase": "Red side chase"}
|
||||
REMOTE_ZONES = ("memory",) # driven by the hardware service
|
||||
LOCAL_ZONES = tuple(zone for zone in LIGHTING_MODES if zone not in REMOTE_ZONES)
|
||||
|
||||
|
||||
class LightingService:
|
||||
def __init__(self, settings: Settings, theme: Theme, chase: tuple[float, float, float, float],
|
||||
overrides: dict[str, str] | None = None, *, rgb=None, memory=None, gpu=None):
|
||||
overrides: dict[str, str] | None = None, *, ram, rgb=None, gpu=None):
|
||||
"""chase: (idle s/LED, full-power s/LED, idle watts, full watts).
|
||||
overrides: modes for this run only (CLI flags), not saved."""
|
||||
overrides: case fan and GPU modes for this run only (CLI flags), not saved.
|
||||
ram: the RAM zone in the hardware service (mode, status, set_mode)."""
|
||||
self._settings = settings
|
||||
self._lock = threading.Lock()
|
||||
self._events = {zone: {mode: threading.Event() for mode in modes if mode != "off"}
|
||||
for zone, modes in LIGHTING_MODES.items()}
|
||||
self._events = {zone: {mode: threading.Event() for mode in LIGHTING_MODES[zone] if mode != "off"}
|
||||
for zone in LOCAL_ZONES}
|
||||
self._overridden = set(overrides or ())
|
||||
modes = settings.section("lighting")
|
||||
modes = {zone: mode for zone, mode in settings.section("lighting").items() if zone in LOCAL_ZONES}
|
||||
modes.update(overrides or {})
|
||||
self._modes: dict[str, str] = {}
|
||||
for zone, mode in modes.items():
|
||||
@@ -44,8 +52,8 @@ class LightingService:
|
||||
self.timing = ChaseTiming(step, fast, (idle_w, full_w))
|
||||
self.timing.reset(SIDE_CHASE_BOTTOM_STEP)
|
||||
self.rgb = rgb or RGBLighting(theme, step, fast, (idle_w, full_w), chase_timing=self.timing)
|
||||
self.memory = memory or MemoryLighting(theme, chase_timing=self.timing)
|
||||
self.gpu = gpu or GpuLighting(self.timing)
|
||||
self.ram = ram
|
||||
self._threads: list[threading.Thread] = []
|
||||
self._power: float | None = None
|
||||
|
||||
@@ -63,7 +71,6 @@ class LightingService:
|
||||
e = self._events
|
||||
for name, target, args in (
|
||||
("case-fan-lighting", self.rgb.run, (stop, e["case_fans"]["temperature"], e["case_fans"]["chase"])),
|
||||
("memory-lighting", self.memory.run, (stop, e["memory"]["temperature"], e["memory"]["chase"])),
|
||||
("gpu-lighting", self.gpu.run, (stop, e["gpu"]["chase"]))):
|
||||
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
|
||||
thread.start()
|
||||
@@ -76,33 +83,40 @@ class LightingService:
|
||||
def on_telemetry(self, cpu_temp: float | None, gpu_temp: float | None, total_watts: float | None) -> None:
|
||||
self._power = total_watts
|
||||
self.rgb.set_temperature(cpu_temp, gpu_temp)
|
||||
self.rgb.set_power(total_watts)
|
||||
self.memory.set_temperature(cpu_temp, gpu_temp)
|
||||
self.memory.set_power(total_watts)
|
||||
self.rgb.set_power(total_watts) # sets the shared clock's pace
|
||||
|
||||
def mode(self, zone: str) -> str:
|
||||
return self._modes[zone]
|
||||
def chase_clock(self) -> dict:
|
||||
"""The shared chase clock now, as the hardware service's ram_chase takes it."""
|
||||
phase, rate = self.timing.sample(time.monotonic())
|
||||
return {"phase": phase, "rate": rate, "power": self._power}
|
||||
|
||||
def mode(self, zone: str) -> str | None:
|
||||
return self.ram.mode if zone in REMOTE_ZONES else self._modes[zone]
|
||||
|
||||
def set_mode(self, zone: str, mode: str) -> None:
|
||||
"""Save first, then switch, so a failed save leaves the lighting as it was."""
|
||||
if zone not in LIGHTING_MODES or mode not in LIGHTING_MODES[zone]:
|
||||
raise ValueError(f"Unknown lighting {zone!r} mode {mode!r}")
|
||||
with self._lock:
|
||||
self._settings.update("lighting", **{zone: mode})
|
||||
self._overridden.discard(zone)
|
||||
self._apply(zone, mode)
|
||||
if zone in REMOTE_ZONES:
|
||||
self.ram.set_mode(mode) # the hardware service saves it
|
||||
else:
|
||||
with self._lock:
|
||||
self._settings.update("lighting", **{zone: mode})
|
||||
self._overridden.discard(zone)
|
||||
self._apply(zone, mode)
|
||||
log.info("%s lighting: %s", ZONE_LABELS[zone], mode)
|
||||
|
||||
def statuses(self) -> dict[str, str]:
|
||||
return {"case_fans": self.rgb.status, "memory": self.memory.status, "gpu": self.gpu.status}
|
||||
return {"case_fans": self.rgb.status, "memory": self.ram.status, "gpu": self.gpu.status}
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
statuses = self.statuses()
|
||||
modes = {**self._modes, "memory": self.ram.mode}
|
||||
# The eased rate once a chase is running; the target rate for the current power until then.
|
||||
rate = self.timing.rate or self.timing.rate_for(self._power)
|
||||
chasing = "chase" in self._modes.values()
|
||||
chasing = "chase" in modes.values()
|
||||
return {"chase_ms_per_led": round(1000 / rate) if chasing else None,
|
||||
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": self._modes[zone],
|
||||
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in modes],
|
||||
"zones": [{"key": zone, "label": ZONE_LABELS[zone], "mode": modes[zone],
|
||||
"modes": [{"key": m, "label": MODE_LABELS[m]} for m in zone_modes],
|
||||
"status": statuses[zone], "this_run_only": zone in self._overridden}
|
||||
for zone, modes in LIGHTING_MODES.items()]}
|
||||
for zone, zone_modes in LIGHTING_MODES.items()]}
|
||||
+26
-18
@@ -3,16 +3,18 @@
|
||||
%LOCALAPPDATA%\\Kurgan\\settings.json, for example:
|
||||
|
||||
{
|
||||
"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5],
|
||||
"profile": "balanced"},
|
||||
"lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"},
|
||||
"lighting": {"case_fans": "chase", "gpu": "off"},
|
||||
"ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40},
|
||||
"web": {"port": 8080}
|
||||
}
|
||||
|
||||
The fan port mapping is written by `python -m kurgan.cooling.control --save-ports ...`; the
|
||||
rest by the web UI. An invalid file stops The Kurgan from starting rather than silently
|
||||
dropping fan control. On first start the TT LCD Dashboard's settings are imported.
|
||||
The web UI writes it. An invalid file stops The Kurgan from starting rather than silently
|
||||
dropping a setting. On first start the TT LCD Dashboard's settings are imported.
|
||||
|
||||
The fans and the RAM lighting belong to the hardware service, in hw-settings.json (see
|
||||
kurgan.hw.settings). Files from before the privilege split may still hold a `cooling` section
|
||||
and `lighting.memory`: they're checked as before and kept, but nothing here uses them, and
|
||||
setup.ps1 moves them to hw-settings.json (kurgan.hw.migrate).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -38,20 +40,22 @@ LIGHTING_MODES = {
|
||||
DEFAULT_WEB_PORT = 8080
|
||||
|
||||
DEFAULTS = {
|
||||
"cooling": {"profile": DEFAULT_PROFILE},
|
||||
"lighting": {zone: "off" for zone in LIGHTING_MODES},
|
||||
"lighting": {"case_fans": "off", "gpu": "off"},
|
||||
"ai": {"active": None, "strata_model": ai_config.STRATA_DEFAULT_MODEL,
|
||||
"idle_stop_minutes": ai_config.IDLE_STOP_MINUTES},
|
||||
"web": {"port": DEFAULT_WEB_PORT},
|
||||
}
|
||||
_OPTIONAL = {
|
||||
"cooling": {"gpu_ports", "cpu_ports", "top_channels"},
|
||||
"lighting": set(),
|
||||
"lighting": {"memory"}, # legacy: the hardware service's now
|
||||
"ai": {"strata_root", "strata_port", "llama_server", "llama_presets", "llama_model", "llama_port"},
|
||||
"web": set(),
|
||||
}
|
||||
|
||||
|
||||
# Sections only files from before the privilege split have: allowed keys (see the docstring).
|
||||
LEGACY_SECTIONS = {"cooling": {"profile", "gpu_ports", "cpu_ports", "top_channels"}}
|
||||
|
||||
|
||||
class SettingsError(ValueError):
|
||||
pass
|
||||
|
||||
@@ -101,21 +105,24 @@ 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)
|
||||
unknown = set(data) - set(DEFAULTS) - set(LEGACY_SECTIONS)
|
||||
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]
|
||||
allowed = LEGACY_SECTIONS[section] if section in LEGACY_SECTIONS else (
|
||||
set(DEFAULTS[section]) | _OPTIONAL[section])
|
||||
bad = set(values) - allowed
|
||||
if bad:
|
||||
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
|
||||
out[section].update(values)
|
||||
out.setdefault(section, {}).update(values)
|
||||
|
||||
validate_cooling(out["cooling"])
|
||||
if "cooling" in out:
|
||||
out["cooling"] = validate_cooling({"profile": DEFAULT_PROFILE, **out["cooling"]})
|
||||
for zone, modes in LIGHTING_MODES.items():
|
||||
if out["lighting"][zone] not in modes:
|
||||
if zone in out["lighting"] and out["lighting"][zone] not in modes:
|
||||
raise SettingsError(f"lighting.{zone} must be one of {', '.join(modes)}")
|
||||
|
||||
ai = out["ai"]
|
||||
@@ -209,18 +216,19 @@ class Settings:
|
||||
log.info("Created %s%s", path, " from the TT LCD Dashboard's settings" if raw else "")
|
||||
|
||||
def section(self, name: str) -> dict:
|
||||
"""A copy of the section ({} for an optional one the file doesn't have)."""
|
||||
with self._lock:
|
||||
return copy.deepcopy(self._data[name])
|
||||
return copy.deepcopy(self._data.get(name, {}))
|
||||
|
||||
def get(self, section: str, key: str, default=None):
|
||||
with self._lock:
|
||||
return copy.deepcopy(self._data[section].get(key, default))
|
||||
return copy.deepcopy(self._data.get(section, {}).get(key, default))
|
||||
|
||||
def update(self, section: str, **changes) -> None:
|
||||
"""Validate and save; on any error nothing changes, in memory or on disk."""
|
||||
with self._lock:
|
||||
data = copy.deepcopy(self._data)
|
||||
data[section].update(changes)
|
||||
data.setdefault(section, {}).update(changes)
|
||||
data = self._validate(data)
|
||||
write_json_atomic(self.path, data)
|
||||
self._data = data
|
||||
@@ -302,7 +302,9 @@ class CpuSensors:
|
||||
# it, or a broken driver costs a heavy CreateFile+DeviceIoControl every second.
|
||||
RETRY_SECONDS = 15.0
|
||||
|
||||
def __init__(self):
|
||||
def __init__(self, package=None):
|
||||
"""package: where the temperature and power come from instead of PawnIO, e.g. the
|
||||
hardware service (kurgan.hw.client.CpuPackage): read() -> (temp, power), and status."""
|
||||
base = r"\Processor Information(_Total)"
|
||||
self.pdh = PerfCounters({
|
||||
"utility": base + r"\% Processor Utility",
|
||||
@@ -310,13 +312,14 @@ class CpuSensors:
|
||||
"perf": base + r"\% Processor Performance",
|
||||
"freq": base + r"\Processor Frequency",
|
||||
})
|
||||
self.package = package
|
||||
self.pkg: IntelPackage | None = None
|
||||
self._pkg_error: str | None = None
|
||||
self._next_pkg_attempt = 0.0
|
||||
self._try_pkg()
|
||||
|
||||
def _try_pkg(self) -> None:
|
||||
if self.pkg or time.monotonic() < self._next_pkg_attempt:
|
||||
if self.package is not None or self.pkg or time.monotonic() < self._next_pkg_attempt:
|
||||
return
|
||||
try:
|
||||
self.pkg = IntelPackage()
|
||||
@@ -329,6 +332,9 @@ class CpuSensors:
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
"""Of the temperature and power reading: "ok", or why not."""
|
||||
if self.package is not None:
|
||||
return self.package.status
|
||||
return "ok" if self.pkg else (self._pkg_error or "not started")
|
||||
|
||||
def read(self) -> Readings:
|
||||
@@ -343,7 +349,9 @@ class CpuSensors:
|
||||
clock = s["freq"] * s["perf"] / 100.0
|
||||
temp = power = None
|
||||
self._try_pkg()
|
||||
if self.pkg:
|
||||
if self.package is not None:
|
||||
temp, power = self.package.read()
|
||||
elif self.pkg:
|
||||
try:
|
||||
temp = self.pkg.temperature()
|
||||
power = self.pkg.power()
|
||||
@@ -872,10 +880,12 @@ class StoragePower:
|
||||
class SystemPower:
|
||||
"""Everything that isn't the CPU package or the graphics card, in watts."""
|
||||
|
||||
def __init__(self, model: PowerModel | None = None):
|
||||
def __init__(self, model: PowerModel | None = None, fans=None):
|
||||
"""fans: where the case fan RPMs come from (read() -> list), e.g. the hardware service
|
||||
(kurgan.hw.client.CommanderReadings); default: the Commander PRO itself."""
|
||||
self.model = model or PowerModel()
|
||||
self.dimms = memory_modules()
|
||||
self.fans = CommanderPro()
|
||||
self.fans = fans if fans is not None else CommanderPro()
|
||||
try:
|
||||
self.storage: StoragePower | None = StoragePower(self.model)
|
||||
except OSError as e:
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""Telemetry service: reads every sensor once a second on one thread and shares the result.
|
||||
|
||||
The LCD, the lighting, the tray tooltip and the web UI all use these samples, so the hardware
|
||||
is polled once however many things are watching. (The fan worker keeps its own temperature
|
||||
reads on purpose: cooling must not depend on any other worker staying healthy.)
|
||||
is polled once however many things are watching. (The hardware service keeps its own
|
||||
temperature reads on purpose: cooling must not depend on this app staying healthy. Its CPU
|
||||
package temperature and power and its fan RPMs come here through kurgan.hw.client.)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,6 +21,7 @@ log = logging.getLogger(__name__)
|
||||
|
||||
HISTORY_SECONDS = 600
|
||||
EMPTY_READS = 3 # consecutive empty readings before a source counts as failing
|
||||
SERVICE_SOURCE = "hardware service"
|
||||
SERIES = ("t", "cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
|
||||
|
||||
|
||||
@@ -43,8 +45,10 @@ def _r(value: float | None, digits: int = 1) -> float | None:
|
||||
|
||||
|
||||
class Telemetry:
|
||||
def __init__(self, cpu, gpu, system, interval: float = 1.0):
|
||||
self.cpu, self.gpu, self.system = cpu, gpu, system
|
||||
def __init__(self, cpu, gpu, system, interval: float = 1.0, hw=None):
|
||||
"""hw: the hardware service client (its error says why it's unavailable); listed in
|
||||
health() as its own source, so its absence isn't also reported as a missing CPU temperature."""
|
||||
self.cpu, self.gpu, self.system, self.hw = cpu, gpu, system, hw
|
||||
self.interval = interval
|
||||
self._cond = threading.Condition()
|
||||
self._latest: Sample | None = None
|
||||
@@ -61,8 +65,11 @@ class Telemetry:
|
||||
"""Read every source independently: one failing source costs only its own readings."""
|
||||
# The sensor classes don't raise when their device is lost (they back off and return
|
||||
# empty readings), so a reading without a temperature counts as failing too.
|
||||
hw_error = None if self.hw is None else self._source(SERVICE_SOURCE, lambda: self.hw.error, None,
|
||||
missing=lambda error: error)
|
||||
c = self._source("CPU sensors", self.cpu.read, Readings(),
|
||||
missing=lambda r: None if r.temp is not None else "no CPU temperature (MSR reader unavailable)")
|
||||
missing=lambda r: None if r.temp is not None or hw_error is not None else
|
||||
f"no CPU temperature ({getattr(self.cpu, 'status', None) or 'reader unavailable'})")
|
||||
g = self._source("GPU sensors", self.gpu.read, Readings(),
|
||||
missing=lambda r: None if r.temp is not None else "no GPU readings (driver unavailable)")
|
||||
p = self._source("system power", self.system.read, PowerReadings(), c, g)
|
||||
|
||||
+10
-5
@@ -12,11 +12,12 @@
|
||||
|
||||
* /strata/... /llama/... the LLM servers, started on demand (kurgan/web/proxy.py)
|
||||
|
||||
The process runs elevated and controls fans, so requests are guarded: the Host header must
|
||||
name this server (blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header,
|
||||
which a page on another site can't send without a CORS preflight that this server never
|
||||
answers. There is no other authentication: anything already running on this PC as you can
|
||||
use the API.
|
||||
The fan profile and the RAM lighting are passed on to the hardware service, which answers
|
||||
503 here while it can't be reached. Requests are guarded: the Host header must name this server
|
||||
(blocks DNS rebinding), and every POST needs JSON plus an X-Kurgan header, which a page on
|
||||
another site can't send without a CORS preflight that this server never answers. There is no
|
||||
other authentication: anything already running on this PC as you can use the API (as it could
|
||||
use the hardware service's pipe directly).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -29,6 +30,7 @@ import threading
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from kurgan.hw.protocol import Unavailable
|
||||
from kurgan.web import proxy
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
@@ -189,6 +191,9 @@ def make_handler(app, port: int):
|
||||
except (ApiError, ValueError) as e:
|
||||
status = e.status if isinstance(e, ApiError) else 400
|
||||
self._json(status, {"error": str(e)})
|
||||
except Unavailable as e: # the hardware service: unreachable, or can't do it now
|
||||
log.warning("POST %s: %s", self.path, e)
|
||||
self._json(503, {"error": f"Hardware service unavailable: {e}"})
|
||||
except OSError as e:
|
||||
log.warning("POST %s failed: %s", self.path, e)
|
||||
self._json(500, {"error": f"Couldn't save the setting: {e}"})
|
||||
|
||||
@@ -501,13 +501,20 @@ function renderHeader(s) {
|
||||
const power = s.telemetry.power;
|
||||
setText("hero-total", (power?.partial ? "≈" : "") + fmt.n0(power?.total));
|
||||
const meta = $("meta");
|
||||
const elevated = s.app.token?.elevated;
|
||||
const health = Object.entries(s.telemetry.health ?? {});
|
||||
const hw = s.hardware ?? {};
|
||||
const health = Object.entries(s.telemetry.health ?? {}).filter(([name]) => name !== "hardware service");
|
||||
meta.replaceChildren(
|
||||
el("span", { class: "pill" }, el("span", { class: "dot good" }), "Live"),
|
||||
el("span", { text: `Up ${fmt.dur(s.app.uptime)}` }),
|
||||
el("span", { class: "pill", title: "PawnIO sensors, top fans and RAM lighting need admin rights" },
|
||||
el("span", { class: `dot ${elevated ? "good" : "warning"}` }), elevated ? "Admin rights" : "No admin rights"),
|
||||
hw.available
|
||||
? el("span", { class: "pill", title: `The Kurgan hardware ${hw.version ?? ""} · pid ${hw.pid ?? "?"} · up ${fmt.dur(hw.uptime)}\nFans, CPU temperature and power, RAM lighting` },
|
||||
el("span", { class: `dot ${hw.settings_error ? "warning" : "good"}` }), "Hardware service")
|
||||
: el("span", { class: "pill", title: hw.error ?? "" },
|
||||
el("span", { class: "dot critical" }), "Hardware service unavailable"),
|
||||
...(s.app.token?.elevated
|
||||
? [el("span", { class: "pill", title: "The app should run without admin rights; only the hardware service needs them" },
|
||||
el("span", { class: "dot warning" }), "Running elevated")]
|
||||
: []),
|
||||
...(health.length
|
||||
? [el("span", { class: "pill", title: health.map(([name, h]) => `${name}: ${h.error}`).join("\n") },
|
||||
el("span", { class: "dot warning" }),
|
||||
|
||||
Reference in new issue
Block a user