forked from mtusi2026/mtusi2026lab4
61 lines
1.8 KiB
Python
61 lines
1.8 KiB
Python
"""Container entrypoint: run the HTTP server as PID 1 with graceful shutdown.
|
|
|
|
Migrations are executed by the dedicated one-shot ``migrate`` compose service
|
|
(``python -m src.migrate``) before any replica starts, so replicas do not race
|
|
on the schema.
|
|
|
|
On SIGTERM/SIGINT the handler marks the process as shutting down: readiness
|
|
degrades to 503 so the balancer drains this replica, then Uvicorn stops
|
|
accepting connections and waits up to ``timeout_graceful_shutdown`` for
|
|
in-flight requests to finish.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
|
|
import uvicorn
|
|
|
|
from . import state
|
|
from .config import settings
|
|
from .instance import INSTANCE_ID
|
|
|
|
|
|
def main() -> None:
|
|
logging.basicConfig(
|
|
level=os.environ.get("LOG_LEVEL", "INFO").upper(),
|
|
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
|
)
|
|
logging.getLogger("messenger").info(
|
|
"starting messenger api instance=%s env=%s port=%s sessions=%s cache=%s",
|
|
INSTANCE_ID,
|
|
settings.app_env,
|
|
settings.app_port,
|
|
settings.session_store,
|
|
"on" if settings.cache_enabled else "off",
|
|
)
|
|
|
|
config = uvicorn.Config(
|
|
"src.app:app",
|
|
host=settings.app_host,
|
|
port=settings.app_port,
|
|
log_level=os.environ.get("LOG_LEVEL", "info").lower(),
|
|
access_log=True,
|
|
timeout_graceful_shutdown=10,
|
|
)
|
|
server = uvicorn.Server(config)
|
|
|
|
def handle_exit(sig, frame=None): # noqa: ANN001 - signal handler
|
|
state.begin_shutdown()
|
|
logging.getLogger("messenger").info("received signal %s; draining", sig)
|
|
server.should_exit = True
|
|
|
|
# Uvicorn installs this exact method as its signal handler; overriding the
|
|
# bound attribute keeps cross-platform behaviour while adding our flag.
|
|
server.handle_exit = handle_exit
|
|
server.run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|