"""One process per replica; bounded drain on SIGTERM.""" import logging import signal import time from waitress import create_server from .api import create_app from .config import Settings def main(): logging.basicConfig(level=logging.INFO) settings = Settings.from_env() app = create_app(settings=settings) server = create_server(app, host=settings.host, port=settings.port, threads=4) stopping = False def stop(signum, frame): nonlocal stopping stopping = True signal.signal(signal.SIGTERM, stop) signal.signal(signal.SIGINT, stop) logging.info('Starting messenger environment=%s', settings.environment) try: while not stopping: server.asyncore.loop(timeout=0.1, count=1, map=server._map) # Stop accepting new TCP connections. Keep the event loop alive briefly # so responses from existing worker tasks can still be flushed. app.config['DRAINING'] = True server.close() deadline = time.monotonic() + 5 while server._map and time.monotonic() < deadline: server.asyncore.loop(timeout=0.1, count=1, map=server._map) finally: server.task_dispatcher.shutdown(timeout=1) server.asyncore.close_all(map=server._map) logging.info('Messenger stopped') if __name__ == '__main__': main()