fix(gateway): request graceful Windows shutdown (#6353)
* fix(gateway): request graceful Windows shutdown * docs(cli): simplify Windows gateway stop guidance * test(gateway): compare native Windows owner SIDs
This commit is contained in:
1 parent
fd30fda8a2
commit
73a55e0b2f
7 files changed
+554
-25
No files matched your search
@@ -980,6 +980,10 @@ def _run_gateway(
|
||||
logger.info("Last local client disappeared; stopping on-demand gateway")
|
||||
|
||||
tasks.extend([
|
||||
asyncio.create_task(
|
||||
gateway_runtime.wait_for_shutdown_request(shutdown_event),
|
||||
name="nanobot-gateway-stop-request",
|
||||
),
|
||||
asyncio.create_task(
|
||||
watch_config_file(
|
||||
Path(config_path),
|
||||
|
||||
@@ -20,10 +20,12 @@ from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Generator, Literal, cast
|
||||
|
||||
from filelock import FileLock
|
||||
from filelock import FileLock, Timeout
|
||||
from loguru import logger
|
||||
|
||||
from nanobot.config.home import get_selected_home_path
|
||||
from nanobot.config.paths import get_data_dir
|
||||
from nanobot.gateway.windows_shutdown import WindowsShutdownEvent, request_windows_shutdown
|
||||
from nanobot.process_runtime import (
|
||||
ManagedProcessRuntime,
|
||||
ProcessResult,
|
||||
@@ -235,6 +237,7 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
|
||||
subprocess_run=subprocess_run,
|
||||
sleep=sleep,
|
||||
)
|
||||
self._shutdown_signal: WindowsShutdownEvent | None = None
|
||||
|
||||
def _build_child_command(self, options: GatewayStartOptions) -> list[str]:
|
||||
return build_gateway_command(self.python_executable, options)
|
||||
@@ -339,12 +342,66 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
|
||||
|
||||
@contextmanager
|
||||
def foreground_instance(self, options: GatewayStartOptions) -> Generator[None]:
|
||||
"""Publish this foreground gateway while it is available to local clients."""
|
||||
self._claim_current_process(options)
|
||||
"""Publish this process and own its stop signal across asyncio.run()."""
|
||||
shutdown_signal = None
|
||||
if self.platform_name == "Windows" and os.name == "nt":
|
||||
identity = self.process_identity(os.getpid())
|
||||
if not isinstance(identity, str):
|
||||
raise OSError("Cannot identify the gateway process for Windows shutdown")
|
||||
shutdown_signal = WindowsShutdownEvent(os.getpid(), identity)
|
||||
self._shutdown_signal = shutdown_signal
|
||||
try:
|
||||
yield
|
||||
self._claim_current_process(options)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
self._release_current_process()
|
||||
finally:
|
||||
self._release_current_process()
|
||||
self._shutdown_signal = None
|
||||
if shutdown_signal is not None:
|
||||
shutdown_signal.close()
|
||||
|
||||
async def wait_for_shutdown_request(self, shutdown_event: asyncio.Event) -> None:
|
||||
"""Bridge the local Windows signal to the application's existing shutdown."""
|
||||
signal = self._shutdown_signal
|
||||
if signal is None:
|
||||
return
|
||||
waiter = asyncio.create_task(asyncio.to_thread(signal.wait))
|
||||
try:
|
||||
await asyncio.shield(waiter)
|
||||
logger.info("Gateway shutdown requested by local CLI")
|
||||
shutdown_event.set()
|
||||
finally:
|
||||
# Cancelling to_thread alone leaves its native wait alive. Wake it
|
||||
# before asyncio.run drains the executor and the owner closes the handle.
|
||||
signal.signal()
|
||||
await waiter
|
||||
|
||||
def _terminate_windows(self, pid: int, *, timeout_s: int) -> bool:
|
||||
state = self._read_state()
|
||||
identity = self._process_identity(pid)
|
||||
if identity is None:
|
||||
return not self._is_pid_running(pid)
|
||||
if self._process_identity_match(state, pid) != "match":
|
||||
return False
|
||||
requested = False
|
||||
if isinstance(identity, str) and state is not None:
|
||||
try:
|
||||
requested = request_windows_shutdown(pid, identity, state.get("shutdown_token"))
|
||||
except OSError as exc:
|
||||
logger.warning("Could not request gateway shutdown: {}", exc)
|
||||
if requested and self._wait_for_exit(pid, timeout_s):
|
||||
return True
|
||||
current_identity = self._process_identity(pid)
|
||||
if current_identity is None:
|
||||
return not self._is_pid_running(pid)
|
||||
if current_identity != identity:
|
||||
return False
|
||||
if requested:
|
||||
logger.warning("Gateway did not exit within {}s; forcing PID tree {}", timeout_s, pid)
|
||||
else:
|
||||
logger.warning("Gateway shutdown signal unavailable; forcing PID tree {}", pid)
|
||||
return super()._terminate_windows(pid, timeout_s=timeout_s)
|
||||
|
||||
def _claim_current_process(self, options: GatewayStartOptions) -> GatewayLaunchMode:
|
||||
lease = GatewayClientLease(self, kind="gateway-foreground")
|
||||
@@ -389,6 +446,9 @@ class GatewayRuntime(ManagedProcessRuntime[GatewayStartOptions]):
|
||||
state.pop("pending_pid_handoff", None)
|
||||
state.pop("stable_identity", None)
|
||||
state.update(self.process_identity_record(pid))
|
||||
state.pop("shutdown_token", None)
|
||||
if self._shutdown_signal is not None:
|
||||
state["shutdown_token"] = self._shutdown_signal.token
|
||||
self._write_state(state)
|
||||
if launch_mode == "foreground":
|
||||
lease._try_mark_persistent_locked()
|
||||
@@ -521,7 +581,13 @@ class GatewayClientLease:
|
||||
|
||||
def begin_orphan_shutdown(self) -> bool:
|
||||
"""Commit shutdown only while an on-demand gateway still has no clients."""
|
||||
with self.transition_lock, self.lifecycle_lock, self.lock:
|
||||
# Explicit stop holds this lock while waiting for us to exit. Never
|
||||
# block the gateway loop (or an executor being drained) behind it.
|
||||
try:
|
||||
transition = self.transition_lock.acquire(timeout=0)
|
||||
except Timeout:
|
||||
return False
|
||||
with transition, self.lifecycle_lock, self.lock:
|
||||
state = self._live_state()
|
||||
if not bool(state.get("auto_stop")) or self._clients(state):
|
||||
self._write_or_clear(state)
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
"""User-private, process-bound Windows gateway shutdown signals."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import re
|
||||
import uuid
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
from ctypes import wintypes
|
||||
from functools import lru_cache
|
||||
from typing import Any
|
||||
|
||||
|
||||
class _SecurityAttributes(ctypes.Structure):
|
||||
_fields_ = [
|
||||
("length", wintypes.DWORD),
|
||||
("descriptor", wintypes.LPVOID),
|
||||
("inherit", wintypes.BOOL),
|
||||
]
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _kernel32() -> Any:
|
||||
kernel = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||
kernel.GetCurrentProcess.restype = wintypes.HANDLE
|
||||
kernel.CreateEventW.argtypes = [
|
||||
ctypes.POINTER(_SecurityAttributes), wintypes.BOOL, wintypes.BOOL, wintypes.LPCWSTR,
|
||||
]
|
||||
kernel.CreateEventW.restype = wintypes.HANDLE
|
||||
kernel.OpenEventW.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.LPCWSTR]
|
||||
kernel.OpenEventW.restype = wintypes.HANDLE
|
||||
kernel.SetEvent.argtypes = [wintypes.HANDLE]
|
||||
kernel.SetEvent.restype = wintypes.BOOL
|
||||
kernel.WaitForSingleObject.argtypes = [wintypes.HANDLE, wintypes.DWORD]
|
||||
kernel.WaitForSingleObject.restype = wintypes.DWORD
|
||||
kernel.CloseHandle.argtypes = [wintypes.HANDLE]
|
||||
kernel.CloseHandle.restype = wintypes.BOOL
|
||||
kernel.LocalFree.argtypes = [wintypes.LPVOID]
|
||||
kernel.LocalFree.restype = wintypes.LPVOID
|
||||
return kernel
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _private_security() -> Generator[_SecurityAttributes]:
|
||||
kernel = _kernel32()
|
||||
security = ctypes.WinDLL("advapi32", use_last_error=True)
|
||||
security.OpenProcessToken.argtypes = [
|
||||
wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE),
|
||||
]
|
||||
security.OpenProcessToken.restype = wintypes.BOOL
|
||||
security.GetTokenInformation.argtypes = [
|
||||
wintypes.HANDLE, ctypes.c_int, wintypes.LPVOID, wintypes.DWORD,
|
||||
ctypes.POINTER(wintypes.DWORD),
|
||||
]
|
||||
security.GetTokenInformation.restype = wintypes.BOOL
|
||||
security.ConvertSidToStringSidW.argtypes = [
|
||||
wintypes.LPVOID, ctypes.POINTER(wintypes.LPWSTR),
|
||||
]
|
||||
security.ConvertSidToStringSidW.restype = wintypes.BOOL
|
||||
security.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
|
||||
wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(wintypes.LPVOID), wintypes.LPVOID,
|
||||
]
|
||||
security.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wintypes.BOOL
|
||||
token = wintypes.HANDLE()
|
||||
if not security.OpenProcessToken(kernel.GetCurrentProcess(), 0x0008, ctypes.byref(token)):
|
||||
raise ctypes.WinError()
|
||||
sid_text = wintypes.LPWSTR()
|
||||
descriptor = wintypes.LPVOID()
|
||||
try:
|
||||
size = wintypes.DWORD()
|
||||
security.GetTokenInformation(token, 1, None, 0, ctypes.byref(size)) # TokenUser
|
||||
if not size.value:
|
||||
raise ctypes.WinError()
|
||||
user = ctypes.create_string_buffer(size.value)
|
||||
if not security.GetTokenInformation(token, 1, user, len(user), ctypes.byref(size)):
|
||||
raise ctypes.WinError()
|
||||
sid = ctypes.cast(user, ctypes.POINTER(wintypes.LPVOID))[0]
|
||||
if not security.ConvertSidToStringSidW(sid, ctypes.byref(sid_text)):
|
||||
raise ctypes.WinError()
|
||||
if not security.ConvertStringSecurityDescriptorToSecurityDescriptorW(
|
||||
f"O:{sid_text.value}D:P(A;;GA;;;{sid_text.value})", 1,
|
||||
ctypes.byref(descriptor), None,
|
||||
):
|
||||
raise ctypes.WinError()
|
||||
yield _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), descriptor, False)
|
||||
finally:
|
||||
if descriptor:
|
||||
kernel.LocalFree(descriptor)
|
||||
if sid_text:
|
||||
kernel.LocalFree(sid_text)
|
||||
kernel.CloseHandle(token)
|
||||
|
||||
|
||||
def _event_name(pid: int, identity: str, token: str) -> str:
|
||||
return rf"Local\nanobot-gateway-stop-{pid}-{identity}-{token}"
|
||||
|
||||
|
||||
class WindowsShutdownEvent:
|
||||
"""Own one latched signal; close only after the native waiter has drained."""
|
||||
|
||||
def __init__(self, pid: int, identity: str) -> None:
|
||||
self.token = uuid.uuid4().hex
|
||||
kernel = _kernel32()
|
||||
with _private_security() as security:
|
||||
ctypes.set_last_error(0)
|
||||
handle = kernel.CreateEventW(
|
||||
ctypes.byref(security), True, False, _event_name(pid, identity, self.token),
|
||||
)
|
||||
error = ctypes.get_last_error()
|
||||
if not handle:
|
||||
raise ctypes.WinError(error)
|
||||
if error == 183: # ERROR_ALREADY_EXISTS: the requested DACL was not applied.
|
||||
kernel.CloseHandle(handle)
|
||||
raise OSError("Gateway shutdown event already exists")
|
||||
self._handle: int | None = int(handle)
|
||||
|
||||
def wait(self) -> None:
|
||||
"""Block a worker, never the event loop; signal() also wakes cancellation."""
|
||||
if _kernel32().WaitForSingleObject(self._handle, 0xFFFFFFFF) != 0:
|
||||
raise ctypes.WinError()
|
||||
|
||||
def signal(self) -> None:
|
||||
if not _kernel32().SetEvent(self._handle):
|
||||
raise ctypes.WinError()
|
||||
|
||||
def close(self) -> None:
|
||||
if self._handle is not None:
|
||||
_kernel32().CloseHandle(self._handle)
|
||||
self._handle = None
|
||||
|
||||
|
||||
def request_windows_shutdown(pid: int, identity: str, token: object) -> bool:
|
||||
"""Signal only a validated token in this exact process-birth namespace."""
|
||||
if not isinstance(token, str) or re.fullmatch(r"[0-9a-f]{32}", token) is None:
|
||||
return False
|
||||
kernel = _kernel32()
|
||||
handle = kernel.OpenEventW(0x0002, False, _event_name(pid, identity, token))
|
||||
if not handle:
|
||||
error = ctypes.get_last_error()
|
||||
if error == 2: # The process exited, or never published this event.
|
||||
return False
|
||||
raise ctypes.WinError(error)
|
||||
try:
|
||||
if not kernel.SetEvent(handle):
|
||||
raise ctypes.WinError()
|
||||
return True
|
||||
finally:
|
||||
kernel.CloseHandle(handle)
|
||||
+12
-14
@@ -390,20 +390,18 @@ class ManagedProcessRuntime(Generic[_StartOptionsT]):
|
||||
# not an individual process, and can interrupt the caller when a
|
||||
# detached/no-window child has no addressable console group. Keep
|
||||
# termination scoped to the recorded PID tree instead.
|
||||
self._subprocess_run(
|
||||
["taskkill", "/PID", str(pid), "/T"],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
if self._wait_for_exit(pid, timeout_s):
|
||||
return True
|
||||
self._subprocess_run(
|
||||
["taskkill", "/PID", str(pid), "/T", "/F"],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
# Cooperative shutdown belongs to the application owner. Non-forced
|
||||
# taskkill cannot close these windowless trees and only wastes its grace period.
|
||||
try:
|
||||
self._subprocess_run(
|
||||
["taskkill", "/PID", str(pid), "/T", "/F"],
|
||||
check=False,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=2,
|
||||
)
|
||||
except subprocess.TimeoutExpired:
|
||||
return False
|
||||
return self._wait_for_exit(pid, 2)
|
||||
|
||||
def _wait_for_exit(self, pid: int, timeout_s: int | float) -> bool:
|
||||
|
||||
Reference in new issue
Block a user