From bc5912d390ff65df13553663fb1a10a2f448dfdf Mon Sep 17 00:00:00 2001 From: Gary Benson Date: Sat, 9 Nov 2024 09:32:57 +0000 Subject: [PATCH] hive-common: Add hive.common.socketserver.serving --- libs/common/hive/common/socketserver.py | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 libs/common/hive/common/socketserver.py diff --git a/libs/common/hive/common/socketserver.py b/libs/common/hive/common/socketserver.py new file mode 100644 index 0000000..ce58f8d --- /dev/null +++ b/libs/common/hive/common/socketserver.py @@ -0,0 +1,32 @@ +import logging + +from contextlib import contextmanager +from socketserver import BaseServer +from threading import Thread + +from .units import SECONDS + +logger = logging.getLogger(__name__) + + +@contextmanager +def serving( + server: BaseServer, + *, + shutdown_timeout: float = 30 * SECONDS, + daemon: bool = True, +) -> Thread: + """Run a :class:`socketserver.BaseServer` in another thread. + """ + thread = Thread(target=server.serve_forever, daemon=daemon) + logger.info("%s:%s: Starting server", thread, server) + thread.start() + try: + logger.info("%s:%s: Server started", thread, server) + yield thread + finally: + logger.info("%s: %s: Stopping server", thread, server) + server.shutdown() + logger.debug("%s: Waiting for thread exit", thread) + thread.join(timeout=30 * SECONDS) + logger.info("%s: %s: Server stopped", thread, server)