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,424 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ftplib
|
||||
import io
|
||||
import posixpath
|
||||
import socket
|
||||
import stat
|
||||
from collections.abc import Callable
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from typing import Any, TypeVar
|
||||
|
||||
import paramiko
|
||||
import pymysql
|
||||
|
||||
import main
|
||||
|
||||
from .config import Settings
|
||||
|
||||
CONNECT_TIMEOUT_SECONDS = 15
|
||||
TRANSFER_TIMEOUT_SECONDS = 120
|
||||
FTP_UNSUPPORTED_COMMAND_CODES = ("500", "502")
|
||||
INSERT_BATCH_SIZE = 1000
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
def entry(directory: str, name: str, is_dir: bool, size: int) -> dict[str, object]:
|
||||
return {"name": name, "path": posixpath.join(directory, name), "is_dir": is_dir, "size": size}
|
||||
|
||||
|
||||
class FtpStorage:
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
username: str,
|
||||
password: str,
|
||||
encoding: str = "utf-8",
|
||||
passive: bool = True,
|
||||
factory: Callable[[], ftplib.FTP] | None = None,
|
||||
) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username or "anonymous"
|
||||
self.password = password
|
||||
self.encoding = encoding
|
||||
self.passive = passive
|
||||
self.factory = factory or ftplib.FTP
|
||||
self._ftp: ftplib.FTP | None = None
|
||||
|
||||
def list_dir(self, path: str) -> list[dict[str, object]]:
|
||||
def action(ftp: ftplib.FTP) -> list[dict[str, object]]:
|
||||
try:
|
||||
return [
|
||||
entry(path, name, facts.get("type") == "dir", _safe_int(facts.get("size", "")))
|
||||
for name, facts in ftp.mlsd(path)
|
||||
if name not in (".", "..") and facts.get("type", "file") not in ("cdir", "pdir")
|
||||
]
|
||||
except ftplib.error_perm as exc:
|
||||
if str(exc)[:3] not in FTP_UNSUPPORTED_COMMAND_CODES:
|
||||
raise
|
||||
lines: list[str] = []
|
||||
ftp.retrlines(f"LIST {path}", lines.append)
|
||||
parsed = (parse_list_line(line) for line in lines)
|
||||
return [entry(path, name, is_dir, size) for name, is_dir, size in (item for item in parsed if item)]
|
||||
|
||||
return self._call("list", path, action)
|
||||
|
||||
def read_bytes(self, path: str) -> bytes:
|
||||
def action(ftp: ftplib.FTP) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
ftp.retrbinary(f"RETR {path}", buffer.write)
|
||||
return buffer.getvalue()
|
||||
|
||||
return self._call("download", path, action)
|
||||
|
||||
def make_dir(self, path: str) -> None:
|
||||
self._call("mkdir", path, lambda ftp: ftp.mkd(path))
|
||||
|
||||
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str:
|
||||
path = posixpath.join(directory, filename)
|
||||
self._call("upload", path, lambda ftp: ftp.storbinary(f"STOR {path}", io.BytesIO(payload)))
|
||||
return path
|
||||
|
||||
def close(self) -> None:
|
||||
ftp, self._ftp = self._ftp, None
|
||||
if ftp is None:
|
||||
return
|
||||
try:
|
||||
ftp.quit()
|
||||
except (OSError, EOFError, ftplib.Error):
|
||||
try:
|
||||
ftp.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _connect(self) -> ftplib.FTP:
|
||||
if self._ftp is None:
|
||||
ftp = self.factory()
|
||||
ftp.encoding = self.encoding
|
||||
try:
|
||||
ftp.connect(self.host, self.port, timeout=CONNECT_TIMEOUT_SECONDS)
|
||||
ftp.login(self.username, self.password)
|
||||
ftp.set_pasv(self.passive)
|
||||
if ftp.sock is not None:
|
||||
ftp.sock.settimeout(TRANSFER_TIMEOUT_SECONDS)
|
||||
except BaseException:
|
||||
try:
|
||||
ftp.close()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
self._ftp = ftp
|
||||
return self._ftp
|
||||
|
||||
def _call(self, operation: str, path: str, action: Callable[[ftplib.FTP], T]) -> T:
|
||||
last_error: BaseException | None = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
return action(self._connect())
|
||||
except ftplib.error_perm as exc:
|
||||
raise main.ProcessingError(f"FTP {operation} {path} failed: {exc}") from exc
|
||||
except (ftplib.Error, OSError, EOFError) as exc:
|
||||
last_error = exc
|
||||
self.close()
|
||||
raise main.ProcessingError(f"FTP {operation} {path} failed: {last_error}")
|
||||
|
||||
|
||||
class SftpStorage:
|
||||
def __init__(self, host: str, port: int, username: str, password: str) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.password = password
|
||||
self._transport: paramiko.Transport | None = None
|
||||
self._sftp: paramiko.SFTPClient | None = None
|
||||
|
||||
def list_dir(self, path: str) -> list[dict[str, object]]:
|
||||
attrs = self._call("list", path, lambda sftp: sftp.listdir_attr(path))
|
||||
return [entry(path, item.filename, stat.S_ISDIR(item.st_mode or 0), int(item.st_size or 0)) for item in attrs]
|
||||
|
||||
def read_bytes(self, path: str) -> bytes:
|
||||
def action(sftp: paramiko.SFTPClient) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
sftp.getfo(path, buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
return self._call("download", path, action)
|
||||
|
||||
def make_dir(self, path: str) -> None:
|
||||
self._call("mkdir", path, lambda sftp: sftp.mkdir(path))
|
||||
|
||||
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str:
|
||||
path = posixpath.join(directory, filename)
|
||||
self._call("upload", path, lambda sftp: sftp.putfo(io.BytesIO(payload), path))
|
||||
return path
|
||||
|
||||
def close(self) -> None:
|
||||
transport, self._transport, self._sftp = self._transport, None, None
|
||||
if transport is not None:
|
||||
try:
|
||||
transport.close()
|
||||
except (OSError, EOFError, paramiko.SSHException):
|
||||
pass
|
||||
|
||||
def _connect(self) -> paramiko.SFTPClient:
|
||||
if self._sftp is None:
|
||||
sock = socket.create_connection((self.host, self.port), timeout=CONNECT_TIMEOUT_SECONDS)
|
||||
transport = paramiko.Transport(sock)
|
||||
try:
|
||||
transport.banner_timeout = CONNECT_TIMEOUT_SECONDS
|
||||
transport.connect(username=self.username, password=self.password)
|
||||
sftp = paramiko.SFTPClient.from_transport(transport)
|
||||
if sftp is None:
|
||||
raise paramiko.SSHException("SFTP channel unavailable")
|
||||
channel = sftp.get_channel()
|
||||
if channel is not None:
|
||||
channel.settimeout(TRANSFER_TIMEOUT_SECONDS)
|
||||
except BaseException:
|
||||
transport.close()
|
||||
raise
|
||||
self._transport, self._sftp = transport, sftp
|
||||
return self._sftp
|
||||
|
||||
def _call(self, operation: str, path: str, action: Callable[[paramiko.SFTPClient], T]) -> T:
|
||||
last_error: BaseException | None = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
return action(self._connect())
|
||||
except (FileNotFoundError, PermissionError, paramiko.AuthenticationException) as exc:
|
||||
raise main.ProcessingError(f"SFTP {operation} {path} failed: {exc}") from exc
|
||||
except (OSError, EOFError, paramiko.SSHException) as exc:
|
||||
last_error = exc
|
||||
self.close()
|
||||
raise main.ProcessingError(f"SFTP {operation} {path} failed: {last_error}")
|
||||
|
||||
|
||||
class MySqlSummaryStore:
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
username: str,
|
||||
password: str,
|
||||
database: str = main.DATABASE_NAME,
|
||||
table: str = main.DATABASE_TABLE,
|
||||
connect: Callable[..., Any] | None = None,
|
||||
) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.database = main.sql_identifier(database, "database")
|
||||
self.table = main.sql_identifier(table, "table")
|
||||
self._connect = connect or pymysql.connect
|
||||
self._schema_ready = False
|
||||
|
||||
def latest_metric_time(self) -> datetime | None:
|
||||
with self._connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(f"SELECT MAX(metric_time) FROM `{self.table}`")
|
||||
row = cursor.fetchone()
|
||||
value = row[0] if row else None
|
||||
if value is None:
|
||||
return None
|
||||
return value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
|
||||
|
||||
def replace_latest(self, rows: list[dict[str, str]]) -> dict[str, object]:
|
||||
metric_time = main.batch_metric_time(rows)
|
||||
main.ensure_not_newer(self.latest_metric_time(), metric_time)
|
||||
params = [main.summary_row_params(row) for row in rows]
|
||||
metric_text = metric_time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
placeholders = ", ".join(["%s"] * len(main.SUMMARY_HEADER))
|
||||
insert_sql = f"INSERT INTO `{self.table}` ({', '.join(main.SUMMARY_HEADER)}) VALUES ({placeholders})"
|
||||
with self._connection() as connection:
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
refreshed = cursor.execute(f"DELETE FROM `{self.table}` WHERE metric_time = %s", (metric_text,))
|
||||
inserted = 0
|
||||
for start in range(0, len(params), INSERT_BATCH_SIZE):
|
||||
inserted += cursor.executemany(insert_sql, params[start : start + INSERT_BATCH_SIZE]) or 0
|
||||
deleted = cursor.execute(f"DELETE FROM `{self.table}` WHERE metric_time <> %s", (metric_text,))
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise main.ProcessingError(f"MySQL write failed: {exc}") from exc
|
||||
return {
|
||||
"enabled": True,
|
||||
"table": self.table,
|
||||
"metric_time": metric_text,
|
||||
"inserted_rows": int(inserted),
|
||||
"refreshed_rows": int(refreshed),
|
||||
"old_rows_deleted": int(deleted),
|
||||
}
|
||||
|
||||
def rows_for_time(self, metric_time: datetime) -> list[dict[str, str]]:
|
||||
sql = (
|
||||
f"SELECT {', '.join(main.SUMMARY_HEADER)} FROM `{self.table}` "
|
||||
"WHERE metric_time = %s ORDER BY cgi, cell_name"
|
||||
)
|
||||
with self._connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql, (metric_time.strftime("%Y-%m-%d %H:%M:%S"),))
|
||||
records = cursor.fetchall()
|
||||
return [
|
||||
{column: mysql_cell(value) for column, value in zip(main.SUMMARY_HEADER, record, strict=True)}
|
||||
for record in records
|
||||
]
|
||||
|
||||
def ping(self) -> str:
|
||||
connection = self._open(database=None)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT VERSION()")
|
||||
row = cursor.fetchone()
|
||||
return str(row[0]) if row else ""
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _connection(self) -> Any:
|
||||
if not self._schema_ready:
|
||||
self._ensure_schema()
|
||||
return _Closing(self._open(database=self.database))
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
connection = self._open(database=None)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(main.create_database_sql(self.database))
|
||||
cursor.execute(f"USE `{self.database}`")
|
||||
cursor.execute(main.create_table_sql(self.table))
|
||||
cursor.execute(
|
||||
"SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
|
||||
(self.database, self.table),
|
||||
)
|
||||
existing = {str(row[0]) for row in cursor.fetchall()}
|
||||
for statement in main.column_migration_sql(self.table, existing):
|
||||
cursor.execute(statement)
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL schema check failed: {exc}") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
self._schema_ready = True
|
||||
|
||||
def _open(self, database: str | None) -> Any:
|
||||
try:
|
||||
return self._connect(
|
||||
host=self.host,
|
||||
port=self.port,
|
||||
user=self.username,
|
||||
password=self.password,
|
||||
database=database,
|
||||
charset="utf8mb4",
|
||||
autocommit=False,
|
||||
connect_timeout=CONNECT_TIMEOUT_SECONDS,
|
||||
read_timeout=TRANSFER_TIMEOUT_SECONDS,
|
||||
write_timeout=TRANSFER_TIMEOUT_SECONDS,
|
||||
)
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL connection failed: {exc}") from exc
|
||||
|
||||
|
||||
class _Closing:
|
||||
def __init__(self, connection: Any) -> None:
|
||||
self.connection = connection
|
||||
|
||||
def __enter__(self) -> Any:
|
||||
return self.connection
|
||||
|
||||
def __exit__(self, *exc_info: object) -> None:
|
||||
self.connection.close()
|
||||
|
||||
|
||||
def mysql_cell(value: object) -> str:
|
||||
if isinstance(value, Decimal):
|
||||
text = format(value, "f")
|
||||
return text.rstrip("0").rstrip(".") if "." in text else text
|
||||
return main.normalize_cell(value)
|
||||
|
||||
|
||||
def build_storage(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
||||
if settings.storage_mode == "metrix":
|
||||
assert client is not None
|
||||
return main.MetrixStorage(client, settings.metrix_storage_id)
|
||||
if settings.storage_mode == "sftp":
|
||||
return SftpStorage(settings.remote_host, settings.remote_port, settings.remote_username, settings.remote_password)
|
||||
return FtpStorage(
|
||||
settings.remote_host,
|
||||
settings.remote_port,
|
||||
settings.remote_username,
|
||||
settings.remote_password,
|
||||
settings.ftp_encoding,
|
||||
settings.ftp_passive,
|
||||
)
|
||||
|
||||
|
||||
def build_store(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
||||
if settings.database_mode == "metrix":
|
||||
assert client is not None
|
||||
return main.ApiSummaryStore(client, settings.metrix_database_id, settings.database_name, settings.table_name)
|
||||
return MySqlSummaryStore(
|
||||
settings.mysql_host,
|
||||
settings.mysql_port,
|
||||
settings.mysql_username,
|
||||
settings.mysql_password,
|
||||
settings.database_name,
|
||||
settings.table_name,
|
||||
)
|
||||
|
||||
|
||||
def build_client(settings: Settings) -> main.MetrixApiClient | None:
|
||||
if not settings.uses_metrix_api():
|
||||
return None
|
||||
return main.MetrixApiClient(settings.metrix_url, settings.metrix_token)
|
||||
|
||||
|
||||
def close_quietly(resource: object) -> None:
|
||||
close = getattr(resource, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
|
||||
|
||||
def check_storage(settings: Settings) -> dict[str, object]:
|
||||
storage = build_storage(settings, build_client(settings))
|
||||
try:
|
||||
source = main.StorageSource(storage, settings.source_root, settings.cell_data_directories)
|
||||
dates = source.date_directories()
|
||||
return {"count": len(dates), "latest": str(dates[-1]["name"]) if dates else "-"}
|
||||
finally:
|
||||
close_quietly(storage)
|
||||
|
||||
|
||||
def check_database(settings: Settings) -> dict[str, object]:
|
||||
store = build_store(settings, build_client(settings))
|
||||
latest = store.latest_metric_time()
|
||||
return {"latest": latest.strftime("%Y-%m-%d %H:%M:%S") if latest else "-"}
|
||||
|
||||
|
||||
def parse_list_line(line: str) -> tuple[str, bool, int] | None:
|
||||
text = line.rstrip()
|
||||
if not text or text.startswith("total "):
|
||||
return None
|
||||
if text[0] in "dl-" and len(text) >= 10:
|
||||
parts = text.split(maxsplit=8)
|
||||
if len(parts) < 9:
|
||||
return None
|
||||
name = parts[8]
|
||||
if text[0] == "l" and " -> " in name:
|
||||
name = name.split(" -> ", 1)[0]
|
||||
if name in (".", ".."):
|
||||
return None
|
||||
return name, text[0] == "d", _safe_int(parts[4])
|
||||
parts = text.split(maxsplit=3)
|
||||
if len(parts) == 4 and parts[0].count("-") == 2:
|
||||
is_dir = parts[2] == "<DIR>"
|
||||
return parts[3], is_dir, 0 if is_dir else _safe_int(parts[2])
|
||||
return None
|
||||
|
||||
|
||||
def _safe_int(value: str) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return 0
|
||||
Reference in New Issue
Block a user