2025-12-05 15:09:39 +08:00
|
|
|
|
import logging
|
|
|
|
|
|
from contextlib import asynccontextmanager
|
2025-11-26 21:11:12 +08:00
|
|
|
|
from fastapi import FastAPI
|
|
|
|
|
|
from fastapi.middleware.cors import CORSMiddleware
|
2025-12-05 15:09:39 +08:00
|
|
|
|
|
2025-11-26 21:11:12 +08:00
|
|
|
|
from app.core.config import settings
|
|
|
|
|
|
from app.api.v1.api import api_router
|
2025-12-05 15:09:39 +08:00
|
|
|
|
from app.db.session import AsyncSessionLocal
|
|
|
|
|
|
from app.db.init_db import init_db
|
|
|
|
|
|
|
2026-01-09 13:23:49 +08:00
|
|
|
|
from app.core.timezone import beijing_time
|
|
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
# 配置日志
|
2026-01-09 13:23:49 +08:00
|
|
|
|
logging.Formatter.converter = beijing_time
|
2026-01-04 17:16:44 +08:00
|
|
|
|
logging.basicConfig(
|
2026-01-16 10:21:30 +08:00
|
|
|
|
level=logging.INFO,
|
2026-01-04 17:16:44 +08:00
|
|
|
|
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
|
|
|
|
|
datefmt='%Y-%m-%d %H:%M:%S'
|
|
|
|
|
|
)
|
2025-12-05 15:09:39 +08:00
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
|
2025-12-12 15:50:48 +08:00
|
|
|
|
# 禁用 uvicorn access log 和 LiteLLM INFO 日志
|
|
|
|
|
|
logging.getLogger("uvicorn.access").setLevel(logging.WARNING)
|
|
|
|
|
|
logging.getLogger("LiteLLM").setLevel(logging.WARNING)
|
|
|
|
|
|
logging.getLogger("litellm").setLevel(logging.WARNING)
|
|
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
|
2025-12-15 15:18:55 +08:00
|
|
|
|
async def check_agent_services():
|
|
|
|
|
|
"""检查 Agent 必须服务的可用性"""
|
|
|
|
|
|
issues = []
|
|
|
|
|
|
|
|
|
|
|
|
# 检查 Docker/沙箱服务
|
|
|
|
|
|
try:
|
|
|
|
|
|
import docker
|
|
|
|
|
|
client = docker.from_env()
|
|
|
|
|
|
client.ping()
|
|
|
|
|
|
logger.info(" - Docker 服务可用")
|
|
|
|
|
|
except ImportError:
|
|
|
|
|
|
issues.append("Docker Python 库未安装 (pip install docker)")
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
issues.append(f"Docker 服务不可用: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
# 检查 Redis 连接(可选警告)
|
|
|
|
|
|
try:
|
|
|
|
|
|
import redis
|
|
|
|
|
|
import os
|
|
|
|
|
|
redis_url = os.environ.get("REDIS_URL", "redis://localhost:6379/0")
|
|
|
|
|
|
r = redis.from_url(redis_url)
|
|
|
|
|
|
r.ping()
|
|
|
|
|
|
logger.info(" - Redis 服务可用")
|
|
|
|
|
|
except ImportError:
|
|
|
|
|
|
logger.warning(" - Redis Python 库未安装,部分功能可能受限")
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.warning(f" - Redis 服务连接失败: {e}")
|
|
|
|
|
|
|
|
|
|
|
|
return issues
|
|
|
|
|
|
|
|
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
@asynccontextmanager
|
|
|
|
|
|
async def lifespan(app: FastAPI):
|
|
|
|
|
|
"""
|
|
|
|
|
|
应用生命周期管理
|
|
|
|
|
|
启动时初始化数据库(创建默认账户等)
|
|
|
|
|
|
"""
|
2025-12-08 21:35:09 +08:00
|
|
|
|
logger.info("DeepAudit 后端服务启动中...")
|
2025-12-15 15:18:55 +08:00
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
# 初始化数据库(创建默认账户)
|
2025-12-05 19:31:47 +08:00
|
|
|
|
# 注意:需要先运行 alembic upgrade head 创建表结构
|
2025-12-05 15:09:39 +08:00
|
|
|
|
try:
|
|
|
|
|
|
async with AsyncSessionLocal() as db:
|
|
|
|
|
|
await init_db(db)
|
2025-12-15 15:18:55 +08:00
|
|
|
|
logger.info(" - 数据库初始化完成")
|
2025-12-05 15:09:39 +08:00
|
|
|
|
except Exception as e:
|
2025-12-05 19:31:47 +08:00
|
|
|
|
# 表不存在时静默跳过,等待用户运行数据库迁移
|
|
|
|
|
|
error_msg = str(e)
|
|
|
|
|
|
if "does not exist" in error_msg or "UndefinedTableError" in error_msg:
|
|
|
|
|
|
logger.info("数据库表未创建,请先运行: alembic upgrade head")
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.warning(f"数据库初始化跳过: {e}")
|
2025-12-15 15:18:55 +08:00
|
|
|
|
|
|
|
|
|
|
# 检查 Agent 服务
|
|
|
|
|
|
logger.info("检查 Agent 核心服务...")
|
|
|
|
|
|
issues = await check_agent_services()
|
|
|
|
|
|
if issues:
|
|
|
|
|
|
logger.warning("=" * 50)
|
|
|
|
|
|
logger.warning("Agent 服务检查发现问题:")
|
|
|
|
|
|
for issue in issues:
|
|
|
|
|
|
logger.warning(f" - {issue}")
|
|
|
|
|
|
logger.warning("部分功能可能不可用,请检查配置")
|
|
|
|
|
|
logger.warning("=" * 50)
|
|
|
|
|
|
else:
|
|
|
|
|
|
logger.info(" - Agent 核心服务检查通过")
|
|
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
logger.info("=" * 50)
|
2025-12-08 21:35:09 +08:00
|
|
|
|
logger.info("DeepAudit 后端服务已启动")
|
2025-12-05 15:09:39 +08:00
|
|
|
|
logger.info(f"API 文档: http://localhost:8000/docs")
|
|
|
|
|
|
logger.info("=" * 50)
|
|
|
|
|
|
logger.info("演示账户: demo@example.com / demo123")
|
|
|
|
|
|
logger.info("=" * 50)
|
2025-12-15 15:18:55 +08:00
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
yield
|
2025-12-15 15:18:55 +08:00
|
|
|
|
|
2025-12-08 21:35:09 +08:00
|
|
|
|
logger.info("DeepAudit 后端服务已关闭")
|
2025-12-05 15:09:39 +08:00
|
|
|
|
|
2025-11-26 21:11:12 +08:00
|
|
|
|
|
|
|
|
|
|
app = FastAPI(
|
|
|
|
|
|
title=settings.PROJECT_NAME,
|
2025-12-05 15:09:39 +08:00
|
|
|
|
openapi_url=f"{settings.API_V1_STR}/openapi.json",
|
|
|
|
|
|
lifespan=lifespan
|
2025-11-26 21:11:12 +08:00
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# Configure CORS - Allow all origins in development
|
|
|
|
|
|
app.add_middleware(
|
|
|
|
|
|
CORSMiddleware,
|
|
|
|
|
|
allow_origins=["*"], # In production, replace with specific frontend URL
|
|
|
|
|
|
allow_credentials=True,
|
|
|
|
|
|
allow_methods=["*"],
|
|
|
|
|
|
allow_headers=["*"],
|
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
|
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
|
2025-11-26 21:11:12 +08:00
|
|
|
|
@app.get("/health")
|
|
|
|
|
|
async def health_check():
|
|
|
|
|
|
return {"status": "ok"}
|
|
|
|
|
|
|
2025-12-05 15:09:39 +08:00
|
|
|
|
|
2025-11-26 21:11:12 +08:00
|
|
|
|
@app.get("/")
|
|
|
|
|
|
async def root():
|
2025-12-05 15:09:39 +08:00
|
|
|
|
return {
|
2025-12-08 21:35:09 +08:00
|
|
|
|
"message": "Welcome to DeepAudit API",
|
2025-12-05 15:09:39 +08:00
|
|
|
|
"docs": "/docs",
|
|
|
|
|
|
"demo_account": {
|
|
|
|
|
|
"email": "demo@example.com",
|
|
|
|
|
|
"password": "demo123"
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|