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:
2026-11-06 16:53:36 +08:00
parent ba2d3b2490
commit 96dd78baca
21 changed files with 3806 additions and 137 deletions
+195
View File
@@ -0,0 +1,195 @@
from __future__ import annotations
import os
import re
import shutil
import subprocess
import sys
import threading
import time
from pathlib import Path
from typing import Any
from .config import SettingsStore
from .runs import RunStore, now_text
APP_ROOT = Path(__file__).resolve().parent.parent
OUTPUT_KEY_RE = re.compile(r"\d{14}")
TERMINATE_GRACE_SECONDS = 10
DETAIL_LIMIT = 500
def parse_output(text: str) -> dict[str, str]:
values: dict[str, str] = {}
for line in text.splitlines():
key, separator, value = line.partition("=")
if separator and re.fullmatch(r"[a-z_]+", key):
values[key] = value.strip()
return values
def last_line(text: str) -> str:
lines = [line.strip() for line in text.splitlines() if line.strip()]
return lines[-1] if lines else ""
class Runner:
def __init__(
self,
settings_store: SettingsStore,
runs: RunStore,
data_dir: Path,
command: list[str] | None = None,
) -> None:
self.settings_store = settings_store
self.runs = runs
self.data_dir = data_dir
self.output_dir = data_dir / "output"
self.log_dir = data_dir / "logs"
self.command = command or [sys.executable, "-m", "etl_app.worker"]
self.seconds_per_minute = 60.0
self._lock = threading.Lock()
self._process: subprocess.Popen[bytes] | None = None
self._current: dict[str, Any] | None = None
self._cancelled = False
@property
def current(self) -> dict[str, Any] | None:
current = self._current
return dict(current) if current else None
def busy(self) -> bool:
return self._lock.locked()
def log_path(self, run_id: int) -> Path:
return self.log_dir / f"{run_id}.log"
def read_log(self, run_id: int, tail: int = 0) -> str:
path = self.log_path(run_id)
if not path.is_file():
return ""
text = path.read_text(encoding="utf-8", errors="replace")
if tail:
return "\n".join(text.splitlines()[-tail:])
return text
def start(self, trigger: str, dry_run: bool = False) -> bool:
if self.busy():
return False
threading.Thread(target=self.run, args=(trigger, dry_run), name=f"etl-{trigger}", daemon=True).start()
return True
def run(self, trigger: str, dry_run: bool = False) -> int | None:
if not self._lock.acquire(blocking=False):
return None
try:
return self._execute(trigger, dry_run)
finally:
self._process = None
self._current = None
self._cancelled = False
self._lock.release()
def cancel(self) -> bool:
process = self._process
if process is None or process.poll() is not None:
return False
self._cancelled = True
self._terminate(process)
return True
def _execute(self, trigger: str, dry_run: bool) -> int:
settings = self.settings_store.get()
run_id = self.runs.create(trigger, dry_run)
self._current = {"id": run_id, "trigger": trigger, "dry_run": dry_run, "started_at": now_text()}
self.log_dir.mkdir(parents=True, exist_ok=True)
self.output_dir.mkdir(parents=True, exist_ok=True)
command = [
*self.command,
"--settings",
str(self.settings_store.path),
"--output",
str(self.output_dir),
*(["--dry-run"] if dry_run else []),
]
env = {key: value for key, value in os.environ.items() if key != "METRIX_APP_PROXY_TOKEN"}
env.update({"PYTHONUNBUFFERED": "1", "PYTHONIOENCODING": "utf-8"})
started = time.monotonic()
timed_out = False
exit_code: int | None = None
try:
with self.log_path(run_id).open("wb") as log:
process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, cwd=APP_ROOT, env=env)
self._process = process
try:
exit_code = process.wait(timeout=settings.timeout_minutes * self.seconds_per_minute)
except subprocess.TimeoutExpired:
timed_out = True
self._terminate(process)
exit_code = process.returncode
except OSError as exc:
self.log_path(run_id).write_text(f"error={exc}\n", encoding="utf-8")
duration_ms = int((time.monotonic() - started) * 1000)
text = self.read_log(run_id)
outcome = parse_output(text)
status, detail = self._classify(outcome, text, exit_code, timed_out, settings.timeout_minutes)
summary_rows = outcome.get("summary_rows")
self.runs.finish(
run_id,
status=status,
finished_at=now_text(),
duration_ms=duration_ms,
target_time=outcome.get("target_time", ""),
summary_rows=int(summary_rows) if summary_rows and summary_rows.isdigit() else None,
detail=detail[:DETAIL_LIMIT],
exit_code=exit_code,
)
self._prune(settings.keep_outputs, settings.keep_runs)
return run_id
def _classify(
self,
outcome: dict[str, str],
text: str,
exit_code: int | None,
timed_out: bool,
timeout_minutes: int,
) -> tuple[str, str]:
if timed_out:
return "timeout", str(timeout_minutes)
if self._cancelled:
return "cancelled", ""
if exit_code != 0:
return "failed", outcome.get("error") or last_line(text)
status = outcome.get("status", "")
if status == "waiting":
return status, outcome.get("missing_sources") or outcome.get("reason", "")
if status == "skipped":
return status, outcome.get("database_metric_time", "")
if status == "history_repaired":
return status, outcome.get("history_output", "")
if status == "processed":
return status, outcome.get("history_output") or outcome.get("output", "")
return "failed", last_line(text)
@staticmethod
def _terminate(process: subprocess.Popen[bytes]) -> None:
process.terminate()
try:
process.wait(timeout=TERMINATE_GRACE_SECONDS)
except subprocess.TimeoutExpired:
process.kill()
process.wait()
def _prune(self, keep_outputs: int, keep_runs: int) -> None:
if self.output_dir.is_dir():
outputs = sorted(
(path for path in self.output_dir.iterdir() if path.is_dir() and OUTPUT_KEY_RE.fullmatch(path.name)),
key=lambda path: path.name,
reverse=True,
)
stale = [path for path in self.output_dir.iterdir() if path.is_dir() and ".tmp-" in path.name]
for path in [*outputs[keep_outputs:], *stale]:
shutil.rmtree(path, ignore_errors=True)
for run_id in self.runs.prune(keep_runs):
self.log_path(run_id).unlink(missing_ok=True)