diff --git a/kdb-bot/src/bot/application.py b/kdb-bot/src/bot/application.py index f479fbac..4198de6b 100644 --- a/kdb-bot/src/bot/application.py +++ b/kdb-bot/src/bot/application.py @@ -65,6 +65,9 @@ class Application(DiscordBotApplicationABC): self._is_stopping = True try: self._logger.info(__name__, f"Try to stop {DiscordBotService.__name__}") + if self._feature_flags.get_flag(FeatureFlagsEnum.api_module): + self._api.stop() + await self._bot.close() self._logger.info(__name__, f"Stopped {DiscordBotService.__name__}") except Exception as e: diff --git a/kdb-bot/src/bot_api/api.py b/kdb-bot/src/bot_api/api.py index 64c060e9..dd086b2d 100644 --- a/kdb-bot/src/bot_api/api.py +++ b/kdb-bot/src/bot_api/api.py @@ -1,8 +1,9 @@ +import socket import sys import textwrap import uuid from functools import partial -from typing import Union +from typing import Union, Optional import eventlet from cpl_core.dependency_injection import ServiceProviderABC @@ -60,6 +61,8 @@ class Api(Flask): self._socketio.on_event("connect", self.on_connect) self._socketio.on_event("disconnect", self.on_disconnect) + self._socket: Optional[socket] = None + self._requests = {} @staticmethod @@ -152,7 +155,14 @@ class Api(Flask): # from waitress import serve # https://docs.pylonsproject.org/projects/waitress/en/stable/arguments.html # serve(self, host=self._apt_settings.host, port=self._apt_settings.port, threads=10, connection_limit=1000, channel_timeout=10) - wsgi.server(eventlet.listen((self._api_settings.host, self._api_settings.port)), self, log_output=False) + self._socket = eventlet.listen((self._api_settings.host, self._api_settings.port)) + wsgi.server(self._socket, self, log_output=False) + + def stop(self): + if self._socket is None: + return + self._socket.shutdown(socket.SHUT_RDWR) + self._socket.close() def on_connect(self): self._logger.info(__name__, f"Client connected") diff --git a/kdb-bot/src/bot_api/api_thread.py b/kdb-bot/src/bot_api/api_thread.py index d49c0467..02a4c41b 100644 --- a/kdb-bot/src/bot_api/api_thread.py +++ b/kdb-bot/src/bot_api/api_thread.py @@ -17,3 +17,10 @@ class ApiThread(threading.Thread): self._api.start() except Exception as e: self._logger.error(__name__, "Start failed", e) + + def stop(self): + try: + self._logger.trace(__name__, f"Try to stop {type(self._api).__name__}") + self._api.stop() + except Exception as e: + self._logger.error(__name__, "Stop failed", e)