Files
the_kurgan/kurgan/app.py
T
paul ba39016d52 Sensor health in the API and UI; balloon tips when something starts going wrong
- telemetry: _source() now remembers each failing source's error message, not
  just the log timestamp; health() reports them and every snapshot carries a
  "health" key, so /api/state shows which sensor source is failing and since
  when. A source that reads again clears its entry.
- Web UI: a header pill counts the failing sources; hovering lists the errors.
- tray: notify() shows a balloon tip from any thread (queued on the tray
  window, NIF_INFO). app.py grows an alert monitor: every 5 s it diffs the
  current bad states (fan failsafes/control errors, AI backend errors, failing
  sensor sources) against the last look and balloons only what is new. The
  first look is the baseline: problems that predate the tray icon stay quiet.
- Tests: test_telemetry.py (5) and test_alerts.py (7); README updated.
2026-12-05 17:51:00 +13:00

464 lines
22 KiB
Python

"""The Kurgan: one process for the LCD, fans, 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)
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).
"""
from __future__ import annotations
import argparse
import collections
import ctypes
import logging
import logging.handlers
import math
import os
import sys
import threading
import time
from kurgan import APP_NAME, __version__, paths
log = logging.getLogger("kurgan")
INSTANCE_MUTEXES = ("Local\\TheKurgan", "Local\\TTLcdDashboard") # the second keeps an old dashboard copy out
DEMO_MUTEXES = ("Local\\TheKurganDemo",)
def _setup_logging(verbose: bool) -> None:
os.makedirs(paths.DATA_DIR, exist_ok=True)
handlers: list[logging.Handler] = [
logging.handlers.RotatingFileHandler(paths.LOG_PATH, maxBytes=1_000_000, backupCount=2, encoding="utf-8")
]
if sys.stderr is not None:
handlers.append(logging.StreamHandler())
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers,
format="%(asctime)s %(levelname)s %(name)s: %(message)s")
def _single_instance(names=INSTANCE_MUTEXES) -> list | None:
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateMutexW.restype = ctypes.c_void_p
k32.CloseHandle.argtypes = [ctypes.c_void_p]
handles = []
for name in names:
handle = k32.CreateMutexW(None, False, name)
if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED
for h in handles + ([handle] if handle else []):
k32.CloseHandle(h)
return None
handles.append(handle)
return handles
def _message_box(text: str) -> None:
try:
ctypes.WinDLL("user32").MessageBoxW(None, text, APP_NAME, 0x10 | 0x10000)
except Exception:
pass
def _parse_color(text: str) -> tuple[int, int, int]:
text = text.lstrip("#")
return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
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."""
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 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"
return states
def new_alerts(known: dict[str, str], states: dict[str, str]) -> list[tuple[str, str]]:
"""(key, message) for alerts that are new since the last look; recovered ones stay quiet."""
return [(key, states[key]) for key in sorted(states.keys() - known.keys())]
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)")
ap.add_argument("--no-ai", action="store_true", help="don't start or watch the LLM servers")
ap.add_argument("--no-lcd", action="store_true", help="don't drive the LCD (sensors keep running)")
ap.add_argument("--no-tray", action="store_true", help="don't show the notification-area icon")
ap.add_argument("--preview", metavar="PNG", help="render one LCD frame from live sensors to a PNG and exit")
ap.add_argument("--demo", action="store_true",
help="simulated sensors and devices, no LCD (set KURGAN_DATA_DIR for separate settings)")
# LCD
ap.add_argument("--interval", type=float, default=1.0, help="seconds between sensor reads/LCD frames (max 2)")
ap.add_argument("--brightness", type=int, default=100, help="LCD backlight 0-100")
ap.add_argument("--rotate180", action="store_true", help="flip the image if the panel is mounted upside down")
ap.add_argument("--accent", default="e81c2c", help="LCD title colour as hex")
ap.add_argument("--psu-watts", type=float, default=1000.0, help="power supply rating; fills the power tank")
ap.add_argument("--cpu-temp-max", type=float, default=100.0)
ap.add_argument("--gpu-temp-max", type=float, default=90.0)
ap.add_argument("--temp-warn", type=float, default=50.0, help="gauges and lighting turn yellow here")
ap.add_argument("--temp-hot", type=float, default=80.0, help="gauges and lighting turn red above this")
ap.add_argument("--load-warn", type=float, default=50.0)
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).
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)")
ap.add_argument("--rgb-chase-step-ms", type=float, default=150.0, help="ms per chase LED at idle power")
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"):
if not math.isfinite(getattr(args, name)) or getattr(args, name) < 20:
ap.error(f"--{name.replace('_', '-')} must be finite and at least 20")
if args.rgb_chase_fast_ms > args.rgb_chase_step_ms:
ap.error("--rgb-chase-fast-ms can't be slower than --rgb-chase-step-ms")
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
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
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.lighting.service import LightingService
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
from kurgan.telemetry.service import Telemetry
from kurgan.theme import Theme
self.args = args
self.settings = settings
self.started = time.time()
self.stop = threading.Event()
self.theme = Theme(accent=_parse_color(args.accent), cpu_temp_range=(20.0, args.cpu_temp_max),
gpu_temp_range=(20.0, args.gpu_temp_max), psu_watts=max(100.0, args.psu_watts),
temp_warn=args.temp_warn, temp_hot=args.temp_hot,
load_warn=args.load_warn, load_hot=args.load_hot)
hw = None
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(),
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
self.system, args.interval)
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 {}))
self.ai = None
if not args.no_ai:
from kurgan.ai.service import AiService
self.ai = AiService(settings)
self.web = None
self.tray = None
self._threads: list[threading.Thread] = []
self.fan_history: collections.deque[tuple] = collections.deque(maxlen=self.telemetry._history.maxlen)
self.telemetry.subscribe(self._on_sample)
# -- 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))
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)}, "
f"GPU {fmt(p.gpu)}, other {fmt(p.other)}")
def _thread(self, name: str, target, *args) -> None:
thread = threading.Thread(target=target, args=args, name=name, daemon=True)
thread.start()
self._threads.append(thread)
def start(self, port: int, tray: bool) -> None:
from kurgan.web.server import WebServer
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)
if self.ai is not None:
self.ai.set_public_url(f"http://127.0.0.1:{port}")
self._threads += self.ai.start(self.stop)
try:
self.web = WebServer(self, port)
self.web.start()
except OSError as e:
log.error("Web UI unavailable on port %s: %s", port, e)
if tray:
self._start_tray()
self._thread("alerts", self._alert_monitor, self.stop)
def _alert_monitor(self, stop: threading.Event) -> None:
"""Balloon tips for things starting to go wrong. The first look is the baseline: what
is already wrong at startup sits in the tray menu and the UI, it doesn't need a balloon."""
known: dict[str, str] | None = None
while not stop.wait(ALERT_SECONDS):
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)
except Exception:
log.exception("Alert check failed")
continue
if known is None:
known = states
continue
for _, message in new_alerts(known, states):
log.warning("Alert: %s", message)
self.tray.notify(APP_NAME, message, warning=True)
known = states
def _start_tray(self) -> None:
from kurgan.tray import TrayIcon, make_icon
try:
icon = make_icon(os.path.join(paths.DATA_DIR, "tray.ico"),
[self.theme.other_color, self.theme.cpu_color, self.theme.gpu_color])
self.tray = TrayIcon(APP_NAME, icon, on_exit=self.stop.set,
on_open=self.open_ui if self.web else None, status_lines=self.tray_lines)
self.tray.start()
except Exception:
log.exception("Tray icon unavailable")
self.tray = None
def open_ui(self) -> None:
from kurgan.ai.launcher import open_url
try:
open_url(self.web.url)
except OSError:
log.exception("Couldn't open the browser")
def wait(self) -> None:
try:
while not self.stop.wait(1):
pass
except KeyboardInterrupt:
self.stop.set()
def close(self) -> None:
self.stop.set()
if self.web is not None:
self.web.close()
if self.tray is not None:
self.tray.close()
deadline = time.monotonic() + 60 # Strata may take up to ~45 s to shut down cleanly
for thread in self._threads:
thread.join(max(0.1, deadline - time.monotonic()))
self.lighting.join()
self.system.fans.close()
# -- the web UI's API
def config(self) -> dict:
from kurgan.cooling.profiles import PROFILES
return {"app": APP_NAME, "version": __version__,
"profiles": [p.as_dict() for p in PROFILES.values()],
"theme": {"temp_warn": self.theme.temp_warn, "temp_hot": self.theme.temp_hot,
"psu_watts": self.theme.psu_watts}}
def state(self) -> dict:
from kurgan.ai.launcher import token_info
try:
me = token_info()
except OSError:
me = None
return {
"app": {"name": APP_NAME, "version": __version__, "uptime": round(time.time() - self.started),
"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}),
"lighting": self.lighting.snapshot(),
"ai": self.ai.snapshot() if self.ai else None,
}
def history(self) -> dict:
return {**self.telemetry.history(),
"fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_history)}}
def set_lighting(self, zone: str, mode: str) -> None:
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])
def set_ai(self, backend: str | None, variant: str | None) -> None:
if self.ai is None:
raise ValueError("AI management is off for this run (--no-ai)")
self.ai.set_active(backend, variant)
def ai_model(self, action: str) -> None:
if self.ai is None:
raise ValueError("AI management is off for this run (--no-ai)")
self.ai.model_action(action)
# -- tray
def tray_lines(self) -> list[str]:
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 ""
lines.append(f"Fans: {profile} ({groups}{top})")
elif self.fan_note:
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']}")
if self.ai is not None:
ai = self.ai.snapshot()
active = next((b for b in ai["backends"] if b["key"] == ai["active"]), None)
if active is None:
lines.append("AI: none selected")
else:
lines.append(f"AI: {active['label']} - {active['process']}, model {active['model']['state']}")
if self.web is not None:
lines.append(f"Web UI: {self.web.url}")
return lines
def main(argv: list[str] | None = None) -> int:
args = parse_args(argv)
_setup_logging(args.verbose)
from kurgan.settings import Settings, SettingsError
if args.preview:
from kurgan.display.renderer import DashboardRenderer
from kurgan.telemetry.sensors import CpuSensors, GpuSensors, SystemPower
from kurgan.theme import Theme
from kurgan.telemetry.service import Telemetry
telemetry = Telemetry(CpuSensors(), GpuSensors(load_source=args.gpu_load), SystemPower())
telemetry.read()
time.sleep(1.0) # let counters and the energy meter accumulate
sample = telemetry.read()
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)
print(f"Wrote {args.preview}")
return 0
mutexes = _single_instance(DEMO_MUTEXES if args.demo else INSTANCE_MUTEXES)
if mutexes is None:
log.error("Another copy of The Kurgan (or the TT LCD Dashboard) is already running")
return 1
try:
settings = Settings(seed={"lighting": lighting_overrides(args)})
except (OSError, SettingsError) as e:
log.error("Invalid settings; refusing to start: %s", e)
_message_box(f"The Kurgan didn't start: its settings are invalid.\n\n{e}\n\nLog: {paths.LOG_PATH}")
return 1
port = args.port or settings.get("web", "port")
log.info("Starting %s %s (pid %s)", APP_NAME, __version__, os.getpid())
try:
app = Kurgan(args, settings)
except ValueError:
log.exception("Invalid configuration; refusing to start")
return 1
app.start(port, tray=not args.no_tray)
app.wait()
log.info("Stopping")
app.close()
log.info("Stopped")
return 0