import asyncio import os from contextlib import asynccontextmanager import uvicorn from fastapi import Depends, FastAPI from auth_config import Caller, auth from db_module import close_connection_pool, create_connection_pool, start_healthcheck_thread from handlers import register_handlers from metrics_server import metrics_api from routers.scheduler import scheduler_router from routers.user import user_router from secret_manager import cleanup_secret_files from send_notifications import NotificationClient from simple_logger_handler import LOG_LEVEL, setup_logger logger = setup_logger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): logger.info("[FastAPI] Starting application...") app.state.notifier = NotificationClient() logger.info("[FastAPI] Creating MySQL connection pool...") create_connection_pool("repositoryQueryPool") start_healthcheck_thread() logger.info("[FastAPI] MySQL healthcheck thread started.") SECRET_PATHS = frozenset({ "/etc/secrets/api_key", "/etc/secrets/db_username", "/etc/secrets/db_password", "/etc/secrets/dockerhub_token", "/etc/secrets/dockerhub_username", "/etc/secrets/github_token" }) cleanup_secret_files(SECRET_PATHS) yield logger.info("[FastAPI] Closing MySQL connection pool...") close_connection_pool() logger.info("[FastAPI] Shutdown complete.") api = FastAPI( title="Docker Repository Query", description="Queries Dockerhub and GHCR for new docker images", version="1.0.0", lifespan=lifespan, dependencies=[Depends(auth.authenticate)], ) register_handlers(api) api.include_router(user_router) api.include_router(scheduler_router) async def start_servers(): logger.info("[Server] Starting main API (port 5000) and metrics server (port 9000)...") logger.info(f"[Server] Build commit id={os.getenv("COMMIT_ID","unknown")}") auth.load_keys(api, Caller.GATEWAY, Caller.SCHEDULER) cleanup_secret_files(auth.key_paths(Caller.GATEWAY, Caller.SCHEDULER)) config_main = uvicorn.Config(api, host="0.0.0.0", port=5000, log_level=LOG_LEVEL.lower(), log_config=None) config_metrics = uvicorn.Config(metrics_api, host="0.0.0.0", port=9000, log_level=LOG_LEVEL.lower(), log_config=None) server_main = uvicorn.Server(config_main) server_metrics = uvicorn.Server(config_metrics) await asyncio.gather(server_main.serve(), server_metrics.serve()) logger.info("[Server] Both servers have stopped") if __name__ == "__main__": asyncio.run(start_servers())