|
| 1 | +import asyncio |
| 2 | +import multiprocessing |
| 3 | +import contextlib |
| 4 | +import time |
| 5 | + |
| 6 | +import pytest |
| 7 | + |
| 8 | + |
| 9 | +from dispatcher.main import DispatcherMain |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +async def asyncio_target(queue_in, queue_out, config): |
| 14 | + try: |
| 15 | + dispatcher = DispatcherMain(config) |
| 16 | + |
| 17 | + await dispatcher.connect_signals() |
| 18 | + await dispatcher.start_working() |
| 19 | + await dispatcher.wait_for_producers_ready() |
| 20 | + queue_out.put('ready') |
| 21 | + |
| 22 | + |
| 23 | + print('dispatcher server listening on queue_in') |
| 24 | + loop = asyncio.get_event_loop() |
| 25 | + message = await loop.run_in_executor(None, queue_in.get) |
| 26 | + |
| 27 | + print(f'got message, will shut down: {message}') |
| 28 | + finally: |
| 29 | + await dispatcher.shutdown() |
| 30 | + await dispatcher.cancel_tasks() |
| 31 | + |
| 32 | + |
| 33 | +def subprocess_target(queue_in, queue_out, config): |
| 34 | + loop = asyncio.get_event_loop() |
| 35 | + try: |
| 36 | + loop.run_until_complete(asyncio_target(queue_in, queue_out, config)) |
| 37 | + except Exception: |
| 38 | + import traceback |
| 39 | + |
| 40 | + traceback.print_exc() |
| 41 | + # We are in a subprocess here, so even if we handle the exception |
| 42 | + # the main process will not know and still wait forever |
| 43 | + # so give them a kick on our way out |
| 44 | + print('sending error message after error') |
| 45 | + queue_out.put('error') |
| 46 | + finally: |
| 47 | + print('closing asyncio loop') |
| 48 | + loop.close() |
| 49 | + |
| 50 | + |
| 51 | +class SubprocessRunner: |
| 52 | + |
| 53 | + def __init__(self): |
| 54 | + self.queue_in = multiprocessing.Queue() |
| 55 | + self.queue_out = multiprocessing.Queue() |
| 56 | + |
| 57 | + def start_in_subprocess(self, config): |
| 58 | + process = multiprocessing.Process(target=subprocess_target, args=(self.queue_in, self.queue_out, config)) |
| 59 | + process.start() |
| 60 | + return process |
| 61 | + |
| 62 | + @contextlib.contextmanager |
| 63 | + def with_server(self, config): |
| 64 | + process = self.start_in_subprocess(config) |
| 65 | + msg = self.queue_out.get() |
| 66 | + if msg != 'ready': |
| 67 | + raise RuntimeError('never got ready message from subprocess') |
| 68 | + try: |
| 69 | + yield self |
| 70 | + finally: |
| 71 | + self.queue_in.put('stop') |
| 72 | + process.terminate() # SIGTERM |
| 73 | + # Poll to close process resources, due to race condition where it is not still running |
| 74 | + for i in range(3): |
| 75 | + time.sleep(0.1) |
| 76 | + try: |
| 77 | + process.close() |
| 78 | + break |
| 79 | + except Exception: |
| 80 | + if i == 2: |
| 81 | + raise |
| 82 | + |
| 83 | + |
| 84 | +@pytest.fixture |
| 85 | +def dispatcher_subprocess(): |
| 86 | + server = SubprocessRunner() |
| 87 | + return server.with_server |
0 commit comments