73 lines
2.2 KiB
Python
73 lines
2.2 KiB
Python
import logging
|
|
import socket
|
|
import sys
|
|
|
|
import uvicorn
|
|
from fastapi import FastAPI
|
|
|
|
from app.api.api import api_router
|
|
from app.core.config import settings
|
|
|
|
# Configure logging
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
app = FastAPI(
|
|
title=settings.PROJECT_NAME,
|
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
|
description="Todo application API",
|
|
version="0.1.0",
|
|
)
|
|
|
|
@app.get("/health", tags=["health"], summary="Health check endpoint")
|
|
def health_check():
|
|
"""
|
|
Basic health check that always returns status ok.
|
|
|
|
This endpoint is used by monitoring systems to check if the application is running.
|
|
"""
|
|
return {"status": "ok"}
|
|
|
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
|
|
|
def find_available_port(start_port, max_attempts=10):
|
|
"""Try to find an available port starting from start_port"""
|
|
for port in range(start_port, start_port + max_attempts):
|
|
try:
|
|
# Try to create a socket with the port
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
s.bind((settings.HOST, port))
|
|
# If we get here, the port is available
|
|
return port
|
|
except OSError:
|
|
# Port is already in use, try the next one
|
|
continue
|
|
|
|
# If we get here, no ports were available in our range
|
|
port_range_end = start_port + max_attempts - 1
|
|
logger.warning(
|
|
f"Could not find an available port in range {start_port}-{port_range_end}"
|
|
)
|
|
return None
|
|
|
|
if __name__ == "__main__":
|
|
port = settings.PORT
|
|
|
|
# Check if the port is already in use
|
|
try:
|
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
|
|
s.bind((settings.HOST, port))
|
|
except OSError:
|
|
logger.warning(
|
|
f"Port {port} is already in use. Trying to find an available port..."
|
|
)
|
|
port = find_available_port(port + 1)
|
|
|
|
if port is None:
|
|
logger.error("Could not find an available port. Exiting.")
|
|
sys.exit(1)
|
|
|
|
logger.info(f"Using alternative port: {port}")
|
|
|
|
# Start the server with the available port
|
|
uvicorn.run("main:app", host=settings.HOST, port=port, reload=True) |