Files
mtusi2026lab7-fork/src/server.py

83 lines
3.9 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Точка входа контейнера: Uvicorn (только HTTPS + mTLS) с фазой осушения перед остановкой.
lab7
----
* Бизнес-порт APP_PORT (8443) — только TLS. Клиентский сертификат обязателен
(CERT_REQUIRED, CA = TLS_CA_FILE), после рукопожатия identity сверяется с
MTLS_ALLOWED_CLIENTS и CRL (src/tls.py). Plaintext HTTP на этом порту нет.
* Docker healthcheck не умеет mTLS, поэтому есть второй, минимальный listener
HEALTH_PORT (8081) на 127.0.0.1 ВНУТРИ контейнера: только GET /health/live и
/health/ready, без бизнес-API. Снаружи контейнера он недоступен (loopback).
LB проверяет реплики по mTLS через основной порт.
Последовательность при SIGTERM (docker stop / rolling update / stop-one) — как в lab3:
t=0 SIGTERM -> /health/ready = 503, ответы с Connection: close;
t<=1.5 с HAProxy помечает реплику DOWN;
t=DRAIN_SECONDS -> Uvicorn закрывает listener, ждёт запросы (<= GRACEFUL_TIMEOUT_SECONDS).
"""
import logging
import os
import ssl
import threading
import uvicorn
from uvicorn.protocols.http.h11_impl import H11Protocol
from . import tls
from .runtime import DRAIN, INSTANCE_ID
log = logging.getLogger("messenger.server")
class DrainingServer(uvicorn.Server):
drain_seconds = 3.0
def handle_exit(self, sig, frame): # вызывается из обработчика сигнала
if self.should_exit or not DRAIN.begin():
return super().handle_exit(sig, frame)
log.info(
"signal %s: instance %s draining for %.1fs (readiness=503), then graceful stop",
sig, INSTANCE_ID, self.drain_seconds,
)
timer = threading.Timer(self.drain_seconds, super().handle_exit, args=(sig, frame))
timer.daemon = True
timer.start()
def main() -> None:
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s %(message)s")
cert = os.environ.get("TLS_CERT_FILE", "").strip()
key = os.environ.get("TLS_KEY_FILE", "").strip()
ca = os.environ.get("TLS_CA_FILE", "").strip()
plaintext_allowed = os.environ.get("ALLOW_PLAINTEXT_FOR_LOCAL_DEV", "").lower() == "true"
kwargs = {}
if cert and key and ca:
tls.POLICY = tls.policy_from_env()
kwargs = dict(ssl_certfile=cert, ssl_keyfile=key, ssl_ca_certs=ca,
ssl_cert_reqs=ssl.CERT_REQUIRED, http=tls.identity_checking_protocol(H11Protocol))
log.info("HTTPS with mandatory client certificate; allowed identities=%s crl=%s",
sorted(tls.POLICY.allowed), "on" if tls.POLICY.crl_file else "off")
elif not plaintext_allowed:
# Нет «тихого» отката на HTTP: без сертификатов реплика не стартует.
raise SystemExit("TLS_CERT_FILE, TLS_KEY_FILE and TLS_CA_FILE are required (lab7: HTTPS + mTLS only)")
config = uvicorn.Config(
"src.main:app",
host=os.environ.get("APP_HOST", "0.0.0.0"),
port=int(os.environ.get("APP_PORT", "8443")),
timeout_keep_alive=int(os.environ.get("KEEP_ALIVE_SECONDS", "30")),
timeout_graceful_shutdown=int(os.environ.get("GRACEFUL_TIMEOUT_SECONDS", "10")),
access_log=False,
server_header=False,
log_config=None,
# Ограничение размера заголовков запроса (h11), байт.
h11_max_incomplete_event_size=int(os.environ.get("MAX_HEADER_BYTES", "16384")),
**kwargs,
)
server = DrainingServer(config)
server.drain_seconds = float(os.environ.get("DRAIN_SECONDS", "3"))
server.run()
if __name__ == "__main__":
main()