Compare commits

..
9 Commits
Author SHA1 Message Date
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
paul 538a464257 test_proxy: wait for the proxy's release bookkeeping instead of racing it
response.read() returns as soon as the body is complete, but the handler
thread records ai.release() after that (and http.client closes the socket
before it), so asserting on ai.calls right away could catch a missing or a
stray entry -- and a stray could land in the next test after its setUp
cleared the list. FakeAi now tracks in-flight claims and request()/tearDown
wait for them (settle()).
2026-12-05 16:47:22 +13:00
paul d637d46777 Fail safe, not dead: bound the HID cancel wait, isolate sensor failures, keep the fan worker alive
- hid.py: after a timed-out HID operation, wait at most 1 s for the driver to
  finish the cancelled IRP; if it does not, mark the channel broken so the
  caller's reconnect path closes it instead of blocking forever on a wedged
  device. Keep abandoned OVERLAPPED/buffer references alive until close so a
  late IRP completion cannot write into reused memory. Check CreateEventW.
- telemetry/service.py: read each source (CPU, GPU, system power, GPU memory)
  independently; a failing source now costs only its own readings instead of
  the whole sample, logged at most once a minute per source.
- sensors.py: the Commander PRO iCUE ownership check runs inside a guard; if
  ownership cannot be established the device is released rather than risking
  swapped replies (and the failure no longer escapes into the sample).
- cooling/control.py: an unexpected exception no longer ends fan control for
  the life of the process; fail safe, log at most once a minute, retry with a
  fresh sensor object after 5 s. failsafe() no longer raises, and control
  errors back off 5 s instead of re-opening the device every second.
2026-12-05 16:47:16 +13:00
36 changed files with 1578 additions and 127 deletions

No files matched your search

+42 -15
View File
@@ -1,5 +1,7 @@
# The Kurgan
![The Kurgan's sword](kurgan/assets/sword.png)
One process that runs this PC's backend systems, with one web UI at **<http://127.0.0.1:8080/>**:
| Capability | What it does | Package |
@@ -30,7 +32,8 @@ This does the following:
`-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.
@@ -49,9 +52,14 @@ is elevated (see `kurgan/ai/launcher.py`). The web UI shows each server's integr
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, or a sensor source starting to fail. 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.
- **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.
- **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.
- **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.
@@ -63,8 +71,9 @@ next start.
| 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"}` |
@@ -133,6 +142,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 +174,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 +188,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 +221,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
@@ -242,8 +261,13 @@ On exit the case fans are left at 100% and the top fans go back to the BIOS Smar
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.
last duty. 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
@@ -361,13 +385,16 @@ 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)
tests/ unittest suites
docs/ design references and research notes
Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

+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}"
+26 -4
View File
@@ -193,8 +193,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 +207,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 +312,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 +326,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,11 +344,16 @@ 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 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
if time.monotonic() < slot.hold_until:
return
# At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the
+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")
+97 -4
View File
@@ -67,6 +67,63 @@ 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]
ALERT_SECONDS = 5.0 # how often the alert monitor looks for things starting to go wrong
def alert_states(fans, ai, telemetry) -> dict[str, str]:
"""What is wrong right now: key -> message, for the things worth one balloon each."""
states = {}
if fans is not None:
for group in fans.groups:
if group.status.startswith(("FAILSAFE", "CONTROL ERROR")):
states[f"fans/{group.name}"] = f"{group.name} case fans: {group.status}"
if fans.top is not None and fans.top.status.startswith(("FAILSAFE", "UNAVAILABLE")):
states["fans/top"] = f"Top fans: {fans.top.status}"
if ai is not None:
for backend in ai.snapshot()["backends"]:
if backend["error"]:
states[f"ai/{backend['key']}"] = f"{backend['label']}: {backend['error']}"
for name, info in telemetry.health().items():
states[f"telemetry/{name}"] = f"{name} read failed ({info['error']}); continuing without it"
return states
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:
from kurgan.cooling.control import parse_ports
@@ -171,6 +228,11 @@ class Kurgan:
self.telemetry = Telemetry(hw["cpu"] if hw else CpuSensors(),
hw["gpu"] if hw else GpuSensors(load_source=args.gpu_load),
self.system, args.interval)
self.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)
@@ -246,14 +308,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.fans, 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,6 +368,8 @@ 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()
@@ -321,6 +407,13 @@ 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)
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

+99 -9
View File
@@ -25,6 +25,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 +60,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 +76,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 +97,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 +135,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 +177,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 +236,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 +256,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 +267,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
@@ -222,13 +287,15 @@ class CaseFanGroup:
self._last_update = None
try:
self.commander.set_duty(self.ports, 100)
except (OSError, HidError):
except Exception: # the worker's finally block depends on this never raising
log.exception("Cannot set %s case fans to failsafe 100%%; controller unavailable", self.name)
class CpuTemperature:
"""CPU package temperature averaged over CPU_AVERAGE readings; None while unavailable."""
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
@@ -249,6 +316,7 @@ class CpuTemperature:
except OSError as e:
log.warning("CPU temperature read failed, will retry: %s", e)
self.close()
self._retry_at = now + self.RETRY_SECONDS
if temp is None:
self._recent.clear()
return None
@@ -262,6 +330,10 @@ class CpuTemperature:
class CaseFanControl:
# Pause after a control error before polling again, so a lost device is not re-opened
# (with a full traceback and process enumeration) every second.
ERROR_RETRY_SECONDS = 5.0
def __init__(self, commander: CommanderPro, gpu_ports: tuple[int, ...],
cpu_ports: tuple[int, ...] | None = None, top: TopFanCurve | None = None,
profile: FanProfile = BALANCED, sensors=None):
@@ -316,11 +388,15 @@ class CaseFanControl:
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
try:
gpu = gpu_factory()
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)
except (OSError, HidError) as e:
self._error(f"CONTROL ERROR: {e}")
@@ -328,10 +404,24 @@ class CaseFanControl:
self.commander.close()
if self.top is not None:
self.top.update(100, None, time.monotonic())
stop.wait(1)
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
log.exception("Case fan control error; failing safe and retrying")
self._error(f"CONTROL ERROR: {e}")
self.failsafe()
if self.top is not None:
try: # as the device-error path does; update() never raises for the board
self.top.update(100, None, time.monotonic())
except Exception:
log.exception("Case fan worker failed")
self._error("CONTROL ERROR: fan worker stopped; check dashboard.log")
log.debug("Top fans: failsafe update failed", exc_info=True)
gpu = None
retry_in = self.ERROR_RETRY_SECONDS
stop.wait(retry_in)
finally:
self.failsafe()
self.commander.close()
+8
View File
@@ -73,14 +73,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)
+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))):
+32 -4
View File
@@ -33,6 +33,13 @@ _ERROR_IO_PENDING = 997
_ERROR_NO_MORE_ITEMS = 259
_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):
@@ -193,6 +200,9 @@ class HidChannel:
)
self._wevent = _k32.CreateEventW(None, True, False, None)
self._revent = _k32.CreateEventW(None, True, False, None)
if not self._wevent or not self._revent:
raise _winerr("CreateEventW")
self._broken = False
except Exception:
_k32.CloseHandle(self.handle)
raise
@@ -203,7 +213,22 @@ class HidChannel:
_k32.CloseHandle(h)
self.handle = None
def _cancel(self, ov, buf, event, what: str) -> None:
"""Cancel a timed-out IRP and give the driver a moment to finish it.
If the device is wedged and the cancellation never completes, mark the channel broken:
further calls fail fast instead of queueing more IRPs behind a dead one, and the
caller's reconnect path closes the handle (which cancels the IRP for good).
"""
_k32.CancelIoEx(self.handle, ctypes.byref(ov))
if _k32.WaitForSingleObject(event, _ABANDON_GRACE_MS) == _WAIT_OBJECT_0:
return
self._broken = True
_ABANDONED.append((ov, buf))
def send(self, payload: bytes, timeout_ms: int = 1000) -> None:
if self._broken:
raise HidError(f"HID write on {self.path}: channel abandoned after a timeout; reconnect it")
data = bytes(1) + payload
if len(data) < self.output_len:
data += bytes(self.output_len - len(data))
@@ -216,14 +241,15 @@ class HidChannel:
if ctypes.get_last_error() != _ERROR_IO_PENDING:
raise _winerr("WriteFile")
if _k32.WaitForSingleObject(self._wevent, timeout_ms) != _WAIT_OBJECT_0:
_k32.CancelIoEx(self.handle, ctypes.byref(ov))
_k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True)
self._cancel(ov, buf, self._wevent, "write")
raise HidError(f"HID write timed out on {self.path}")
if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(written), True):
raise _winerr("WriteFile (completion)")
def read(self, timeout_ms: int) -> bytes | None:
"""Read one input report, or None on timeout."""
if self._broken:
raise HidError(f"HID read on {self.path}: channel abandoned after a timeout; reconnect it")
buf = ctypes.create_string_buffer(self.input_len)
ov = _OVERLAPPED()
ov.hEvent = self._revent
@@ -232,8 +258,10 @@ class HidChannel:
if not _k32.ReadFile(self.handle, buf, self.input_len, None, ctypes.byref(ov)):
if ctypes.get_last_error() != _ERROR_IO_PENDING:
raise _winerr("ReadFile")
if _k32.WaitForSingleObject(self._revent, timeout_ms) == _WAIT_TIMEOUT:
_k32.CancelIoEx(self.handle, ctypes.byref(ov))
if _k32.WaitForSingleObject(self._revent, timeout_ms) != _WAIT_OBJECT_0:
self._cancel(ov, buf, self._revent, "read")
if self._broken:
raise HidError(f"HID read timed out on {self.path} and the device ignored the cancel")
ok = _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True)
return buf.raw[: got.value] if ok and got.value else None
if not _k32.GetOverlappedResult(self.handle, ctypes.byref(ov), ctypes.byref(got), True):
+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}
+33 -2
View File
@@ -298,6 +298,10 @@ class IntelPackage:
# ----------------------------------------------------------------------------- CPU
class CpuSensors:
# 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):
base = r"\Processor Information(_Total)"
self.pdh = PerfCounters({
@@ -347,12 +351,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 +369,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 +427,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 +454,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,
@@ -596,6 +610,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 +622,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:
@@ -678,19 +696,24 @@ 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 _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]:
now = time.monotonic()
if now >= self._next_check:
self._next_check = now + self.RECHECK
try:
if self._corsair_software_running():
self.close()
self._say("iCUE is running, leaving the device to it")
@@ -701,14 +724,22 @@ class CommanderPro:
except Exception as e:
self.close()
self._say(f"unavailable ({e})")
except Exception as e:
# Ownership cannot be established (e.g. process enumeration failed): give the
# device up rather than risk swapped replies, and retry on the next check.
self.close()
self._say(f"ownership check failed ({e}); device released, retrying in {self.RECHECK:.0f} s")
if self.ch is not None:
try:
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]
+48 -5
View File
@@ -19,6 +19,7 @@ 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
SERIES = ("t", "cpu_temp", "gpu_temp", "cpu_load", "gpu_load", "cpu_w", "gpu_w", "other_w", "total_w", "vram_used")
@@ -50,15 +51,56 @@ class Telemetry:
self._history: collections.deque[tuple] = collections.deque(maxlen=int(HISTORY_SECONDS / interval))
self._listeners: list[Callable[[Sample], None]] = []
self._seq = 0
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:
c, g = self.cpu.read(), self.gpu.read()
p = self.system.read(c, g)
"""Read every source independently: one failing source costs only its own readings."""
# The sensor classes don't raise when their device is lost (they back off and return
# empty readings), so a reading without a temperature counts as failing too.
c = self._source("CPU sensors", self.cpu.read, Readings(),
missing=lambda r: None if r.temp is not None else "no CPU temperature (MSR reader unavailable)")
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, self.gpu.memory())
return Sample(self._seq, time.time(), c, g, p, vram)
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:
result = read(*args)
except Exception as e:
# The loop retries every second, so log each failing source at most once a minute.
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():
@@ -101,15 +143,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
+35 -40
View File
@@ -2,7 +2,8 @@
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,
@@ -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
@@ -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")
+8 -1
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"}
@@ -26,6 +27,7 @@ import mimetypes
import os
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs
from kurgan.web import proxy
@@ -105,12 +107,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 +124,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"})
+82 -11
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,21 @@ 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 health = Object.entries(s.telemetry.health ?? {});
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"),
...(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 +564,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 +578,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) {
@@ -751,7 +821,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 +861,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

+72 -2
View File
@@ -2,10 +2,11 @@ import os
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,6 +312,75 @@ 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")
class LauncherTest(unittest.TestCase):
def test_child_runs_as_a_normal_user_with_its_output_logged(self):
+130
View File
@@ -0,0 +1,130 @@
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_fans(gpu_status="GPU 50 C, 40% PWM", top_status="55 C, 45%"):
group = Mock()
group.name = "GPU"
group.status = gpu_status
top = Mock()
top.status = top_status
fans = Mock()
fans.groups = [group]
fans.top = top
return fans
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_fans(), fake_ai(("strata", None), ("llama", None)),
fake_health()), {})
def test_failsafes_errors_and_failing_sources_are_collected(self):
states = alert_states(
fake_fans(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()), {})
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()
+107 -4
View File
@@ -38,6 +38,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,6 +111,75 @@ 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)}
@@ -224,8 +294,13 @@ 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)
@@ -238,15 +313,43 @@ class FanWorkerTest(unittest.TestCase):
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
self.commander.close.assert_called_once()
def test_worker_error_is_visible_and_attempts_failsafe(self):
def test_worker_survives_unexpected_errors_and_keeps_failing_safe(self):
stop = threading.Event()
gpu = Mock()
gpu.read.side_effect = RuntimeError("sensor failure")
with patch("kurgan.cooling.control.GpuSensors", return_value=gpu):
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
self.assertIn("CONTROL ERROR", self.control.status)
self.commander.set_duty.assert_called_once_with((4, 5, 6), 100)
self.commander.set_duty.assert_called_with((4, 5, 6), 100)
def test_unexpected_errors_fail_the_top_fans_safe_too(self):
top = Mock(spec=TopFanCurve)
self.control.top = top
stop = threading.Event()
gpu = Mock()
def read():
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(top.update.call_args.args[:2], (100, None))
top.release.assert_called_once()
class CommanderControlTest(unittest.TestCase):
+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
+22 -1
View File
@@ -93,6 +93,7 @@ class FakeAi:
self.slots = {b.key: SimpleNamespace(backend=b) for b in backends}
self.up = {b.key: True for b in backends}
self.calls = []
self.pending = 0 # claims without a matching release: handler threads still working
self.error = None
self.wait_for_client = False # act like a claim waiting for the other server
@@ -108,9 +109,11 @@ class FakeAi:
if gone():
raise RouteError("while waiting for Strata to finish", CLIENT_GONE)
time.sleep(0.05)
self.pending += 1
return self.slots[key].backend
def release(self, key):
self.pending -= 1
self.calls.append(("release", key))
@@ -142,19 +145,37 @@ class ProxyTest(unittest.TestCase):
def setUp(self):
self.upstream.requests.clear()
self.ai.calls.clear()
self.ai.pending = 0
self.ai.up = {"strata": True, "llama": True}
self.ai.error = None
self.ai.wait_for_client = False
self.llama.port = self.upstream.port
self.upstream.release_slow.clear()
def tearDown(self):
self.settle() # no handler thread may still append to ai.calls for the next test
def settle(self, timeout=5):
"""Wait until every claimed request has been released.
The proxy's handler thread records release() after the client already has its reply
(and http.client closes the connection before that), so assertions on ai.calls must
wait for the bookkeeping instead of racing it.
"""
deadline = time.monotonic() + timeout
while self.ai.pending > 0 and time.monotonic() < deadline:
time.sleep(0.01)
self.assertEqual(self.ai.pending, 0, f"unfinished claims: {self.ai.calls}")
def request(self, method, path, body=None, headers=None, chunked=False):
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
try:
base = {"Host": f"127.0.0.1:{self.port}", **(headers or {})}
connection.request(method, path, body=body, headers=base, encode_chunked=chunked)
response = connection.getresponse()
return response.status, dict(response.getheaders()), response.read()
data = response.read()
self.settle()
return response.status, dict(response.getheaders()), data
finally:
connection.close()
+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()
+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()
+19
View File
@@ -35,6 +35,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:
@@ -127,6 +133,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()