Compare commits

..
17 Commits
Author SHA1 Message Date
paulandClaude Opus 5.5 04fee83542 Privilege split 11/11: docs for the two-process Kurgan
- README: how it's split (the hardware service and the app), what setup.ps1
  now does, updating from the elevated version, a security model section
  (what the pipe allows and checks, the unelevated app, and that this is not
  a boundary against malware running as the user: the service runs code from
  user-writable folders), where each setting lives (hw-settings.json and the
  legacy sections), the 503s, the service log, identifying fan ports with the
  service stopped, running either part by hand, and the new layout.
- The USB hub note, in the README and case_fans.py: the LCD is now on a
  back-panel port (Intel root hub); the CORE shares the Genesys hub with the
  Commander PRO. The ~22 frames/s cap stays as a margin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:54:50 +13:00
paulandClaude Opus 5.5 0d5f470c4a Privilege split 10/11: app-level tests with and without the hardware service
- tests/test_app.py runs the whole app in demo mode (the real HardwareService
  in-process on the demo fakes, reached through the client), in a temp folder
  on a spare port:
  - with the service: the fan groups, fan history, and profile and RAM
    lighting changes through the web API;
  - without it: the app carries on (telemetry, the app's own lighting), the
    state, health, alert, tray line and a 503 from the API all say the
    hardware service is unavailable; when it's back, everything recovers.
- The rest of stage 10 landed with the stages it belongs to: --demo on the
  in-process service (6), the service loop with no client (4), the client
  reconnecting (6) and the settings migration (9).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:52:40 +13:00
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
paulandClaude Opus 5.5 a7ebf42838 Privilege split 8/11: The Kurgan's logon task runs without admin rights
- setup.ps1: the elevated part removes the old tasks ("TT LCD Dashboard" and
  the elevated "The Kurgan"); back in the unelevated part, setup registers
  "The Kurgan" as the user with RunLevel Limited and starts it. Registered
  as the user, the tray's "Start with Windows" can change it without admin
  rights (checked on this machine with a throwaway task). Running setup.ps1
  from an elevated window is refused, since the task must be registered
  unelevated. The hardware service's install follows in stage 9.
- kurgan/tray.py: texts for an unelevated task; a failed toggle suggests
  re-running setup.ps1 (for a task an older setup registered elevated).
- README: the task is unelevated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:46:48 +13:00
paulandClaude Opus 5.5 e583e25346 Privilege split 7/11: launch the LLM servers as plain child processes
- kurgan/ai/launcher.py: the app is unelevated now, so the servers are
  started with CreateProcessW, still suspended into their own kill-on-close
  job object and with an explicit handle list (only the log and NUL are
  inherited). Gone: the copy of Explorer's token (CreateProcessWithTokenW),
  the Safer "normal user" token and CreateProcessAsUserW, and with them the
  AI service's wait for the desktop at logon.
- launch() refuses (PermissionError) if The Kurgan itself is elevated, rather
  than pass admin rights on to a model server; this also covers opening the
  browser.
- Tests: the handle list is checked for real (an inheritable, unlisted handle
  doesn't reach the child; a control run without the list leaks it), and an
  elevated app starts nothing. The launch tests skip when the suite itself
  runs elevated.
- The UI's server token label and the README's launcher paragraph follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:44:47 +13:00
paulandClaude Opus 5.5 eb771656fb 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>
2026-12-05 19:41:51 +13:00
paulandClaude Opus 5.5 3e84ab1322 Privilege split 5/11: host kurgan.hw as a Windows service (pywin32)
- kurgan/hw/winservice.py: pywin32's ServiceFramework, hosted by the base
  interpreter's python.exe (PrepareToHostSingle + StartServiceCtrlDispatcher),
  not pythonservice.exe. The venv's python.exe is a redirector that starts the
  base interpreter as a child, and the service manager only talks to the
  process it started. Recorded as Decision 0002 in the vault.
- Accepts stop and shutdown; both end the hardware loop, which leaves the case
  fans at 100% and hands the top fans back to the BIOS curve. An unexpected
  failure exits without reporting "stopped", so the recovery actions (set by
  setup.ps1: restart after 5 s, 10 s, 60 s) bring it back.
- hw_service.py: the service's image, run as
  "<base python>" -I -S -B hw_service.py. It adds the repo and the venv's
  site-packages itself (pywin32's .pth bootstrap included), so the base
  interpreter's own packages never load and SYSTEM writes no .pyc into the
  repo. --check imports everything the service needs (setup.ps1 runs it
  first); started from a console it runs the service in the foreground.
- requirements.txt: pywin32>=311 (312 has cp314 wheels).
- Tests: 5 new (stop/shutdown, the run, failure exits, console fallback, and
  the bootstrap under the base interpreter in isolated mode).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:30:25 +13:00
paulandClaude Opus 5.5 7190db733f Privilege split 4/11: the kurgan.hw service process
- kurgan/hw/service.py, HardwareService: one loop a second reads the CPU
  package (PawnIO MSR: temperature and power) and the GPU (NVML), runs the
  fan curves, and publishes a state snapshot. It never depends on a client:
  the pipe side takes no lock the loop needs, every sensor read is guarded
  (a fault is a missing temperature, so those fans fail safe), and a bug in
  the loop fails the fans safe and retries. On exit the case fans are left at
  100% and the top fans go back to the BIOS curve.
- Without saved ports it only reads the Commander PRO's RPMs (for the app's
  power estimate). With an invalid hw-settings.json it holds every connected
  PWM fan at 100% (CommanderPro.full_speed) and says why in its state,
  instead of refusing to start and leaving the fans at their last duty.
- State carries the app's cooling snapshot unchanged (profile, groups, top,
  note, row) plus the CPU temperature and power, GPU temperature, the
  Commander PRO RPMs and the RAM lighting. NaN never reaches the pipe.
- RAM lighting runs in the service; its chase follows the app's clock
  (SyncedChase, fed by ram_chase) so it stays in step with the other chases.
- kurgan/hw/settings.py: %ProgramData%\Kurgan\hw-settings.json, the cooling
  and RAM lighting sections, as strict as settings.json (validate_cooling is
  shared). The folder is created SYSTEM/Administrators full, Users read.
- kurgan/hw/main.py: serve() wires the loop, the RAM lighting and the pipe
  (the fans run whatever happens to the pipe); `python -m kurgan.hw` runs it
  in a console. The pipe user comes from HKLM\...\Services\KurganHw\
  Parameters\UserSid; the OpenRGB check reads that user's %APPDATA%.
- control.py: CaseFanControl.step() (one guarded pass) and shutdown()
  replace run(); CpuTemperature also keeps the latest reading, the package
  power and why it has none. The fan CLI saves to hw-settings.json.
- sensors.py: the Commander PRO mutex is Global\KurganCommanderPro, so a
  console tool in the user's session sees the service's claim.
- The app still uses the old worker; it is rewired in step 6.
- Tests: 16 new or rewritten (202 pass), including the loop with no client
  and a stuck client that can't stop fan control.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:28:32 +13:00
paulandClaude Opus 5.5 73a424f6a8 Privilege split 3/11: the access-controlled named pipe (server and client)
- kurgan/hw/pipe.py, ctypes with overlapped I/O and timeouts throughout.
- Server: each connection on its own thread (the fan loop never waits on a
  client); up to 8 at once. A client that sends nothing, or leaves a line
  unfinished, for 30 s is dropped, and so is one that won't read its replies
  (5 s write timeout). An oversized line gets a too_large reply, then the
  connection closes. Remote clients are rejected.
- Access list (pipe_sddl): SYSTEM and Administrators full, the installing
  user's SID FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES, and
  nobody else. GENERIC_WRITE is avoided because for a pipe it includes
  FILE_CREATE_PIPE_INSTANCE, which would let the user's other programs add an
  instance and answer in the service's name. The first instance uses
  FILE_FLAG_FIRST_PIPE_INSTANCE, so a squatter makes the service fail loudly.
- Client: identification-level impersonation only, and it refuses a pipe
  whose owner isn't SYSTEM or Administrators (one an unelevated program
  created while the service was down). Clear errors for "not running" and
  "refused this user".
- Tests: 11 new, against real pipes: round trip, several clients at once,
  silent and trickling clients dropped without affecting others, oversized
  lines, prompt shutdown, owner check, and (unelevated) a user missing from
  the access list is refused and the user can't add a pipe instance.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:21:24 +13:00
paulandClaude Opus 5.5 b1404ac4ba Privilege split 2/11: the hardware service's pipe protocol
- kurgan/hw/protocol.py: newline-delimited JSON between the app and the
  coming kurgan.hw service. Requests {"op", "args", "id"}; replies {"id",
  "ok", "result"|"error": {"code", "message"}}. Operations: hello (protocol
  and service versions; required first on every connection), state,
  set_profile, set_ram_lighting, and ram_chase, which carries the app's chase
  clock so the RAM stays in step with the case fan and GPU chases.
- Strict: a 64 KiB line cap (an oversized line closes the connection),
  unknown operations and fields, missing or mistyped arguments, NaN and
  Infinity, duplicate keys and deep nesting are all rejected. Profiles and RAM
  modes are checked against the same lists the web API uses, on both sides:
  the client encodes through the same checks before sending.
- Session: one connection's state machine (hello first, a version mismatch is
  answered then closed, operation errors map to invalid/unavailable/internal,
  a reply that can't be encoded is an internal error, not a dead connection).
- Tests: 15 new (malformed, oversized and unknown input, version mismatch).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 19:17:36 +13:00
paulandClaude Opus 5.5 b983528183 Review fixes: demo fans, record averages and restarts, combined alerts, quiet sensors
- demo.py: FakeBoard grows rpms(). The top fans' stall check (b2da221) called
  it, so under --demo every poll raised AttributeError and the case fans sat
  in CONTROL ERROR at 100%.
- control.py: TopFanCurve.update hands the headers back to the BIOS on any
  failure, a bug included, instead of letting it escape into the case fans'
  loop (unexpected errors are logged with a traceback once). The worker's
  catch-all now fails the top fans safe as well as the case fans, as the
  device-error path already did. The snapshot gives None for a channel whose
  tach has never turned, and the UI says "no tach reading" (and "Channel",
  not "Port") rather than showing SYS_FAN1's unwired tach as a dead fan.
- record.py: an hour's average is over the samples that carried the metric,
  not all of them: a GPU that dropped out for half an hour no longer halves
  its recorded power. Lines carry the count as a fourth number; the reader
  weights by it, and treats three-number lines as before.
- record.py: the hour in progress is checkpointed to records-current.json
  every minute and on close and resumed at start, so a hard stop (schtasks
  /End, the documented restart) loses at most a minute instead of the hour;
  a checkpoint from an earlier hour is written out at start. A failing write
  no longer stops recording for the run: it is logged at most once an hour
  and finished hours wait in memory (up to 48) until the disk works.
- app.py: alerts that start together share one balloon (Windows shows one at
  a time, so each notify() replaced the last), shortened to fit 255
  characters; a problem that clears and comes back balloons again only after
  10 minutes.
- telemetry/service.py: health also counts a source that returns no
  temperature three reads running. GpuSensors and CpuSensors don't raise
  when their device is lost, so a lost GPU driver used to show as healthy.
- hid.py: buffers of IRPs the driver never finished cancelling are kept for
  the life of the process; freeing them with their channel could still let a
  late completion write into reused memory.
- Tests: 13 new (160 pass). README updated to match.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 18:31:11 +13:00
paulandClaude Opus 5.5 8cc1e9223f The sword: tray icon, favicon, header logo and a backdrop for the web UI
- The-Kurgan-Sword.png is the source. kurgan/assets/make_assets.py cleans it
  (drops the white fringe left by the cut-out, smooths the edge to about a
  pixel) and builds everything from it:
  - kurgan/assets/kurgan.ico: the tray icon, 16-256 px, cropped to the
    crossguard; sizes of 32 px and under are brightened a little so the
    metal still reads on a dark taskbar.
  - web/static/favicon.ico: the same crop, 16-48 px.
  - web/static/logo.png: the header logo, the whole sword with the cut-off
    blade faded out.
  - web/static/sword-vertical.png: the whole sword turned 90 degrees
    clockwise.
- tray.py: ICON_PATH replaces the drawn power-tank icon (make_icon is gone).
  app.py already imports ICON_PATH; it went in with f717f7a.
- style.css: the vertical sword is a fixed backdrop below the header, lined
  up with the right edge of the tiles; the cards are 90% opaque so it shows
  through. 90% keeps the grey text at 4.5:1 contrast or better over the
  sword in both themes; 80% dropped it to 3.4:1.
- favicon.svg removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-05 18:25:27 +13:00
paul f717f7a82f Long-term telemetry: hourly rollups in JSONL, a range selector in the UI
- telemetry/record.py: a Recorder subscribed to Telemetry keeps min/avg/max
  per metric for the current hour and appends each finished hour as one JSON
  line to records-YYYY-MM.jsonl in the data dir (~400 days kept; whole months
  older than that are pruned on start). Best effort by design: a failing disk
  logs once and stops recording; nothing else notices. load() merges lines per
  hour (a restart re-writes the current hour; torn last lines are skipped).
- app.py: the recorder runs unless --demo (simulated samples must not mix into
  real records) and flushes the open hour in close(), after the telemetry
  thread has stopped. records(days) validates 1..400.
- Web: GET /api/records?days=N (bad values answer 400 with the reason).
- UI: a range selector above the power/temperature charts switches them
  between the live 10 minutes and hourly averages for 24 h / 7 d / 30 d /
  1 y; the chart window, tick labels (min/h/d), tooltips and table captions
  adapt to the span. Live samples keep accumulating behind a long-range view,
  so switching back is instant.
- Tests: test_record.py (5) and a /api/records case in test_web.py; README
  updated (API table, System section, layout).
2026-12-05 18:04:57 +13:00
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
paul b2da2213b7 Top fans: stall detection from the tach registers, and no manual duty left behind
- control.py: TopFanCurve reads the NCT6687D tach registers while the fans are
  commanded to spin. A channel whose fan was seen turning and then reads 0 RPM
  on three consecutive polls raises everything to 100% and says FAILSAFE. A
  channel whose tach has never been seen turning (SYS_FAN1's is not wired on
  this board) is left alone, so an unwired or empty header cannot cry wolf.
  The latest readings are in the snapshot.
- control.py: CaseFanGroup's stall check now needs three consecutive low
  readings instead of one; a single glitchy RPM no longer forces 100%.
- control.py: when a top-fan write fails, the channels are handed back to the
  BIOS curve at once (best effort); the status says so, or names the duty the
  fans are left at when even the hand-back fails. Previously the UI claimed
  "BIOS curve keeps control" even while the fans sat at a manual duty.
- Tests (three new, one reworked, board doubles given rpms) and README updated
  to match.
2026-12-05 17:32:22 +13:00
paul 8969a57045 AI: never cut a request off mid-reply; bound the logs and the stop path
- service.py: the idle stop's settings write now happens under the same lock
  claim() holds, so a request arriving between the idle check and the write
  can no longer have its selection overwritten and its server stopped under it.
- service.py: _reconcile no longer stops or replaces a server with a request
  in flight, however the switch happens (selecting another backend or None,
  changing Strata's model): the old server finishes its request, and the new
  one does not start until the GPU's memory is free again.
- service.py: an "external" server is only used once a poll has proved the
  program behind its port answers as that server; a port held by something
  else now fails the request saying who holds it, instead of forwarding
  prompts to it.
- strata_host.py: the stop watchdog is real -- if server.main never returns
  within 40 s of the stop request it ends the engine processes and exits,
  instead of relying on interrupt_main() alone (The Kurgan's 45 s kill stays
  as the last resort); the never-read stopping event is gone. It rotates its
  logs at startup: the task log keeps one .prev, the newest seven stdout or
  stderr files per start are kept.
- backends.py: StrataBackend.before_start rotates strata-host.log the way
  LlamaBackend does for llama-server.log.
- tests: five new tests (the two draining guards, external verification,
  both rotations). README updated to match.

VRAM-aware start (the review's "port closed != GPU free, check VRAM before
start") stays a capability idea: no setting knows a model's size to check
free VRAM against.
2026-12-05 17:13:10 +13:00
paul 9036c6e734 Stop presenting stale data as live, and back off broken devices
- readings.py: PowerReadings.total now sums the known parts (None only when
  nothing is known), with a complete property saying whether it under-counts;
  the snapshot exposes it as partial and the web UI marks it with a tilde.
- display/service.py: telemetry older than 15 s is drawn as -- instead of
  re-rendering frozen readings as if they were current.
- sensors.py: Commander PRO last-known RPMs expire after 10 s instead of
  feeding the power model forever (empty list = unknown); a runtime MSR
  failure backs off 15 s instead of re-opening PawnIO every second; GPU NVML
  reconnects back off 10 s instead of nvmlInit() every second, and the
  sample-buffer timestamp resets on a driver-reset reconnect.
- control.py: CpuTemperature read failures back off 15 s instead of churning
  the MSR handle every poll.
2026-12-05 16:54:01 +13:00
65 changed files with 5387 additions and 616 deletions

No files matched your search

+176 -64
View File
@@ -1,19 +1,39 @@
# The Kurgan
One process that runs this PC's backend systems, with one web UI at **<http://127.0.0.1:8080/>**:
![The Kurgan's sword](kurgan/assets/sword.png)
Runs this PC's backend systems, with one web UI at **<http://127.0.0.1:8080/>**:
| Capability | What it does | Package |
| --- | --- | --- |
| Telemetry | CPU, GPU and whole-PC power readings, once a second, with 10 minutes of history | `kurgan/telemetry` |
| Display | The CPU/GPU/power dashboard on the Thermaltake 3.9" LCD | `kurgan/display` |
| Cooling | Commander PRO case fans and motherboard top fans on selectable profiles | `kurgan/cooling` |
| Cooling | Commander PRO case fans and motherboard top fans on selectable profiles | `kurgan/cooling`, run by `kurgan/hw` |
| Lighting | Case fan, RAM and GPU LEDs: off, temperature or the red side chase | `kurgan/lighting` |
| AI | Serves Strata and llama.cpp at `/strata/v1` and `/llama/v1`, running **one** at a time: a request starts the one it needs, and an unused one stops | `kurgan/ai` |
| Web UI | Control and monitoring for all of the above, plus a JSON API | `kurgan/web` |
It replaces three background programs: the TT LCD Dashboard task, Strata's tray service and
the Qwen4 service (llama.cpp plus its monitor page on port 8084). Sensors are read once and
shared, so the LCD, the fan curves, the lighting and the web UI all use the same readings.
the Qwen4 service (llama.cpp plus its monitor page on port 8084).
## How it's split
Two processes, so that only the part that needs admin rights has them:
- **The hardware service**, "The Kurgan hardware" (`KurganHw`, `kurgan/hw`): a Windows service
running as LocalSystem from boot, before anyone logs on. It does what needs PawnIO, plus what
must never depend on anything else: the case and top fan curves with their fail-safes, the
CPU package temperature and power, the GPU temperature it needs for the curves, and the RAM
lighting. It listens on no network port; its only interface is the named pipe
`\\.\pipe\kurgan-hw`. If it crashes, Windows restarts it after 5 s, 10 s, then 60 s.
- **The app**, "The Kurgan" (`python -m kurgan`): everything else, without admin rights, from a
logon task: the web UI, the AI servers (as its own children), telemetry, the LCD, the case fan
and GPU lighting, and the tray icon. It shows what the hardware service reports and asks it
for profile and RAM lighting changes. While the service is unavailable the app says so (UI,
tray balloon) and carries on without those readings.
Restarting or killing the app never touches the fans. Sensors the app reads itself are read
once and shared, so the LCD, the lighting and the web UI all use the same readings.
## Setup
@@ -21,50 +41,82 @@ shared, so the LCD, the fan curves, the lighting and the web UI all use the same
powershell -ExecutionPolicy Bypass -File .\setup.ps1 -RetireAIServices
```
This does the following:
Run it from a normal (not elevated) PowerShell window; it asks for admin rights itself. It:
- Installs the Python packages into the project's `.venv` (or for the current user).
- Installs the Python packages into the project's `.venv` (creating it if needed; the hardware service runs from it too).
- Installs [PawnIO](https://pawnio.eu). PawnIO is the signed driver LibreHardwareMonitor and FanControl also use. It reads the Intel CPU sensors and drives the motherboard fan headers and the RAM lighting.
- Replaces the old **TT LCD Dashboard** task with a **The Kurgan** scheduled task. The task runs `pythonw -m kurgan` hidden, with admin rights, at every logon.
- Installs or updates the **The Kurgan hardware** service (`KurganHw`): LocalSystem, automatic start, restart on failure. It runs the base Python interpreter (not the venv's `python.exe`, a redirector) on `hw_service.py`, after checking that it can.
- Creates `%ProgramData%\Kurgan` (Administrators and SYSTEM write, users read) and, once, moves the fan settings and the RAM lighting mode from your `settings.json` into `hw-settings.json` there. `settings.json` keeps a dated `.bak` copy from before.
- Replaces the old **TT LCD Dashboard** task (and an older, elevated **The Kurgan** task) with a **The Kurgan** scheduled task, registered as you. The task runs `pythonw -m kurgan` hidden, without admin rights, at every logon.
- Prints what the hardware service reports (`python -m kurgan.hw.client` does that any time).
Run `setup.ps1` again after updating The Kurgan: it stops, updates and restarts both parts.
**Updating from the elevated version:** run `setup.ps1` before restarting the old elevated
"The Kurgan" task with this code. Until then there's no hardware service: the new app would
have no fan control to show, and (being elevated) it refuses to start the AI servers.
`-RetireAIServices` stops and disables the **Strata Local Service** and **Qwen4 Local Service**
tasks, so The Kurgan can run whichever server you select. Without that switch, The Kurgan finds
those servers already listening on their ports. It shows them as "running outside The Kurgan"
and monitors them, but it never starts a second copy.
and monitors them, but it never starts a second copy. Requests go to one only once it answers
as the expected server; a port held by some other program is reported, not served.
`uninstall.ps1` removes the task. `uninstall.ps1 -RestoreAIServices` also re-enables and starts
the two LLM service tasks. `-RemovePawnIO` uninstalls PawnIO.
`uninstall.ps1` removes the task and the hardware service (stopping it leaves the case fans at
100% and the top fans on the BIOS curve). `uninstall.ps1 -RestoreAIServices` also re-enables and
starts the two LLM service tasks. `-RemovePawnIO` uninstalls PawnIO. Settings stay in
`%LOCALAPPDATA%\Kurgan` and `%ProgramData%\Kurgan`.
Admin rights are needed for these readings and controls:
### Security model
- CPU temperature and power
- The motherboard top fans
- The RAM lighting
Without admin rights those show `--` or stay idle, and everything else works. The LLM servers
always run as a normal user at medium integrity, never elevated, even though The Kurgan itself
is elevated (see `kurgan/ai/launcher.py`). The web UI shows each server's integrity level.
- **Only the hardware service has admin rights**, and it has no network interface. Its pipe
allows SYSTEM, Administrators and the user who ran `setup.ps1` (read and write, but not
creating pipe instances, so nothing running as you can impersonate the service's end), and
refuses remote clients. It accepts five operations (`hello`, `state`, `set_profile`,
`set_ram_lighting`, `ram_chase`), checked strictly, in messages of at most 64 KiB; a client
silent for 30 s is dropped, and no client can hold up the fan loop. The app checks that the
pipe belongs to SYSTEM or Administrators before using it.
- **The app runs without admin rights**: the web UI (127.0.0.1 only), the proxy, and the LLM
servers, which are its own children in job objects at medium integrity. If the app is ever
started elevated it refuses to start them rather than pass admin rights on (see
`kurgan/ai/launcher.py`); the UI then warns "Running elevated", and shows each server's
integrity level. Anything running as you can use the web API, and through it (or the pipe)
change the fan profile and the RAM lighting, nothing more.
- **Not a boundary against malware running as you.** The service runs code from this repo and
the Python install in your profile, both of which you (and so anything running as you) can
change; the change would run as SYSTEM at the service's next start. That is the trust the
old elevated logon task had, at a higher level. A real boundary would need the service's code
and interpreter in an admin-only folder; that's not done.
## Web UI
Open it from the tray icon (left-click, or **Open The Kurgan** in its menu) or browse to
<http://127.0.0.1:8080/>. It only listens on 127.0.0.1. The page refreshes once a second while it
is visible. Every chart has a **Table** button that shows the same numbers as a table.
is visible. Every chart has a **Table** button that shows the same numbers as a table. The tray
icon also pops a balloon tip when something starts to go wrong — a fan group entering failsafe,
an AI server reporting an error, a sensor source starting to fail, or the hardware service
becoming unavailable. Problems that start together
share one balloon (Windows shows one at a time), and a problem that clears and comes back
balloons again only after 10 minutes. What is already wrong when The Kurgan starts is not
ballooned; it sits in the tray menu and the UI. The header shows whether the hardware service
is reachable (hover for its version and uptime, or why not).
- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes.
- **Cooling**: the fan profile selector; each fan group's duty, temperature and RPMs; fan speeds over time; and the selected profile's curves, with a dot for each group's current operating point. Hover over a profile to preview its curves.
- **System**: CPU and GPU temperature, load, clock and power; GPU memory; the LCD's state. Charts show whole-PC power (stacked: other, CPU, GPU) and temperatures over the last 10 minutes. A range selector above the charts switches them to hourly averages for 24 hours, 7 days, 30 days or a year. Those long-term rollups live in `%LOCALAPPDATA%\Kurgan\records-YYYY-MM.jsonl` — one JSON line per hour with min, average and max per metric (the average only over the samples that had the metric), about 400 days kept. The hour in progress is checkpointed to `records-current.json` every minute and on exit and resumed at the next start, so a restart — even `schtasks /End` — loses at most a minute. Writing is best effort: a failing disk is logged at most once an hour, and finished hours wait in memory (up to two days) until it works again. `--demo` never records. When a sensor source is failing — its read raised, or it has returned no temperature three times in a row (a lost GPU driver, an unavailable MSR reader) — a pill in the header names it and hover shows the error.
- **Cooling**: the fan profile selector; each fan group's duty, temperature and RPMs; fan speeds over time; and the selected profile's curves, with a dot for each group's current operating point. Hover over a profile to preview its curves. All of it comes from the hardware service, and a profile change goes to it.
- **Lighting**: a mode selector per zone (case fans, RAM, GPU), the zone's status, and the shared chase speed.
- **AI**: pick Strata (and its model), llama.cpp or None; requests to either address also pick it. Then see the server's process, model, context size, live request progress and token speeds, and when it will stop if unused; load or unload the model; GPU memory over time; and recent requests.
Every choice is saved immediately in `%LOCALAPPDATA%\Kurgan\settings.json` and restored at the
next start.
Every choice is saved immediately and restored at the next start: the fan profile and the RAM
lighting by the hardware service in `%ProgramData%\Kurgan\hw-settings.json`, the rest in
`%LOCALAPPDATA%\Kurgan\settings.json`.
### JSON API
| Request | Body / result |
| --- | --- |
| `GET /api/state` | Everything live (what the UI polls) |
| `GET /api/state` | Everything live (what the UI polls), including `telemetry.health`: the sensor sources that are failing (latest read raised, or no temperature three reads running), each with its error and age |
| `GET /api/history` | The last 10 minutes of telemetry and fan duty |
| `GET /api/records?days=N` | Hourly min/avg/max rollups for the last N days (1-400), oldest first |
| `GET /api/config` | Fan profiles and LCD theme thresholds |
| `POST /api/lighting` | `{"zone": "case_fans"\|"memory"\|"gpu", "mode": "off"\|"temperature"\|"chase"}` |
| `POST /api/cooling/profile` | `{"profile": "quiet"\|"balanced"\|"performance"\|"full"}` |
@@ -76,6 +128,8 @@ POSTs to `/api/...` need `Content-Type: application/json` and an `X-Kurgan: 1` h
site can't send that header without a CORS preflight, which this server never answers. Requests
must also name `127.0.0.1:<port>` or `localhost:<port>` as the Host, which blocks DNS rebinding.
There is no other authentication: any program already running on this PC as you can use the API.
`POST /api/cooling/profile`, and `/api/lighting` for the RAM, answer **503** while the hardware
service can't be reached (or can't save the change).
```powershell
curl.exe -s -X POST -H "Content-Type: application/json" -H "X-Kurgan: 1" `
@@ -84,22 +138,35 @@ curl.exe -s -X POST -H "Content-Type: application/json" -H "X-Kurgan: 1" `
## Settings
`%LOCALAPPDATA%\Kurgan\settings.json`, created on the first start:
The app's: `%LOCALAPPDATA%\Kurgan\settings.json`, created on the first start:
```json
{
"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]},
"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}
}
```
On the first start, The Kurgan imports the TT LCD Dashboard's fan ports and RAM and GPU lighting
modes from `%LOCALAPPDATA%\TTLcdDashboard`. The old task's `--rgb-side-chase` becomes
`case_fans: chase`. The file is checked strictly. An invalid file stops The Kurgan with a message,
rather than starting without fan control. A failed save leaves the previous setting in place,
both in memory and on disk.
The hardware service's: `%ProgramData%\Kurgan\hw-settings.json` (admins write, users read):
```json
{
"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]},
"lighting": {"memory": "off"}
}
```
Both files are checked strictly, and a failed save leaves the previous setting in place, both in
memory and on disk. An invalid `settings.json` stops the app with a message. An invalid
`hw-settings.json` doesn't stop the service: it holds every case fan at 100% and says why in the
UI's cooling section; fix the file and `Restart-Service KurganHw` (elevated). A `settings.json`
from before the split may still hold `cooling` and `lighting.memory`: they're checked and kept,
but nothing uses them (`setup.ps1` moves them).
On the first start, The Kurgan imports the TT LCD Dashboard's settings from
`%LOCALAPPDATA%\TTLcdDashboard` into `settings.json` (`setup.ps1` then moves the fan and RAM
parts). The old task's `--rgb-side-chase` becomes `case_fans: chase`.
`idle_stop_minutes` is how long a server may go unused before The Kurgan stops it (0 = never,
up to 1440). The `ai` section also accepts these optional keys, for when an install moves:
@@ -110,9 +177,12 @@ up to 1440). The `ai` section also accepts these optional keys, for when an inst
See `kurgan/ai/config.py`. Restart The Kurgan after editing the file by hand.
Command-line lighting options such as `--rgb-side-chase` apply to that run only. The UI marks
them "this run only"; choosing a mode in the UI saves it.
them "this run only"; choosing a mode in the UI saves it. The RAM has none: it's the hardware
service's, and only the UI changes it.
Log: `%LOCALAPPDATA%\Kurgan\kurgan.log`
Logs: `%LOCALAPPDATA%\Kurgan\kurgan.log` (the app), `%ProgramData%\Kurgan\kurgan-hw.log` (the
hardware service; it logs each change of a fan group's status, which carries its temperature,
duty and speeds, so it shows fan control running even before logon).
## AI: Strata and llama.cpp
@@ -133,6 +203,9 @@ server it is addressed to. If the other server is running, it is stopped first:
cutting it off.
- Stopping means stopping completely: every process in its job object has ended and its port
has closed. Only then does the other server start.
- A server with a request in flight is never stopped or replaced mid-reply, however the switch
happens: the old server finishes its request first, and the new one doesn't start until the
GPU's memory is free again.
- A request that has to start its server waits for it. A swap takes a few seconds, plus the model's
load time (about 45 s for either model). Give clients a generous timeout.
@@ -162,10 +235,12 @@ Strata's optional API-monitor page (`/api-monitor`) uses absolute paths, so it d
Both start with no model in memory. The model loads on the first request, or when you press
**Load model**. Strata unloads it after 2000 s idle; llama.cpp sleeps after its preset's idle
time. Strata is stopped gracefully through a named event, and gets 45 s to finish. llama.cpp
is ended through its job object. Each server gets the same environment its own service gave it:
Strata runs with `GGML_CUDA_DISABLE_GRAPHS=1`, and llama.cpp runs without it. Both use OpenBLAS's
default threading, not the single-thread pin The Kurgan uses for itself.
time. Strata is stopped gracefully through a named event, and gets 45 s to finish; if the server
somehow never returns from that, it ends its engine processes and exits by itself after 40 s
(The Kurgan's kill stays as the last resort). llama.cpp is ended through its job object. Each
server gets the same environment its own service gave it: Strata runs with
`GGML_CUDA_DISABLE_GRAPHS=1`, and llama.cpp runs without it. Both use OpenBLAS's default
threading, not the single-thread pin The Kurgan uses for itself.
Live progress comes from different places:
@@ -174,8 +249,10 @@ Live progress comes from different places:
Logs:
- `%LOCALAPPDATA%\Kurgan\logs\strata-host.log`, plus Strata's own `D:\AI\Strata\logs\local-service-*.log`
- `%LOCALAPPDATA%\Kurgan\logs\llama-server.log` (the previous run's log is kept as `.prev`)
- `%LOCALAPPDATA%\Kurgan\logs\strata-host.log` and `llama-server.log` (each keeps the previous
run's log as `.prev`)
- Strata's own `D:\AI\Strata\logs\local-service-*.log`: the task log keeps one `.prev`, and the
newest seven stdout/stderr pairs are kept
A server that exits on its own is restarted after 5 seconds. After 5 exits within 5 minutes,
The Kurgan waits 5 minutes before trying again, and the UI shows why.
@@ -205,7 +282,10 @@ every profile:
- Fans run at 100% on start-up.
- They run at 100% after a polling gap of over 5 seconds.
- They run at 100% when a temperature is missing or invalid.
- A group runs at 100% when one of its fans is below 200 RPM after its 10-second spin-up.
- A group runs at 100% when one of its fans reads below 200 RPM on three consecutive polls
after its 10-second spin-up; a single glitchy reading doesn't count.
- The top fans run at 100% when a fan that was seen turning then reads 0 RPM on three
consecutive polls.
- The top fans are held at 100% while either case-fan group runs at 85% or more. They are released once both groups are at 65% or less.
### Ports and channels
@@ -216,10 +296,11 @@ On this machine, identification confirmed these mappings:
- The two top extractors are on **SYS_FAN1 and SYS_FAN4** (NCT6687D PWM channels 2 and 5).
- The CPU cooler is on CPU_FAN1 (channel 0), which is never touched.
The mapping is in `settings.json`. To identify or change it, first exit The Kurgan from its
tray menu, then run:
The mapping is in `hw-settings.json`. To identify or change it, from an elevated PowerShell,
stop the hardware service (the case fans go to 100%), run the tools, then start it again:
```powershell
Stop-Service KurganHw
.\.venv\Scripts\python.exe -m kurgan.cooling.control --identify 1,2,3 # these ports to 100%; watch which side speeds up
.\.venv\Scripts\python.exe -m kurgan.cooling.control --save-ports 4,5,6 # GPU side
.\.venv\Scripts\python.exe -m kurgan.cooling.control --save-cpu-ports 1,2,3 # CPU side (GPU side first)
@@ -227,37 +308,44 @@ tray menu, then run:
.\.venv\Scripts\python.exe -m kurgan.cooling.board_fans --identify 2,5 # hold channels at 100% (admin)
.\.venv\Scripts\python.exe -m kurgan.cooling.board_fans --auto 2,5 # hand them back to the BIOS (admin)
.\.venv\Scripts\python.exe -m kurgan.cooling.control --save-top-channels 2,5
Start-Service KurganHw
```
`--identify` leaves the selected group at 100%, rather than guessing its previous profile. Do not
guess the port mapping. `--gpu-fan-ports 4,5,6` overrides the saved ports for one run, and
`--no-gpu-fan-control` turns fan control off for one run.
guess the port mapping. (The app's old `--gpu-fan-ports` and `--no-gpu-fan-control` options are
gone: the hardware service owns the fans and reads the mapping from its own settings.)
**Controller ownership:** exit iCUE, FanControl and other Commander PRO tools. If you run OpenRGB,
disable its **Corsair Commander Pro** and **Corsair Lighting Node Core** detectors in both
`%APPDATA%\OpenRGB\OpenRGB.json` and `C:\Program Files\OpenRGB\service_config\OpenRGB.json`. While
another tool has a device, The Kurgan leaves that device alone and says so in the UI. The top fans
share LibreHardwareMonitor's ISA-bus mutex, so don't let another tool control the same headers.
On exit the case fans are left at 100% and the top fans go back to the BIOS Smart Fan curve.
When the hardware service stops (including at shutdown), the case fans are left at 100% and the
top fans go back to the BIOS Smart Fan curve.
This is software control, not a hardware thermal safeguard. It can't guarantee a speed change
after a USB failure, a forced process kill or a system hang, and the Commander PRO may keep its
last duty. Verify temperatures and fan rotation under your real workloads. Only SYS_FAN4 reports
RPM, so there is no stall detection on the top fans.
after a USB failure, a forced kill of the hardware service or a system hang, and the Commander
PRO keeps its last duty until the service is back (Windows restarts it within seconds). If a top-fan write fails, The Kurgan hands those headers back to the BIOS curve at
once; if even that fails, the UI says what duty they are left at. Verify temperatures and fan
rotation under your real workloads. Only SYS_FAN4's tach is wired to the EC, so top-fan stall
detection covers that fan only: a channel whose tach has never been seen turning is left alone
rather than crying wolf, and the UI shows "no tach reading" for it instead of 0 rpm. If the
top-fan code fails in any unexpected way, those headers go back to the BIOS curve and the case
fans carry on; if the case fans' control loop itself hits an unexpected error, all fans go to 100%.
## Lighting
| Zone | Device | Modes |
| --- | --- | --- |
| Case fans | Corsair Lighting Node CORE (`1B1C:0C1A`), six QL120 fans on header 1 | off, temperature, red side chase |
| RAM | Four Corsair Dominator Platinum DDR5 sticks, over the Intel SMBus through PawnIO (admin) | off, temperature, red side chase |
| RAM | Four Corsair Dominator Platinum DDR5 sticks, over the Intel SMBus through PawnIO (driven by the hardware service) | off, temperature, red side chase |
| GPU | ASUS ROG STRIX RTX 4090 LED row, over NVIDIA's `nvapi64.dll` | off, red side chase |
- **Off**: the case fans return to the CORE's own hardware effect. The RAM is held dark while The Kurgan runs; black frames are refreshed every 5 s, and the stored effects are untouched. The GPU's previous direct colours and mode are restored.
- **Temperature**:
- Case fans: the CPU-side fans follow CPU temperature and the GPU-side fans follow GPU temperature. They are green below `--temp-warn` (50 C), yellow up to `--temp-hot` (80 C), and red above.
- RAM: the hotter of CPU and GPU blends from dark red `(24, 0, 0)` to warm orange `(255, 48, 0)`.
- **Red side chase**: warm-orange heads with four fading trail LEDs over dark red. All three zones share one power-paced clock, so they stay in step. The pace is 150 ms per LED at 150 W or less, speeding up evenly to 25 ms at 550 W or more (`--rgb-chase-*`).
- RAM: the hotter of CPU and GPU blends from dark red `(24, 0, 0)` to warm orange `(255, 48, 0)`, between 50 C and 80 C (the hardware service's fixed range; `--temp-warn` and `--temp-hot` don't reach it).
- **Red side chase**: warm-orange heads with four fading trail LEDs over dark red. All three zones share one power-paced clock, so they stay in step: the app sends it to the hardware service for the RAM once a second. The pace is 150 ms per LED at 150 W or less, speeding up evenly to 25 ms at 550 W or more (`--rgb-chase-*`).
- Case fans: the CPU route is bottom → middle → top → middle, and the GPU side is mirrored.
- RAM: two mirrored heads visit sticks 4 → 3 → 2 → 1 → 2 → 3 once per fan cycle.
- GPU: one head runs front to back and back again once per cycle.
@@ -275,11 +363,13 @@ Calibrated case-fan outer-ring indices (zero-based within each 34-LED fan: hub 0
| 6 | CPU middle | 19 / 20 |
The CORE needs a keep-alive every 5 seconds or it drops back to its hardware effect. Updates on
every device are capped at about 22 per second. The CORE and the LCD share a Genesys USB 2.0 hub,
and heavier traffic once hung the LCD firmware until it was power-cycled. If the LCD repeatedly
reports a handshake timeout (opcode `0x85`), set the case fans to off. Then safely power-cycle
the LCD and check the cable, power and hub routing before re-enabling the chase. Do not unplug
internal cables while the PC is powered.
every device are capped at about 22 per second. The CORE and the LCD used to share a Genesys
USB 2.0 hub, and heavier traffic once hung the LCD firmware until it was power-cycled. The LCD is
now on a back-panel port, directly on the Intel root hub; the CORE shares the Genesys hub
(`05E3:0610`, then `05E3:0608`) with the Commander PRO, which sends little. The cap stays as a
margin. If the LCD repeatedly reports a handshake timeout (opcode `0x85`), set the case fans to
off. Then safely power-cycle the LCD and check the cable, power and hub routing before
re-enabling the chase. Do not unplug internal cables while the PC is powered.
The RAM controllers are at `0x18`-`0x1B`, top to bottom. They are written directly over SMBus
with PawnIO's I801 module (PawnIO Modules 0.2.12; its LGPL source and licence are in
@@ -318,12 +408,12 @@ All figures are DC watts, i.e. load on the power supply; wall draw is roughly 8
| Part | Source |
| --- | --- |
| CPU | Measured: the package's energy counter (RAPL), via PawnIO |
| CPU | Measured: the package's energy counter (RAPL), via PawnIO, read by the hardware service |
| GPU | Measured: board power from NVIDIA (the whole card, including its fans and lighting) |
| CPU regulator losses | Derived: CPU watts × 11% |
| Memory | Estimated per module (4 × DDR5): 2.5 W idle to 5.5 W, scaled by CPU load |
| Drives | Estimated from each drive's activity and rated power (Lexar NQ790 3.5 W, Kingston KC3000 8.8 W; the USB hard drive as bus-powered, spun down after 10 minutes idle) |
| Case fans | Estimated from the Commander PRO's fan speeds (about 2 W per fan at 1500 rpm) |
| Case fans | Estimated from the Commander PRO's fan speeds, read by the hardware service (about 2 W per fan at 1500 rpm) |
| Motherboard & chipset | Fixed 15 W |
| Motherboard-header fans/pump | Fixed 5 W |
| USB devices & RGB lighting | Fixed 12 W |
@@ -332,22 +422,36 @@ The estimates are in `PowerModel` in `kurgan/telemetry/sensors.py`.
## Running by hand
The app (no admin rights needed; the hardware service keeps running):
```powershell
Stop-ScheduledTask "The Kurgan" # only one copy runs at a time
.\.venv\Scripts\python.exe -m kurgan # console, Ctrl+C to stop
.\.venv\Scripts\python.exe -m kurgan --preview x.png # render one LCD frame from live sensors
$env:KURGAN_DATA_DIR = "$env:TEMP\kurgan-demo"
.\.venv\Scripts\python.exe -m kurgan --demo --port 18080 # simulated hardware; separate settings
Start-ScheduledTask "The Kurgan" # back to the hidden, elevated copy
Start-ScheduledTask "The Kurgan" # back to the hidden copy
```
In demo mode the LLM servers use ports 18082 and 18083, but they are real servers.
The hardware service (elevated PowerShell for all but the first line):
```powershell
.\.venv\Scripts\python.exe -m kurgan.hw.client # is it reachable, and what is it doing?
Restart-Service KurganHw # e.g. after editing hw-settings.json
Stop-Service KurganHw # case fans to 100%, top fans to the BIOS
& (.\.venv\Scripts\python.exe -c "import sys; print(sys._base_executable)") -I -S -B .\hw_service.py -v # in a console instead
Start-Service KurganHw
```
In demo mode the hardware service runs inside the app on simulated devices, with its settings in
`demo-hw-settings.json` in the demo's data folder. The LLM servers use ports 18082 and 18083, but
they are real servers.
`python -m kurgan --help` lists the LCD and lighting options. To make one permanent, add it to the
task's arguments. Lighting modes are better chosen in the UI.
| Tool | Use |
| --- | --- |
| `python -m kurgan.telemetry.sensors` | Print the live readings and power breakdown (exit The Kurgan first: one program at a time should poll the Commander PRO) |
| `python -m kurgan.telemetry.sensors` | Print the live readings and power breakdown (elevated, with the hardware service stopped: one program at a time should poll the Commander PRO) |
| `python -m kurgan.display.renderer demo.png` | Render the LCD with fixed demo values |
| `python -m kurgan.display.tt_lcd` | LCD test card |
| `python -m kurgan.tray` | Show a test tray icon for 20 seconds |
@@ -361,14 +465,22 @@ kurgan/
app.py wires the capabilities together; command line; single instance
settings.py settings.json: defaults, strict validation, atomic saves, legacy import
paths.py, theme.py, tray.py, demo.py (simulated hardware for --demo)
telemetry/ sensors.py (CPU/GPU/system power), readings.py, service.py (sampling + history)
telemetry/ sensors.py (CPU/GPU/system power), readings.py, service.py (sampling + history),
record.py (hourly rollups for the long-term charts)
display/ tt_lcd.py (panel HID protocol), renderer.py, service.py (LCD loop), background.png
cooling/ profiles.py, control.py (case-fan groups, top-fan curve), board_fans.py (NCT6687D)
lighting/ case_fans.py (CORE patterns + shared chase clock), lighting_node.py, memory.py, gpu.py, service.py
ai/ config.py, launcher.py (non-elevated child processes in job objects),
backends.py (Strata, llama.cpp), service.py (one-at-a-time supervisor), strata_host.py
web/ server.py (API), static/ (index.html, app.js, style.css)
web/ server.py (API), static/ (index.html, app.js, style.css, logo.png, favicon.ico)
assets/ sword.png, hilt.png, kurgan.ico (tray icon); make_assets.py rebuilds them and the
web UI's logo and favicon from The-Kurgan-Sword.png
hardware/ hid.py (Windows HID), pawnio/ (signed PawnIO modules, LGPL-2.1)
hw/ the hardware service: protocol.py, pipe.py (access-controlled named pipe),
service.py (fan loop, RAM lighting, state), main.py, winservice.py (pywin32 host),
settings.py (hw-settings.json), install.py and migrate.py (setup.ps1),
client.py (the app's side)
hw_service.py the hardware service's entry point (what the service manager runs)
tests/ unittest suites
docs/ design references and research notes
lcd_dashboard.py compatibility shim for the old "TT LCD Dashboard" task until setup.ps1 is re-run
Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

+25
View File
@@ -0,0 +1,25 @@
"""Entry point of the "The Kurgan hardware" Windows service (KurganHw); see kurgan/hw/winservice.py.
The service manager runs it with the base interpreter (setup.ps1 installs it):
"<base Python>\\python.exe" -I -S -B "C:\\Dev\\the_kurgan\\hw_service.py"
-I: isolated (no PYTHON* variables, no user site-packages, no current folder on the path);
-S: no automatic site-packages; -B: no .pyc files written into the repo by SYSTEM. This file
adds the repo and its .venv's packages, so the base interpreter's own packages are never loaded.
... hw_service.py --check can the service start? (setup.ps1 runs this before installing)
... hw_service.py [-v] run it in a console instead (elevated, with the service stopped)
"""
import os
import site
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
site.addsitedir(os.path.join(HERE, ".venv", "Lib", "site-packages")) # runs pywin32's .pth bootstrap
from kurgan.hw.winservice import main # noqa: E402
sys.exit(main())
+10
View File
@@ -202,6 +202,16 @@ class StrataBackend(Backend):
finally:
_k32.CloseHandle(handle)
def before_start(self) -> None:
# The launcher appends; keep one previous run's log, as LlamaBackend does for its own.
os.makedirs(LOG_DIR, exist_ok=True)
try:
path = os.path.join(LOG_DIR, "strata-host.log")
if os.path.exists(path):
os.replace(path, os.path.join(LOG_DIR, "strata-host.prev.log"))
except OSError as e:
log.warning("Could not rotate strata-host.log: %s", e)
def _url(self, path: str) -> str:
return f"http://127.0.0.1:{self.port}{path}"
+24 -144
View File
@@ -1,22 +1,14 @@
"""Start the AI servers as ordinary, non-elevated processes, even though The Kurgan runs elevated.
"""Start the AI servers as ordinary child processes, each in its own job object.
The Kurgan needs admin rights for PawnIO (CPU sensors, top fans, RAM lighting), but the LLM
servers never did: they ran from non-elevated tasks before. How a server is started:
- The Kurgan elevated (the normal case): with a copy of the desktop shell's (Explorer's) own
token, through CreateProcessWithTokenW. The server is then exactly what Explorer would have
started: medium integrity, not elevated, in the desktop's logon session.
- No desktop shell yet (just after logon; see desktop_ready) or The Kurgan not elevated (tests,
--demo): a "normal user" token from the Safer API (Administrators made deny-only, admin
privileges removed, medium integrity). Windows still counts that token as part of the elevated
logon session, so the shell's token is preferred.
The Kurgan runs without admin rights (only the hardware service, kurgan.hw, is elevated), so
its children are what any program the user starts would be: medium integrity, not elevated,
in the desktop's logon session. launch() refuses to start anything if The Kurgan itself has
been run elevated, rather than hand a model server admin rights.
Each server gets its own job object that kills everything in it when The Kurgan closes the
job, including the model processes the server starts itself; a crashed Kurgan leaves no
orphan holding VRAM or a port. stdout/stderr go to a log file. The Safer path passes an explicit
handle list, so only the log and NUL handles are inherited. CreateProcessWithTokenW can't take
one; Python makes its handles non-inheritable, and launches are serialised, so in practice the
same two are all the child gets.
orphan holding VRAM or a port. stdout/stderr go to a log file, and an explicit handle list
means the log and NUL handles are all the child inherits.
"""
from __future__ import annotations
@@ -33,13 +25,8 @@ log = logging.getLogger(__name__)
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
SAFER_SCOPEID_USER = 2
SAFER_LEVELID_NORMALUSER = 0x20000
SAFER_LEVEL_OPEN = 1
TOKEN_INTEGRITY_LEVEL = 25
TOKEN_ELEVATION = 20
SE_GROUP_INTEGRITY = 0x20
MEDIUM_INTEGRITY_SID = "S-1-16-8192"
CREATE_SUSPENDED = 0x4
CREATE_NEW_PROCESS_GROUP = 0x200
@@ -61,9 +48,6 @@ WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
STILL_ACTIVE = 259
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
TOKEN_QUERY = 0x8
TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_ADJUST_DEFAULT, TOKEN_ADJUST_SESSIONID = 0x1, 0x2, 0x80, 0x100
SECURITY_IMPERSONATION, TOKEN_PRIMARY = 2, 1
ERROR_INVALID_PARAMETER = 87
class SecurityAttributes(ctypes.Structure):
@@ -105,18 +89,6 @@ class ExtendedLimits(ctypes.Structure):
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
_adv.SaferCreateLevel.argtypes = [wt.DWORD, wt.DWORD, wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.LPVOID]
_adv.SaferCreateLevel.restype = wt.BOOL
_adv.SaferComputeTokenFromLevel.argtypes = [wt.HANDLE, wt.HANDLE, ctypes.POINTER(wt.HANDLE), wt.DWORD, wt.LPVOID]
_adv.SaferComputeTokenFromLevel.restype = wt.BOOL
_adv.SaferCloseLevel.argtypes = [wt.HANDLE]
_adv.SaferCloseLevel.restype = wt.BOOL
_adv.ConvertStringSidToSidW.argtypes = [wt.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)]
_adv.ConvertStringSidToSidW.restype = wt.BOOL
_adv.GetLengthSid.argtypes = [ctypes.c_void_p]
_adv.GetLengthSid.restype = wt.DWORD
_adv.SetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD]
_adv.SetTokenInformation.restype = wt.BOOL
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)]
_adv.GetTokenInformation.restype = wt.BOOL
_adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
@@ -125,11 +97,6 @@ _adv.GetSidSubAuthority.argtypes = [ctypes.c_void_p, wt.DWORD]
_adv.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD)
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
_adv.OpenProcessToken.restype = wt.BOOL
_adv.CreateProcessAsUserW.argtypes = [wt.HANDLE, wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD,
wt.LPVOID, wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
_adv.CreateProcessAsUserW.restype = wt.BOOL
_k32.LocalFree.argtypes = [wt.HLOCAL]
_k32.LocalFree.restype = wt.HLOCAL
_k32.CloseHandle.argtypes = [wt.HANDLE]
_k32.CloseHandle.restype = wt.BOOL
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD,
@@ -158,18 +125,10 @@ _k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_s
_k32.UpdateProcThreadAttribute.restype = wt.BOOL
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
_k32.DeleteProcThreadAttributeList.restype = None
_k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD]
_k32.OpenProcess.restype = wt.HANDLE
_k32.GetCurrentProcess.restype = wt.HANDLE
_adv.DuplicateTokenEx.argtypes = [wt.HANDLE, wt.DWORD, wt.LPVOID, ctypes.c_int, ctypes.c_int, ctypes.POINTER(wt.HANDLE)]
_adv.DuplicateTokenEx.restype = wt.BOOL
_adv.CreateProcessWithTokenW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPCWSTR, wt.LPWSTR, wt.DWORD, wt.LPVOID, wt.LPCWSTR,
ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
_adv.CreateProcessWithTokenW.restype = wt.BOOL
_u32 = ctypes.WinDLL("user32", use_last_error=True)
_u32.GetShellWindow.restype = wt.HWND
_u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)]
_u32.GetWindowThreadProcessId.restype = wt.DWORD
_k32.CreateProcessW.argtypes = [wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD, wt.LPVOID,
wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
_k32.CreateProcessW.restype = wt.BOOL
_launch_lock = threading.Lock()
@@ -180,31 +139,6 @@ def _check(ok, what: str):
return ok
def _normal_user_token() -> wt.HANDLE:
"""A primary token like this process's, minus admin rights, at medium integrity."""
level, token = wt.HANDLE(), wt.HANDLE()
_check(_adv.SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN,
ctypes.byref(level), None), "SaferCreateLevel")
try:
_check(_adv.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None),
"SaferComputeTokenFromLevel")
finally:
_adv.SaferCloseLevel(level)
sid = ctypes.c_void_p()
try:
_check(_adv.ConvertStringSidToSidW(MEDIUM_INTEGRITY_SID, ctypes.byref(sid)), "ConvertStringSidToSid")
label = SidAndAttributes(sid, SE_GROUP_INTEGRITY)
_check(_adv.SetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, ctypes.byref(label),
ctypes.sizeof(label) + _adv.GetLengthSid(sid)), "SetTokenInformation")
except OSError:
_k32.CloseHandle(token)
raise
finally:
if sid:
_k32.LocalFree(sid)
return token
def _describe_token(token: wt.HANDLE) -> dict:
size = wt.DWORD()
_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size))
@@ -241,46 +175,6 @@ def elevated() -> bool:
return _ELEVATED
def _desktop_token() -> wt.HANDLE | None:
"""A primary copy of the desktop shell's token, or None if there is no (non-elevated) shell."""
hwnd = _u32.GetShellWindow()
if not hwnd:
return None
pid = wt.DWORD()
_u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid))
process = _k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value)
if not process:
return None
shell, token = wt.HANDLE(), wt.HANDLE()
try:
if not _adv.OpenProcessToken(process, TOKEN_DUPLICATE | TOKEN_QUERY, ctypes.byref(shell)):
return None
try:
_check(_adv.DuplicateTokenEx(shell, TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE
| TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, None,
SECURITY_IMPERSONATION, TOKEN_PRIMARY, ctypes.byref(token)),
"DuplicateTokenEx")
finally:
_k32.CloseHandle(shell)
finally:
_k32.CloseHandle(process)
if _describe_token(token)["elevated"]: # someone runs Explorer elevated: no better than our own
_k32.CloseHandle(token)
return None
return token
def desktop_ready() -> bool:
"""True once servers can be started with the desktop's own token (always true when not elevated)."""
if not elevated():
return True
token = _desktop_token()
if token is None:
return False
_k32.CloseHandle(token)
return True
def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE:
sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True)
handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None)
@@ -360,15 +254,17 @@ class ChildProcess:
def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None,
contained: bool = True) -> ChildProcess:
"""Start argv as a normal user, windowless, with stdout/stderr appended to log_path (None: discarded).
"""Start argv windowless, with stdout/stderr appended to log_path (None: discarded).
contained: put it in its own kill-on-close job (servers). Without it the process outlives
the returned handle (used to open the browser)."""
the returned handle (used to open the browser). OSError if this process is elevated."""
if elevated():
raise PermissionError("The Kurgan is running with admin rights, so it starts nothing (its children "
"would get them too); run it from its logon task, which setup.ps1 registers "
"without them")
if log_path is not None:
os.makedirs(os.path.dirname(log_path), exist_ok=True)
with _launch_lock:
desktop = _desktop_token() if elevated() else None
token = desktop or _normal_user_token()
job = out = nul = None
attributes = None
try:
@@ -384,29 +280,15 @@ def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str]
nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING)
command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
block = _environment_block(env if env is not None else child_environment())
flags = CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP
flags = (CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP
| EXTENDED_STARTUPINFO_PRESENT)
pi = ProcessInformation()
if desktop:
info = StartupInfo()
info.cb = ctypes.sizeof(StartupInfo)
info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
info.wShowWindow = SW_HIDE
info.hStdInput, info.hStdOutput, info.hStdError = nul, out, out
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags, block, cwd,
ctypes.byref(info), ctypes.byref(pi))
if not ok and ctypes.get_last_error() == ERROR_INVALID_PARAMETER:
# Not every creation flag is accepted here; SW_HIDE still hides a console window.
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags & ~CREATE_NO_WINDOW, block,
cwd, ctypes.byref(info), ctypes.byref(pi))
_check(ok, f"Starting {argv[0]}")
else:
size = ctypes.c_size_t()
_k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
attributes = ctypes.create_string_buffer(size.value)
_check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)),
"InitializeProcThreadAttributeList")
handles = (wt.HANDLE * 2)(out, nul)
handles = (wt.HANDLE * 2)(out, nul) # all the child inherits
_check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles,
ctypes.sizeof(handles), None, None),
"UpdateProcThreadAttribute")
@@ -416,8 +298,7 @@ def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str]
info.StartupInfo.wShowWindow = SW_HIDE
info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out
info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p)
_check(_adv.CreateProcessAsUserW(token, None, command, None, None, True,
flags | EXTENDED_STARTUPINFO_PRESENT, block, cwd,
_check(_k32.CreateProcessW(None, command, None, None, True, flags, block, cwd,
ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}")
if job and not _k32.AssignProcessToJobObject(job, pi.hProcess):
error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
@@ -429,20 +310,19 @@ def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str]
_k32.CloseHandle(pi.hThread)
child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv)
job = None # owned by the child object now
log.info("Started %s (pid %s, %s token, %s integrity%s)", os.path.basename(argv[0]), child.pid,
"desktop" if desktop else "restricted", child.token["integrity"],
", ELEVATED" if child.token["elevated"] else "")
log.info("Started %s (pid %s, %s integrity%s)", os.path.basename(argv[0]), child.pid,
child.token["integrity"], ", ELEVATED" if child.token["elevated"] else "")
return child
finally:
if attributes is not None:
_k32.DeleteProcThreadAttributeList(attributes)
for handle in (out, nul, job, token):
for handle in (out, nul, job):
if handle:
_k32.CloseHandle(handle)
def open_url(url: str) -> None:
"""Open a web page in the default browser as the normal user, never elevated."""
"""Open a web page in the default browser (never elevated: launch() refuses if we are)."""
rundll = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "rundll32.exe")
child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None,
contained=False)
+26 -10
View File
@@ -121,7 +121,6 @@ class AiService:
self.action: str | None = None # "Loading model..." while a load/unload request runs
self.message: str | None = None
self._stop: threading.Event | None = None
self._born = time.monotonic()
def set_public_url(self, url: str) -> None:
"""The Kurgan's web server, which the links in the UI point to."""
@@ -193,8 +192,12 @@ class AiService:
def _wait_ready(self, key: str, slot: Slot, gone=None) -> None:
start = time.monotonic()
while True:
running = slot.external is not None or (slot.child is not None and not slot.stopping)
if running and port_in_use(slot.backend.port):
if slot.external is not None:
# An open port isn't proof the program behind it is this server: only a poll
# that succeeded means it speaks the API the proxy is about to use.
if slot.reachable:
return
elif slot.child is not None and not slot.stopping and port_in_use(slot.backend.port):
return
if self._stop is not None and self._stop.is_set():
raise RouteError("The Kurgan is shutting down")
@@ -203,6 +206,10 @@ class AiService:
waited = time.monotonic() - start
if slot.external is None and self.settings.get("ai", "active") != key and waited > 3:
raise RouteError(f"{slot.backend.label} was switched off in The Kurgan")
if slot.external is not None and not slot.reachable and waited > 10:
pid, name = slot.external
raise RouteError(f"port {slot.backend.port} is held by {name} (pid {pid}), "
f"which isn't answering as {slot.backend.label}")
if slot.child is None and slot.error and waited > 3:
raise RouteError(slot.error)
if waited >= self.READY_WAIT:
@@ -304,6 +311,9 @@ class AiService:
if time.monotonic() - self.last_used[active] < minutes * 60:
return active
try:
# Under the same lock as claim(): a request arriving between the check and the
# write would otherwise have its selection overwritten and its server stopped
# under it.
self.settings.update("ai", active=None)
except OSError as e:
log.warning("Couldn't save the AI selection: %s", e)
@@ -315,9 +325,15 @@ class AiService:
active = self._idle_check(self.settings.get("ai", "active"))
for slot in self.slots.values():
self._check_exit(slot)
with self._cv:
# A server with a request in flight finishes it before being stopped or replaced:
# clients wait for servers, they are never cut off mid-reply.
draining = next((key for key, slot in self.slots.items()
if key != active and slot.child is not None and self.inflight[key]), None)
busy_here = active is not None and self.inflight[active] > 0
# Stop whatever isn't selected first, so the selected server gets the GPU to itself.
for key, slot in self.slots.items():
if slot.child is not None and key != active:
if slot.child is not None and key != active and key != draining:
self._stop_slot(slot, "switching" if active else "none selected")
for key, slot in self.slots.items():
slot.external = None
@@ -327,17 +343,17 @@ class AiService:
self.transition = None
return
slot = self.slots[active]
if slot.child is not None and slot.variant != slot.backend.variant():
if slot.child is not None and not busy_here and slot.variant != slot.backend.variant():
self._stop_slot(slot, "changing model")
if slot.child is not None or slot.external is not None:
self.transition = None
return
if time.monotonic() < slot.hold_until:
if draining is not None:
# The GPU's memory is still held by the server answering its last request; the
# selected one must not start onto it.
self.transition = f"Waiting for {self.slots[draining].backend.label} to finish its request"
return
# At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the
# server gets the desktop's own token (see launcher.py) rather than the fallback.
if time.monotonic() - self._born < 120 and not launcher.desktop_ready():
self.transition = f"Waiting for the desktop to start {slot.backend.label}"
if time.monotonic() < slot.hold_until:
return
problem = slot.backend.check_files()
if problem:
+43 -5
View File
@@ -5,6 +5,8 @@ imported by it. Does what Strata's local-service-tray.py did, without the tray i
the same environment, arguments, logs and single-instance mutex. The Kurgan asks it to stop
by setting the named event given in --stop-event; Strata then shuts down cleanly (finishing
or cancelling the current request within --shutdown-timeout) and ends its engine processes.
If the server somehow never returns from that, a watchdog ends the process rather than
letting it hang; The Kurgan's own kill (a little later) is the last resort behind that.
"""
from __future__ import annotations
@@ -23,6 +25,8 @@ import sys
import threading
LOG = logging.getLogger("kurgan-strata")
SHUTDOWN_GRACE = 40 # Strata's --shutdown-timeout is 30 s; The Kurgan kills at 45 s (its stop_timeout)
KEEP_LOG_PAIRS = 7 # stdout/stderr files are written per start; keep the newest few
K32 = ctypes.WinDLL("kernel32", use_last_error=True)
K32.CreateEventW.argtypes, K32.CreateEventW.restype = [wt.LPVOID, wt.BOOL, wt.BOOL, wt.LPCWSTR], wt.HANDLE
K32.CreateMutexW.argtypes, K32.CreateMutexW.restype = [wt.LPVOID, wt.BOOL, wt.LPCWSTR], wt.HANDLE
@@ -30,12 +34,43 @@ K32.WaitForSingleObject.argtypes, K32.WaitForSingleObject.restype = [wt.HANDLE,
K32.CloseHandle.argtypes = [wt.HANDLE]
def watch_stop(event: int, stopping: threading.Event) -> None:
def watch_stop(event: int, shutdown: threading.Event, cleanup) -> None:
while K32.WaitForSingleObject(event, 1000) != 0:
pass
LOG.info("The Kurgan asked Strata to stop")
stopping.set()
_thread.interrupt_main()
_thread.interrupt_main() # KeyboardInterrupt in the main thread unwinds server.main()
if not shutdown.wait(SHUTDOWN_GRACE):
# The server never returned (stuck in engine code, say): end the children ourselves
# rather than leave The Kurgan to kill the whole job without a clean shutdown.
LOG.error("Strata did not stop within %d s of the request; ending it", SHUTDOWN_GRACE)
try:
cleanup()
except Exception:
LOG.exception("Ending the engine processes failed")
os._exit(1)
def rotate_logs(logs: Path) -> None:
"""Bound the log directory: one previous task log, and the newest few stdout/stderr pairs."""
task = logs / "local-service-task.log"
if task.exists():
try:
task.replace(logs / "local-service-task.prev.log")
except OSError as e:
LOG.warning("Could not rotate the task log: %s", e)
stamps = set()
for path in logs.glob("local-service-std*.log"):
for kind in ("stdout", "stderr"):
prefix = f"local-service-{kind}-"
if path.name.startswith(prefix):
stamps.add(path.name[len(prefix):-len(".log")])
break
for stamp in sorted(stamps)[:-KEEP_LOG_PAIRS]:
for path in logs.glob(f"local-service-std*-{stamp}.log"):
try:
path.unlink()
except OSError as e:
LOG.warning("Could not delete the old log %s: %s", path.name, e)
def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: str) -> int:
@@ -58,8 +93,9 @@ def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: st
if not stop_event:
K32.CloseHandle(mutex)
raise ctypes.WinError(ctypes.get_last_error())
stopping = threading.Event()
threading.Thread(target=watch_stop, args=(stop_event, stopping), name="kurgan-stop", daemon=True).start()
shutdown = threading.Event()
threading.Thread(target=watch_stop, args=(stop_event, shutdown, lifeline.end_children),
name="kurgan-stop", daemon=True).start()
try:
LOG.info("Starting Strata API for %s at 127.0.0.1:%s (The Kurgan, pid %s)", model_id, port, os.getpid())
os.environ["GGML_CUDA_DISABLE_GRAPHS"] = "1"
@@ -71,6 +107,7 @@ def run(root: Path, config_name: str, port: int, idle_unload: int, stop_name: st
except KeyboardInterrupt:
return 0
finally:
shutdown.set() # the process is winding down: the watchdog stands down
lifeline.end_children()
K32.CloseHandle(stop_event)
K32.CloseHandle(mutex)
@@ -87,6 +124,7 @@ def main() -> int:
args = parser.parse_args()
logs = args.root / "logs"
logs.mkdir(exist_ok=True)
rotate_logs(logs)
stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
logging.basicConfig(filename=logs / "local-service-task.log", level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s")
+155 -77
View File
@@ -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
@@ -67,9 +68,71 @@ def _parse_color(text: str) -> tuple[int, int, int]:
return tuple(int(text[i:i + 2], 16) for i in (0, 2, 4)) # type: ignore[return-value]
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
from kurgan.cooling.control import parse_ports
ALERT_SECONDS = 5.0 # how often the alert monitor looks for things starting to go wrong
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 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():
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
ALERT_REPEAT_SECONDS = 600.0 # a problem that clears and comes back balloons again only after this
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 due_alerts(new: list[tuple[str, str]], alerted: dict[str, float], now: float) -> list[tuple[str, str]]:
"""The new alerts not already ballooned in the last ALERT_REPEAT_SECONDS; records them in
`alerted` (key -> when). A flapping problem balloons once, not every time it comes back."""
due = [(key, message) for key, message in new if now - alerted.get(key, -1e18) >= ALERT_REPEAT_SECONDS]
alerted.update((key, now) for key, _ in due)
return due
def balloon(messages: list[str]) -> tuple[str, str]:
"""One balloon (title, text) for all of them: Windows shows one balloon at a time, so a
second notify() would only replace the first. The text holds up to 255 characters."""
if len(messages) == 1:
return APP_NAME, messages[0]
lines: list[str] = []
for i, message in enumerate(messages):
rest = len(messages) - i - 1
tail = f"\n...and {rest} more" if rest else ""
if len("\n".join(lines + [message])) + len(tail) > 255:
if not lines: # the first one alone is too long: shorten it
lines.append(message[:255 - len(tail) - 3] + "...")
lines.append(tail.lstrip("\n"))
else: # the previous round made sure this note fits
lines.append(f"...and {rest + 1} more")
break
lines.append(message)
return f"{APP_NAME}: {len(messages)} problems", "\n".join(filter(None, lines))
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
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)")
@@ -93,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)")
@@ -108,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"):
@@ -124,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
@@ -134,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
@@ -146,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
@@ -164,38 +213,33 @@ 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
self.recorder = Recorder(paths.DATA_DIR)
self.telemetry.subscribe(self.recorder.on_sample)
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
@@ -208,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)}, "
@@ -230,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)
@@ -246,14 +289,36 @@ class Kurgan:
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
alerted: dict[str, float] = {} # key -> when it last ballooned
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.hw.cooling(), self.ai, self.telemetry)
except Exception:
log.exception("Alert check failed")
continue
if known is None:
known = states
continue
due = due_alerts(new_alerts(known, states), alerted, time.monotonic())
for _, message in due:
log.warning("Alert: %s", message)
if due:
self.tray.notify(*balloon([message for _, message in due]), warning=True)
known = states
def _start_tray(self) -> None:
from kurgan.tray import TrayIcon, make_icon
from kurgan.tray import ICON_PATH, TrayIcon
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,
self.tray = TrayIcon(APP_NAME, ICON_PATH, 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:
@@ -284,8 +349,9 @@ class Kurgan:
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()))
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
@@ -309,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,
}
@@ -321,17 +385,19 @@ class Kurgan:
return {**self.telemetry.history(),
"fans": {"series": ("t", "gpu_duty", "cpu_duty", "top_duty"), "rows": list(self.fan_history)}}
def records(self, days: int) -> dict:
from kurgan.telemetry.record import RETENTION_DAYS, load
if not isinstance(days, int) or not 1 <= days <= RETENTION_DAYS:
raise ValueError(f"days must be a whole number from 1 to {RETENTION_DAYS}")
return load(paths.DATA_DIR, days)
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])
"""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:
@@ -346,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']}")
@@ -377,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)
Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 57 KiB

+127
View File
@@ -0,0 +1,127 @@
"""Make The Kurgan's logo and icons from the source photo, The-Kurgan-Sword.png (repo root).
.venv\\Scripts\\python.exe -m kurgan.assets.make_assets [source.png]
Writes:
kurgan/assets/sword.png the whole sword, cleaned and trimmed (master copy)
kurgan/assets/hilt.png 512 px square: the crossguard centred and as large as it fits
kurgan/assets/kurgan.ico the tray icon (16-256 px), from the hilt
kurgan/web/static/logo.png the web UI's header logo: the whole sword, the cut-off blade faded out
kurgan/web/static/sword-vertical.png the web UI's backdrop: the whole sword, full size, turned 90°
clockwise (pommel up); the page's bottom edge cuts the blade off
kurgan/web/static/favicon.ico the browser tab icon, from the hilt
Cleaning: the photo was cut out of a white background, leaving a pale one-pixel fringe and
stair-stepped edges. The outline is pulled in by a pixel, edge pixels take the colour of the
sword next to them instead of white, and the edge is smoothed to about a pixel wide.
Small icons (32 px and under) have their metal brightened a little: at 16 px on a dark taskbar
the mid-grey crossguard otherwise reads as black. The black grip still disappears there; an
outline was tried and made the 16 px icon a blur.
"""
from __future__ import annotations
import os
import sys
import numpy as np
from PIL import Image, ImageFilter
HERE = os.path.dirname(os.path.abspath(__file__))
ROOT = os.path.dirname(os.path.dirname(HERE))
STATIC = os.path.join(ROOT, "kurgan", "web", "static")
SOURCE = os.path.join(ROOT, "The-Kurgan-Sword.png")
ICON_SIZES = (16, 20, 24, 32, 40, 48, 64, 256) # tray: 16 at 100% scaling up to 32 at 200%; the rest for Windows
FAVICON_SIZES = (16, 32, 48)
LOGO_HEIGHT = 96 # shown 40 px high in the header: sharp up to about 240% scaling
SMALL_LIFT = 1.35 # gamma applied to icons of 32 px and under
BLADE_FADE = 0.18 # the last 18% of the header logo's width fades out (the photo cuts the blade off)
def _bleed(rgb: np.ndarray, known: np.ndarray, steps: int) -> np.ndarray:
"""Give pixels outside `known` the average colour of their known neighbours, ring by ring."""
rgb, known = rgb.copy(), known.copy()
for _ in range(steps):
acc = np.zeros_like(rgb)
count = np.zeros(known.shape, np.float32)
for dy in (-1, 0, 1):
for dx in (-1, 0, 1):
if dy or dx:
k = np.roll(known, (dy, dx), (0, 1))
acc += np.roll(rgb, (dy, dx), (0, 1)) * k[..., None]
count += k
new = ~known & (count > 0)
rgb[new] = acc[new] / count[new][:, None]
known |= new
return rgb
def clean(path: str) -> Image.Image:
"""The sword without its white fringe, with smooth edges, trimmed to its outline."""
src = np.asarray(Image.open(path).convert("RGBA")).astype(np.float32)
solid = Image.fromarray(((src[..., 3] > 128) * 255).astype(np.uint8))
core_img = solid.filter(ImageFilter.MinFilter(3)) # one pixel in: drops the fringe
core = np.asarray(core_img) > 0
rgb = _bleed(src[..., :3], core, 8) # edges take the sword's colour, not white
soft = np.asarray(core_img.filter(ImageFilter.GaussianBlur(1.0))).astype(np.float32) / 255
alpha = np.clip((soft - 0.5) * 2.0 + 0.5, 0, 1) # smooth, about a pixel wide
img = Image.fromarray(np.dstack([rgb, alpha * 255]).round().clip(0, 255).astype(np.uint8), "RGBA")
return img.crop(img.getchannel("A").point(lambda v: 255 if v > 8 else 0).getbbox())
def hilt(sword: Image.Image) -> Image.Image:
"""A square around the crossguard (the columns where the sword is tallest), as large as fits."""
a = np.asarray(sword.getchannel("A")) > 128
guard = np.nonzero(a.sum(0) > 0.6 * a.shape[0])[0]
rows = np.nonzero(a[:, guard].any(1))[0]
cx, cy = (guard.min() + guard.max()) / 2, (rows.min() + rows.max()) / 2
side = round((rows.max() - rows.min() + 1) * 1.03)
left, top = round(cx - side / 2), round(cy - side / 2)
square = Image.new("RGBA", (side, side), (0, 0, 0, 0))
piece = sword.crop((max(left, 0), max(top, 0), min(left + side, sword.width), min(top + side, sword.height)))
square.alpha_composite(piece, (max(-left, 0), max(-top, 0)))
return square
def icon_image(square: Image.Image, size: int) -> Image.Image:
small = square.resize((size, size), Image.LANCZOS)
if size > 32:
return small
small = small.filter(ImageFilter.UnsharpMask(0.6, 80, 0))
r, g, b, a = small.split()
lift = [round(255 * (v / 255) ** (1 / SMALL_LIFT)) for v in range(256)]
return Image.merge("RGBA", (r.point(lift), g.point(lift), b.point(lift), a))
def save_ico(square: Image.Image, path: str, sizes: tuple[int, ...]) -> None:
images = [icon_image(square, s) for s in sizes]
images[-1].save(path, format="ICO", sizes=[(s, s) for s in sizes], append_images=images[:-1])
def header_logo(sword: Image.Image) -> Image.Image:
width = round(sword.width * LOGO_HEIGHT / sword.height)
logo = sword.resize((width, LOGO_HEIGHT), Image.LANCZOS)
x = np.linspace(0, 1, width)
t = np.clip((x - (1 - BLADE_FADE)) / BLADE_FADE, 0, 1)
fade = 1 - t * t * (3 - 2 * t) # smoothstep down to nothing at the tip
alpha = np.asarray(logo.getchannel("A")).astype(np.float32) * fade[None, :]
logo.putalpha(Image.fromarray(alpha.round().astype(np.uint8)))
return logo
def main(source: str = SOURCE) -> None:
sword = clean(source)
sword.save(os.path.join(HERE, "sword.png"), optimize=True)
square = hilt(sword)
square.resize((512, 512), Image.LANCZOS).save(os.path.join(HERE, "hilt.png"), optimize=True)
save_ico(square, os.path.join(HERE, "kurgan.ico"), ICON_SIZES)
header_logo(sword).save(os.path.join(STATIC, "logo.png"), optimize=True)
sword.transpose(Image.Transpose.ROTATE_270).save(os.path.join(STATIC, "sword-vertical.png"), optimize=True)
save_ico(square, os.path.join(STATIC, "favicon.ico"), FAVICON_SIZES)
print(f"sword {sword.size}, hilt {square.size} -> 512, icons {ICON_SIZES}, logo height {LOGO_HEIGHT}")
if __name__ == "__main__":
main(*sys.argv[1:2])
Binary file not shown.

After

Width:  |  Height:  |  Size: 222 KiB

+122 -43
View File
@@ -9,13 +9,12 @@ import argparse
import collections
import logging
import math
import threading
import time
from kurgan.cooling.board_fans import Nct6687, parse_channels
from kurgan.cooling.profiles import BALANCED, FanProfile
from kurgan.hardware.hid import HidError
from kurgan.telemetry.sensors import CommanderPro, GpuSensors, IntelPackage
from kurgan.telemetry.sensors import CommanderPro, IntelPackage
log = logging.getLogger(__name__)
# The Balanced profile's curves (the original ones); the active profile can replace them at runtime.
@@ -25,6 +24,8 @@ BOOST_ON, BOOST_OFF = 85, 65 # case fan duty (either side) that starts / ends t
TOP_START, TOP_STOP = BALANCED.top_start, BALANCED.top_stop # top fans start at / stop below (C) ...
TOP_STOP_HOLD = 30 # ... once it has stayed below the stop temperature for this many seconds
TOP_KICK, TOP_KICK_SECONDS = 40, 3 # spin-up duty when starting from stopped
# Consecutive low/zero-RPM polls (1 s apart) before a stall is believed: one reading can glitch.
STALL_READINGS = 3
def parse_ports(text: str) -> tuple[int, ...]:
@@ -58,7 +59,8 @@ class TopFanCurve:
"""Motherboard header fans on their own curve from the hotter of CPU/GPU, stopped while cool.
They are also held at 100% while either case fan group works hard; on exit the BIOS curve
takes over again."""
takes over again. A fan that stops turning while commanded to spin raises all of them to
100% and says so (see _tach_stall)."""
RETRY = 30.0
@@ -73,12 +75,15 @@ class TopFanCurve:
self.running = False
self.duty = 0
self.status = "Starting"
self.rpms: dict[int, int] = {} # latest tach reading per channel, for the snapshot
self._retry_at = 0.0
self._written: int | None = None
self._kick_until = 0.0
self._cool_since: float | None = None
self._last_rise = 0.0
self._last_update: float | None = None
self._spun: set[int] = set() # channels whose tach has been seen turning
self._zeros = collections.Counter() # consecutive zero-RPM polls per channel
def apply_profile(self, profile: FanProfile) -> None:
self.curve, self.start, self.stop = profile.top_curve, profile.top_start, profile.top_stop
@@ -91,8 +96,15 @@ class TopFanCurve:
def snapshot(self) -> dict:
return {"channels": list(self.channels), "temp": self.temp, "duty": self.duty, "running": self.running,
"boosted": self.boosted, "status": self.status,
"rpms": {str(c): self._shown_rpm(c) for c in self.channels},
"failsafe": self.status.startswith(("FAILSAFE", "UNAVAILABLE"))}
def _shown_rpm(self, channel: int) -> int | None:
"""The channel's RPM, or None while its tach has never been seen turning: on this board
SYS_FAN1's tach isn't wired, and a constant 0 would read as a dead fan."""
rpm = self.rpms.get(channel)
return rpm if rpm or channel in self._spun else None
def close(self) -> None:
if self.board is not None:
self.board.close()
@@ -122,6 +134,32 @@ class TopFanCurve:
target = max(target, TOP_KICK)
return target, f"{temp:.0f} C, {{duty}}%" + (f" (case fans >= {BOOST_ON}%)" if self.boosted else "")
def _tach_stall(self, now: float) -> list[int] | None:
"""Channels whose fan was seen turning but now reads 0 RPM: stalled or unplugged.
A channel whose tachometer has never been seen turning (an empty header, or a tach this
board doesn't wire to the channel) is left alone, so a wrong channel-to-tach guess
cannot cry wolf. Returns the stalled channels; the duty is raised to 100% for the
caller to write."""
assert self.board is not None
tachs = self.board.rpms()
self.rpms = {c: tachs[c] for c in self.channels}
if self.duty <= 0 or now < self._kick_until:
self._zeros.clear() # stopped or spinning up: zero RPM proves nothing yet
return None
stalled = []
for c in self.channels:
if self.rpms[c] > 0:
self._spun.add(c)
self._zeros[c] = 0
elif c in self._spun:
self._zeros[c] += 1
if self._zeros[c] >= STALL_READINGS:
stalled.append(c)
if stalled:
self.duty, self._last_rise = 100, now
return stalled or None
def update(self, case_duty: int, temp: float | None, now: float) -> None:
self.temp = temp
target, text = self._target(case_duty, temp, now)
@@ -138,13 +176,35 @@ class TopFanCurve:
try:
if self.board is None:
self.board = self._factory()
stalled = self._tach_stall(now)
# Compared every poll, so a firmware reset (e.g. after sleep) or a crash is corrected.
if self.duty != self._written or self.board.manual_mask() & self._mask != self._mask:
self.board.set_manual(self.channels, self.duty)
self._written = self.duty
if stalled:
text = f"FAILSAFE 100%: no RPM on channels {stalled}"
self._status(text.format(duty=self.duty), warning=text.startswith("FAILSAFE"))
except (OSError, ValueError) as e:
self._status(f"UNAVAILABLE ({e}); BIOS curve keeps control", warning=True)
except Exception as e:
# Any failure, a bug included: the top fans must not take the case fans' control
# loop down with them. Best effort: hand the channels back to the BIOS curve, so a
# manual duty left behind (0% included) doesn't persist until the next successful
# write or a reboot.
if not isinstance(e, (OSError, ValueError)) and not self.status.startswith("UNAVAILABLE"):
log.error("Top fan control failed unexpectedly", exc_info=True)
held, handed_back = self._written, False
try:
if self.board is not None:
self.board.set_auto(self.channels)
handed_back = True
except Exception: # the fallback must never mask the original error
log.debug("Cannot hand the top fans back to the BIOS curve", exc_info=True)
if handed_back:
note = "BIOS curve keeps control"
elif held is not None:
note = f"fans held at the last written duty ({held}%)"
else:
note = "no duty was ever written"
self._status(f"UNAVAILABLE ({e}); {note}", warning=True)
self.close()
self._retry_at = now + self.RETRY
@@ -175,6 +235,7 @@ class CaseFanGroup:
self._last_update: float | None = None
self._last_rise = 0.0
self._started: float | None = None
self._lows = {p: 0 for p in self.ports} # consecutive low-RPM polls per port
def set_status(self, text: str, warning: bool = False) -> None:
if text != self.status:
@@ -194,6 +255,7 @@ class CaseFanGroup:
self.duty = 100
self._last_rise = now
self._started = now
self._lows = {p: 0 for p in self.ports}
elapsed = 0 if self._last_update is None else min(2, max(0, now - self._last_update))
if target >= self.duty:
if target > self.duty or invalid:
@@ -204,7 +266,9 @@ class CaseFanGroup:
self._last_update = now
rpms = self.rpms = self.commander.set_duty(self.ports, self.duty)
if self._started is not None and now - self._started >= 10:
stalled = [p for p in self.ports if rpms.get(p, 0) < 200]
for p in self.ports:
self._lows[p] = self._lows[p] + 1 if rpms.get(p, 0) < 200 else 0
stalled = [p for p in self.ports if self._lows[p] >= STALL_READINGS]
if stalled:
self.duty = 100
self._last_rise = now
@@ -227,13 +291,21 @@ class CaseFanGroup:
class CpuTemperature:
"""CPU package temperature averaged over CPU_AVERAGE readings; None while unavailable."""
"""CPU package temperature, averaged over CPU_AVERAGE readings for the fans, and package power.
read() returns the average (None while unavailable); `temp` and `power` hold the latest
readings and `error` why there are none."""
RETRY_SECONDS = 15.0 # pause after a read failure, so a lost PawnIO device is not re-opened every poll
def __init__(self, factory=IntelPackage):
self._factory = factory
self.pkg: IntelPackage | None = None
self._retry_at = 0.0
self._recent: collections.deque[float] = collections.deque(maxlen=CPU_AVERAGE)
self.temp: float | None = None
self.power: float | None = None
self.error: str | None = "not read yet"
def read(self, now: float) -> float | None:
if self.pkg is None and now >= self._retry_at:
@@ -241,14 +313,20 @@ class CpuTemperature:
self.pkg = self._factory()
except Exception as e: # PawnIO missing, not admin, ...
log.warning("CPU temperature unavailable for fan control: %s", e)
self.error = str(e)
self._retry_at = now + 60
temp = None
temp = power = None
if self.pkg is not None:
try:
temp = self.pkg.temperature()
power = self.pkg.power()
self.error = None if temp is not None else "the package sensor reported no reading"
except OSError as e:
log.warning("CPU temperature read failed, will retry: %s", e)
self.error = str(e)
self.close()
self._retry_at = now + self.RETRY_SECONDS
self.temp, self.power = temp, power
if temp is None:
self._recent.clear()
return None
@@ -268,11 +346,12 @@ class CaseFanControl:
def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...],
cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None,
profile: FanProfile = BALANCED, sensors=None):
"""sensors: (GPU sensor factory, CPU temperature factory), for tests and --demo."""
profile: FanProfile = BALANCED):
"""Driven by the hardware service's loop (kurgan.hw.service): step() once a second with
fresh temperatures, shutdown() when it ends."""
self.commander = commander
self.profile = profile
self._sensors = sensors or (lambda: GpuSensors(load_source="nvml"), CpuTemperature)
self._reported: float | None = None # when the last unexpected error was logged
self.gpu = CaseFanGroup("GPU", profile.gpu_curve, commander, gpu_ports)
self.cpu = CaseFanGroup("CPU", profile.cpu_curve, commander, cpu_ports) if cpu_ports else None
if self.cpu is not None and set(self.cpu.ports) & set(self.gpu.ports):
@@ -317,45 +396,41 @@ class CaseFanControl:
for g in self.groups:
g.set_status(text, warning=True)
def run(self, stop: threading.Event) -> None:
gpu_factory, cpu_factory = self._sensors
cpu_temp = cpu_factory() if self.cpu is not None else None
gpu = None
reported: float | None = None # when the last unexpected error was logged
def _failsafe_top(self) -> None:
if self.top is not None:
try: # update() never raises for the board, but a bug must not stop the case fans' fail-safe
self.top.update(100, None, time.monotonic())
except Exception:
log.debug("Top fans: failsafe update failed", exc_info=True)
def step(self, gpu_temp: float | None, cpu_temp: float | None, now: float) -> float:
"""One control pass; never raises. Returns the seconds to wait before the next one.
A device error closes the Commander PRO (reopened on the next pass) and fails every fan
safe. So does any other error, a bug included: fan control must not end for the life of
the service. Those are logged at most once a minute."""
try:
while not stop.is_set():
now = time.monotonic()
retry_in = 1.0
try:
if gpu is None:
gpu = gpu_factory()
self.update(gpu.read().temp, now, cpu_temp.read(now) if cpu_temp else None)
self.update(gpu_temp, now, cpu_temp)
return 1.0
except (OSError, HidError) as e:
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
self.commander.close()
if self.top is not None:
self.top.update(100, None, time.monotonic())
retry_in = self.ERROR_RETRY_SECONDS
except Exception as e:
# A sensor or control bug must not end fan control for the life of the
# process: fail safe, log at most once a minute, and retry with a freshly
# built sensor object.
if reported is None or now - reported >= 60:
reported = now
if self._reported is None or now - self._reported >= 60:
self._reported = now
log.exception("Case fan control error; failing safe and retrying")
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
gpu = None
retry_in = self.ERROR_RETRY_SECONDS
stop.wait(retry_in)
finally:
self._failsafe_top()
return self.ERROR_RETRY_SECONDS
def shutdown(self) -> None:
"""Leave the case fans at 100% and hand the top fans back to the BIOS curve."""
self.failsafe()
self.commander.close()
if self.top is not None:
self.top.release()
if cpu_temp is not None:
cpu_temp.close()
def main() -> int:
@@ -364,7 +439,7 @@ def main() -> int:
action.add_argument("--identify", type=parse_ports, metavar="1,2,3",
help="raise these three ports to 100%% to identify their physical side")
action.add_argument("--save-ports", type=parse_ports, metavar="4,5,6",
help="save identified GPU-side ports for dashboard startup")
help="save identified GPU-side ports (hw-settings.json; run elevated)")
action.add_argument("--save-cpu-ports", type=parse_ports, metavar="1,2,3",
help="save identified CPU-side ports (follow CPU temperature)")
action.add_argument("--save-top-channels", type=parse_channels, metavar="2,5",
@@ -372,10 +447,12 @@ def main() -> int:
args = ap.parse_args()
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
if args.save_ports or args.save_cpu_ports or args.save_top_channels:
from kurgan.settings import Settings, SettingsError
from kurgan.hw import settings as hw_settings
from kurgan.settings import SettingsError
try:
settings = Settings()
try: # the hardware service's file: only an elevated prompt can write it
hw_settings.ensure_data_dir()
settings = hw_settings.load()
if args.save_ports:
settings.update("cooling", gpu_ports=list(args.save_ports))
elif args.save_cpu_ports:
@@ -385,7 +462,8 @@ def main() -> int:
except (OSError, SettingsError):
log.exception("Cannot save fan configuration")
return 1
print(f"Saved {settings.section('cooling')} to {settings.path}. Restart The Kurgan to apply it.")
print(f"Saved {settings.section('cooling')} to {settings.path}.")
print("Restart the hardware service to apply it (elevated): Restart-Service KurganHw")
return 0
commander = CommanderPro()
try:
@@ -396,7 +474,8 @@ def main() -> int:
print("RPMs: " + ", ".join(f"{p}: {rpm}" for p, rpm in rpms.items()))
return 0
except (OSError, HidError) as e:
log.error("Identification failed: %s", e)
log.error("Identification failed: %s%s", e, " (stop the hardware service first, elevated: "
"Stop-Service KurganHw)" if "in use" in str(e) else "")
return 1
finally:
commander.close()
+48 -10
View File
@@ -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
"""
@@ -57,13 +58,16 @@ class FakeCommander:
self.duty[p] = duty
return {p: self._rpm(p) for p in ports}
def full_speed(self) -> dict[int, int]:
return self.set_duty(range(1, 7), 100)
def close(self) -> None:
pass
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),
@@ -73,14 +77,22 @@ class FakeSystem:
class FakeBoard:
BIOS_RPM = 700 # what a channel left to the BIOS curve turns at
def __init__(self):
self.mask = 0
self.duties: dict[int, int] = {}
def manual_mask(self) -> int:
return self.mask
def rpms(self) -> list[int]:
"""All 16 tachs, like Nct6687.rpms(): 14 RPM per % of duty, a fixed speed under the BIOS."""
return [14 * self.duties.get(c, 0) if self.mask >> c & 1 else self.BIOS_RPM for c in range(16)]
def set_manual(self, channels, duty: int) -> None:
self.mask |= sum(1 << c for c in channels)
self.duties.update((c, duty) for c in channels)
def set_auto(self, channels) -> None:
self.mask &= ~sum(1 << c for c in channels)
@@ -90,8 +102,17 @@ class FakeBoard:
class FakeCpuTemperature:
"""Stands in for cooling.control.CpuTemperature (the service's PawnIO reader)."""
error = None
def __init__(self):
self.temp = self.power = None
def read(self, now: float) -> float:
return FakeCpu().read().temp
reading = FakeCpu().read()
self.temp, self.power = reading.temp, reading.power
return reading.temp
def close(self) -> None:
pass
@@ -119,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"))
+5
View File
@@ -20,6 +20,9 @@ log = logging.getLogger(__name__)
class DisplayService:
# Telemetry older than this is drawn as "--" rather than presented as a live reading.
STALE_AFTER = 15.0
def __init__(self, renderer: DashboardRenderer, telemetry: Telemetry, brightness: int = 100):
self.renderer = renderer
self.telemetry = telemetry
@@ -54,6 +57,8 @@ class DisplayService:
sample = self.telemetry.wait_newer(seq, timeout=1.5)
if stop.is_set():
break
if sample is not None and time.time() - sample.t > self.STALE_AFTER:
sample = None # frozen readings must not be presented as current
seq = sample.seq if sample is not None else seq
t0 = time.monotonic()
if lcd.send_jpeg(encode_jpeg(self.render(sample))):
+6 -7
View File
@@ -35,6 +35,11 @@ _WAIT_OBJECT_0 = 0
_WAIT_TIMEOUT = 0x102
# How long to wait for the driver to finish a cancelled IRP before giving up on the channel.
_ABANDON_GRACE_MS = 1000
# OVERLAPPED structs and buffers of IRPs the driver never finished cancelling, kept for the life
# of the process. Nothing can tell us when the driver is done with them, so freeing them (even
# with their channel) could let a late completion write into reused memory. A few hundred
# bytes each, and only after a wedged device.
_ABANDONED: list = []
class _GUID(ctypes.Structure):
@@ -198,9 +203,6 @@ class HidChannel:
if not self._wevent or not self._revent:
raise _winerr("CreateEventW")
self._broken = False
# OVERLAPPED structs and buffers of IRPs we gave up on, kept alive so a late
# completion by the driver can never write into memory that has been reused.
self._abandoned: list = []
except Exception:
_k32.CloseHandle(self.handle)
raise
@@ -210,9 +212,6 @@ class HidChannel:
if h:
_k32.CloseHandle(h)
self.handle = None
# _abandoned is deliberately not cleared: closing the handle cancels the pending IRPs,
# but the driver may still complete them asynchronously. The channel object is dropped
# by the caller (a broken channel is always reopened), which frees the buffers then.
def _cancel(self, ov, buf, event, what: str) -> None:
"""Cancel a timed-out IRP and give the driver a moment to finish it.
@@ -225,7 +224,7 @@ class HidChannel:
if _k32.WaitForSingleObject(event, _ABANDON_GRACE_MS) == _WAIT_OBJECT_0:
return
self._broken = True
self._abandoned.append((ov, buf))
_ABANDONED.append((ov, buf))
def send(self, payload: bytes, timeout_ms: int = 1000) -> None:
if self._broken:
+13
View File
@@ -0,0 +1,13 @@
"""The hardware service: the only part of The Kurgan that runs with admin rights.
`kurgan.hw` is a Windows service (LocalSystem, started at boot) that owns the hardware the
unelevated app must not touch:
fan control Commander PRO case fans and motherboard top fans, profiles and fail-safes,
with its own CPU (PawnIO MSR) and GPU (NVML) temperature readings
RAM lighting the Dominator DDR5 sticks over the SMBus (PawnIO)
The app (web UI, proxy, AI servers, telemetry, LCD, the other lighting, tray) talks to it over
the named pipe \\\\.\\pipe\\kurgan-hw (protocol.py). The service never depends on the app: with
no client connected it keeps controlling the fans.
"""
+7
View File
@@ -0,0 +1,7 @@
"""python -m kurgan.hw: the hardware service in a console (see kurgan/hw/main.py)."""
import sys
from kurgan.hw.main import main
sys.exit(main())
+329
View File
@@ -0,0 +1,329 @@
"""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())
+162
View File
@@ -0,0 +1,162 @@
"""Install or update the hardware service; setup.ps1 runs this elevated (Decision 0002).
python -m kurgan.hw.install --python BASE_PYTHON --user-sid SID --user-settings PATH
1. checks that BASE_PYTHON can run the service (hw_service.py --check);
2. creates %ProgramData%\\Kurgan, or resets its access (Administrators own it; SYSTEM and
Administrators full control, users read), and moves the fan and RAM lighting settings into
hw-settings.json there, once (kurgan.hw.migrate);
3. creates the "KurganHw" service, or updates it after stopping it: LocalSystem, automatic start,
restart after 5 s, 10 s and 60 s on failure, and the user whose app may use its pipe;
4. starts it and waits until it runs.
The service runs the base interpreter, not the venv's python.exe (a redirector that starts the
base interpreter as a child, which the service manager wouldn't be talking to):
"BASE_PYTHON" -I -S -B "<repo>\\hw_service.py"
uninstall.ps1 removes the service with sc.exe; nothing else is needed for that.
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
from kurgan import paths
from kurgan.hw import main as hw_main
from kurgan.hw.pipe import valid_sid
SCRIPT = os.path.join(paths.PROJECT_DIR, "hw_service.py")
DESCRIPTION = ("The Kurgan's hardware control: case and top fan curves with their fail-safes, and the RAM "
"lighting. Stopping it leaves the case fans at 100% and the top fans on the BIOS curve.")
RESTARTS_MS = (5000, 10000, 60000)
RESET_SECONDS = 24 * 3600 # the failure count starts again after a day without one
# The data folder, owner included (kurgan.hw.settings.DATA_DIR_SDDL is the access list).
DATA_DIR_OWNER_SDDL = "O:BAG:SY"
def image_path(python: str, script: str = SCRIPT) -> str:
return f'"{python}" -I -S -B "{script}"'
def failure_actions() -> dict:
import win32service
return {"ResetPeriod": RESET_SECONDS, "RebootMsg": None, "Command": None,
"Actions": [(win32service.SC_ACTION_RESTART, ms) for ms in RESTARTS_MS]}
def check(python: str) -> str:
"""hw_service.py --check under the service's interpreter and flags; RuntimeError if it fails."""
try:
result = subprocess.run([python, "-I", "-S", "-B", SCRIPT, "--check"], capture_output=True, text=True,
timeout=120, cwd=paths.PROJECT_DIR)
except (OSError, subprocess.TimeoutExpired) as e:
raise RuntimeError(f"{python} can't run the hardware service: {e}") from None
if result.returncode != 0:
detail = (result.stderr or result.stdout).strip().splitlines()
raise RuntimeError(f"{python} can't run the hardware service: {detail[-1] if detail else result.returncode}")
return result.stdout.strip()
def reset_data_dir(path: str = paths.HW_DATA_DIR) -> None:
"""Create the data folder, or give an existing one exactly the intended owner and access."""
import win32security
from kurgan.hw import settings as hw_settings
hw_settings.ensure_data_dir(path)
sd = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
DATA_DIR_OWNER_SDDL + hw_settings.DATA_DIR_SDDL, win32security.SDDL_REVISION_1)
win32security.SetNamedSecurityInfo( # also passes the inheritable entries on to the files inside
path, win32security.SE_FILE_OBJECT,
win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
| win32security.PROTECTED_DACL_SECURITY_INFORMATION,
sd.GetSecurityDescriptorOwner(), None, sd.GetSecurityDescriptorDacl(), None)
def _wait(service, state: int, seconds: float) -> int:
import win32service
deadline = time.monotonic() + seconds
while True:
current = win32service.QueryServiceStatus(service)[1]
if current == state or time.monotonic() > deadline:
return current
time.sleep(0.5)
def install(python: str, user_sid: str) -> None:
"""Create or update the service (stopping it first if it runs), then start it."""
import pywintypes
import win32service
import winerror
import winreg
manager = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
try:
args = (win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START,
win32service.SERVICE_ERROR_NORMAL, image_path(python), None, False, None)
try:
service = win32service.OpenService(manager, hw_main.SERVICE_NAME, win32service.SERVICE_ALL_ACCESS)
except pywintypes.error as e:
if e.winerror != winerror.ERROR_SERVICE_DOES_NOT_EXIST:
raise
service = win32service.CreateService(manager, hw_main.SERVICE_NAME, hw_main.SERVICE_DISPLAY_NAME,
win32service.SERVICE_ALL_ACCESS, *args, None, None)
print(f"Created the {hw_main.SERVICE_DISPLAY_NAME!r} service ({hw_main.SERVICE_NAME})")
else:
if win32service.QueryServiceStatus(service)[1] != win32service.SERVICE_STOPPED:
print("Stopping the running hardware service (case fans to 100% meanwhile)...")
win32service.ControlService(service, win32service.SERVICE_CONTROL_STOP)
if _wait(service, win32service.SERVICE_STOPPED, hw_main.STOP_SECONDS + 10) != win32service.SERVICE_STOPPED:
raise RuntimeError("the hardware service didn't stop; try again, or reboot")
win32service.ChangeServiceConfig(service, *args, "LocalSystem", None, hw_main.SERVICE_DISPLAY_NAME)
print(f"Updated the {hw_main.SERVICE_DISPLAY_NAME!r} service ({hw_main.SERVICE_NAME})")
try:
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_DESCRIPTION, DESCRIPTION)
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, failure_actions())
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, True)
with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, hw_main.PARAMETERS_KEY, 0, winreg.KEY_SET_VALUE) as key:
winreg.SetValueEx(key, "UserSid", 0, winreg.REG_SZ, user_sid)
win32service.StartService(service, None)
state = _wait(service, win32service.SERVICE_RUNNING, 30)
if state != win32service.SERVICE_RUNNING:
raise RuntimeError(f"the hardware service didn't start (state {state}); see {paths.HW_LOG_PATH}")
print(f"The hardware service is running. Log: {paths.HW_LOG_PATH}")
finally:
win32service.CloseServiceHandle(service)
finally:
win32service.CloseServiceHandle(manager)
def main(argv: list[str] | None = None) -> int:
from kurgan.hw import migrate
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.install", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--python", required=True, help="the base interpreter's python.exe (not the venv's)")
ap.add_argument("--user-sid", required=True, help="the user whose app may use the pipe")
ap.add_argument("--user-settings", required=True, help="that user's settings.json, to move settings from")
args = ap.parse_args(argv)
if not valid_sid(args.user_sid):
ap.error(f"not a SID: {args.user_sid!r}")
if not os.path.isfile(args.python):
ap.error(f"no such interpreter: {args.python}")
try:
print(check(args.python))
reset_data_dir()
print(migrate.copy(args.user_settings))
install(args.python, args.user_sid)
except Exception as e: # setup.ps1 shows this and stops
print(f"error: {type(e).__name__}: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+161
View File
@@ -0,0 +1,161 @@
"""Starting and stopping the hardware service's parts: settings, the hardware loop, RAM lighting
and the pipe.
python -m kurgan.hw in a console (elevated), Ctrl+C to stop: for debugging, with the
real service stopped (only one copy runs)
As a Windows service it is started through hw_service.py (see kurgan/hw/winservice.py).
"""
from __future__ import annotations
import argparse
import ctypes
import logging
import logging.handlers
import os
import sys
import threading
import winreg
from kurgan import __version__, paths
log = logging.getLogger("kurgan.hw")
SERVICE_NAME = "KurganHw"
SERVICE_DISPLAY_NAME = "The Kurgan hardware"
PARAMETERS_KEY = rf"SYSTEM\CurrentControlSet\Services\{SERVICE_NAME}\Parameters"
INSTANCE_MUTEX = "Global\\KurganHw"
STOP_SECONDS = 30.0 # how long a stop may take: the loop's last pass plus handing the fans back
def setup_logging(console: bool, verbose: bool = False) -> None:
from kurgan.hw.settings import ensure_data_dir
ensure_data_dir()
handlers: list[logging.Handler] = [logging.handlers.RotatingFileHandler(
paths.HW_LOG_PATH, maxBytes=1_000_000, backupCount=3, encoding="utf-8")]
if console and sys.stderr is not None:
handlers.append(logging.StreamHandler())
logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO, handlers=handlers, force=True,
format="%(asctime)s %(levelname)s %(threadName)s %(name)s: %(message)s")
def configured_user_sid() -> str | None:
"""The installing user's SID, from the service's Parameters key (written by setup.ps1)."""
from kurgan.hw.pipe import valid_sid
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, PARAMETERS_KEY) as key:
value, kind = winreg.QueryValueEx(key, "UserSid")
except OSError:
return None
if kind != winreg.REG_SZ or not valid_sid(value):
log.error("Ignoring the invalid UserSid %r in HKLM\\%s", value, PARAMETERS_KEY)
return None
return value
def user_appdata(sid: str | None) -> str | None:
"""That user's roaming AppData folder, from their profile's registry entry."""
if sid is None:
return None
try:
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,
rf"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\{sid}") as key:
profile = os.path.expandvars(winreg.QueryValueEx(key, "ProfileImagePath")[0])
except OSError:
return None
return os.path.join(profile, "AppData", "Roaming")
def single_instance():
"""A handle that keeps a second copy out, or None if one is already running."""
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
k32.CreateMutexW.restype = ctypes.c_void_p
k32.CloseHandle.argtypes = [ctypes.c_void_p]
handle = k32.CreateMutexW(None, False, INSTANCE_MUTEX)
if not handle or ctypes.get_last_error() in (183, 5): # ERROR_ALREADY_EXISTS, ERROR_ACCESS_DENIED
if handle:
k32.CloseHandle(handle)
return None
return handle
def load_settings():
"""(settings, None), or (None, why) when hw-settings.json can't be used."""
from kurgan.hw import settings as hw_settings
from kurgan.settings import SettingsError
try:
return hw_settings.load(), None
except (OSError, SettingsError) as e:
log.error("hw-settings.json can't be used; holding every case fan at 100%%: %s", e)
return None, str(e)
def serve(stop: threading.Event, user_sid: str | None, *, service=None, pipe_name: str | None = None) -> None:
"""Run until `stop` is set. The fans are controlled whatever happens to the pipe."""
from kurgan.hw.pipe import PipeServer, pipe_sddl
from kurgan.hw.protocol import PIPE_NAME, Session
from kurgan.telemetry import sensors
if service is None:
from kurgan.hw.service import HardwareService
sensors.USER_APPDATA = user_appdata(user_sid)
service = HardwareService(*load_settings())
if user_sid is None:
log.warning("No user is configured for the pipe (HKLM\\%s UserSid); only SYSTEM and Administrators "
"can connect. Run setup.ps1 again.", PARAMETERS_KEY)
loop = threading.Thread(target=service.run, args=(stop,), name="hw-loop")
loop.start()
lighting = service.start_lighting(stop)
server = None
try:
server = PipeServer(pipe_name or PIPE_NAME, pipe_sddl(user_sid),
lambda: Session(service.dispatch, __version__))
server.start()
log.info("Listening on %s for %s", pipe_name or PIPE_NAME, user_sid or "SYSTEM and Administrators only")
except Exception:
log.exception("The pipe is unavailable; fan control carries on without it")
try:
while loop.is_alive() and not stop.wait(1.0):
pass
finally:
stop.set()
loop.join(STOP_SECONDS)
if server is not None:
server.close()
lighting.join(10)
if loop.is_alive():
log.error("The hardware loop didn't stop within %.0f s", STOP_SECONDS)
def main(argv: list[str] | None = None) -> int:
from kurgan.hw.pipe import current_user_sid, valid_sid
ap = argparse.ArgumentParser(prog="python -m kurgan.hw", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--user-sid", help="the user allowed on the pipe (default: the configured one, else you)")
ap.add_argument("-v", "--verbose", action="store_true")
args = ap.parse_args(argv)
setup_logging(console=True, verbose=args.verbose)
if args.user_sid is not None and not valid_sid(args.user_sid):
ap.error(f"not a SID: {args.user_sid}")
mutex = single_instance()
if mutex is None:
log.error("The hardware service is already running (Stop-Service %s first)", SERVICE_NAME)
return 1
log.info("Starting %s %s in a console (pid %s)", SERVICE_DISPLAY_NAME, __version__, os.getpid())
stop = threading.Event()
worker = threading.Thread(target=serve, args=(stop, args.user_sid or configured_user_sid() or current_user_sid()),
name="hw-serve")
worker.start()
try:
while worker.is_alive():
worker.join(0.5)
except KeyboardInterrupt:
log.info("Stopping")
stop.set()
worker.join(STOP_SECONDS + 15)
return 0
+113
View File
@@ -0,0 +1,113 @@
"""Moving the fan and RAM lighting settings from the user's settings.json to hw-settings.json.
setup.ps1 runs both halves, once per install; each is safe to run again:
python -m kurgan.hw.migrate copy USER_SETTINGS elevated: create hw-settings.json from the user's
`cooling` and `lighting.memory`, unless it exists
python -m kurgan.hw.migrate strip as the user: once hw-settings.json exists, remove
them from settings.json, keeping a dated backup
An invalid file on either side stops the move (and setup) rather than lose a setting.
"""
from __future__ import annotations
import argparse
import copy as _copy
import json
import os
import shutil
import sys
import time
from kurgan import paths
from kurgan.hw import settings as hw_settings
from kurgan.settings import SettingsError, validate, write_json_atomic
def _read_json(path: str) -> dict | None:
"""The file's contents, or None if it doesn't exist; SettingsError if it isn't valid JSON."""
try:
with open(path, encoding="utf-8") as stream:
return json.load(stream)
except FileNotFoundError:
return None
except ValueError as e:
raise SettingsError(f"{path}: {e}") from None
def hardware_sections(user: dict) -> dict:
"""The parts of a user settings.json that belong to the hardware service."""
out: dict = {}
if isinstance(user.get("cooling"), dict):
out["cooling"] = dict(user["cooling"])
lighting = user.get("lighting")
if isinstance(lighting, dict) and "memory" in lighting:
out["lighting"] = {"memory": lighting["memory"]}
return out
def copy(user_path: str, hw_path: str = paths.HW_SETTINGS_PATH) -> str:
"""Create hw-settings.json from the user's settings, unless it exists. Returns what it did."""
if os.path.exists(hw_path):
return f"{hw_path} already exists; left as it is"
raw = _read_json(user_path)
sections = {}
if raw is not None:
try:
sections = hardware_sections(validate(raw))
except SettingsError as e:
raise SettingsError(f"{user_path}: {e}") from None
try:
data = hw_settings.validate(sections)
except SettingsError as e:
raise SettingsError(f"{user_path}'s fan or RAM settings can't move: {e}") from None
write_json_atomic(hw_path, data)
moved = [name for name, present in (("cooling", "cooling" in sections),
("lighting.memory", "lighting" in sections)) if present]
return f"Created {hw_path}" + (f" with {' and '.join(moved)} from {user_path}" if moved else " with the defaults")
def strip(user_path: str = paths.SETTINGS_PATH, hw_path: str = paths.HW_SETTINGS_PATH, now: float | None = None) -> str:
"""Remove the hardware sections from the user's settings.json, once hw-settings.json exists."""
if not os.path.exists(hw_path):
return f"{hw_path} doesn't exist yet; settings.json left as it is"
raw = _read_json(user_path)
if raw is None or not hardware_sections(raw):
return f"Nothing to move out of {user_path}"
stripped = _copy.deepcopy(raw)
stripped.pop("cooling", None)
if isinstance(stripped.get("lighting"), dict):
stripped["lighting"].pop("memory", None)
try:
data = validate(stripped)
except SettingsError as e:
raise SettingsError(f"{user_path}: {e}") from None
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
backup = f"{user_path}.{stamp}.bak"
shutil.copy2(user_path, backup)
write_json_atomic(user_path, data)
return f"Removed the fan and RAM lighting settings from {user_path} (now in {hw_path}); backup: {backup}"
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.migrate", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="action", required=True)
sub.add_parser("copy", help="create hw-settings.json (elevated)").add_argument("user_settings")
sub.add_parser("strip", help="tidy the user's settings.json (as the user)")
args = ap.parse_args(argv)
try:
if args.action == "copy":
hw_settings.ensure_data_dir()
print(copy(args.user_settings))
else:
print(strip())
except (OSError, SettingsError) as e:
print(f"error: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+478
View File
@@ -0,0 +1,478 @@
"""The named pipe between the hardware service and the app: server and client, with timeouts.
Server (the service): every connection gets its own thread, so a slow or hostile client can
only waste its own slot, never the fan loop's time. A connection that sends nothing, or leaves
a line unfinished, for READ_TIMEOUT seconds is dropped, and so is one that won't read its
replies. The pipe refuses remote clients, and its access list (pipe_sddl) allows SYSTEM and
Administrators full access and the installing user read/write only: no
FILE_CREATE_PIPE_INSTANCE, so the user's other programs can't add an instance of their own and
answer in the service's name. The first instance is created with FILE_FLAG_FIRST_PIPE_INSTANCE,
so a program that took the name first makes the service fail loudly instead of sharing it.
Client (the app): connects at identification level only (the service can't act as the user),
and refuses a pipe whose owner isn't SYSTEM or Administrators, i.e. one that some unelevated
program created while the service was down.
"""
from __future__ import annotations
import ctypes
import ctypes.wintypes as wt
import logging
import re
import threading
import time
from typing import Callable
from kurgan.hw.protocol import READ_TIMEOUT, TOO_LARGE, LineBuffer, ProtocolError, encode_error
log = logging.getLogger(__name__)
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
ERROR_FILE_NOT_FOUND = 2
ERROR_ACCESS_DENIED = 5
ERROR_BROKEN_PIPE = 109
ERROR_PIPE_BUSY = 231
ERROR_NO_DATA = 232
ERROR_MORE_DATA = 234
ERROR_PIPE_CONNECTED = 535
ERROR_OPERATION_ABORTED = 995
ERROR_IO_PENDING = 997
WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
INFINITE = 0xFFFFFFFF
INVALID_HANDLE = wt.HANDLE(-1).value
PIPE_ACCESS_DUPLEX = 0x3
FILE_FLAG_OVERLAPPED = 0x40000000
FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000
PIPE_TYPE_BYTE = PIPE_READMODE_BYTE = PIPE_WAIT = 0
PIPE_REJECT_REMOTE_CLIENTS = 0x8
GENERIC_READ = 0x80000000
FILE_WRITE_DATA = 0x2
OPEN_EXISTING = 3
SECURITY_SQOS_PRESENT = 0x00100000
SECURITY_IDENTIFICATION = 0x00010000
SE_KERNEL_OBJECT = 6
OWNER_SECURITY_INFORMATION = 0x1
TOKEN_QUERY, TOKEN_USER = 0x8, 1
# What the installing user gets on the pipe: FILE_GENERIC_READ | FILE_WRITE_DATA |
# FILE_WRITE_ATTRIBUTES. Deliberately not GENERIC_WRITE, which includes FILE_APPEND_DATA, i.e.
# FILE_CREATE_PIPE_INSTANCE for a pipe.
USER_ACCESS = 0x0012018B
SYSTEM_SID, ADMINISTRATORS_SID = "S-1-5-18", "S-1-5-32-544"
TRUSTED_OWNERS = (SYSTEM_SID, ADMINISTRATORS_SID)
BUFFER_SIZE = 128 * 1024
_SID = re.compile(r"S-1-\d+(-\d+)+")
class _Overlapped(ctypes.Structure):
_fields_ = [("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t),
("Offset", wt.DWORD), ("OffsetHigh", wt.DWORD), ("hEvent", wt.HANDLE)]
class _SecurityAttributes(ctypes.Structure):
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)]
class _SidAndAttributes(ctypes.Structure):
_fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)]
_k32.CreateNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD,
ctypes.POINTER(_SecurityAttributes)]
_k32.CreateNamedPipeW.restype = wt.HANDLE
_k32.ConnectNamedPipe.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped)]
_k32.ConnectNamedPipe.restype = wt.BOOL
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
_k32.CreateFileW.restype = wt.HANDLE
_k32.WaitNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD]
_k32.WaitNamedPipeW.restype = wt.BOOL
_k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_Overlapped)]
_k32.ReadFile.restype = wt.BOOL
_k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_Overlapped)]
_k32.WriteFile.restype = wt.BOOL
_k32.GetOverlappedResult.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped), ctypes.POINTER(wt.DWORD), wt.BOOL]
_k32.GetOverlappedResult.restype = wt.BOOL
_k32.CancelIoEx.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped)]
_k32.CancelIoEx.restype = wt.BOOL
_k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR]
_k32.CreateEventW.restype = wt.HANDLE
_k32.SetEvent.argtypes = [wt.HANDLE]
_k32.SetEvent.restype = wt.BOOL
_k32.ResetEvent.argtypes = [wt.HANDLE]
_k32.ResetEvent.restype = wt.BOOL
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
_k32.WaitForSingleObject.restype = wt.DWORD
_k32.WaitForMultipleObjects.argtypes = [wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.BOOL, wt.DWORD]
_k32.WaitForMultipleObjects.restype = wt.DWORD
_k32.CloseHandle.argtypes = [wt.HANDLE]
_k32.CloseHandle.restype = wt.BOOL
_k32.LocalFree.argtypes = [ctypes.c_void_p]
_k32.LocalFree.restype = ctypes.c_void_p
_k32.GetCurrentProcess.restype = wt.HANDLE
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wt.LPCWSTR, wt.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wt.ULONG)]
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wt.BOOL
_adv.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.LPWSTR)]
_adv.ConvertSidToStringSidW.restype = wt.BOOL
_adv.GetSecurityInfo.argtypes = [wt.HANDLE, ctypes.c_int, wt.DWORD, ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p),
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p)]
_adv.GetSecurityInfo.restype = wt.DWORD
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
_adv.OpenProcessToken.restype = wt.BOOL
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD)]
_adv.GetTokenInformation.restype = wt.BOOL
class PipeError(OSError):
"""The pipe couldn't be opened, read or written; .code is the Windows error, when there was one."""
def __init__(self, message: str, code: int | None = None):
super().__init__(message)
self.code = code
def _error(what: str, code: int | None = None) -> PipeError:
code = ctypes.get_last_error() if code is None else code
return PipeError(f"{what}: [{code}] {ctypes.FormatError(code).strip()}", code)
def _sid_string(sid: int) -> str:
text = wt.LPWSTR()
if not _adv.ConvertSidToStringSidW(sid, ctypes.byref(text)):
raise _error("ConvertSidToStringSid")
try:
return text.value
finally:
_k32.LocalFree(text)
def current_user_sid() -> str:
"""This process's user SID, e.g. S-1-5-21-...-1001."""
token = wt.HANDLE()
if not _adv.OpenProcessToken(_k32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(token)):
raise _error("OpenProcessToken")
try:
size = wt.DWORD()
_adv.GetTokenInformation(token, TOKEN_USER, None, 0, ctypes.byref(size))
buf = ctypes.create_string_buffer(size.value)
if not _adv.GetTokenInformation(token, TOKEN_USER, buf, size, ctypes.byref(size)):
raise _error("GetTokenInformation(TokenUser)")
return _sid_string(_SidAndAttributes.from_buffer(buf).Sid)
finally:
_k32.CloseHandle(token)
def valid_sid(text: object) -> bool:
return isinstance(text, str) and _SID.fullmatch(text) is not None
def pipe_sddl(user_sid: str | None, server_sid: str | None = None) -> str:
"""The pipe's access list: SYSTEM and Administrators full, `user_sid` read/write, nobody else.
server_sid also gets full access; only for a server that isn't SYSTEM or an elevated admin
(tests), since creating each further instance of the pipe needs FILE_CREATE_PIPE_INSTANCE."""
aces = ["(A;;GA;;;SY)", "(A;;GA;;;BA)"]
for sid, access in ((server_sid, "GA"), (user_sid, f"0x{USER_ACCESS:x}")):
if sid is not None:
if not valid_sid(sid):
raise ValueError(f"not a SID: {sid!r}")
aces.append(f"(A;;{access};;;{sid})")
return "D:P" + "".join(aces)
def pipe_owner(handle) -> str:
owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
code = _adv.GetSecurityInfo(handle, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, ctypes.byref(owner),
None, None, None, ctypes.byref(descriptor))
if code != 0:
raise _error("GetSecurityInfo", code)
try:
return _sid_string(owner.value)
finally:
_k32.LocalFree(descriptor)
def _event() -> wt.HANDLE:
event = _k32.CreateEventW(None, True, False, None)
if not event:
raise _error("CreateEvent")
return event
def _ms(seconds: float | None) -> int:
return INFINITE if seconds is None else max(0, min(int(seconds * 1000), INFINITE - 1))
def _finish(handle, ov: _Overlapped, events: list, timeout: float | None) -> int | None:
"""Wait for a pending overlapped call: bytes transferred, or None if it timed out or another
event (a stop request) fired first, in which case the call is cancelled and waited for, so
its buffer and OVERLAPPED can be freed. Raises PipeError if the call failed."""
handles = (wt.HANDLE * (1 + len(events)))(ov.hEvent, *events)
which = _k32.WaitForMultipleObjects(len(handles), handles, False, _ms(timeout))
done = wt.DWORD()
if which != WAIT_OBJECT_0:
_k32.CancelIoEx(handle, ctypes.byref(ov))
if _k32.GetOverlappedResult(handle, ctypes.byref(ov), ctypes.byref(done), True):
return done.value # it completed before the cancel landed
return None
if not _k32.GetOverlappedResult(handle, ctypes.byref(ov), ctypes.byref(done), False):
code = ctypes.get_last_error()
if code == ERROR_MORE_DATA:
return done.value
raise _error("pipe I/O", code)
return done.value
def _read(handle, event, timeout: float | None, stop_events=(), size: int = 65536) -> bytes | None:
"""Up to `size` bytes; b"" when the other end has closed; None on timeout or stop."""
buf = ctypes.create_string_buffer(size)
ov = _Overlapped(hEvent=event)
_k32.ResetEvent(event)
if not _k32.ReadFile(handle, buf, size, None, ctypes.byref(ov)):
code = ctypes.get_last_error()
if code in (ERROR_BROKEN_PIPE, ERROR_NO_DATA):
return b""
if code not in (ERROR_IO_PENDING, ERROR_MORE_DATA):
raise _error("ReadFile", code)
try:
got = _finish(handle, ov, list(stop_events), timeout)
except PipeError as e:
if e.code in (ERROR_BROKEN_PIPE, ERROR_NO_DATA, ERROR_OPERATION_ABORTED):
return b""
raise
return None if got is None else buf.raw[:got]
def _write(handle, event, data: bytes, timeout: float, stop_events=()) -> None:
buf = ctypes.create_string_buffer(data, len(data))
ov = _Overlapped(hEvent=event)
_k32.ResetEvent(event)
if not _k32.WriteFile(handle, buf, len(data), None, ctypes.byref(ov)):
code = ctypes.get_last_error()
if code != ERROR_IO_PENDING:
raise _error("WriteFile", code)
sent = _finish(handle, ov, list(stop_events), timeout)
if sent is None:
raise PipeError("pipe write timed out (the other end isn't reading)")
if sent != len(data):
raise PipeError(f"pipe write sent {sent} of {len(data)} bytes")
# ----------------------------------------------------------------------------- server
class PipeServer:
"""Serves `session_factory()` sessions (protocol.Session) on a named pipe, one thread each."""
def __init__(self, name: str, sddl: str, session_factory: Callable, *, max_clients: int = 8,
read_timeout: float = READ_TIMEOUT, write_timeout: float = 5.0):
self.name = name
self.max_clients = max_clients
self.read_timeout = read_timeout
self.write_timeout = write_timeout
self._sessions = session_factory
self._descriptor = ctypes.c_void_p()
if not _adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1, ctypes.byref(self._descriptor),
None):
raise _error(f"Invalid pipe security descriptor {sddl!r}")
self._attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), self._descriptor, False)
self._stop = _event()
self._stopping = False
self._lock = threading.Condition()
self._clients = 0
self._threads: list[threading.Thread] = []
self._listener: threading.Thread | None = None
self.error: str | None = None # why the pipe can't be created right now, for the snapshot
def start(self) -> None:
self._listener = threading.Thread(target=self._listen, name="hw-pipe", daemon=True)
self._listener.start()
def close(self, timeout: float = 5.0) -> None:
self._stopping = True
_k32.SetEvent(self._stop)
with self._lock:
self._lock.notify_all()
deadline = time.monotonic() + timeout
for thread in [self._listener, *list(self._threads)]:
if thread is not None:
thread.join(max(0.0, deadline - time.monotonic()))
if self._descriptor and not (self._listener is not None and self._listener.is_alive()):
_k32.LocalFree(self._descriptor)
self._descriptor = ctypes.c_void_p()
@property
def clients(self) -> int:
with self._lock:
return self._clients
def _create(self) -> wt.HANDLE | None:
with self._lock:
first = self._clients == 0
mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | (FILE_FLAG_FIRST_PIPE_INSTANCE if first else 0)
handle = _k32.CreateNamedPipeW(self.name, mode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT
| PIPE_REJECT_REMOTE_CLIENTS, self.max_clients, BUFFER_SIZE, BUFFER_SIZE,
0, ctypes.byref(self._attributes))
if handle == INVALID_HANDLE or not handle:
code = ctypes.get_last_error()
hint = (" (another program holds the pipe's name)" if code == ERROR_ACCESS_DENIED and first
else "")
message = f"can't create {self.name}: [{code}] {ctypes.FormatError(code).strip()}{hint}"
if message != self.error:
log.error("Pipe server %s; retrying", message)
self.error = message
return None
if self.error is not None:
log.info("Pipe server listening on %s again", self.name)
self.error = None
return handle
def _listen(self) -> None:
event = _event()
try:
while not self._stopping:
with self._lock:
if self._clients >= self.max_clients: # wait for a slot (each times out eventually)
self._lock.wait(0.5)
continue
handle = self._create()
if handle is None:
if _k32.WaitForSingleObject(self._stop, 5000) == WAIT_OBJECT_0:
break
continue
ov = _Overlapped(hEvent=event)
_k32.ResetEvent(event)
connected = bool(_k32.ConnectNamedPipe(handle, ctypes.byref(ov)))
if not connected:
code = ctypes.get_last_error()
if code == ERROR_PIPE_CONNECTED:
connected = True
elif code == ERROR_IO_PENDING:
try:
connected = _finish(handle, ov, [self._stop], None) is not None
except PipeError as e:
log.debug("Pipe connect failed: %s", e)
else:
log.debug("ConnectNamedPipe failed: [%d]", code)
if not connected or self._stopping:
_k32.CloseHandle(handle)
continue
with self._lock:
self._clients += 1
thread = threading.Thread(target=self._serve, args=(handle,), name="hw-pipe-client", daemon=True)
self._threads = [t for t in self._threads if t.is_alive()] + [thread]
thread.start()
except Exception:
log.exception("Pipe listener failed")
self.error = "pipe listener failed; see the service log"
finally:
_k32.CloseHandle(event)
def _serve(self, handle) -> None:
read_event, write_event = _event(), _event()
session = self._sessions()
buffer = LineBuffer()
line_started: float | None = None
try:
while not self._stopping:
now = time.monotonic()
deadline = (line_started or now) + self.read_timeout
data = _read(handle, read_event, max(0.0, deadline - now), [self._stop])
if not data: # closed, timed out (silent too long, or a line left unfinished), or stopping
if data is None and not self._stopping:
log.debug("Dropping a pipe client that sent nothing for %.0f s", self.read_timeout)
return
try:
lines = buffer.feed(data)
except ProtocolError as e:
_write(handle, write_event, encode_error(None, TOO_LARGE, str(e)), self.write_timeout,
[self._stop])
return
line_started = (line_started or time.monotonic()) if buffer.partial else None
for line in lines:
reply, close = session.handle(line)
_write(handle, write_event, reply, self.write_timeout, [self._stop])
if close:
return
except PipeError as e:
log.debug("Pipe client dropped: %s", e)
except Exception:
log.exception("Pipe client failed")
finally:
# No DisconnectNamedPipe: it would discard a last reply the client hasn't read yet.
_k32.CloseHandle(handle)
for event in (read_event, write_event):
_k32.CloseHandle(event)
with self._lock:
self._clients -= 1
self._lock.notify_all()
# ----------------------------------------------------------------------------- client
class PipeClient:
"""One connection to the service. Not thread-safe: callers serialise request()."""
def __init__(self, name: str, timeout: float = 2.0, trusted_owners: tuple[str, ...] | None = TRUSTED_OWNERS):
deadline = time.monotonic() + timeout
while True:
handle = _k32.CreateFileW(name, GENERIC_READ | FILE_WRITE_DATA, 0, None, OPEN_EXISTING,
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, None)
if handle != INVALID_HANDLE and handle:
break
code = ctypes.get_last_error()
left = deadline - time.monotonic()
if code == ERROR_PIPE_BUSY and left > 0:
_k32.WaitNamedPipeW(name, max(1, int(left * 1000)))
continue
if code == ERROR_FILE_NOT_FOUND:
raise PipeError("the hardware service isn't running (no pipe)", code)
if code == ERROR_ACCESS_DENIED:
raise PipeError("the hardware service's pipe refused this user", code)
raise _error(f"can't open {name}", code)
self._handle = handle
self._read_event, self._write_event = _event(), _event()
self._buffer = LineBuffer()
self._lines: list[bytes] = []
if trusted_owners is not None:
try:
owner = pipe_owner(handle)
except OSError:
self.close()
raise
if owner not in trusted_owners:
self.close()
raise PipeError(f"{name} belongs to {owner}, not the hardware service; not using it")
def request(self, data: bytes, timeout: float) -> bytes:
"""Send one line, return the next line received (without its newline)."""
if self._handle is None:
raise PipeError("pipe closed")
deadline = time.monotonic() + timeout
_write(self._handle, self._write_event, data, timeout)
while not self._lines:
left = deadline - time.monotonic()
chunk = _read(self._handle, self._read_event, max(0.0, left)) if left > 0 else None
if chunk is None:
raise PipeError(f"no reply from the hardware service within {timeout:g} s")
if not chunk:
raise PipeError("the hardware service closed the connection", ERROR_BROKEN_PIPE)
self._lines += self._buffer.feed(chunk)
return self._lines.pop(0)
def close(self) -> None:
for name in ("_handle", "_read_event", "_write_event"):
handle = getattr(self, name, None)
if handle:
_k32.CloseHandle(handle)
setattr(self, name, None)
def __del__(self):
try:
self.close()
except Exception:
pass
+315
View File
@@ -0,0 +1,315 @@
"""The hardware service's pipe protocol: newline-delimited JSON between the app and kurgan.hw.
request {"op": "state", "args": {}, "id": 7}
reply {"id": 7, "ok": true, "result": {...}}
{"id": 7, "ok": false, "error": {"code": "invalid", "message": "..."}}
Operations and their arguments:
hello {"protocol": 1, "client": "..."} the first request on every connection
state {} the service's latest snapshot
set_profile {"profile": "quiet"|"balanced"|"performance"|"full"}
set_ram_lighting {"mode": "off"|"temperature"|"chase"}
ram_chase {"phase": n, "rate": n, "power": n|null}
the app's chase clock, about once a second while the RAM chases, so the
RAM stays in step with the case fan and GPU chases
Each message is one line of UTF-8 JSON, at most MAX_MESSAGE bytes. Rejected: unknown
operations, unknown, missing or mistyped fields, NaN and Infinity, duplicate keys, and any
request before a successful hello. A protocol version mismatch is answered and the connection
closed. A line over MAX_MESSAGE closes the connection, since the stream can't be trusted after it.
"""
from __future__ import annotations
import json
import logging
import math
from dataclasses import dataclass, field
from typing import Callable
from kurgan.cooling.profiles import PROFILES
from kurgan.settings import LIGHTING_MODES
log = logging.getLogger(__name__)
PIPE_NAME = r"\\.\pipe\kurgan-hw"
PROTOCOL_VERSION = 1
MAX_MESSAGE = 64 * 1024
READ_TIMEOUT = 30.0 # seconds a connection may stay silent (or mid-line) before the service drops it
# Error codes
BAD_REQUEST = "bad_request" # not a well-formed request
UNKNOWN_OP = "unknown_op"
INVALID = "invalid" # well-formed, but the arguments are wrong
HELLO_FIRST = "hello_first"
VERSION = "version"
TOO_LARGE = "too_large"
UNAVAILABLE = "unavailable" # the service can't do that right now
INTERNAL = "internal"
_MAX_ID = 2 ** 53
_MAX_TEXT = 64
class ProtocolError(Exception):
def __init__(self, code: str, message: str, request_id: int | str | None = None):
super().__init__(message)
self.code = code
self.request_id = request_id
class RemoteError(Exception):
"""The service answered with an error."""
def __init__(self, code: str, message: str):
super().__init__(message)
self.code = code
class Unavailable(OSError):
"""Raised by the service's operations when they can't run now (answered as UNAVAILABLE)."""
# ----------------------------------------------------------------------------- argument checks
def _integer(low: int, high: int):
def check(name: str, value) -> int:
if type(value) is not int or not low <= value <= high:
raise ValueError(f"{name} must be a whole number from {low} to {high}")
return value
return check
def _number(low: float, high: float, nullable: bool = False):
def check(name: str, value) -> float | None:
if value is None and nullable:
return None
if type(value) not in (int, float) or not math.isfinite(value) or not low <= value <= high:
raise ValueError(f"{name} must be a number from {low:g} to {high:g}" + (" or null" if nullable else ""))
return float(value)
return check
def _text(max_length: int = _MAX_TEXT):
def check(name: str, value) -> str:
if not isinstance(value, str) or len(value) > max_length:
raise ValueError(f"{name} must be a string of at most {max_length} characters")
return value
return check
def _choice(choices):
choices = tuple(choices)
def check(name: str, value) -> str:
if value not in choices or not isinstance(value, str):
raise ValueError(f"{name} must be one of {', '.join(choices)}")
return value
return check
# op -> {field: (check, required)}
OPERATIONS: dict[str, dict[str, tuple[Callable, bool]]] = {
"hello": {"protocol": (_integer(0, 1_000_000), True), "client": (_text(), False)},
"state": {},
"set_profile": {"profile": (_choice(PROFILES), True)},
"set_ram_lighting": {"mode": (_choice(LIGHTING_MODES["memory"]), True)},
"ram_chase": {"phase": (_number(-1e12, 1e12), True), "rate": (_number(0, 1000), True),
"power": (_number(0, 100_000, nullable=True), True)},
}
def check_args(op: str, args: object) -> dict:
"""The arguments, normalised, or ValueError."""
if not isinstance(args, dict):
raise ValueError("args must be an object")
schema = OPERATIONS[op]
unknown = set(args) - set(schema)
if unknown:
raise ValueError(f"{op}: unknown field(s): {', '.join(sorted(map(str, unknown)))}")
out = {}
for name, (check, required) in schema.items():
if name in args:
out[name] = check(name, args[name])
elif required:
raise ValueError(f"{op}: {name} is required")
return out
# ----------------------------------------------------------------------------- encoding
def _no_duplicates(pairs):
out = {}
for key, value in pairs:
if key in out:
raise ValueError(f"duplicate key {key!r}")
out[key] = value
return out
def _reject_constant(name: str):
raise ValueError(f"{name} is not valid JSON")
def _loads(line: bytes):
if len(line) > MAX_MESSAGE:
raise ProtocolError(TOO_LARGE, f"message over {MAX_MESSAGE} bytes")
try:
return json.loads(line.decode("utf-8"), object_pairs_hook=_no_duplicates, parse_constant=_reject_constant)
except (UnicodeDecodeError, ValueError, RecursionError) as e:
raise ProtocolError(BAD_REQUEST, f"not valid JSON: {e}") from None
def encode(message: dict) -> bytes:
"""One line of JSON, newline included. ValueError if it can't be sent."""
data = json.dumps(message, separators=(",", ":"), allow_nan=False).encode("utf-8")
if len(data) > MAX_MESSAGE:
raise ValueError(f"message over {MAX_MESSAGE} bytes")
return data + b"\n"
@dataclass
class Request:
op: str
args: dict = field(default_factory=dict)
id: int | str = 0
def _check_id(value) -> int | str:
if type(value) is int and -_MAX_ID < value < _MAX_ID:
return value
if isinstance(value, str) and len(value) <= _MAX_TEXT:
return value
raise ValueError("id must be an integer or a short string")
def decode_request(line: bytes) -> Request:
data = _loads(line)
if not isinstance(data, dict):
raise ProtocolError(BAD_REQUEST, "a request must be a JSON object")
request_id = None
if "id" in data:
try:
request_id = _check_id(data["id"])
except ValueError as e:
raise ProtocolError(BAD_REQUEST, str(e)) from None
unknown = set(data) - {"op", "args", "id"}
if unknown:
raise ProtocolError(BAD_REQUEST, f"unknown field(s): {', '.join(sorted(unknown))}", request_id)
if request_id is None:
raise ProtocolError(BAD_REQUEST, "id is required")
op = data.get("op")
if not isinstance(op, str):
raise ProtocolError(BAD_REQUEST, "op is required", request_id)
if op not in OPERATIONS:
raise ProtocolError(UNKNOWN_OP, f"unknown operation {op[:_MAX_TEXT]!r}", request_id)
try:
args = check_args(op, data.get("args", {}))
except ValueError as e:
raise ProtocolError(INVALID, str(e), request_id) from None
return Request(op, args, request_id)
def encode_request(op: str, args: dict | None, request_id: int | str) -> bytes:
"""Checked like the service checks it, so a bad call fails here, before anything is sent."""
if op not in OPERATIONS:
raise ValueError(f"unknown operation {op!r}")
return encode({"op": op, "args": check_args(op, args or {}), "id": _check_id(request_id)})
def encode_reply(request_id, result) -> bytes:
return encode({"id": request_id, "ok": True, "result": result})
def encode_error(request_id, code: str, message: str) -> bytes:
return encode({"id": request_id, "ok": False, "error": {"code": code, "message": message[:1000]}})
def decode_reply(line: bytes, request_id: int | str):
"""The result of the reply to `request_id`; RemoteError for an error reply, ProtocolError
(BAD_REQUEST) for anything that isn't a well-formed reply to that request."""
data = _loads(line)
if not isinstance(data, dict) or data.get("id") != request_id or type(data.get("ok")) is not bool:
raise ProtocolError(BAD_REQUEST, "not a reply to this request")
if data["ok"]:
if set(data) != {"id", "ok", "result"}:
raise ProtocolError(BAD_REQUEST, "malformed reply")
return data["result"]
error = data.get("error")
if (set(data) != {"id", "ok", "error"} or not isinstance(error, dict) or set(error) != {"code", "message"}
or not all(isinstance(v, str) for v in error.values())):
raise ProtocolError(BAD_REQUEST, "malformed error reply")
raise RemoteError(error["code"], error["message"])
# ----------------------------------------------------------------------------- framing and sessions
class LineBuffer:
"""Splits a byte stream into lines; ProtocolError(TOO_LARGE) once a line can't fit."""
def __init__(self, limit: int = MAX_MESSAGE):
self.limit = limit
self._pending = bytearray()
def feed(self, data: bytes) -> list[bytes]:
self._pending += data
lines = []
while True:
end = self._pending.find(b"\n")
if end < 0:
break
line = bytes(self._pending[:end])
del self._pending[:end + 1]
if len(line) > self.limit:
raise ProtocolError(TOO_LARGE, f"message over {self.limit} bytes")
lines.append(line[:-1] if line.endswith(b"\r") else line)
if len(self._pending) > self.limit:
raise ProtocolError(TOO_LARGE, f"message over {self.limit} bytes")
return lines
@property
def partial(self) -> bool:
return bool(self._pending)
class Session:
"""One connection's side of the protocol, in the service.
dispatch(op, args) runs an operation: ValueError is answered as INVALID, Unavailable as
UNAVAILABLE, anything else as INTERNAL (and logged)."""
def __init__(self, dispatch: Callable[[str, dict], object], service_version: str):
self._dispatch = dispatch
self._version = service_version
self.greeted = False
def handle(self, line: bytes) -> tuple[bytes, bool]:
"""(reply, close the connection after sending it)."""
try:
request = decode_request(line)
except ProtocolError as e:
return encode_error(e.request_id, e.code, str(e)), e.code == TOO_LARGE
if request.op == "hello":
theirs = request.args["protocol"]
if theirs != PROTOCOL_VERSION:
return encode_error(request.id, VERSION, f"the service speaks protocol {PROTOCOL_VERSION}, "
f"the client {theirs}"), True
self.greeted = True
return encode_reply(request.id, {"protocol": PROTOCOL_VERSION, "service": self._version}), False
if not self.greeted:
return encode_error(request.id, HELLO_FIRST, "send hello first"), False
try:
result = self._dispatch(request.op, request.args)
except Unavailable as e:
return encode_error(request.id, UNAVAILABLE, str(e)), False
except ValueError as e:
return encode_error(request.id, INVALID, str(e)), False
except Exception:
log.exception("%s failed", request.op)
return encode_error(request.id, INTERNAL, f"{request.op} failed; see the service log"), False
try:
return encode_reply(request.id, result), False
except (TypeError, ValueError):
log.exception("%s: the reply can't be encoded", request.op)
return encode_error(request.id, INTERNAL, f"{request.op}: the reply can't be sent; see the service log"), False
+306
View File
@@ -0,0 +1,306 @@
"""The hardware service's work: fan control on its own temperature readings, RAM lighting, and
the state snapshot the app reads over the pipe.
One loop, once a second (HardwareService.run):
read the CPU package (PawnIO MSR: temperature and power) and the GPU (NVML: temperature)
run the fan curves (CaseFanControl.step), or, while the port mapping isn't saved, only read
the Commander PRO's RPMs, or, while hw-settings.json is invalid, hold every fan at 100%
publish a snapshot for the pipe
Nothing on the pipe side takes a lock the loop needs, and every read the loop makes is guarded,
so neither a client nor a sensor fault can stop it. When it ends, the case fans are left at 100%
and the top fans go back to the BIOS curve, as The Kurgan always did on exit.
"""
from __future__ import annotations
import logging
import math
import os
import threading
import time
from kurgan import __version__
from kurgan.cooling.board_fans import Nct6687
from kurgan.cooling.control import CaseFanControl, CpuTemperature, TopFanCurve
from kurgan.cooling.profiles import PROFILES
from kurgan.hw.protocol import PROTOCOL_VERSION, Unavailable
from kurgan.lighting.case_fans import SIDE_CHASE_BOTTOM_STEP
log = logging.getLogger(__name__)
ERROR_RETRY_SECONDS = 5.0
LOG_EVERY = 60.0 # seconds between repeats of the same failure in the log
def _clean(value):
"""JSON-safe copy: NaN and infinities become None (the protocol refuses them)."""
if isinstance(value, float):
return value if math.isfinite(value) else None
if isinstance(value, dict):
return {str(k): _clean(v) for k, v in value.items()}
if isinstance(value, (list, tuple)):
return [_clean(v) for v in value]
return value
class SyncedChase:
"""The RAM chase's clock in the service, a stand-in for the app's ChaseTiming.
The app sends its clock (phase, rate) about once a second (ram_chase); in between, and when
the app is gone, the phase runs on at the last rate. Both processes read time.monotonic(),
which on Windows is the system-wide performance counter, so no offset needs translating."""
IDLE_RATE = 1 / 0.15 # LEDs per second: the app's default idle pace (--rgb-chase-step-ms 150)
def __init__(self):
self._lock = threading.Lock()
self.phase = float(SIDE_CHASE_BOTTOM_STEP)
self.rate = self.IDLE_RATE
self.last_time: float | None = None
def sync(self, phase: float, rate: float, now: float) -> None:
with self._lock:
self.phase, self.rate, self.last_time = phase, rate, now
def reset(self, phase: float = 0.0) -> None:
with self._lock:
self.phase, self.last_time = phase, None
def set_power(self, total_watts: float | None) -> None:
pass # the pace comes with the phase
def rate_for(self, total_watts: float | None) -> float:
return self.rate
def sample(self, now: float) -> tuple[float, float]:
with self._lock:
if self.last_time is None:
self.last_time = now
self.phase += self.rate * max(0.0, now - self.last_time)
self.last_time = max(now, self.last_time)
return self.phase, self.rate
class HardwareService:
def __init__(self, settings, settings_error: str | None = None, *, commander=None,
board_factory=Nct6687, gpu_factory=None, cpu=None, memory=None):
"""settings: kurgan.hw.settings.load(), or None when hw-settings.json is invalid
(settings_error says why). The rest replace the real hardware in tests and --demo."""
from kurgan.telemetry.sensors import CommanderPro, GpuSensors
self.started = time.time()
self.settings = settings
self.settings_error = settings_error
self.commander = commander if commander is not None else CommanderPro()
self.cpu = cpu if cpu is not None else CpuTemperature()
self._gpu_factory = gpu_factory or (lambda: GpuSensors(load_source="nvml"))
self._gpu = None
self.gpu_temp: float | None = None
self.gpu_error: str | None = "not read yet"
self.chase = SyncedChase()
if memory is None:
from kurgan.lighting.memory import MemoryLighting
from kurgan.theme import Theme
memory = MemoryLighting(Theme(), chase_timing=self.chase)
self.memory = memory
self._memory_events = {"temperature": threading.Event(), "chase": threading.Event()}
self._memory_mode = "off"
self._lock = threading.Lock() # settings changes (pipe threads); the loop never takes it
self._failures: dict[str, float] = {} # what -> when it was last logged
self._rpms: list[int] = []
self._seq = 0
self.fans: CaseFanControl | None = None
self.note: str | None = None
# Kept here so neither the loop nor `state` ever waits on the settings file's lock.
self._profile: str | None = None if settings is None else settings.get("cooling", "profile")
if settings is None:
self.note = (f"hw-settings.json is invalid, so every case fan is held at 100%: {settings_error}. "
"Fix the file, then restart the hardware service.")
else:
cooling = settings.section("cooling")
if cooling.get("gpu_ports"):
top = None
if cooling.get("top_channels"):
top = TopFanCurve(tuple(cooling["top_channels"]), board_factory=board_factory)
self.fans = CaseFanControl(self.commander, tuple(cooling["gpu_ports"]),
tuple(cooling.get("cpu_ports") or ()) or None, top,
profile=PROFILES[cooling["profile"]])
self.commander.controlled = True
else:
self.note = "Fan control isn't set up: save the Commander PRO ports first (see README)."
self._apply_memory(settings.get("lighting", "memory"))
self._snapshot = self._build(time.time())
# -- the loop
def _logged(self, what: str, now: float) -> bool:
"""True when a failure of `what` should be logged now (at most once a LOG_EVERY)."""
last = self._failures.get(what)
if last is None or now - last >= LOG_EVERY:
self._failures[what] = now
return True
return False
def _read_gpu(self, now: float) -> float | None:
try:
if self._gpu is None:
self._gpu = self._gpu_factory()
temp = self._gpu.read().temp
self.gpu_error = None if temp is not None else "no GPU temperature (driver unavailable?)"
return temp
except Exception as e: # rebuilt on the next pass
if self._logged("gpu", now):
log.warning("GPU temperature read failed; the GPU-side fans fail safe: %s", e, exc_info=True)
self.gpu_error = f"{type(e).__name__}: {e}"
self._gpu = None
return None
def _read_cpu(self, now: float) -> float | None:
try:
return self.cpu.read(now)
except Exception as e:
if self._logged("cpu", now):
log.warning("CPU temperature read failed; the CPU-side fans fail safe: %s", e, exc_info=True)
self.cpu.temp = self.cpu.power = None
self.cpu.error = f"{type(e).__name__}: {e}"
return None
def _full_speed(self, now: float) -> float:
try:
self._rpms = sorted(self.commander.full_speed().values())
return 1.0
except Exception as e:
if self._logged("full-speed", now):
log.error("Can't hold the case fans at 100%%: %s", e)
self.commander.close()
self._rpms = []
return ERROR_RETRY_SECONDS
def tick(self, now: float) -> float:
"""One pass of the loop; never raises. Returns the seconds until the next."""
delay = 1.0
try:
self.gpu_temp = self._read_gpu(now)
cpu_average = self._read_cpu(now)
if self.fans is not None:
delay = self.fans.step(self.gpu_temp, cpu_average, now)
self._rpms = self.commander.read()
elif self.settings is None:
delay = self._full_speed(now)
else:
self._rpms = self.commander.read() # read-only, for the app's power estimate
self.memory.set_temperature(self.cpu.temp, self.gpu_temp)
except Exception:
if self._logged("loop", now):
log.exception("Hardware loop error; failing safe and retrying")
if self.fans is not None:
self.fans.failsafe()
delay = ERROR_RETRY_SECONDS
try:
self._snapshot = self._build(time.time())
except Exception:
if self._logged("snapshot", now):
log.exception("Can't build the state snapshot")
return delay
def run(self, stop: threading.Event) -> None:
log.info("Hardware loop started (%s)", "fan control on" if self.fans is not None
else "fans held at 100%" if self.settings is None else "fan control not set up")
try:
while not stop.is_set():
stop.wait(self.tick(time.monotonic()))
finally:
if self.fans is not None:
self.fans.shutdown()
else:
self.commander.close()
self.cpu.close()
log.info("Hardware loop stopped; case fans at 100%%, top fans on the BIOS curve")
def start_lighting(self, stop: threading.Event) -> threading.Thread:
e = self._memory_events
thread = threading.Thread(target=self.memory.run, args=(stop, e["temperature"], e["chase"]),
name="memory-lighting", daemon=True)
thread.start()
return thread
# -- state
def _build(self, t: float) -> dict:
fans = self.fans
if fans is not None:
cooling = {**fans.snapshot(), "note": None,
"row": [round(t, 1), fans.gpu.duty, None if fans.cpu is None else fans.cpu.duty,
None if fans.top is None else fans.top.duty]}
else:
cooling = {"profile": self._profile, "groups": [], "top": None, "note": self.note, "row": None}
self._seq += 1
return _clean({
"service": {"version": __version__, "protocol": PROTOCOL_VERSION, "pid": os.getpid(),
"uptime": round(t - self.started), "settings_error": self.settings_error},
"seq": self._seq, "t": round(t, 3),
"cpu": {"temp": self.cpu.temp, "power": self.cpu.power, "error": self.cpu.error},
"gpu": {"temp": self.gpu_temp, "error": self.gpu_error},
"commander": {"rpms": list(self._rpms)},
"cooling": cooling,
"lighting": {"memory": {"mode": self._memory_mode, "status": self.memory.status}},
})
def snapshot(self) -> dict:
"""The latest published state, with the current profile and RAM lighting (a change made
over the pipe shows at once, not at the next pass)."""
state = dict(self._snapshot)
state["cooling"] = {**state["cooling"], "profile": self._profile}
state["lighting"] = {"memory": {"mode": self._memory_mode, "status": self.memory.status}}
return state
# -- operations (from the pipe; arguments already checked by the protocol)
def _apply_memory(self, mode: str) -> None:
for name, event in self._memory_events.items(): # clear the old pattern before setting the new
if name != mode:
event.clear()
if mode != "off":
self._memory_events[mode].set()
self._memory_mode = mode
def _save(self, section: str, **changes) -> None:
if self.settings is None:
raise Unavailable(f"hw-settings.json is invalid ({self.settings_error}); fix it and restart "
"the hardware service")
try:
self.settings.update(section, **changes)
except OSError as e:
raise Unavailable(f"couldn't save hw-settings.json: {e}") from None
def set_profile(self, key: str) -> None:
with self._lock:
self._save("cooling", profile=key)
self._profile = key
if self.fans is not None:
self.fans.apply_profile(PROFILES[key])
log.info("Fan profile set to %s by the app", key)
def set_ram_lighting(self, mode: str) -> None:
with self._lock:
self._save("lighting", memory=mode)
self._apply_memory(mode)
log.info("RAM lighting set to %s by the app", mode)
def dispatch(self, op: str, args: dict):
if op == "state":
return self.snapshot()
if op == "set_profile":
self.set_profile(args["profile"])
return self.snapshot()
if op == "set_ram_lighting":
self.set_ram_lighting(args["mode"])
return self.snapshot()
if op == "ram_chase":
self.chase.sync(args["phase"], args["rate"], time.monotonic())
self.memory.set_power(args["power"])
return None
raise ValueError(f"unknown operation {op!r}")
+89
View File
@@ -0,0 +1,89 @@
"""The hardware service's settings: %ProgramData%\\Kurgan\\hw-settings.json.
{
"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3],
"top_channels": [2, 5]},
"lighting": {"memory": "off"}
}
The cooling section is checked exactly as settings.json's was (kurgan.settings.validate_cooling);
the lighting section holds the RAM zone only, which the service drives. The folder is writable
by SYSTEM and Administrators only, and readable by users: the service writes the file when the
app changes the profile or the RAM lighting, and the port mapping is saved from an elevated
`python -m kurgan.cooling.control --save-ports ...`.
An invalid file doesn't stop the service: it holds every case fan at 100% and says why in its
state, so the app can show it (see kurgan.hw.service).
"""
from __future__ import annotations
import copy
import ctypes
import ctypes.wintypes as wt
import os
from kurgan import paths
from kurgan.cooling.profiles import DEFAULT_PROFILE
from kurgan.settings import LIGHTING_MODES, Settings, SettingsError, validate_cooling
DEFAULTS = {
"cooling": {"profile": DEFAULT_PROFILE},
"lighting": {"memory": "off"},
}
_OPTIONAL = {"cooling": {"gpu_ports", "cpu_ports", "top_channels"}, "lighting": set()}
# The data folder: SYSTEM and Administrators full control, users read, nothing inherited.
DATA_DIR_SDDL = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)"
def validate(data: object) -> dict:
"""A normalised copy with defaults filled in, or SettingsError."""
if not isinstance(data, dict):
raise SettingsError("settings must be a JSON object")
unknown = set(data) - set(DEFAULTS)
if unknown:
raise SettingsError(f"unknown section(s): {', '.join(sorted(unknown))}")
out = copy.deepcopy(DEFAULTS)
for section, values in data.items():
if not isinstance(values, dict):
raise SettingsError(f"{section} must be an object")
bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section]
if bad:
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
out[section].update(values)
validate_cooling(out["cooling"])
if out["lighting"]["memory"] not in LIGHTING_MODES["memory"]:
raise SettingsError(f"lighting.memory must be one of {', '.join(LIGHTING_MODES['memory'])}")
return out
def load(path: str = paths.HW_SETTINGS_PATH) -> Settings:
"""The service's settings (created with the defaults if missing); OSError or SettingsError."""
return Settings(path, legacy_dir=None, validator=validate)
class _SecurityAttributes(ctypes.Structure):
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)]
def ensure_data_dir(path: str = paths.HW_DATA_DIR) -> None:
"""Create the data folder, if missing, with DATA_DIR_SDDL (setup.ps1 also resets it)."""
if os.path.isdir(path):
return
os.makedirs(os.path.dirname(path), exist_ok=True)
adv = ctypes.WinDLL("advapi32", use_last_error=True)
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
descriptor = ctypes.c_void_p()
adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
wt.LPCWSTR, wt.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p]
k32.CreateDirectoryW.argtypes = [wt.LPCWSTR, ctypes.POINTER(_SecurityAttributes)]
k32.LocalFree.argtypes = [ctypes.c_void_p]
if not adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(DATA_DIR_SDDL, 1, ctypes.byref(descriptor), None):
raise ctypes.WinError(ctypes.get_last_error())
try:
attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
if not k32.CreateDirectoryW(path, ctypes.byref(attributes)) and not os.path.isdir(path):
raise ctypes.WinError(ctypes.get_last_error())
finally:
k32.LocalFree(descriptor)
+97
View File
@@ -0,0 +1,97 @@
"""Hosting the hardware service in the Windows service manager, with pywin32 (Decision 0002).
setup.ps1 installs it as the "KurganHw" service, LocalSystem, automatic start at boot:
"<base Python>\\python.exe" -I -S -B "<repo>\\hw_service.py"
The base interpreter, not the venv's python.exe: on Windows that one is a redirector that runs
the real interpreter as a child process, and the service manager only talks to the process it
started. hw_service.py puts the repo and the venv's packages on the path itself.
Stop and shutdown (the service accepts both) end the hardware loop, which leaves the case fans
at 100% and hands the top fans back to the BIOS curve. If the service fails unexpectedly the
process exits without reporting "stopped", so the service manager's recovery actions (restart
after 5 s, 10 s, then 60 s; set by setup.ps1) bring it back.
"""
from __future__ import annotations
import logging
import os
import sys
import threading
import pywintypes
import servicemanager
import win32service
import win32serviceutil
from kurgan import __version__
from kurgan.hw import main as hw_main
log = logging.getLogger("kurgan.hw")
ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063 # not started by the service manager
class KurganHwService(win32serviceutil.ServiceFramework):
_svc_name_ = hw_main.SERVICE_NAME
_svc_display_name_ = hw_main.SERVICE_DISPLAY_NAME
_svc_description_ = ("The Kurgan's hardware control: case and top fan curves with their fail-safes, "
"and the RAM lighting. The app talks to it over \\\\.\\pipe\\kurgan-hw.")
def __init__(self, args):
super().__init__(args)
self.stop = threading.Event()
def SvcStop(self) -> None:
self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, waitHint=int(hw_main.STOP_SECONDS * 1000))
self.stop.set()
def SvcShutdown(self) -> None: # defining it makes the framework accept SERVICE_CONTROL_SHUTDOWN
self.SvcStop()
def SvcDoRun(self) -> None:
try:
hw_main.setup_logging(console=False)
log.info("Starting %s %s as a service (pid %s)", hw_main.SERVICE_DISPLAY_NAME, __version__, os.getpid())
mutex = hw_main.single_instance()
if mutex is None:
raise RuntimeError("another copy is running (python -m kurgan.hw in a console?)")
hw_main.serve(self.stop, hw_main.configured_user_sid())
log.info("Stopped")
except BaseException:
fail()
def fail() -> None:
"""Exit at once, without reporting "stopped", so the service manager restarts the service."""
log.exception("The hardware service failed; exiting so the service manager restarts it")
logging.shutdown()
os._exit(1)
def check() -> int:
"""What setup.ps1 runs before installing: can this interpreter load everything the service needs?"""
import pynvml # noqa: F401 (the GPU temperature)
from kurgan.hw import service # noqa: F401 (and with it the fan control and the RAM lighting)
print(f"ok: {hw_main.SERVICE_DISPLAY_NAME} {__version__}, Python {sys.version.split()[0]} "
f"at {sys.executable}")
return 0
def main(argv: list[str] | None = None) -> int:
argv = sys.argv[1:] if argv is None else argv
if argv == ["--check"]:
return check()
if not argv:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(KurganHwService)
try:
servicemanager.StartServiceCtrlDispatcher()
return 0
except pywintypes.error as e:
if e.winerror != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
raise
return hw_main.main(argv) # started from a console: run there
+4 -2
View File
@@ -20,8 +20,10 @@ log = logging.getLogger(__name__)
_RETRY_SECONDS = 10.0
_FAN_TOP_RIGHT = (17, 17, 17, 20, 11, 20)
_CHASE_EASE_SECONDS = 1.0
# The CORE shares a USB 2.0 hub with the LCD; flooding it hung the LCD firmware, so cap
# frames at ~22/s and let a fast chase advance more than one LED per frame instead.
# The CORE used to share a USB 2.0 hub with the LCD, and flooding it hung the LCD firmware. The
# LCD is now on a back-panel port, and the CORE shares its Genesys hub with the Commander PRO
# (light traffic); frames stay capped at ~22/s as a margin, a fast chase advancing more than one
# LED per frame instead.
MIN_CHASE_FRAME_SECONDS = 0.045
CHASE_POLL_SECONDS = 0.02
+34 -20
View File
@@ -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,17 +83,23 @@ 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}")
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)
@@ -94,15 +107,16 @@ class LightingService:
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()]}
+7
View File
@@ -12,5 +12,12 @@ SETTINGS_PATH = os.path.join(DATA_DIR, "settings.json")
# The TT LCD Dashboard's folder; its fan and lighting settings are imported once on first start.
LEGACY_DIR = os.path.join(_LOCAL, "TTLcdDashboard")
# The hardware service's settings and log (kurgan.hw, LocalSystem): writable by SYSTEM and
# Administrators only, readable by users. KURGAN_HW_DATA_DIR moves them (tests, a console run).
HW_DATA_DIR = (os.environ.get("KURGAN_HW_DATA_DIR")
or os.path.join(os.environ.get("ProgramData", r"C:\ProgramData"), "Kurgan"))
HW_SETTINGS_PATH = os.path.join(HW_DATA_DIR, "hw-settings.json")
HW_LOG_PATH = os.path.join(HW_DATA_DIR, "kurgan-hw.log")
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__))
PROJECT_DIR = os.path.dirname(PACKAGE_DIR)
+49 -35
View File
@@ -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
@@ -73,23 +77,8 @@ def _port_number(value, where: str) -> int:
return value
def validate(data: object) -> dict:
"""Return a normalised copy with defaults filled in, or raise SettingsError."""
if not isinstance(data, dict):
raise SettingsError("settings must be a JSON object")
unknown = set(data) - set(DEFAULTS)
if unknown:
raise SettingsError(f"unknown section(s): {', '.join(sorted(unknown))}")
out = copy.deepcopy(DEFAULTS)
for section, values in data.items():
if not isinstance(values, dict):
raise SettingsError(f"{section} must be an object")
bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section]
if bad:
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
out[section].update(values)
cooling = out["cooling"]
def validate_cooling(cooling: dict) -> dict:
"""Check and normalise a cooling section in place (also used for the hardware service's)."""
if cooling["profile"] not in PROFILES:
raise SettingsError(f"cooling.profile must be one of {', '.join(PROFILES)}")
if ("cpu_ports" in cooling or "top_channels" in cooling) and "gpu_ports" not in cooling:
@@ -109,9 +98,31 @@ def validate(data: object) -> dict:
cooling["top_channels"] = list(parse_channels(",".join(map(str, value))))
except argparse.ArgumentTypeError as e:
raise SettingsError(f"cooling.top_channels: {e}") from None
return cooling
def validate(data: object) -> dict:
"""Return a normalised copy with defaults filled in, or raise SettingsError."""
if not isinstance(data, dict):
raise SettingsError("settings must be a JSON object")
unknown = set(data) - set(DEFAULTS) - 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")
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.setdefault(section, {}).update(values)
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"]
@@ -179,9 +190,11 @@ class Settings:
"""Thread-safe: the web server, the tray and the CLI all go through update()."""
def __init__(self, path: str = paths.SETTINGS_PATH, legacy_dir: str | None = paths.LEGACY_DIR,
seed: dict | None = None):
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags)."""
seed: dict | None = None, validator=None):
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags).
validator: the file's validate() (default: this module's, for settings.json)."""
self.path = path
self._validate = validator or validate
self._lock = threading.RLock()
self.created = False
try:
@@ -195,7 +208,7 @@ class Settings:
except ValueError as e:
raise SettingsError(f"{path}: {e}") from None
try:
self._data = validate(raw)
self._data = self._validate(raw)
except SettingsError as e:
raise SettingsError(f"{path}: {e}") from None
if self.created:
@@ -203,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 = validate(data)
data.setdefault(section, {}).update(changes)
data = self._validate(data)
write_json_atomic(self.path, data)
self._data = data
+8 -3
View File
@@ -22,6 +22,11 @@ class PowerReadings:
@property
def total(self) -> float | None:
if self.cpu is None or self.gpu is None or self.other is None:
return None
return self.cpu + self.gpu + self.other
"""The known parts summed; None only when nothing is known. While a part is missing
the total under-counts -- `complete` says so."""
known = [v for v in (self.cpu, self.gpu, self.other) if v is not None]
return sum(known) if known else None
@property
def complete(self) -> bool:
return self.cpu is not None and self.gpu is not None and self.other is not None
+235
View File
@@ -0,0 +1,235 @@
"""Long-term telemetry: hourly min/avg/max per metric, one JSON line per hour.
The live history in the service keeps ten minutes; this keeps about a year, so the web UI can
draw weeks and months. Files are append-only JSONL in the data dir, one per month
(records-YYYY-MM.jsonl); each line looks like:
{"hour":1764892800,"n":3600,"cpu_temp":[41.0,55.3,78.0,3600],...}
that is min, average and max, and how many samples carried the metric (a sensor can drop out
for part of an hour; its average is over the samples that had it). Lines written before the
count existed have three numbers and count as `n` samples.
The hour in progress is checkpointed to records-current.json every minute and on exit, and
resumed at the next start: a restart, even a hard stop such as `schtasks /End`, loses at most
a minute. Should two lines ever exist for one hour, the reader merges them.
Recording is best effort: a failing write is logged at most once an hour and retried; finished
hours wait in memory (up to two days of them) until the disk takes them again.
"""
from __future__ import annotations
import glob
import json
import logging
import os
import time
log = logging.getLogger(__name__)
METRICS = ("cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
RETENTION_DAYS = 400 # a little over a year of monthly files
CHECKPOINT_SECONDS = 60
MAX_PENDING = 48 # finished hours kept in memory while writes fail
REPORT_SECONDS = 3600 # a failing disk is logged at most this often
_FILE = "records-%s.jsonl"
_CURRENT = "records-current.json"
def _values(sample) -> dict[str, float | None]:
return {"cpu_temp": sample.cpu.temp, "gpu_temp": sample.gpu.temp,
"cpu_load": sample.cpu.load, "gpu_load": sample.gpu.load,
"cpu_w": sample.cpu.power, "gpu_w": sample.gpu.power,
"other_w": sample.power.other, "total_w": sample.power.total,
"vram_used": None if sample.vram is None else sample.vram[0]}
class Recorder:
"""Subscribed to Telemetry (called once per sample); writes each finished hour to its month file."""
def __init__(self, directory: str, retention_days: int = RETENTION_DAYS):
self.directory = directory
self.retention_days = retention_days
self._hour = 0
self._n = 0
self._stats: dict[str, list[float]] = {} # metric -> [min, max, sum, count]
self._pending: list[dict] = [] # finished hours not written yet
self._checkpoint_at = 0.0
self._reported: float | None = None # when a failure was last logged
self._prune()
self._resume()
def on_sample(self, sample) -> None:
try:
hour = int(sample.t // 3600) * 3600
if hour != self._hour:
self._finish_hour()
self._hour, self._n, self._stats = hour, 0, {}
self._n += 1
for name, value in _values(sample).items():
if value is None:
continue
s = self._stats.get(name)
if s is None:
self._stats[name] = [value, value, value, 1]
else:
s[0], s[1], s[2], s[3] = min(s[0], value), max(s[1], value), s[2] + value, s[3] + 1
if abs(sample.t - self._checkpoint_at) >= CHECKPOINT_SECONDS:
self._checkpoint_at = sample.t
self._save_checkpoint()
except Exception:
self._report("Telemetry recording failed")
def close(self) -> None:
"""Checkpoint the hour in progress (the next start carries on with it) and write anything pending."""
try:
self._save_checkpoint()
self._write_pending()
except Exception:
self._report("Telemetry recording failed while closing")
# ------------------------------------------------------------------ the hour in progress
def _row(self) -> dict:
row = {"hour": self._hour, "n": self._n}
for name in METRICS:
s = self._stats.get(name)
row[name] = [round(s[0], 1), round(s[2] / s[3], 1), round(s[1], 1), s[3]] if s else None
return row
def _finish_hour(self) -> None:
if self._hour and self._n:
self._pending.append(self._row())
del self._pending[:-MAX_PENDING]
self._write_pending()
def _save_checkpoint(self) -> None:
if not self._hour or not self._n:
return
try:
os.makedirs(self.directory, exist_ok=True)
path = os.path.join(self.directory, _CURRENT)
with open(path + ".tmp", "w", encoding="utf-8") as f:
json.dump({"hour": self._hour, "n": self._n, "stats": self._stats}, f, separators=(",", ":"))
os.replace(path + ".tmp", path)
except OSError:
self._report("Couldn't checkpoint the hour's telemetry")
def _resume(self) -> None:
"""Carry on with the checkpointed hour if it is this hour; otherwise it is finished: write it."""
path = os.path.join(self.directory, _CURRENT)
try:
with open(path, encoding="utf-8") as f:
saved = json.load(f)
hour, n, stats = int(saved["hour"]), int(saved["n"]), saved["stats"]
if not all(isinstance(v, list) and len(v) == 4 for v in stats.values()):
raise ValueError("bad stats")
except (FileNotFoundError, NotADirectoryError):
return # nothing to resume (a broken data dir shows up at the first write)
except (OSError, ValueError, KeyError, TypeError, AttributeError):
log.warning("Ignoring an unreadable telemetry checkpoint", exc_info=True)
return
self._hour, self._n, self._stats = hour, n, {k: v for k, v in stats.items() if k in METRICS}
if hour != int(time.time() // 3600) * 3600:
self._finish_hour()
self._hour, self._n, self._stats = 0, 0, {}
if not self._pending: # written: the checkpoint must not be written again next start
try:
os.remove(path)
except OSError:
pass
# ------------------------------------------------------------------ the month files
def _write_pending(self) -> None:
while self._pending:
row = self._pending[0]
month = time.strftime("%Y-%m", time.gmtime(row["hour"]))
try:
os.makedirs(self.directory, exist_ok=True)
with open(os.path.join(self.directory, _FILE % month), "a", encoding="utf-8") as f:
f.write(json.dumps(row, separators=(",", ":")) + "\n")
except OSError:
self._report(f"Couldn't write telemetry records ({len(self._pending)} hours waiting)")
return
self._pending.pop(0)
def _report(self, what: str) -> None:
now = time.monotonic()
if self._reported is None or now - self._reported >= REPORT_SECONDS:
self._reported = now
log.warning("%s; will keep trying", what, exc_info=True)
def _prune(self) -> None:
"""Delete month files whose whole month is older than the retention window."""
# Drop a month file only once its whole month is past the window: it can end up to 31
# days after the month it is named for starts.
cutoff = time.time() - (self.retention_days + 31) * 86400
try:
for path in glob.glob(os.path.join(self.directory, _FILE % "*")):
try:
month = os.path.basename(path)[len("records-"):-len(".jsonl")]
when = time.mktime(time.strptime(month, "%Y-%m"))
except ValueError:
continue
if when < cutoff:
os.remove(path)
log.info("Removed telemetry file older than %s days: %s", self.retention_days, path)
except OSError:
log.warning("Couldn't prune old telemetry files", exc_info=True)
def load(directory: str, days: int) -> dict:
"""Hourly rollups for the last `days` days, oldest first: {"metrics", "rows", "days"}.
Each metric of a row is [min, avg, max] (or null); lines for the same hour are merged,
their averages weighted by how many samples carried the metric."""
since = time.time() - days * 86400
rows: dict[int, dict] = {}
try:
names = sorted(os.listdir(directory))
except OSError:
names = []
for name in names:
if not (name.startswith("records-") and name.endswith(".jsonl")):
continue
try:
with open(os.path.join(directory, name), encoding="utf-8") as f:
lines = f.readlines()
except OSError:
log.warning("Couldn't read telemetry file %s", name)
continue
for line in lines:
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
except ValueError:
continue # a torn last line from a crash: skip it
hour = row.get("hour")
if not isinstance(hour, (int, float)) or hour < since:
continue
merged = rows.setdefault(int(hour), {"hour": int(hour), "n": 0})
n = row.get("n") if isinstance(row.get("n"), int) else 0
merged["n"] += n
for metric in METRICS:
stats = row.get(metric)
if not isinstance(stats, list) or len(stats) not in (3, 4):
continue
count = stats[3] if len(stats) == 4 else n # older lines: every sample counted
cur = merged.get(metric)
if cur is None:
merged[metric] = [stats[0], stats[1], stats[2], count]
else:
cur[0] = min(cur[0], stats[0])
cur[2] = max(cur[2], stats[2])
if cur[3] + count:
cur[1] = (cur[1] * cur[3] + stats[1] * count) / (cur[3] + count)
cur[3] += count
for row in rows.values():
for metric in METRICS:
if row.get(metric) is not None:
row[metric] = row[metric][:3]
return {"metrics": list(METRICS), "rows": [rows[h] for h in sorted(rows)], "days": days}
+68 -11
View File
@@ -298,7 +298,13 @@ class IntelPackage:
# ----------------------------------------------------------------------------- CPU
class CpuSensors:
def __init__(self):
# A runtime MSR failure usually means the PawnIO device is gone: pause before re-opening
# it, or a broken driver costs a heavy CreateFile+DeviceIoControl every second.
RETRY_SECONDS = 15.0
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",
@@ -306,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()
@@ -325,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:
@@ -339,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()
@@ -347,12 +359,16 @@ class CpuSensors:
log.warning("MSR read failed, will retry: %s", e)
self.pkg.msr.close()
self.pkg = None
self._next_pkg_attempt = time.monotonic() + self.RETRY_SECONDS
return Readings(temp=temp, load=load, clock=clock, power=power)
# ----------------------------------------------------------------------------- GPU
class GpuSensors:
# Pause between re-open attempts while the GPU/driver is gone, like CpuSensors'.
RECONNECT_SECONDS = 10.0
def __init__(self, index: int = 0, load_source: str = "windows"):
"""load_source: "windows" = same figure as Task Manager, "nvml" = NVIDIA's kernel-busy figure."""
import pynvml
@@ -361,6 +377,7 @@ class GpuSensors:
self.index = index
self.handle = None
self._last_sample_ts = 0
self._next_connect = 0.0
self.engine_load: GpuEngineLoad | None = None
if load_source == "windows":
try:
@@ -418,6 +435,10 @@ class GpuSensors:
def read(self) -> Readings:
if self.handle is None:
now = time.monotonic()
if now < self._next_connect:
return Readings()
self._next_connect = now + self.RECONNECT_SECONDS
self._connect()
if self.handle is None:
return Readings()
@@ -441,6 +462,7 @@ class GpuSensors:
except Exception:
pass
self.handle = None
self._last_sample_ts = 0 # the driver's sample buffer restarts with the driver
return Readings(
temp=None if temp is None else float(temp),
load=util,
@@ -515,6 +537,11 @@ def _process_names() -> list[str]:
return names
# Whose %APPDATA% holds the OpenRGB settings to check. The hardware service runs as LocalSystem,
# so it points this at the installing user's profile (kurgan.hw.service.user_appdata).
USER_APPDATA: str | None = None
def corsair_software_running(openrgb_detector: str, fan_tools: bool = True) -> bool:
"""True if iCUE (or, with `fan_tools`, FanControl) runs, or a running OpenRGB may drive the device.
@@ -527,7 +554,7 @@ def corsair_software_running(openrgb_detector: str, fan_tools: bool = True) -> b
return True
if not any("openrgb" in n for n in names):
return False
configs = [os.path.join(os.environ.get("APPDATA", ""), "OpenRGB", "OpenRGB.json"),
configs = [os.path.join(USER_APPDATA or os.environ.get("APPDATA", ""), "OpenRGB", "OpenRGB.json"),
os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "OpenRGB",
"service_config", "OpenRGB.json")]
try:
@@ -596,6 +623,9 @@ class CommanderPro:
CMD_FAN_RPM = 0x21
PORTS = 6
RECHECK = 30.0
# Last known RPMs must not feed the power model forever: after this long without a
# successful read the fan speeds are unknown, not merely stale.
RPM_STALE = 10.0
def __init__(self):
self.ch: HidChannel | None = None
@@ -605,6 +635,7 @@ class CommanderPro:
self.ports: list[int] = []
self.rpm: dict[int, int] = {}
self._next_check = 0.0
self._read_at = 0.0
self._note: str | None = None
def _say(self, note: str) -> None:
@@ -639,12 +670,13 @@ class CommanderPro:
if self.ch is not None:
return
ctypes.set_last_error(0)
mutex = _k32.CreateMutexW(None, False, "Local\\TTLcdCommanderPro")
# Global: the hardware service runs in session 0, a console tool in the user's session.
mutex = _k32.CreateMutexW(None, False, "Global\\KurganCommanderPro")
err = ctypes.get_last_error()
if not mutex or err == 183:
if not mutex or err == 183: # exists already, or exists and belongs to SYSTEM (access denied)
if mutex:
_k32.CloseHandle(mutex)
raise OSError("Commander PRO is in use by another dashboard/sensor process")
raise OSError("Commander PRO is in use by another process (the hardware service?)")
self._mutex = mutex
try:
paths = hid_device_paths(self.VID, self.PID)
@@ -678,13 +710,33 @@ class CommanderPro:
for p in self.ports:
r = self._cmd(self.CMD_FAN_RPM, p)
self.rpm[p] = (r[2] << 8) | r[3]
self._read_at = time.monotonic()
return {p + 1: rpm for p, rpm in self.rpm.items()}
def full_speed(self) -> dict[int, int]:
"""Every port with a PWM fan to 100%: the fail-safe while the port mapping is unknown."""
with self._lock:
if self._corsair_software_running():
self.close()
raise OSError("Commander PRO busy: exit iCUE/FanControl, or disable OpenRGB's "
"Corsair Commander Pro detector and restart OpenRGB")
self._open()
modes = self._cmd(self.CMD_FAN_MODES)
if len(modes) < 8:
raise OSError("Incomplete Commander PRO fan modes reply")
ports = tuple(p + 1 for p in range(self.PORTS) if modes[2 + p] == 2)
if not ports:
raise OSError("no PWM fans connected to the Commander PRO")
return self.set_duty(ports, 100)
def _fresh_rpms(self) -> bool:
return time.monotonic() - self._read_at <= self.RPM_STALE
def read(self) -> list[int]:
"""RPM of each connected fan (the last known values while iCUE has the device)."""
"""RPM of each connected fan; empty while the device is lost or held by other software."""
with self._lock:
if self.controlled:
return list(self.rpm.values())
return list(self.rpm.values()) if self._fresh_rpms() else []
return self._read()
def _read(self) -> list[int]:
@@ -712,9 +764,12 @@ class CommanderPro:
for p in self.ports:
r = self._cmd(self.CMD_FAN_RPM, p)
self.rpm[p] = (r[2] << 8) | r[3]
self._read_at = time.monotonic()
except Exception as e:
self.close()
self._say(f"lost ({e}), retrying in {self.RECHECK:.0f} s")
if not self._fresh_rpms():
return []
return [self.rpm[p] for p in self.ports if p in self.rpm]
@@ -825,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:
+49 -13
View File
@@ -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
@@ -19,6 +20,8 @@ from kurgan.telemetry.readings import PowerReadings, Readings
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")
@@ -42,37 +45,69 @@ 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
self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval))
self._listeners: list[Callable[[Sample], None]] = []
self._seq = 0
self._last_failure: dict[str, float] = {}
self._failures: dict[str, tuple[float, str]] = {} # source -> (monotonic, message) of its latest failed read
self._empty: dict[str, int] = {} # source -> consecutive empty readings
def subscribe(self, listener: Callable[[Sample], None]) -> None:
self._listeners.append(listener)
def read(self) -> Sample:
"""Read every source independently: one failing source costs only its own readings."""
c = self._source("CPU sensors", self.cpu.read, Readings())
g = self._source("GPU sensors", self.gpu.read, 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 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)
vram = self._source("GPU memory", self.gpu.memory, None)
self._seq += 1
return Sample(self._seq, time.time(), c, g, p, vram)
def _source(self, name: str, read: Callable, fallback, *args):
def _source(self, name: str, read: Callable, fallback, *args, missing: Callable | None = None):
"""read(*args), or fallback if it raises. Failures are kept for health(); so is a result
that missing(result) describes as empty (a message), once EMPTY_READS in a row were."""
try:
return read(*args)
result = read(*args)
except Exception as e:
# The loop retries every second, so log each failing source at most once a minute.
if time.monotonic() - self._last_failure.get(name, -1e9) >= 60:
self._last_failure[name] = time.monotonic()
now = time.monotonic()
last = self._failures.get(name)
if last is None or now - last[0] >= 60:
log.warning("%s read failed; continuing without it: %s", name, e, exc_info=True)
self._failures[name] = (now, f"{type(e).__name__}: {e}")
return fallback
problem = missing(result) if missing is not None else None
if problem is None:
self._empty.pop(name, None)
if self._failures.pop(name, None) is not None: # reading again: healthy
log.info("%s reading again", name)
return result
self._empty[name] = self._empty.get(name, 0) + 1
if self._empty[name] >= EMPTY_READS: # one empty read at startup or a glitch proves nothing
if name not in self._failures:
log.warning("%s: %s", name, problem)
self._failures[name] = (time.monotonic(), problem)
return result
def health(self) -> dict[str, dict]:
"""Sources whose latest read failed: name -> {"error", "age_s"}. Empty while every source reads."""
now = time.monotonic()
return {name: {"error": message, "age_s": round(now - when, 1)}
for name, (when, message) in self._failures.items()}
def run(self, stop: threading.Event) -> None:
while not stop.is_set():
@@ -115,15 +150,16 @@ class Telemetry:
def snapshot(self) -> dict:
s = self.latest
if s is None:
return {"seq": 0}
return {"seq": 0, "health": self.health()}
return {
"seq": s.seq, "t": s.t,
"health": self.health(),
"cpu": {"temp": _r(s.cpu.temp), "load": _r(s.cpu.load), "clock": _r(s.cpu.clock, 0), "power": _r(s.cpu.power)},
"gpu": {"temp": _r(s.gpu.temp), "load": _r(s.gpu.load), "clock": _r(s.gpu.clock, 0), "power": _r(s.gpu.power),
"vram_used": None if s.vram is None else s.vram[0],
"vram_total": None if s.vram is None else s.vram[1]},
"power": {"cpu": _r(s.power.cpu), "gpu": _r(s.power.gpu), "other": _r(s.power.other),
"total": _r(s.power.total),
"total": _r(s.power.total), "partial": not s.power.complete,
"parts": {k: round(v, 1) for k, v in s.power.parts.items()}},
"row": s.row(),
}
+1 -1
View File
@@ -1,4 +1,4 @@
"""Colours and thresholds shared by the LCD, the case/RAM lighting and the tray icon."""
"""Colours and thresholds shared by the LCD and the case/RAM lighting."""
from __future__ import annotations
+42 -47
View File
@@ -2,14 +2,15 @@
The tooltip shows the power draw; the menu shows each capability's status and has
"Open The Kurgan" (the web UI), "Start with Windows" and "Exit". Clicking the icon with the
left button opens the web UI directly.
left button opens the web UI directly. notify() shows a balloon tip when something starts
going wrong (fan failsafes, AI server errors, failing sensors).
"Start with Windows" switches the logon trigger of "The Kurgan" scheduled task (installed by
setup.ps1) on or off. The task itself stays enabled, so it can still be started by hand,
with admin rights and no UAC prompt: Start-ScheduledTask "The Kurgan"
"Start with Windows" switches the logon trigger of "The Kurgan" scheduled task on or off.
setup.ps1 registers that task as you, without admin rights, so changing it needs none. The task
itself stays enabled, so it can still be started by hand: Start-ScheduledTask "The Kurgan"
The Kurgan usually runs elevated while Explorer doesn't, so Windows would drop Explorer's
clicks on the icon; the window explicitly accepts those messages (ChangeWindowMessageFilterEx).
If The Kurgan is ever run elevated (it shouldn't be), Windows would drop Explorer's clicks on
the icon; the window explicitly accepts those messages (ChangeWindowMessageFilterEx).
"""
from __future__ import annotations
@@ -17,11 +18,14 @@ from __future__ import annotations
import ctypes
import ctypes.wintypes as wt
import logging
import os
import subprocess
import threading
log = logging.getLogger(__name__)
# The sword's hilt, 16-256 px (made by kurgan/assets/make_assets.py from The-Kurgan-Sword.png).
ICON_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets", "kurgan.ico")
TASK_NAME = "The Kurgan"
LEGACY_TASK_NAME = "TT LCD Dashboard" # until setup.ps1 re-registers the task
@@ -83,37 +87,6 @@ def set_autostart(on: bool) -> None:
_powershell(_SET.replace("%TASK%", name).replace("%ON%", "$true" if on else "$false"))
# ----------------------------------------------------------------------------- icon image
def make_icon(path: str, layers: list[tuple[int, int, int]]) -> str:
"""Draw a small version of the dashboard's power tank and save it as a .ico file.
layers: colours from the bottom up (other, CPU, GPU).
"""
from PIL import Image, ImageDraw
s = 256
img = Image.new("RGBA", (s, s), (0, 0, 0, 0))
d = ImageDraw.Draw(img)
chrome, dark = (206, 206, 212, 255), (20, 20, 24, 255)
x0, x1 = 52, 204 # glass
d.rectangle([x0, 30, x1, 226], fill=dark)
y = 226
for h, c in zip((50, 42, 56), layers): # bottom up
d.rectangle([x0, y - h, x1, y], fill=c + (255,))
y -= h
d.rectangle([x0, y - 3, x1, y + 3], fill=dark)
hl = Image.new("RGBA", (s, s), (0, 0, 0, 0))
ImageDraw.Draw(hl).rectangle([x0 + 22, 36, x0 + 40, 222], fill=(255, 255, 255, 70))
img.alpha_composite(hl)
d = ImageDraw.Draw(img)
for y0, y1 in ((4, 40), (216, 252)): # end caps
d.rounded_rectangle([28, y0, 228, y1], radius=12, fill=chrome)
d.rectangle([28, (y0 + y1) // 2 - 2, 228, (y0 + y1) // 2 + 2], fill=(120, 120, 128, 255))
img.save(path, sizes=[(16, 16), (20, 20), (24, 24), (32, 32), (40, 40), (48, 48), (64, 64)])
return path
# ----------------------------------------------------------------------------- Win32
_u32 = ctypes.WinDLL("user32", use_last_error=True)
@@ -127,8 +100,10 @@ WM_NULL, WM_DESTROY, WM_CLOSE, WM_TIMER = 0x0000, 0x0002, 0x0010, 0x0113
WM_LBUTTONUP, WM_RBUTTONUP = 0x0202, 0x0205
WM_TRAY = 0x8000 + 1 # WM_APP + 1: Explorer -> us, mouse events on the icon
WM_TRAY_TIP = 0x8000 + 2 # WM_APP + 2: main thread -> us, tooltip changed
WM_TRAY_INFO = 0x8000 + 3 # WM_APP + 3: any thread -> us, balloon tip to show
NIM_ADD, NIM_MODIFY, NIM_DELETE = 0, 1, 2
NIF_MESSAGE, NIF_ICON, NIF_TIP = 0x1, 0x2, 0x4
NIF_MESSAGE, NIF_ICON, NIF_TIP, NIF_INFO = 0x1, 0x2, 0x4, 0x10
NIIF_NONE, NIIF_WARNING, NIIF_ERROR = 0x0, 0x2, 0x3
MF_STRING, MF_GRAYED, MF_CHECKED, MF_SEPARATOR = 0x0, 0x1, 0x8, 0x800
TPM_RIGHTBUTTON, TPM_NONOTIFY, TPM_RETURNCMD = 0x2, 0x80, 0x100
MB_ICONWARNING, MB_SETFOREGROUND = 0x30, 0x10000
@@ -213,6 +188,7 @@ class TrayIcon:
self.on_open = on_open
self.status_lines = status_lines or (lambda: [])
self._tip = title
self._info: tuple[str, str, int] | None = None
self._hwnd = None
self._hicon = None
self._shown = False
@@ -235,6 +211,27 @@ class TrayIcon:
if self._hwnd:
_u32.PostMessageW(self._hwnd, WM_TRAY_TIP, 0, 0)
def notify(self, title: str, message: str, warning: bool = False) -> None:
"""Show a balloon tip; safe from any thread (it queues on the tray window)."""
self._info = (title[:63], message[:255], NIIF_WARNING if warning else NIIF_NONE)
if self._hwnd:
_u32.PostMessageW(self._hwnd, WM_TRAY_INFO, 0, 0)
def _info_nid(self) -> NOTIFYICONDATAW:
title, message, flags = self._info
nid = NOTIFYICONDATAW()
nid.cbSize = ctypes.sizeof(nid)
nid.hWnd = self._hwnd
nid.uID = 1
nid.uFlags = NIF_INFO
nid.szInfo = message
nid.szInfoTitle = title
nid.dwInfoFlags = flags
return nid
def _show_info(self) -> None:
_shell32.Shell_NotifyIconW(NIM_MODIFY, ctypes.byref(self._info_nid()))
def close(self) -> None:
if self._hwnd:
_u32.PostMessageW(self._hwnd, WM_CLOSE, 0, 0)
@@ -309,6 +306,10 @@ class TrayIcon:
if self._shown:
self._notify(NIM_MODIFY)
return 0
if msg == WM_TRAY_INFO:
if self._shown and self._info is not None:
self._show_info()
return 0
if msg == self._msg_taskbar or (msg == WM_TIMER and wparam == RETRY_TIMER):
self._add() # Explorer restarted (or the taskbar wasn't up yet)
return 0
@@ -380,8 +381,8 @@ class TrayIcon:
except Exception as e:
log.warning("Couldn't change Start with Windows: %s", e)
hint = "" if _is_admin() else (
"\n\nChanging this needs admin rights. The Kurgan has them when its startup task "
"starts it (Start-ScheduledTask \"The Kurgan\").")
"\n\nIf the task was registered with admin rights (by an older setup.ps1), run "
"setup.ps1 again: it registers the task as you, and then this works.")
_u32.MessageBoxW(self._hwnd, f"Couldn't turn Start with Windows {'on' if want else 'off'}.\n\n{e}{hint}",
self.title, MB_ICONWARNING | MB_SETFOREGROUND)
self._refresh_autostart() # show what the task really says now
@@ -389,16 +390,10 @@ class TrayIcon:
if __name__ == "__main__":
# Quick check: show the icon for 20 s with a test tooltip.
import os
import tempfile
import time
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
print("Start with Windows:", autostart_enabled())
path = make_icon(os.path.join(tempfile.gettempdir(), "kurgan_tray_test.ico"),
[(217, 89, 38), (57, 135, 229), (25, 158, 112)])
done = threading.Event()
tray = TrayIcon("The Kurgan (test)", path, on_exit=done.set, status_lines=lambda: ["Test run"])
tray = TrayIcon("The Kurgan (test)", ICON_PATH, on_exit=done.set, status_lines=lambda: ["Test run"])
tray.start()
for i in range(20):
tray.set_tooltip(f"The Kurgan (test)\n{i} s")
+18 -6
View File
@@ -3,6 +3,7 @@
GET / the UI (static/index.html)
GET /api/state everything live, polled by the UI once a second
GET /api/history the last 10 minutes of telemetry (fetched once; the UI appends from /api/state)
GET /api/records?days=N hourly min/avg/max rollups for the last N days (long-term telemetry)
GET /api/config fan profiles, lighting zones and AI backends (static)
POST /api/lighting {"zone": "case_fans"|"memory"|"gpu", "mode": "off"|...}
POST /api/cooling/profile {"profile": "quiet"|"balanced"|"performance"|"full"}
@@ -11,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
@@ -26,7 +28,9 @@ import mimetypes
import os
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__)
@@ -105,12 +109,15 @@ def make_handler(app, port: int):
def do_GET(self) -> None:
if self._proxied() or not self._guard():
return
path = self.path.split("?", 1)[0]
path, _, query = self.path.partition("?")
try:
if path == "/api/state":
self._json(200, app.state())
elif path == "/api/history":
self._json(200, app.history())
elif path == "/api/records":
raw = parse_qs(query).get("days", ["7"])[0]
self._json(200, app.records(int(raw) if raw.isdigit() else -1))
elif path == "/api/config":
self._json(200, app.config())
elif path in ("/", "/index.html"):
@@ -119,6 +126,8 @@ def make_handler(app, port: int):
self._static(path[len("/static/"):])
else:
self._json(404, {"error": "not found"})
except ValueError as e:
self._json(400, {"error": str(e)})
except Exception:
log.exception("GET %s failed", path)
self._json(500, {"error": "internal error; see kurgan.log"})
@@ -182,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}"})
+93 -15
View File
@@ -45,6 +45,7 @@ const fmt = {
return h >= 24 ? `${Math.floor(h / 24)} d ${h % 24} h` : `${h} h ${m} min`;
},
clock: (t) => new Date(t * 1000).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit", second: "2-digit" }),
stamp: (t) => new Date(t * 1000).toLocaleString([], { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" }),
};
const ICON = {
@@ -140,6 +141,7 @@ class Chart {
this.xs = [];
this.cols = {};
this.markers = [];
this.window = null; // seconds shown; null falls back to the live 10-minute window
const legend = this.o.series.length > 1 ? el("div", { class: "legend" },
this.o.series.map((s) => el("span", {}, el("span", { class: this.o.stacked ? "key" : "key line",
style: `background:var(${s.color})` }), s.label))) : null;
@@ -164,6 +166,8 @@ class Chart {
this.svg.setAttribute("aria-label", title);
}
setWindow(seconds) { this.window = seconds; this.draw(); }
setData(xs, cols, markers = []) {
this.xs = xs;
this.cols = cols;
@@ -199,9 +203,10 @@ class Chart {
this.svg.replaceChildren();
const xo = this.o.x;
let x0, x1;
const span = this.window ?? WINDOW_S;
if (xo.type === "time") {
x1 = this.xs.length ? this.xs[this.xs.length - 1] : Date.now() / 1000;
x0 = x1 - WINDOW_S;
x0 = x1 - span;
} else {
[x0, x1] = [xo.min, xo.max];
}
@@ -226,11 +231,16 @@ class Chart {
}
this.svg.append(grid);
this.svg.append(svg("line", { class: "baseline", x1: m.l, x2: m.l + w, y1: Y(0), y2: Y(0) }));
// x ticks
const xticks = xo.type === "time" ? [0, 120, 240, 360, 480, 600].map((s) => x1 - WINDOW_S + s) : xo.ticks;
// x ticks: five even steps, labelled in minutes, hours or days to suit the span
const ago = (xv) => {
const s = x1 - xv;
return s < 1 ? "now" : span <= 600 ? `−${Math.round(s / 60)} min`
: span <= 172800 ? `−${Math.round(s / 3600)} h` : `−${Math.round(s / 86400)} d`;
};
const xticks = xo.type === "time" ? [0, 1, 2, 3, 4, 5].map((k) => x1 - span + (span * k) / 5) : xo.ticks;
for (const xv of xticks) {
const t = svg("text", { x: X(xv), y: H - 6, "text-anchor": "middle", class: "tick" });
t.textContent = xo.type === "time" ? (x1 - xv < 1 ? "now" : `−${Math.round((x1 - xv) / 60)} min`) : xo.fmt(xv);
t.textContent = xo.type === "time" ? ago(xv) : xo.fmt(xv);
this.svg.append(t);
}
// reference lines (e.g. the warn/hot temperatures)
@@ -308,7 +318,9 @@ class Chart {
this.cross.setAttribute("x1", cx);
this.cross.setAttribute("x2", cx);
this.cross.setAttribute("visibility", "visible");
const title = this.o.x.type === "time" ? fmt.clock(this.xs[best]) : this.o.x.fmt(this.xs[best]);
const title = this.o.x.type === "time"
? ((this.window ?? WINDOW_S) > 7200 ? fmt.stamp(this.xs[best]) : fmt.clock(this.xs[best]))
: this.o.x.fmt(this.xs[best]);
const rows = this.o.series.slice().reverse().map((s) => {
const v = this.value(s.key, best);
return { color: `var(${s.color})`, label: s.label, value: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` };
@@ -335,6 +347,7 @@ class Chart {
renderTable() {
const time = this.o.x.type === "time";
const stamp = (this.window ?? WINDOW_S) > 7200;
const head = el("tr", {}, el("th", { text: time ? "Time" : this.o.x.label }),
this.o.series.map((s) => el("th", { class: "r", text: s.label })));
const rows = [];
@@ -344,11 +357,12 @@ class Chart {
if (time && lastT - this.xs[i] < 29.5) continue; // one row per 30 s
lastT = this.xs[i];
if (!time && this.xs[i] % 5 !== 0) continue;
rows.push(el("tr", {}, el("td", { class: "num", text: time ? fmt.clock(this.xs[i]) : this.o.x.fmt(this.xs[i]) }),
rows.push(el("tr", {}, el("td", { class: "num", text: time ? (stamp ? fmt.stamp(this.xs[i]) : fmt.clock(this.xs[i])) : this.o.x.fmt(this.xs[i]) }),
this.o.series.map((s) => { const v = this.value(s.key, i); return el("td", { class: "r", text: v == null ? "--" : `${v.toFixed(this.o.digits)}${this.o.unit}` }); })));
}
this.tableNode.replaceChildren(el("table", {}, el("caption", { class: "muted", style: "text-align:left;caption-side:top;padding:0 0 6px",
text: time ? "Every 30 seconds, newest first" : "" }), el("thead", {}, head), el("tbody", {}, rows)));
text: time ? ((this.window ?? WINDOW_S) > 600 ? "One row per hour, newest first" : "Every 30 seconds, newest first") : "" }),
el("thead", {}, head), el("tbody", {}, rows)));
}
stale(on) { this.plot.classList.toggle("stale", on); }
@@ -380,6 +394,49 @@ let charts = {};
let built = { profiles: false, groups: "", zones: false, backends: "" };
let strataVariant = null;
let profileShown = null;
let rangeDays = 0; // 0 = the live 10-minute view; otherwise days of hourly rollups on the system charts
let rangeToken = 0;
const RANGES = [["10 min", 0], ["24 h", 1], ["7 d", 7], ["30 d", 30], ["1 y", 365]];
function buildRange() {
const group = $("chart-range");
group.replaceChildren(...RANGES.map(([name, days]) => el("label", {},
el("input", { type: "radio", name: "range", value: String(days), checked: days === 0,
onchange: () => setRange(days) }),
el("span", { text: name }))));
}
async function setRange(days) {
rangeDays = days;
const token = ++rangeToken;
if (days === 0) {
charts.power.setWindow(null);
charts.temps.setWindow(null);
charts.power.setTitle("Power", `Whole PC, last 10 minutes (DC watts; ${fmt.n0(config.theme.psu_watts)} W supply)`);
charts.temps.setTitle("Temperatures", "Last 10 minutes");
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
return;
}
try {
const data = await api(`/api/records?days=${days}`);
if (token !== rangeToken) return; // another range was picked while this one loaded
const t = [], cols = Object.fromEntries(data.metrics.map((m) => [m, []]));
for (const r of data.rows) {
t.push(r.hour);
for (const m of data.metrics) cols[m].push(r[m] ? r[m][1] : null); // the hourly average
}
const label = days === 1 ? "last 24 hours" : `last ${days} days`;
charts.power.setWindow(days * 86400);
charts.temps.setWindow(days * 86400);
charts.power.setTitle("Power", `Whole PC, ${label}, hourly averages (DC watts; ${fmt.n0(config.theme.psu_watts)} W supply)`);
charts.temps.setTitle("Temperatures", `${label}, hourly averages`);
charts.power.setData(t, cols);
charts.temps.setData(t, cols);
} catch (error) {
if (token === rangeToken) banner("critical", `Couldn't load the long-term history: ${error.message}`);
}
}
function buildCharts() {
const temps = config.theme;
@@ -441,14 +498,28 @@ function drawCurves(state) {
/* ------------------------------------------------------------------ render: header & system */
function renderHeader(s) {
setText("hero-total", fmt.n0(s.telemetry.power?.total));
const power = s.telemetry.power;
setText("hero-total", (power?.partial ? "≈" : "") + fmt.n0(power?.total));
const meta = $("meta");
const elevated = s.app.token?.elevated;
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" }),
`${health.length} sensor source${health.length > 1 ? "s are" : " is"} failing`)]
: []),
);
setText("footer", `${s.app.name} ${s.app.version} · pid ${s.app.pid} · log: %LOCALAPPDATA%\\Kurgan\\kurgan.log · JSON: /api/state`);
}
@@ -500,7 +571,8 @@ function fanCard(g, kind) {
el("div", { class: "fan-head", style: "margin-top:4px" }, el("span", { class: "fan-duty", "data-f": "duty" }),
el("span", { class: "muted", "data-f": "temp" })),
el("div", { class: `meter ${kind}`, role: "meter", "aria-label": "PWM duty", "data-f": "meter" }, el("span")),
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {}, `Port ${p} `, el("b", { "data-port": p }), " rpm"))),
el("div", { class: "fan-ports", "data-f": "ports" }, ports.map(([p]) => el("span", {},
`${kind === "top" ? "Channel" : "Port"} ${p} `, el("b", { "data-port": p }), el("span", { "data-unit": p }, " rpm")))),
el("div", { "data-f": "note" }));
}
@@ -513,7 +585,12 @@ function updateFanCard(card, g, kind) {
meter.firstChild.style.width = `${g.duty}%`;
meter.setAttribute("aria-valuenow", g.duty);
meter.className = `meter ${g.failsafe ? "critical" : kind}`;
for (const [p, rpm] of Object.entries(g.rpms ?? {})) setText(card.querySelector(`[data-port="${p}"]`), fmt.n0(rpm));
for (const [p, rpm] of Object.entries(g.rpms ?? {})) {
// null: a top-fan channel whose tach has never reported a speed (SYS_FAN1's isn't wired)
const noTach = kind === "top" && rpm == null;
setText(card.querySelector(`[data-port="${p}"]`), noTach ? "no tach reading" : fmt.n0(rpm));
card.querySelector(`[data-unit="${p}"]`).hidden = noTach;
}
const n = q("note");
const text = g.failsafe ? g.status : kind === "top" && g.boosted ? "Held at 100% while a case-fan group runs at 85% or more." : "";
if (n.dataset.text !== text) {
@@ -686,7 +763,7 @@ function renderActive(ai) {
const st = b.model.state;
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
const token = !b.token ? null : adminLevel ? `admin rights, ${b.token.integrity} integrity (unexpected)`
: `${b.token.elevated ? "restricted token" : "normal user"}, ${b.token.integrity} integrity`;
: `normal user, ${b.token.integrity} integrity`;
const kv = el("dl", { class: "kv" },
el("dt", { text: "Model" }), el("dd", { text: b.model.id ?? b.model_label }),
b.model.context ? [el("dt", { text: "Context" }), el("dd", { text: `${fmt.n0(b.model.context)} tokens` })] : null,
@@ -751,7 +828,7 @@ function render(s) {
lastState = s;
renderHeader(s);
renderSystem(s);
if (telemetry.push(s.telemetry.row)) {
if (telemetry.push(s.telemetry.row) && rangeDays === 0) { // the live series stays fresh even in a long-range view
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
}
@@ -791,6 +868,7 @@ async function start() {
return;
}
buildCharts();
buildRange();
charts.power.setData(telemetry.t, telemetry.cols);
charts.temps.setData(telemetry.t, telemetry.cols);
charts.fans.setData(fanHistory.t, fanHistory.cols);
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

-12
View File
@@ -1,12 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32">
<symbol id="tank" viewBox="0 0 32 32">
<rect x="6.5" y="4" width="19" height="24" rx="1" fill="#141418"/>
<rect x="6.5" y="21" width="19" height="7" fill="#d95926"/>
<rect x="6.5" y="14.5" width="19" height="6" fill="#3987e5"/>
<rect x="6.5" y="8" width="19" height="6" fill="#199e70"/>
<rect x="9" y="5" width="2.2" height="22" fill="#fff" opacity=".25"/>
<rect x="3.5" y="1" width="25" height="4.5" rx="1.5" fill="#cecdd4"/>
<rect x="3.5" y="26.5" width="25" height="4.5" rx="1.5" fill="#cecdd4"/>
</symbol>
<use href="#tank"/>
</svg>

Before

Width:  |  Height:  |  Size: 632 B

+5 -2
View File
@@ -4,14 +4,14 @@
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>The Kurgan</title>
<link rel="icon" href="/static/favicon.svg" type="image/svg+xml">
<link rel="icon" href="/static/favicon.ico" sizes="16x16 32x32 48x48">
<link rel="stylesheet" href="/static/style.css">
<script src="/static/app.js" defer></script>
</head>
<body>
<header class="masthead">
<div class="brand">
<svg viewBox="0 0 32 32" aria-hidden="true"><use href="/static/favicon.svg#tank"/></svg>
<img src="/static/logo.png" alt="" width="90" height="40">
<h1>THE KURGAN</h1>
</div>
<nav aria-label="Sections">
@@ -51,6 +51,9 @@
<div class="detail" id="lcd-detail">&nbsp;</div>
</div>
</div>
<div class="row" style="justify-content:flex-end;margin:0 0 10px">
<div class="seg" role="radiogroup" aria-label="Chart range" id="chart-range"></div>
</div>
<div class="grid2">
<figure class="card chart" id="chart-power"></figure>
<figure class="card chart" id="chart-temps"></figure>
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+21 -2
View File
@@ -73,9 +73,10 @@ button, select, input { font: inherit; color: inherit; }
background: color-mix(in srgb, var(--page) 92%, transparent);
backdrop-filter: blur(6px);
border-bottom: 1px solid var(--border);
anchor-name: --masthead;
}
.brand { display: flex; align-items: center; gap: 10px; }
.brand svg { width: 22px; height: 22px; }
.brand img { display: block; width: auto; height: 40px; }
.brand h1 {
margin: 0; font-size: 17px; font-weight: 700; letter-spacing: 0.22em; color: var(--brand);
}
@@ -97,6 +98,20 @@ button, select, input { font: inherit; color: inherit; }
}
.banner .note { margin: 0; font-size: 14px; }
/* ---------------------------------------------------------------- the sword behind everything
Full size, pommel up, from just below the header to the bottom of the window, lined up with
the right edge of the tiles. Fixed: the page scrolls over it. The top follows the header's
height (it wraps on narrow windows); browsers without anchor positioning assume one row. */
body::after {
content: ""; position: fixed; z-index: -1; pointer-events: none;
top: 71px; bottom: 0; left: 0;
right: calc(max(0px, (100% - 1480px) / 2) + 24px); /* main's max-width and padding */
background: url("/static/sword-vertical.png") right top / auto 100% no-repeat;
}
@supports (top: anchor(--masthead bottom)) {
body::after { top: anchor(--masthead bottom); }
}
/* ---------------------------------------------------------------- layout */
main { padding: 8px 24px 40px; max-width: 1480px; margin: 0 auto; }
section { margin-top: 28px; }
@@ -107,7 +122,10 @@ section > h2 {
.grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); gap: 16px; margin-top: 16px; }
.grid3 { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 16px; margin-top: 16px; }
.card {
background: var(--surface); border: 1px solid var(--border); border-radius: 10px;
/* The sword shows through. 90% keeps the grey text at 4.5:1 or better over the brightest
metal (dark theme) and the black grip (light theme); 80% dropped it to 3.4:1. */
background: color-mix(in srgb, var(--surface) 90%, transparent);
border: 1px solid var(--border); border-radius: 10px;
padding: 16px 18px; margin: 0; min-width: 0;
}
.card h3 { margin: 0 0 2px; font-size: 15px; font-weight: 600; }
@@ -264,6 +282,7 @@ footer { color: var(--text-2); font-size: 12.5px; padding: 0 24px 28px; max-widt
@media (max-width: 720px) {
.masthead { padding: 10px 14px; gap: 12px; }
main { padding: 8px 14px 32px; }
body::after { right: 14px; }
.hero-value { font-size: 36px; }
.grid2 { grid-template-columns: 1fr; }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 228 KiB

+1
View File
@@ -1,3 +1,4 @@
pillow>=10.1
numpy>=1.26
nvidia-ml-py>=12.0
pywin32>=311
+82 -45
View File
@@ -1,16 +1,21 @@
# Sets up The Kurgan:
# 1. installs the Python packages it needs (into the project's .venv if there is one)
# 1. installs the Python packages it needs into the project's .venv (creating it if needed)
# 2. installs PawnIO (signed driver used by LibreHardwareMonitor) for CPU sensors, top fans and RAM lighting
# 3. replaces the old "TT LCD Dashboard" startup task with "The Kurgan" (hidden, admin rights, at logon)
# 3. removes the old startup tasks ("TT LCD Dashboard", and "The Kurgan" from when it ran with admin rights)
# 4. with -RetireAIServices: stops and disables the "Strata Local Service" and "Qwen4 Local Service"
# tasks, so The Kurgan runs whichever LLM server you select (re-enable them with uninstall.ps1)
# 5. starts The Kurgan; the web UI is at http://127.0.0.1:8080/
# 5. installs or updates the "The Kurgan hardware" Windows service (KurganHw: fans, CPU sensors,
# RAM lighting; LocalSystem, starts at boot) and moves the fan and RAM lighting settings from
# your settings.json to %ProgramData%\Kurgan\hw-settings.json (once)
# 6. registers "The Kurgan" (hidden, at logon) as you, WITHOUT admin rights, so the tray's
# "Start with Windows" can change it, and starts it; the web UI is at http://127.0.0.1:8080/
#
# Run from a normal PowerShell window:
# Run from a normal (not elevated) PowerShell window:
# powershell -ExecutionPolicy Bypass -File .\setup.ps1 [-RetireAIServices]
# It asks for administrator rights (UAC) itself.
# It asks for administrator rights (UAC) itself for steps 2-5. Run it again after updating The Kurgan.
param([switch]$Elevated, [string]$PythonW, [switch]$RetireAIServices)
param([switch]$Elevated, [switch]$RetireAIServices, [string]$Python, [string]$BasePython, [string]$UserSid,
[string]$UserSettings)
$ErrorActionPreference = 'Stop'
$TaskName = 'The Kurgan'
@@ -21,28 +26,72 @@ $Here = $PSScriptRoot
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator)
if ($isAdmin -and -not $Elevated) {
Write-Host "Run setup.ps1 from a normal PowerShell window, not an elevated one: The Kurgan's startup" -ForegroundColor Red
Write-Host "task must be registered as you without admin rights. It asks for admin rights itself." -ForegroundColor Red
exit 1
}
if (-not $isAdmin) {
# Prefer the project's own .venv; otherwise use whichever python is on PATH.
$venvPython = Join-Path $Here '.venv\Scripts\python.exe'
if (Test-Path $venvPython) {
$python = $venvPython
} else {
$python = (Get-Command python -ErrorAction Stop).Source
Set-Location $Here
# The project's own .venv: the hardware service runs from it too (hw_service.py adds its packages).
$python = Join-Path $Here '.venv\Scripts\python.exe'
if (-not (Test-Path $python)) {
Write-Host "Creating the project's .venv..." -ForegroundColor Cyan
& (Get-Command python -ErrorAction Stop).Source -m venv (Join-Path $Here '.venv')
if ($LASTEXITCODE -ne 0) { throw "creating .venv failed" }
}
$inVenv = (& $python -c "import sys; print(int(sys.prefix != sys.base_prefix))") -eq '1'
$pipArgs = if ($inVenv) { @() } else { @('--user') }
$pythonw = Join-Path (Split-Path $python) 'pythonw.exe'
if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found next to $python" }
Write-Host "Installing Python packages into $(Split-Path (Split-Path $python))..." -ForegroundColor Cyan
& $python -m pip install @pipArgs --quiet --disable-pip-version-check -r (Join-Path $Here 'requirements.txt')
& $python -m pip install --quiet --disable-pip-version-check -r (Join-Path $Here 'requirements.txt')
if ($LASTEXITCODE -ne 0) { throw "pip install failed" }
Write-Host "Requesting administrator rights for PawnIO and the startup task..." -ForegroundColor Cyan
$argList = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Elevated -PythonW `"$pythonw`""
# What the elevated part needs to know about you and this Python.
$basePython = (& $python -c "import sys; print(sys._base_executable)").Trim() # the service runs this one
$userSettings = (& $python -c "from kurgan import paths; print(paths.SETTINGS_PATH)").Trim()
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
Write-Host "Requesting administrator rights for PawnIO, the old startup tasks and the hardware service..." -ForegroundColor Cyan
$argList = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Elevated -Python `"$python`" " +
"-BasePython `"$basePython`" -UserSid $userSid -UserSettings `"$userSettings`""
if ($RetireAIServices) { $argList += ' -RetireAIServices' }
$p = Start-Process powershell -Verb RunAs -ArgumentList $argList -Wait -PassThru
exit $p.ExitCode
if ($p.ExitCode -ne 0) { Write-Host "Setup stopped (the elevated part failed)." -ForegroundColor Red; exit $p.ExitCode }
try {
# --- the fan and RAM settings now live in hw-settings.json: tidy settings.json ------
& $python -m kurgan.hw.migrate strip
if ($LASTEXITCODE -ne 0) { throw "tidying settings.json failed (see above)" }
# --- The Kurgan's startup task: as you, without admin rights ----------------------
$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$action = New-ScheduledTaskAction -Execute $pythonw -Argument '-m kurgan' -WorkingDirectory $Here
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Limited
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
-ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1) `
-MultipleInstances IgnoreNew -StartWhenAvailable
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Principal $principal `
-Settings $settings -Description 'The Kurgan: LCD dashboard, lighting, the local LLM servers and the web UI' `
-Force | Out-Null
Start-ScheduledTask -TaskName $TaskName
} catch {
Write-Host "Setup failed: $_" -ForegroundColor Red
exit 1
}
& $python -m kurgan.hw.client # what the hardware service says
Write-Host "Done. '$TaskName' is running and will start at every logon." -ForegroundColor Green
Write-Host "Web UI: http://127.0.0.1:8080/ Log: $env:LOCALAPPDATA\Kurgan\kurgan.log"
if (-not $RetireAIServices) {
$running = $AITasks | Where-Object { (Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue).State -eq 'Running' }
if ($running) {
Write-Host "Still running on their own: $($running -join ', '). The Kurgan only watches them;" -ForegroundColor Yellow
Write-Host "run setup.ps1 -RetireAIServices to let The Kurgan run and swap them." -ForegroundColor Yellow
}
}
exit 0
}
function Stop-Matching([scriptblock]$Filter) {
@@ -50,13 +99,8 @@ function Stop-Matching([scriptblock]$Filter) {
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
}
# --- the elevated part ----------------------------------------------------------------------
try {
if (-not $PythonW) {
$venvPythonW = Join-Path $Here '.venv\Scripts\pythonw.exe'
$PythonW = if (Test-Path $venvPythonW) { $venvPythonW } else {
Join-Path (Split-Path (Get-Command python -ErrorAction Stop).Source) 'pythonw.exe' }
}
# --- PawnIO -------------------------------------------------------------------------
$pawn = Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\PawnIO' -ErrorAction SilentlyContinue
if ($pawn) {
@@ -71,7 +115,11 @@ try {
foreach ($name in $TaskName, $LegacyTaskName) { Stop-ScheduledTask -TaskName $name -ErrorAction SilentlyContinue }
Stop-Matching { $_.Name -like 'python*.exe' -and ($_.CommandLine -like '*lcd_dashboard.py*' -or
$_.CommandLine -like '*-m kurgan*') }
Unregister-ScheduledTask -TaskName $LegacyTaskName -Confirm:$false -ErrorAction SilentlyContinue
# "The Kurgan" is registered again afterwards, as you and without admin rights (a task
# registered elevated couldn't be replaced from there, nor changed by the tray).
foreach ($name in $TaskName, $LegacyTaskName) {
Unregister-ScheduledTask -TaskName $name -Confirm:$false -ErrorAction SilentlyContinue
}
# --- the LLM servers' own startup tasks ------------------------------------------------
if ($RetireAIServices) {
@@ -87,27 +135,16 @@ try {
($_.Name -eq 'llama-server.exe' -and $_.CommandLine -like '*qwen4-35b-a3b\service\presets.ini*') }
}
# --- scheduled task ------------------------------------------------------------------
$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$action = New-ScheduledTaskAction -Execute $PythonW -Argument '-m kurgan' -WorkingDirectory $Here
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries `
-ExecutionTimeLimit ([TimeSpan]::Zero) -RestartCount 5 -RestartInterval (New-TimeSpan -Minutes 1) `
-MultipleInstances IgnoreNew -StartWhenAvailable
Register-ScheduledTask -TaskName $TaskName -Action $action -Trigger $trigger -Principal $principal `
-Settings $settings -Description 'The Kurgan: LCD dashboard, fans, lighting and the local LLM server' `
-Force | Out-Null
Start-ScheduledTask -TaskName $TaskName
Write-Host "Done. '$TaskName' is running and will start at every logon." -ForegroundColor Green
Write-Host "Web UI: http://127.0.0.1:8080/ Log: $env:LOCALAPPDATA\Kurgan\kurgan.log"
if (-not $RetireAIServices) {
$running = $AITasks | Where-Object { (Get-ScheduledTask -TaskName $_ -ErrorAction SilentlyContinue).State -eq 'Running' }
if ($running) {
Write-Host "Still running on their own: $($running -join ', '). The Kurgan only watches them;" -ForegroundColor Yellow
Write-Host "run setup.ps1 -RetireAIServices to let The Kurgan run and swap them." -ForegroundColor Yellow
}
# --- the hardware service ------------------------------------------------------------
# Checks that the base interpreter can run it, sets up %ProgramData%\Kurgan (admins write, users
# read), moves the fan and RAM settings there once, then installs or updates and starts KurganHw.
if (-not ($Python -and $BasePython -and $UserSid -and $UserSettings)) {
throw "run setup.ps1 from a normal PowerShell window; it passes these on to the elevated part"
}
Set-Location $Here
& $Python -m kurgan.hw.install --python $BasePython --user-sid $UserSid --user-settings $UserSettings
if ($LASTEXITCODE -ne 0) { throw "installing the hardware service failed (see above)" }
} catch {
Write-Host "Setup failed: $_" -ForegroundColor Red
Read-Host "Press Enter to close"
+104 -2
View File
@@ -1,11 +1,14 @@
import msvcrt
import os
import sys
import tempfile
import threading
import unittest
from pathlib import Path
from unittest.mock import patch
from kurgan.ai import launcher
from kurgan.ai.backends import Backend, LlamaLog
from kurgan.ai import launcher, strata_host
from kurgan.ai.backends import Backend, LlamaLog, StrataBackend
from kurgan.ai.service import CLIENT_GONE, AiService, RouteError
from kurgan.settings import Settings
@@ -311,8 +314,81 @@ class AiServiceTest(unittest.TestCase):
self.reconcile()
self.assertEqual(self.processes()["llama"], "starting")
def test_a_server_with_a_request_in_flight_is_not_stopped_or_replaced(self):
self.service.set_active("strata")
self.reconcile()
self.service.inflight["strata"] = 1 # a reply in progress
self.service.set_active("llama")
self.reconcile()
# Strata finishes its request first; llama must not start onto the GPU's memory.
self.assertEqual(self.events, [("start", "strata")])
self.assertIn("Waiting for Strata to finish its request", self.service.transition)
self.service.release("strata")
self.reconcile()
self.assertEqual(self.events, [("start", "strata"), ("stop", "strata"), ("start", "llama")])
def test_a_model_change_waits_for_the_request_in_flight(self):
self.service.set_active("strata", "iq3")
self.reconcile()
self.service.inflight["strata"] = 1
self.service.set_active("strata", "q5")
self.reconcile()
self.assertEqual(self.events, [("start", "strata")]) # iq3 keeps serving until the reply ends
self.service.release("strata")
self.reconcile()
self.assertEqual(self.events, [("start", "strata"), ("stop", "strata"), ("start", "strata")])
def test_a_port_held_by_a_program_that_is_not_the_server_is_not_used(self):
self.external_ports.add(18082)
self.service.set_active("strata")
self.reconcile()
self.assertEqual(self.service.snapshot()["backends"][0]["process"], "external")
self.service.slots["strata"].reachable = True # a poll succeeded: the program is Strata
self.assertEqual(self.service.claim("strata").key, "strata")
self.service.release("strata")
self.service.slots["strata"].reachable = False # ...and then it stopped answering as one
thread, result = self.claim_in_background("strata")
threading.Event().wait(0.2)
self.clock[0] += 11
thread.join(5)
self.assertIn("isn't answering as Strata", str(result["error"]))
self.assertEqual(self.service.inflight["strata"], 0) # the failed claim gave its place back
class StrataLogRotationTest(unittest.TestCase):
def test_old_strata_logs_are_rotated_and_pruned(self):
with tempfile.TemporaryDirectory() as directory:
logs = Path(directory)
(logs / "local-service-task.log").write_text("last run")
for number in range(9):
stamp = f"2026010{number + 1}-000000-000000"
(logs / f"local-service-stdout-{stamp}.log").write_text("out")
(logs / f"local-service-stderr-{stamp}.log").write_text("err")
strata_host.rotate_logs(logs)
self.assertEqual((logs / "local-service-task.prev.log").read_text(), "last run")
self.assertFalse((logs / "local-service-task.log").exists())
names = sorted(p.name for p in logs.glob("local-service-std*.log"))
self.assertEqual(len(names), 2 * strata_host.KEEP_LOG_PAIRS) # the newest few pairs
self.assertIn("local-service-stdout-20260109-000000-000000.log", names)
self.assertNotIn("local-service-stdout-20260101-000000-000000.log", names)
def test_strata_host_log_is_rotated_before_a_start(self):
with tempfile.TemporaryDirectory() as directory:
with patch("kurgan.ai.backends.LOG_DIR", directory):
backend = StrataBackend(Settings(os.path.join(directory, "settings.json"), None))
with open(os.path.join(directory, "strata-host.log"), "w") as log:
log.write("previous run")
backend.before_start()
self.assertFalse(os.path.exists(os.path.join(directory, "strata-host.log")))
with open(os.path.join(directory, "strata-host.prev.log")) as log:
self.assertEqual(log.read(), "previous run")
ELEVATED = launcher.token_info()["elevated"]
class LauncherTest(unittest.TestCase):
@unittest.skipIf(ELEVATED, "the launcher refuses to run elevated")
def test_child_runs_as_a_normal_user_with_its_output_logged(self):
with tempfile.TemporaryDirectory() as directory:
log_path = os.path.join(directory, "logs", "child.log")
@@ -325,6 +401,32 @@ class LauncherTest(unittest.TestCase):
with open(log_path, encoding="utf-8", errors="replace") as f:
self.assertIn("hello from the child", f.read())
@unittest.skipIf(ELEVATED, "the launcher refuses to run elevated")
def test_only_the_log_and_nul_are_inherited(self):
# The child names the file behind a handle number of ours that is inheritable but not listed.
script = ("import ctypes, sys; b = ctypes.create_unicode_buffer(1024); "
"n = ctypes.windll.kernel32.GetFinalPathNameByHandleW(ctypes.c_void_p(int(sys.argv[1])), b, 1024, 0); "
"print(b.value if n else 'no such handle')")
with tempfile.TemporaryDirectory() as directory:
log_path = os.path.join(directory, "child.log")
with open(os.path.join(directory, "secret.txt"), "w") as f:
handle = msvcrt.get_osfhandle(f.fileno())
os.set_handle_inheritable(handle, True)
child = launcher.launch([sys._base_executable, "-I", "-c", script, str(handle)], directory, log_path)
try:
self.assertEqual(child.wait(30), 0)
finally:
child.close()
with open(log_path, encoding="utf-8") as f:
self.assertNotIn("secret.txt", f.read())
def test_an_elevated_kurgan_starts_nothing(self):
with patch.object(launcher, "elevated", return_value=True), tempfile.TemporaryDirectory() as directory:
with self.assertRaises(PermissionError) as raised:
launcher.launch(["cmd.exe", "/d", "/c", "exit 0"], directory, None)
self.assertIn("admin rights", str(raised.exception))
@unittest.skipIf(ELEVATED, "the launcher refuses to run elevated")
def test_kill_ends_the_whole_job(self):
with tempfile.TemporaryDirectory() as directory:
child = launcher.launch(["cmd.exe", "/d", "/c", "ping -n 30 127.0.0.1"], directory, None)
+132
View File
@@ -0,0 +1,132 @@
import unittest
from unittest.mock import Mock, patch
from kurgan import tray
from kurgan.app import ALERT_REPEAT_SECONDS, alert_states, balloon, due_alerts, new_alerts
def fake_cooling(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
"""The hardware service's fan state, as HardwareClient.cooling() returns it."""
return {"profile": "balanced", "groups": [{"name": "GPU", "duty": 40, "status": gpu_status}],
"top": {"duty": 45, "status": top_status}, "note": None, "row": None}
def fake_ai(*errors):
ai = Mock()
ai.snapshot.return_value = {"backends": [{"key": key, "label": key.capitalize(), "error": error}
for key, error in errors]}
return ai
def fake_health(entries=None):
telemetry = Mock()
telemetry.health.return_value = entries or {}
return telemetry
class AlertStatesTest(unittest.TestCase):
def test_healthy_everything_is_quiet(self):
self.assertEqual(alert_states(fake_cooling(), fake_ai(("strata", None), ("llama", None)),
fake_health()), {})
def test_failsafes_errors_and_failing_sources_are_collected(self):
states = alert_states(
fake_cooling(gpu_status="FAILSAFE 100%: GPU temperature unavailable",
top_status="UNAVAILABLE (lost); BIOS curve keeps control"),
fake_ai(("strata", "exited (code 3); restarting."), ("llama", None)),
fake_health({"GPU sensors": {"error": "NVMLError: uninitialised", "age_s": 3.0}}))
self.assertEqual(states, {
"fans/GPU": "GPU case fans: FAILSAFE 100%: GPU temperature unavailable",
"fans/top": "Top fans: UNAVAILABLE (lost); BIOS curve keeps control",
"ai/strata": "Strata: exited (code 3); restarting.",
"telemetry/GPU sensors": "GPU sensors read failed (NVMLError: uninitialised); continuing without it",
})
def test_fans_or_ai_being_off_is_not_an_error(self):
self.assertEqual(alert_states(None, None, fake_health()), {})
not_set_up = {"profile": "balanced", "groups": [], "top": None, "note": "Fan control isn't set up", "row": None}
self.assertEqual(alert_states(not_set_up, None, fake_health()), {})
def test_the_hardware_service_being_unavailable_is_one_alert_of_its_own(self):
states = alert_states({"profile": None, "groups": [], "top": None, "note": "unavailable", "row": None}, None,
fake_health({"hardware service": {"error": "the hardware service isn't running (no pipe)",
"age_s": 0.0}}))
self.assertEqual(states, {"hw": "Hardware service unavailable: the hardware service isn't running (no pipe)"})
class NewAlertsTest(unittest.TestCase):
def test_only_new_keys_alert_and_recovery_is_quiet(self):
known = {"fans/GPU": "an earlier message"}
states = {"fans/GPU": "still failing", "ai/strata": "exited"}
self.assertEqual(new_alerts(known, states), [("ai/strata", "exited")])
self.assertEqual(new_alerts(states, {}), []) # everything recovered: nothing new
self.assertEqual(new_alerts({}, states), [("ai/strata", "exited"), ("fans/GPU", "still failing")])
class DueAlertsTest(unittest.TestCase):
def test_a_flapping_problem_balloons_once_per_cooldown(self):
alerted = {}
flap = [("telemetry/GPU sensors", "GPU sensors read failed")]
self.assertEqual(due_alerts(flap, alerted, 0), flap)
self.assertEqual(due_alerts(flap, alerted, 15), []) # cleared and came back: quiet
self.assertEqual(due_alerts(flap, alerted, ALERT_REPEAT_SECONDS - 1), [])
self.assertEqual(due_alerts(flap, alerted, ALERT_REPEAT_SECONDS), flap)
other = [("fans/GPU", "GPU case fans: FAILSAFE")]
self.assertEqual(due_alerts(other, alerted, 20), other) # each problem has its own cooldown
class BalloonTest(unittest.TestCase):
def test_one_alert_is_its_own_balloon(self):
self.assertEqual(balloon(["Top fans: FAILSAFE 100%"]), ("The Kurgan", "Top fans: FAILSAFE 100%"))
def test_alerts_at_the_same_moment_share_one_balloon(self):
title, text = balloon(["GPU case fans: CONTROL ERROR", "CPU case fans: CONTROL ERROR", "Top fans: FAILSAFE"])
self.assertEqual(title, "The Kurgan: 3 problems")
self.assertEqual(text, "GPU case fans: CONTROL ERROR\nCPU case fans: CONTROL ERROR\nTop fans: FAILSAFE")
def test_too_many_for_the_balloon_end_with_a_count(self):
messages = [f"problem {i}: " + "x" * 60 for i in range(6)]
title, text = balloon(messages)
self.assertLessEqual(len(text), 255)
lines = text.split("\n")
self.assertEqual(lines[:3], messages[:3])
self.assertEqual(lines[-1], f"...and {6 - (len(lines) - 1)} more")
_, text = balloon(["y" * 300, "short"]) # even the first alone doesn't fit
self.assertLessEqual(len(text), 255)
self.assertTrue(text.endswith("...\n...and 1 more"))
class TrayNotifyTest(unittest.TestCase):
def make_icon(self):
return tray.TrayIcon("The Kurgan", "unused.ico", on_exit=lambda: None)
def test_notify_queues_a_balloon_and_pings_the_tray_thread(self):
icon = self.make_icon()
icon.notify("The Kurgan", "Top fans: FAILSAFE 100%", warning=True) # no window yet: just stored
self.assertEqual(icon._info, ("The Kurgan", "Top fans: FAILSAFE 100%", tray.NIIF_WARNING))
icon._hwnd = 123
with patch.object(tray, "_u32") as u32:
icon.notify("The Kurgan", "hello")
u32.PostMessageW.assert_called_once_with(123, tray.WM_TRAY_INFO, 0, 0)
self.assertEqual(icon._info[2], tray.NIIF_NONE)
def test_messages_are_cut_to_what_the_structure_holds(self):
icon = self.make_icon()
icon.notify("t" * 100, "m" * 300)
title, message, _ = icon._info
self.assertEqual((len(title), len(message)), (63, 255))
def test_the_balloon_fields_are_filled_and_shown(self):
icon = self.make_icon()
icon._hwnd = 1
icon._info = ("The Kurgan", "GPU case fans: FAILSAFE 100%", tray.NIIF_WARNING)
nid = icon._info_nid()
self.assertEqual((nid.uFlags, nid.szInfoTitle, nid.szInfo, nid.dwInfoFlags),
(tray.NIF_INFO, "The Kurgan", "GPU case fans: FAILSAFE 100%", tray.NIIF_WARNING))
with patch.object(tray, "_shell32") as shell:
icon._show_info()
self.assertEqual(shell.Shell_NotifyIconW.call_args.args[0], tray.NIM_MODIFY)
if __name__ == "__main__":
unittest.main()
+103
View File
@@ -0,0 +1,103 @@
import http.client
import json
import os
import socket
import tempfile
import time
import unittest
from unittest.mock import patch
from kurgan import app as kurgan_app
from kurgan import paths
from kurgan.hw.client import HardwareUnavailable
from kurgan.hw.pipe import PipeError
from kurgan.settings import Settings
def free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def wait_for(condition, timeout=10.0):
deadline = time.monotonic() + timeout
while not condition():
if time.monotonic() > deadline:
raise AssertionError("timed out")
time.sleep(0.05)
class AppTest(unittest.TestCase):
"""The whole app in demo mode (the real hardware service in-process, on fakes), in a temp folder."""
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
patcher = patch.object(paths, "DATA_DIR", directory.name) # demo-hw-settings.json goes here
patcher.start()
self.addCleanup(patcher.stop)
self.port = free_port()
args = kurgan_app.parse_args(["--demo", "--no-ai", "--no-tray", "--interval", "0.25"])
self.app = kurgan_app.Kurgan(args, Settings(os.path.join(directory.name, "settings.json"), None))
self.app.hw.poll_seconds = 0.1
self.connect = self.app.hw._connect
self.app.start(self.port, tray=False)
self.addCleanup(self.app.close)
def post(self, path, body):
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
try:
connection.request("POST", path, json.dumps(body),
{"Content-Type": "application/json", "X-Kurgan": "1", "Host": f"127.0.0.1:{self.port}"})
response = connection.getresponse()
return response.status, json.loads(response.read())
finally:
connection.close()
def test_the_demo_app_shows_and_drives_the_services_fans(self):
wait_for(lambda: self.app.state()["cooling"]["groups"])
state = self.app.state()
self.assertTrue(state["hardware"]["available"])
self.assertEqual([g["name"] for g in state["cooling"]["groups"]], ["GPU", "CPU"])
wait_for(lambda: self.app.history()["fans"]["rows"])
status, body = self.post("/api/cooling/profile", {"profile": "performance"})
self.assertEqual((status, body["cooling"]["profile"]), (200, "performance"))
status, body = self.post("/api/lighting", {"zone": "memory", "mode": "temperature"})
self.assertEqual(status, 200)
self.assertEqual(next(z for z in body["lighting"]["zones"] if z["key"] == "memory")["mode"], "temperature")
def test_without_the_service_the_app_carries_on_and_says_so(self):
def no_service():
raise PipeError("the hardware service isn't running (no pipe)", 2)
with self.assertLogs("kurgan", level="WARNING"):
self.app.hw._connect = no_service
self.app.hw._drop()
wait_for(lambda: "hardware service" in self.app.telemetry.health())
state = self.app.state()
self.assertFalse(state["hardware"]["available"])
self.assertIn("isn't running", state["hardware"]["error"])
self.assertEqual(state["cooling"]["groups"], [])
self.assertIn("Hardware service unavailable", state["cooling"]["note"])
self.assertIsNotNone(state["telemetry"]["gpu"]["temp"]) # the rest of telemetry carries on
self.assertEqual(list(state["telemetry"]["health"]), ["hardware service"])
states = kurgan_app.alert_states(self.app.hw.cooling(), self.app.ai, self.app.telemetry)
self.assertEqual(list(states), ["hw"])
self.assertIn("Fans: hardware service unavailable", self.app.tray_lines())
with self.assertLogs("kurgan.web.server", level="WARNING"):
status, body = self.post("/api/cooling/profile", {"profile": "quiet"})
self.assertEqual(status, 503)
self.assertIn("isn't running", body["error"])
with self.assertRaises(HardwareUnavailable):
self.app.set_lighting("memory", "chase")
self.app.set_lighting("gpu", "chase") # the app's own lighting still works
with self.assertLogs("kurgan", level="INFO"):
self.app.hw._connect = self.connect # the service is back
wait_for(lambda: self.app.telemetry.health() == {} and self.app.state()["cooling"]["groups"])
self.assertTrue(self.app.state()["hardware"]["available"])
if __name__ == "__main__":
unittest.main()
+112 -27
View File
@@ -1,6 +1,5 @@
import argparse
import contextlib
import threading
import unittest
from unittest.mock import Mock, call, mock_open, patch
@@ -38,6 +37,7 @@ class TopFanCurveTest(unittest.TestCase):
self.mask = 0
self.duties = []
self.board.manual_mask.side_effect = lambda: self.mask
self.board.rpms.return_value = [0] * 16 # nothing has been seen turning yet
def manual(ch, duty):
self.mask |= 0x24
@@ -110,16 +110,82 @@ class TopFanCurveTest(unittest.TestCase):
top.update(100, 60, 31)
self.board.set_manual.assert_called_once_with((2, 5), 100)
def test_a_failed_write_hands_the_fans_back_to_the_bios_curve(self):
self.top.update(40, 70, 0) # manual 100% written on channels 2,5
self.mask = 0 # the EC forgot (sleep, crash): a rewrite is due ...
self.board.set_manual.side_effect = OSError("bus busy") # ... and fails
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 70, 1)
self.board.set_auto.assert_called_with((2, 5))
self.assertIn("BIOS curve keeps control", self.top.status)
def test_a_failed_hand_back_says_what_the_fans_are_left_at(self):
self.top.update(40, 70, 0)
self.mask = 0
self.board.set_manual.side_effect = OSError("bus busy")
self.board.set_auto.side_effect = OSError("still busy") # even the hand-back fails
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 70, 1)
self.assertIn("held at the last written duty (100%)", self.top.status)
def test_a_top_fan_that_stops_turning_is_detected(self):
tachs = [0] * 16
self.board.rpms.return_value = tachs
for now in range(10): # spinning, but no tach has been seen turning: no evidence yet
self.top.update(40, 55, now)
self.assertNotIn("FAILSAFE", self.top.status)
tachs[2], tachs[5] = 1500, 1400
self.top.update(40, 55, 10)
self.top.update(40, 55, 11)
self.assertNotIn("FAILSAFE", self.top.status) # learned: both tachs turn
tachs[5] = 0
self.top.update(40, 55, 12)
self.top.update(40, 55, 13)
self.assertNotIn("FAILSAFE", self.top.status) # one glitchy reading is not a stall
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.top.update(40, 55, 14)
self.assertIn("FAILSAFE", self.top.status)
self.assertIn("[5]", self.top.status)
self.assertEqual(self.top.duty, 100)
self.board.set_manual.assert_called_with((2, 5), 100)
tachs[5] = 1300 # the fan turns again: the failsafe lifts on the next poll
self.top.update(40, 55, 15)
self.assertNotIn("FAILSAFE", self.top.status)
self.assertEqual(self.top.snapshot()["rpms"], {"2": 1500, "5": 1300})
def test_a_tach_never_seen_turning_shows_no_reading(self):
tachs = [0] * 16
self.board.rpms.return_value = tachs
tachs[5] = 1040 # channel 2's tach isn't wired: it always reads 0
for now in range(5):
self.top.update(40, 55, now)
self.assertEqual(self.top.snapshot()["rpms"], {"2": None, "5": 1040})
def test_an_unexpected_board_error_hands_back_to_the_bios_instead_of_escaping(self):
self.top.update(40, 70, 0)
self.board.rpms.side_effect = AttributeError("no rpms") # a bug, not a device error
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.top.update(40, 70, 1) # must not raise into the case fans' loop
self.board.set_auto.assert_called_with((2, 5))
self.assertIn("UNAVAILABLE", self.top.status)
def test_the_demo_board_supports_stall_detection(self):
from kurgan.demo import FakeBoard
top = TopFanCurve((2, 5), board_factory=FakeBoard)
for now in range(8):
top.update(40, 60, now)
self.assertNotIn("UNAVAILABLE", top.status)
self.assertNotIn("FAILSAFE", top.status)
self.assertEqual(top.snapshot()["rpms"], {"2": 14 * top.duty, "5": 14 * top.duty})
def test_gpu_worker_drives_top_fans_and_releases_them_on_exit(self):
commander = Mock(spec=CommanderPro)
commander.set_duty.return_value = {p: 900 for p in range(1, 7)}
control = CaseFanControl(commander, (4, 5, 6), None, self.top)
control.update(40, 0) # startup runs the case fans at 100%
self.assertTrue(self.top.boosted)
stop = threading.Event()
stop.set()
with patch("kurgan.cooling.control.GpuSensors"):
control.run(stop)
control.shutdown()
self.assertEqual(self.mask, 0)
self.board.close.assert_called()
@@ -158,12 +224,23 @@ class TopFanCurveTest(unittest.TestCase):
def test_cpu_temperature_is_averaged_and_gaps_are_not(self):
pkg = Mock()
pkg.temperature.side_effect = [50, 90, None, 60]
pkg.power.return_value = 35.0
cpu = CpuTemperature(factory=lambda: pkg)
self.assertEqual(cpu.read(0), 50)
self.assertEqual(cpu.read(1), 70)
self.assertEqual((cpu.temp, cpu.power, cpu.error), (90, 35.0, None)) # the latest, for the app
self.assertIsNone(cpu.read(2))
self.assertIsNotNone(cpu.error)
self.assertEqual(cpu.read(3), 60)
def test_cpu_temperature_failures_say_why_and_back_off(self):
cpu = CpuTemperature(factory=Mock(side_effect=OSError("Cannot open PawnIO")))
with self.assertLogs("kurgan.cooling.control", level="WARNING"):
self.assertIsNone(cpu.read(0))
self.assertEqual((cpu.temp, cpu.power, cpu.error), (None, None, "Cannot open PawnIO"))
cpu.read(30) # within the minute: not re-opened
self.assertEqual(cpu._factory.call_count, 1)
class Nct6687ControlTest(unittest.TestCase):
def test_override_uses_config_handshake_and_keeps_other_channels(self):
@@ -224,39 +301,47 @@ class FanWorkerTest(unittest.TestCase):
self.commander.set_duty.return_value = {1: 0, 4: 900, 5: 900, 6: 900}
self.settle()
self.assertNotIn("FAILSAFE", self.control.status)
# One glitchy reading is not a stall; STALL_READINGS in a row are.
self.commander.set_duty.return_value = {4: 900, 5: 0, 6: 900}
self.control.update(50, 36)
self.control.update(50, 37)
self.assertNotIn("FAILSAFE", self.control.status)
self.commander.set_duty.reset_mock()
self.control.update(50, 38)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.assertIn("FAILSAFE", self.control.status)
self.assertIn("[5]", self.control.status)
def test_exit_leaves_selected_ports_at_full_speed_even_without_lcd(self):
stop = threading.Event()
stop.set()
with patch("kurgan.cooling.control.GpuSensors"):
self.control.run(stop)
def test_shutdown_leaves_selected_ports_at_full_speed(self):
self.control.shutdown()
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
self.commander.close.assert_called_once()
def test_worker_survives_unexpected_errors_and_keeps_failing_safe(self):
stop = threading.Event()
gpu = Mock()
reads = []
def read():
reads.append(1)
if len(reads) >= 3:
stop.set()
raise RuntimeError("sensor failure")
gpu.read.side_effect = read
with patch("kurgan.cooling.control.GpuSensors", return_value=gpu), \
patch.object(CaseFanControl, "ERROR_RETRY_SECONDS", 0):
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.control.run(stop)
self.assertEqual(len(reads), 3) # retried instead of dying on the first error
def test_a_device_error_fails_safe_reopens_and_backs_off(self):
self.commander.set_duty.side_effect = [OSError("no reply to command 0x20"), {4: 900, 5: 900, 6: 900}]
self.assertEqual(self.control.step(50, None, 0), CaseFanControl.ERROR_RETRY_SECONDS)
self.assertIn("CONTROL ERROR", self.control.status)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
self.commander.close.assert_called_once() # reopened on the next pass
def test_a_control_bug_fails_safe_and_the_next_pass_runs(self):
ok = {p: 900 for p in range(1, 7)}
self.commander.set_duty.side_effect = [RuntimeError("bug"), ok, ok]
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.assertEqual(self.control.step(50, None, 0), CaseFanControl.ERROR_RETRY_SECONDS)
self.assertIn("CONTROL ERROR", self.control.status)
self.assertEqual(self.commander.set_duty.call_args_list[1], call((4, 5, 6), 100))
self.assertEqual(self.control.step(50, None, 5), 1.0) # not dead: the next pass works
def test_unexpected_errors_fail_the_top_fans_safe_too(self):
top = Mock(spec=TopFanCurve)
self.control.top = top
self.commander.set_duty.side_effect = [RuntimeError("bug"), {p: 900 for p in range(1, 7)}]
with self.assertLogs("kurgan.cooling.control", level="ERROR"):
self.control.step(50, None, 0)
self.assertEqual(top.update.call_args.args[:2], (100, None))
self.control.shutdown()
top.release.assert_called_once()
class CommanderControlTest(unittest.TestCase):
+212
View File
@@ -0,0 +1,212 @@
import json
import os
import tempfile
import threading
import time
import unittest
from kurgan import demo
from kurgan.hw import client as hw_client
from kurgan.hw.client import (CommanderReadings, CpuPackage, HardwareClient, HardwareUnavailable, LocalTransport,
PipeTransport, RamLighting)
from kurgan.hw.pipe import PipeError, PipeServer, current_user_sid, pipe_sddl
from kurgan.hw.protocol import VERSION, RemoteError, Session
from kurgan.telemetry.sensors import CpuSensors, SystemPower
from kurgan.telemetry.service import SERVICE_SOURCE, Telemetry
class Service:
"""The demo's hardware service (the real HardwareService on fakes) and a client to it."""
def __init__(self, test: unittest.TestCase):
directory = tempfile.TemporaryDirectory()
test.addCleanup(directory.cleanup)
self.path = os.path.join(directory.name, "hw-settings.json")
self.service = demo.hardware_service(self.path)
self.service.tick(time.monotonic())
self.connects = 0
self.down = False # the next connects fail, as with no pipe
self.transport: LocalTransport | None = None
def connect(self):
self.connects += 1
if self.down:
raise PipeError("the hardware service isn't running (no pipe)", 2)
self.transport = LocalTransport(self.service.dispatch)
return self.transport
def saved(self) -> dict:
with open(self.path, encoding="utf-8") as stream:
return json.load(stream)
class ClientTest(unittest.TestCase):
def setUp(self):
self.hw = Service(self)
self.client = HardwareClient(self.hw.connect)
def test_reads_the_services_state(self):
self.client.poll()
self.assertIsNone(self.client.error)
cooling = self.client.cooling()
self.assertEqual([g["name"] for g in cooling["groups"]], ["GPU", "CPU"])
self.assertEqual(cooling["profile"], "balanced")
self.assertEqual(len(cooling["row"]), 4)
self.assertIsNotNone(self.client.cpu()["temp"])
self.assertEqual(len(self.client.fan_rpms()), 6)
self.assertEqual(self.client.ram_lighting()["mode"], "off")
snapshot = self.client.snapshot()
self.assertTrue(snapshot["available"])
self.assertEqual(snapshot["pid"], os.getpid())
def test_changes_go_to_the_service_and_are_saved_there(self):
self.client.poll()
self.client.set_profile("quiet")
self.assertEqual(self.client.cooling()["profile"], "quiet") # the reply's state, no poll needed
self.client.set_ram_lighting("chase")
self.assertEqual(RamLighting(self.client).mode, "chase")
self.assertEqual(self.hw.saved()["cooling"]["profile"], "quiet")
self.assertEqual(self.hw.saved()["lighting"]["memory"], "chase")
def test_bad_values_are_value_errors_and_nothing_is_sent(self):
self.client.poll()
for call, value in ((self.client.set_profile, "turbo"), (self.client.set_ram_lighting, "rainbow")):
with self.subTest(value=value), self.assertRaises(ValueError):
call(value)
self.assertEqual(self.hw.saved()["cooling"]["profile"], "balanced")
def test_without_a_service_everything_reads_empty_and_changes_raise(self):
self.hw.down = True
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIn("isn't running", self.client.error)
self.assertIsNone(self.client.state)
cooling = self.client.cooling()
self.assertEqual((cooling["groups"], cooling["top"], cooling["row"]), ([], None, None))
self.assertIn("Hardware service unavailable", cooling["note"])
self.assertEqual(self.client.fan_rpms(), [])
self.assertEqual(CpuPackage(self.client).read(), (None, None))
self.assertIn("unavailable", CpuPackage(self.client).status)
self.assertIn("unavailable", RamLighting(self.client).status)
self.assertFalse(self.client.snapshot()["available"])
with self.assertRaises(HardwareUnavailable):
self.client.set_profile("quiet")
def test_reconnects_and_greets_again_after_the_service_restarts(self):
self.client.poll()
self.client.set_profile("quiet")
self.hw.transport.close() # the service went away mid-connection
self.hw.down = True
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIsNotNone(self.client.error)
self.assertEqual(self.client.cooling()["profile"], "quiet") # the last one known, for the buttons
self.hw.down = False
with self.assertLogs("kurgan.hw.client", level="INFO"):
self.client.poll()
self.assertIsNone(self.client.error)
self.assertEqual(self.hw.connects, 2) # the failed poll found the old connection broken
self.assertTrue(self.hw.transport._session.greeted)
def test_a_different_protocol_drops_the_connection_and_says_what_to_do(self):
class Old:
closed = False
def call(self, op, args=None, timeout=None):
raise RemoteError(VERSION, "the service speaks protocol 2, the client 1")
def close(self):
self.closed = True
old = Old()
client = HardwareClient(lambda: old)
with self.assertLogs("kurgan.hw.client", level="WARNING"):
client.poll()
self.assertIn("re-run setup.ps1", client.error)
self.assertTrue(old.closed)
def test_a_refusal_by_a_service_that_is_up_keeps_the_connection(self):
self.client.poll()
self.hw.service.settings = None # hw-settings.json turned out invalid
self.hw.service.settings_error = "cooling.profile must be one of ..."
with self.assertRaises(HardwareUnavailable) as raised:
self.client.set_profile("quiet")
self.assertIn("hw-settings.json is invalid", str(raised.exception))
self.client.poll()
self.assertIsNone(self.client.error)
self.assertEqual(self.hw.connects, 1)
def test_a_stuck_service_loop_counts_as_unavailable(self):
self.client.poll()
self.hw.service._snapshot["t"] = time.time() - 60 # the loop stopped publishing a minute ago
with self.assertLogs("kurgan.hw.client", level="WARNING"):
self.client.poll()
self.assertIn("stalled", self.client.error)
self.assertIsNone(self.client.state)
def test_an_old_state_is_no_state(self):
self.client.poll()
self.client._state_at -= hw_client.STALE_SECONDS + 1 # no poll got through since
self.assertEqual(self.client.error, "no state from the hardware service")
self.assertEqual(self.client.fan_rpms(), [])
def test_each_poll_sends_the_chase_clock(self):
self.client.chase = lambda: {"phase": 123.0, "rate": 9.0, "power": 400.0}
self.client.poll()
chase = self.hw.service.chase
self.assertEqual((chase.phase, chase.rate), (123.0, 9.0))
def test_the_app_side_readers_take_the_services_values(self):
self.client.poll()
state = self.client.state
self.assertEqual(CommanderReadings(self.client).read(), state["commander"]["rpms"])
cpu = CpuSensors(package=CpuPackage(self.client))
self.assertEqual(cpu.read().temp, state["cpu"]["temp"])
self.assertEqual(cpu.status, "ok")
def test_telemetry_lists_the_service_once_not_also_the_cpu_temperature(self):
self.hw.down = True
cpu = CpuSensors(package=CpuPackage(self.client))
fake = demo.FakeGpu()
telemetry = Telemetry(cpu, fake, SystemPower(fans=CommanderReadings(self.client)), hw=self.client)
with self.assertLogs("kurgan", level="WARNING"):
for _ in range(3):
self.client.poll()
sample = telemetry.read()
self.assertIsNone(sample.cpu.temp)
self.assertEqual(list(telemetry.health()), [SERVICE_SOURCE])
self.hw.down = False
with self.assertLogs("kurgan", level="INFO"):
self.client.poll()
telemetry.read()
self.assertEqual(telemetry.health(), {})
class PipeEndToEndTest(unittest.TestCase):
def test_the_client_over_a_real_pipe(self):
me = current_user_sid()
hw = Service(self)
name = rf"\\.\pipe\kurgan-hw-client-test-{os.getpid()}"
server = PipeServer(name, pipe_sddl(me, server_sid=me), lambda: Session(hw.service.dispatch, "test"))
server.start()
self.addCleanup(server.close)
client = HardwareClient(lambda: PipeTransport(name, trusted_owners=None))
deadline = time.monotonic() + 2
while True: # the listener may not have created the pipe yet
with self.assertLogs("kurgan.hw.client", level="INFO"):
client.poll()
if client.error is None or time.monotonic() > deadline:
break
self.assertIsNone(client.error)
client.set_profile("performance")
self.assertEqual(hw.saved()["cooling"]["profile"], "performance")
stop = threading.Event()
thread = threading.Thread(target=client.run, args=(stop,))
thread.start()
stop.set()
thread.join(5)
self.assertFalse(thread.is_alive())
if __name__ == "__main__":
unittest.main()
+49
View File
@@ -0,0 +1,49 @@
import contextlib
import io
import sys
import unittest
import win32security
import win32service
from kurgan.hw import install
from kurgan.hw import settings as hw_settings
class InstallTest(unittest.TestCase):
def test_the_image_path_runs_the_base_interpreter_isolated(self):
self.assertEqual(install.image_path(r"C:\Python 3\python.exe", r"C:\Dev\the_kurgan\hw_service.py"),
r'"C:\Python 3\python.exe" -I -S -B "C:\Dev\the_kurgan\hw_service.py"')
def test_recovery_restarts_after_5_10_and_60_seconds(self):
actions = install.failure_actions()
self.assertEqual(actions["Actions"], [(win32service.SC_ACTION_RESTART, 5000),
(win32service.SC_ACTION_RESTART, 10000),
(win32service.SC_ACTION_RESTART, 60000)])
def test_the_data_folder_is_owned_by_administrators_and_read_only_for_users(self):
sd = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
install.DATA_DIR_OWNER_SDDL + hw_settings.DATA_DIR_SDDL, win32security.SDDL_REVISION_1)
owner = win32security.ConvertSidToStringSid(sd.GetSecurityDescriptorOwner())
self.assertEqual(owner, "S-1-5-32-544")
dacl = sd.GetSecurityDescriptorDacl()
users = [dacl.GetAce(i) for i in range(dacl.GetAceCount())
if win32security.ConvertSidToStringSid(dacl.GetAce(i)[2]) == "S-1-5-32-545"]
self.assertEqual(len(users), 1)
self.assertFalse(users[0][1] & 0x2) # FILE_WRITE_DATA
def test_the_check_runs_the_service_entry_point(self):
self.assertTrue(install.check(sys._base_executable).startswith("ok: The Kurgan hardware"))
with self.assertRaises(RuntimeError):
install.check(sys.executable + "-missing")
def test_bad_arguments_are_refused_before_anything_changes(self):
for argv in (["--python", sys._base_executable, "--user-sid", "nobody", "--user-settings", "x.json"],
["--python", r"C:\nowhere\python.exe", "--user-sid", "S-1-5-21-1-2-3-1001",
"--user-settings", "x.json"]):
with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
install.main(argv)
if __name__ == "__main__":
unittest.main()
+86
View File
@@ -0,0 +1,86 @@
import json
import os
import tempfile
import unittest
from kurgan.hw import migrate
from kurgan.settings import SettingsError
OLD_USER = {
"cooling": {"profile": "quiet", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]},
"lighting": {"case_fans": "chase", "memory": "temperature", "gpu": "off"},
"ai": {"active": "strata"},
"web": {"port": 8080},
}
class MigrateTest(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.dir = directory.name
self.user = os.path.join(self.dir, "settings.json")
self.hw = os.path.join(self.dir, "ProgramData", "hw-settings.json")
def write(self, path, data):
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
f.write(data if isinstance(data, str) else json.dumps(data))
def read(self, path):
with open(path, encoding="utf-8") as f:
return json.load(f)
def test_the_fan_and_ram_settings_move_and_the_rest_stays(self):
self.write(self.user, OLD_USER)
self.assertIn("with cooling and lighting.memory", migrate.copy(self.user, self.hw))
self.assertEqual(self.read(self.hw), {"cooling": OLD_USER["cooling"], "lighting": {"memory": "temperature"}})
message = migrate.strip(self.user, self.hw, now=0)
self.assertIn("backup", message)
user = self.read(self.user)
self.assertNotIn("cooling", user)
self.assertEqual(user["lighting"], {"case_fans": "chase", "gpu": "off"})
self.assertEqual(user["ai"]["active"], "strata")
backups = [name for name in os.listdir(self.dir) if name.endswith(".bak")]
self.assertEqual(len(backups), 1)
self.assertEqual(self.read(os.path.join(self.dir, backups[0])), OLD_USER)
def test_running_it_again_changes_nothing(self):
self.write(self.user, OLD_USER)
migrate.copy(self.user, self.hw)
migrate.strip(self.user, self.hw)
hw, user = self.read(self.hw), self.read(self.user)
self.write(self.user, {**user, "cooling": {"profile": "full"}}) # stale, e.g. from an old backup
self.assertIn("already exists", migrate.copy(self.user, self.hw))
self.assertEqual(self.read(self.hw), hw) # never overwritten
migrate.strip(self.user, self.hw) # the stale section goes too
self.assertEqual(self.read(self.user), user)
self.assertIn("Nothing to move", migrate.strip(self.user, self.hw))
def test_no_user_settings_gives_the_defaults(self):
self.assertIn("with the defaults", migrate.copy(self.user, self.hw))
self.assertEqual(self.read(self.hw), {"cooling": {"profile": "balanced"}, "lighting": {"memory": "off"}})
self.assertIn("Nothing to move", migrate.strip(self.user, self.hw))
def test_settings_json_is_left_alone_until_hw_settings_exists(self):
self.write(self.user, OLD_USER)
self.assertIn("doesn't exist yet", migrate.strip(self.user, self.hw))
self.assertEqual(self.read(self.user), OLD_USER)
def test_an_invalid_file_stops_the_move(self):
for bad in ("{not json", {"cooling": {"profile": "turbo"}}, {"extra": {}}):
with self.subTest(bad=bad):
self.write(self.user, bad)
with self.assertRaises(SettingsError):
migrate.copy(self.user, self.hw)
self.assertFalse(os.path.exists(self.hw))
self.write(self.hw, {"cooling": {"profile": "balanced"}})
self.write(self.user, {"cooling": {"profile": "quiet"}, "web": {"port": 80}})
with self.assertRaises(SettingsError):
migrate.strip(self.user, self.hw)
self.assertEqual(self.read(self.user)["web"]["port"], 80) # untouched
self.assertFalse([name for name in os.listdir(self.dir) if name.endswith(".bak")])
if __name__ == "__main__":
unittest.main()
+177
View File
@@ -0,0 +1,177 @@
import ctypes
import json
import os
import threading
import time
import unittest
import uuid
from kurgan.ai.launcher import token_info
from kurgan.hw import pipe
from kurgan.hw.protocol import MAX_MESSAGE, PROTOCOL_VERSION, Session, decode_reply, encode_request
from kurgan.hw.pipe import PipeClient, PipeError, PipeServer, current_user_sid, pipe_sddl
ME = current_user_sid()
ELEVATED = token_info()["elevated"]
def pipe_name() -> str:
return rf"\\.\pipe\kurgan-hw-test-{os.getpid()}-{uuid.uuid4().hex[:8]}"
class Calls:
def __init__(self):
self.ops = []
self.threads = set()
self.lock = threading.Lock()
def dispatch(self, op, args):
with self.lock:
self.ops.append(op)
self.threads.add(threading.get_ident())
return {"op": op}
def session(self):
return Session(self.dispatch, "test")
def ask(client, op, args=None, request_id=1, timeout=2.0):
return decode_reply(client.request(encode_request(op, args, request_id), timeout), request_id)
def greet(client):
return ask(client, "hello", {"protocol": PROTOCOL_VERSION, "client": "test"}, 0)
class PipeTest(unittest.TestCase):
def serve(self, sddl=None, **options):
name = pipe_name()
calls = Calls()
server = PipeServer(name, sddl or pipe_sddl(ME, server_sid=ME), calls.session, **options)
server.start()
self.addCleanup(server.close)
return name, server, calls
def connect(self, name, **options):
options.setdefault("trusted_owners", None)
deadline = time.monotonic() + 2
while True: # the listener thread may not have created the pipe yet
try:
client = PipeClient(name, **options)
break
except PipeError as e:
if e.code != pipe.ERROR_FILE_NOT_FOUND or time.monotonic() > deadline:
raise
time.sleep(0.02)
self.addCleanup(client.close)
return client
def test_round_trip(self):
name, server, calls = self.serve()
client = self.connect(name)
self.assertEqual(greet(client), {"protocol": PROTOCOL_VERSION, "service": "test"})
self.assertEqual(ask(client, "state", request_id=2)["op"], "state")
self.assertEqual(ask(client, "set_profile", {"profile": "quiet"}, request_id=3)["op"], "set_profile")
self.assertEqual(calls.ops, ["state", "set_profile"])
def test_several_clients_at_once_each_on_its_own_thread(self):
name, server, calls = self.serve()
clients = [self.connect(name) for _ in range(3)]
for client in clients:
greet(client)
for i, client in enumerate(clients * 2): # interleaved: each gets its own replies
self.assertEqual(ask(client, "state", request_id=i)["op"], "state")
self.assertEqual(server.clients, 3)
self.assertEqual(len(calls.threads), 3)
def test_a_silent_client_is_dropped_without_affecting_the_others(self):
name, server, calls = self.serve(read_timeout=0.3)
silent = self.connect(name)
busy = self.connect(name)
greet(busy)
for i in range(5): # keeps talking, so keeps its connection
time.sleep(0.1)
ask(busy, "state", request_id=i)
with self.assertRaises(PipeError):
ask(silent, "state")
ask(busy, "state", request_id=99)
def test_a_line_left_unfinished_is_dropped_at_the_timeout(self):
name, server, calls = self.serve(read_timeout=0.4)
client = self.connect(name)
greet(client)
handle_event = pipe._event()
try:
for _ in range(6): # trickles a byte every 0.1 s but never ends the line
pipe._write(client._handle, handle_event, b" ", 1.0)
time.sleep(0.1)
except PipeError:
pass # already dropped
finally:
pipe._k32.CloseHandle(handle_event)
with self.assertRaises(PipeError):
ask(client, "state")
def test_an_oversized_line_gets_an_error_then_the_connection_closes(self):
name, server, calls = self.serve()
client = self.connect(name)
greet(client)
reply = json.loads(client.request(b"x" * (MAX_MESSAGE + 10) + b"\n", 2.0))
self.assertEqual((reply["ok"], reply["error"]["code"]), (False, "too_large"))
with self.assertRaises(PipeError):
ask(client, "state")
self.assertEqual(calls.ops, [])
def test_closing_the_server_ends_connections_promptly(self):
name, server, calls = self.serve()
client = self.connect(name)
greet(client)
started = time.monotonic()
server.close()
self.assertLess(time.monotonic() - started, 2)
with self.assertRaises(PipeError):
ask(client, "state")
def test_a_pipe_not_owned_by_system_or_administrators_is_refused(self):
name, server, calls = self.serve()
with self.assertRaisesRegex(PipeError, "not the hardware service"):
self.connect(name, trusted_owners=pipe.TRUSTED_OWNERS)
self.connect(name, trusted_owners=(ME,))
def test_no_service_means_a_clear_error(self):
with self.assertRaisesRegex(PipeError, "isn't running") as caught:
PipeClient(pipe_name(), timeout=0.1, trusted_owners=None)
self.assertEqual(caught.exception.code, pipe.ERROR_FILE_NOT_FOUND)
@unittest.skipIf(ELEVATED, "an elevated test process is an Administrator, which the pipe allows")
def test_a_user_not_on_the_access_list_is_refused(self):
other = "S-1-5-21-1000000001-1000000002-1000000003-1001"
name, server, calls = self.serve(sddl=pipe_sddl(other))
time.sleep(0.2)
with self.assertRaises(PipeError) as caught:
PipeClient(name, timeout=0.5, trusted_owners=None)
self.assertEqual(caught.exception.code, pipe.ERROR_ACCESS_DENIED)
@unittest.skipIf(ELEVATED, "an elevated test process is an Administrator, which may add instances")
def test_the_user_may_not_add_an_instance_of_the_pipe(self):
name, server, calls = self.serve(sddl=pipe_sddl(ME))
self.connect(name) # the user can connect ...
handle = pipe._k32.CreateNamedPipeW(name, pipe.PIPE_ACCESS_DUPLEX, 0, 8, 4096, 4096, 0, None)
error = ctypes.get_last_error()
if handle != pipe.INVALID_HANDLE:
pipe._k32.CloseHandle(handle)
self.assertEqual((handle, error), (pipe.INVALID_HANDLE, pipe.ERROR_ACCESS_DENIED)) # ... not serve it
def test_access_list(self):
self.assertEqual(pipe_sddl("S-1-5-21-1-2-3-1001"),
"D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12018b;;;S-1-5-21-1-2-3-1001)")
self.assertEqual(pipe_sddl(None), "D:P(A;;GA;;;SY)(A;;GA;;;BA)")
for bad in ("BU", "WD", "S-1-5-21-1-2-3-1001)(A;;GA;;;WD", ""):
with self.subTest(bad=bad):
with self.assertRaises(ValueError):
pipe_sddl(bad)
self.assertEqual(pipe.USER_ACCESS & 0x4, 0) # FILE_CREATE_PIPE_INSTANCE
if __name__ == "__main__":
unittest.main()
+189
View File
@@ -0,0 +1,189 @@
import json
import unittest
from kurgan.hw import protocol
from kurgan.hw.protocol import (
BAD_REQUEST, HELLO_FIRST, INTERNAL, INVALID, MAX_MESSAGE, PROTOCOL_VERSION, TOO_LARGE, UNAVAILABLE,
UNKNOWN_OP, VERSION, LineBuffer, ProtocolError, RemoteError, Session, Unavailable,
decode_reply, decode_request, encode_request,
)
def line(obj) -> bytes:
return json.dumps(obj).encode()
class DecodeRequestTest(unittest.TestCase):
def assertRejected(self, raw: bytes, code: str):
with self.assertRaises(ProtocolError) as caught:
decode_request(raw)
self.assertEqual(caught.exception.code, code, str(caught.exception))
return caught.exception
def test_well_formed_requests(self):
request = decode_request(line({"op": "set_profile", "args": {"profile": "quiet"}, "id": 3}))
self.assertEqual((request.op, request.args, request.id), ("set_profile", {"profile": "quiet"}, 3))
self.assertEqual(decode_request(line({"op": "state", "id": "a"})).args, {}) # args may be left out
chase = decode_request(line({"op": "ram_chase", "id": 1, "args": {"phase": 6, "rate": 6.7, "power": None}}))
self.assertEqual(chase.args, {"phase": 6.0, "rate": 6.7, "power": None})
def test_malformed_input_is_rejected(self):
for raw in (b"", b"not json", b"[1, 2]", b'"state"', b"\xff\xfe{}", b'{"op": "state"',
b'{"op": "state", "id": 1, "id": 2}', # duplicate key
b'{"op": "ram_chase", "id": 1, "args": {"phase": NaN, "rate": 1, "power": null}}',
b'{"op": "ram_chase", "id": 1, "args": {"phase": Infinity, "rate": 1, "power": null}}',
b"[" * 30_000 + b"]" * 30_000, # deep nesting
line({"op": "state"}), # no id
line({"op": "state", "id": True}), # bool is not an id
line({"op": "state", "id": 1.5}),
line({"op": "state", "id": "x" * 65}),
line({"op": 7, "id": 1}),
line({"id": 1})):
with self.subTest(raw=raw[:60]):
self.assertRejected(raw, BAD_REQUEST)
def test_errors_echo_the_id_when_it_was_readable(self):
self.assertEqual(self.assertRejected(line({"op": "reboot", "id": 9}), UNKNOWN_OP).request_id, 9)
self.assertIsNone(self.assertRejected(line({"op": "state", "id": [1]}), BAD_REQUEST).request_id)
def test_unknown_ops_and_fields_are_rejected(self):
self.assertRejected(line({"op": "reboot", "id": 1}), UNKNOWN_OP)
self.assertRejected(line({"op": "__class__", "id": 1}), UNKNOWN_OP)
self.assertRejected(line({"op": "state", "id": 1, "extra": 1}), BAD_REQUEST)
self.assertRejected(line({"op": "state", "id": 1, "args": {"verbose": True}}), INVALID)
self.assertRejected(line({"op": "set_profile", "id": 1, "args": {"profile": "quiet", "x": 1}}), INVALID)
def test_arguments_are_checked_like_the_api_checks_them(self):
for args in ({}, {"profile": "turbo"}, {"profile": 1}, {"profile": ["quiet"]}):
with self.subTest(args=args):
self.assertRejected(line({"op": "set_profile", "id": 1, "args": args}), INVALID)
for mode in ("rainbow", "", None, True):
with self.subTest(mode=mode):
self.assertRejected(line({"op": "set_ram_lighting", "id": 1, "args": {"mode": mode}}), INVALID)
for args in ({"phase": 1, "rate": -1, "power": None}, {"phase": "1", "rate": 1, "power": None},
{"phase": 1, "rate": True, "power": None}, {"phase": 1, "rate": 1},
{"phase": 1, "rate": 1, "power": 1e9}):
with self.subTest(args=args):
self.assertRejected(line({"op": "ram_chase", "id": 1, "args": args}), INVALID)
self.assertRejected(line({"op": "state", "id": 1, "args": []}), INVALID)
self.assertRejected(line({"op": "hello", "id": 1, "args": {"protocol": "1"}}), INVALID)
self.assertRejected(line({"op": "hello", "id": 1, "args": {"protocol": 1, "client": "x" * 65}}), INVALID)
def test_oversized_messages_are_rejected(self):
padding = "x" * MAX_MESSAGE
self.assertRejected(line({"op": "state", "id": padding}), TOO_LARGE)
with self.assertRaises(ValueError):
protocol.encode({"padding": padding})
def test_client_side_encoding_uses_the_same_checks(self):
self.assertEqual(json.loads(encode_request("set_profile", {"profile": "full"}, 2)),
{"op": "set_profile", "args": {"profile": "full"}, "id": 2})
for op, args in (("set_profile", {"profile": "turbo"}), ("reboot", {}), ("state", {"x": 1})):
with self.subTest(op=op):
with self.assertRaises(ValueError):
encode_request(op, args, 1)
class DecodeReplyTest(unittest.TestCase):
def test_results_errors_and_mismatches(self):
self.assertEqual(decode_reply(line({"id": 4, "ok": True, "result": {"a": 1}}), 4), {"a": 1})
with self.assertRaises(RemoteError) as caught:
decode_reply(line({"id": 4, "ok": False, "error": {"code": INVALID, "message": "bad"}}), 4)
self.assertEqual((caught.exception.code, str(caught.exception)), (INVALID, "bad"))
for reply in ({"id": 5, "ok": True, "result": 1}, # someone else's reply
{"id": 4, "ok": 1, "result": 1},
{"id": 4, "ok": True},
{"id": 4, "ok": True, "result": 1, "extra": 2},
{"id": 4, "ok": False, "error": "bad"},
{"id": 4, "ok": False, "error": {"code": "x"}},
[4, True]):
with self.subTest(reply=reply):
with self.assertRaises(ProtocolError):
decode_reply(line(reply), 4)
class LineBufferTest(unittest.TestCase):
def test_lines_split_across_reads_and_crlf(self):
buffer = LineBuffer()
self.assertEqual(buffer.feed(b'{"a"'), [])
self.assertTrue(buffer.partial)
self.assertEqual(buffer.feed(b':1}\r\n{"b":2}\n{"c"'), [b'{"a":1}', b'{"b":2}'])
self.assertEqual(buffer.feed(b":3}\n"), [b'{"c":3}'])
self.assertFalse(buffer.partial)
def test_a_line_over_the_limit_is_refused_before_it_ends(self):
buffer = LineBuffer(limit=10)
self.assertEqual(buffer.feed(b"x" * 10 + b"\n"), [b"x" * 10])
with self.assertRaises(ProtocolError) as caught:
buffer.feed(b"y" * 11) # no newline yet: refused without waiting for the rest
self.assertEqual(caught.exception.code, TOO_LARGE)
with self.assertRaises(ProtocolError):
LineBuffer(limit=10).feed(b"z" * 11 + b"\n")
class SessionTest(unittest.TestCase):
def setUp(self):
self.calls = []
def dispatch(op, args):
self.calls.append((op, args))
if args.get("profile") == "quiet":
raise ValueError("can't today")
if args.get("profile") == "full":
raise Unavailable("settings are invalid")
if args.get("profile") == "performance":
raise RuntimeError("bug")
if op == "state":
return {"temp": float("nan")}
return {"done": op}
self.session = Session(dispatch, "9.9.9")
def send(self, obj):
reply, close = self.session.handle(line(obj) if not isinstance(obj, bytes) else obj)
return json.loads(reply), close
def hello(self, version=PROTOCOL_VERSION):
return self.send({"op": "hello", "id": 0, "args": {"protocol": version, "client": "test"}})
def test_hello_first_then_operations(self):
reply, close = self.send({"op": "set_profile", "id": 1, "args": {"profile": "balanced"}})
self.assertEqual((reply["error"]["code"], close), (HELLO_FIRST, False))
self.assertEqual(self.calls, [])
reply, close = self.hello()
self.assertEqual((reply["result"], close), ({"protocol": PROTOCOL_VERSION, "service": "9.9.9"}, False))
reply, _ = self.send({"op": "set_profile", "id": 2, "args": {"profile": "balanced"}})
self.assertEqual(reply, {"id": 2, "ok": True, "result": {"done": "set_profile"}})
def test_version_mismatch_is_answered_then_the_connection_closes(self):
reply, close = self.hello(PROTOCOL_VERSION + 1)
self.assertEqual((reply["error"]["code"], close), (VERSION, True))
self.assertIn(str(PROTOCOL_VERSION), reply["error"]["message"])
self.assertFalse(self.session.greeted)
def test_operation_failures_map_to_error_codes(self):
self.hello()
for profile, code in (("quiet", INVALID), ("full", UNAVAILABLE), ("performance", INTERNAL)):
with self.subTest(profile=profile):
if code == INTERNAL:
with self.assertLogs("kurgan.hw.protocol", level="ERROR"):
reply, close = self.send({"op": "set_profile", "id": 3, "args": {"profile": profile}})
else:
reply, close = self.send({"op": "set_profile", "id": 3, "args": {"profile": profile}})
self.assertEqual((reply["id"], reply["error"]["code"], close), (3, code, False))
def test_a_reply_that_cannot_be_encoded_is_an_internal_error(self):
self.hello()
with self.assertLogs("kurgan.hw.protocol", level="ERROR"):
reply, close = self.send({"op": "state", "id": 4})
self.assertEqual((reply["error"]["code"], close), (INTERNAL, False))
def test_bad_lines_keep_the_connection_but_oversized_ones_close_it(self):
reply, close = self.send(b"garbage")
self.assertEqual((reply["error"]["code"], close), (BAD_REQUEST, False))
reply, close = self.send(b"x" * (MAX_MESSAGE + 1))
self.assertEqual((reply["error"]["code"], close), (TOO_LARGE, True))
if __name__ == "__main__":
unittest.main()
+244
View File
@@ -0,0 +1,244 @@
import json
import os
import tempfile
import threading
import time
import unittest
import uuid
from unittest.mock import Mock, patch
from kurgan import demo
from kurgan.hw import settings as hw_settings
from kurgan.hw.main import serve
from kurgan.hw.pipe import PipeClient, PipeError, current_user_sid
from kurgan.hw.protocol import PROTOCOL_VERSION, Unavailable, decode_reply, encode_request
from kurgan.hw.service import HardwareService, SyncedChase
from kurgan.settings import SettingsError
def write(path, data):
with open(path, "w", encoding="utf-8") as f:
json.dump(data, f)
class Fakes:
"""The demo's simulated hardware, with a few knobs for failures."""
def __init__(self):
self.commander = demo.FakeCommander()
self.board = demo.FakeBoard()
self.gpu = demo.FakeGpu()
self.cpu = demo.FakeCpuTemperature()
self.memory = demo.FakeLights("RAM")
def service(self, settings, error=None):
return HardwareService(settings, error, commander=self.commander, board_factory=lambda: self.board,
gpu_factory=lambda: self.gpu, cpu=self.cpu, memory=self.memory)
class ServiceTest(unittest.TestCase):
def setUp(self):
self.dir = tempfile.mkdtemp()
self.path = os.path.join(self.dir, "hw-settings.json")
write(self.path, {"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3],
"top_channels": [2, 5]},
"lighting": {"memory": "chase"}})
self.fakes = Fakes()
self.service = self.fakes.service(hw_settings.load(self.path))
def saved(self):
with open(self.path, encoding="utf-8") as f:
return json.load(f)
def test_the_loop_controls_the_fans_with_no_client(self):
stop = threading.Event()
original = self.service.tick
self.service.tick = lambda now: (original(now), 0.01)[1] # passes 10 ms apart, not 1 s
thread = threading.Thread(target=self.service.run, args=(stop,))
thread.start()
time.sleep(0.3)
stop.set()
thread.join(5)
self.assertFalse(thread.is_alive())
state = self.service.snapshot()
self.assertGreater(state["seq"], 1)
self.assertEqual([g["name"] for g in state["cooling"]["groups"]], ["GPU", "CPU"])
self.assertIsNotNone(state["cpu"]["temp"])
self.assertIsNotNone(state["cpu"]["power"])
self.assertIsNotNone(state["gpu"]["temp"])
self.assertEqual(len(state["commander"]["rpms"]), 6) # the power model's case fan speeds
self.assertEqual(state["lighting"]["memory"]["mode"], "chase")
# The loop's exit: case fans at 100%, top fans back on the BIOS curve.
self.assertEqual(set(self.fakes.commander.duty.values()), {100})
self.assertEqual(self.fakes.board.mask, 0)
def test_the_snapshot_has_the_fields_the_app_shows(self):
self.service.tick(0)
state = self.service.snapshot()
self.assertEqual(set(state["cooling"]), {"profile", "groups", "top", "note", "row"})
self.assertEqual(state["cooling"]["row"][1:], [100, 100, 100]) # startup: everything at 100%
self.assertEqual(state["service"]["protocol"], PROTOCOL_VERSION)
json.dumps(state, allow_nan=False)
def test_sensor_faults_fail_safe_and_the_loop_carries_on(self):
self.fakes.gpu.read = Mock(side_effect=RuntimeError("NVML exploded"))
for now in range(40): # settle at the curve, then lose the GPU
self.fakes.gpu.read.side_effect = None if now < 35 else RuntimeError("NVML exploded")
self.fakes.gpu.read.return_value = demo.Readings(temp=40.0)
if now == 35:
with self.assertLogs("kurgan", level="WARNING") as logs:
self.service.tick(now)
self.assertTrue(any("NVML exploded" in line for line in logs.output))
self.assertTrue(any("GPU case fans: FAILSAFE" in line for line in logs.output))
else:
self.service.tick(now)
state = self.service.snapshot()
self.assertIn("NVML exploded", state["gpu"]["error"])
gpu = state["cooling"]["groups"][0]
self.assertEqual((gpu["duty"], gpu["failsafe"]), (100, True))
def test_a_loop_bug_fails_safe_and_is_retried(self):
self.service.memory.set_temperature = Mock(side_effect=RuntimeError("bug"))
with self.assertLogs("kurgan.hw.service", level="ERROR"):
self.assertEqual(self.service.tick(0), 5.0)
self.assertEqual(self.fakes.commander.duty[4], 100)
def test_nan_readings_never_reach_the_pipe(self):
self.fakes.cpu.read = lambda now: setattr(self.fakes.cpu, "temp", float("nan"))
with self.assertLogs("kurgan.cooling.control", level="WARNING"): # the CPU side fails safe
self.service.tick(0)
self.assertIsNone(self.service.snapshot()["cpu"]["temp"])
def test_set_profile_saves_and_applies(self):
state = self.service.dispatch("set_profile", {"profile": "full"})
self.assertEqual(state["cooling"]["profile"], "full")
self.assertEqual(self.service.fans.profile.key, "full")
self.assertEqual(self.saved()["cooling"]["profile"], "full")
self.assertEqual(hw_settings.load(self.path).get("cooling", "profile"), "full") # survives a restart
def test_set_ram_lighting_saves_and_switches_the_pattern(self):
events = self.service._memory_events
self.assertTrue(events["chase"].is_set())
self.service.dispatch("set_ram_lighting", {"mode": "temperature"})
self.assertEqual((events["temperature"].is_set(), events["chase"].is_set()), (True, False))
self.assertEqual(self.saved()["lighting"], {"memory": "temperature"})
self.service.dispatch("set_ram_lighting", {"mode": "off"})
self.assertFalse(any(e.is_set() for e in events.values()))
def test_a_failed_save_changes_nothing(self):
with patch("kurgan.settings.write_json_atomic", side_effect=OSError("disk full")):
with self.assertRaisesRegex(Unavailable, "disk full"):
self.service.dispatch("set_profile", {"profile": "quiet"})
self.assertEqual(self.service.fans.profile.key, "balanced")
self.assertEqual(self.saved()["cooling"]["profile"], "balanced")
def test_ram_chase_follows_the_app_clock(self):
with patch("kurgan.hw.service.time.monotonic", return_value=100.0):
self.assertIsNone(self.service.dispatch("ram_chase", {"phase": 42.0, "rate": 10.0, "power": 300.0}))
self.assertEqual(self.service.chase.sample(100.5), (47.0, 10.0))
def test_fan_control_not_set_up_only_reads_the_rpms(self):
write(self.path, {"cooling": {"profile": "quiet"}})
service = self.fakes.service(hw_settings.load(self.path))
service.tick(0)
state = service.snapshot()
self.assertIsNone(service.fans)
self.assertIn("isn't set up", state["cooling"]["note"])
self.assertEqual(state["cooling"]["profile"], "quiet")
self.assertEqual(len(state["commander"]["rpms"]), 6)
self.assertEqual(set(self.fakes.commander.duty.values()), {100}) # untouched since power-on
def test_invalid_settings_hold_every_fan_at_full_speed(self):
write(self.path, {"cooling": {"profile": "turbo"}})
with self.assertRaises(SettingsError):
hw_settings.load(self.path)
self.fakes.commander.duty = {p: 30 for p in range(1, 7)}
service = self.fakes.service(None, "cooling.profile must be one of ...")
service.tick(0)
self.assertEqual(set(self.fakes.commander.duty.values()), {100})
state = service.snapshot()
self.assertIn("held at 100%", state["cooling"]["note"])
self.assertEqual(state["service"]["settings_error"], "cooling.profile must be one of ...")
for op, args in (("set_profile", {"profile": "quiet"}), ("set_ram_lighting", {"mode": "off"})):
with self.assertRaises(Unavailable):
service.dispatch(op, args)
class SettingsFileTest(unittest.TestCase):
def test_created_with_defaults_and_strict(self):
path = os.path.join(tempfile.mkdtemp(), "hw-settings.json")
settings = hw_settings.load(path)
self.assertEqual(settings.section("cooling"), {"profile": "balanced"})
self.assertTrue(os.path.exists(path))
for bad in ({"ai": {}}, {"cooling": {"profile": "balanced", "speed": 3}},
{"lighting": {"memory": "rainbow"}}, {"lighting": {"case_fans": "off"}},
{"cooling": {"cpu_ports": [1, 2, 3]}}, {"cooling": {"gpu_ports": [4, 5, 5]}}, []):
with self.subTest(bad=bad):
with self.assertRaises(SettingsError):
hw_settings.validate(bad)
class SyncedChaseTest(unittest.TestCase):
def test_runs_on_at_the_last_rate_between_syncs(self):
chase = SyncedChase()
self.assertEqual(chase.sample(10.0), (6.0, SyncedChase.IDLE_RATE)) # idle pace until the app speaks
chase.sync(100.0, 20.0, 11.0)
self.assertEqual(chase.sample(11.25), (105.0, 20.0))
self.assertEqual(chase.sample(11.0), (105.0, 20.0)) # never backwards
class ServeTest(unittest.TestCase):
"""The service's parts together, with a real pipe and the demo's hardware."""
def test_a_stuck_client_cannot_stop_fan_control(self):
directory = tempfile.mkdtemp()
path = os.path.join(directory, "hw-settings.json")
write(path, {"cooling": {"profile": "balanced", "gpu_ports": [4, 5, 6]}})
fakes = Fakes()
service = fakes.service(hw_settings.load(path))
ticks = []
original = service.tick
service.tick = lambda now: (ticks.append(now), original(now))[1] and 0.05
stuck = threading.Event()
save = service.settings.update
def slow_update(*args, **kwargs):
stuck.wait(5) # a save that hangs, e.g. a wedged disk
return save(*args, **kwargs)
service.settings.update = slow_update
name = rf"\\.\pipe\kurgan-hw-test-{os.getpid()}-{uuid.uuid4().hex[:8]}"
stop = threading.Event()
me = current_user_sid()
with patch("kurgan.hw.pipe.pipe_sddl", return_value=f"D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;GA;;;{me})"):
server = threading.Thread(target=serve, args=(stop, me), kwargs={"service": service, "pipe_name": name})
server.start()
try:
client = None
deadline = time.monotonic() + 3
while client is None:
try:
client = PipeClient(name, trusted_owners=None)
except PipeError:
if time.monotonic() > deadline:
raise
time.sleep(0.05)
hello = encode_request("hello", {"protocol": PROTOCOL_VERSION}, 0)
self.assertEqual(decode_reply(client.request(hello, 2), 0)["protocol"], PROTOCOL_VERSION)
blocked = encode_request("set_profile", {"profile": "full"}, 1)
with self.assertRaises(PipeError):
client.request(blocked, 0.3) # its reply is stuck behind the hung save ...
before = len(ticks)
time.sleep(0.4)
self.assertGreater(len(ticks) - before, 3) # ... while the fan loop keeps running
stuck.set()
client.close()
finally:
stop.set()
server.join(10)
self.assertFalse(server.is_alive())
self.assertEqual(set(fakes.commander.duty[p] for p in (4, 5, 6)), {100}) # stopped: fail-safe
if __name__ == "__main__":
unittest.main()
+67
View File
@@ -0,0 +1,67 @@
import subprocess
import sys
import threading
import unittest
from unittest.mock import Mock, patch
import win32service
from kurgan import paths
from kurgan.hw import winservice
from kurgan.hw.winservice import KurganHwService
def bare_service() -> KurganHwService:
"""The service object without registering with a service manager we aren't running under."""
service = KurganHwService.__new__(KurganHwService)
service.stop = threading.Event()
service.ReportServiceStatus = Mock()
return service
class WinServiceTest(unittest.TestCase):
def test_accepts_stop_and_shutdown_and_both_end_the_loop(self):
accepted = bare_service().GetAcceptedControls()
self.assertTrue(accepted & win32service.SERVICE_ACCEPT_STOP)
self.assertTrue(accepted & win32service.SERVICE_ACCEPT_SHUTDOWN)
for control in ("SvcStop", "SvcShutdown"):
with self.subTest(control=control):
service = bare_service()
getattr(service, control)()
self.assertTrue(service.stop.is_set())
self.assertEqual(service.ReportServiceStatus.call_args.args[0], win32service.SERVICE_STOP_PENDING)
def test_runs_until_stopped(self):
service = bare_service()
with patch("kurgan.hw.main.setup_logging"), patch("kurgan.hw.main.single_instance", return_value=1), \
patch("kurgan.hw.main.configured_user_sid", return_value="S-1-5-21-1-2-3-1001"), \
patch("kurgan.hw.main.serve") as serve, patch("kurgan.hw.winservice.fail") as fail:
service.SvcDoRun()
serve.assert_called_once_with(service.stop, "S-1-5-21-1-2-3-1001")
fail.assert_not_called()
def test_an_unexpected_failure_exits_so_the_service_manager_restarts_it(self):
service = bare_service()
with patch("kurgan.hw.main.setup_logging"), patch("kurgan.hw.main.single_instance", return_value=None), \
patch("kurgan.hw.main.serve") as serve, patch("kurgan.hw.winservice.fail") as fail:
service.SvcDoRun() # a console copy already holds the mutex
serve.assert_not_called()
fail.assert_called_once()
def test_started_from_a_console_it_runs_there(self):
with patch("kurgan.hw.main.main", return_value=7) as console:
self.assertEqual(winservice.main([]), 7) # the service manager refused us: not a service
console.assert_called_once_with([])
with patch("kurgan.hw.main.main", return_value=0) as console:
winservice.main(["-v"])
console.assert_called_once_with(["-v"])
def test_the_bootstrap_loads_under_the_base_interpreter_in_isolated_mode(self):
result = subprocess.run([sys._base_executable, "-I", "-S", "-B", f"{paths.PROJECT_DIR}\\hw_service.py",
"--check"], capture_output=True, text=True, timeout=60)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertTrue(result.stdout.startswith("ok: The Kurgan hardware"), result.stdout)
if __name__ == "__main__":
unittest.main()
+48 -7
View File
@@ -18,6 +18,19 @@ class FakeWorker:
pass
class FakeRam:
"""The RAM zone in the hardware service (kurgan.hw.client.RamLighting)."""
def __init__(self):
self.mode, self.status, self.error = "off", "off", None
def set_mode(self, mode):
if self.error is not None:
raise self.error
self.mode = mode
self.status = f"{mode} (service)"
class LightingServiceTest(unittest.TestCase):
def setUp(self):
self.dir = tempfile.TemporaryDirectory()
@@ -25,22 +38,50 @@ class LightingServiceTest(unittest.TestCase):
self.settings = Settings(os.path.join(self.dir.name, "settings.json"), None)
def service(self, overrides=None):
self.ram = FakeRam()
return LightingService(self.settings, Theme(), (0.15, 0.025, 150.0, 550.0), overrides,
rgb=FakeWorker(), memory=FakeWorker(), gpu=FakeWorker())
ram=self.ram, rgb=FakeWorker(), gpu=FakeWorker())
def active(self, service, zone):
return sorted(mode for mode, event in service._events[zone].items() if event.is_set())
def test_saved_modes_start_and_switch_exclusively(self):
self.settings.update("lighting", memory="temperature")
self.settings.update("lighting", case_fans="temperature")
service = self.service()
self.assertEqual(self.active(service, "memory"), ["temperature"])
service.set_mode("memory", "chase")
self.assertEqual(self.active(service, "memory"), ["chase"])
self.assertEqual(self.active(service, "case_fans"), ["temperature"])
service.set_mode("case_fans", "chase")
self.assertEqual(self.active(service, "case_fans"), ["chase"])
self.assertEqual(self.active(service, "gpu"), [])
service.set_mode("case_fans", "off")
self.assertEqual(self.active(service, "case_fans"), [])
self.assertEqual(Settings(self.settings.path, None).get("lighting", "case_fans"), "off")
def test_the_ram_is_the_hardware_services_and_not_saved_here(self):
self.settings.update("lighting", memory="temperature") # an old settings.json: ignored
service = self.service()
self.assertNotIn("memory", service._events)
self.assertEqual(service.mode("memory"), "off")
service.set_mode("memory", "chase")
self.assertEqual(self.ram.mode, "chase")
zone = service.snapshot()["zones"][1]
self.assertEqual((zone["key"], zone["mode"], zone["status"]), ("memory", "chase", "chase (service)"))
self.assertEqual(self.settings.get("lighting", "memory"), "temperature") # left alone
self.assertEqual(service.snapshot()["chase_ms_per_led"], 150) # a RAM chase counts
self.ram.error = OSError("the hardware service isn't running (no pipe)")
with self.assertRaises(OSError):
service.set_mode("memory", "off")
self.assertEqual(self.active(service, "memory"), [])
self.assertEqual(Settings(self.settings.path, None).get("lighting", "memory"), "off")
self.assertEqual(service.mode("memory"), "chase")
def test_the_chase_clock_is_what_the_hardware_service_takes(self):
from kurgan.hw.protocol import check_args
service = self.service()
service.on_telemetry(50, 50, 350.0)
clock = service.chase_clock()
self.assertEqual(check_args("ram_chase", clock), clock)
self.assertEqual(clock["power"], 350.0)
later = service.chase_clock()
self.assertGreaterEqual(later["phase"], clock["phase"])
def test_failed_save_leaves_the_lights_as_they_were(self):
service = self.service()
+1
View File
@@ -34,6 +34,7 @@ class ProfileSwitchTest(unittest.TestCase):
self.commander.set_duty.side_effect = lambda ports, duty: {p: 1200 for p in ports}
board = Mock(spec=Nct6687)
board.manual_mask.return_value = 0x24
board.rpms.return_value = [0] * 16 # no tach has been seen turning: stall detection stays quiet
self.top = TopFanCurve((2, 5), board_factory=lambda: board)
self.fans = CaseFanControl(self.commander, (4, 5, 6), (1, 2, 3), top=self.top, profile=BALANCED)
self.now = 0.0
+157
View File
@@ -0,0 +1,157 @@
import json
import os
import tempfile
import time
import unittest
from unittest.mock import patch
from kurgan.telemetry.readings import PowerReadings, Readings
from kurgan.telemetry.record import Recorder, load
from kurgan.telemetry.service import Sample
HOUR = 1764892800 # any hour boundary; 1764892800 % 3600 == 0
def sample(t, cpu_temp=50.0, gpu_temp=None, vram=None, cpu_w=30.0, gpu_w=80.0, other_w=20.0):
return Sample(1, t, Readings(temp=cpu_temp, power=cpu_w), Readings(temp=gpu_temp, power=gpu_w),
PowerReadings(cpu=cpu_w, gpu=gpu_w, other=other_w), vram)
def written(directory):
rows = []
for name in sorted(os.listdir(directory)):
if not name.endswith(".jsonl"):
continue # records-current.json is the checkpoint of the hour in progress
with open(os.path.join(directory, name), encoding="utf-8") as f:
rows += [json.loads(line) for line in f if line.strip()]
return rows
def at(t):
"""Pretend the wall clock reads t (the recorder decides at startup whether its checkpoint is this hour)."""
return patch("kurgan.telemetry.record.time.time", return_value=t)
class RecorderTest(unittest.TestCase):
def test_an_hour_is_written_when_it_ends(self):
with tempfile.TemporaryDirectory() as d:
rec = Recorder(d)
rec.on_sample(sample(HOUR + 1))
rec.on_sample(sample(HOUR + 3599, cpu_temp=70.0))
rec.on_sample(sample(HOUR + 3600, cpu_temp=40.0)) # the new hour writes the old one
rec.close() # ... and closing checkpoints the hour still in progress
month = time.strftime("%Y-%m", time.gmtime(HOUR))
self.assertEqual(sorted(os.listdir(d)), [f"records-{month}.jsonl", "records-current.json"])
rows = written(d)
self.assertEqual(len(rows), 1)
first = rows[0]
self.assertEqual((first["hour"], first["n"]), (HOUR, 2))
self.assertEqual(first["cpu_temp"], [50.0, 60.0, 70.0, 2]) # min, avg, max, samples
self.assertEqual(first["total_w"], [130.0, 130.0, 130.0, 2]) # 30 + 80 + 20 W every sample
self.assertIsNone(first["gpu_temp"]) # a metric no sample carried stays null ...
self.assertIsNone(first["vram_used"])
def test_an_average_counts_only_the_samples_that_had_the_metric(self):
with tempfile.TemporaryDirectory() as d:
rec = Recorder(d)
rec.on_sample(sample(HOUR + 1, gpu_w=80.0))
rec.on_sample(sample(HOUR + 2, gpu_w=None)) # the GPU's power reading dropped out
rec.on_sample(sample(HOUR + 3, gpu_w=100.0))
rec.on_sample(sample(HOUR + 3600))
row = written(d)[0]
self.assertEqual(row["n"], 3)
self.assertEqual(row["gpu_w"], [80.0, 90.0, 100.0, 2]) # not 60: the gap isn't a zero
def test_a_hard_stop_loses_at_most_a_minute(self):
with tempfile.TemporaryDirectory() as d:
with at(HOUR + 1):
first = Recorder(d)
first.on_sample(sample(HOUR + 1, cpu_temp=40.0))
first.on_sample(sample(HOUR + 61, cpu_temp=60.0)) # checkpointed; then killed, no close()
with at(HOUR + 300):
second = Recorder(d) # the same hour: carries on with it
second.on_sample(sample(HOUR + 301, cpu_temp=80.0))
second.on_sample(sample(HOUR + 3600))
rows = written(d)
self.assertEqual(len(rows), 1)
self.assertEqual((rows[0]["n"], rows[0]["cpu_temp"]), (3, [40.0, 60.0, 80.0, 3]))
def test_a_checkpoint_from_an_earlier_hour_is_written_at_start(self):
with tempfile.TemporaryDirectory() as d:
with at(HOUR + 1):
first = Recorder(d)
first.on_sample(sample(HOUR + 1))
first.close()
self.assertEqual(written(d), [])
with at(HOUR + 7200):
Recorder(d)
rows = written(d)
self.assertNotIn("records-current.json", os.listdir(d))
with at(HOUR + 7300):
Recorder(d) # nothing left to write a second time
self.assertEqual(written(d), rows)
self.assertEqual([(r["hour"], r["n"]) for r in rows], [(HOUR, 1)])
def test_a_failing_disk_is_logged_once_and_catches_up_when_it_recovers(self):
with tempfile.TemporaryDirectory() as d:
blocked = os.path.join(d, "blocked")
open(blocked, "w").close()
rec = Recorder(blocked) # the "directory" is a file: every write fails
with self.assertLogs("kurgan.telemetry.record", level="WARNING") as logs:
rec.on_sample(sample(HOUR))
rec.on_sample(sample(HOUR + 3600)) # the hour can't be written: it waits
rec.on_sample(sample(HOUR + 7200))
self.assertEqual(len(logs.output), 1)
os.remove(blocked)
os.makedirs(blocked) # the disk is back
rec.on_sample(sample(HOUR + 10800))
self.assertEqual([r["hour"] for r in written(blocked)], [HOUR, HOUR + 3600, HOUR + 7200])
def test_pruning_removes_months_older_than_the_retention(self):
with tempfile.TemporaryDirectory() as d:
old = os.path.join(d, "records-2020-01.jsonl")
current = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime())}.jsonl")
open(old, "w").close()
open(current, "w").close()
Recorder(d, retention_days=400)
self.assertFalse(os.path.exists(old))
self.assertTrue(os.path.exists(current))
class LoadTest(unittest.TestCase):
def test_load_merges_restarts_and_skips_junk(self):
h = int(time.time() // 3600) * 3600
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime(h))}.jsonl")
with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps({"hour": h, "n": 100, "cpu_temp": [40.0, 50.0, 60.0], "total_w": None}) + "\n")
f.write(json.dumps({"hour": h, "n": 300, "cpu_temp": [30.0, 40.0, 80.0]}) + "\n") # a restart re-wrote this hour
f.write(json.dumps({"hour": h - 5 * 86400, "n": 3600, "cpu_temp": [10.0, 20.0, 30.0]}) + "\n") # outside the window
f.write("{torn\n") # the last line of a crashed run
data = load(d, days=1)
self.assertEqual(data["days"], 1)
self.assertEqual(data["metrics"][0], "cpu_temp")
self.assertEqual(len(data["rows"]), 1)
row = data["rows"][0]
self.assertEqual((row["hour"], row["n"]), (h, 400))
self.assertEqual(row["cpu_temp"], [30.0, 42.5, 80.0]) # min, sample-weighted avg, max
self.assertIsNone(row.get("total_w"))
def test_load_weights_averages_by_the_samples_that_had_the_metric(self):
h = int(time.time() // 3600) * 3600
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, f"records-{time.strftime('%Y-%m', time.gmtime(h))}.jsonl")
with open(path, "w", encoding="utf-8") as f:
f.write(json.dumps({"hour": h, "n": 3000, "gpu_w": [50.0, 100.0, 150.0, 3000]}) + "\n")
f.write(json.dumps({"hour": h, "n": 600, "gpu_w": [10.0, 40.0, 70.0, 100]}) + "\n") # the GPU dropped out
row = load(d, days=1)["rows"][0]
self.assertEqual(row["n"], 3600)
self.assertEqual([round(v, 2) for v in row["gpu_w"]], [10.0, 98.06, 150.0]) # (100*3000 + 40*100) / 3100
def test_load_without_a_directory_is_empty(self):
data = load(os.path.join(tempfile.gettempdir(), "kurgan-no-such-records-dir"), 7)
self.assertEqual(data["rows"], [])
if __name__ == "__main__":
unittest.main()
+14 -4
View File
@@ -24,11 +24,21 @@ class ValidateTest(unittest.TestCase):
validate({"cooling": cooling})
def test_lighting_modes_follow_each_zone(self):
self.assertEqual(validate({"lighting": {"memory": "chase"}})["lighting"]["memory"], "chase")
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}):
self.assertEqual(validate({"lighting": {"case_fans": "chase"}})["lighting"]["case_fans"], "chase")
for lighting in ({"gpu": "temperature"}, {"case_fans": "rainbow"}, {"keyboard": "off"}, {"memory": "rainbow"}):
with self.subTest(lighting=lighting), self.assertRaises(SettingsError):
validate({"lighting": lighting})
def test_the_hardware_services_old_sections_are_checked_kept_and_never_added(self):
self.assertNotIn("cooling", validate({}))
self.assertNotIn("memory", validate({})["lighting"])
old = validate({"cooling": {"profile": "quiet", "gpu_ports": [4, 5, 6]}, "lighting": {"memory": "chase"}})
self.assertEqual(old["cooling"], {"profile": "quiet", "gpu_ports": [4, 5, 6]})
self.assertEqual(old["lighting"]["memory"], "chase")
self.assertEqual(validate({"cooling": {"gpu_ports": [4, 5, 6]}})["cooling"]["profile"], "balanced")
with self.assertRaises(SettingsError):
validate({"cooling": {"profile": "quiet", "fans": 3}})
def test_ai_choices_and_ports(self):
self.assertEqual(validate({"ai": {"active": "llama"}})["ai"]["active"], "llama")
for ai in ({"active": "ollama"}, {"strata_model": "q8"}, {"strata_port": 80},
@@ -95,8 +105,8 @@ class SettingsFileTest(unittest.TestCase):
def test_returned_sections_are_copies(self):
settings = Settings(self.path, None)
settings.section("lighting")["memory"] = "chase"
self.assertEqual(settings.get("lighting", "memory"), "off")
settings.section("lighting")["case_fans"] = "chase"
self.assertEqual(settings.get("lighting", "case_fans"), "off")
if __name__ == "__main__":
+105
View File
@@ -0,0 +1,105 @@
import threading
import unittest
from kurgan.telemetry.readings import PowerReadings, Readings
from kurgan.telemetry.service import Telemetry
class FakeSource:
"""A cpu/gpu-shaped source: readings, plus the memory query the GPU one provides."""
def __init__(self):
self.fail = False
self.memory_fails = False
def read(self, *args):
if self.fail:
raise OSError("device gone")
return Readings(temp=50, load=10, clock=4000, power=30)
def memory(self):
if self.memory_fails:
raise OSError("nvml busy")
return (8 * 1024 ** 3, 24 * 1024 ** 3)
class FakeSystem:
def __init__(self):
self.fail = False
def read(self, cpu, gpu):
if self.fail:
raise OSError("commander gone")
return PowerReadings(cpu=cpu.power, gpu=gpu.power, other=40, parts={"fans": 2.0})
class TelemetryHealthTest(unittest.TestCase):
def setUp(self):
self.cpu, self.gpu, self.system = FakeSource(), FakeSource(), FakeSystem()
self.telemetry = Telemetry(self.cpu, self.gpu, self.system)
def test_before_the_first_read_there_is_nothing_to_report(self):
self.assertEqual(self.telemetry.snapshot(), {"seq": 0, "health": {}})
def test_a_healthy_run_has_no_health_entries(self):
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
self.assertEqual(self.telemetry.snapshot()["health"], {})
def test_a_failing_source_costs_only_itself_and_is_reported(self):
self.cpu.fail = True
with self.assertLogs("kurgan.telemetry.service", level="WARNING"):
sample = self.telemetry.read()
health = self.telemetry.health()
self.assertEqual(list(health), ["CPU sensors"])
self.assertIn("device gone", health["CPU sensors"]["error"])
self.assertIsNone(sample.cpu.temp) # the fallback stands in ...
self.assertEqual(sample.gpu.temp, 50) # ... while every other source still reads
self.assertEqual(sample.power.total, 70) # GPU 30 W + other 40 W; the CPU part is missing
def test_recovery_clears_the_entry(self):
self.gpu.fail = True
with self.assertLogs("kurgan.telemetry.service", level="WARNING"):
self.telemetry.read()
self.assertEqual(list(self.telemetry.health()), ["GPU sensors"])
self.gpu.fail = False
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
def test_a_source_that_goes_quiet_without_raising_is_reported(self):
# GpuSensors returns empty readings when the driver is lost (and while it backs off)
self.gpu.read = lambda *args: Readings()
self.telemetry.read()
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {}) # a gap or two proves nothing
with self.assertLogs("kurgan.telemetry.service", level="WARNING"):
self.telemetry.read()
health = self.telemetry.health()
self.assertEqual(list(health), ["GPU sensors"])
self.assertIn("driver unavailable", health["GPU sensors"]["error"])
del self.gpu.read # the driver is back
with self.assertLogs("kurgan.telemetry.service", level="INFO"):
self.telemetry.read()
self.assertEqual(self.telemetry.health(), {})
def test_the_snapshot_carries_health(self):
self.system.fail = True
self.gpu.memory_fails = True
first, stop = threading.Event(), threading.Event()
self.telemetry.subscribe(lambda sample: first.set())
with self.assertLogs("kurgan.telemetry.service", level="WARNING") as logs:
thread = threading.Thread(target=self.telemetry.run, args=(stop,), daemon=True)
thread.start()
self.assertTrue(first.wait(5)) # the listener fires after read(): both warnings are out
stop.set()
thread.join(5)
self.assertEqual(len(logs.output), 2) # each failing source is reported once
health = self.telemetry.snapshot()["health"]
self.assertEqual(set(health), {"system power", "GPU memory"})
snapshot = self.telemetry.snapshot()
self.assertIsNone(snapshot["gpu"]["vram_used"])
self.assertEqual(snapshot["gpu"]["temp"], 50)
if __name__ == "__main__":
unittest.main()
+23
View File
@@ -3,6 +3,7 @@ import json
import socket
import unittest
from kurgan.hw.client import HardwareUnavailable
from kurgan.web.server import WebServer
@@ -28,6 +29,8 @@ class FakeApp:
self.calls.append(("profile", profile))
if profile == "full-disk":
raise OSError("disk full")
if profile == "no-service":
raise HardwareUnavailable("the hardware service isn't running (no pipe)")
def set_ai(self, backend, variant):
self.calls.append(("ai", backend, variant))
@@ -35,6 +38,12 @@ class FakeApp:
def ai_model(self, action):
self.calls.append(("model", action))
def records(self, days):
self.calls.append(("records", days))
if not 1 <= days <= 400:
raise ValueError("days must be a whole number from 1 to 400")
return {"metrics": [], "rows": [], "days": days}
def free_port() -> int:
with socket.socket() as s:
@@ -113,6 +122,7 @@ class WebServerTest(unittest.TestCase):
("/api/lighting", b"x" * 20000, 400, "oversized"),
("/api/ai/active", {"backend": 3}, 400, "string or null"),
("/api/cooling/profile", {"profile": "full-disk"}, 500, "disk full"),
("/api/cooling/profile", {"profile": "no-service"}, 503, "isn't running"),
("/api/fans", {"x": 1}, 404, None))
for path, body, expected, message in cases:
with self.subTest(path=path, body=body):
@@ -127,6 +137,19 @@ class WebServerTest(unittest.TestCase):
self.request("POST", "/api/ai/active", {"backend": "strata", "variant": "iq3"})
self.assertEqual(self.app.calls, [("ai", None, None), ("ai", "strata", "iq3")])
def test_records_serves_the_long_term_rollups(self):
status, _, body = self.request("GET", "/api/records") # no days: the default week
self.assertEqual((status, json.loads(body)["days"]), (200, 7))
status, _, body = self.request("GET", "/api/records?days=30")
self.assertEqual((status, json.loads(body)["days"]), (200, 30))
self.assertEqual(self.app.calls, [("records", 7), ("records", 30)])
for path in ("/api/records?days=abc", "/api/records?days=0", "/api/records?days=-3",
"/api/records?days=401", "/api/records?days=1.5"):
with self.subTest(path=path):
status, _, raw = self.request("GET", path)
self.assertEqual(status, 400)
self.assertIn("whole number", json.loads(raw)["error"])
if __name__ == "__main__":
unittest.main()
+10 -2
View File
@@ -1,7 +1,9 @@
# Removes The Kurgan's startup task and stops it (an LLM server it started stops with it).
# Removes The Kurgan's startup task and stops it (an LLM server it started stops with it), and
# removes the "The Kurgan hardware" service (KurganHw). Stopping the service leaves the case fans
# at 100% and hands the top fans back to the BIOS curve.
# -RestoreAIServices re-enables and starts the "Strata Local Service" and "Qwen4 Local Service" tasks
# -RemovePawnIO also uninstalls PawnIO (leave it if LibreHardwareMonitor or FanControl uses it)
# Settings stay in %LOCALAPPDATA%\Kurgan.
# Settings stay in %LOCALAPPDATA%\Kurgan and %ProgramData%\Kurgan.
param([switch]$RemovePawnIO, [switch]$RestoreAIServices)
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
@@ -23,6 +25,12 @@ Get-CimInstance Win32_Process -Filter "Name like 'python%.exe'" |
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Write-Host "Removed 'The Kurgan'." -ForegroundColor Green
if (Get-Service -Name 'KurganHw' -ErrorAction SilentlyContinue) {
Stop-Service -Name 'KurganHw' -Force -ErrorAction SilentlyContinue
sc.exe delete KurganHw | Out-Null
Write-Host "Removed the hardware service: case fans at 100%, top fans on the BIOS curve." -ForegroundColor Green
}
if ($RestoreAIServices) {
Start-Sleep -Seconds 2 # let the LLM server's port close
foreach ($name in 'Strata Local Service', 'Qwen4 Local Service') {