From 3e84ab1322c7540b7f27dfd335e0c6afcfd86c6a Mon Sep 17 00:00:00 2001 From: Semprini Date: Sat, 5 Dec 2026 19:30:25 +1300 Subject: [PATCH] Privilege split 5/11: host kurgan.hw as a Windows service (pywin32) - kurgan/hw/winservice.py: pywin32's ServiceFramework, hosted by the base interpreter's python.exe (PrepareToHostSingle + StartServiceCtrlDispatcher), not pythonservice.exe. The venv's python.exe is a redirector that starts the base interpreter as a child, and the service manager only talks to the process it started. Recorded as Decision 0002 in the vault. - Accepts stop and shutdown; both end the hardware loop, which leaves the case fans at 100% and hands the top fans back to the BIOS curve. An unexpected failure exits without reporting "stopped", so the recovery actions (set by setup.ps1: restart after 5 s, 10 s, 60 s) bring it back. - hw_service.py: the service's image, run as "" -I -S -B hw_service.py. It adds the repo and the venv's site-packages itself (pywin32's .pth bootstrap included), so the base interpreter's own packages never load and SYSTEM writes no .pyc into the repo. --check imports everything the service needs (setup.ps1 runs it first); started from a console it runs the service in the foreground. - requirements.txt: pywin32>=311 (312 has cp314 wheels). - Tests: 5 new (stop/shutdown, the run, failure exits, console fallback, and the bootstrap under the base interpreter in isolated mode). Co-Authored-By: Claude Opus 5.5 --- hw_service.py | 25 ++++++++++ kurgan/hw/winservice.py | 97 +++++++++++++++++++++++++++++++++++++ requirements.txt | 1 + tests/test_hw_winservice.py | 67 +++++++++++++++++++++++++ 4 files changed, 190 insertions(+) create mode 100644 hw_service.py create mode 100644 kurgan/hw/winservice.py create mode 100644 tests/test_hw_winservice.py diff --git a/hw_service.py b/hw_service.py new file mode 100644 index 0000000..0311231 --- /dev/null +++ b/hw_service.py @@ -0,0 +1,25 @@ +"""Entry point of the "The Kurgan hardware" Windows service (KurganHw); see kurgan/hw/winservice.py. + +The service manager runs it with the base interpreter (setup.ps1 installs it): + + "\\python.exe" -I -S -B "C:\\Dev\\the_kurgan\\hw_service.py" + +-I: isolated (no PYTHON* variables, no user site-packages, no current folder on the path); +-S: no automatic site-packages; -B: no .pyc files written into the repo by SYSTEM. This file +adds the repo and its .venv's packages, so the base interpreter's own packages are never loaded. + + ... hw_service.py --check can the service start? (setup.ps1 runs this before installing) + ... hw_service.py [-v] run it in a console instead (elevated, with the service stopped) +""" + +import os +import site +import sys + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +site.addsitedir(os.path.join(HERE, ".venv", "Lib", "site-packages")) # runs pywin32's .pth bootstrap + +from kurgan.hw.winservice import main # noqa: E402 + +sys.exit(main()) diff --git a/kurgan/hw/winservice.py b/kurgan/hw/winservice.py new file mode 100644 index 0000000..c8183e2 --- /dev/null +++ b/kurgan/hw/winservice.py @@ -0,0 +1,97 @@ +"""Hosting the hardware service in the Windows service manager, with pywin32 (Decision 0002). + +setup.ps1 installs it as the "KurganHw" service, LocalSystem, automatic start at boot: + + "\\python.exe" -I -S -B "\\hw_service.py" + +The base interpreter, not the venv's python.exe: on Windows that one is a redirector that runs +the real interpreter as a child process, and the service manager only talks to the process it +started. hw_service.py puts the repo and the venv's packages on the path itself. + +Stop and shutdown (the service accepts both) end the hardware loop, which leaves the case fans +at 100% and hands the top fans back to the BIOS curve. If the service fails unexpectedly the +process exits without reporting "stopped", so the service manager's recovery actions (restart +after 5 s, 10 s, then 60 s; set by setup.ps1) bring it back. +""" + +from __future__ import annotations + +import logging +import os +import sys +import threading + +import pywintypes +import servicemanager +import win32service +import win32serviceutil + +from kurgan import __version__ +from kurgan.hw import main as hw_main + +log = logging.getLogger("kurgan.hw") +ERROR_FAILED_SERVICE_CONTROLLER_CONNECT = 1063 # not started by the service manager + + +class KurganHwService(win32serviceutil.ServiceFramework): + _svc_name_ = hw_main.SERVICE_NAME + _svc_display_name_ = hw_main.SERVICE_DISPLAY_NAME + _svc_description_ = ("The Kurgan's hardware control: case and top fan curves with their fail-safes, " + "and the RAM lighting. The app talks to it over \\\\.\\pipe\\kurgan-hw.") + + def __init__(self, args): + super().__init__(args) + self.stop = threading.Event() + + def SvcStop(self) -> None: + self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING, waitHint=int(hw_main.STOP_SECONDS * 1000)) + self.stop.set() + + def SvcShutdown(self) -> None: # defining it makes the framework accept SERVICE_CONTROL_SHUTDOWN + self.SvcStop() + + def SvcDoRun(self) -> None: + try: + hw_main.setup_logging(console=False) + log.info("Starting %s %s as a service (pid %s)", hw_main.SERVICE_DISPLAY_NAME, __version__, os.getpid()) + mutex = hw_main.single_instance() + if mutex is None: + raise RuntimeError("another copy is running (python -m kurgan.hw in a console?)") + hw_main.serve(self.stop, hw_main.configured_user_sid()) + log.info("Stopped") + except BaseException: + fail() + + +def fail() -> None: + """Exit at once, without reporting "stopped", so the service manager restarts the service.""" + log.exception("The hardware service failed; exiting so the service manager restarts it") + logging.shutdown() + os._exit(1) + + +def check() -> int: + """What setup.ps1 runs before installing: can this interpreter load everything the service needs?""" + import pynvml # noqa: F401 (the GPU temperature) + + from kurgan.hw import service # noqa: F401 (and with it the fan control and the RAM lighting) + + print(f"ok: {hw_main.SERVICE_DISPLAY_NAME} {__version__}, Python {sys.version.split()[0]} " + f"at {sys.executable}") + return 0 + + +def main(argv: list[str] | None = None) -> int: + argv = sys.argv[1:] if argv is None else argv + if argv == ["--check"]: + return check() + if not argv: + servicemanager.Initialize() + servicemanager.PrepareToHostSingle(KurganHwService) + try: + servicemanager.StartServiceCtrlDispatcher() + return 0 + except pywintypes.error as e: + if e.winerror != ERROR_FAILED_SERVICE_CONTROLLER_CONNECT: + raise + return hw_main.main(argv) # started from a console: run there diff --git a/requirements.txt b/requirements.txt index efa5590..bb7caa2 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,4 @@ pillow>=10.1 numpy>=1.26 nvidia-ml-py>=12.0 +pywin32>=311 diff --git a/tests/test_hw_winservice.py b/tests/test_hw_winservice.py new file mode 100644 index 0000000..3a231df --- /dev/null +++ b/tests/test_hw_winservice.py @@ -0,0 +1,67 @@ +import subprocess +import sys +import threading +import unittest +from unittest.mock import Mock, patch + +import win32service + +from kurgan import paths +from kurgan.hw import winservice +from kurgan.hw.winservice import KurganHwService + + +def bare_service() -> KurganHwService: + """The service object without registering with a service manager we aren't running under.""" + service = KurganHwService.__new__(KurganHwService) + service.stop = threading.Event() + service.ReportServiceStatus = Mock() + return service + + +class WinServiceTest(unittest.TestCase): + def test_accepts_stop_and_shutdown_and_both_end_the_loop(self): + accepted = bare_service().GetAcceptedControls() + self.assertTrue(accepted & win32service.SERVICE_ACCEPT_STOP) + self.assertTrue(accepted & win32service.SERVICE_ACCEPT_SHUTDOWN) + for control in ("SvcStop", "SvcShutdown"): + with self.subTest(control=control): + service = bare_service() + getattr(service, control)() + self.assertTrue(service.stop.is_set()) + self.assertEqual(service.ReportServiceStatus.call_args.args[0], win32service.SERVICE_STOP_PENDING) + + def test_runs_until_stopped(self): + service = bare_service() + with patch("kurgan.hw.main.setup_logging"), patch("kurgan.hw.main.single_instance", return_value=1), \ + patch("kurgan.hw.main.configured_user_sid", return_value="S-1-5-21-1-2-3-1001"), \ + patch("kurgan.hw.main.serve") as serve, patch("kurgan.hw.winservice.fail") as fail: + service.SvcDoRun() + serve.assert_called_once_with(service.stop, "S-1-5-21-1-2-3-1001") + fail.assert_not_called() + + def test_an_unexpected_failure_exits_so_the_service_manager_restarts_it(self): + service = bare_service() + with patch("kurgan.hw.main.setup_logging"), patch("kurgan.hw.main.single_instance", return_value=None), \ + patch("kurgan.hw.main.serve") as serve, patch("kurgan.hw.winservice.fail") as fail: + service.SvcDoRun() # a console copy already holds the mutex + serve.assert_not_called() + fail.assert_called_once() + + def test_started_from_a_console_it_runs_there(self): + with patch("kurgan.hw.main.main", return_value=7) as console: + self.assertEqual(winservice.main([]), 7) # the service manager refused us: not a service + console.assert_called_once_with([]) + with patch("kurgan.hw.main.main", return_value=0) as console: + winservice.main(["-v"]) + console.assert_called_once_with(["-v"]) + + def test_the_bootstrap_loads_under_the_base_interpreter_in_isolated_mode(self): + result = subprocess.run([sys._base_executable, "-I", "-S", "-B", f"{paths.PROJECT_DIR}\\hw_service.py", + "--check"], capture_output=True, text=True, timeout=60) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(result.stdout.startswith("ok: The Kurgan hardware"), result.stdout) + + +if __name__ == "__main__": + unittest.main()