2021-12-13 18:08:32 +00:00
|
|
|
# tractor: structured concurrent "actors".
|
|
|
|
# Copyright 2018-eternity Tyler Goodlet.
|
|
|
|
|
|
|
|
# This program is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU Affero General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU Affero General Public License for more details.
|
|
|
|
|
|
|
|
# You should have received a copy of the GNU Affero General Public License
|
|
|
|
# along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
|
|
|
2021-11-22 18:28:30 +00:00
|
|
|
'''
|
2020-12-27 15:55:00 +00:00
|
|
|
Root actor runtime ignition(s).
|
2021-11-22 18:28:30 +00:00
|
|
|
|
|
|
|
'''
|
2020-12-27 15:55:00 +00:00
|
|
|
from contextlib import asynccontextmanager
|
|
|
|
from functools import partial
|
|
|
|
import importlib
|
2021-11-17 19:45:24 +00:00
|
|
|
import logging
|
2022-10-13 17:12:17 +00:00
|
|
|
import signal
|
2023-03-07 21:46:14 +00:00
|
|
|
import sys
|
|
|
|
import os
|
2020-12-27 16:51:38 +00:00
|
|
|
import warnings
|
2020-12-27 15:55:00 +00:00
|
|
|
|
2022-10-09 17:12:50 +00:00
|
|
|
|
|
|
|
from exceptiongroup import BaseExceptionGroup
|
2020-12-27 15:55:00 +00:00
|
|
|
import trio
|
|
|
|
|
2022-10-13 17:12:17 +00:00
|
|
|
from ._runtime import (
|
|
|
|
Actor,
|
|
|
|
Arbiter,
|
|
|
|
async_main,
|
|
|
|
)
|
2023-09-28 18:14:50 +00:00
|
|
|
from .devx import _debug
|
2020-12-27 15:55:00 +00:00
|
|
|
from . import _spawn
|
|
|
|
from . import _state
|
|
|
|
from . import log
|
|
|
|
from ._ipc import _connect_chan
|
2021-08-03 00:37:27 +00:00
|
|
|
from ._exceptions import is_multi_cancelled
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
# set at startup and after forks
|
2023-10-18 23:08:35 +00:00
|
|
|
_default_host: str = '127.0.0.1'
|
2023-10-18 18:12:58 +00:00
|
|
|
_default_port: int = 1616
|
|
|
|
|
|
|
|
# default registry always on localhost
|
|
|
|
_default_lo_addrs: list[tuple[str, int]] = [(
|
2023-10-18 23:08:35 +00:00
|
|
|
_default_host,
|
2023-10-18 18:12:58 +00:00
|
|
|
_default_port,
|
|
|
|
)]
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
|
|
|
|
logger = log.get_logger('tractor')
|
|
|
|
|
|
|
|
|
|
|
|
@asynccontextmanager
|
|
|
|
async def open_root_actor(
|
2020-12-27 16:51:38 +00:00
|
|
|
|
2023-01-13 21:57:55 +00:00
|
|
|
*,
|
2020-12-27 16:51:38 +00:00
|
|
|
# defaults are above
|
2023-09-27 19:19:30 +00:00
|
|
|
registry_addrs: list[tuple[str, int]] | None = None,
|
2023-01-13 21:57:55 +00:00
|
|
|
|
|
|
|
# defaults are above
|
2023-09-27 19:19:30 +00:00
|
|
|
arbiter_addr: tuple[str, int] | None = None,
|
2020-12-27 16:51:38 +00:00
|
|
|
|
2023-01-26 17:43:06 +00:00
|
|
|
name: str | None = 'root',
|
2020-12-27 16:51:38 +00:00
|
|
|
|
|
|
|
# either the `multiprocessing` start method:
|
|
|
|
# https://docs.python.org/3/library/multiprocessing.html#contexts-and-start-methods
|
|
|
|
# OR `trio` (the new default).
|
2023-01-26 17:43:06 +00:00
|
|
|
start_method: _spawn.SpawnMethodKey | None = None,
|
2020-12-27 16:51:38 +00:00
|
|
|
|
|
|
|
# enables the multi-process debugger support
|
2020-12-27 15:55:00 +00:00
|
|
|
debug_mode: bool = False,
|
2020-12-27 16:51:38 +00:00
|
|
|
|
2021-01-03 02:34:39 +00:00
|
|
|
# internal logging
|
2023-01-26 17:43:06 +00:00
|
|
|
loglevel: str | None = None,
|
2021-01-03 02:34:39 +00:00
|
|
|
|
2023-01-26 17:43:06 +00:00
|
|
|
enable_modules: list | None = None,
|
|
|
|
rpc_module_paths: list | None = None,
|
2021-01-03 02:34:39 +00:00
|
|
|
|
2023-11-07 21:45:22 +00:00
|
|
|
# NOTE: allow caller to ensure that only one registry exists
|
|
|
|
# and that this call creates it.
|
|
|
|
ensure_registry: bool = False,
|
|
|
|
|
2023-10-19 16:40:37 +00:00
|
|
|
) -> Actor:
|
2022-10-13 17:12:17 +00:00
|
|
|
'''
|
|
|
|
Runtime init entry point for ``tractor``.
|
2020-12-27 15:55:00 +00:00
|
|
|
|
2022-10-13 17:12:17 +00:00
|
|
|
'''
|
2021-02-16 00:23:53 +00:00
|
|
|
# Override the global debugger hook to make it play nice with
|
2023-03-07 21:46:14 +00:00
|
|
|
# ``trio``, see much discussion in:
|
2021-02-16 00:23:53 +00:00
|
|
|
# https://github.com/python-trio/trio/issues/1155#issuecomment-742964018
|
2023-03-07 21:46:14 +00:00
|
|
|
builtin_bp_handler = sys.breakpointhook
|
|
|
|
orig_bp_path: str | None = os.environ.get('PYTHONBREAKPOINT', None)
|
2023-09-28 18:14:50 +00:00
|
|
|
os.environ['PYTHONBREAKPOINT'] = 'tractor.devx._debug.pause_from_sync'
|
2021-02-16 00:23:53 +00:00
|
|
|
|
2022-10-13 17:12:17 +00:00
|
|
|
# attempt to retreive ``trio``'s sigint handler and stash it
|
|
|
|
# on our debugger lock state.
|
2023-01-26 17:43:06 +00:00
|
|
|
_debug.Lock._trio_handler = signal.getsignal(signal.SIGINT)
|
2022-10-13 17:12:17 +00:00
|
|
|
|
2020-12-27 15:55:00 +00:00
|
|
|
# mark top most level process as root actor
|
|
|
|
_state._runtime_vars['_is_root'] = True
|
|
|
|
|
2021-01-03 02:34:39 +00:00
|
|
|
# caps based rpc list
|
2021-01-05 13:28:06 +00:00
|
|
|
enable_modules = enable_modules or []
|
|
|
|
|
|
|
|
if rpc_module_paths:
|
|
|
|
warnings.warn(
|
|
|
|
"`rpc_module_paths` is now deprecated, use "
|
|
|
|
" `enable_modules` instead.",
|
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=2,
|
|
|
|
)
|
|
|
|
enable_modules.extend(rpc_module_paths)
|
2021-01-03 02:34:39 +00:00
|
|
|
|
2020-12-27 15:55:00 +00:00
|
|
|
if start_method is not None:
|
|
|
|
_spawn.try_set_start_method(start_method)
|
|
|
|
|
2023-01-13 21:57:55 +00:00
|
|
|
if arbiter_addr is not None:
|
|
|
|
warnings.warn(
|
2023-09-27 19:19:30 +00:00
|
|
|
'`arbiter_addr` is now deprecated\n'
|
|
|
|
'Use `registry_addrs: list[tuple]` instead..',
|
2023-01-13 21:57:55 +00:00
|
|
|
DeprecationWarning,
|
|
|
|
stacklevel=2,
|
|
|
|
)
|
2023-09-27 19:19:30 +00:00
|
|
|
registry_addrs = [arbiter_addr]
|
2023-01-13 21:57:55 +00:00
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
registry_addrs: list[tuple[str, int]] = (
|
|
|
|
registry_addrs
|
2023-10-19 16:40:37 +00:00
|
|
|
or
|
2023-10-18 18:12:58 +00:00
|
|
|
_default_lo_addrs
|
2021-11-22 18:28:30 +00:00
|
|
|
)
|
2023-10-18 23:08:35 +00:00
|
|
|
assert registry_addrs
|
2021-11-22 18:28:30 +00:00
|
|
|
|
2024-02-20 18:23:16 +00:00
|
|
|
loglevel = (
|
|
|
|
loglevel
|
|
|
|
or log._default_loglevel
|
|
|
|
).upper()
|
|
|
|
|
|
|
|
if (
|
|
|
|
debug_mode
|
|
|
|
and _spawn._spawn_method == 'trio'
|
|
|
|
):
|
2020-12-27 15:55:00 +00:00
|
|
|
_state._runtime_vars['_debug_mode'] = True
|
|
|
|
|
2024-02-20 18:23:16 +00:00
|
|
|
# expose internal debug module to every actor allowing for
|
|
|
|
# use of ``await tractor.pause()``
|
2023-09-28 18:14:50 +00:00
|
|
|
enable_modules.append('tractor.devx._debug')
|
2020-12-27 15:55:00 +00:00
|
|
|
|
2021-11-17 19:45:24 +00:00
|
|
|
# if debug mode get's enabled *at least* use that level of
|
|
|
|
# logging for some informative console prompts.
|
2021-11-22 18:28:30 +00:00
|
|
|
if (
|
|
|
|
logging.getLevelName(
|
|
|
|
# lul, need the upper case for the -> int map?
|
|
|
|
# sweet "dynamic function behaviour" stdlib...
|
2022-07-01 18:37:16 +00:00
|
|
|
loglevel,
|
2021-11-22 18:28:30 +00:00
|
|
|
) > logging.getLevelName('PDB')
|
|
|
|
):
|
|
|
|
loglevel = 'PDB'
|
2021-07-08 17:02:33 +00:00
|
|
|
|
2020-12-27 15:55:00 +00:00
|
|
|
elif debug_mode:
|
|
|
|
raise RuntimeError(
|
|
|
|
"Debug mode is only supported for the `trio` backend!"
|
|
|
|
)
|
|
|
|
|
2024-02-20 18:23:16 +00:00
|
|
|
assert loglevel
|
|
|
|
_log = log.get_console_log(loglevel)
|
|
|
|
assert _log
|
|
|
|
|
|
|
|
# TODO: factor this into `.devx._stackscope`!!
|
|
|
|
if debug_mode:
|
|
|
|
try:
|
|
|
|
logger.info('Enabling `stackscope` traces on SIGUSR1')
|
|
|
|
from .devx import enable_stack_on_sig
|
|
|
|
enable_stack_on_sig()
|
|
|
|
except ImportError:
|
|
|
|
logger.warning(
|
|
|
|
'`stackscope` not installed for use in debug mode!'
|
|
|
|
)
|
2022-07-01 18:37:16 +00:00
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
# closed into below ping task-func
|
|
|
|
ponged_addrs: list[tuple[str, int]] = []
|
|
|
|
|
|
|
|
async def ping_tpt_socket(
|
|
|
|
addr: tuple[str, int],
|
|
|
|
timeout: float = 1,
|
|
|
|
) -> None:
|
|
|
|
'''
|
|
|
|
Attempt temporary connection to see if a registry is
|
|
|
|
listening at the requested address by a tranport layer
|
|
|
|
ping.
|
|
|
|
|
|
|
|
If a connection can't be made quickly we assume none no
|
|
|
|
server is listening at that addr.
|
|
|
|
|
|
|
|
'''
|
|
|
|
try:
|
|
|
|
# TODO: this connect-and-bail forces us to have to
|
|
|
|
# carefully rewrap TCP 104-connection-reset errors as
|
|
|
|
# EOF so as to avoid propagating cancel-causing errors
|
|
|
|
# to the channel-msg loop machinery. Likely it would
|
|
|
|
# be better to eventually have a "discovery" protocol
|
|
|
|
# with basic handshake instead?
|
|
|
|
with trio.move_on_after(timeout):
|
|
|
|
async with _connect_chan(*addr):
|
|
|
|
ponged_addrs.append(addr)
|
|
|
|
|
|
|
|
except OSError:
|
|
|
|
# TODO: make this a "discovery" log level?
|
|
|
|
logger.warning(f'No actor registry found @ {addr}')
|
|
|
|
|
|
|
|
async with trio.open_nursery() as tn:
|
|
|
|
for addr in registry_addrs:
|
2023-10-19 16:40:37 +00:00
|
|
|
tn.start_soon(
|
|
|
|
ping_tpt_socket,
|
|
|
|
tuple(addr), # TODO: just drop this requirement?
|
|
|
|
)
|
2023-09-27 19:19:30 +00:00
|
|
|
|
|
|
|
trans_bind_addrs: list[tuple[str, int]] = []
|
|
|
|
|
|
|
|
# Create a new local root-actor instance which IS NOT THE
|
|
|
|
# REGISTRAR
|
|
|
|
if ponged_addrs:
|
2020-12-27 16:51:38 +00:00
|
|
|
|
2023-11-07 21:45:22 +00:00
|
|
|
if ensure_registry:
|
|
|
|
raise RuntimeError(
|
|
|
|
f'Failed to open `{name}`@{ponged_addrs}: '
|
|
|
|
'registry socket(s) already bound'
|
|
|
|
)
|
|
|
|
|
2020-12-27 16:51:38 +00:00
|
|
|
# we were able to connect to an arbiter
|
2023-09-27 19:19:30 +00:00
|
|
|
logger.info(
|
|
|
|
f'Registry(s) seem(s) to exist @ {ponged_addrs}'
|
|
|
|
)
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
actor = Actor(
|
2023-09-27 19:19:30 +00:00
|
|
|
name=name or 'anonymous',
|
|
|
|
registry_addrs=ponged_addrs,
|
2021-01-03 02:34:39 +00:00
|
|
|
loglevel=loglevel,
|
2021-01-05 13:28:06 +00:00
|
|
|
enable_modules=enable_modules,
|
2020-12-27 15:55:00 +00:00
|
|
|
)
|
2023-09-27 19:19:30 +00:00
|
|
|
# DO NOT use the registry_addrs as the transport server
|
|
|
|
# addrs for this new non-registar, root-actor.
|
|
|
|
for host, port in ponged_addrs:
|
|
|
|
# NOTE: zero triggers dynamic OS port allocation
|
|
|
|
trans_bind_addrs.append((host, 0))
|
|
|
|
|
|
|
|
# Start this local actor as the "registrar", aka a regular
|
|
|
|
# actor who manages the local registry of "mailboxes" of
|
|
|
|
# other process-tree-local sub-actors.
|
2020-12-27 15:55:00 +00:00
|
|
|
else:
|
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
# NOTE that if the current actor IS THE REGISTAR, the
|
|
|
|
# following init steps are taken:
|
|
|
|
# - the tranport layer server is bound to each (host, port)
|
|
|
|
# pair defined in provided registry_addrs, or the default.
|
|
|
|
trans_bind_addrs = registry_addrs
|
|
|
|
|
|
|
|
# - it is normally desirable for any registrar to stay up
|
|
|
|
# indefinitely until either all registered (child/sub)
|
|
|
|
# actors are terminated (via SC supervision) or,
|
|
|
|
# a re-election process has taken place.
|
|
|
|
# NOTE: all of ^ which is not implemented yet - see:
|
|
|
|
# https://github.com/goodboy/tractor/issues/216
|
|
|
|
# https://github.com/goodboy/tractor/pull/348
|
|
|
|
# https://github.com/goodboy/tractor/issues/296
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
actor = Arbiter(
|
2023-09-27 19:19:30 +00:00
|
|
|
name or 'registrar',
|
|
|
|
registry_addrs=registry_addrs,
|
2021-01-03 02:34:39 +00:00
|
|
|
loglevel=loglevel,
|
2021-01-05 13:28:06 +00:00
|
|
|
enable_modules=enable_modules,
|
2020-12-27 15:55:00 +00:00
|
|
|
)
|
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
# Start up main task set via core actor-runtime nurseries.
|
2020-12-27 15:55:00 +00:00
|
|
|
try:
|
|
|
|
# assign process-local actor
|
|
|
|
_state._current_actor = actor
|
|
|
|
|
|
|
|
# start local channel-server and fake the portal API
|
|
|
|
# NOTE: this won't block since we provide the nursery
|
2023-09-27 19:19:30 +00:00
|
|
|
ml_addrs_str: str = '\n'.join(
|
|
|
|
f'@{addr}' for addr in trans_bind_addrs
|
|
|
|
)
|
|
|
|
logger.info(
|
|
|
|
f'Starting local {actor.uid} on the following transport addrs:\n'
|
|
|
|
f'{ml_addrs_str}'
|
|
|
|
)
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
# start the actor runtime in a new task
|
|
|
|
async with trio.open_nursery() as nursery:
|
|
|
|
|
2023-10-03 14:54:46 +00:00
|
|
|
# ``_runtime.async_main()`` creates an internal nursery
|
|
|
|
# and blocks here until any underlying actor(-process)
|
|
|
|
# tree has terminated thereby conducting so called
|
|
|
|
# "end-to-end" structured concurrency throughout an
|
|
|
|
# entire hierarchical python sub-process set; all
|
|
|
|
# "actor runtime" primitives are SC-compat and thus all
|
|
|
|
# transitively spawned actors/processes must be as
|
|
|
|
# well.
|
2020-12-27 15:55:00 +00:00
|
|
|
await nursery.start(
|
|
|
|
partial(
|
2022-08-03 19:29:34 +00:00
|
|
|
async_main,
|
|
|
|
actor,
|
2023-09-27 19:19:30 +00:00
|
|
|
accept_addrs=trans_bind_addrs,
|
2020-12-27 15:55:00 +00:00
|
|
|
parent_addr=None
|
|
|
|
)
|
|
|
|
)
|
|
|
|
try:
|
|
|
|
yield actor
|
2021-02-24 17:59:43 +00:00
|
|
|
|
2022-10-09 17:12:50 +00:00
|
|
|
except (
|
|
|
|
Exception,
|
|
|
|
BaseExceptionGroup,
|
|
|
|
) as err:
|
2021-08-01 14:43:21 +00:00
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
entered: bool = await _debug._maybe_enter_pm(err)
|
|
|
|
|
2023-07-07 19:35:52 +00:00
|
|
|
if (
|
2023-09-27 19:19:30 +00:00
|
|
|
not entered
|
2023-07-07 19:35:52 +00:00
|
|
|
and not is_multi_cancelled(err)
|
|
|
|
):
|
2021-06-30 12:45:43 +00:00
|
|
|
logger.exception("Root actor crashed:")
|
2020-12-27 15:55:00 +00:00
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
# ALWAYS re-raise any error bubbled up from the
|
|
|
|
# runtime!
|
2020-12-27 15:55:00 +00:00
|
|
|
raise
|
2021-04-29 02:19:36 +00:00
|
|
|
|
2020-12-27 15:55:00 +00:00
|
|
|
finally:
|
2021-12-15 19:27:01 +00:00
|
|
|
# NOTE: not sure if we'll ever need this but it's
|
|
|
|
# possibly better for even more determinism?
|
2022-07-28 18:54:03 +00:00
|
|
|
# logger.cancel(
|
|
|
|
# f'Waiting on {len(nurseries)} nurseries in root..')
|
2021-12-15 19:27:01 +00:00
|
|
|
# nurseries = actor._actoruid2nursery.values()
|
|
|
|
# async with trio.open_nursery() as tempn:
|
|
|
|
# for an in nurseries:
|
|
|
|
# tempn.start_soon(an.exited.wait)
|
|
|
|
|
2021-10-05 23:25:28 +00:00
|
|
|
logger.cancel("Shutting down root actor")
|
2024-02-22 19:45:08 +00:00
|
|
|
await actor.cancel(None) # self cancel
|
2020-12-27 15:55:00 +00:00
|
|
|
finally:
|
|
|
|
_state._current_actor = None
|
2023-03-07 21:46:14 +00:00
|
|
|
|
2023-09-27 19:19:30 +00:00
|
|
|
# restore built-in `breakpoint()` hook state
|
2023-03-07 21:46:14 +00:00
|
|
|
sys.breakpointhook = builtin_bp_handler
|
|
|
|
if orig_bp_path is not None:
|
|
|
|
os.environ['PYTHONBREAKPOINT'] = orig_bp_path
|
|
|
|
else:
|
|
|
|
# clear env back to having no entry
|
|
|
|
os.environ.pop('PYTHONBREAKPOINT')
|
|
|
|
|
2021-10-05 23:25:28 +00:00
|
|
|
logger.runtime("Root actor terminated")
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
|
2022-09-15 20:15:17 +00:00
|
|
|
def run_daemon(
|
|
|
|
enable_modules: list[str],
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
# runtime kwargs
|
2023-01-26 17:43:06 +00:00
|
|
|
name: str | None = 'root',
|
2023-10-18 18:12:58 +00:00
|
|
|
registry_addrs: list[tuple[str, int]] = _default_lo_addrs,
|
2020-12-27 15:55:00 +00:00
|
|
|
|
2023-01-26 17:43:06 +00:00
|
|
|
start_method: str | None = None,
|
2020-12-27 15:55:00 +00:00
|
|
|
debug_mode: bool = False,
|
2022-09-15 20:15:17 +00:00
|
|
|
**kwargs
|
2020-12-27 15:55:00 +00:00
|
|
|
|
2022-09-15 20:15:17 +00:00
|
|
|
) -> None:
|
|
|
|
'''
|
|
|
|
Spawn daemon actor which will respond to RPC; the main task simply
|
|
|
|
starts the runtime and then sleeps forever.
|
|
|
|
|
|
|
|
This is a very minimal convenience wrapper around starting
|
|
|
|
a "run-until-cancelled" root actor which can be started with a set
|
|
|
|
of enabled modules for RPC request handling.
|
|
|
|
|
|
|
|
'''
|
|
|
|
kwargs['enable_modules'] = list(enable_modules)
|
|
|
|
|
|
|
|
for path in enable_modules:
|
|
|
|
importlib.import_module(path)
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
async def _main():
|
|
|
|
|
|
|
|
async with open_root_actor(
|
2023-09-27 19:19:30 +00:00
|
|
|
registry_addrs=registry_addrs,
|
2020-12-27 15:55:00 +00:00
|
|
|
name=name,
|
|
|
|
start_method=start_method,
|
|
|
|
debug_mode=debug_mode,
|
|
|
|
**kwargs,
|
|
|
|
):
|
2022-09-15 20:15:17 +00:00
|
|
|
return await trio.sleep_forever()
|
2020-12-27 15:55:00 +00:00
|
|
|
|
|
|
|
return trio.run(_main)
|