221 lines
8.9 KiB
Python
221 lines
8.9 KiB
Python
"""The Kurgan's settings: one JSON file, validated when loaded and before every save.
|
|
|
|
%LOCALAPPDATA%\\Kurgan\\settings.json, for example:
|
|
|
|
{
|
|
"cooling": {"gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5],
|
|
"profile": "balanced"},
|
|
"lighting": {"case_fans": "chase", "memory": "off", "gpu": "off"},
|
|
"ai": {"active": "strata", "strata_model": "q5", "idle_stop_minutes": 40},
|
|
"web": {"port": 8080}
|
|
}
|
|
|
|
The fan port mapping is written by `python -m kurgan.cooling.control --save-ports ...`; the
|
|
rest by the web UI. An invalid file stops The Kurgan from starting rather than silently
|
|
dropping fan control. On first start the TT LCD Dashboard's settings are imported.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import copy
|
|
import json
|
|
import logging
|
|
import os
|
|
import threading
|
|
|
|
from kurgan import paths
|
|
from kurgan.ai import config as ai_config
|
|
from kurgan.cooling.profiles import DEFAULT_PROFILE, PROFILES
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
LIGHTING_MODES = {
|
|
"case_fans": ("off", "temperature", "chase"), # Lighting Node CORE (QL120 fan LEDs)
|
|
"memory": ("off", "temperature", "chase"), # Dominator Platinum DDR5
|
|
"gpu": ("off", "chase"), # ASUS ROG STRIX RTX 4090
|
|
}
|
|
DEFAULT_WEB_PORT = 8080
|
|
|
|
DEFAULTS = {
|
|
"cooling": {"profile": DEFAULT_PROFILE},
|
|
"lighting": {zone: "off" for zone in LIGHTING_MODES},
|
|
"ai": {"active": None, "strata_model": ai_config.STRATA_DEFAULT_MODEL,
|
|
"idle_stop_minutes": ai_config.IDLE_STOP_MINUTES},
|
|
"web": {"port": DEFAULT_WEB_PORT},
|
|
}
|
|
_OPTIONAL = {
|
|
"cooling": {"gpu_ports", "cpu_ports", "top_channels"},
|
|
"lighting": set(),
|
|
"ai": {"strata_root", "strata_port", "llama_server", "llama_presets", "llama_model", "llama_port"},
|
|
"web": set(),
|
|
}
|
|
|
|
|
|
class SettingsError(ValueError):
|
|
pass
|
|
|
|
|
|
def _ports(value, where: str) -> list[int]:
|
|
from kurgan.cooling.control import parse_ports
|
|
|
|
if not isinstance(value, list) or any(type(v) is not int for v in value):
|
|
raise SettingsError(f"{where} must be an array of integers")
|
|
try:
|
|
return list(parse_ports(",".join(map(str, value))))
|
|
except argparse.ArgumentTypeError as e:
|
|
raise SettingsError(f"{where}: {e}") from None
|
|
|
|
|
|
def _port_number(value, where: str) -> int:
|
|
if type(value) is not int or not 1024 <= value <= 65535:
|
|
raise SettingsError(f"{where} must be a TCP port number 1024-65535")
|
|
return value
|
|
|
|
|
|
def validate(data: object) -> dict:
|
|
"""Return a normalised copy with defaults filled in, or raise SettingsError."""
|
|
if not isinstance(data, dict):
|
|
raise SettingsError("settings must be a JSON object")
|
|
unknown = set(data) - set(DEFAULTS)
|
|
if unknown:
|
|
raise SettingsError(f"unknown section(s): {', '.join(sorted(unknown))}")
|
|
out = copy.deepcopy(DEFAULTS)
|
|
for section, values in data.items():
|
|
if not isinstance(values, dict):
|
|
raise SettingsError(f"{section} must be an object")
|
|
bad = set(values) - set(DEFAULTS[section]) - _OPTIONAL[section]
|
|
if bad:
|
|
raise SettingsError(f"{section}: unknown setting(s): {', '.join(sorted(bad))}")
|
|
out[section].update(values)
|
|
|
|
cooling = out["cooling"]
|
|
if cooling["profile"] not in PROFILES:
|
|
raise SettingsError(f"cooling.profile must be one of {', '.join(PROFILES)}")
|
|
if ("cpu_ports" in cooling or "top_channels" in cooling) and "gpu_ports" not in cooling:
|
|
raise SettingsError("cooling: save the GPU-side ports (gpu_ports) first")
|
|
for key in ("gpu_ports", "cpu_ports"):
|
|
if key in cooling:
|
|
cooling[key] = _ports(cooling[key], f"cooling.{key}")
|
|
if set(cooling.get("cpu_ports", ())) & set(cooling.get("gpu_ports", ())):
|
|
raise SettingsError("cooling: cpu_ports and gpu_ports must not overlap")
|
|
if "top_channels" in cooling:
|
|
from kurgan.cooling.board_fans import parse_channels
|
|
|
|
value = cooling["top_channels"]
|
|
if not isinstance(value, list) or any(type(v) is not int for v in value):
|
|
raise SettingsError("cooling.top_channels must be an array of integers")
|
|
try:
|
|
cooling["top_channels"] = list(parse_channels(",".join(map(str, value))))
|
|
except argparse.ArgumentTypeError as e:
|
|
raise SettingsError(f"cooling.top_channels: {e}") from None
|
|
|
|
for zone, modes in LIGHTING_MODES.items():
|
|
if out["lighting"][zone] not in modes:
|
|
raise SettingsError(f"lighting.{zone} must be one of {', '.join(modes)}")
|
|
|
|
ai = out["ai"]
|
|
if ai["active"] is not None and ai["active"] not in ai_config.BACKENDS:
|
|
raise SettingsError(f"ai.active must be null or one of {', '.join(ai_config.BACKENDS)}")
|
|
if ai["strata_model"] not in ai_config.STRATA_MODELS:
|
|
raise SettingsError(f"ai.strata_model must be one of {', '.join(ai_config.STRATA_MODELS)}")
|
|
if type(ai["idle_stop_minutes"]) is not int or not 0 <= ai["idle_stop_minutes"] <= 1440:
|
|
raise SettingsError("ai.idle_stop_minutes must be 0 (never) to 1440")
|
|
for key in ("strata_root", "llama_server", "llama_presets", "llama_model"):
|
|
if key in ai and (not isinstance(ai[key], str) or not ai[key]):
|
|
raise SettingsError(f"ai.{key} must be a non-empty string")
|
|
for key in ("strata_port", "llama_port"):
|
|
if key in ai:
|
|
_port_number(ai[key], f"ai.{key}")
|
|
if ai.get("strata_port", ai_config.STRATA_PORT) == ai.get("llama_port", ai_config.LLAMA_PORT):
|
|
raise SettingsError("ai: Strata and llama.cpp need different ports")
|
|
_port_number(out["web"]["port"], "web.port")
|
|
return out
|
|
|
|
|
|
def write_json_atomic(path: str, data: dict) -> None:
|
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
temporary = path + ".tmp"
|
|
try:
|
|
with open(temporary, "w", encoding="utf-8") as stream:
|
|
json.dump(data, stream, indent=2)
|
|
stream.write("\n")
|
|
stream.flush()
|
|
os.fsync(stream.fileno())
|
|
os.replace(temporary, path)
|
|
finally:
|
|
if os.path.exists(temporary):
|
|
os.remove(temporary)
|
|
|
|
|
|
def _legacy(legacy_dir: str) -> dict:
|
|
"""The TT LCD Dashboard's fan-control.json, memory-lighting.json and gpu-lighting.json."""
|
|
data: dict = {}
|
|
|
|
def read(name: str):
|
|
try:
|
|
with open(os.path.join(legacy_dir, name), encoding="utf-8") as stream:
|
|
return json.load(stream)
|
|
except FileNotFoundError:
|
|
return None
|
|
except ValueError as e:
|
|
raise SettingsError(f"{legacy_dir}\\{name}: {e}") from None
|
|
|
|
fans = read("fan-control.json")
|
|
if fans is not None:
|
|
if not isinstance(fans, dict) or not set(fans) <= {"gpu_ports", "cpu_ports", "top_channels"}:
|
|
raise SettingsError(f"{legacy_dir}\\fan-control.json has unexpected contents")
|
|
data["cooling"] = dict(fans)
|
|
for name, zone in (("memory-lighting.json", "memory"), ("gpu-lighting.json", "gpu")):
|
|
mode = read(name)
|
|
if mode is not None:
|
|
if not isinstance(mode, dict) or set(mode) != {"mode"}:
|
|
raise SettingsError(f"{legacy_dir}\\{name} has unexpected contents")
|
|
data.setdefault("lighting", {})[zone] = mode["mode"]
|
|
return data
|
|
|
|
|
|
class Settings:
|
|
"""Thread-safe: the web server, the tray and the CLI all go through update()."""
|
|
|
|
def __init__(self, path: str = paths.SETTINGS_PATH, legacy_dir: str | None = paths.LEGACY_DIR,
|
|
seed: dict | None = None):
|
|
"""seed: values applied only when the file is first created (e.g. the old task's CLI flags)."""
|
|
self.path = path
|
|
self._lock = threading.RLock()
|
|
self.created = False
|
|
try:
|
|
with open(path, encoding="utf-8") as stream:
|
|
raw = json.load(stream)
|
|
except FileNotFoundError:
|
|
raw = _legacy(legacy_dir) if legacy_dir else {}
|
|
for section, values in (seed or {}).items():
|
|
raw.setdefault(section, {}).update(values)
|
|
self.created = True
|
|
except ValueError as e:
|
|
raise SettingsError(f"{path}: {e}") from None
|
|
try:
|
|
self._data = validate(raw)
|
|
except SettingsError as e:
|
|
raise SettingsError(f"{path}: {e}") from None
|
|
if self.created:
|
|
write_json_atomic(path, self._data)
|
|
log.info("Created %s%s", path, " from the TT LCD Dashboard's settings" if raw else "")
|
|
|
|
def section(self, name: str) -> dict:
|
|
with self._lock:
|
|
return copy.deepcopy(self._data[name])
|
|
|
|
def get(self, section: str, key: str, default=None):
|
|
with self._lock:
|
|
return copy.deepcopy(self._data[section].get(key, default))
|
|
|
|
def update(self, section: str, **changes) -> None:
|
|
"""Validate and save; on any error nothing changes, in memory or on disk."""
|
|
with self._lock:
|
|
data = copy.deepcopy(self._data)
|
|
data[section].update(changes)
|
|
data = validate(data)
|
|
write_json_atomic(self.path, data)
|
|
self._data = data
|