| 1 |
""" |
| 2 |
Internal Worker->Controller RPC support module. |
| 3 |
|
| 4 |
Implements a minimal multiprocessing context for an in-process LocalManager RPC server hosted on the primary Ansible controller process. |
| 5 |
""" |
| 6 |
|
| 7 |
from __future__ import annotations |
| 8 |
|
| 9 |
import collections.abc as c |
| 10 |
import dataclasses |
| 11 |
import signal |
| 12 |
import threading |
| 13 |
import typing as t |
| 14 |
|
| 15 |
from multiprocessing.context import BaseContext |
| 16 |
from multiprocessing.managers import BaseManager, Server |
| 17 |
from multiprocessing.process import BaseProcess |
| 18 |
|
| 19 |
from ..module_utils._internal._concurrent._futures import DaemonThreadPoolExecutor |
| 20 |
|
| 21 |
_server_ready: threading.Event = threading.Event() |
| 22 |
|
| 23 |
|
| 24 |
class LocalNotAProcess(BaseProcess): |
| 25 |
"""Minimal BaseProcess impl that runs `target` locally in a thread instead of a subprocess.""" |
| 26 |
|
| 27 |
def __init__(self, *posargs, target, args, **kwargs): |
| 28 |
super().__init__(*posargs, **kwargs) |
| 29 |
|
| 30 |
self._args = args |
| 31 |
self._kwargs = kwargs |
| 32 |
self._target = target |
| 33 |
self._tpe = DaemonThreadPoolExecutor() |
| 34 |
|
| 35 |
def start(self): |
| 36 |
if threading.current_thread() is not threading.main_thread(): |
| 37 |
# temporary signal patch is only safe under the main thread; guaranteed to be restored before it can be used |
| 38 |
raise RuntimeError("Local RPC server must be started from the main thread.") |
| 39 |
|
| 40 |
original_signal = signal.signal |
| 41 |
|
| 42 |
try: |
| 43 |
# signal.signal raises if called from a non-main thread, disable it until we're past that point of the server startup |
| 44 |
signal.signal = lambda *args, **kwargs: None |
| 45 |
|
| 46 |
# the only target this should see is _run_server |
| 47 |
# start cannot return until Server.serve_forever is called (our custom subclass sets the _server_ready event) |
| 48 |
self._tpe.submit(self._target, *self._args, **self._kwargs) |
| 49 |
|
| 50 |
if not _server_ready.wait(5): |
| 51 |
raise TimeoutError("Local RPC server did not start.") |
| 52 |
finally: |
| 53 |
signal.signal = original_signal # always restore default signal impl |
| 54 |
|
| 55 |
|
| 56 |
class LocalContext(BaseContext): |
| 57 |
"""Minimal Context impl to support in-proc LocalManager.""" |
| 58 |
|
| 59 |
Process = LocalNotAProcess |
| 60 |
|
| 61 |
|
| 62 |
class LocalServer(Server): |
| 63 |
"""Customized Server for in-proc LocalManager.""" |
| 64 |
|
| 65 |
def serve_forever(self): |
| 66 |
_server_ready.set() |
| 67 |
return super().serve_forever() |
| 68 |
|
| 69 |
|
| 70 |
class LocalManager(BaseManager): |
| 71 |
"""Customized BaseManager for in-proc usage.""" |
| 72 |
|
| 73 |
_Server = LocalServer # override BaseManager to use custom Server subclass |
| 74 |
_shared_instance: t.ClassVar[t.Self | None] = None |
| 75 |
_shared_lock = threading.Lock() |
| 76 |
|
| 77 |
def __init__(self): |
| 78 |
type(self)._current = self # HACK: ew |
| 79 |
|
| 80 |
super().__init__(serializer='pickle', ctx=LocalContext()) |
| 81 |
|
| 82 |
@property |
| 83 |
def authkey(self) -> bytes: |
| 84 |
return self._authkey |
| 85 |
|
| 86 |
@classmethod |
| 87 |
def register( |
| 88 |
cls, |
| 89 |
typeid: str, |
| 90 |
callable: t.Callable | None = None, |
| 91 |
proxytype: type | None = None, |
| 92 |
exposed: c.Sequence[str] | None = None, |
| 93 |
method_to_typeid: c.Mapping[str, str] | None = None, |
| 94 |
create_method: bool = True, |
| 95 |
) -> None: |
| 96 |
with cls._shared_lock: |
| 97 |
super().register( |
| 98 |
typeid=typeid, |
| 99 |
callable=callable, |
| 100 |
proxytype=proxytype, |
| 101 |
exposed=exposed, |
| 102 |
method_to_typeid=method_to_typeid, |
| 103 |
create_method=create_method, |
| 104 |
) |
| 105 |
|
| 106 |
@classmethod |
| 107 |
def shared_instance(cls) -> t.Self: |
| 108 |
"""Access a lazily-created LocalManager singleton.""" |
| 109 |
if not cls._shared_instance: |
| 110 |
with cls._shared_lock: |
| 111 |
if not cls._shared_instance: |
| 112 |
instance = cls() |
| 113 |
instance.start() |
| 114 |
|
| 115 |
cls._shared_instance = instance |
| 116 |
|
| 117 |
return cls._shared_instance |
| 118 |
|
| 119 |
|
| 120 |
@dataclasses.dataclass(kw_only=True) |
| 121 |
class AsyncRPCOperation: |
| 122 |
"""Wrapper around a deferred invocation with a waitable completion event.""" |
| 123 |
|
| 124 |
event: threading.Event = dataclasses.field(default_factory=threading.Event) |
| 125 |
impl: t.Callable |
| 126 |
args: tuple |
| 127 |
kwargs: dict[str, object] |
| 128 |
|
| 129 |
_response: object = None |
| 130 |
_exception: BaseException | None = None |
| 131 |
|
| 132 |
# FUTURE: reimplement as a lighter-weight future/asyncio executor if RPC volume gets significantly higher |
| 133 |
|
| 134 |
@property |
| 135 |
def result(self) -> object: |
| 136 |
if self._exception: |
| 137 |
raise self._exception |
| 138 |
|
| 139 |
return self._response |
| 140 |
|
| 141 |
def dispatch(self) -> None: |
| 142 |
try: |
| 143 |
self._response = self.impl(*self.args, **self.kwargs) |
| 144 |
except BaseException as ex: |
| 145 |
self._exception = ex |
| 146 |
|
| 147 |
self.event.set() |
| 148 |
|
| 149 |
|
| 150 |
class AutoRegisterRPC: |
| 151 |
"""Base class for an RPC implementation which automatically registers its methods.""" |
| 152 |
|
| 153 |
def __init_subclass__(cls, **kwargs): |
| 154 |
instance = cls() |
| 155 |
LocalManager.register(cls.__name__, lambda: instance) |
| 156 |
|
| 157 |
@classmethod |
| 158 |
def get_client(cls) -> t.Self: |
| 159 |
"""Get the RPC client for this implementation.""" |
| 160 |
rpc_host = LocalManager.shared_instance() # this assumes the caller was forked from the controller after the manager was started |
| 161 |
|
| 162 |
rpc_client = BaseManager(address=rpc_host.address, authkey=rpc_host.authkey) |
| 163 |
rpc_client.register(cls.__name__) |
| 164 |
rpc_client.connect() |
| 165 |
|
| 166 |
return getattr(rpc_client, cls.__name__)() |