Privilege split 9/11: setup installs the hardware service and moves its settings
- kurgan/hw/install.py (run elevated by setup.ps1): checks the base interpreter can run hw_service.py, creates %ProgramData%\Kurgan or resets its owner and access (Administrators own it; SYSTEM and Administrators full control, users read), moves the fan and RAM settings there, then creates or updates KurganHw through the service manager API (pywin32; sc.exe's quoting from Windows PowerShell 5.1 isn't reliable): LocalSystem, automatic start, restart after 5 s, 10 s and 60 s, the user's SID for the pipe. A running service is stopped first; then it's started and must reach "running". - kurgan/hw/migrate.py: "copy" (elevated) creates hw-settings.json from the user's cooling and lighting.memory, never overwriting an existing file; "strip" (as the user) removes them from settings.json once hw-settings.json exists, keeping a dated backup. An invalid file on either side stops it. - setup.ps1: creates the .venv if needed (the service runs from it), passes the base interpreter, the user's SID and settings path to the elevated part, which installs the service; then strips settings.json, registers and starts the app's task, and prints the service's status. - uninstall.ps1: also stops and deletes the service. - python -m kurgan.hw.client prints the service's status (setup runs it). - The pipe's "isn't running", "refused this user" and "closed the connection" errors no longer repeat the Windows error text. - Tests: migration (move, re-run, defaults, invalid files) and the install module's parts that don't need admin rights. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a7ebf42838
commit
8f91a38695
8 files changed
+492
-22
No files matched your search
@@ -299,3 +299,31 @@ class RamLighting:
|
||||
|
||||
def set_mode(self, mode: str) -> None:
|
||||
self.client.set_ram_lighting(mode)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
"""python -m kurgan.hw.client: is the hardware service reachable, and what is it doing?"""
|
||||
logging.basicConfig(level=logging.ERROR, format="%(message)s")
|
||||
client = HardwareClient()
|
||||
client.poll()
|
||||
if client.error is not None:
|
||||
print(f"Hardware service unavailable: {client.error}")
|
||||
return 1
|
||||
service, cooling, cpu, ram = client.snapshot(), client.cooling(), client.cpu(), client.ram_lighting()
|
||||
print(f"The Kurgan hardware {service['version']} (pid {service['pid']}, up {service['uptime']} s)")
|
||||
if cooling["groups"]:
|
||||
top = f", top {cooling['top']['duty']}%" if cooling["top"] else ""
|
||||
groups = ", ".join(f"{g['name']} {g['duty']}%" for g in cooling["groups"])
|
||||
print(f"Fans: {cooling['profile']} profile; {groups}{top}")
|
||||
if cooling["note"]:
|
||||
print(f"Fans: {cooling['note']}")
|
||||
fmt = lambda v, unit: "--" if v is None else f"{v:.0f} {unit}"
|
||||
print(f"CPU: {fmt(cpu['temp'], 'C')}, {fmt(cpu['power'], 'W')}" + (f" ({cpu['error']})" if cpu["error"] else ""))
|
||||
print(f"RAM lighting: {ram['mode']} ({ram['status']})")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,162 @@
|
||||
"""Install or update the hardware service; setup.ps1 runs this elevated (Decision 0002).
|
||||
|
||||
python -m kurgan.hw.install --python BASE_PYTHON --user-sid SID --user-settings PATH
|
||||
|
||||
1. checks that BASE_PYTHON can run the service (hw_service.py --check);
|
||||
2. creates %ProgramData%\\Kurgan, or resets its access (Administrators own it; SYSTEM and
|
||||
Administrators full control, users read), and moves the fan and RAM lighting settings into
|
||||
hw-settings.json there, once (kurgan.hw.migrate);
|
||||
3. creates the "KurganHw" service, or updates it after stopping it: LocalSystem, automatic start,
|
||||
restart after 5 s, 10 s and 60 s on failure, and the user whose app may use its pipe;
|
||||
4. starts it and waits until it runs.
|
||||
|
||||
The service runs the base interpreter, not the venv's python.exe (a redirector that starts the
|
||||
base interpreter as a child, which the service manager wouldn't be talking to):
|
||||
|
||||
"BASE_PYTHON" -I -S -B "<repo>\\hw_service.py"
|
||||
|
||||
uninstall.ps1 removes the service with sc.exe; nothing else is needed for that.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from kurgan import paths
|
||||
from kurgan.hw import main as hw_main
|
||||
from kurgan.hw.pipe import valid_sid
|
||||
|
||||
SCRIPT = os.path.join(paths.PROJECT_DIR, "hw_service.py")
|
||||
DESCRIPTION = ("The Kurgan's hardware control: case and top fan curves with their fail-safes, and the RAM "
|
||||
"lighting. Stopping it leaves the case fans at 100% and the top fans on the BIOS curve.")
|
||||
RESTARTS_MS = (5000, 10000, 60000)
|
||||
RESET_SECONDS = 24 * 3600 # the failure count starts again after a day without one
|
||||
# The data folder, owner included (kurgan.hw.settings.DATA_DIR_SDDL is the access list).
|
||||
DATA_DIR_OWNER_SDDL = "O:BAG:SY"
|
||||
|
||||
|
||||
def image_path(python: str, script: str = SCRIPT) -> str:
|
||||
return f'"{python}" -I -S -B "{script}"'
|
||||
|
||||
|
||||
def failure_actions() -> dict:
|
||||
import win32service
|
||||
|
||||
return {"ResetPeriod": RESET_SECONDS, "RebootMsg": None, "Command": None,
|
||||
"Actions": [(win32service.SC_ACTION_RESTART, ms) for ms in RESTARTS_MS]}
|
||||
|
||||
|
||||
def check(python: str) -> str:
|
||||
"""hw_service.py --check under the service's interpreter and flags; RuntimeError if it fails."""
|
||||
try:
|
||||
result = subprocess.run([python, "-I", "-S", "-B", SCRIPT, "--check"], capture_output=True, text=True,
|
||||
timeout=120, cwd=paths.PROJECT_DIR)
|
||||
except (OSError, subprocess.TimeoutExpired) as e:
|
||||
raise RuntimeError(f"{python} can't run the hardware service: {e}") from None
|
||||
if result.returncode != 0:
|
||||
detail = (result.stderr or result.stdout).strip().splitlines()
|
||||
raise RuntimeError(f"{python} can't run the hardware service: {detail[-1] if detail else result.returncode}")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def reset_data_dir(path: str = paths.HW_DATA_DIR) -> None:
|
||||
"""Create the data folder, or give an existing one exactly the intended owner and access."""
|
||||
import win32security
|
||||
|
||||
from kurgan.hw import settings as hw_settings
|
||||
|
||||
hw_settings.ensure_data_dir(path)
|
||||
sd = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
|
||||
DATA_DIR_OWNER_SDDL + hw_settings.DATA_DIR_SDDL, win32security.SDDL_REVISION_1)
|
||||
win32security.SetNamedSecurityInfo( # also passes the inheritable entries on to the files inside
|
||||
path, win32security.SE_FILE_OBJECT,
|
||||
win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
|
||||
| win32security.PROTECTED_DACL_SECURITY_INFORMATION,
|
||||
sd.GetSecurityDescriptorOwner(), None, sd.GetSecurityDescriptorDacl(), None)
|
||||
|
||||
|
||||
def _wait(service, state: int, seconds: float) -> int:
|
||||
import win32service
|
||||
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
current = win32service.QueryServiceStatus(service)[1]
|
||||
if current == state or time.monotonic() > deadline:
|
||||
return current
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def install(python: str, user_sid: str) -> None:
|
||||
"""Create or update the service (stopping it first if it runs), then start it."""
|
||||
import pywintypes
|
||||
import win32service
|
||||
import winerror
|
||||
import winreg
|
||||
|
||||
manager = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
|
||||
try:
|
||||
args = (win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START,
|
||||
win32service.SERVICE_ERROR_NORMAL, image_path(python), None, False, None)
|
||||
try:
|
||||
service = win32service.OpenService(manager, hw_main.SERVICE_NAME, win32service.SERVICE_ALL_ACCESS)
|
||||
except pywintypes.error as e:
|
||||
if e.winerror != winerror.ERROR_SERVICE_DOES_NOT_EXIST:
|
||||
raise
|
||||
service = win32service.CreateService(manager, hw_main.SERVICE_NAME, hw_main.SERVICE_DISPLAY_NAME,
|
||||
win32service.SERVICE_ALL_ACCESS, *args, None, None)
|
||||
print(f"Created the {hw_main.SERVICE_DISPLAY_NAME!r} service ({hw_main.SERVICE_NAME})")
|
||||
else:
|
||||
if win32service.QueryServiceStatus(service)[1] != win32service.SERVICE_STOPPED:
|
||||
print("Stopping the running hardware service (case fans to 100% meanwhile)...")
|
||||
win32service.ControlService(service, win32service.SERVICE_CONTROL_STOP)
|
||||
if _wait(service, win32service.SERVICE_STOPPED, hw_main.STOP_SECONDS + 10) != win32service.SERVICE_STOPPED:
|
||||
raise RuntimeError("the hardware service didn't stop; try again, or reboot")
|
||||
win32service.ChangeServiceConfig(service, *args, "LocalSystem", None, hw_main.SERVICE_DISPLAY_NAME)
|
||||
print(f"Updated the {hw_main.SERVICE_DISPLAY_NAME!r} service ({hw_main.SERVICE_NAME})")
|
||||
try:
|
||||
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_DESCRIPTION, DESCRIPTION)
|
||||
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, failure_actions())
|
||||
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, True)
|
||||
with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, hw_main.PARAMETERS_KEY, 0, winreg.KEY_SET_VALUE) as key:
|
||||
winreg.SetValueEx(key, "UserSid", 0, winreg.REG_SZ, user_sid)
|
||||
win32service.StartService(service, None)
|
||||
state = _wait(service, win32service.SERVICE_RUNNING, 30)
|
||||
if state != win32service.SERVICE_RUNNING:
|
||||
raise RuntimeError(f"the hardware service didn't start (state {state}); see {paths.HW_LOG_PATH}")
|
||||
print(f"The hardware service is running. Log: {paths.HW_LOG_PATH}")
|
||||
finally:
|
||||
win32service.CloseServiceHandle(service)
|
||||
finally:
|
||||
win32service.CloseServiceHandle(manager)
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
from kurgan.hw import migrate
|
||||
|
||||
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.install", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--python", required=True, help="the base interpreter's python.exe (not the venv's)")
|
||||
ap.add_argument("--user-sid", required=True, help="the user whose app may use the pipe")
|
||||
ap.add_argument("--user-settings", required=True, help="that user's settings.json, to move settings from")
|
||||
args = ap.parse_args(argv)
|
||||
if not valid_sid(args.user_sid):
|
||||
ap.error(f"not a SID: {args.user_sid!r}")
|
||||
if not os.path.isfile(args.python):
|
||||
ap.error(f"no such interpreter: {args.python}")
|
||||
try:
|
||||
print(check(args.python))
|
||||
reset_data_dir()
|
||||
print(migrate.copy(args.user_settings))
|
||||
install(args.python, args.user_sid)
|
||||
except Exception as e: # setup.ps1 shows this and stops
|
||||
print(f"error: {type(e).__name__}: {e}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Moving the fan and RAM lighting settings from the user's settings.json to hw-settings.json.
|
||||
|
||||
setup.ps1 runs both halves, once per install; each is safe to run again:
|
||||
|
||||
python -m kurgan.hw.migrate copy USER_SETTINGS elevated: create hw-settings.json from the user's
|
||||
`cooling` and `lighting.memory`, unless it exists
|
||||
python -m kurgan.hw.migrate strip as the user: once hw-settings.json exists, remove
|
||||
them from settings.json, keeping a dated backup
|
||||
|
||||
An invalid file on either side stops the move (and setup) rather than lose a setting.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import copy as _copy
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
|
||||
from kurgan import paths
|
||||
from kurgan.hw import settings as hw_settings
|
||||
from kurgan.settings import SettingsError, validate, write_json_atomic
|
||||
|
||||
|
||||
def _read_json(path: str) -> dict | None:
|
||||
"""The file's contents, or None if it doesn't exist; SettingsError if it isn't valid JSON."""
|
||||
try:
|
||||
with open(path, encoding="utf-8") as stream:
|
||||
return json.load(stream)
|
||||
except FileNotFoundError:
|
||||
return None
|
||||
except ValueError as e:
|
||||
raise SettingsError(f"{path}: {e}") from None
|
||||
|
||||
|
||||
def hardware_sections(user: dict) -> dict:
|
||||
"""The parts of a user settings.json that belong to the hardware service."""
|
||||
out: dict = {}
|
||||
if isinstance(user.get("cooling"), dict):
|
||||
out["cooling"] = dict(user["cooling"])
|
||||
lighting = user.get("lighting")
|
||||
if isinstance(lighting, dict) and "memory" in lighting:
|
||||
out["lighting"] = {"memory": lighting["memory"]}
|
||||
return out
|
||||
|
||||
|
||||
def copy(user_path: str, hw_path: str = paths.HW_SETTINGS_PATH) -> str:
|
||||
"""Create hw-settings.json from the user's settings, unless it exists. Returns what it did."""
|
||||
if os.path.exists(hw_path):
|
||||
return f"{hw_path} already exists; left as it is"
|
||||
raw = _read_json(user_path)
|
||||
sections = {}
|
||||
if raw is not None:
|
||||
try:
|
||||
sections = hardware_sections(validate(raw))
|
||||
except SettingsError as e:
|
||||
raise SettingsError(f"{user_path}: {e}") from None
|
||||
try:
|
||||
data = hw_settings.validate(sections)
|
||||
except SettingsError as e:
|
||||
raise SettingsError(f"{user_path}'s fan or RAM settings can't move: {e}") from None
|
||||
write_json_atomic(hw_path, data)
|
||||
moved = [name for name, present in (("cooling", "cooling" in sections),
|
||||
("lighting.memory", "lighting" in sections)) if present]
|
||||
return f"Created {hw_path}" + (f" with {' and '.join(moved)} from {user_path}" if moved else " with the defaults")
|
||||
|
||||
|
||||
def strip(user_path: str = paths.SETTINGS_PATH, hw_path: str = paths.HW_SETTINGS_PATH, now: float | None = None) -> str:
|
||||
"""Remove the hardware sections from the user's settings.json, once hw-settings.json exists."""
|
||||
if not os.path.exists(hw_path):
|
||||
return f"{hw_path} doesn't exist yet; settings.json left as it is"
|
||||
raw = _read_json(user_path)
|
||||
if raw is None or not hardware_sections(raw):
|
||||
return f"Nothing to move out of {user_path}"
|
||||
stripped = _copy.deepcopy(raw)
|
||||
stripped.pop("cooling", None)
|
||||
if isinstance(stripped.get("lighting"), dict):
|
||||
stripped["lighting"].pop("memory", None)
|
||||
try:
|
||||
data = validate(stripped)
|
||||
except SettingsError as e:
|
||||
raise SettingsError(f"{user_path}: {e}") from None
|
||||
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
|
||||
backup = f"{user_path}.{stamp}.bak"
|
||||
shutil.copy2(user_path, backup)
|
||||
write_json_atomic(user_path, data)
|
||||
return f"Removed the fan and RAM lighting settings from {user_path} (now in {hw_path}); backup: {backup}"
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.migrate", description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
sub = ap.add_subparsers(dest="action", required=True)
|
||||
sub.add_parser("copy", help="create hw-settings.json (elevated)").add_argument("user_settings")
|
||||
sub.add_parser("strip", help="tidy the user's settings.json (as the user)")
|
||||
args = ap.parse_args(argv)
|
||||
try:
|
||||
if args.action == "copy":
|
||||
hw_settings.ensure_data_dir()
|
||||
print(copy(args.user_settings))
|
||||
else:
|
||||
print(strip())
|
||||
except (OSError, SettingsError) as e:
|
||||
print(f"error: {e}", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+3
-3
@@ -430,9 +430,9 @@ class PipeClient:
|
||||
_k32.WaitNamedPipeW(name, max(1, int(left * 1000)))
|
||||
continue
|
||||
if code == ERROR_FILE_NOT_FOUND:
|
||||
raise _error("the hardware service isn't running (no pipe)", code)
|
||||
raise PipeError("the hardware service isn't running (no pipe)", code)
|
||||
if code == ERROR_ACCESS_DENIED:
|
||||
raise _error("the hardware service's pipe refused this user", code)
|
||||
raise PipeError("the hardware service's pipe refused this user", code)
|
||||
raise _error(f"can't open {name}", code)
|
||||
self._handle = handle
|
||||
self._read_event, self._write_event = _event(), _event()
|
||||
@@ -460,7 +460,7 @@ class PipeClient:
|
||||
if chunk is None:
|
||||
raise PipeError(f"no reply from the hardware service within {timeout:g} s")
|
||||
if not chunk:
|
||||
raise _error("the hardware service closed the connection", ERROR_BROKEN_PIPE)
|
||||
raise PipeError("the hardware service closed the connection", ERROR_BROKEN_PIPE)
|
||||
self._lines += self._buffer.feed(chunk)
|
||||
return self._lines.pop(0)
|
||||
|
||||
|
||||
@@ -1,17 +1,21 @@
|
||||
# Sets up The Kurgan:
|
||||
# 1. installs the Python packages it needs (into the project's .venv if there is one)
|
||||
# 1. installs the Python packages it needs into the project's .venv (creating it if needed)
|
||||
# 2. installs PawnIO (signed driver used by LibreHardwareMonitor) for CPU sensors, top fans and RAM lighting
|
||||
# 3. removes the old startup tasks ("TT LCD Dashboard", and "The Kurgan" from when it ran with admin rights)
|
||||
# 4. with -RetireAIServices: stops and disables the "Strata Local Service" and "Qwen4 Local Service"
|
||||
# tasks, so The Kurgan runs whichever LLM server you select (re-enable them with uninstall.ps1)
|
||||
# 5. registers "The Kurgan" (hidden, at logon) as you, WITHOUT admin rights, so the tray's
|
||||
# 5. installs or updates the "The Kurgan hardware" Windows service (KurganHw: fans, CPU sensors,
|
||||
# RAM lighting; LocalSystem, starts at boot) and moves the fan and RAM lighting settings from
|
||||
# your settings.json to %ProgramData%\Kurgan\hw-settings.json (once)
|
||||
# 6. registers "The Kurgan" (hidden, at logon) as you, WITHOUT admin rights, so the tray's
|
||||
# "Start with Windows" can change it, and starts it; the web UI is at http://127.0.0.1:8080/
|
||||
#
|
||||
# Run from a normal (not elevated) PowerShell window:
|
||||
# powershell -ExecutionPolicy Bypass -File .\setup.ps1 [-RetireAIServices]
|
||||
# It asks for administrator rights (UAC) itself for steps 2-4.
|
||||
# It asks for administrator rights (UAC) itself for steps 2-5. Run it again after updating The Kurgan.
|
||||
|
||||
param([switch]$Elevated, [switch]$RetireAIServices)
|
||||
param([switch]$Elevated, [switch]$RetireAIServices, [string]$Python, [string]$BasePython, [string]$UserSid,
|
||||
[string]$UserSettings)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$TaskName = 'The Kurgan'
|
||||
@@ -29,30 +33,39 @@ if ($isAdmin -and -not $Elevated) {
|
||||
}
|
||||
|
||||
if (-not $isAdmin) {
|
||||
# Prefer the project's own .venv; otherwise use whichever python is on PATH.
|
||||
$venvPython = Join-Path $Here '.venv\Scripts\python.exe'
|
||||
if (Test-Path $venvPython) {
|
||||
$python = $venvPython
|
||||
} else {
|
||||
$python = (Get-Command python -ErrorAction Stop).Source
|
||||
Set-Location $Here
|
||||
# The project's own .venv: the hardware service runs from it too (hw_service.py adds its packages).
|
||||
$python = Join-Path $Here '.venv\Scripts\python.exe'
|
||||
if (-not (Test-Path $python)) {
|
||||
Write-Host "Creating the project's .venv..." -ForegroundColor Cyan
|
||||
& (Get-Command python -ErrorAction Stop).Source -m venv (Join-Path $Here '.venv')
|
||||
if ($LASTEXITCODE -ne 0) { throw "creating .venv failed" }
|
||||
}
|
||||
$inVenv = (& $python -c "import sys; print(int(sys.prefix != sys.base_prefix))") -eq '1'
|
||||
$pipArgs = if ($inVenv) { @() } else { @('--user') }
|
||||
$pythonw = Join-Path (Split-Path $python) 'pythonw.exe'
|
||||
if (-not (Test-Path $pythonw)) { throw "pythonw.exe not found next to $python" }
|
||||
|
||||
Write-Host "Installing Python packages into $(Split-Path (Split-Path $python))..." -ForegroundColor Cyan
|
||||
& $python -m pip install @pipArgs --quiet --disable-pip-version-check -r (Join-Path $Here 'requirements.txt')
|
||||
& $python -m pip install --quiet --disable-pip-version-check -r (Join-Path $Here 'requirements.txt')
|
||||
if ($LASTEXITCODE -ne 0) { throw "pip install failed" }
|
||||
|
||||
Write-Host "Requesting administrator rights for PawnIO and the old startup tasks..." -ForegroundColor Cyan
|
||||
$argList = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Elevated"
|
||||
# What the elevated part needs to know about you and this Python.
|
||||
$basePython = (& $python -c "import sys; print(sys._base_executable)").Trim() # the service runs this one
|
||||
$userSettings = (& $python -c "from kurgan import paths; print(paths.SETTINGS_PATH)").Trim()
|
||||
$userSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
||||
|
||||
Write-Host "Requesting administrator rights for PawnIO, the old startup tasks and the hardware service..." -ForegroundColor Cyan
|
||||
$argList = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Elevated -Python `"$python`" " +
|
||||
"-BasePython `"$basePython`" -UserSid $userSid -UserSettings `"$userSettings`""
|
||||
if ($RetireAIServices) { $argList += ' -RetireAIServices' }
|
||||
$p = Start-Process powershell -Verb RunAs -ArgumentList $argList -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0) { Write-Host "Setup stopped (the elevated part failed)." -ForegroundColor Red; exit $p.ExitCode }
|
||||
|
||||
# --- The Kurgan's startup task: as you, without admin rights --------------------------
|
||||
try {
|
||||
# --- the fan and RAM settings now live in hw-settings.json: tidy settings.json ------
|
||||
& $python -m kurgan.hw.migrate strip
|
||||
if ($LASTEXITCODE -ne 0) { throw "tidying settings.json failed (see above)" }
|
||||
|
||||
# --- The Kurgan's startup task: as you, without admin rights ----------------------
|
||||
$user = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
$action = New-ScheduledTaskAction -Execute $pythonw -Argument '-m kurgan' -WorkingDirectory $Here
|
||||
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
|
||||
@@ -65,9 +78,10 @@ if (-not $isAdmin) {
|
||||
-Force | Out-Null
|
||||
Start-ScheduledTask -TaskName $TaskName
|
||||
} catch {
|
||||
Write-Host "Registering the startup task failed: $_" -ForegroundColor Red
|
||||
Write-Host "Setup failed: $_" -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
& $python -m kurgan.hw.client # what the hardware service says
|
||||
Write-Host "Done. '$TaskName' is running and will start at every logon." -ForegroundColor Green
|
||||
Write-Host "Web UI: http://127.0.0.1:8080/ Log: $env:LOCALAPPDATA\Kurgan\kurgan.log"
|
||||
if (-not $RetireAIServices) {
|
||||
@@ -121,6 +135,16 @@ try {
|
||||
($_.Name -eq 'llama-server.exe' -and $_.CommandLine -like '*qwen4-35b-a3b\service\presets.ini*') }
|
||||
}
|
||||
|
||||
# --- the hardware service ------------------------------------------------------------
|
||||
# Checks that the base interpreter can run it, sets up %ProgramData%\Kurgan (admins write, users
|
||||
# read), moves the fan and RAM settings there once, then installs or updates and starts KurganHw.
|
||||
if (-not ($Python -and $BasePython -and $UserSid -and $UserSettings)) {
|
||||
throw "run setup.ps1 from a normal PowerShell window; it passes these on to the elevated part"
|
||||
}
|
||||
Set-Location $Here
|
||||
& $Python -m kurgan.hw.install --python $BasePython --user-sid $UserSid --user-settings $UserSettings
|
||||
if ($LASTEXITCODE -ne 0) { throw "installing the hardware service failed (see above)" }
|
||||
|
||||
} catch {
|
||||
Write-Host "Setup failed: $_" -ForegroundColor Red
|
||||
Read-Host "Press Enter to close"
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import contextlib
|
||||
import io
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
import win32security
|
||||
import win32service
|
||||
|
||||
from kurgan.hw import install
|
||||
from kurgan.hw import settings as hw_settings
|
||||
|
||||
|
||||
class InstallTest(unittest.TestCase):
|
||||
def test_the_image_path_runs_the_base_interpreter_isolated(self):
|
||||
self.assertEqual(install.image_path(r"C:\Python 3\python.exe", r"C:\Dev\the_kurgan\hw_service.py"),
|
||||
r'"C:\Python 3\python.exe" -I -S -B "C:\Dev\the_kurgan\hw_service.py"')
|
||||
|
||||
def test_recovery_restarts_after_5_10_and_60_seconds(self):
|
||||
actions = install.failure_actions()
|
||||
self.assertEqual(actions["Actions"], [(win32service.SC_ACTION_RESTART, 5000),
|
||||
(win32service.SC_ACTION_RESTART, 10000),
|
||||
(win32service.SC_ACTION_RESTART, 60000)])
|
||||
|
||||
def test_the_data_folder_is_owned_by_administrators_and_read_only_for_users(self):
|
||||
sd = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
|
||||
install.DATA_DIR_OWNER_SDDL + hw_settings.DATA_DIR_SDDL, win32security.SDDL_REVISION_1)
|
||||
owner = win32security.ConvertSidToStringSid(sd.GetSecurityDescriptorOwner())
|
||||
self.assertEqual(owner, "S-1-5-32-544")
|
||||
dacl = sd.GetSecurityDescriptorDacl()
|
||||
users = [dacl.GetAce(i) for i in range(dacl.GetAceCount())
|
||||
if win32security.ConvertSidToStringSid(dacl.GetAce(i)[2]) == "S-1-5-32-545"]
|
||||
self.assertEqual(len(users), 1)
|
||||
self.assertFalse(users[0][1] & 0x2) # FILE_WRITE_DATA
|
||||
|
||||
def test_the_check_runs_the_service_entry_point(self):
|
||||
self.assertTrue(install.check(sys._base_executable).startswith("ok: The Kurgan hardware"))
|
||||
with self.assertRaises(RuntimeError):
|
||||
install.check(sys.executable + "-missing")
|
||||
|
||||
def test_bad_arguments_are_refused_before_anything_changes(self):
|
||||
for argv in (["--python", sys._base_executable, "--user-sid", "nobody", "--user-settings", "x.json"],
|
||||
["--python", r"C:\nowhere\python.exe", "--user-sid", "S-1-5-21-1-2-3-1001",
|
||||
"--user-settings", "x.json"]):
|
||||
with self.subTest(argv=argv), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit):
|
||||
install.main(argv)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,86 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
from kurgan.hw import migrate
|
||||
from kurgan.settings import SettingsError
|
||||
|
||||
OLD_USER = {
|
||||
"cooling": {"profile": "quiet", "gpu_ports": [4, 5, 6], "cpu_ports": [1, 2, 3], "top_channels": [2, 5]},
|
||||
"lighting": {"case_fans": "chase", "memory": "temperature", "gpu": "off"},
|
||||
"ai": {"active": "strata"},
|
||||
"web": {"port": 8080},
|
||||
}
|
||||
|
||||
|
||||
class MigrateTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
directory = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(directory.cleanup)
|
||||
self.dir = directory.name
|
||||
self.user = os.path.join(self.dir, "settings.json")
|
||||
self.hw = os.path.join(self.dir, "ProgramData", "hw-settings.json")
|
||||
|
||||
def write(self, path, data):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(data if isinstance(data, str) else json.dumps(data))
|
||||
|
||||
def read(self, path):
|
||||
with open(path, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def test_the_fan_and_ram_settings_move_and_the_rest_stays(self):
|
||||
self.write(self.user, OLD_USER)
|
||||
self.assertIn("with cooling and lighting.memory", migrate.copy(self.user, self.hw))
|
||||
self.assertEqual(self.read(self.hw), {"cooling": OLD_USER["cooling"], "lighting": {"memory": "temperature"}})
|
||||
message = migrate.strip(self.user, self.hw, now=0)
|
||||
self.assertIn("backup", message)
|
||||
user = self.read(self.user)
|
||||
self.assertNotIn("cooling", user)
|
||||
self.assertEqual(user["lighting"], {"case_fans": "chase", "gpu": "off"})
|
||||
self.assertEqual(user["ai"]["active"], "strata")
|
||||
backups = [name for name in os.listdir(self.dir) if name.endswith(".bak")]
|
||||
self.assertEqual(len(backups), 1)
|
||||
self.assertEqual(self.read(os.path.join(self.dir, backups[0])), OLD_USER)
|
||||
|
||||
def test_running_it_again_changes_nothing(self):
|
||||
self.write(self.user, OLD_USER)
|
||||
migrate.copy(self.user, self.hw)
|
||||
migrate.strip(self.user, self.hw)
|
||||
hw, user = self.read(self.hw), self.read(self.user)
|
||||
self.write(self.user, {**user, "cooling": {"profile": "full"}}) # stale, e.g. from an old backup
|
||||
self.assertIn("already exists", migrate.copy(self.user, self.hw))
|
||||
self.assertEqual(self.read(self.hw), hw) # never overwritten
|
||||
migrate.strip(self.user, self.hw) # the stale section goes too
|
||||
self.assertEqual(self.read(self.user), user)
|
||||
self.assertIn("Nothing to move", migrate.strip(self.user, self.hw))
|
||||
|
||||
def test_no_user_settings_gives_the_defaults(self):
|
||||
self.assertIn("with the defaults", migrate.copy(self.user, self.hw))
|
||||
self.assertEqual(self.read(self.hw), {"cooling": {"profile": "balanced"}, "lighting": {"memory": "off"}})
|
||||
self.assertIn("Nothing to move", migrate.strip(self.user, self.hw))
|
||||
|
||||
def test_settings_json_is_left_alone_until_hw_settings_exists(self):
|
||||
self.write(self.user, OLD_USER)
|
||||
self.assertIn("doesn't exist yet", migrate.strip(self.user, self.hw))
|
||||
self.assertEqual(self.read(self.user), OLD_USER)
|
||||
|
||||
def test_an_invalid_file_stops_the_move(self):
|
||||
for bad in ("{not json", {"cooling": {"profile": "turbo"}}, {"extra": {}}):
|
||||
with self.subTest(bad=bad):
|
||||
self.write(self.user, bad)
|
||||
with self.assertRaises(SettingsError):
|
||||
migrate.copy(self.user, self.hw)
|
||||
self.assertFalse(os.path.exists(self.hw))
|
||||
self.write(self.hw, {"cooling": {"profile": "balanced"}})
|
||||
self.write(self.user, {"cooling": {"profile": "quiet"}, "web": {"port": 80}})
|
||||
with self.assertRaises(SettingsError):
|
||||
migrate.strip(self.user, self.hw)
|
||||
self.assertEqual(self.read(self.user)["web"]["port"], 80) # untouched
|
||||
self.assertFalse([name for name in os.listdir(self.dir) if name.endswith(".bak")])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
+10
-2
@@ -1,7 +1,9 @@
|
||||
# Removes The Kurgan's startup task and stops it (an LLM server it started stops with it).
|
||||
# Removes The Kurgan's startup task and stops it (an LLM server it started stops with it), and
|
||||
# removes the "The Kurgan hardware" service (KurganHw). Stopping the service leaves the case fans
|
||||
# at 100% and hands the top fans back to the BIOS curve.
|
||||
# -RestoreAIServices re-enables and starts the "Strata Local Service" and "Qwen4 Local Service" tasks
|
||||
# -RemovePawnIO also uninstalls PawnIO (leave it if LibreHardwareMonitor or FanControl uses it)
|
||||
# Settings stay in %LOCALAPPDATA%\Kurgan.
|
||||
# Settings stay in %LOCALAPPDATA%\Kurgan and %ProgramData%\Kurgan.
|
||||
param([switch]$RemovePawnIO, [switch]$RestoreAIServices)
|
||||
|
||||
$isAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
|
||||
@@ -23,6 +25,12 @@ Get-CimInstance Win32_Process -Filter "Name like 'python%.exe'" |
|
||||
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
||||
Write-Host "Removed 'The Kurgan'." -ForegroundColor Green
|
||||
|
||||
if (Get-Service -Name 'KurganHw' -ErrorAction SilentlyContinue) {
|
||||
Stop-Service -Name 'KurganHw' -Force -ErrorAction SilentlyContinue
|
||||
sc.exe delete KurganHw | Out-Null
|
||||
Write-Host "Removed the hardware service: case fans at 100%, top fans on the BIOS curve." -ForegroundColor Green
|
||||
}
|
||||
|
||||
if ($RestoreAIServices) {
|
||||
Start-Sleep -Seconds 2 # let the LLM server's port close
|
||||
foreach ($name in 'Strata Local Service', 'Qwen4 Local Service') {
|
||||
|
||||
Reference in new issue
Block a user