feat: 支持托管到Metrix应用包并移除授权与平台模式
- 新增 scripts/package_metrix.py 打包应用包(user_auth=metrix、admin_auth=none、数据目录 /data) - 托管模式只认平台代理身份,停用应用登录与改密码,新增 /api/session - 后端按 X-Forwarded-Prefix 注入 <base href>,前端改为相对路径构建并按 basePath 请求 - 托管时隐藏登录页、退出按钮和修改密码页,顶栏显示 Metrix 用户名 - 移除授权到期校验、激活码和连点品牌图标打开的授权延期窗口 - 移除 Metrix 平台数据源/仓库模式及相关配置、接口、设置页和 requests 依赖 - 新增托管鉴权与 base href 注入测试,更新使用与开发文档
This commit is contained in:
+17
-3
@@ -1,12 +1,27 @@
|
||||
from fastapi import APIRouter, Body
|
||||
from fastapi import APIRouter, Body, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.auth import create_jwt_token, get_auth_config, save_auth_password
|
||||
from app.auth import (
|
||||
create_jwt_token,
|
||||
get_auth_config,
|
||||
is_hosted,
|
||||
resolve_platform_context,
|
||||
save_auth_password,
|
||||
)
|
||||
|
||||
|
||||
router = APIRouter(tags=["auth"])
|
||||
|
||||
|
||||
@router.get("/api/session")
|
||||
async def get_session(request: Request):
|
||||
if not is_hosted():
|
||||
return {"hosted": False, "user": None}
|
||||
context = resolve_platform_context(request)
|
||||
user = {"name": context.payload["name"], "role": context.payload["role"]} if context else None
|
||||
return {"hosted": True, "user": user}
|
||||
|
||||
|
||||
@router.post("/api/login")
|
||||
async def login(
|
||||
username: str = Body(..., embed=True),
|
||||
@@ -33,4 +48,3 @@ async def change_password(
|
||||
|
||||
save_auth_password(new_password)
|
||||
return {"success": True, "message": "密码修改成功"}
|
||||
|
||||
|
||||
@@ -14,11 +14,8 @@ from app.config import (
|
||||
DataMappingsConfig,
|
||||
DEFAULT_CELL_DATA_MAPPING,
|
||||
HistoryRetentionConfig,
|
||||
MetrixConfig,
|
||||
MySQLConfig,
|
||||
RemoteDataConfig,
|
||||
SOURCE_TYPES,
|
||||
WAREHOUSE_TYPES,
|
||||
)
|
||||
from app.services.remote_download import RemoteDataDownloader
|
||||
|
||||
@@ -62,41 +59,6 @@ async def update_remote_config(config: dict[str, Any] = Body(...)):
|
||||
return {"success": True, "message": "远程数据配置已更新", "update": state.config.update}
|
||||
|
||||
|
||||
@router.post("/api/config/metrix-enabled")
|
||||
async def update_metrix_enabled(enabled: bool = Body(..., embed=True)):
|
||||
state.reload_config()
|
||||
state.config.metrix_enabled = enabled
|
||||
if not enabled:
|
||||
state.config.source_type = "external"
|
||||
state.config.warehouse_type = "mysql"
|
||||
state.config.save()
|
||||
return {"success": True, "message": "已更新", "update": state.config.update}
|
||||
|
||||
|
||||
@router.post("/api/config/backend")
|
||||
async def update_backend(
|
||||
source_type: str = Body(...),
|
||||
warehouse_type: str = Body(...),
|
||||
):
|
||||
if source_type not in SOURCE_TYPES:
|
||||
raise HTTPException(status_code=400, detail="不支持的源类型")
|
||||
if warehouse_type not in WAREHOUSE_TYPES:
|
||||
raise HTTPException(status_code=400, detail="不支持的仓库类型")
|
||||
state.reload_config()
|
||||
state.config.source_type = source_type
|
||||
state.config.warehouse_type = warehouse_type
|
||||
state.config.save()
|
||||
return {"success": True, "message": "后端类型已更新", "update": state.config.update}
|
||||
|
||||
|
||||
@router.post("/api/config/metrix")
|
||||
async def update_metrix_config(config: dict[str, Any] = Body(...)):
|
||||
state.reload_config()
|
||||
state.config.metrix = MetrixConfig.from_dict(config)
|
||||
state.config.save()
|
||||
return {"success": True, "message": "Metrix 连接配置已更新", "update": state.config.update}
|
||||
|
||||
|
||||
@router.post("/api/config/data-mappings")
|
||||
async def update_data_mappings_config(config: dict[str, Any] = Body(...)):
|
||||
state.reload_config()
|
||||
@@ -255,23 +217,6 @@ async def upload_config(file: UploadFile = File(...)):
|
||||
|
||||
|
||||
def _apply_config_data(data: dict[str, Any]) -> None:
|
||||
if "MetrixEnabled" in data:
|
||||
state.config.metrix_enabled = bool(data["MetrixEnabled"])
|
||||
|
||||
if data.get("SourceType") in SOURCE_TYPES:
|
||||
state.config.source_type = data["SourceType"]
|
||||
if data.get("WarehouseType") in WAREHOUSE_TYPES:
|
||||
state.config.warehouse_type = data["WarehouseType"]
|
||||
|
||||
# 未启用 Metrix 时强制回落为外部储存 + 直连 MySQL,避免导入后状态不一致
|
||||
if not state.config.metrix_enabled:
|
||||
state.config.source_type = "external"
|
||||
state.config.warehouse_type = "mysql"
|
||||
|
||||
metrix_data = data.get("Metrix")
|
||||
if isinstance(metrix_data, dict):
|
||||
state.config.metrix = MetrixConfig.from_dict(metrix_data)
|
||||
|
||||
data_mappings = data.get("DataMappings")
|
||||
if isinstance(data_mappings, dict):
|
||||
state.config.data_mappings = DataMappingsConfig.from_dict(data_mappings)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""容量看板分析接口。
|
||||
|
||||
基于 4G/5G 结果表(含富集 + 高负荷判定 + 优化建议列)做聚合分析,供前端容量看板展示。
|
||||
读经 `make_warehouse`(直连 MySQL 或 Metrix 平台),分析对象为“主仓库”里的结果表。
|
||||
读经 `make_warehouse`(直连 MySQL),分析对象为“主仓库”里的结果表。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ from starlette.background import BackgroundTask
|
||||
from app import state
|
||||
from app.config import CACHE_DIR
|
||||
from app.database import DatabaseManager, detect_csv_encoding
|
||||
from app.services.platform import make_client
|
||||
from app.utils.files import remove_file_safely
|
||||
from app.warehouse import make_cell_data_warehouse, make_warehouse
|
||||
|
||||
@@ -55,7 +54,6 @@ def _dataframe_from_table(db: DatabaseManager, table_name: str) -> pd.DataFrame:
|
||||
|
||||
|
||||
def _db(database_source: DatabaseSource = "main"):
|
||||
"""Direct MySQL DatabaseManager, or a Metrix-backed warehouse with the same interface."""
|
||||
config = state.current_config()
|
||||
if database_source == "cell_data":
|
||||
return make_cell_data_warehouse(config)
|
||||
@@ -335,8 +333,8 @@ def execute_sql(
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
|
||||
# Sync def so FastAPI runs it in a threadpool: exporting large tables (and the Metrix
|
||||
# export-job polling) is blocking and would otherwise freeze the single-worker event loop.
|
||||
# Sync def so FastAPI runs it in a threadpool: exporting large tables is blocking and
|
||||
# would otherwise freeze the single-worker event loop.
|
||||
@router.post("/api/download")
|
||||
def download_table(
|
||||
table_name: Optional[str] = Body(None, embed=True),
|
||||
@@ -353,10 +351,6 @@ def download_table(
|
||||
if file_format == "csv" and len(requested_tables) != 1:
|
||||
raise HTTPException(status_code=400, detail="CSV 每次只能导出一张表")
|
||||
|
||||
config = state.current_config()
|
||||
if database_source == "main" and config.warehouse_type == "metrix":
|
||||
return _download_via_metrix(config, requested_tables, file_format)
|
||||
|
||||
db = _db(database_source)
|
||||
try:
|
||||
available_tables = set(db.get_tables())
|
||||
@@ -399,32 +393,3 @@ def download_table(
|
||||
media_type=media_type,
|
||||
background=BackgroundTask(remove_file_safely, filepath),
|
||||
)
|
||||
|
||||
|
||||
def _download_via_metrix(config, requested_tables: list[str], file_format: str) -> FileResponse:
|
||||
"""Metrix 仓库模式:用平台导出任务生成文件后流式返回(避免分页上限丢行)。"""
|
||||
metrix = config.metrix.normalized()
|
||||
client = make_client(metrix)
|
||||
try:
|
||||
job_id = client.submit_export(metrix.database_conn_id, requested_tables, file_format, metrix.target_database)
|
||||
job = client.wait_job(job_id)
|
||||
if job.get("status") != "success":
|
||||
raise HTTPException(status_code=500, detail=f"导出失败: {job.get('error_code') or job.get('status')}")
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
filename_prefix = requested_tables[0] if len(requested_tables) == 1 else "tables"
|
||||
filename = f"{filename_prefix}_{timestamp}.{file_format}"
|
||||
filepath = CACHE_DIR / filename
|
||||
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
client.download_job_file(job_id, filepath)
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=str(exc)) from exc
|
||||
|
||||
media_type = "text/csv" if file_format == "csv" else "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
return FileResponse(
|
||||
path=str(filepath),
|
||||
filename=filename,
|
||||
media_type=media_type,
|
||||
background=BackgroundTask(remove_file_safely, filepath),
|
||||
)
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
from fastapi import APIRouter, Body, HTTPException
|
||||
|
||||
from app.services.license import InvalidActivationCodeError, activate, get_license_info
|
||||
|
||||
|
||||
router = APIRouter(tags=["license"])
|
||||
|
||||
|
||||
@router.get("/api/license/status")
|
||||
async def get_license_status():
|
||||
info = get_license_info()
|
||||
return {"success": True, **info.to_dict()}
|
||||
|
||||
|
||||
@router.post("/api/license/activate")
|
||||
async def activate_license(code: str = Body(..., embed=True)):
|
||||
try:
|
||||
info = activate(code)
|
||||
except InvalidActivationCodeError as exc:
|
||||
raise HTTPException(status_code=400, detail=exc.to_detail()) from exc
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "激活成功,到期日期已延长 30 天",
|
||||
**info.to_dict(),
|
||||
}
|
||||
+13
-35
@@ -1,4 +1,3 @@
|
||||
import time
|
||||
from datetime import date, datetime
|
||||
from pathlib import Path
|
||||
from threading import Thread
|
||||
@@ -7,32 +6,23 @@ from typing import Any, Callable, Iterable
|
||||
from fastapi import APIRouter, Body, HTTPException
|
||||
|
||||
from app import state
|
||||
from app.api.routers.task_runtime import (
|
||||
apply_history_retention_safely,
|
||||
log_license_check,
|
||||
set_task_stage,
|
||||
)
|
||||
from app.api.routers.task_runtime import apply_history_retention_safely, set_task_stage
|
||||
from app.config import AppConfig, CACHE_DIR, RemoteDataConfig
|
||||
from app.processor import DataProcessor, ProcessLogger
|
||||
from app.config import CELLDATA_SCRIPT
|
||||
from app.services.cell_data import copy_celldata_tables_to_capacity, execute_celldata_script, refresh_cell_data
|
||||
from app.services.license import LicenseError, check_processing_allowed
|
||||
from app.services.platform import PlatformStorageDownloader, make_source_downloader
|
||||
from app.services.pipeline import RESULT_TABLES, run_import_and_report
|
||||
from app.services.remote_download import RemoteDataDownloader
|
||||
|
||||
|
||||
router = APIRouter(tags=["remote"])
|
||||
RESULT_TABLES = ["4G_结果表", "5G_结果表"]
|
||||
|
||||
|
||||
@router.post("/api/remote/test")
|
||||
def test_remote_connection(config: dict[str, Any] | None = Body(None)):
|
||||
app_config = state.current_config()
|
||||
try:
|
||||
if app_config.source_type == "metrix":
|
||||
PlatformStorageDownloader(app_config).test_connection()
|
||||
return {"success": True, "message": "平台储存连接成功"}
|
||||
# FTP/SFTP: test the posted form config if provided, else the saved one.
|
||||
# Test the posted form config if provided, else the saved one.
|
||||
remote_config = RemoteDataConfig.from_dict(config) if config else app_config.remote_data
|
||||
RemoteDataDownloader(remote_config).test_connection()
|
||||
return {"success": True, "message": "远程服务器连接成功"}
|
||||
@@ -133,14 +123,11 @@ def _run_remote_processing(
|
||||
) -> None:
|
||||
final_status = "failed"
|
||||
try:
|
||||
if app_config.source_type == "metrix":
|
||||
logger.info(f"开始从平台储存下载,目录: {remote_config.remote_dir}")
|
||||
else:
|
||||
logger.info(
|
||||
f"开始远程下载,协议: {remote_config.protocol.upper()},"
|
||||
f"服务器: {remote_config.host}:{remote_config.port},目录: {remote_config.remote_dir}"
|
||||
)
|
||||
downloader = make_source_downloader(app_config, logger.info)
|
||||
logger.info(
|
||||
f"开始远程下载,协议: {remote_config.protocol.upper()},"
|
||||
f"服务器: {remote_config.host}:{remote_config.port},目录: {remote_config.remote_dir}"
|
||||
)
|
||||
downloader = RemoteDataDownloader(remote_config, logger.info)
|
||||
download_result = downloader.download_to(work_dir, target_dates=target_dates)
|
||||
logger.success(
|
||||
f"下载完成,共 {download_result.file_count} 个文件,"
|
||||
@@ -154,18 +141,11 @@ def _run_remote_processing(
|
||||
|
||||
_try_refresh_cell_data(app_config, work_dir, logger)
|
||||
|
||||
if app_config.warehouse_type == "metrix":
|
||||
started = time.time()
|
||||
run_import_and_report(work_dir, app_config, logger)
|
||||
status, error, elapsed = "completed", None, round(time.time() - started, 2)
|
||||
else:
|
||||
logger.set_stage("license")
|
||||
log_license_check(logger, check_processing_allowed(work_dir))
|
||||
processor = DataProcessor(app_config, work_dir, logger)
|
||||
result = processor.process()
|
||||
status = "completed" if result.get("success") else "failed"
|
||||
error = result.get("error")
|
||||
elapsed = result.get("elapsed_time", 0)
|
||||
processor = DataProcessor(app_config, work_dir, logger)
|
||||
result = processor.process()
|
||||
status = "completed" if result.get("success") else "failed"
|
||||
error = result.get("error")
|
||||
elapsed = result.get("elapsed_time", 0)
|
||||
if status == "completed" and remote_config.auto_delete_source:
|
||||
try:
|
||||
deleted_count = downloader.delete_source_files(download_result.remote_files)
|
||||
@@ -191,7 +171,6 @@ def _run_remote_processing(
|
||||
"error": error,
|
||||
}
|
||||
except Exception as exc:
|
||||
error_detail = exc.to_detail() if isinstance(exc, LicenseError) else None
|
||||
if source == "scheduler":
|
||||
logger.error(f"自动调度任务失败: {exc}")
|
||||
else:
|
||||
@@ -202,7 +181,6 @@ def _run_remote_processing(
|
||||
"status": "failed",
|
||||
"stage": "failed",
|
||||
"error": str(exc),
|
||||
"error_detail": error_detail,
|
||||
}
|
||||
finally:
|
||||
apply_history_retention_safely()
|
||||
|
||||
@@ -115,10 +115,6 @@ def _run_script(
|
||||
logger.info(f"开始执行{label}...")
|
||||
if script_type == "celldata":
|
||||
_run_celldata_script(script_path, app_config, logger)
|
||||
elif app_config.warehouse_type == "metrix":
|
||||
from app.services.pipeline import run_report_sql
|
||||
|
||||
run_report_sql(app_config, logger)
|
||||
else:
|
||||
temp_work_dir = CACHE_DIR / task_id
|
||||
temp_work_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app import state
|
||||
|
||||
@@ -17,18 +16,6 @@ def set_task_stage(task_id: str, stage: str, logs: list[str], status: str = "pro
|
||||
state.global_task_lock["stage"] = stage
|
||||
|
||||
|
||||
def log_license_check(logger: Any, info: Any) -> None:
|
||||
if info.current_date:
|
||||
logger.info(
|
||||
f"授权校验通过,数据日期: {info.current_date.isoformat()},"
|
||||
f"到期日期: {info.expires_on.isoformat()}"
|
||||
)
|
||||
elif info.zip_count:
|
||||
logger.warning("未从 ZIP 文件名识别到日期,已跳过授权日期比对")
|
||||
else:
|
||||
logger.warning("未找到 ZIP 文件,已跳过授权日期比对")
|
||||
|
||||
|
||||
def apply_history_retention_safely() -> None:
|
||||
try:
|
||||
state.apply_history_retention()
|
||||
|
||||
@@ -6,16 +6,11 @@ from typing import Any
|
||||
from fastapi import APIRouter, Body, HTTPException
|
||||
|
||||
from app import state
|
||||
from app.api.routers.task_runtime import (
|
||||
apply_history_retention_safely,
|
||||
log_license_check,
|
||||
set_task_stage,
|
||||
)
|
||||
from app.api.routers.task_runtime import apply_history_retention_safely, set_task_stage
|
||||
from app.config import AppConfig
|
||||
from app.processor import DataProcessor, ProcessLogger
|
||||
from app.config import CELLDATA_SCRIPT
|
||||
from app.services.cell_data import copy_celldata_tables_to_capacity, execute_celldata_script, refresh_cell_data
|
||||
from app.services.license import LicenseError, check_processing_allowed
|
||||
|
||||
|
||||
router = APIRouter(tags=["tasks"])
|
||||
@@ -142,7 +137,6 @@ async def get_processing_status(task_id: str = Body(..., embed=True)):
|
||||
"stage": task_info.get("stage"),
|
||||
"logs": logs,
|
||||
"error": task_info.get("error"),
|
||||
"error_detail": task_info.get("error_detail"),
|
||||
}
|
||||
|
||||
record = state.history_manager.get(task_id)
|
||||
@@ -171,23 +165,12 @@ def _task_finished(task_id: str) -> bool:
|
||||
def _run_processing(task_id: str, work_dir: Path, logger: ProcessLogger, app_config: AppConfig) -> None:
|
||||
try:
|
||||
_try_refresh_cell_data(app_config, work_dir, logger)
|
||||
if app_config.warehouse_type == "metrix":
|
||||
import time
|
||||
|
||||
from app.services.pipeline import RESULT_TABLES, run_import_and_report
|
||||
|
||||
started = time.time()
|
||||
run_import_and_report(work_dir, app_config, logger)
|
||||
status, error, elapsed, result_tables = "completed", None, round(time.time() - started, 2), RESULT_TABLES
|
||||
else:
|
||||
logger.set_stage("license")
|
||||
log_license_check(logger, check_processing_allowed(work_dir))
|
||||
processor = DataProcessor(app_config, work_dir, logger)
|
||||
result = processor.process()
|
||||
status = "completed" if result.get("success") else "failed"
|
||||
error = result.get("error")
|
||||
elapsed = result.get("elapsed_time", 0)
|
||||
result_tables = ["4G_结果表", "5G_结果表"]
|
||||
processor = DataProcessor(app_config, work_dir, logger)
|
||||
result = processor.process()
|
||||
status = "completed" if result.get("success") else "failed"
|
||||
error = result.get("error")
|
||||
elapsed = result.get("elapsed_time", 0)
|
||||
result_tables = ["4G_结果表", "5G_结果表"]
|
||||
state.history_manager.update(
|
||||
task_id,
|
||||
status=status,
|
||||
@@ -202,7 +185,6 @@ def _run_processing(task_id: str, work_dir: Path, logger: ProcessLogger, app_con
|
||||
"error": error,
|
||||
}
|
||||
except Exception as exc:
|
||||
error_detail = exc.to_detail() if isinstance(exc, LicenseError) else None
|
||||
logger.error(str(exc))
|
||||
state.history_manager.update(task_id, status="failed", error=str(exc))
|
||||
state.processing_tasks[task_id] = {
|
||||
@@ -210,7 +192,6 @@ def _run_processing(task_id: str, work_dir: Path, logger: ProcessLogger, app_con
|
||||
"status": "failed",
|
||||
"stage": "failed",
|
||||
"error": str(exc),
|
||||
"error_detail": error_detail,
|
||||
}
|
||||
finally:
|
||||
apply_history_retention_safely()
|
||||
|
||||
Reference in New Issue
Block a user