diff --git a/.dockerignore b/.dockerignore index c8a679b..b9d905c 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,3 +1,7 @@ * !Dockerfile !requirements.txt +!requirements-app.txt +!main.py +!etl_app/ +etl_app/**/__pycache__ diff --git a/README.md b/README.md index 2b0b72c..b0a5e1d 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,37 @@ python main.py --source-dir C:\path\to\mock-or-exported-tree --output-dir output Use `--window 2026073110001100` to select the natural 15-minute group containing that source start time. Without it, the newest observed source start time determines the group. Incomplete groups wait and never fall back. +## Metrix hosted app + +The app mode runs InterferenceETL as one long-lived container in Metrix App Hosting. A FastAPI + NiceGUI admin page at `/admin` (Metrix account, admin role only) edits every setting, shows the live log and keeps the run history. The schedule runs inside the same container with APScheduler (fixed interval in minutes or a 5-field cron expression, timezone `Asia/Shanghai`). Each run is a child Python process inside that container, so no extra containers are started; one run at a time, with a per-run timeout. + +Settings live on the app data volume and are edited only through the admin page: + +- Source storage: Metrix storage API, or direct FTP / SFTP (host, port, account, FTP encoding and passive mode). +- Database: Metrix database connection API, or direct MySQL (host, port, account). Database and table names are configurable. +- Metrix API address and token are required only when either side uses the Metrix API. +- Source root, history CSV directory (optional), CellData directories, lookback days and retention. + +Passwords and tokens are written to `/data/settings.json` (mode 0600) and never returned to the browser; a blank field keeps the saved value. Run records are in `/data/runs.db`, run logs in `/data/logs/`, local outputs in `/data/output/` (newest 48 kept by default). + +Build the app bundle on a machine with docker, then upload it in App Hosting: + +```powershell +python scripts\package_metrix.py +``` + +The bundle `dist/metrix/interference-etl-.zip` contains `metrix-app.json`, `icon.svg` and `image.tar` built from `deploy/Dockerfile`. `--pip-index` and `--python-image` override the package index and base image. The schedule starts paused; enable it from the overview page after the connection test passes. + +For local development of the app: + +```powershell +python -m pip install -r requirements-app.txt +$env:METRIX_APP_DATA_DIR = "Temp\appdata"; $env:ETL_DEV_ADMIN = "1"; $env:PORT = "18090" +python -m etl_app.server +``` + +`ETL_DEV_ADMIN=1` grants admin access only when no Metrix proxy token is configured. + ## Metrix Script Management The target server is offline. Build the dependency image locally, then generate a self-contained Script Management upload ZIP: diff --git a/deploy/Dockerfile b/deploy/Dockerfile new file mode 100644 index 0000000..535f86f --- /dev/null +++ b/deploy/Dockerfile @@ -0,0 +1,19 @@ +ARG PYTHON_IMAGE=python:3.13.11-slim + +FROM ${PYTHON_IMAGE} +ARG PIP_INDEX= +WORKDIR /app +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PIP_DISABLE_PIP_VERSION_CHECK=1 \ + TZ=Asia/Shanghai \ + METRIX_APP_DATA_DIR=/data \ + PORT=8080 +COPY requirements-app.txt . +RUN if [ -n "$PIP_INDEX" ]; then pip install --no-cache-dir --index-url "$PIP_INDEX" -r requirements-app.txt; \ + else pip install --no-cache-dir -r requirements-app.txt; fi +COPY main.py . +COPY etl_app/ ./etl_app/ +VOLUME ["/data"] +EXPOSE 8080 +CMD ["python", "-m", "etl_app.server"] diff --git a/etl_app/__init__.py b/etl_app/__init__.py new file mode 100644 index 0000000..5becc17 --- /dev/null +++ b/etl_app/__init__.py @@ -0,0 +1 @@ +__version__ = "1.0.0" diff --git a/etl_app/auth.py b/etl_app/auth.py new file mode 100644 index 0000000..970f2bb --- /dev/null +++ b/etl_app/auth.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +import hmac +import os +from collections.abc import Mapping +from dataclasses import dataclass +from urllib.parse import unquote + +from fastapi import HTTPException, Request + + +@dataclass(frozen=True) +class Identity: + user_id: str + username: str + display_name: str + role: str + + @property + def is_admin(self) -> bool: + return self.role == "admin" + + @property + def label(self) -> str: + return self.display_name or self.username + + +def identify(headers: Mapping[str, str]) -> Identity | None: + expected = os.getenv("METRIX_APP_PROXY_TOKEN", "") + if not expected: + if os.getenv("ETL_DEV_ADMIN") == "1": + return Identity("dev", "dev", "Developer", "admin") + return None + presented = headers.get("x-metrix-proxy-token", "") + if not hmac.compare_digest(presented.encode(), expected.encode()): + return None + return Identity( + user_id=unquote(headers.get("x-metrix-user-id", "")), + username=unquote(headers.get("x-metrix-username", "")), + display_name=unquote(headers.get("x-metrix-display-name", "")), + role=unquote(headers.get("x-metrix-app-role", "")), + ) + + +def require_admin(request: Request) -> Identity: + identity = identify(request.headers) + if identity is None: + raise HTTPException(status_code=401, detail="unauthorized") + if not identity.is_admin: + raise HTTPException(status_code=403, detail="forbidden") + return identity diff --git a/etl_app/config.py b/etl_app/config.py new file mode 100644 index 0000000..b1f8ff0 --- /dev/null +++ b/etl_app/config.py @@ -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 diff --git a/etl_app/connectors.py b/etl_app/connectors.py new file mode 100644 index 0000000..5c85e29 --- /dev/null +++ b/etl_app/connectors.py @@ -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] == "" + 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 diff --git a/etl_app/i18n.py b/etl_app/i18n.py new file mode 100644 index 0000000..831aa6b --- /dev/null +++ b/etl_app/i18n.py @@ -0,0 +1,309 @@ +from __future__ import annotations + +MESSAGES: dict[str, dict[str, str]] = { + "zh": { + "app.title": "干扰数据处理", + "tab.overview": "概览", + "tab.runs": "运行记录", + "tab.settings": "设置", + "header.scheduleOn": "定时运行中", + "header.scheduleOff": "定时已暂停", + "header.theme": "切换日夜间", + "header.language": "English", + "header.languageShort": "EN", + "card.schedule": "定时任务", + "card.current": "当前状态", + "card.lastRun": "最近结果", + "card.latestData": "最新入库", + "schedule.every": "每 {n} 分钟", + "schedule.cron": "Cron {expr}", + "schedule.paused": "已暂停", + "schedule.next": "下次运行 {time}", + "schedule.setup": "请先完成设置", + "current.idle": "空闲", + "current.running": "运行中", + "current.elapsed": "#{id} · {trigger} · 已运行 {elapsed}", + "current.lastFinished": "上次结束于 {time}", + "empty.dash": "—", + "empty.never": "暂无记录", + "latest.rows": "{rows} 行 · {time} 写入", + "today.summary": "今日运行 {total} 次 · 入库 {processed} · 无新数据 {idle} · 异常 {problem}", + "action.run": "立即运行", + "action.dryRun": "试运行", + "action.dryRunHint": "处理最新一组文件并保存在本地,不写数据库和历史目录", + "action.pause": "暂停定时", + "action.resume": "启用定时", + "action.cancel": "停止运行", + "action.refresh": "刷新", + "action.save": "保存设置", + "action.test": "测试连接", + "action.copy": "复制日志", + "action.close": "关闭", + "action.viewAll": "查看全部", + "log.title": "运行日志", + "log.empty": "暂无日志输出", + "log.copied": "已复制", + "recent.title": "最近运行", + "recent.empty": "还没有运行记录", + "status.running": "运行中", + "status.processed": "已入库", + "status.history_repaired": "已补传历史", + "status.skipped": "无新数据", + "status.waiting": "等待数据", + "status.failed": "失败", + "status.timeout": "超时", + "status.cancelled": "已停止", + "status.interrupted": "已中断", + "status.dryRunDone": "试运行完成", + "trigger.schedule": "定时", + "trigger.manual": "手动", + "trigger.dryRun": "试运行", + "detail.missing": "缺少 {count} 类:{sources}", + "detail.noFiles": "未找到源文件", + "detail.upToDate": "数据库已是 {time}", + "detail.timeout": "超过 {n} 分钟未完成", + "detail.dryRunOutput": "结果保存在本地", + "runs.filter.all": "全部", + "runs.filter.processed": "已入库", + "runs.filter.idle": "无新数据", + "runs.filter.problem": "异常", + "runs.col.id": "编号", + "runs.col.started": "开始时间", + "runs.col.trigger": "触发", + "runs.col.status": "状态", + "runs.col.target": "数据时间", + "runs.col.rows": "汇总行数", + "runs.col.duration": "耗时", + "runs.col.detail": "说明", + "runs.total": "共 {n} 条", + "runs.empty": "没有符合条件的记录", + "dialog.title": "运行 #{id}", + "dialog.started": "开始", + "dialog.finished": "结束", + "dialog.duration": "耗时", + "dialog.target": "数据时间", + "dialog.rows": "汇总行数", + "section.schedule": "定时运行", + "section.metrix": "Metrix 接口", + "section.source": "文件来源", + "section.history": "历史归档", + "section.database": "数据库", + "section.retention": "保留策略", + "field.schedule_enabled": "启用定时", + "field.schedule_mode": "运行方式", + "field.interval_minutes": "间隔(分钟)", + "field.cron_expression": "Cron 表达式", + "field.cron_hint": "分 时 日 月 周,例如 */15 * * * *", + "field.timeout_minutes": "单次超时(分钟)", + "field.metrix_url": "接口地址", + "field.metrix_token": "API 令牌", + "field.storage_mode": "访问方式", + "field.metrix_storage_id": "存储连接 ID", + "field.remote_host": "主机", + "field.remote_port": "端口", + "field.remote_username": "用户名", + "field.remote_password": "密码", + "field.ftp_encoding": "文件名编码", + "field.ftp_passive": "被动模式", + "field.source_root": "源数据目录", + "field.lookback_days": "回看天数", + "field.cell_data_directories": "小区信息目录", + "field.cell_data_hint": "每行一个目录", + "field.history_enabled": "上传历史 CSV", + "field.history_root": "历史目录", + "field.database_mode": "写入方式", + "field.metrix_database_id": "数据库连接 ID", + "field.mysql_host": "主机", + "field.mysql_port": "端口", + "field.mysql_username": "用户名", + "field.mysql_password": "密码", + "field.database_name": "库名", + "field.table_name": "表名", + "field.keep_outputs": "本地结果保留份数", + "field.keep_runs": "运行记录保留条数", + "option.interval": "固定间隔", + "option.cron": "Cron 表达式", + "option.storageMetrix": "Metrix 存储", + "option.databaseMetrix": "Metrix 数据库连接", + "option.mysql": "MySQL 直连", + "secret.saved": "已保存,留空则不修改", + "secret.empty": "未设置", + "check.storage": "文件来源", + "check.database": "数据库", + "check.storageOk": "找到 {count} 个日期目录,最新 {latest}", + "check.databaseOk": "连接正常,最新数据 {latest}", + "check.running": "正在测试连接…", + "msg.saved": "设置已保存", + "msg.started": "已开始运行", + "msg.busy": "已有任务在运行", + "msg.cancelled": "已发送停止指令", + "msg.scheduleOn": "定时已启用", + "msg.scheduleOff": "定时已暂停", + "error.required": "请填写“{field}”", + "error.range": "“{field}”应在 {min} 到 {max} 之间", + "error.invalidChoice": "“{field}”取值无效", + "error.invalidCron": "Cron 表达式无效", + "error.invalidUrl": "接口地址需以 http:// 或 https:// 开头", + "error.absolutePath": "“{field}”需要以 / 开头", + "error.invalidIdentifier": "“{field}”只能包含字母、数字和下划线", + "forbidden.title": "无权访问", + "forbidden.body": "只有应用管理员可以打开管理界面。", + }, + "en": { + "app.title": "Interference ETL", + "tab.overview": "Overview", + "tab.runs": "Runs", + "tab.settings": "Settings", + "header.scheduleOn": "Schedule on", + "header.scheduleOff": "Schedule paused", + "header.theme": "Toggle theme", + "header.language": "中文", + "header.languageShort": "中", + "card.schedule": "Schedule", + "card.current": "Current", + "card.lastRun": "Last result", + "card.latestData": "Latest data", + "schedule.every": "Every {n} min", + "schedule.cron": "Cron {expr}", + "schedule.paused": "Paused", + "schedule.next": "Next run {time}", + "schedule.setup": "Settings required", + "current.idle": "Idle", + "current.running": "Running", + "current.elapsed": "#{id} · {trigger} · {elapsed} elapsed", + "current.lastFinished": "Last finished {time}", + "empty.dash": "—", + "empty.never": "No runs yet", + "latest.rows": "{rows} rows · written {time}", + "today.summary": "Today: {total} runs · {processed} processed · {idle} no new data · {problem} problems", + "action.run": "Run now", + "action.dryRun": "Dry run", + "action.dryRunHint": "Process the latest file group locally without writing the database or history", + "action.pause": "Pause schedule", + "action.resume": "Enable schedule", + "action.cancel": "Stop run", + "action.refresh": "Refresh", + "action.save": "Save settings", + "action.test": "Test connections", + "action.copy": "Copy log", + "action.close": "Close", + "action.viewAll": "View all", + "log.title": "Run log", + "log.empty": "No log output", + "log.copied": "Copied", + "recent.title": "Recent runs", + "recent.empty": "No runs yet", + "status.running": "Running", + "status.processed": "Processed", + "status.history_repaired": "History repaired", + "status.skipped": "No new data", + "status.waiting": "Waiting for data", + "status.failed": "Failed", + "status.timeout": "Timed out", + "status.cancelled": "Stopped", + "status.interrupted": "Interrupted", + "status.dryRunDone": "Dry run done", + "trigger.schedule": "Scheduled", + "trigger.manual": "Manual", + "trigger.dryRun": "Dry run", + "detail.missing": "Missing {count}: {sources}", + "detail.noFiles": "No source files found", + "detail.upToDate": "Database already at {time}", + "detail.timeout": "Not finished within {n} min", + "detail.dryRunOutput": "Result kept locally", + "runs.filter.all": "All", + "runs.filter.processed": "Processed", + "runs.filter.idle": "No new data", + "runs.filter.problem": "Problems", + "runs.col.id": "ID", + "runs.col.started": "Started", + "runs.col.trigger": "Trigger", + "runs.col.status": "Status", + "runs.col.target": "Data time", + "runs.col.rows": "Rows", + "runs.col.duration": "Duration", + "runs.col.detail": "Detail", + "runs.total": "{n} runs", + "runs.empty": "No matching runs", + "dialog.title": "Run #{id}", + "dialog.started": "Started", + "dialog.finished": "Finished", + "dialog.duration": "Duration", + "dialog.target": "Data time", + "dialog.rows": "Rows", + "section.schedule": "Schedule", + "section.metrix": "Metrix API", + "section.source": "File source", + "section.history": "History archive", + "section.database": "Database", + "section.retention": "Retention", + "field.schedule_enabled": "Enabled", + "field.schedule_mode": "Mode", + "field.interval_minutes": "Interval (minutes)", + "field.cron_expression": "Cron expression", + "field.cron_hint": "minute hour day month weekday, e.g. */15 * * * *", + "field.timeout_minutes": "Timeout (minutes)", + "field.metrix_url": "Base URL", + "field.metrix_token": "API token", + "field.storage_mode": "Access", + "field.metrix_storage_id": "Storage ID", + "field.remote_host": "Host", + "field.remote_port": "Port", + "field.remote_username": "Username", + "field.remote_password": "Password", + "field.ftp_encoding": "Filename encoding", + "field.ftp_passive": "Passive mode", + "field.source_root": "Source directory", + "field.lookback_days": "Lookback days", + "field.cell_data_directories": "Cell data directories", + "field.cell_data_hint": "One directory per line", + "field.history_enabled": "Upload history CSV", + "field.history_root": "History directory", + "field.database_mode": "Access", + "field.metrix_database_id": "Connection ID", + "field.mysql_host": "Host", + "field.mysql_port": "Port", + "field.mysql_username": "Username", + "field.mysql_password": "Password", + "field.database_name": "Database", + "field.table_name": "Table", + "field.keep_outputs": "Local results kept", + "field.keep_runs": "Runs kept", + "option.interval": "Interval", + "option.cron": "Cron", + "option.storageMetrix": "Metrix storage", + "option.databaseMetrix": "Metrix connection", + "option.mysql": "Direct MySQL", + "secret.saved": "Saved; leave blank to keep", + "secret.empty": "Not set", + "check.storage": "File source", + "check.database": "Database", + "check.storageOk": "{count} date folders, latest {latest}", + "check.databaseOk": "Connected, latest data {latest}", + "check.running": "Testing connections…", + "msg.saved": "Settings saved", + "msg.started": "Run started", + "msg.busy": "A run is already in progress", + "msg.cancelled": "Stop requested", + "msg.scheduleOn": "Schedule enabled", + "msg.scheduleOff": "Schedule paused", + "error.required": "{field} is required", + "error.range": "{field} must be between {min} and {max}", + "error.invalidChoice": "Invalid {field}", + "error.invalidCron": "Invalid cron expression", + "error.invalidUrl": "Base URL must start with http:// or https://", + "error.absolutePath": "{field} must start with /", + "error.invalidIdentifier": "{field} may only contain letters, digits and underscores", + "forbidden.title": "Access denied", + "forbidden.body": "Only app administrators can open this page.", + }, +} + + +class Translator: + def __init__(self, lang: str) -> None: + self.lang = lang if lang in MESSAGES else "zh" + + def __call__(self, key: str, **params: object) -> str: + text = MESSAGES[self.lang].get(key) or MESSAGES["zh"].get(key) or key + return text.format(**params) if params else text diff --git a/etl_app/runner.py b/etl_app/runner.py new file mode 100644 index 0000000..f11fb26 --- /dev/null +++ b/etl_app/runner.py @@ -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) diff --git a/etl_app/runs.py b/etl_app/runs.py new file mode 100644 index 0000000..a7af613 --- /dev/null +++ b/etl_app/runs.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import sqlite3 +import threading +from contextlib import closing +from datetime import datetime +from pathlib import Path +from typing import Any + +FINAL_FIELDS = ("status", "finished_at", "duration_ms", "target_time", "summary_rows", "detail", "exit_code") +STATUS_GROUPS = { + "processed": ("processed", "history_repaired"), + "idle": ("waiting", "skipped"), + "problem": ("failed", "timeout", "interrupted", "cancelled"), +} + + +def now_text() -> str: + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + +class RunStore: + def __init__(self, path: Path) -> None: + self.path = path + self.path.parent.mkdir(parents=True, exist_ok=True) + self._lock = threading.Lock() + with self._connect() as connection: + connection.executescript( + """ + PRAGMA journal_mode=WAL; + CREATE TABLE IF NOT EXISTS runs ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + trigger TEXT NOT NULL, + dry_run INTEGER NOT NULL DEFAULT 0, + status TEXT NOT NULL, + started_at TEXT NOT NULL, + finished_at TEXT, + duration_ms INTEGER, + target_time TEXT NOT NULL DEFAULT '', + summary_rows INTEGER, + detail TEXT NOT NULL DEFAULT '', + exit_code INTEGER + ); + CREATE INDEX IF NOT EXISTS runs_status ON runs(status, id); + """ + ) + + def create(self, trigger: str, dry_run: bool) -> int: + with self._lock, self._connect() as connection: + cursor = connection.execute( + "INSERT INTO runs(trigger, dry_run, status, started_at) VALUES (?, ?, 'running', ?)", + (trigger, int(dry_run), now_text()), + ) + return int(cursor.lastrowid) + + def finish(self, run_id: int, **values: Any) -> None: + columns = [name for name in FINAL_FIELDS if name in values] + assignments = ", ".join(f"{name} = ?" for name in columns) + with self._lock, self._connect() as connection: + connection.execute( + f"UPDATE runs SET {assignments} WHERE id = ?", + (*[values[name] for name in columns], run_id), + ) + + def get(self, run_id: int) -> dict[str, Any] | None: + with self._connect() as connection: + row = connection.execute("SELECT * FROM runs WHERE id = ?", (run_id,)).fetchone() + return dict(row) if row else None + + def page(self, page: int = 1, page_size: int = 20, status: str = "") -> tuple[list[dict[str, Any]], int]: + where, params = self._status_filter(status) + offset = max(0, page - 1) * page_size + with self._connect() as connection: + total = connection.execute(f"SELECT COUNT(*) FROM runs {where}", params).fetchone()[0] + rows = connection.execute( + f"SELECT * FROM runs {where} ORDER BY id DESC LIMIT ? OFFSET ?", + (*params, page_size, offset), + ).fetchall() + return [dict(row) for row in rows], int(total) + + def latest_finished(self) -> dict[str, Any] | None: + with self._connect() as connection: + row = connection.execute("SELECT * FROM runs WHERE status <> 'running' ORDER BY id DESC LIMIT 1").fetchone() + return dict(row) if row else None + + def latest_written(self) -> dict[str, Any] | None: + with self._connect() as connection: + row = connection.execute( + "SELECT * FROM runs WHERE status = 'processed' AND dry_run = 0 ORDER BY id DESC LIMIT 1" + ).fetchone() + return dict(row) if row else None + + def counts_since(self, started_at: str) -> dict[str, int]: + with self._connect() as connection: + rows = connection.execute( + "SELECT status, COUNT(*) FROM runs WHERE started_at >= ? AND dry_run = 0 GROUP BY status", + (started_at,), + ).fetchall() + return {str(status): int(count) for status, count in rows} + + def mark_interrupted(self) -> int: + with self._lock, self._connect() as connection: + cursor = connection.execute( + "UPDATE runs SET status = 'interrupted', finished_at = ? WHERE status = 'running'", + (now_text(),), + ) + return cursor.rowcount + + def prune(self, keep: int) -> list[int]: + with self._lock, self._connect() as connection: + rows = connection.execute( + "SELECT id FROM runs WHERE status <> 'running' ORDER BY id DESC LIMIT -1 OFFSET ?", + (keep,), + ).fetchall() + removed = [int(row[0]) for row in rows] + connection.executemany("DELETE FROM runs WHERE id = ?", [(run_id,) for run_id in removed]) + return removed + + @staticmethod + def _status_filter(status: str) -> tuple[str, tuple[object, ...]]: + statuses = STATUS_GROUPS.get(status, (status,) if status else ()) + if not statuses: + return "", () + return f"WHERE status IN ({', '.join('?' for _ in statuses)})", statuses + + def _connect(self) -> Any: + connection = sqlite3.connect(self.path, timeout=30) + connection.row_factory = sqlite3.Row + return _Transaction(connection) + + +class _Transaction: + def __init__(self, connection: sqlite3.Connection) -> None: + self.connection = connection + + def __enter__(self) -> sqlite3.Connection: + return self.connection + + def __exit__(self, exc_type: object, *_: object) -> None: + with closing(self.connection): + if exc_type is None: + self.connection.commit() + else: + self.connection.rollback() diff --git a/etl_app/scheduler.py b/etl_app/scheduler.py new file mode 100644 index 0000000..676d4d1 --- /dev/null +++ b/etl_app/scheduler.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from datetime import datetime + +from apscheduler.schedulers.background import BackgroundScheduler +from apscheduler.triggers.cron import CronTrigger +from apscheduler.triggers.interval import IntervalTrigger + +from .config import TIMEZONE, Settings +from .runner import Runner + +JOB_ID = "interference-etl" + + +class EtlScheduler: + def __init__(self, runner: Runner) -> None: + self.runner = runner + self.scheduler = BackgroundScheduler( + timezone=TIMEZONE, + job_defaults={"coalesce": True, "max_instances": 1, "misfire_grace_time": 300}, + ) + + def start(self, settings: Settings) -> None: + if not self.scheduler.running: + self.scheduler.start() + self.apply(settings) + + def shutdown(self) -> None: + if self.scheduler.running: + self.scheduler.shutdown(wait=False) + + def apply(self, settings: Settings) -> None: + if self.scheduler.get_job(JOB_ID): + self.scheduler.remove_job(JOB_ID) + if not settings.schedule_enabled: + return + if settings.schedule_mode == "cron": + trigger = CronTrigger.from_crontab(settings.cron_expression, timezone=TIMEZONE) + else: + trigger = IntervalTrigger(minutes=settings.interval_minutes, timezone=TIMEZONE) + self.scheduler.add_job(self._run, trigger, id=JOB_ID, replace_existing=True) + + def next_run_time(self) -> datetime | None: + job = self.scheduler.get_job(JOB_ID) + return getattr(job, "next_run_time", None) if job else None + + def _run(self) -> None: + self.runner.run("schedule") diff --git a/etl_app/server.py b/etl_app/server.py new file mode 100644 index 0000000..326835d --- /dev/null +++ b/etl_app/server.py @@ -0,0 +1,136 @@ +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 = """ +InterferenceETL + +InterferenceETL +""" + + +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() diff --git a/etl_app/service.py b/etl_app/service.py new file mode 100644 index 0000000..f74bfe3 --- /dev/null +++ b/etl_app/service.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +from datetime import datetime +from pathlib import Path +from typing import Any + +from . import __version__ +from .config import Settings, SettingsError, SettingsStore, validate +from .connectors import check_database, check_storage +from .runner import Runner +from .runs import RunStore +from .scheduler import EtlScheduler + + +class EtlService: + def __init__(self, root: Path, runner_command: list[str] | None = None) -> None: + self.root = root + self.settings = SettingsStore(root / "settings.json") + self.runs = RunStore(root / "runs.db") + self.runner = Runner(self.settings, self.runs, root, runner_command) + self.scheduler = EtlScheduler(self.runner) + + def start(self) -> None: + self.runs.mark_interrupted() + self.scheduler.start(self.settings.get()) + + def stop(self) -> None: + self.scheduler.shutdown() + self.runner.cancel() + + def update_settings(self, data: dict[str, Any]) -> Settings: + settings = self.settings.update(data) + self.scheduler.apply(settings) + return settings + + def set_schedule_enabled(self, enabled: bool) -> Settings: + return self.update_settings({"schedule_enabled": enabled}) + + def status(self) -> dict[str, Any]: + settings = self.settings.get() + next_run = self.scheduler.next_run_time() + today = datetime.now().strftime("%Y-%m-%d 00:00:00") + return { + "version": __version__, + "configured": self.settings.configured(), + "schedule_enabled": settings.schedule_enabled, + "schedule_mode": settings.schedule_mode, + "interval_minutes": settings.interval_minutes, + "cron_expression": settings.cron_expression, + "storage_mode": settings.storage_mode, + "database_mode": settings.database_mode, + "next_run_at": next_run.strftime("%Y-%m-%d %H:%M:%S") if next_run else "", + "running": self.runner.current, + "last_run": self.runs.latest_finished(), + "last_processed": self.runs.latest_written(), + "today": self.runs.counts_since(today), + } + + def check_connections(self, data: dict[str, Any] | None = None) -> dict[str, dict[str, Any]]: + settings = validate(data or {}, self.settings.get()) + return { + "storage": _attempt(check_storage, settings), + "database": _attempt(check_database, settings), + } + + +def _attempt(check: Any, settings: Settings) -> dict[str, Any]: + try: + return {"ok": True, **check(settings)} + except SettingsError: + raise + except Exception as exc: + return {"ok": False, "detail": str(exc)[:500]} diff --git a/etl_app/static/icon.svg b/etl_app/static/icon.svg new file mode 100644 index 0000000..f148937 --- /dev/null +++ b/etl_app/static/icon.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/etl_app/theme.py b/etl_app/theme.py new file mode 100644 index 0000000..b3816f6 --- /dev/null +++ b/etl_app/theme.py @@ -0,0 +1,259 @@ +from __future__ import annotations + +from pathlib import Path + +ICON_PATH = Path(__file__).resolve().parent / "static" / "icon.svg" +ICON_SVG = ICON_PATH.read_text(encoding="utf-8") + +STYLE = """ + +""" diff --git a/etl_app/ui.py b/etl_app/ui.py new file mode 100644 index 0000000..8e249ff --- /dev/null +++ b/etl_app/ui.py @@ -0,0 +1,792 @@ +from __future__ import annotations + +import posixpath +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from datetime import datetime +from typing import Any + +from fastapi import Request +from nicegui import Client, run, ui +from nicegui.element import Element +from nicegui.elements.mixins.value_element import ValueElement + +from . import __version__ +from .auth import Identity, identify +from .config import SettingsError, public_view +from .i18n import Translator +from .service import EtlService +from .theme import ICON_SVG, STYLE + +PREFS_JS = """ +return { + lang: localStorage.getItem('interference-etl.lang') || localStorage.getItem('metrix.locale') || navigator.language || 'zh-CN', + dark: localStorage.getItem('interference-etl.dark') ?? localStorage.getItem('metrix.dark') + ?? (window.matchMedia('(prefers-color-scheme: dark)').matches ? '1' : '0'), +}; +""" + +STATUS_TONES = { + "running": "primary", + "processed": "success", + "history_repaired": "success", + "skipped": "neutral", + "waiting": "neutral", + "failed": "danger", + "timeout": "danger", + "interrupted": "danger", + "cancelled": "warning", +} +RUN_FILTERS = ("", "processed", "idle", "problem") +PAGE_SIZE = 20 +LOG_TAIL_LINES = 300 + + +def register(service: EtlService) -> None: + @ui.page("/admin", title="InterferenceETL", response_timeout=10) + async def admin_page(request: Request, client: Client) -> None: + ui.add_head_html(STYLE) + identity = identify(request.headers) + if identity is None or not identity.is_admin: + accept = request.headers.get("accept-language", "").lower() + render_forbidden(Translator("en" if accept.startswith("en") else "zh")) + return + await client.connected() + prefs = await ui.run_javascript(PREFS_JS, timeout=5) or {} + AdminPage(service, identity, prefs).build() + + +def render_forbidden(t: Translator) -> None: + with ui.element("div").classes("etl-forbidden"): + with ui.element("div").classes("etl-card etl-forbidden-card"): + ui.icon("lock").classes("etl-forbidden-icon") + ui.label(t("forbidden.title")).classes("etl-forbidden-title") + ui.label(t("forbidden.body")).classes("etl-muted") + + +def tone_of(status: str) -> str: + return STATUS_TONES.get(status, "neutral") + + +def format_duration(milliseconds: int | None) -> str: + if milliseconds is None: + return "" + seconds = milliseconds / 1000 + if seconds < 60: + return f"{seconds:.1f}s" + minutes, rest = divmod(int(seconds), 60) + if minutes < 60: + return f"{minutes}m {rest:02d}s" + hours, minutes = divmod(minutes, 60) + return f"{hours}h {minutes:02d}m" + + +def elapsed_since(started_at: str) -> str: + try: + started = datetime.strptime(started_at, "%Y-%m-%d %H:%M:%S") + except ValueError: + return "" + seconds = max(0, int((datetime.now() - started).total_seconds())) + minutes, rest = divmod(seconds, 60) + return f"{minutes:02d}:{rest:02d}" + + +def short_time(value: str) -> str: + return value[:16] if value else "" + + +class AdminPage: + def __init__(self, service: EtlService, identity: Identity, prefs: dict[str, Any]) -> None: + self.service = service + self.identity = identity + lang = str(prefs.get("lang") or "zh").lower() + self.t = Translator("en" if lang.startswith("en") else "zh") + self.dark = ui.dark_mode(str(prefs.get("dark")) == "1") + self.status: dict[str, Any] = {} + self.conditional: list[tuple[Element, Callable[[dict[str, Any]], bool]]] = [] + self.secret_inputs: dict[str, Any] = {} + self.log_key: tuple[Any, ...] | None = None + self.recent_key: tuple[Any, ...] | None = None + self.runs_key: tuple[Any, ...] | None = None + self.runs_filter = "" + self.runs_page = 1 + self.form: dict[str, Any] = {} + self.inputs: dict[str, ValueElement] = {} + + def build(self) -> None: + self.status = self.service.status() + with ui.element("div").classes("etl-shell"): + self.build_header() + with ui.element("main").classes("etl-main"): + with ui.tab_panels(self.tabs, value="overview", animated=False).classes("etl-panels"): + with ui.tab_panel("overview").classes("etl-panel"): + self.build_overview() + with ui.tab_panel("runs").classes("etl-panel"): + self.build_runs() + with ui.tab_panel("settings").classes("etl-panel"): + self.build_settings() + self.build_log_dialog() + self.refresh() + ui.timer(2.0, self.refresh) + + # Header + + def build_header(self) -> None: + t = self.t + with ui.element("header").classes("etl-header"): + with ui.element("div").classes("etl-header-inner"): + with ui.element("div").classes("etl-brand"): + ui.html(ICON_SVG, sanitize=False).classes("etl-brand-icon") + with ui.element("div").classes("etl-brand-text"): + ui.label(t("app.title")).classes("etl-brand-title") + ui.label(f"InterferenceETL · v{__version__}").classes("etl-brand-sub") + with ui.tabs(value="overview").props("no-caps dense align=left indicator-color=primary narrow-indicator").classes( + "etl-tabs" + ) as tabs: + ui.tab("overview", label=t("tab.overview")) + ui.tab("runs", label=t("tab.runs")) + ui.tab("settings", label=t("tab.settings")) + self.tabs = tabs + with ui.element("div").classes("etl-header-tools"): + with ui.element("div").classes("etl-pill") as pill: + ui.element("span").classes("etl-pill-dot") + self.pill_label = ui.label("") + self.pill = pill + ui.button(t("header.languageShort"), on_click=self.toggle_language).props( + "flat dense no-caps" + ).classes("etl-tool-btn").tooltip(t("header.language")) + self.theme_button = ui.button(icon="dark_mode", on_click=self.toggle_theme).props("flat dense round").classes( + "etl-tool-btn" + ) + self.theme_button.tooltip(t("header.theme")) + with ui.element("div").classes("etl-user"): + ui.label((self.identity.label or "?")[:1].upper()).classes("etl-avatar") + ui.label(self.identity.label).classes("etl-user-name") + + async def toggle_language(self) -> None: + next_lang = "en-US" if self.t.lang == "zh" else "zh-CN" + ui.run_javascript(f"localStorage.setItem('interference-etl.lang', '{next_lang}'); history.go(0);") + + def toggle_theme(self) -> None: + dark = not bool(self.dark.value) + self.dark.set_value(dark) + ui.run_javascript(f"localStorage.setItem('interference-etl.dark', '{1 if dark else 0}')") + self.refresh_header() + + # Overview + + def build_overview(self) -> None: + t = self.t + with ui.element("div").classes("etl-cards"): + self.card_schedule = self.metric_card("schedule", t("card.schedule")) + self.card_current = self.metric_card("bolt", t("card.current")) + self.card_last = self.metric_card("task_alt", t("card.lastRun")) + self.card_latest = self.metric_card("storage", t("card.latestData")) + + with ui.element("section").classes("etl-card etl-actions"): + with ui.element("div").classes("etl-actions-buttons"): + self.run_button = ui.button(t("action.run"), icon="play_arrow", on_click=lambda: self.start_run(False)).props( + "unelevated no-caps color=primary" + ).classes("etl-btn etl-btn-primary") + self.dry_button = ui.button(t("action.dryRun"), icon="science", on_click=lambda: self.start_run(True)).props( + "outline no-caps" + ).classes("etl-btn") + self.dry_button.tooltip(t("action.dryRunHint")) + self.schedule_button = ui.button("", on_click=self.toggle_schedule).props("outline no-caps").classes("etl-btn") + self.cancel_button = ui.button(t("action.cancel"), icon="stop", on_click=self.cancel_run).props( + "outline no-caps" + ).classes("etl-btn etl-btn-danger") + self.today_label = ui.label("").classes("etl-muted etl-today") + + with ui.element("div").classes("etl-split"): + with ui.element("section").classes("etl-card etl-log-card"): + with ui.element("div").classes("etl-card-head"): + with ui.element("div").classes("etl-card-title"): + ui.icon("terminal").classes("etl-card-icon") + ui.label(t("log.title")) + self.log_meta = ui.label("").classes("etl-muted etl-log-meta") + self.log_view = ui.label(t("log.empty")).classes("etl-log") + with ui.element("section").classes("etl-card etl-recent-card"): + with ui.element("div").classes("etl-card-head"): + with ui.element("div").classes("etl-card-title"): + ui.icon("history").classes("etl-card-icon") + ui.label(t("recent.title")) + ui.button(t("action.viewAll"), on_click=lambda: self.tabs.set_value("runs")).props( + "flat dense no-caps color=primary" + ).classes("etl-link-btn") + self.recent_box = ui.element("div").classes("etl-recent") + + def metric_card(self, icon: str, title: str) -> dict[str, Any]: + with ui.element("section").classes("etl-card etl-metric"): + with ui.element("div").classes("etl-metric-head"): + ui.label(title).classes("etl-metric-title") + ui.icon(icon).classes("etl-metric-icon") + with ui.element("div").classes("etl-metric-value-row"): + spinner = ui.spinner(size="18px").classes("etl-metric-spinner") + value = ui.label("").classes("etl-metric-value") + sub = ui.label("").classes("etl-metric-sub") + return {"value": value, "sub": sub, "spinner": spinner} + + def refresh(self) -> None: + self.status = self.service.status() + self.refresh_header() + self.refresh_cards() + self.refresh_actions() + self.refresh_log() + self.refresh_recent() + self.refresh_runs() + + def refresh_header(self) -> None: + enabled = bool(self.status["schedule_enabled"]) + self.pill_label.set_text(self.t("header.scheduleOn" if enabled else "header.scheduleOff")) + self.pill.classes(replace=f"etl-pill {'is-on' if enabled else 'is-off'}") + self.theme_button.props(f"icon={'light_mode' if self.dark.value else 'dark_mode'}") + + def refresh_cards(self) -> None: + t, status = self.t, self.status + card = self.card_schedule + if not status["configured"]: + card["value"].set_text(t("schedule.setup")) + card["sub"].set_text(t("empty.dash")) + elif not status["schedule_enabled"]: + card["value"].set_text(t("schedule.paused")) + card["sub"].set_text(self.schedule_text()) + else: + card["value"].set_text(self.schedule_text()) + next_run = status["next_run_at"] + card["sub"].set_text(t("schedule.next", time=next_run[11:19]) if next_run else t("empty.dash")) + card["value"].classes(replace="etl-metric-value" + ("" if status["schedule_enabled"] else " is-muted")) + card["spinner"].set_visibility(False) + + running = status["running"] + card = self.card_current + card["spinner"].set_visibility(bool(running)) + if running: + card["value"].set_text(t("current.running")) + card["sub"].set_text( + t( + "current.elapsed", + id=running["id"], + trigger=self.trigger_text(running["trigger"], running["dry_run"]), + elapsed=elapsed_since(running["started_at"]), + ) + ) + else: + last = status["last_run"] + card["value"].set_text(t("current.idle")) + finished = (last or {}).get("finished_at") or "" + card["sub"].set_text(t("current.lastFinished", time=finished[5:19]) if finished else t("empty.dash")) + card["value"].classes(replace="etl-metric-value" + (" tone-primary" if running else "")) + + last = status["last_run"] + card = self.card_last + card["spinner"].set_visibility(False) + if last: + card["value"].set_text(self.status_text(last)) + card["value"].classes(replace=f"etl-metric-value tone-{tone_of(last['status'])}") + card["sub"].set_text(f"{last['started_at'][5:19]} · {self.detail_text(last) or self.trigger_text(last['trigger'], last['dry_run'])}") + else: + card["value"].set_text(t("empty.never")) + card["value"].classes(replace="etl-metric-value is-muted") + card["sub"].set_text(t("empty.dash")) + + latest = status["last_processed"] + card = self.card_latest + card["spinner"].set_visibility(False) + if latest: + card["value"].set_text(short_time(latest["target_time"]) or t("empty.dash")) + rows = latest.get("summary_rows") + card["sub"].set_text( + t("latest.rows", rows=f"{rows:,}" if isinstance(rows, int) else "-", time=(latest["finished_at"] or "")[5:16]) + ) + card["value"].classes(replace="etl-metric-value") + else: + card["value"].set_text(t("empty.dash")) + card["value"].classes(replace="etl-metric-value is-muted") + card["sub"].set_text(t("empty.never")) + + def refresh_actions(self) -> None: + running = bool(self.status["running"]) + configured = bool(self.status["configured"]) + self.run_button.set_enabled(not running and configured) + self.dry_button.set_enabled(not running and configured) + self.cancel_button.set_visibility(running) + enabled = bool(self.status["schedule_enabled"]) + self.schedule_button.set_text(self.t("action.pause" if enabled else "action.resume")) + self.schedule_button.props(f"icon={'pause' if enabled else 'schedule'}") + self.schedule_button.set_enabled(configured or enabled) + today = self.status["today"] + processed = today.get("processed", 0) + today.get("history_repaired", 0) + idle = today.get("skipped", 0) + today.get("waiting", 0) + problem = sum(today.get(name, 0) for name in ("failed", "timeout", "interrupted", "cancelled")) + self.today_label.set_text( + self.t("today.summary", total=sum(today.values()), processed=processed, idle=idle, problem=problem) + ) + + def refresh_log(self) -> None: + running = self.status["running"] + run = running or self.status["last_run"] + if not run: + return + run_id = run["id"] + log_text = self.service.runner.read_log(run_id, tail=LOG_TAIL_LINES) + key = (run_id, bool(running), len(log_text), log_text[-64:]) + if key == self.log_key: + return + self.log_key = key + status = self.t("status.running") if running else self.status_text(run) + self.log_meta.set_text(f"#{run_id} · {status} · {run['started_at'][5:19]}") + self.log_view.set_text(log_text or self.t("log.empty")) + ui.run_javascript(f"const el = getHtmlElement({self.log_view.id}); if (el) el.scrollTop = el.scrollHeight;") + + def refresh_recent(self) -> None: + rows, _ = self.service.runs.page(1, 8) + key = tuple((row["id"], row["status"]) for row in rows) + if key == self.recent_key: + return + self.recent_key = key + self.recent_box.clear() + with self.recent_box: + if not rows: + ui.label(self.t("recent.empty")).classes("etl-muted etl-empty") + for row in rows: + with ui.element("div").classes("etl-recent-item").on("click", lambda _, run_id=row["id"]: self.open_log(run_id)): + ui.element("span").classes(f"etl-dot tone-{tone_of(row['status'])}") + with ui.element("div").classes("etl-recent-text"): + ui.label(self.status_text(row)).classes("etl-recent-status") + ui.label(self.detail_text(row) or self.trigger_text(row["trigger"], row["dry_run"])).classes( + "etl-recent-detail" + ) + ui.label(row["started_at"][11:19]).classes("etl-recent-time") + + # Runs + + def build_runs(self) -> None: + t = self.t + with ui.element("section").classes("etl-card etl-runs-card"): + with ui.element("div").classes("etl-runs-toolbar"): + ui.toggle( + {key: t(f"runs.filter.{key or 'all'}") for key in RUN_FILTERS}, + value="", + on_change=self.change_filter, + ).props("no-caps unelevated dense toggle-color=primary").classes("etl-segment") + with ui.element("div").classes("etl-runs-tools"): + self.runs_total = ui.label("").classes("etl-muted") + ui.button(icon="refresh", on_click=lambda: self.refresh_runs(force=True)).props("flat round dense").tooltip( + t("action.refresh") + ) + columns = [ + {"name": "id", "label": t("runs.col.id"), "field": "id", "align": "left"}, + {"name": "started_at", "label": t("runs.col.started"), "field": "started_at", "align": "left"}, + {"name": "trigger", "label": t("runs.col.trigger"), "field": "trigger_text", "align": "left"}, + {"name": "status", "label": t("runs.col.status"), "field": "status_text", "align": "left"}, + {"name": "target_time", "label": t("runs.col.target"), "field": "target_text", "align": "left"}, + {"name": "summary_rows", "label": t("runs.col.rows"), "field": "rows_text", "align": "right"}, + {"name": "duration", "label": t("runs.col.duration"), "field": "duration_text", "align": "right"}, + {"name": "detail", "label": t("runs.col.detail"), "field": "detail_text", "align": "left"}, + ] + self.runs_table = ui.table(rows=[], columns=columns, row_key="id", pagination=0).props( + "flat hide-pagination" + ).classes("etl-table") + self.runs_table.props["no-data-label"] = t("runs.empty") + self.runs_table.add_slot( + "body-cell-status", + '{{ props.value }}', + ) + self.runs_table.add_slot( + "body-cell-detail", + '
{{ props.value }}
', + ) + self.runs_table.on("rowClick", lambda event: self.open_log(int(event.args[1]["id"]))) + with ui.element("div").classes("etl-runs-footer"): + self.runs_pagination = ui.pagination(1, 1, direction_links=True, value=1, on_change=self.change_page).props( + "max-pages=7 boundary-numbers flat active-design=unelevated active-color=primary" + ) + + def change_filter(self, event: Any) -> None: + self.runs_filter = event.value or "" + self.runs_page = 1 + self.runs_pagination.set_value(1) + self.refresh_runs(force=True) + + def change_page(self, event: Any) -> None: + self.runs_page = int(event.value or 1) + self.refresh_runs(force=True) + + def refresh_runs(self, force: bool = False) -> None: + rows, total = self.service.runs.page(self.runs_page, PAGE_SIZE, self.runs_filter) + key = (self.runs_filter, self.runs_page, total, tuple((row["id"], row["status"]) for row in rows)) + if key == self.runs_key and not force: + return + self.runs_key = key + self.runs_table.rows = [self.table_row(row) for row in rows] + self.runs_table.update() + self.runs_total.set_text(self.t("runs.total", n=total)) + self.runs_pagination.max = max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE) + self.runs_pagination.update() + + def table_row(self, row: dict[str, Any]) -> dict[str, Any]: + rows = row.get("summary_rows") + return { + "id": row["id"], + "started_at": row["started_at"], + "trigger_text": self.trigger_text(row["trigger"], row["dry_run"]), + "status_text": self.status_text(row), + "tone": tone_of(row["status"]), + "target_text": short_time(row.get("target_time") or ""), + "rows_text": f"{rows:,}" if isinstance(rows, int) else "", + "duration_text": format_duration(row.get("duration_ms")), + "detail_text": self.detail_text(row), + } + + # Log dialog + + def build_log_dialog(self) -> None: + with ui.dialog() as dialog, ui.card().classes("etl-dialog"): + with ui.element("div").classes("etl-dialog-head"): + self.dialog_title = ui.label("").classes("etl-dialog-title") + self.dialog_badge = ui.label("").classes("etl-badge") + ui.element("div").classes("etl-grow") + ui.button(icon="close", on_click=dialog.close).props("flat round dense") + self.dialog_meta = ui.element("div").classes("etl-dialog-meta") + self.dialog_log = ui.label("").classes("etl-log etl-log-dialog") + with ui.element("div").classes("etl-dialog-foot"): + ui.button(self.t("action.copy"), icon="content_copy", on_click=self.copy_log).props("flat no-caps") + ui.button(self.t("action.close"), on_click=dialog.close).props("unelevated no-caps color=primary").classes( + "etl-btn-primary" + ) + self.dialog = dialog + self.dialog_text = "" + + def open_log(self, run_id: int) -> None: + run_row = self.service.runs.get(run_id) + if run_row is None: + return + t = self.t + self.dialog_title.set_text(t("dialog.title", id=run_id)) + self.dialog_badge.set_text(self.status_text(run_row)) + self.dialog_badge.classes(replace=f"etl-badge tone-{tone_of(run_row['status'])}") + self.dialog_meta.clear() + rows = run_row.get("summary_rows") + items = ( + ("dialog.started", run_row["started_at"]), + ("dialog.finished", run_row.get("finished_at") or t("empty.dash")), + ("dialog.duration", format_duration(run_row.get("duration_ms")) or t("empty.dash")), + ("dialog.target", run_row.get("target_time") or t("empty.dash")), + ("dialog.rows", f"{rows:,}" if isinstance(rows, int) else t("empty.dash")), + ) + with self.dialog_meta: + for key, value in items: + with ui.element("div").classes("etl-meta-item"): + ui.label(t(key)).classes("etl-meta-label") + ui.label(str(value)).classes("etl-meta-value") + self.dialog_text = self.service.runner.read_log(run_id) + self.dialog_log.set_text(self.dialog_text or t("log.empty")) + self.dialog.open() + + def copy_log(self) -> None: + ui.clipboard.write(self.dialog_text) + ui.notify(self.t("log.copied"), type="positive", position="top") + + # Actions + + def start_run(self, dry_run: bool) -> None: + if self.service.runner.start("manual", dry_run): + ui.notify(self.t("msg.started"), type="positive", position="top") + else: + ui.notify(self.t("msg.busy"), type="warning", position="top") + ui.timer(0.4, self.refresh, once=True) + + def cancel_run(self) -> None: + if self.service.runner.cancel(): + ui.notify(self.t("msg.cancelled"), type="info", position="top") + self.refresh() + + def toggle_schedule(self) -> None: + enabled = not bool(self.status["schedule_enabled"]) + try: + settings = self.service.set_schedule_enabled(enabled) + except SettingsError as exc: + ui.notify(self.error_text(exc), type="negative", position="top") + return + self.set_form("schedule_enabled", settings.schedule_enabled) + ui.notify(self.t("msg.scheduleOn" if enabled else "msg.scheduleOff"), type="positive", position="top") + self.refresh() + + # Settings + + def build_settings(self) -> None: + t = self.t + self.load_form() + with ui.element("div").classes("etl-settings"): + with self.section("schedule", "section.schedule"): + with self.field("field.schedule_enabled"): + self.bind(ui.switch(), "schedule_enabled").props("color=primary") + with self.field("field.schedule_mode"): + self.segment({"interval": t("option.interval"), "cron": t("option.cron")}, "schedule_mode") + with self.field("field.interval_minutes", when=lambda form: form["schedule_mode"] == "interval"): + self.number("interval_minutes", 1, 1440) + with self.field("field.cron_expression", "field.cron_hint", when=lambda form: form["schedule_mode"] == "cron"): + self.text("cron_expression") + with self.field("field.timeout_minutes"): + self.number("timeout_minutes", 1, 1440) + + with self.section( + "metrix", + "section.metrix", + when=lambda form: form["storage_mode"] == "metrix" or form["database_mode"] == "metrix", + ): + with self.field("field.metrix_url"): + self.text("metrix_url") + with self.field("field.metrix_token"): + self.secret("metrix_token") + + with self.section("source", "section.source"): + with self.field("field.storage_mode"): + self.segment( + {"metrix": t("option.storageMetrix"), "ftp": "FTP", "sftp": "SFTP"}, + "storage_mode", + self.change_storage_mode, + ) + metrix = lambda form: form["storage_mode"] == "metrix" # noqa: E731 + remote = lambda form: form["storage_mode"] != "metrix" # noqa: E731 + with self.field("field.metrix_storage_id", when=metrix): + self.text("metrix_storage_id") + with self.field("field.remote_host", when=remote): + self.text("remote_host") + with self.field("field.remote_port", when=remote): + self.number("remote_port", 1, 65535) + with self.field("field.remote_username", when=remote): + self.text("remote_username").props("autocomplete=off") + with self.field("field.remote_password", when=remote): + self.secret("remote_password") + with self.field("field.ftp_encoding", when=lambda form: form["storage_mode"] == "ftp"): + self.bind(ui.select({"utf-8": "UTF-8", "gbk": "GBK", "gb18030": "GB18030"}), "ftp_encoding").props( + "outlined dense options-dense" + ).classes("etl-input etl-input-short") + with self.field("field.ftp_passive", when=lambda form: form["storage_mode"] == "ftp"): + self.bind(ui.switch(), "ftp_passive").props("color=primary") + with self.field("field.source_root"): + self.text("source_root") + with self.field("field.lookback_days"): + self.number("lookback_days", 1, 31) + with self.field("field.cell_data_directories", "field.cell_data_hint"): + self.bind(ui.textarea(), "cell_data_directories").props("outlined dense autogrow").classes( + "etl-input etl-textarea" + ) + + with self.section("history", "section.history"): + with self.field("field.history_enabled"): + self.bind(ui.switch(), "history_enabled", self.sync_visibility).props("color=primary") + with self.field("field.history_root", when=lambda form: bool(form["history_enabled"])): + self.text("history_root") + + with self.section("database", "section.database"): + with self.field("field.database_mode"): + self.segment({"metrix": t("option.databaseMetrix"), "mysql": t("option.mysql")}, "database_mode") + metrix_db = lambda form: form["database_mode"] == "metrix" # noqa: E731 + mysql = lambda form: form["database_mode"] == "mysql" # noqa: E731 + with self.field("field.metrix_database_id", when=metrix_db): + self.text("metrix_database_id") + with self.field("field.mysql_host", when=mysql): + self.text("mysql_host") + with self.field("field.mysql_port", when=mysql): + self.number("mysql_port", 1, 65535) + with self.field("field.mysql_username", when=mysql): + self.text("mysql_username").props("autocomplete=off") + with self.field("field.mysql_password", when=mysql): + self.secret("mysql_password") + with self.field("field.database_name"): + self.text("database_name") + with self.field("field.table_name"): + self.text("table_name") + + with self.section("retention", "section.retention"): + with self.field("field.keep_outputs"): + self.number("keep_outputs", 1, 1000) + with self.field("field.keep_runs"): + self.number("keep_runs", 50, 100000) + + with ui.element("div").classes("etl-save-bar"): + self.check_box = ui.element("div").classes("etl-checks") + self.test_button = ui.button(t("action.test"), icon="lan", on_click=self.test_connections).props( + "outline no-caps" + ).classes("etl-btn") + ui.button(t("action.save"), icon="save", on_click=self.save_settings).props( + "unelevated no-caps color=primary" + ).classes("etl-btn etl-btn-primary") + self.sync_visibility() + + def load_form(self) -> None: + data = public_view(self.service.settings.get()) + data["cell_data_directories"] = "\n".join(data["cell_data_directories"]) + self.form.clear() + self.form.update(data) + + @contextmanager + def section(self, name: str, title_key: str, when: Callable[[dict[str, Any]], bool] | None = None) -> Iterator[None]: + with ui.element("section").classes(f"etl-card etl-section etl-section-{name}") as section: + ui.label(self.t(title_key)).classes("etl-section-title") + with ui.element("div").classes("etl-fields"): + yield + if when is not None: + self.conditional.append((section, when)) + + @contextmanager + def field( + self, + label_key: str, + hint_key: str | None = None, + when: Callable[[dict[str, Any]], bool] | None = None, + ) -> Iterator[None]: + with ui.element("div").classes("etl-field") as row: + with ui.element("div").classes("etl-field-label"): + ui.label(self.t(label_key)) + if hint_key: + ui.label(self.t(hint_key)).classes("etl-field-hint") + with ui.element("div").classes("etl-field-control"): + yield + if when is not None: + self.conditional.append((row, when)) + + def bind(self, element: ValueElement, name: str, after: Callable[[Any], None] | None = None) -> ValueElement: + element.value = self.form[name] + + def changed(event: Any) -> None: + self.form[name] = event.value + if after is not None: + after(event.value) + + element.on_value_change(changed) + self.inputs[name] = element + return element + + def set_form(self, name: str, value: Any) -> None: + self.form[name] = value + if name in self.inputs: + self.inputs[name].value = value + + def text(self, name: str) -> ValueElement: + return self.bind(ui.input(), name).props("outlined dense").classes("etl-input") + + def segment(self, options: dict[str, str], name: str, after: Callable[[Any], None] | None = None) -> None: + self.bind(ui.toggle(options), name, after or self.sync_visibility).props( + "no-caps unelevated dense toggle-color=primary" + ).classes("etl-segment") + + def number(self, name: str, minimum: int, maximum: int) -> None: + self.bind(ui.number(min=minimum, max=maximum, precision=0, step=1), name).props("outlined dense").classes( + "etl-input etl-input-short" + ) + + def secret(self, name: str) -> None: + field = self.bind(ui.input(password=True), name).props("outlined dense autocomplete=new-password") + field.classes("etl-input") + self.secret_inputs[name] = field + self.update_secret_placeholder(name) + + def update_secret_placeholder(self, name: str) -> None: + saved = bool(self.form.get(f"has_{name}")) + self.secret_inputs[name].props["placeholder"] = self.t("secret.saved" if saved else "secret.empty") + + def change_storage_mode(self, mode: str) -> None: + port = int(self.form.get("remote_port") or 0) + if mode == "sftp" and port in (0, 21): + self.set_form("remote_port", 22) + elif mode == "ftp" and port in (0, 22): + self.set_form("remote_port", 21) + self.sync_visibility() + + def sync_visibility(self, *_: Any) -> None: + for element, predicate in self.conditional: + element.set_visibility(predicate(self.form)) + + def collect_form(self) -> dict[str, Any]: + payload = {key: value for key, value in self.form.items() if not key.startswith("has_")} + payload["cell_data_directories"] = str(self.form.get("cell_data_directories") or "") + return payload + + def save_settings(self) -> None: + try: + settings = self.service.update_settings(self.collect_form()) + except SettingsError as exc: + ui.notify(self.error_text(exc), type="negative", position="top") + return + data = public_view(settings) + for name in self.secret_inputs: + self.form[f"has_{name}"] = data[f"has_{name}"] + self.set_form(name, "") + self.update_secret_placeholder(name) + ui.notify(self.t("msg.saved"), type="positive", position="top") + self.refresh() + + async def test_connections(self) -> None: + self.test_button.props("loading") + self.check_box.clear() + with self.check_box: + ui.label(self.t("check.running")).classes("etl-muted") + try: + result = await run.io_bound(self.service.check_connections, self.collect_form()) + except SettingsError as exc: + self.check_box.clear() + ui.notify(self.error_text(exc), type="negative", position="top") + return + finally: + self.test_button.props(remove="loading") + self.check_box.clear() + with self.check_box: + storage, database = result["storage"], result["database"] + self.check_line( + "check.storage", + storage, + self.t("check.storageOk", count=storage.get("count", 0), latest=storage.get("latest", "-")), + ) + self.check_line("check.database", database, self.t("check.databaseOk", latest=database.get("latest", "-"))) + + def check_line(self, label_key: str, result: dict[str, Any], ok_text: str) -> None: + ok = bool(result.get("ok")) + with ui.element("div").classes(f"etl-check {'is-ok' if ok else 'is-fail'}"): + ui.icon("check_circle" if ok else "error") + ui.label(self.t(label_key)).classes("etl-check-name") + text = ok_text if ok else str(result.get("detail") or "") + detail = ui.label(text).classes("etl-check-text") + detail.props["title"] = text + + # Text helpers + + def schedule_text(self) -> str: + if self.status["schedule_mode"] == "cron": + return self.t("schedule.cron", expr=self.status["cron_expression"]) + return self.t("schedule.every", n=self.status["interval_minutes"]) + + def status_text(self, row: dict[str, Any]) -> str: + if row["status"] == "processed" and row.get("dry_run"): + return self.t("status.dryRunDone") + return self.t(f"status.{row['status']}") + + def trigger_text(self, trigger: str, dry_run: Any) -> str: + if dry_run: + return self.t("trigger.dryRun") + return self.t(f"trigger.{trigger}") + + def detail_text(self, row: dict[str, Any]) -> str: + status, detail = row["status"], str(row.get("detail") or "") + if status == "waiting": + if not detail or detail == "no_source_files": + return self.t("detail.noFiles") + sources = [item for item in detail.split(",") if item] + separator = "、" if self.t.lang == "zh" else ", " + return self.t("detail.missing", count=len(sources), sources=separator.join(sources)) + if status == "skipped": + return self.t("detail.upToDate", time=short_time(detail)) if detail else "" + if status == "timeout": + return self.t("detail.timeout", n=detail) + if status == "processed" and row.get("dry_run"): + return self.t("detail.dryRunOutput") + if status in ("processed", "history_repaired"): + return posixpath.basename(detail.replace("\\", "/")) + return detail + + def error_text(self, exc: SettingsError) -> str: + field = self.t(f"field.{exc.field}") if exc.field else "" + return self.t(f"error.{exc.key}", field=field, **exc.params) diff --git a/etl_app/worker.py b/etl_app/worker.py new file mode 100644 index 0000000..fe53c55 --- /dev/null +++ b/etl_app/worker.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import argparse +import sys +import traceback +from pathlib import Path + +import main + +from .config import SettingsStore +from .connectors import build_client, build_storage, build_store, close_quietly + + +def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int: + settings = SettingsStore(settings_path).get() + print(f"storage_mode={settings.storage_mode}") + print(f"database_mode={'none' if dry_run else settings.database_mode}") + client = build_client(settings) + storage = build_storage(settings, client) + try: + source = main.StorageSource(storage, settings.source_root, settings.cell_data_directories) + store = None if dry_run else build_store(settings, client) + history = None + if store is not None and settings.history_enabled: + history = main.StorageHistoryStore(storage, settings.history_root) + main.process(source, output_dir, settings.lookback_days, store=store, history=history) + finally: + close_quietly(storage) + return 0 + + +def entry(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description="Run one InterferenceETL pass with the saved app settings") + parser.add_argument("--settings", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--dry-run", action="store_true") + args = parser.parse_args(argv) + try: + return run(args.settings, args.output, args.dry_run) + except main.ProcessingError as exc: + print(f"error={exc}", file=sys.stderr, flush=True) + return 1 + except Exception as exc: + traceback.print_exc() + print(f"error={type(exc).__name__}: {exc}", file=sys.stderr, flush=True) + return 1 + + +if __name__ == "__main__": + raise SystemExit(entry()) diff --git a/main.py b/main.py index f8d11bc..5de4256 100644 --- a/main.py +++ b/main.py @@ -94,6 +94,7 @@ CELL_DATA_FILE_RE = re.compile(r"(?P20\d{6})\.xlsx$", re.IGNORECASE) LTE_PLMN = "460-00" DATABASE_NAME = "interference_etl" DATABASE_TABLE = "interference_hourly_summary" +SQL_IDENTIFIER_RE = re.compile(r"[A-Za-z0-9_]{1,64}") DEFAULT_HISTORY_ROOT = f"{DEFAULT_ROOT}/干扰历史数据" LOCAL_CSV_ENCODING = "utf-8-sig" HISTORY_CSV_ENCODING = "gbk" @@ -210,6 +211,48 @@ SUMMARY_HEADER = ( "prev_nearby_fdd", ) +TABLE_COLUMNS_DDL = """ + metric_time DATETIME NOT NULL COMMENT '指标开始时间', + network_type VARCHAR(16) NOT NULL DEFAULT '', + cgi VARCHAR(128) NOT NULL, + cell_name VARCHAR(255) NOT NULL, + interference_dbm DECIMAL(10,3) NOT NULL, + prev_interference_dbm DECIMAL(10,3) NULL, + longitude DECIMAL(10,6) NULL, + latitude DECIMAL(10,6) NULL, + azimuth DECIMAL(6,2) NOT NULL DEFAULT 0, + nearby_count INT NOT NULL DEFAULT 0, + nearby_26g INT NOT NULL DEFAULT 0, + nearby_700m INT NOT NULL DEFAULT 0, + nearby_tdd INT NOT NULL DEFAULT 0, + nearby_fdd INT NOT NULL DEFAULT 0, + prev_nearby_count INT NULL, + prev_nearby_26g INT NULL, + prev_nearby_700m INT NULL, + prev_nearby_tdd INT NULL, + prev_nearby_fdd INT NULL, + PRIMARY KEY (metric_time, cgi) +""" + +COLUMN_MIGRATIONS = { + "network_type": "VARCHAR(16) NOT NULL DEFAULT ''", + "prev_interference_dbm": "DECIMAL(10,3) NULL", + "longitude": "DECIMAL(10,6) NULL", + "latitude": "DECIMAL(10,6) NULL", + "azimuth": "DECIMAL(6,2) NOT NULL DEFAULT 0", + "nearby_count": "INT NOT NULL DEFAULT 0", + "nearby_26g": "INT NOT NULL DEFAULT 0", + "nearby_700m": "INT NOT NULL DEFAULT 0", + "nearby_tdd": "INT NOT NULL DEFAULT 0", + "nearby_fdd": "INT NOT NULL DEFAULT 0", + "prev_nearby_count": "INT NULL", + "prev_nearby_26g": "INT NULL", + "prev_nearby_700m": "INT NULL", + "prev_nearby_tdd": "INT NULL", + "prev_nearby_fdd": "INT NULL", +} + + class ProcessingError(RuntimeError): pass @@ -244,6 +287,16 @@ class HistoryStore(Protocol): def upload(self, metric_time: datetime, payload: bytes) -> str: ... +class FileStorage(Protocol): + def list_dir(self, path: str) -> list[dict[str, object]]: ... + + def read_bytes(self, path: str) -> bytes: ... + + def make_dir(self, path: str) -> None: ... + + def write_bytes(self, directory: str, filename: str, payload: bytes) -> str: ... + + class MetrixApiClient: def __init__(self, base_url: str, token: str) -> None: if not token: @@ -333,36 +386,33 @@ class MetrixApiClient: class ApiSummaryStore: - def __init__(self, client: MetrixApiClient, connection_id: str) -> None: + def __init__( + self, + client: MetrixApiClient, + connection_id: str, + database: str = DATABASE_NAME, + table: str = DATABASE_TABLE, + ) -> None: if not connection_id: raise ProcessingError("METRIX_DATABASE_CONNECTION_ID is required for database output") self.client = client self.connection_id = connection_id - self.table = DATABASE_TABLE + self.database = sql_identifier(database, "database") + self.table = sql_identifier(table, "table") def latest_metric_time(self) -> datetime | None: self._ensure_schema() payload = self._query( f"SELECT MAX(metric_time) AS latest_time FROM `{self.table}`", - database=DATABASE_NAME, + database=self.database, ) rows = payload.get("rows", []) value = rows[0].get("latest_time") if rows else None return datetime.fromisoformat(str(value)) if value else None def replace_latest(self, rows: list[dict[str, str]]) -> dict[str, object]: - if not rows: - raise ProcessingError("Refusing to replace database data with an empty batch") - metric_times = {datetime.strptime(row["metric_time"], "%Y-%m-%d %H:%M:%S") for row in rows} - if len(metric_times) != 1: - raise ProcessingError("Database batch must contain exactly one metric time") - metric_time = next(iter(metric_times)) - latest_time = self.latest_metric_time() - if latest_time is not None and latest_time > metric_time: - raise ProcessingError( - f"Database already contains newer metric time {latest_time:%Y-%m-%d %H:%M:%S}; " - f"refusing to replace it with {metric_time:%Y-%m-%d %H:%M:%S}" - ) + metric_time = batch_metric_time(rows) + ensure_not_newer(self.latest_metric_time(), metric_time) metric_literal = f"'{metric_time:%Y-%m-%d %H:%M:%S}'" values = ",\n".join(self._row_values(metric_literal, row) for row in rows) @@ -373,13 +423,13 @@ class ApiSummaryStore: START TRANSACTION; DELETE FROM `{self.table}` WHERE metric_time = {metric_literal}; INSERT INTO `{self.table}` - (metric_time, network_type, cgi, cell_name, interference_dbm, prev_interference_dbm, longitude, latitude, azimuth, nearby_count, nearby_26g, nearby_700m, nearby_tdd, nearby_fdd, prev_nearby_count, prev_nearby_26g, prev_nearby_700m, prev_nearby_tdd, prev_nearby_fdd) + ({', '.join(SUMMARY_HEADER)}) VALUES {values}; DELETE FROM `{self.table}` WHERE metric_time <> {metric_literal}; COMMIT; """, - "database": DATABASE_NAME, + "database": self.database, "stop_on_error": True, "single_session": True, }, @@ -414,7 +464,7 @@ class ApiSummaryStore: result: list[dict[str, str]] = [] page = 1 while True: - payload = self._query(sql, database=DATABASE_NAME, page=page, page_size=1000) + payload = self._query(sql, database=self.database, page=page, page_size=1000) rows = payload.get("rows", []) if not isinstance(rows, list): raise ProcessingError("Metrix Database API returned invalid rows") @@ -427,68 +477,24 @@ class ApiSummaryStore: return result page += 1 + def ping(self) -> str: + payload = self.client.get_json(self._endpoint("server-info")) + if not isinstance(payload, dict): + raise ProcessingError("Metrix Database API returned invalid server info") + return str(payload.get("version") or payload.get("server_version") or "") + def _ensure_schema(self) -> None: - self._query( - f"CREATE DATABASE IF NOT EXISTS `{DATABASE_NAME}` " - "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" - ) - self._query( - f""" - CREATE TABLE IF NOT EXISTS `{self.table}` ( - metric_time DATETIME NOT NULL COMMENT '指标开始时间', - network_type VARCHAR(16) NOT NULL DEFAULT '', - cgi VARCHAR(128) NOT NULL, - cell_name VARCHAR(255) NOT NULL, - interference_dbm DECIMAL(10,3) NOT NULL, - prev_interference_dbm DECIMAL(10,3) NULL, - longitude DECIMAL(10,6) NULL, - latitude DECIMAL(10,6) NULL, - azimuth DECIMAL(6,2) NOT NULL DEFAULT 0, - nearby_count INT NOT NULL DEFAULT 0, - nearby_26g INT NOT NULL DEFAULT 0, - nearby_700m INT NOT NULL DEFAULT 0, - nearby_tdd INT NOT NULL DEFAULT 0, - nearby_fdd INT NOT NULL DEFAULT 0, - prev_nearby_count INT NULL, - prev_nearby_26g INT NULL, - prev_nearby_700m INT NULL, - prev_nearby_tdd INT NULL, - prev_nearby_fdd INT NULL, - PRIMARY KEY (metric_time, cgi) - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 - """, - database=DATABASE_NAME, - ) + self._query(create_database_sql(self.database)) + self._query(create_table_sql(self.table), database=self.database) columns = self.client.get_json( self._endpoint("columns"), - {"database": DATABASE_NAME, "table": self.table}, + {"database": self.database, "table": self.table}, ) if not isinstance(columns, list): raise ProcessingError("Metrix Database API returned invalid column metadata") existing_columns = {str(item.get("name")) for item in columns if isinstance(item, dict)} - migrations = { - "network_type": "VARCHAR(16) NOT NULL DEFAULT ''", - "prev_interference_dbm": "DECIMAL(10,3) NULL", - "longitude": "DECIMAL(10,6) NULL", - "latitude": "DECIMAL(10,6) NULL", - "azimuth": "DECIMAL(6,2) NOT NULL DEFAULT 0", - "nearby_count": "INT NOT NULL DEFAULT 0", - "nearby_26g": "INT NOT NULL DEFAULT 0", - "nearby_700m": "INT NOT NULL DEFAULT 0", - "nearby_tdd": "INT NOT NULL DEFAULT 0", - "nearby_fdd": "INT NOT NULL DEFAULT 0", - "prev_nearby_count": "INT NULL", - "prev_nearby_26g": "INT NULL", - "prev_nearby_700m": "INT NULL", - "prev_nearby_tdd": "INT NULL", - "prev_nearby_fdd": "INT NULL", - } - for column, definition in migrations.items(): - if column not in existing_columns: - self._query( - f"ALTER TABLE `{self.table}` ADD COLUMN `{column}` {definition}", - database=DATABASE_NAME, - ) + for statement in column_migration_sql(self.table, existing_columns): + self._query(statement, database=self.database) def _endpoint(self, action: str) -> str: return f"/api/databases/{quote(self.connection_id, safe='')}/{action}" @@ -530,105 +536,137 @@ class ApiSummaryStore: ) + ")" -class ApiHistoryStore: - def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None: +class MetrixStorage: + def __init__(self, client: MetrixApiClient, storage_id: str) -> None: + if not storage_id: + raise ProcessingError("Metrix storage ID is required") self.client = client self.storage_id = storage_id - self.root = root.rstrip("/") - def exists(self, metric_time: datetime) -> bool: - directory, filename = self.target(metric_time) - base_entries = self._list_dir(self.root) - if not any(item.get("is_dir") and item.get("path") == directory for item in base_entries): - return False - return any( - not item.get("is_dir") and item.get("name") == filename and int(item.get("size") or 0) > 0 - for item in self._list_dir(directory) - ) + def list_dir(self, path: str) -> list[dict[str, object]]: + payload = self.client.get_json(self._endpoint("files"), {"path": path, "recursive": "false"}) + if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list): + raise ProcessingError("Metrix Storage API returned an invalid file list") + return payload["entries"] - def upload(self, metric_time: datetime, payload: bytes) -> str: - directory, filename = self.target(metric_time) - base_entries = self._list_dir(self.root) - if not any(item.get("is_dir") and item.get("path") == directory for item in base_entries): - response = self.client.post_json( - self._endpoint("mkdir"), - {"path": directory}, - timeout=120, - ) - if not isinstance(response, dict) or response.get("path") != directory: - raise ProcessingError("Metrix Storage API returned an invalid mkdir result") - response = self.client.post_file( - self._endpoint("upload"), - {"path": directory}, - filename, - payload, - ) + def read_bytes(self, path: str) -> bytes: + return self.client.get_bytes(self._endpoint("download"), {"path": path}, timeout=120) + + def make_dir(self, path: str) -> None: + response = self.client.post_json(self._endpoint("mkdir"), {"path": path}, timeout=120) + if not isinstance(response, dict) or response.get("path") != path: + raise ProcessingError("Metrix Storage API returned an invalid mkdir result") + + def write_bytes(self, directory: str, filename: str, payload: bytes) -> str: + response = self.client.post_file(self._endpoint("upload"), {"path": directory}, filename, payload) expected_path = posixpath.join(directory, filename) if not isinstance(response, dict) or response.get("path") != expected_path: raise ProcessingError("Metrix Storage API returned an invalid upload result") return expected_path + def _endpoint(self, action: str) -> str: + return f"/api/storages/{quote(self.storage_id, safe='')}/{action}" + + +class StorageHistoryStore: + def __init__(self, storage: FileStorage, root: str = DEFAULT_HISTORY_ROOT) -> None: + self.storage = storage + self.root = root.rstrip("/") or "/" + + def exists(self, metric_time: datetime) -> bool: + directory, filename = self.target(metric_time) + if not self._has_directory(directory): + return False + return any( + not item.get("is_dir") and item.get("name") == filename and int(item.get("size") or 0) > 0 + for item in self.storage.list_dir(directory) + ) + + def upload(self, metric_time: datetime, payload: bytes) -> str: + directory, filename = self.target(metric_time) + if not self._has_directory(directory): + self.storage.make_dir(directory) + return self.storage.write_bytes(directory, filename, payload) + def target(self, metric_time: datetime) -> tuple[str, str]: directory = posixpath.join(self.root, metric_time.strftime("%Y-%m-%d")) filename = f"干扰数据处理结果_{metric_time:%Y%m%d%H%M%S}.csv" return directory, filename - def _endpoint(self, action: str) -> str: - return f"/api/storages/{quote(self.storage_id, safe='')}/{action}" - - def _list_dir(self, path: str) -> list[dict[str, object]]: - payload = self.client.get_json(self._endpoint("files"), {"path": path, "recursive": "false"}) - if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list): - raise ProcessingError("Metrix Storage API returned an invalid file list") - return payload["entries"] + def _has_directory(self, directory: str) -> bool: + return any(item.get("is_dir") and item.get("path") == directory for item in self.storage.list_dir(self.root)) -class ApiSource: - def __init__(self, client: MetrixApiClient, storage_id: str, root: str) -> None: - self.client = client - self.storage_id = storage_id +class ApiHistoryStore(StorageHistoryStore): + def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None: + super().__init__(MetrixStorage(client, storage_id), root) + + +class StorageSource: + def __init__( + self, + storage: FileStorage, + root: str, + cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES, + ) -> None: + self.storage = storage self.root = root.rstrip("/") or "/" + self.cell_data_directories = tuple(cell_data_directories) def candidates(self, lookback_days: int) -> list[Candidate]: - root_entries = self._list_dir(self.root) - date_dirs = sorted( - (item for item in root_entries if item.get("is_dir") and re.fullmatch(r"\d{4}-\d{2}-\d{2}", item.get("name", ""))), - key=lambda item: item["name"], - ) + date_dirs = self.date_directories() selected_dirs = date_dirs[-max(1, lookback_days) :] result: list[Candidate] = [] for directory in selected_dirs: - for item in self._list_dir(directory["path"]): + for item in self.storage.list_dir(str(directory["path"])): if item.get("is_dir"): continue - candidate = parse_candidate(item["path"], int(item.get("size") or 0)) + candidate = parse_candidate(str(item["path"]), int(item.get("size") or 0)) if candidate is not None: result.append(candidate) return result + def date_directories(self) -> list[dict[str, object]]: + return sorted( + ( + item + for item in self.storage.list_dir(self.root) + if item.get("is_dir") and re.fullmatch(r"\d{4}-\d{2}-\d{2}", str(item.get("name", ""))) + ), + key=lambda item: str(item["name"]), + ) + def download(self, path: str) -> bytes: - endpoint = f"/api/storages/{quote(self.storage_id, safe='')}/download" - return self.client.get_bytes(endpoint, {"path": path}, timeout=120) + return self.storage.read_bytes(path) def cell_data_workbooks(self) -> list[tuple[str, bytes]]: workbooks: list[tuple[str, bytes]] = [] - for directory in CELL_DATA_DIRECTORIES: - item = select_latest_cell_data_file(self._list_dir(directory), directory) + for directory in self.cell_data_directories: + item = select_latest_cell_data_file(self.storage.list_dir(directory), directory) path = str(item["path"]) workbooks.append((path, self.download(path))) return workbooks - def _list_dir(self, path: str) -> list[dict[str, object]]: - endpoint = f"/api/storages/{quote(self.storage_id, safe='')}/files" - payload = self.client.get_json(endpoint, {"path": path, "recursive": "false"}) - if not isinstance(payload, dict) or not isinstance(payload.get("entries"), list): - raise ProcessingError("Metrix Storage API returned an invalid file list") - return payload["entries"] + +class ApiSource(StorageSource): + def __init__( + self, + client: MetrixApiClient, + storage_id: str, + root: str, + cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES, + ) -> None: + super().__init__(MetrixStorage(client, storage_id), root, cell_data_directories) class LocalSource: - def __init__(self, root: Path) -> None: + def __init__( + self, + root: Path, + cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES, + ) -> None: self.root = root.resolve() + self.cell_data_directories = tuple(cell_data_directories) if not self.root.is_dir(): raise ProcessingError(f"Local source directory does not exist: {self.root}") @@ -645,12 +683,12 @@ class LocalSource: return Path(path).read_bytes() def cell_data_workbooks(self) -> list[tuple[str, bytes]]: - directories = [self.root / Path(directory.lstrip("/")) for directory in CELL_DATA_DIRECTORIES] + directories = [self.root / Path(directory.lstrip("/")) for directory in self.cell_data_directories] existing = [directory for directory in directories if directory.is_dir()] if not existing: return [] if len(existing) != len(directories): - raise ProcessingError("Local CellData source must contain all five configured directories") + raise ProcessingError("Local CellData source must contain all configured directories") workbooks: list[tuple[str, bytes]] = [] for directory in directories: entries = [ @@ -830,6 +868,7 @@ def process( history: HistoryStore | None = None, ) -> Path | None: candidates = source.candidates(lookback_days) + progress(f"scanned {len(candidates)} source archives") metric_time, selected, missing = select_window(candidates, requested_window) if metric_time is None: print("status=waiting") @@ -865,9 +904,12 @@ def process( return None if latest_time is not None: previous_rows = store.rows_for_time(latest_time) + progress(f"loaded {len(previous_rows)} previous rows for {latest_time:%Y-%m-%d %H:%M:%S}") + progress(f"processing {metric_time_text}") cell_data_workbooks = source.cell_data_workbooks() cell_metadata = load_cell_metadata(cell_data_workbooks) + progress(f"loaded {len(cell_data_workbooks)} cell data workbooks with {len(cell_metadata)} cells") output_key = metric_time.strftime("%Y%m%d%H%M%S") temp_dir = output_root.resolve() / f".{output_key}.tmp-{os.getpid()}" final_dir = output_root.resolve() / output_key @@ -887,6 +929,8 @@ def process( candidate = selected[source_type] raw_zip = source.download(candidate.path) header, rows, member_name = parse_workbook(raw_zip, source_type) + archive_name = posixpath.basename(candidate.path.replace("\\", "/")) + progress(f"{source_type}: {len(rows)} rows from {archive_name}") csv_name = f"{source_type}_{candidate.window}.csv" write_csv(converted_dir / csv_name, header, rows) for row_number, row in enumerate(rows, start=2): @@ -913,14 +957,17 @@ def process( summary_rows.sort(key=lambda item: (item["cgi"], item["cell_name"])) summary_name = f"interference_summary_{output_key}.csv" write_dict_csv(temp_dir / summary_name, SUMMARY_HEADER, summary_rows) + progress(f"built {len(summary_rows)} summary rows") if store is not None: database_result = store.replace_latest(summary_rows) + progress(f"database updated with {database_result['inserted_rows']} rows") if history is not None: history_path = history.upload( metric_time, dict_csv_bytes(SUMMARY_HEADER, summary_rows, HISTORY_CSV_ENCODING), ) history_result = {"enabled": True, "path": history_path} + progress("history CSV uploaded") matched_coordinates = sum(bool(row["longitude"] and row["latitude"]) for row in summary_rows) manifest = { "generated_at": datetime.now(timezone.utc).isoformat(), @@ -966,6 +1013,10 @@ def process( return final_dir +def progress(message: str) -> None: + print(f"[{datetime.now():%H:%M:%S}] {message}", flush=True) + + def summary_record( record: dict[str, object], source_type: str, @@ -1139,22 +1190,96 @@ def normalize_csv_cell(value: object) -> str: return normalize_cell(value).replace("\u00a0", " ") +def sql_identifier(value: str, field: str) -> str: + if not SQL_IDENTIFIER_RE.fullmatch(value or ""): + raise ProcessingError(f"Invalid {field} name: {value!r}") + return value + + +def create_database_sql(database: str) -> str: + return ( + f"CREATE DATABASE IF NOT EXISTS `{sql_identifier(database, 'database')}` " + "CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci" + ) + + +def create_table_sql(table: str) -> str: + return ( + f"CREATE TABLE IF NOT EXISTS `{sql_identifier(table, 'table')}` ({TABLE_COLUMNS_DDL}) " + "ENGINE=InnoDB DEFAULT CHARSET=utf8mb4" + ) + + +def column_migration_sql(table: str, existing_columns: set[str]) -> list[str]: + return [ + f"ALTER TABLE `{sql_identifier(table, 'table')}` ADD COLUMN `{column}` {definition}" + for column, definition in COLUMN_MIGRATIONS.items() + if column not in existing_columns + ] + + +def batch_metric_time(rows: list[dict[str, str]]) -> datetime: + if not rows: + raise ProcessingError("Refusing to replace database data with an empty batch") + metric_times = {datetime.strptime(row["metric_time"], "%Y-%m-%d %H:%M:%S") for row in rows} + if len(metric_times) != 1: + raise ProcessingError("Database batch must contain exactly one metric time") + return next(iter(metric_times)) + + +def ensure_not_newer(latest_time: datetime | None, metric_time: datetime) -> None: + if latest_time is not None and latest_time > metric_time: + raise ProcessingError( + f"Database already contains newer metric time {latest_time:%Y-%m-%d %H:%M:%S}; " + f"refusing to replace it with {metric_time:%Y-%m-%d %H:%M:%S}" + ) + + +def summary_row_params(row: dict[str, str]) -> tuple[object, ...]: + return ( + row["metric_time"], + row["network_type"], + row["cgi"], + row["cell_name"], + parse_decimal(row["interference_dbm"], "interference_dbm"), + parse_decimal(row["prev_interference_dbm"], "prev_interference_dbm", nullable=True), + parse_decimal(row["longitude"], "longitude", nullable=True), + parse_decimal(row["latitude"], "latitude", nullable=True), + parse_decimal(row["azimuth"], "azimuth"), + int(row["nearby_count"]), + int(row["nearby_26g"]), + int(row["nearby_700m"]), + int(row["nearby_tdd"]), + int(row["nearby_fdd"]), + parse_decimal(row["prev_nearby_count"], "prev_nearby_count", nullable=True), + parse_decimal(row["prev_nearby_26g"], "prev_nearby_26g", nullable=True), + parse_decimal(row["prev_nearby_700m"], "prev_nearby_700m", nullable=True), + parse_decimal(row["prev_nearby_tdd"], "prev_nearby_tdd", nullable=True), + parse_decimal(row["prev_nearby_fdd"], "prev_nearby_fdd", nullable=True), + ) + + def sql_text_literal(value: str) -> str: encoded = value.encode("utf-8").hex() return "''" if not encoded else f"CONVERT(0x{encoded} USING utf8mb4)" -def sql_decimal_literal(value: str, field: str, nullable: bool = False) -> str: +def parse_decimal(value: str, field: str, nullable: bool = False) -> Decimal | None: normalized = value.strip() if not normalized and nullable: - return "NULL" + return None try: number = Decimal(normalized) except InvalidOperation as exc: raise ProcessingError(f"Invalid decimal value for {field}: {value}") from exc if not number.is_finite(): raise ProcessingError(f"Invalid decimal value for {field}: {value}") - return format(number, "f") + return number + + +def sql_decimal_literal(value: str, field: str, nullable: bool = False) -> str: + number = parse_decimal(value, field, nullable) + return "NULL" if number is None else format(number, "f") def write_csv(path: Path, header: tuple[str, ...], rows: list[tuple[object, ...]]) -> None: diff --git a/requirements-app.txt b/requirements-app.txt new file mode 100644 index 0000000..2c92926 --- /dev/null +++ b/requirements-app.txt @@ -0,0 +1,8 @@ +nicegui==4.0.0 +fastapi==0.162.0 +uvicorn==0.54.0 +APScheduler==3.11.3 +PyMySQL==1.2.3 +paramiko==5.1.0 +openpyxl==3.1.5 +tzdata==2026.6 diff --git a/scripts/package_metrix.py b/scripts/package_metrix.py new file mode 100644 index 0000000..604ed61 --- /dev/null +++ b/scripts/package_metrix.py @@ -0,0 +1,127 @@ +"""Build the InterferenceETL Metrix app bundle: dist/metrix/interference-etl-.zip. + +The bundle holds metrix-app.json, icon.svg and the image file image.tar. The version is +etl_app.__version__ plus the git short hash, with -dirty when tracked files have changes. +Requires a working local docker. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +import zipfile +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SLUG = "interference-etl" +NAME = "InterferenceETL" +WEB_PORT = 8080 +DATA_DIR = "/data" + + +def _git(*args: str) -> str: + completed = subprocess.run( + ["git", "-c", f"safe.directory={ROOT.as_posix()}", *args], + cwd=ROOT, + capture_output=True, + text=True, + check=True, + ) + return completed.stdout.strip() + + +def base_version() -> str: + source = (ROOT / "etl_app" / "__init__.py").read_text(encoding="utf-8") + match = re.search(r'__version__\s*=\s*"([^"]+)"', source) + if match is None: + raise SystemExit("etl_app/__init__.py has no __version__") + return match.group(1) + + +def version() -> str: + base = base_version() + try: + commit = _git("rev-parse", "--short", "HEAD") + dirty = bool(_git("status", "--porcelain", "--untracked-files=no")) + except (OSError, subprocess.CalledProcessError): + return base + return f"{base}-{commit}-dirty" if dirty else f"{base}-{commit}" + + +def manifest(image: str, release: str) -> dict: + return { + "schema": 2, + "slug": SLUG, + "name": NAME, + "version": release, + "user_auth": "metrix", + "admin_auth": "metrix", + "admin_path": "/admin", + "icon": "icon.svg", + "services": [ + {"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT}, + ], + "data_dir": DATA_DIR, + "env": {"TZ": "Asia/Shanghai"}, + } + + +def _run(command: list[str]) -> None: + print("+ " + " ".join(command), flush=True) + subprocess.run(command, cwd=ROOT, check=True) + + +def build_image(image: str, args: argparse.Namespace) -> None: + command = ["docker", "build", "-f", "deploy/Dockerfile", "-t", image] + for key, value in (("PYTHON_IMAGE", args.python_image), ("PIP_INDEX", args.pip_index)): + if value: + command += ["--build-arg", f"{key}={value}"] + command.append(".") + _run(command) + + +def write_bundle(image: str, release: str, target: Path) -> None: + target.parent.mkdir(parents=True, exist_ok=True) + partial = target.with_name(target.name + ".partial") + with tempfile.TemporaryDirectory(prefix="interference-etl-pack-", dir=target.parent) as work: + tar = Path(work) / "image.tar" + _run(["docker", "save", "-o", str(tar), image]) + with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle: + bundle.writestr("metrix-app.json", json.dumps(manifest(image, release), ensure_ascii=False, indent=2) + "\n") + bundle.write(ROOT / "etl_app" / "static" / "icon.svg", "icon.svg") + bundle.write(tar, "image.tar") + os.replace(partial, target) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Build the InterferenceETL Metrix app bundle") + parser.add_argument("--skip-build", action="store_true", help="package the existing local image of this version") + parser.add_argument("--python-image", default=os.environ.get("ETL_PYTHON_IMAGE", ""), help="base Python image") + parser.add_argument("--pip-index", default=os.environ.get("ETL_PIP_INDEX", ""), help="pip index URL") + parser.add_argument("--output", default=str(ROOT / "dist" / "metrix"), help="output directory") + args = parser.parse_args() + + if shutil.which("docker") is None: + print("docker not found", file=sys.stderr) + return 1 + current = version() + image = f"{SLUG}:{current}" + if not args.skip_build: + build_image(image, args) + target = Path(args.output).resolve() / f"{SLUG}-{current}.zip" + write_bundle(image, current, target) + size = target.stat().st_size + print(f"bundle: {target}") + print(f"size: {size / 1024 / 1024:.1f} MB ({size} bytes)") + print(f"image: {image}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_app.py b/tests/test_app.py new file mode 100644 index 0000000..b1728ac --- /dev/null +++ b/tests/test_app.py @@ -0,0 +1,609 @@ +from __future__ import annotations + +import contextlib +import ftplib +import io +import json +import os +import sys +import tempfile +import time +import unittest +from datetime import datetime +from decimal import Decimal +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +from fastapi.testclient import TestClient + +import main +from etl_app import auth, connectors, worker +from etl_app.config import Settings, SettingsError, SettingsStore, public_view, validate +from etl_app.runner import Runner, parse_output +from etl_app.runs import RunStore +from etl_app.scheduler import EtlScheduler +from etl_app.server import build_api +from etl_app.service import EtlService +from test_pipeline import COMPLETE_WINDOW, RecordingStore, create_archive, create_cell_data_sources + + +def complete_settings(**overrides: object) -> dict[str, object]: + values: dict[str, object] = { + "metrix_url": "http://metrix.local:18271", + "metrix_token": "token-1", + "metrix_storage_id": "stg_test", + "metrix_database_id": "db_test", + } + values.update(overrides) + return values + + +class SettingsTest(unittest.TestCase): + def test_defaults_require_credentials(self) -> None: + with self.assertRaises(SettingsError) as context: + validate({}, Settings()) + self.assertEqual((context.exception.key, context.exception.field), ("required", "metrix_token")) + + def test_blank_secret_keeps_saved_value_and_public_view_masks_it(self) -> None: + settings = validate(complete_settings(), Settings()) + updated = validate({"metrix_token": "", "interval_minutes": "5"}, settings) + + self.assertEqual(updated.metrix_token, "token-1") + self.assertEqual(updated.interval_minutes, 5) + view = public_view(updated) + self.assertEqual(view["metrix_token"], "") + self.assertTrue(view["has_metrix_token"]) + self.assertFalse(view["has_mysql_password"]) + + def test_direct_modes_validate_their_own_fields(self) -> None: + base = validate(complete_settings(), Settings()) + with self.assertRaises(SettingsError) as context: + validate({"storage_mode": "sftp"}, base) + self.assertEqual(context.exception.field, "remote_host") + with self.assertRaises(SettingsError) as context: + validate({"database_mode": "mysql", "mysql_host": "db"}, base) + self.assertEqual(context.exception.field, "mysql_username") + + direct = validate( + { + "storage_mode": "ftp", + "remote_host": "ftp.local", + "database_mode": "mysql", + "mysql_host": "db", + "mysql_username": "etl", + "metrix_token": "", + }, + Settings(), + ) + self.assertFalse(direct.uses_metrix_api()) + + def test_rejects_bad_values(self) -> None: + base = validate(complete_settings(), Settings()) + cases = { + "interval_minutes": (0, "range"), + "cron_expression": ("not a cron", "invalidCron"), + "source_root": ("relative/path", "absolutePath"), + "table_name": ("bad-name;", "invalidIdentifier"), + "storage_mode": ("smb", "invalidChoice"), + "metrix_url": ("metrix.local", "invalidUrl"), + } + for field, (value, key) in cases.items(): + data = {field: value} + if field == "cron_expression": + data["schedule_mode"] = "cron" + with self.subTest(field=field), self.assertRaises(SettingsError) as context: + validate(data, base) + self.assertEqual(context.exception.key, key) + + def test_cell_data_directories_accept_lines(self) -> None: + settings = validate(complete_settings(cell_data_directories="/a/\n\n/b\n/a"), Settings()) + self.assertEqual(settings.cell_data_directories, ["/a", "/b"]) + + def test_store_persists_settings(self) -> None: + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / "settings.json" + store = SettingsStore(path) + self.assertFalse(store.configured()) + store.update(complete_settings(schedule_enabled=True)) + + reloaded = SettingsStore(path) + self.assertTrue(reloaded.configured()) + self.assertTrue(reloaded.get().schedule_enabled) + self.assertEqual(json.loads(path.read_text(encoding="utf-8"))["metrix_token"], "token-1") + + +class RunStoreTest(unittest.TestCase): + def test_lifecycle_filters_and_prune(self) -> None: + with tempfile.TemporaryDirectory() as temp: + runs = RunStore(Path(temp) / "runs.db") + first = runs.create("schedule", False) + runs.finish(first, status="processed", target_time="2026-07-31 10:00:00", summary_rows=3) + second = runs.create("manual", True) + runs.finish(second, status="failed", detail="boom") + third = runs.create("schedule", False) + + self.assertEqual(runs.latest_finished()["id"], second) + self.assertEqual(runs.latest_written()["id"], first) + self.assertEqual([row["id"] for row in runs.page(status="problem")[0]], [second]) + self.assertEqual(runs.page(status="processed")[1], 1) + self.assertEqual(runs.counts_since("2000-01-01 00:00:00"), {"processed": 1, "running": 1}) + + self.assertEqual(runs.mark_interrupted(), 1) + self.assertEqual(runs.get(third)["status"], "interrupted") + self.assertEqual(runs.prune(1), [second, first]) + self.assertEqual(runs.page()[1], 1) + + +FAKE_WORKER = """ +import sys, time +mode = open(sys.argv[1], encoding="utf-8").read().strip() +print("dry_run=" + str("--dry-run" in sys.argv)) +if mode == "processed": + print("status=processed") + print("target_time=2026-07-31 10:00:00") + print("summary_rows=42") + print("history_output=/history/2026-07-31/result.csv") +elif mode == "fail": + print("error=storage unavailable", file=sys.stderr) + sys.exit(1) +elif mode == "sleep": + print("sleeping", flush=True) + time.sleep(30) +""" + + +class RunnerTest(unittest.TestCase): + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + root = Path(self.temp.name) + self.mode_file = root / "mode.txt" + script = root / "fake_worker.py" + script.write_text(FAKE_WORKER, encoding="utf-8") + self.settings = SettingsStore(root / "settings.json") + self.settings.update(complete_settings(timeout_minutes=1, keep_outputs=1, keep_runs=50)) + self.runs = RunStore(root / "runs.db") + self.runner = Runner(self.settings, self.runs, root, [sys.executable, str(script), str(self.mode_file)]) + + def tearDown(self) -> None: + self.temp.cleanup() + + def run_mode(self, mode: str) -> dict[str, object]: + self.mode_file.write_text(mode, encoding="utf-8") + run_id = self.runner.run("manual") + assert run_id is not None + row = self.runs.get(run_id) + assert row is not None + return row + + def test_processed_run_records_outcome_and_log(self) -> None: + row = self.run_mode("processed") + + self.assertEqual(row["status"], "processed") + self.assertEqual(row["summary_rows"], 42) + self.assertEqual(row["target_time"], "2026-07-31 10:00:00") + self.assertEqual(row["detail"], "/history/2026-07-31/result.csv") + self.assertIn("status=processed", self.runner.read_log(int(row["id"]))) + + def test_failed_run_keeps_error_detail(self) -> None: + row = self.run_mode("fail") + self.assertEqual((row["status"], row["detail"], row["exit_code"]), ("failed", "storage unavailable", 1)) + + def test_timeout_kills_worker(self) -> None: + self.runner.seconds_per_minute = 0.5 + started = time.monotonic() + row = self.run_mode("sleep") + self.assertEqual(row["status"], "timeout") + self.assertLess(time.monotonic() - started, 20) + + def test_cancel_stops_worker_and_busy_runner_rejects_second_run(self) -> None: + self.mode_file.write_text("sleep", encoding="utf-8") + self.assertTrue(self.runner.start("manual")) + deadline = time.monotonic() + 10 + while self.runner._process is None and time.monotonic() < deadline: + time.sleep(0.05) + self.assertIsNone(self.runner.run("schedule")) + self.assertTrue(self.runner.cancel()) + while self.runner.busy() and time.monotonic() < deadline + 10: + time.sleep(0.05) + self.assertEqual(self.runs.latest_finished()["status"], "cancelled") + + def test_prune_keeps_latest_outputs(self) -> None: + output = Path(self.temp.name) / "output" + for name in ("20260731090000", "20260731100000", ".20260731110000.tmp-1"): + (output / name).mkdir(parents=True) + self.run_mode("processed") + self.assertEqual(sorted(path.name for path in output.iterdir()), ["20260731100000"]) + + def test_parse_output_reads_last_values(self) -> None: + self.assertEqual(parse_output("status=waiting\nnoise line\nstatus=processed\n"), {"status": "processed"}) + + +class SchedulerTest(unittest.TestCase): + def test_apply_switches_triggers(self) -> None: + scheduler = EtlScheduler(mock.Mock()) + scheduler.start(Settings()) + try: + self.assertIsNone(scheduler.next_run_time()) + scheduler.apply(Settings(schedule_enabled=True, interval_minutes=5)) + first = scheduler.next_run_time() + self.assertIsNotNone(first) + scheduler.apply(Settings(schedule_enabled=True, schedule_mode="cron", cron_expression="0 3 * * *")) + cron_next = scheduler.next_run_time() + assert cron_next is not None + self.assertEqual((cron_next.hour, cron_next.minute), (3, 0)) + scheduler.apply(Settings(schedule_enabled=False)) + self.assertIsNone(scheduler.next_run_time()) + finally: + scheduler.shutdown() + + +class AuthTest(unittest.TestCase): + def test_identity_requires_matching_proxy_token(self) -> None: + headers = { + "x-metrix-proxy-token": "secret", + "x-metrix-username": "admin", + "x-metrix-display-name": "%E7%AE%A1%E7%90%86%E5%91%98", + "x-metrix-app-role": "admin", + } + with mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "secret"}, clear=False): + identity = auth.identify(headers) + assert identity is not None + self.assertTrue(identity.is_admin) + self.assertEqual(identity.label, "管理员") + self.assertIsNone(auth.identify({**headers, "x-metrix-proxy-token": "wrong"})) + + def test_dev_identity_only_without_proxy_token(self) -> None: + with mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "", "ETL_DEV_ADMIN": "1"}, clear=False): + self.assertIsNotNone(auth.identify({})) + with mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "secret", "ETL_DEV_ADMIN": "1"}, clear=False): + self.assertIsNone(auth.identify({})) + + +class ApiTest(unittest.TestCase): + def test_admin_api_requires_proxy_identity(self) -> None: + with tempfile.TemporaryDirectory() as temp, mock.patch.dict( + os.environ, {"METRIX_APP_PROXY_TOKEN": "secret"}, clear=False + ): + service = EtlService(Path(temp)) + with TestClient(build_api(service)) as client: + self.assertEqual(client.get("/").status_code, 200) + self.assertEqual(client.get("/api/status").status_code, 401) + member = {"x-metrix-proxy-token": "secret", "x-metrix-app-role": "user"} + self.assertEqual(client.get("/api/status", headers=member).status_code, 403) + + admin = {"x-metrix-proxy-token": "secret", "x-metrix-app-role": "admin"} + self.assertFalse(client.get("/api/status", headers=admin).json()["configured"]) + self.assertEqual(client.post("/api/runs", headers=admin).status_code, 409) + invalid = client.put("/api/settings", headers=admin, json={"interval_minutes": 0}) + self.assertEqual(invalid.status_code, 422) + self.assertEqual(invalid.json()["field"], "interval_minutes") + + saved = client.put("/api/settings", headers=admin, json=complete_settings(schedule_enabled=True)) + self.assertEqual(saved.status_code, 200) + self.assertEqual(saved.json()["metrix_token"], "") + status = client.get("/api/status", headers=admin).json() + self.assertTrue(status["schedule_enabled"]) + self.assertTrue(status["next_run_at"]) + self.assertEqual(client.get("/api/runs", headers=admin).json(), {"items": [], "total": 0}) + self.assertEqual(client.get("/api/runs/1/log", headers=admin).status_code, 404) + + +class FakeFtp: + instances: list[FakeFtp] = [] + + def __init__(self, mlsd_supported: bool = True, fail_first_list: bool = False) -> None: + self.mlsd_supported = mlsd_supported + self.fail_first_list = fail_first_list + self.sock = None + self.commands: list[str] = [] + self.encoding = "" + FakeFtp.instances.append(self) + + def connect(self, host: str, port: int, timeout: int) -> None: + self.commands.append(f"connect {host}:{port}") + + def login(self, username: str, password: str) -> None: + self.commands.append(f"login {username}") + + def set_pasv(self, value: bool) -> None: + self.commands.append(f"pasv {value}") + + def mlsd(self, path: str): + if self.fail_first_list: + self.fail_first_list = False + raise ConnectionResetError("reset") + if not self.mlsd_supported: + raise ftplib.error_perm("500 MLSD not understood") + return iter([(".", {"type": "cdir"}), ("2026-07-31", {"type": "dir"}), ("a.zip", {"type": "file", "size": "12"})]) + + def retrlines(self, command: str, callback) -> None: + self.commands.append(command) + callback("drwxr-xr-x 1 ftp ftp 0 Jul 31 10:00 2026-07-31") + callback("-rw-r--r-- 1 ftp ftp 34 Jul 31 10:00 带 空格.zip") + callback("07-31-26 10:00AM win dir") + + def retrbinary(self, command: str, callback) -> None: + self.commands.append(command) + callback(b"abc") + + def storbinary(self, command: str, handle) -> None: + self.commands.append(f"{command} {handle.read()!r}") + + def mkd(self, path: str) -> str: + self.commands.append(f"MKD {path}") + return path + + def quit(self) -> None: + self.commands.append("quit") + + def close(self) -> None: + pass + + +class FtpStorageTest(unittest.TestCase): + def test_mlsd_listing_and_transfers(self) -> None: + ftp = FakeFtp() + storage = connectors.FtpStorage("ftp.local", 21, "user", "pass", "gbk", factory=lambda: ftp) + + entries = storage.list_dir("/root") + self.assertEqual( + entries, + [ + {"name": "2026-07-31", "path": "/root/2026-07-31", "is_dir": True, "size": 0}, + {"name": "a.zip", "path": "/root/a.zip", "is_dir": False, "size": 12}, + ], + ) + self.assertEqual(storage.read_bytes("/root/a.zip"), b"abc") + storage.make_dir("/root/new") + self.assertEqual(storage.write_bytes("/root/new", "x.csv", b"data"), "/root/new/x.csv") + storage.close() + self.assertEqual(ftp.encoding, "gbk") + self.assertIn("STOR /root/new/x.csv b'data'", ftp.commands) + self.assertEqual(ftp.commands.count("login user"), 1) + + def test_list_falls_back_to_plain_list(self) -> None: + ftp = FakeFtp(mlsd_supported=False) + storage = connectors.FtpStorage("ftp.local", 21, "", "", factory=lambda: ftp) + + entries = storage.list_dir("/root") + + self.assertEqual([(item["name"], item["is_dir"], item["size"]) for item in entries], [ + ("2026-07-31", True, 0), + ("带 空格.zip", False, 34), + ("win dir", True, 0), + ]) + self.assertIn("login anonymous", ftp.commands) + + def test_reconnects_once_after_connection_error(self) -> None: + FakeFtp.instances = [] + first = FakeFtp(fail_first_list=True) + factory = mock.Mock(side_effect=[first, FakeFtp()]) + storage = connectors.FtpStorage("ftp.local", 21, "user", "pass", factory=factory) + + self.assertEqual(len(storage.list_dir("/root")), 2) + self.assertEqual(factory.call_count, 2) + + def test_permission_errors_are_not_retried(self) -> None: + ftp = FakeFtp() + ftp.mkd = mock.Mock(side_effect=ftplib.error_perm("550 denied")) + factory = mock.Mock(return_value=ftp) + storage = connectors.FtpStorage("ftp.local", 21, "user", "pass", factory=factory) + + with self.assertRaisesRegex(main.ProcessingError, "550 denied"): + storage.make_dir("/root/x") + self.assertEqual(factory.call_count, 1) + + +class SftpStorageTest(unittest.TestCase): + def test_operations_use_sftp_client(self) -> None: + sftp = mock.Mock() + sftp.listdir_attr.return_value = [ + SimpleNamespace(filename="2026-07-31", st_mode=0o040755, st_size=0), + SimpleNamespace(filename="a.zip", st_mode=0o100644, st_size=7), + ] + sftp.getfo.side_effect = lambda path, buffer: buffer.write(b"zip") + storage = connectors.SftpStorage("sftp.local", 22, "user", "pass") + storage._sftp = sftp + + self.assertEqual([item["is_dir"] for item in storage.list_dir("/root")], [True, False]) + self.assertEqual(storage.read_bytes("/root/a.zip"), b"zip") + self.assertEqual(storage.write_bytes("/root", "b.csv", b"csv"), "/root/b.csv") + self.assertEqual(sftp.putfo.call_args.args[1], "/root/b.csv") + + def test_missing_file_is_reported(self) -> None: + sftp = mock.Mock() + sftp.getfo.side_effect = FileNotFoundError(2, "No such file") + storage = connectors.SftpStorage("sftp.local", 22, "user", "pass") + storage._sftp = sftp + with self.assertRaisesRegex(main.ProcessingError, "SFTP download /missing failed"): + storage.read_bytes("/missing") + + +class FakeCursor: + def __init__(self, connection: FakeConnection) -> None: + self.connection = connection + self.result: list[tuple[object, ...]] = [] + + def __enter__(self) -> FakeCursor: + return self + + def __exit__(self, *_: object) -> None: + pass + + def execute(self, sql: str, params: tuple[object, ...] | None = None) -> int: + self.connection.log.append((sql.strip(), params)) + if sql.startswith("SELECT MAX"): + self.result = [(self.connection.latest,)] + elif "information_schema" in sql: + self.result = [("metric_time",), ("cgi",)] + elif sql.startswith("SELECT metric_time"): + self.result = [self.connection.stored_row] + else: + self.result = [] + return 4 if sql.startswith("DELETE") else 0 + + def executemany(self, sql: str, params: list[tuple[object, ...]]) -> int: + self.connection.log.append((sql.strip(), tuple(params))) + return len(params) + + def fetchone(self) -> tuple[object, ...] | None: + return self.result[0] if self.result else None + + def fetchall(self) -> list[tuple[object, ...]]: + return self.result + + +class FakeConnection: + def __init__(self, shared: dict[str, object]) -> None: + self.shared = shared + self.log: list[tuple[str, object]] = shared["log"] # type: ignore[assignment] + self.latest = shared.get("latest") + self.stored_row = shared.get("stored_row") + + def cursor(self) -> FakeCursor: + return FakeCursor(self) + + def commit(self) -> None: + self.log.append(("COMMIT", None)) + + def rollback(self) -> None: + self.log.append(("ROLLBACK", None)) + + def close(self) -> None: + pass + + +class MySqlStoreTest(unittest.TestCase): + def make_store(self, **shared: object) -> tuple[connectors.MySqlSummaryStore, list[tuple[str, object]]]: + log: list[tuple[str, object]] = [] + state = {"log": log, **shared} + store = connectors.MySqlSummaryStore( + "db", 3306, "etl", "pw", connect=lambda **kwargs: FakeConnection(state) + ) + return store, log + + def test_replace_latest_runs_one_transaction(self) -> None: + store, log = self.make_store(latest=datetime(2026, 7, 31, 9, 0)) + row = {column: "" for column in main.SUMMARY_HEADER} + row.update({ + "metric_time": "2026-07-31 10:00:00", + "network_type": "2.6G", + "cgi": "460-00-1-1", + "cell_name": "小区", + "interference_dbm": "-100.5", + "azimuth": "0", + "nearby_count": "1", + "nearby_26g": "1", + "nearby_700m": "0", + "nearby_tdd": "0", + "nearby_fdd": "0", + }) + + result = store.replace_latest([row]) + + statements = [sql for sql, _ in log] + self.assertIn(main.create_database_sql("interference_etl"), statements) + self.assertTrue(any("ADD COLUMN `network_type`" in sql for sql in statements)) + insert = next(params for sql, params in log if sql.startswith("INSERT INTO")) + self.assertEqual(insert[0][4], Decimal("-100.5")) + self.assertIsNone(insert[0][5]) + tail = statements[statements.index("DELETE FROM `interference_hourly_summary` WHERE metric_time = %s"):] + self.assertEqual(tail[-1], "COMMIT") + self.assertEqual(result["inserted_rows"], 1) + self.assertEqual(result["old_rows_deleted"], 4) + + def test_refuses_to_replace_newer_data(self) -> None: + store, log = self.make_store(latest=datetime(2026, 7, 31, 11, 0)) + row = {column: "0" for column in main.SUMMARY_HEADER} + row["metric_time"] = "2026-07-31 10:00:00" + with self.assertRaisesRegex(main.ProcessingError, "newer metric time"): + store.replace_latest([row]) + self.assertFalse(any(sql.startswith("INSERT") for sql, _ in log)) + + def test_rows_for_time_normalizes_decimals(self) -> None: + stored = ( + datetime(2026, 7, 31, 10, 0), "2.6G", "460-00-1-1", "小区", Decimal("-100.500"), None, + Decimal("113.123456"), Decimal("22.654321"), Decimal("30.00"), 1, 1, 0, 0, 0, None, None, None, None, None, + ) + store, _ = self.make_store(stored_row=stored) + + rows = store.rows_for_time(datetime(2026, 7, 31, 10, 0)) + + self.assertEqual(rows[0]["metric_time"], "2026-07-31 10:00:00") + self.assertEqual(rows[0]["interference_dbm"], "-100.5") + self.assertEqual(rows[0]["azimuth"], "30") + self.assertEqual(rows[0]["prev_interference_dbm"], "") + + +class LocalFileStorage: + def __init__(self, root: Path) -> None: + self.root = root + + def _path(self, path: str) -> Path: + return self.root / path.lstrip("/") + + def list_dir(self, path: str) -> list[dict[str, object]]: + return [ + {"name": item.name, "path": f"{path.rstrip('/')}/{item.name}", "is_dir": item.is_dir(), "size": item.stat().st_size} + for item in sorted(self._path(path).iterdir()) + ] + + def read_bytes(self, path: str) -> bytes: + return self._path(path).read_bytes() + + def make_dir(self, path: str) -> None: + self._path(path).mkdir(parents=True) + + def write_bytes(self, directory: str, filename: str, payload: bytes) -> str: + (self._path(directory) / filename).write_bytes(payload) + return f"{directory}/{filename}" + + +class WorkerTest(unittest.TestCase): + def test_worker_processes_with_configured_storage_and_store(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "remote" + create_archive_tree = root / "source" + for source_type in main.EXPECTED_TYPES: + create_archive(create_archive_tree, source_type, COMPLETE_WINDOW) + create_cell_data_sources(root) + (root / "history").mkdir() + settings_path = Path(temp) / "settings.json" + SettingsStore(settings_path).update( + complete_settings(source_root="/source", history_root="/history", lookback_days=3) + ) + store = RecordingStore() + output = io.StringIO() + with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object( + worker, "build_store", return_value=store + ), contextlib.redirect_stdout(output): + self.assertEqual(worker.run(settings_path, Path(temp) / "output", dry_run=False), 0) + + self.assertIn("status=processed", output.getvalue()) + self.assertEqual(len(store.rows), 2) + archived = list((root / "history" / "2026-07-31").iterdir()) + self.assertEqual(len(archived), 1) + + def test_dry_run_skips_database_and_history(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "remote" + for source_type in main.EXPECTED_TYPES: + create_archive(root / "source", source_type, COMPLETE_WINDOW) + create_cell_data_sources(root) + settings_path = Path(temp) / "settings.json" + SettingsStore(settings_path).update(complete_settings(source_root="/source", history_root="/history")) + build_store = mock.Mock() + output = io.StringIO() + with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object( + worker, "build_store", build_store + ), contextlib.redirect_stdout(output): + worker.run(settings_path, Path(temp) / "output", dry_run=True) + + build_store.assert_not_called() + self.assertIn("database_mode=none", output.getvalue()) + self.assertFalse((root / "history").exists()) + + +if __name__ == "__main__": + unittest.main()