- 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>
163 lines
7.7 KiB
Python
163 lines
7.7 KiB
Python
"""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())
|