848f804169
- FastAPI 后端 + Vue 3 前端 - Docker Compose 一键部署 - Casdoor OAuth 认证集成 - LogHive 集中式日志 - 设备批量 CSV 导入/导出 - WebSocket 实时状态推送 - 企业微信告警通知 - fping 高性能并发 Ping 检测 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
100 lines
2.3 KiB
Python
100 lines
2.3 KiB
Python
"""
|
|
PingWatch — 网络设备离线监控系统
|
|
FastAPI 后端入口
|
|
"""
|
|
|
|
import asyncio
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
from app.config import settings
|
|
from app.core.deps import init_db
|
|
from app.core.loghive import LogHiveHandler
|
|
from app.services.scheduler import scheduler
|
|
from app.services.cleanup import cleanup_old_data
|
|
from app.api import devices, alerts, stats, auth, ws, users
|
|
|
|
# 日志配置
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s [%(name)s] %(levelname)s: %(message)s",
|
|
)
|
|
|
|
# 接入 LogHive 日志系统
|
|
loghive_handler = LogHiveHandler(
|
|
endpoint=settings.LOGHIVE_ENDPOINT,
|
|
project=settings.LOGHIVE_PROJECT,
|
|
api_key=settings.LOGHIVE_API_KEY,
|
|
)
|
|
if settings.LOGHIVE_API_KEY:
|
|
logging.getLogger().addHandler(loghive_handler)
|
|
|
|
logger = logging.getLogger("pingwatch")
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""应用生命周期"""
|
|
logger.info("PingWatch 启动中...")
|
|
|
|
# 初始化数据库
|
|
await init_db()
|
|
logger.info("数据库初始化完成")
|
|
|
|
# 启动 Ping 调度器
|
|
scheduler.start()
|
|
logger.info("Ping 调度器已启动")
|
|
|
|
# 启动定时清理任务
|
|
async def cleanup_loop():
|
|
while True:
|
|
await asyncio.sleep(3600 * 6) # 每 6 小时
|
|
try:
|
|
await cleanup_old_data()
|
|
except Exception as e:
|
|
logger.error(f"清理任务异常: {e}")
|
|
|
|
cleanup_task = asyncio.create_task(cleanup_loop())
|
|
|
|
yield
|
|
|
|
# 关闭
|
|
await scheduler.stop()
|
|
cleanup_task.cancel()
|
|
loghive_handler.close()
|
|
logger.info("PingWatch 已关闭")
|
|
|
|
|
|
app = FastAPI(
|
|
title="PingWatch",
|
|
description="网络设备离线监控系统",
|
|
version="1.0.0",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# CORS
|
|
origins = [o.strip() for o in settings.CORS_ORIGINS.split(",")]
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=origins,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
# 注册路由
|
|
app.include_router(auth.router)
|
|
app.include_router(devices.router)
|
|
app.include_router(alerts.router)
|
|
app.include_router(stats.router)
|
|
app.include_router(ws.router)
|
|
app.include_router(users.router)
|
|
|
|
|
|
@app.get("/api/health")
|
|
async def health():
|
|
return {"status": "ok"}
|