aio-libs/aiomonitor

Traceback on process shutdown

gjcarneiro opened this issue · 5 comments

My code looks like this, which is taken from the example in the aiomonitor README:

def main() -> None:  # pragma: no cover
    if "NO_UVLOOP" not in os.environ:
        asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
    logging.basicConfig(
        level=getattr(logging, os.environ.get("LOG_LEVEL", "INFO"))
    )
    logging.getLogger("watchgod.main").setLevel(logging.INFO)
    app = create_web_app()
    loop = asyncio.get_event_loop()
    with aiomonitor.start_monitor(loop=loop, locals={"app": app}):
        web.run_app(
            app, host="0.0.0.0", port=int(os.environ.get("LISTEN_PORT", "80"))
        )

At process shutdown time (after it receives SIGTERM), this traceback always happens:

RuntimeError: Event loop is closed
  File "python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "betslipdisp/__main__.py", line 138, in <module>
    main()
  File "betslipdisp/__main__.py", line 133, in main
    app, host="0.0.0.0", port=int(os.environ.get("LISTEN_PORT", "80"))
  File "aiomonitor/monitor.py", line 126, in __exit__
    self.close()
  File "aiomonitor/monitor.py", line 133, in close
    close_console_server(self._console_server, self._loop)
  File "aiomonitor/utils.py", line 84, in close_console_server
    loop.run_until_complete(coro)
  File "uvloop/loop.pyx", line 1420, in uvloop.loop.Loop.run_until_complete
  File "uvloop/loop.pyx", line 634, in uvloop.loop.Loop._check_closed

I guess it's because the aiomonitor context manager __exit__ runs after aiohttp has already closed the event loop.

I have aiohttp 3.4.4 and aiomonitor 0.4.0, CPython 3.7, uvloop 0.11.3.

@asvetlov what do you think about adding flag to web.run_app to indicate that loop should not be closed? Or should aiomonitor has own app runner?

Would be nice if aiomonitor worked from inside coroutines. Then I could use aiohttp's on_startup/on_shutdown to start/stop aiomonitor as needed.

I think it is possible with recent master.

I tried aiomonitor master, and then the problem is simply gone, without any code changes!

But it definitely happens in the latest pypi release, 0.4.3. Maybe just make a release? 🤷‍♂️