Leave the rotation before closing the listener on SIGTERM

On SIGTERM gunicorn closed the listener at once, so a request already
queued on the closing socket reached the balancer as a dropped
connection after sending: a retry for GET and keyed messages, a 502
for user, chat and login posts. Now each worker first raises a
draining flag and keeps serving for DRAIN_SECONDS (2 s by default,
above the 1.5 s worst detection of a 503): readiness answers 503
unavailable, liveness stays 200, and the balancer takes the replica
out while it is still healthy. Only then uvicorn closes the listener
and finishes accepted requests within SHUTDOWN_TIMEOUT_SECONDS minus
the window, so gunicorn graceful_timeout stays 5 s.

The worker runs a uvicorn Server subclass whose main loop adds the
window after the exit signal; UvicornWorker._serve is overridden to
use it. Tests check readiness under the flag and run real gunicorn on
a free port: during the window ready is 503 and live 200, the port
closes after the window, a registration accepted before SIGTERM and
finished after the port closed still gets 201, and the master exits
with code 0 before the shutdown limit.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Artyom
2026-10-28 19:33:02 +03:00
co-authored by Claude Opus 5.5
parent 6e4c387e50
commit 6fb4587ef6
4 changed files with 145 additions and 6 deletions
+27 -2
View File
@@ -1,13 +1,21 @@
import asyncio
import logging
import os
import sys
from typing import Any
from gunicorn.arbiter import Arbiter
from gunicorn.glogging import Logger as GunicornBaseLogger
from uvicorn.server import Server
from uvicorn_worker import UvicornWorker
from messenger.main import LOG_FIELDS
from messenger.shared.entrypoints.health import DRAINING
from messenger.shared.infrastructure.logging import configure
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
SHUTDOWN_SECONDS = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5"))
DRAIN_SECONDS = float(os.environ.get("DRAIN_SECONDS", "2"))
class StructlogGunicornLogger(GunicornBaseLogger):
@@ -18,14 +26,31 @@ class StructlogGunicornLogger(GunicornBaseLogger):
return
class DrainingServer(Server):
async def main_loop(self) -> None:
await super().main_loop()
if not self.force_exit:
DRAINING.set()
logging.getLogger("uvicorn.error").info("Draining for %.1f s", DRAIN_SECONDS)
await asyncio.sleep(DRAIN_SECONDS)
class MessengerWorker(UvicornWorker):
CONFIG_KWARGS: dict[str, Any] = {
"access_log": False,
"server_header": False,
"date_header": False,
"timeout_graceful_shutdown": int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5")),
"timeout_graceful_shutdown": max(1, int(SHUTDOWN_SECONDS - DRAIN_SECONDS)),
}
async def _serve(self) -> None:
self.config.app = self.wsgi
server = DrainingServer(config=self.config)
self._install_sigquit_handler()
await server.serve(sockets=self.sockets)
if not server.started:
sys.exit(Arbiter.WORKER_BOOT_ERROR)
bind = f"{os.environ.get('HOST', '0.0.0.0')}:{os.environ.get('PORT', '8080')}"
workers = int(os.environ.get("WEB_CONCURRENCY", "2"))
@@ -35,7 +60,7 @@ loglevel = LOG_LEVEL.lower()
accesslog = None
errorlog = "-"
timeout = int(float(os.environ.get("REQUEST_TIMEOUT_SECONDS", "8")) + 5)
graceful_timeout = int(os.environ.get("SHUTDOWN_TIMEOUT_SECONDS", "5"))
graceful_timeout = SHUTDOWN_SECONDS
keepalive = 5
preload_app = False
control_socket_disable = True
@@ -1,10 +1,14 @@
from threading import Event
from dishka.integrations.fastapi import FromDishka, inject
from fastapi import APIRouter
from messenger.shared.application.errors import Unavailable
from messenger.shared.entrypoints.schemas import HealthOut
from messenger.shared.infrastructure.postgres import Database
router = APIRouter(tags=["health"])
DRAINING = Event()
@router.get("/health/live")
@@ -15,5 +19,7 @@ async def live() -> HealthOut:
@router.get("/health/ready")
@inject
async def ready(database: FromDishka[Database]) -> HealthOut:
if DRAINING.is_set():
raise Unavailable("Реплика выходит из ротации")
await database.ping()
return HealthOut()