- kurgan/ai/launcher.py: the app is unelevated now, so the servers are started with CreateProcessW, still suspended into their own kill-on-close job object and with an explicit handle list (only the log and NUL are inherited). Gone: the copy of Explorer's token (CreateProcessWithTokenW), the Safer "normal user" token and CreateProcessAsUserW, and with them the AI service's wait for the desktop at logon. - launch() refuses (PermissionError) if The Kurgan itself is elevated, rather than pass admin rights on to a model server; this also covers opening the browser. - Tests: the handle list is checked for real (an inheritable, unlisted handle doesn't reach the child; a control run without the list leaks it), and an elevated app starts nothing. The launch tests skip when the suite itself runs elevated. - The UI's server token label and the README's launcher paragraph follow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
330 lines
15 KiB
Python
330 lines
15 KiB
Python
"""Start the AI servers as ordinary child processes, each in its own job object.
|
|
|
|
The Kurgan runs without admin rights (only the hardware service, kurgan.hw, is elevated), so
|
|
its children are what any program the user starts would be: medium integrity, not elevated,
|
|
in the desktop's logon session. launch() refuses to start anything if The Kurgan itself has
|
|
been run elevated, rather than hand a model server admin rights.
|
|
|
|
Each server gets its own job object that kills everything in it when The Kurgan closes the
|
|
job, including the model processes the server starts itself; a crashed Kurgan leaves no
|
|
orphan holding VRAM or a port. stdout/stderr go to a log file, and an explicit handle list
|
|
means the log and NUL handles are all the child inherits.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import ctypes
|
|
import ctypes.wintypes as wt
|
|
import logging
|
|
import os
|
|
import subprocess
|
|
import threading
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
|
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
|
|
|
|
TOKEN_INTEGRITY_LEVEL = 25
|
|
TOKEN_ELEVATION = 20
|
|
|
|
CREATE_SUSPENDED = 0x4
|
|
CREATE_NEW_PROCESS_GROUP = 0x200
|
|
CREATE_UNICODE_ENVIRONMENT = 0x400
|
|
EXTENDED_STARTUPINFO_PRESENT = 0x80000
|
|
CREATE_NO_WINDOW = 0x08000000
|
|
STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES = 0x1, 0x100
|
|
SW_HIDE = 0
|
|
PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x20002
|
|
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000
|
|
JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9
|
|
GENERIC_READ, GENERIC_WRITE = 0x80000000, 0x40000000
|
|
FILE_APPEND_DATA = 0x4
|
|
SYNCHRONIZE = 0x100000
|
|
FILE_SHARE_ALL = 0x7
|
|
OPEN_EXISTING, OPEN_ALWAYS = 3, 4
|
|
INVALID_HANDLE = wt.HANDLE(-1).value
|
|
WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
|
|
STILL_ACTIVE = 259
|
|
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
|
TOKEN_QUERY = 0x8
|
|
|
|
|
|
class SecurityAttributes(ctypes.Structure):
|
|
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", wt.LPVOID), ("bInheritHandle", wt.BOOL)]
|
|
|
|
|
|
class StartupInfo(ctypes.Structure):
|
|
_fields_ = [("cb", wt.DWORD), ("lpReserved", wt.LPWSTR), ("lpDesktop", wt.LPWSTR), ("lpTitle", wt.LPWSTR),
|
|
("dwX", wt.DWORD), ("dwY", wt.DWORD), ("dwXSize", wt.DWORD), ("dwYSize", wt.DWORD),
|
|
("dwXCountChars", wt.DWORD), ("dwYCountChars", wt.DWORD), ("dwFillAttribute", wt.DWORD),
|
|
("dwFlags", wt.DWORD), ("wShowWindow", wt.WORD), ("cbReserved2", wt.WORD),
|
|
("lpReserved2", ctypes.c_void_p), ("hStdInput", wt.HANDLE), ("hStdOutput", wt.HANDLE),
|
|
("hStdError", wt.HANDLE)]
|
|
|
|
|
|
class StartupInfoEx(ctypes.Structure):
|
|
_fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", ctypes.c_void_p)]
|
|
|
|
|
|
class ProcessInformation(ctypes.Structure):
|
|
_fields_ = [("hProcess", wt.HANDLE), ("hThread", wt.HANDLE), ("dwProcessId", wt.DWORD),
|
|
("dwThreadId", wt.DWORD)]
|
|
|
|
|
|
class SidAndAttributes(ctypes.Structure):
|
|
_fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)]
|
|
|
|
|
|
class BasicLimits(ctypes.Structure):
|
|
_fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64),
|
|
("LimitFlags", wt.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t),
|
|
("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wt.DWORD),
|
|
("Affinity", ctypes.c_size_t), ("PriorityClass", wt.DWORD), ("SchedulingClass", wt.DWORD)]
|
|
|
|
|
|
class ExtendedLimits(ctypes.Structure):
|
|
_fields_ = [("BasicLimitInformation", BasicLimits), ("IoInfo", ctypes.c_uint64 * 6),
|
|
("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t),
|
|
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)]
|
|
|
|
|
|
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)]
|
|
_adv.GetTokenInformation.restype = wt.BOOL
|
|
_adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
|
|
_adv.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte)
|
|
_adv.GetSidSubAuthority.argtypes = [ctypes.c_void_p, wt.DWORD]
|
|
_adv.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD)
|
|
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
|
|
_adv.OpenProcessToken.restype = wt.BOOL
|
|
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
|
_k32.CloseHandle.restype = wt.BOOL
|
|
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD,
|
|
wt.DWORD, wt.HANDLE]
|
|
_k32.CreateFileW.restype = wt.HANDLE
|
|
_k32.CreateJobObjectW.argtypes = [wt.LPVOID, wt.LPCWSTR]
|
|
_k32.CreateJobObjectW.restype = wt.HANDLE
|
|
_k32.SetInformationJobObject.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD]
|
|
_k32.SetInformationJobObject.restype = wt.BOOL
|
|
_k32.AssignProcessToJobObject.argtypes = [wt.HANDLE, wt.HANDLE]
|
|
_k32.AssignProcessToJobObject.restype = wt.BOOL
|
|
_k32.TerminateJobObject.argtypes = [wt.HANDLE, wt.UINT]
|
|
_k32.TerminateJobObject.restype = wt.BOOL
|
|
_k32.TerminateProcess.argtypes = [wt.HANDLE, wt.UINT]
|
|
_k32.TerminateProcess.restype = wt.BOOL
|
|
_k32.ResumeThread.argtypes = [wt.HANDLE]
|
|
_k32.ResumeThread.restype = wt.DWORD
|
|
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
|
_k32.WaitForSingleObject.restype = wt.DWORD
|
|
_k32.GetExitCodeProcess.argtypes = [wt.HANDLE, ctypes.POINTER(wt.DWORD)]
|
|
_k32.GetExitCodeProcess.restype = wt.BOOL
|
|
_k32.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, wt.DWORD, wt.DWORD, ctypes.POINTER(ctypes.c_size_t)]
|
|
_k32.InitializeProcThreadAttributeList.restype = wt.BOOL
|
|
_k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_size_t, wt.LPVOID, ctypes.c_size_t,
|
|
wt.LPVOID, wt.LPVOID]
|
|
_k32.UpdateProcThreadAttribute.restype = wt.BOOL
|
|
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
|
|
_k32.DeleteProcThreadAttributeList.restype = None
|
|
_k32.GetCurrentProcess.restype = wt.HANDLE
|
|
_k32.CreateProcessW.argtypes = [wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD, wt.LPVOID,
|
|
wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
|
|
_k32.CreateProcessW.restype = wt.BOOL
|
|
|
|
_launch_lock = threading.Lock()
|
|
|
|
|
|
def _check(ok, what: str):
|
|
if not ok:
|
|
raise ctypes.WinError(ctypes.get_last_error(), f"{what} failed")
|
|
return ok
|
|
|
|
|
|
def _describe_token(token: wt.HANDLE) -> dict:
|
|
size = wt.DWORD()
|
|
_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size))
|
|
buf = ctypes.create_string_buffer(size.value)
|
|
_check(_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buf, size, ctypes.byref(size)),
|
|
"GetTokenInformation(IntegrityLevel)")
|
|
sid = SidAndAttributes.from_buffer(buf).Sid
|
|
rid = _adv.GetSidSubAuthority(sid, _adv.GetSidSubAuthorityCount(sid)[0] - 1)[0]
|
|
elevated = wt.DWORD()
|
|
_check(_adv.GetTokenInformation(token, TOKEN_ELEVATION, ctypes.byref(elevated), 4, ctypes.byref(size)),
|
|
"GetTokenInformation(Elevation)")
|
|
names = {0x1000: "low", 0x2000: "medium", 0x2100: "medium-plus", 0x3000: "high", 0x4000: "system"}
|
|
return {"integrity": names.get(rid, hex(rid)), "elevated": bool(elevated.value)}
|
|
|
|
|
|
def token_info(process_handle=None) -> dict:
|
|
"""{"integrity": "medium"|"high"|..., "elevated": bool} for a process (default: this one)."""
|
|
token = wt.HANDLE()
|
|
handle = process_handle if process_handle is not None else _k32.GetCurrentProcess()
|
|
_check(_adv.OpenProcessToken(handle, TOKEN_QUERY, ctypes.byref(token)), "OpenProcessToken")
|
|
try:
|
|
return _describe_token(token)
|
|
finally:
|
|
_k32.CloseHandle(token)
|
|
|
|
|
|
_ELEVATED: bool | None = None
|
|
|
|
|
|
def elevated() -> bool:
|
|
global _ELEVATED
|
|
if _ELEVATED is None:
|
|
_ELEVATED = token_info()["elevated"]
|
|
return _ELEVATED
|
|
|
|
|
|
def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE:
|
|
sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True)
|
|
handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None)
|
|
if handle == INVALID_HANDLE or not handle:
|
|
raise ctypes.WinError(ctypes.get_last_error(), f"Opening {path} failed")
|
|
return handle
|
|
|
|
|
|
def _environment_block(env: dict[str, str]) -> ctypes.Array:
|
|
items = sorted(env.items(), key=lambda kv: kv[0].upper())
|
|
text = "".join(f"{k}={v}\0" for k, v in items) + "\0"
|
|
return ctypes.create_unicode_buffer(text, len(text))
|
|
|
|
|
|
def child_environment(extra: dict[str, str] | None = None) -> dict[str, str]:
|
|
env = dict(os.environ)
|
|
# The Kurgan pins OpenBLAS to one thread for itself (see kurgan/__init__.py); the servers get the default.
|
|
if env.get("KURGAN_PINNED_OPENBLAS") == "1":
|
|
env.pop("OPENBLAS_NUM_THREADS", None)
|
|
env.pop("KURGAN_PINNED_OPENBLAS", None)
|
|
env.update(extra or {})
|
|
return env
|
|
|
|
|
|
class ChildProcess:
|
|
"""A launched server: poll/wait/kill like subprocess.Popen, plus the job it runs in."""
|
|
|
|
def __init__(self, pid: int, process: wt.HANDLE, job: wt.HANDLE, argv: list[str]):
|
|
self.pid = pid
|
|
self.argv = argv
|
|
self._process = process
|
|
self._job = job
|
|
self.returncode: int | None = None
|
|
try:
|
|
self.token = token_info(process)
|
|
except OSError as e:
|
|
log.warning("Could not read the token of process %s: %s", pid, e)
|
|
self.token = {"integrity": "unknown", "elevated": None}
|
|
|
|
def poll(self) -> int | None:
|
|
return self.wait(0)
|
|
|
|
def wait(self, timeout: float | None = None) -> int | None:
|
|
if self.returncode is not None:
|
|
return self.returncode
|
|
if self._process is None:
|
|
return None
|
|
ms = 0xFFFFFFFF if timeout is None else max(0, int(timeout * 1000))
|
|
if _k32.WaitForSingleObject(self._process, ms) != WAIT_OBJECT_0:
|
|
return None
|
|
code = wt.DWORD()
|
|
_check(_k32.GetExitCodeProcess(self._process, ctypes.byref(code)), "GetExitCodeProcess")
|
|
self.returncode = code.value
|
|
return self.returncode
|
|
|
|
def kill(self) -> None:
|
|
"""End the server and everything it started."""
|
|
if self._job:
|
|
_k32.TerminateJobObject(self._job, 1)
|
|
elif self._process:
|
|
_k32.TerminateProcess(self._process, 1)
|
|
|
|
def close(self) -> None:
|
|
"""Release the handles; closing the job also kills anything still in it."""
|
|
for name in ("_process", "_job"):
|
|
handle = getattr(self, name)
|
|
if handle:
|
|
_k32.CloseHandle(handle)
|
|
setattr(self, name, None)
|
|
|
|
def __del__(self):
|
|
try:
|
|
self.close()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None,
|
|
contained: bool = True) -> ChildProcess:
|
|
"""Start argv windowless, with stdout/stderr appended to log_path (None: discarded).
|
|
|
|
contained: put it in its own kill-on-close job (servers). Without it the process outlives
|
|
the returned handle (used to open the browser). OSError if this process is elevated."""
|
|
if elevated():
|
|
raise PermissionError("The Kurgan is running with admin rights, so it starts nothing (its children "
|
|
"would get them too); run it from its logon task, which setup.ps1 registers "
|
|
"without them")
|
|
if log_path is not None:
|
|
os.makedirs(os.path.dirname(log_path), exist_ok=True)
|
|
with _launch_lock:
|
|
job = out = nul = None
|
|
attributes = None
|
|
try:
|
|
if contained:
|
|
job = _check(_k32.CreateJobObjectW(None, None), "CreateJobObject")
|
|
limits = ExtendedLimits()
|
|
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
_check(_k32.SetInformationJobObject(job, JOB_OBJECT_EXTENDED_LIMIT_INFORMATION,
|
|
ctypes.byref(limits), ctypes.sizeof(limits)),
|
|
"SetInformationJobObject")
|
|
out = (_inheritable(log_path, FILE_APPEND_DATA | SYNCHRONIZE, OPEN_ALWAYS) if log_path is not None
|
|
else _inheritable("NUL", GENERIC_WRITE, OPEN_EXISTING))
|
|
nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING)
|
|
command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
|
|
block = _environment_block(env if env is not None else child_environment())
|
|
flags = (CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP
|
|
| EXTENDED_STARTUPINFO_PRESENT)
|
|
pi = ProcessInformation()
|
|
size = ctypes.c_size_t()
|
|
_k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
|
|
attributes = ctypes.create_string_buffer(size.value)
|
|
_check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)),
|
|
"InitializeProcThreadAttributeList")
|
|
handles = (wt.HANDLE * 2)(out, nul) # all the child inherits
|
|
_check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles,
|
|
ctypes.sizeof(handles), None, None),
|
|
"UpdateProcThreadAttribute")
|
|
info = StartupInfoEx()
|
|
info.StartupInfo.cb = ctypes.sizeof(StartupInfoEx)
|
|
info.StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
|
|
info.StartupInfo.wShowWindow = SW_HIDE
|
|
info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out
|
|
info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p)
|
|
_check(_k32.CreateProcessW(None, command, None, None, True, flags, block, cwd,
|
|
ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}")
|
|
if job and not _k32.AssignProcessToJobObject(job, pi.hProcess):
|
|
error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
|
|
_k32.TerminateProcess(pi.hProcess, 1)
|
|
_k32.CloseHandle(pi.hThread)
|
|
_k32.CloseHandle(pi.hProcess)
|
|
raise error
|
|
_k32.ResumeThread(pi.hThread)
|
|
_k32.CloseHandle(pi.hThread)
|
|
child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv)
|
|
job = None # owned by the child object now
|
|
log.info("Started %s (pid %s, %s integrity%s)", os.path.basename(argv[0]), child.pid,
|
|
child.token["integrity"], ", ELEVATED" if child.token["elevated"] else "")
|
|
return child
|
|
finally:
|
|
if attributes is not None:
|
|
_k32.DeleteProcThreadAttributeList(attributes)
|
|
for handle in (out, nul, job):
|
|
if handle:
|
|
_k32.CloseHandle(handle)
|
|
|
|
|
|
def open_url(url: str) -> None:
|
|
"""Open a web page in the default browser (never elevated: launch() refuses if we are)."""
|
|
rundll = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "rundll32.exe")
|
|
child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None,
|
|
contained=False)
|
|
child.close()
|