feat: 新增Metrix托管应用模式,含管理界面与容器内定时运行
- 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,覆盖设置、运行记录、执行器、调度、身份、接口与各连接器
This commit is contained in:
@@ -0,0 +1,253 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import threading
|
||||
from dataclasses import asdict, dataclass, field, fields, replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
import main
|
||||
|
||||
TIMEZONE = os.getenv("TZ") or "Asia/Shanghai"
|
||||
SECRET_FIELDS = ("metrix_token", "remote_password", "mysql_password")
|
||||
STORAGE_MODES = ("metrix", "ftp", "sftp")
|
||||
DATABASE_MODES = ("metrix", "mysql")
|
||||
SCHEDULE_MODES = ("interval", "cron")
|
||||
FTP_ENCODINGS = ("utf-8", "gbk", "gb18030")
|
||||
DEFAULT_PORTS = {"ftp": 21, "sftp": 22}
|
||||
|
||||
|
||||
def data_dir() -> Path:
|
||||
return Path(os.getenv("METRIX_APP_DATA_DIR") or "data").resolve()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
schedule_enabled: bool = False
|
||||
schedule_mode: str = "interval"
|
||||
interval_minutes: int = 2
|
||||
cron_expression: str = "*/15 * * * *"
|
||||
timeout_minutes: int = 30
|
||||
|
||||
metrix_url: str = "http://188.5.127.115:18271"
|
||||
metrix_token: str = ""
|
||||
|
||||
storage_mode: str = "metrix"
|
||||
metrix_storage_id: str = main.DEFAULT_STORAGE_ID
|
||||
remote_host: str = ""
|
||||
remote_port: int = 21
|
||||
remote_username: str = ""
|
||||
remote_password: str = ""
|
||||
ftp_encoding: str = "utf-8"
|
||||
ftp_passive: bool = True
|
||||
|
||||
source_root: str = main.DEFAULT_ROOT
|
||||
history_enabled: bool = True
|
||||
history_root: str = main.DEFAULT_HISTORY_ROOT
|
||||
lookback_days: int = 3
|
||||
cell_data_directories: list[str] = field(default_factory=lambda: list(main.CELL_DATA_DIRECTORIES))
|
||||
|
||||
database_mode: str = "metrix"
|
||||
metrix_database_id: str = ""
|
||||
mysql_host: str = ""
|
||||
mysql_port: int = 3306
|
||||
mysql_username: str = ""
|
||||
mysql_password: str = ""
|
||||
database_name: str = main.DATABASE_NAME
|
||||
table_name: str = main.DATABASE_TABLE
|
||||
|
||||
keep_outputs: int = 48
|
||||
keep_runs: int = 2000
|
||||
|
||||
def uses_metrix_api(self) -> bool:
|
||||
return self.storage_mode == "metrix" or self.database_mode == "metrix"
|
||||
|
||||
|
||||
FIELD_NAMES = {item.name for item in fields(Settings)}
|
||||
|
||||
|
||||
class SettingsError(ValueError):
|
||||
def __init__(self, key: str, field_name: str = "", **params: object) -> None:
|
||||
super().__init__(f"{field_name}: {key}" if field_name else key)
|
||||
self.key = key
|
||||
self.field = field_name
|
||||
self.params = params
|
||||
|
||||
|
||||
def validate(data: dict[str, Any], current: Settings) -> Settings:
|
||||
merged = asdict(current)
|
||||
for name, value in data.items():
|
||||
if name not in FIELD_NAMES:
|
||||
continue
|
||||
if name in SECRET_FIELDS and (value is None or str(value) == ""):
|
||||
continue
|
||||
merged[name] = value
|
||||
values = {
|
||||
"schedule_enabled": _bool(merged["schedule_enabled"]),
|
||||
"schedule_mode": _choice(merged, "schedule_mode", SCHEDULE_MODES),
|
||||
"interval_minutes": _int(merged, "interval_minutes", 1, 1440),
|
||||
"cron_expression": _text(merged, "cron_expression"),
|
||||
"timeout_minutes": _int(merged, "timeout_minutes", 1, 1440),
|
||||
"metrix_url": _text(merged, "metrix_url").rstrip("/"),
|
||||
"metrix_token": _text(merged, "metrix_token"),
|
||||
"storage_mode": _choice(merged, "storage_mode", STORAGE_MODES),
|
||||
"metrix_storage_id": _text(merged, "metrix_storage_id"),
|
||||
"remote_host": _text(merged, "remote_host"),
|
||||
"remote_port": _int(merged, "remote_port", 1, 65535),
|
||||
"remote_username": _text(merged, "remote_username"),
|
||||
"remote_password": str(merged["remote_password"] or ""),
|
||||
"ftp_encoding": _choice(merged, "ftp_encoding", FTP_ENCODINGS),
|
||||
"ftp_passive": _bool(merged["ftp_passive"]),
|
||||
"source_root": _remote_path(merged, "source_root"),
|
||||
"history_enabled": _bool(merged["history_enabled"]),
|
||||
"history_root": _remote_path(merged, "history_root"),
|
||||
"lookback_days": _int(merged, "lookback_days", 1, 31),
|
||||
"cell_data_directories": _directories(merged["cell_data_directories"]),
|
||||
"database_mode": _choice(merged, "database_mode", DATABASE_MODES),
|
||||
"metrix_database_id": _text(merged, "metrix_database_id"),
|
||||
"mysql_host": _text(merged, "mysql_host"),
|
||||
"mysql_port": _int(merged, "mysql_port", 1, 65535),
|
||||
"mysql_username": _text(merged, "mysql_username"),
|
||||
"mysql_password": str(merged["mysql_password"] or ""),
|
||||
"database_name": _identifier(merged, "database_name"),
|
||||
"table_name": _identifier(merged, "table_name"),
|
||||
"keep_outputs": _int(merged, "keep_outputs", 1, 1000),
|
||||
"keep_runs": _int(merged, "keep_runs", 50, 100000),
|
||||
}
|
||||
settings = Settings(**values)
|
||||
if settings.schedule_mode == "cron":
|
||||
try:
|
||||
CronTrigger.from_crontab(settings.cron_expression, timezone=TIMEZONE)
|
||||
except ValueError as exc:
|
||||
raise SettingsError("invalidCron", "cron_expression") from exc
|
||||
if settings.uses_metrix_api():
|
||||
if not re.match(r"^https?://[^\s/]+", settings.metrix_url):
|
||||
raise SettingsError("invalidUrl", "metrix_url")
|
||||
_require(settings, "metrix_token")
|
||||
if settings.storage_mode == "metrix":
|
||||
_require(settings, "metrix_storage_id")
|
||||
else:
|
||||
_require(settings, "remote_host")
|
||||
if settings.database_mode == "metrix":
|
||||
_require(settings, "metrix_database_id")
|
||||
else:
|
||||
_require(settings, "mysql_host")
|
||||
_require(settings, "mysql_username")
|
||||
return settings
|
||||
|
||||
|
||||
def public_view(settings: Settings) -> dict[str, Any]:
|
||||
payload = asdict(settings)
|
||||
for name in SECRET_FIELDS:
|
||||
payload[f"has_{name}"] = bool(payload[name])
|
||||
payload[name] = ""
|
||||
return payload
|
||||
|
||||
|
||||
class SettingsStore:
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
self._settings = self._load()
|
||||
|
||||
def get(self) -> Settings:
|
||||
with self._lock:
|
||||
return replace(self._settings, cell_data_directories=list(self._settings.cell_data_directories))
|
||||
|
||||
def update(self, data: dict[str, Any]) -> Settings:
|
||||
with self._lock:
|
||||
settings = validate(data, self._settings)
|
||||
self._write(settings)
|
||||
self._settings = settings
|
||||
return replace(settings, cell_data_directories=list(settings.cell_data_directories))
|
||||
|
||||
def configured(self) -> bool:
|
||||
try:
|
||||
validate({}, self.get())
|
||||
except SettingsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _load(self) -> Settings:
|
||||
if not self.path.is_file():
|
||||
return Settings()
|
||||
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
defaults = asdict(Settings())
|
||||
defaults.update({key: value for key, value in raw.items() if key in FIELD_NAMES})
|
||||
return Settings(**defaults)
|
||||
|
||||
def _write(self, settings: Settings) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = self.path.with_name(f".{self.path.name}.tmp")
|
||||
handle = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as file:
|
||||
json.dump(asdict(settings), file, ensure_ascii=False, indent=2)
|
||||
file.write("\n")
|
||||
os.replace(temp, self.path)
|
||||
|
||||
|
||||
def _require(settings: Settings, name: str) -> None:
|
||||
if not getattr(settings, name):
|
||||
raise SettingsError("required", name)
|
||||
|
||||
|
||||
def _text(values: dict[str, Any], name: str) -> str:
|
||||
return str(values[name] or "").strip()
|
||||
|
||||
|
||||
def _bool(value: object) -> bool:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in ("1", "true", "yes", "on")
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _choice(values: dict[str, Any], name: str, options: tuple[str, ...]) -> str:
|
||||
value = _text(values, name)
|
||||
if value not in options:
|
||||
raise SettingsError("invalidChoice", name)
|
||||
return value
|
||||
|
||||
|
||||
def _int(values: dict[str, Any], name: str, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
number = int(float(values[name]))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise SettingsError("range", name, min=minimum, max=maximum) from exc
|
||||
if not minimum <= number <= maximum:
|
||||
raise SettingsError("range", name, min=minimum, max=maximum)
|
||||
return number
|
||||
|
||||
|
||||
def _remote_path(values: dict[str, Any], name: str) -> str:
|
||||
value = _text(values, name)
|
||||
if not value.startswith("/"):
|
||||
raise SettingsError("absolutePath", name)
|
||||
return value.rstrip("/") or "/"
|
||||
|
||||
|
||||
def _directories(value: object) -> list[str]:
|
||||
items = value.splitlines() if isinstance(value, str) else list(value or [])
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
path = str(item).strip()
|
||||
if not path:
|
||||
continue
|
||||
if not path.startswith("/"):
|
||||
raise SettingsError("absolutePath", "cell_data_directories")
|
||||
path = path.rstrip("/") or "/"
|
||||
if path not in result:
|
||||
result.append(path)
|
||||
if not result:
|
||||
raise SettingsError("required", "cell_data_directories")
|
||||
return result
|
||||
|
||||
|
||||
def _identifier(values: dict[str, Any], name: str) -> str:
|
||||
value = _text(values, name)
|
||||
if not main.SQL_IDENTIFIER_RE.fullmatch(value):
|
||||
raise SettingsError("invalidIdentifier", name)
|
||||
return value
|
||||
Reference in New Issue
Block a user