level 4, changed to HAProxy
This commit is contained in:
+32
-1
@@ -1,17 +1,48 @@
|
||||
import logging
|
||||
import threading
|
||||
|
||||
import uvicorn
|
||||
|
||||
from .config import load_settings
|
||||
from .drain import draining
|
||||
|
||||
logger = logging.getLogger('messenger')
|
||||
|
||||
|
||||
class DrainingServer(uvicorn.Server):
|
||||
"""First SIGTERM/SIGINT: keep serving for drain_seconds with readiness 503, then uvicorn's graceful stop.
|
||||
|
||||
drain_seconds must exceed the LB detection time (HAProxy inter 1s x fall 2 + timeout check 1s),
|
||||
so the replica is out of rotation before it stops accepting connections.
|
||||
"""
|
||||
|
||||
def __init__(self, config: uvicorn.Config, drain_seconds: float):
|
||||
super().__init__(config)
|
||||
self.drain_seconds = drain_seconds
|
||||
|
||||
def handle_exit(self, sig, frame) -> None:
|
||||
if draining.is_set() or self.drain_seconds <= 0:
|
||||
draining.set()
|
||||
super().handle_exit(sig, frame)
|
||||
return
|
||||
draining.set()
|
||||
logger.warning('signal %s: draining for %.1f s before shutdown', sig, self.drain_seconds)
|
||||
timer = threading.Timer(self.drain_seconds, super().handle_exit, (sig, frame))
|
||||
timer.daemon = True
|
||||
timer.start()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
settings = load_settings()
|
||||
uvicorn.run(
|
||||
config = uvicorn.Config(
|
||||
'app.main:app',
|
||||
host=settings.host,
|
||||
port=settings.port,
|
||||
log_level=settings.log_level,
|
||||
timeout_graceful_shutdown=settings.shutdown_timeout,
|
||||
timeout_keep_alive=settings.keepalive_timeout,
|
||||
)
|
||||
DrainingServer(config, settings.drain_seconds).run()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
Reference in New Issue
Block a user