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 "<base python>" -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 <noreply@anthropic.com>
This commit is contained in:
1 parent
7190db733f
commit
3e84ab1322
4 files changed
+190
No files matched your search
@@ -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:
|
||||
|
||||
"<base Python>\\python.exe" -I -S -B "<repo>\\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
|
||||
Reference in new issue
Block a user