|
| 1 | +import os |
| 2 | +from collections.abc import AsyncGenerator |
| 3 | +from contextlib import asynccontextmanager |
| 4 | + |
| 5 | +from fastapi import FastAPI |
| 6 | +from loguru import logger |
| 7 | +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter |
| 8 | +from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor |
| 9 | +from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor |
| 10 | +from opentelemetry.instrumentation.redis import RedisInstrumentor |
| 11 | +from opentelemetry.instrumentation.sqlalchemy import SQLAlchemyInstrumentor |
| 12 | +from opentelemetry.sdk.resources import ( |
| 13 | + DEPLOYMENT_ENVIRONMENT, |
| 14 | + SERVICE_NAME, |
| 15 | + TELEMETRY_SDK_LANGUAGE, |
| 16 | + Resource, |
| 17 | +) |
| 18 | +from opentelemetry.sdk.trace import TracerProvider |
| 19 | +from opentelemetry.sdk.trace.export import BatchSpanProcessor |
| 20 | +from opentelemetry.trace import set_tracer_provider |
| 21 | +from prometheus_fastapi_instrumentator.instrumentation import ( |
| 22 | + PrometheusFastApiInstrumentator, |
| 23 | +) |
| 24 | +from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine |
| 25 | + |
| 26 | +from app.adapters.kafka.lifespan import init_kafka, shutdown_kafka |
| 27 | +from app.adapters.rabbit.lifespan import init_rabbit, shutdown_rabbit |
| 28 | +from app.adapters.redis.lifespan import init_redis, shutdown_redis |
| 29 | +from app.core.config import settings |
| 30 | +from app.core.tkq import broker |
| 31 | + |
| 32 | + |
| 33 | +def _setup_db(app: FastAPI) -> None: # pragma: no cover |
| 34 | + """ |
| 35 | + Creates connection to the database. |
| 36 | +
|
| 37 | + This function creates SQLAlchemy engine instance, |
| 38 | + session_factory for creating sessions |
| 39 | + and stores them in the application's state property. |
| 40 | +
|
| 41 | + :param app: fastAPI application. |
| 42 | + """ |
| 43 | + engine = create_async_engine(str(settings.db_url), echo=settings.DB_ECHO) |
| 44 | + session_factory = async_sessionmaker( |
| 45 | + engine, |
| 46 | + # See https://fastapi-users.github.io/fastapi-users/latest/configuration/databases/sqlalchemy/#asynchronous-driver |
| 47 | + expire_on_commit=False, |
| 48 | + ) |
| 49 | + app.state.db_engine = engine |
| 50 | + app.state.db_session_factory = session_factory |
| 51 | + |
| 52 | + |
| 53 | +def setup_opentelemetry(app: FastAPI) -> None: # pragma: no cover |
| 54 | + """ |
| 55 | + Enables opentelemetry instrumentation. |
| 56 | +
|
| 57 | + :param app: current application. |
| 58 | + """ |
| 59 | + if not settings.OPENTELEMETRY_ENDPOINT: |
| 60 | + return |
| 61 | + |
| 62 | + tracer_provider = TracerProvider( |
| 63 | + resource=Resource( |
| 64 | + attributes={ |
| 65 | + SERVICE_NAME: settings.API_CONTAINER_HOST, |
| 66 | + TELEMETRY_SDK_LANGUAGE: "python", |
| 67 | + DEPLOYMENT_ENVIRONMENT: settings.ENVIRONMENT, |
| 68 | + }, |
| 69 | + ), |
| 70 | + ) |
| 71 | + |
| 72 | + tracer_provider.add_span_processor( |
| 73 | + BatchSpanProcessor( |
| 74 | + OTLPSpanExporter( |
| 75 | + endpoint=settings.OPENTELEMETRY_ENDPOINT, |
| 76 | + insecure=True, |
| 77 | + ), |
| 78 | + ), |
| 79 | + ) |
| 80 | + |
| 81 | + excluded_endpoints = [ |
| 82 | + app.url_path_for("health_check"), |
| 83 | + app.url_path_for("openapi"), |
| 84 | + app.url_path_for("swagger_ui_html"), |
| 85 | + app.url_path_for("swagger_ui_redirect"), |
| 86 | + app.url_path_for("redoc_html"), |
| 87 | + "/metrics", |
| 88 | + ] |
| 89 | + |
| 90 | + FastAPIInstrumentor().instrument_app( |
| 91 | + app, |
| 92 | + tracer_provider=tracer_provider, |
| 93 | + excluded_urls=",".join(excluded_endpoints), |
| 94 | + ) |
| 95 | + RedisInstrumentor().instrument( |
| 96 | + tracer_provider=tracer_provider, |
| 97 | + ) |
| 98 | + SQLAlchemyInstrumentor().instrument( |
| 99 | + tracer_provider=tracer_provider, |
| 100 | + engine=app.state.db_engine.sync_engine, |
| 101 | + ) |
| 102 | + AioPikaInstrumentor().instrument( |
| 103 | + tracer_provider=tracer_provider, |
| 104 | + ) |
| 105 | + |
| 106 | + set_tracer_provider(tracer_provider=tracer_provider) |
| 107 | + |
| 108 | + |
| 109 | +def stop_opentelemetry(app: FastAPI) -> None: # pragma: no cover |
| 110 | + """ |
| 111 | + Disables opentelemetry instrumentation. |
| 112 | +
|
| 113 | + :param app: current application. |
| 114 | + """ |
| 115 | + if not settings.OPENTELEMETRY_ENDPOINT: |
| 116 | + return |
| 117 | + |
| 118 | + FastAPIInstrumentor().uninstrument_app(app) |
| 119 | + RedisInstrumentor().uninstrument() |
| 120 | + SQLAlchemyInstrumentor().uninstrument() |
| 121 | + AioPikaInstrumentor().uninstrument() |
| 122 | + |
| 123 | + |
| 124 | +def setup_prometheus(app: FastAPI) -> None: # pragma: no cover |
| 125 | + """ |
| 126 | + Enables prometheus integration. |
| 127 | +
|
| 128 | + :param app: current application. |
| 129 | + """ |
| 130 | + PrometheusFastApiInstrumentator(should_group_status_codes=False).instrument( |
| 131 | + app, |
| 132 | + ).expose(app, should_gzip=True, name="prometheus_metrics") |
| 133 | + |
| 134 | + |
| 135 | +@asynccontextmanager |
| 136 | +async def lifespan_setup( |
| 137 | + app: FastAPI, |
| 138 | +) -> AsyncGenerator[None]: # pragma: no cover |
| 139 | + """ |
| 140 | + Actions to run on application startup. |
| 141 | +
|
| 142 | + This function uses fastAPI app to store data |
| 143 | + in the state, such as db_engine. |
| 144 | +
|
| 145 | + :param app: the fastAPI application. |
| 146 | + :return: function that actually performs actions. |
| 147 | + """ |
| 148 | + app.middleware_stack = None |
| 149 | + if not broker.is_worker_process: |
| 150 | + await broker.startup() |
| 151 | + _setup_db(app) |
| 152 | + setup_opentelemetry(app) |
| 153 | + init_redis(app) |
| 154 | + init_rabbit(app) |
| 155 | + await init_kafka(app) |
| 156 | + setup_prometheus(app) |
| 157 | + app.middleware_stack = app.build_middleware_stack() |
| 158 | + |
| 159 | + logger.debug("Debug log") |
| 160 | + logger.info("Info log with cid + tracing") |
| 161 | + logger.warning("Warning log") |
| 162 | + logger.error("Error log") |
| 163 | + logger.critical("Critical log") |
| 164 | + |
| 165 | + logger.info(os.environ) |
| 166 | + logger.info(app.routes) |
| 167 | + |
| 168 | + yield |
| 169 | + if not broker.is_worker_process: |
| 170 | + await broker.shutdown() |
| 171 | + await app.state.db_engine.dispose() |
| 172 | + |
| 173 | + await shutdown_redis(app) |
| 174 | + await shutdown_rabbit(app) |
| 175 | + await shutdown_kafka(app) |
| 176 | + stop_opentelemetry(app) |
0 commit comments