- etl_app:FastAPI + NiceGUI 管理页(概览、运行记录、设置),仅 Metrix 管理员可访问,中英文与日夜间 - 设置页可配定时频率(间隔/Cron)、超时、Metrix 接口、FTP/SFTP 直连、MySQL 直连、目录与保留策略,密码只写不回显 - APScheduler 在同一容器内定时,每次运行是容器内子进程,单实例互斥、超时终止,运行记录存 SQLite、日志落盘 - main.py 抽出文件存储与数据库写入接口,新增 FTP/SFTP/MySQL 实现,脚本模式 CLI 不变 - deploy/Dockerfile、requirements-app.txt、scripts/package_metrix.py 生成应用包,README 补充说明 - 新增 tests/test_app.py,覆盖设置、运行记录、执行器、调度、身份、接口与各连接器
137 lines
4.5 KiB
Python
137 lines
4.5 KiB
Python
from __future__ import annotations
|
|
|
|
import logging
|
|
import os
|
|
from collections.abc import AsyncIterator
|
|
from contextlib import asynccontextmanager
|
|
from typing import Any
|
|
|
|
from fastapi import Body, Depends, FastAPI, HTTPException
|
|
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
|
|
|
|
from .auth import Identity, require_admin
|
|
from .config import SettingsError, data_dir, public_view
|
|
from .service import EtlService
|
|
|
|
LANDING_HTML = """<!doctype html>
|
|
<html><head><meta charset="utf-8"><title>InterferenceETL</title>
|
|
<script>location.replace(location.pathname.replace(/\\/?$/, '/') + 'admin');</script>
|
|
</head><body><a href="admin">InterferenceETL</a></body></html>
|
|
"""
|
|
|
|
|
|
def settings_error(exc: SettingsError) -> JSONResponse:
|
|
return JSONResponse(status_code=422, content={"error": exc.key, "field": exc.field, "params": exc.params})
|
|
|
|
|
|
def build_api(service: EtlService) -> FastAPI:
|
|
@asynccontextmanager
|
|
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
|
service.start()
|
|
try:
|
|
yield
|
|
finally:
|
|
service.stop()
|
|
|
|
api = FastAPI(title="InterferenceETL", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
|
|
|
@api.get("/", include_in_schema=False)
|
|
def landing() -> HTMLResponse:
|
|
return HTMLResponse(LANDING_HTML)
|
|
|
|
@api.get("/healthz")
|
|
def health() -> dict[str, bool]:
|
|
return {"ok": True}
|
|
|
|
@api.get("/api/status")
|
|
def status(_: Identity = Depends(require_admin)) -> dict[str, Any]:
|
|
return service.status()
|
|
|
|
@api.get("/api/settings")
|
|
def read_settings(_: Identity = Depends(require_admin)) -> dict[str, Any]:
|
|
return public_view(service.settings.get())
|
|
|
|
@api.put("/api/settings", response_model=None)
|
|
def write_settings(payload: dict[str, Any] = Body(...), _: Identity = Depends(require_admin)) -> Any:
|
|
try:
|
|
return public_view(service.update_settings(payload))
|
|
except SettingsError as exc:
|
|
return settings_error(exc)
|
|
|
|
@api.post("/api/checks", response_model=None)
|
|
def checks(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> Any:
|
|
try:
|
|
return service.check_connections(payload)
|
|
except SettingsError as exc:
|
|
return settings_error(exc)
|
|
|
|
@api.get("/api/runs")
|
|
def runs(page: int = 1, page_size: int = 20, status: str = "", _: Identity = Depends(require_admin)) -> dict[str, Any]:
|
|
items, total = service.runs.page(max(1, page), min(max(1, page_size), 200), status)
|
|
return {"items": items, "total": total}
|
|
|
|
@api.post("/api/runs")
|
|
def start_run(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> dict[str, bool]:
|
|
if not service.settings.configured():
|
|
raise HTTPException(status_code=409, detail="not_configured")
|
|
if not service.runner.start("manual", bool((payload or {}).get("dry_run"))):
|
|
raise HTTPException(status_code=409, detail="busy")
|
|
return {"started": True}
|
|
|
|
@api.post("/api/runs/cancel")
|
|
def cancel_run(_: Identity = Depends(require_admin)) -> dict[str, bool]:
|
|
return {"cancelled": service.runner.cancel()}
|
|
|
|
@api.get("/api/runs/{run_id}/log", response_class=PlainTextResponse)
|
|
def run_log(run_id: int, _: Identity = Depends(require_admin)) -> str:
|
|
if service.runs.get(run_id) is None:
|
|
raise HTTPException(status_code=404, detail="not_found")
|
|
return service.runner.read_log(run_id)
|
|
|
|
return api
|
|
|
|
|
|
def create_app() -> FastAPI:
|
|
from nicegui import ui
|
|
|
|
from .theme import ICON_PATH
|
|
from .ui import register
|
|
|
|
service = EtlService(data_dir())
|
|
api = build_api(service)
|
|
register(service)
|
|
ui.run_with(
|
|
api,
|
|
title="InterferenceETL",
|
|
favicon=ICON_PATH,
|
|
dark=None,
|
|
language="zh-CN",
|
|
reconnect_timeout=10,
|
|
show_welcome_message=False,
|
|
)
|
|
return api
|
|
|
|
|
|
class QuietSockets(logging.Filter):
|
|
def filter(self, record: logging.LogRecord) -> bool:
|
|
message = record.getMessage()
|
|
return not (message.startswith("connection ") or '"WebSocket ' in message)
|
|
|
|
|
|
def main() -> None:
|
|
import uvicorn
|
|
|
|
config = uvicorn.Config(
|
|
create_app(),
|
|
host=os.getenv("HOST", "0.0.0.0"),
|
|
port=int(os.getenv("PORT", "8080")),
|
|
access_log=False,
|
|
timeout_graceful_shutdown=15,
|
|
)
|
|
logging.getLogger("uvicorn.error").addFilter(QuietSockets())
|
|
uvicorn.Server(config).run()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|