|
| 1 | +import asyncio |
| 2 | +import contextlib |
| 3 | +import logging |
| 4 | +import multiprocessing |
| 5 | +import sys |
| 6 | +from multiprocessing.context import BaseContext |
| 7 | +from types import ModuleType |
| 8 | +from typing import Any, AsyncGenerator, Union |
| 9 | + |
| 10 | +from ..config import DispatcherSettings |
| 11 | +from ..factories import from_settings |
| 12 | +from ..service.main import DispatcherMain |
| 13 | + |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | + |
| 16 | + |
| 17 | +class CommunicationItems: |
| 18 | + """Various things used for communication between the parent process and the subprocess service |
| 19 | +
|
| 20 | + This will be passed in the call to the subprocess. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__(self, main_events: tuple[str], pool_events: tuple[str], context: Union[BaseContext, ModuleType]) -> None: |
| 24 | + self.q_in: multiprocessing.Queue = context.Queue() |
| 25 | + self.q_out: multiprocessing.Queue = context.Queue() |
| 26 | + self.main_events = main_events |
| 27 | + self.pool_events = pool_events |
| 28 | + |
| 29 | + |
| 30 | +@contextlib.asynccontextmanager |
| 31 | +async def adispatcher_service(config: dict) -> AsyncGenerator[DispatcherMain, Any]: |
| 32 | + dispatcher = None |
| 33 | + try: |
| 34 | + settings = DispatcherSettings(config) |
| 35 | + dispatcher = from_settings(settings=settings) # type: ignore[arg-type] |
| 36 | + |
| 37 | + await dispatcher.connect_signals() |
| 38 | + await dispatcher.start_working() |
| 39 | + await dispatcher.wait_for_producers_ready() |
| 40 | + await dispatcher.pool.events.workers_ready.wait() |
| 41 | + |
| 42 | + assert dispatcher.pool.finished_count == 0 # sanity |
| 43 | + assert dispatcher.control_count == 0 |
| 44 | + |
| 45 | + yield dispatcher |
| 46 | + finally: |
| 47 | + if dispatcher: |
| 48 | + try: |
| 49 | + await dispatcher.shutdown() |
| 50 | + await dispatcher.cancel_tasks() |
| 51 | + except Exception: |
| 52 | + logger.exception('shutdown had error') |
| 53 | + |
| 54 | + |
| 55 | +async def asyncio_target(config: dict, comms: CommunicationItems) -> None: |
| 56 | + loop = asyncio.get_event_loop() |
| 57 | + async with adispatcher_service(config) as dispatcher: |
| 58 | + comms.q_out.put('ready') |
| 59 | + |
| 60 | + events: dict[str, asyncio.Event] = {} |
| 61 | + for event_name in comms.main_events: |
| 62 | + events[event_name] = getattr(dispatcher.events, event_name) |
| 63 | + for event_name in comms.pool_events: |
| 64 | + events[event_name] = getattr(dispatcher.pool.events, event_name) |
| 65 | + |
| 66 | + event_tasks: dict[str, asyncio.Task] = {} |
| 67 | + for event_name, event in events.items(): |
| 68 | + event_tasks[event_name] = asyncio.create_task(event.wait(), name=f'waiting_for_{event_name}') |
| 69 | + |
| 70 | + new_message_task = None |
| 71 | + |
| 72 | + while True: |
| 73 | + if new_message_task is None: |
| 74 | + new_message_task = loop.run_in_executor(None, comms.q_in.get) |
| 75 | + |
| 76 | + all_tasks = list(event_tasks.values()) + [new_message_task] |
| 77 | + await asyncio.wait(all_tasks, return_when=asyncio.FIRST_COMPLETED) |
| 78 | + |
| 79 | + # Update our parent process with any events they requested from us |
| 80 | + for event_name, event in events.items(): |
| 81 | + if event.is_set(): |
| 82 | + comms.q_out.put(event_name) |
| 83 | + # await loop.run_in_executor(None, comms.q_out.put, event_name) |
| 84 | + event.clear() |
| 85 | + event_tasks[event_name] = asyncio.create_task(event.wait()) |
| 86 | + |
| 87 | + # If no no instructions came from parent then work is done, continue loop |
| 88 | + if not new_message_task.done(): |
| 89 | + continue |
| 90 | + |
| 91 | + message = new_message_task.result() |
| 92 | + new_message_task = None |
| 93 | + |
| 94 | + if message == 'stop': |
| 95 | + print('shutting down pool server') |
| 96 | + for event in events.values(): |
| 97 | + event.set() # close out other tasks |
| 98 | + await dispatcher.shutdown() |
| 99 | + break |
| 100 | + else: |
| 101 | + eval(message) |
| 102 | + |
| 103 | + |
| 104 | +def subprocess_main(config, comms): |
| 105 | + loop = asyncio.new_event_loop() |
| 106 | + try: |
| 107 | + loop.run_until_complete(asyncio_target(config, comms)) |
| 108 | + except Exception: |
| 109 | + # The main process is very likely waiting for message of an event |
| 110 | + # and exceptions may not automatically halt the test, so give a value |
| 111 | + comms.q_out.put('error') |
| 112 | + raise |
| 113 | + finally: |
| 114 | + loop.close() |
| 115 | + |
| 116 | + |
| 117 | +@contextlib.contextmanager |
| 118 | +def dispatcher_service(config, main_events=(), pool_events=()): |
| 119 | + ctx = multiprocessing.get_context('spawn') |
| 120 | + comms = CommunicationItems(main_events=main_events, pool_events=pool_events, context=ctx) |
| 121 | + process = multiprocessing.Process(target=subprocess_main, args=(config, comms)) |
| 122 | + try: |
| 123 | + process.start() |
| 124 | + ready_msg = comms.q_out.get() |
| 125 | + if ready_msg != 'ready': |
| 126 | + raise RuntimeError(f'Never got "ready" message from server, got {ready_msg}') |
| 127 | + yield comms |
| 128 | + finally: |
| 129 | + comms.q_in.put('stop') |
| 130 | + process.join(timeout=1) |
| 131 | + if process.is_alive(): |
| 132 | + process.terminate() # SIGTERM |
| 133 | + comms.q_in.close() |
| 134 | + comms.q_out.close() |
| 135 | + sys.stdout.flush() |
| 136 | + sys.stderr.flush() |
0 commit comments