Compare commits
1
Commits
main
..
2eda0a0887
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2eda0a0887 |
+2
-4
@@ -1,5 +1,3 @@
|
||||
*
|
||||
!requirements-app.txt
|
||||
!main.py
|
||||
!etl_app/
|
||||
etl_app/**/__pycache__
|
||||
!Dockerfile
|
||||
!requirements.txt
|
||||
|
||||
@@ -7,4 +7,3 @@ runtime_config.py
|
||||
output/
|
||||
dist/
|
||||
aidocs/
|
||||
Temp/
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
FROM python:3.13.11-slim
|
||||
|
||||
COPY requirements.txt /tmp/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /tmp/requirements.txt
|
||||
|
||||
WORKDIR /workspace
|
||||
|
||||
CMD ["python", "main.py"]
|
||||
@@ -1,10 +1,10 @@
|
||||
# InterferenceETL
|
||||
|
||||
InterferenceETL follows the newest interference KPI time group in the configured file source. It reads seven ZIP/XLSX source types, converts each `Sheet0` to CSV, and creates one merged high-interference summary. It runs as a hosted app in Metrix App Hosting with an admin page at `/admin`.
|
||||
InterferenceETL follows the newest interference KPI time group in Metrix storage. It reads seven ZIP/XLSX source types, converts each `Sheet0` to CSV, and creates one merged high-interference summary.
|
||||
|
||||
Source file names are identified by one of the seven fixed prefixes plus a final `_YYYYMMDDHHMMHHMM.zip`; text between the prefix and time is unrestricted. Only the first `YYYYMMDDHHMM` start time is used for grouping. Start times are rounded down to natural 15-minute boundaries, so `12:00` through `12:14` belong to `12:00`. This also works unchanged when all providers switch together to hourly or daily delivery.
|
||||
|
||||
Every run follows only the group containing the newest source start time. It never falls back or backfills an older group. If any source type is missing, the run reports `status=waiting` with the missing types and ends successfully. When one source has multiple files in the group, its latest start time wins.
|
||||
Every run follows only the group containing the newest source start time. It never falls back or backfills an older group. If any source type is missing, the script prints `status=waiting` with the missing types and exits successfully. When one source has multiple files in the group, its latest start time wins.
|
||||
|
||||
## Output
|
||||
|
||||
@@ -20,9 +20,7 @@ output/20260731100000/
|
||||
└── manifest.json
|
||||
```
|
||||
|
||||
For every processed group, the run also reads the latest filename-dated XLSX from each configured CellData directory. It builds CellData CGI as `460-00-{eNB/gNB}-{CI}` and adds coordinates plus direction angle to matching interference rows. Unmatched rows keep empty coordinates and use `0` for azimuth.
|
||||
|
||||
In each CellData directory, only XLSX files ending with a valid `YYYYMMDD.xlsx` date are considered, and the latest date is selected. CellData column `方向角` maps to summary/database column `azimuth`; an empty source value becomes `0`. Parsing these workbooks is the slow part of a run, so the parsed result of each workbook is kept in `/data/cache/cell-data/`, named after the SHA-256 of the workbook bytes. A workbook is parsed again whenever its content changes; entries that the latest run did not use are removed.
|
||||
For every processed group, the script also reads the latest filename-dated XLSX from each configured CellData directory. It builds CellData CGI as `460-00-{eNB/gNB}-{CI}` and adds coordinates plus direction angle to matching interference rows. Unmatched rows keep empty coordinates and use `0` for azimuth.
|
||||
|
||||
The summary columns are:
|
||||
|
||||
@@ -42,67 +40,84 @@ When multiple retained source rows have the same CGI, the summary keeps the row
|
||||
|
||||
`prev_interference_dbm`, `prev_nearby_count`, and the four `prev_nearby_26g/700m/tdd/fdd` fields come from the previously retained database time, matched by CGI before the current batch replaces old rows. They represent the same cell's previous-period interference value and nearby high-interference counts. On the first run, or when a CGI did not exist in the previous period, these fields are empty in CSV/history output and `NULL` in MySQL.
|
||||
|
||||
A run never modifies or deletes source ZIP or CellData files. Before downloading source ZIP files or CellData, it compares the normalized target time with the database. A target already present, or older than the database, is not processed again.
|
||||
The script never modifies or deletes source storage files. Before downloading source ZIP files or CellData, it compares the normalized target time with the database. A target already present, or older than the database, is not processed again.
|
||||
|
||||
The database table contains normalized `metric_time DATETIME`, `network_type VARCHAR(16)`, `interference_dbm DECIMAL(10,3)`, nullable `prev_interference_dbm DECIMAL(10,3)`, nullable `longitude` and `latitude`, `azimuth DECIMAL(6,2) NOT NULL DEFAULT 0`, the five `NOT NULL DEFAULT 0` INT count columns (`nearby_count`, `nearby_26g`, `nearby_700m`, `nearby_tdd`, `nearby_fdd`), and the five nullable INT previous-period count columns (`prev_nearby_count`, `prev_nearby_26g`, `prev_nearby_700m`, `prev_nearby_tdd`, `prev_nearby_fdd`). A successful transaction replaces the target batch and deletes every other database time, so the table retains only the latest processed group. The previous-period values are read before this replacement transaction. The database and table are created automatically when they do not exist.
|
||||
The database table contains normalized `metric_time DATETIME`, `network_type VARCHAR(16)`, `interference_dbm DECIMAL(10,3)`, nullable `prev_interference_dbm DECIMAL(10,3)`, nullable `longitude` and `latitude`, `azimuth DECIMAL(6,2) NOT NULL DEFAULT 0`, the five `NOT NULL DEFAULT 0` INT count columns (`nearby_count`, `nearby_26g`, `nearby_700m`, `nearby_tdd`, `nearby_fdd`), and the five nullable INT previous-period count columns (`prev_nearby_count`, `prev_nearby_26g`, `prev_nearby_700m`, `prev_nearby_tdd`, `prev_nearby_fdd`). A successful transaction replaces the target batch and deletes every other database time, so the table retains only the latest processed group. The previous-period values are read before this replacement transaction.
|
||||
|
||||
After the database succeeds, the same nineteen result columns are uploaded as GBK CSV to the history directory:
|
||||
After the database succeeds, the same nineteen result columns are uploaded as GBK CSV to:
|
||||
|
||||
```text
|
||||
/网优日常优化数据文档/(勿删)干扰定时小时指标/干扰历史数据/YYYY-MM-DD/干扰数据处理结果_YYYYMMDDHHMMSS.csv
|
||||
```
|
||||
|
||||
The filename time comes from normalized `metric_time`, never the server clock. If the database already contains the target time but its history CSV is missing or empty, the run exports that time from the database and repairs the history file without reprocessing source data.
|
||||
The filename time comes from normalized `metric_time`, never the server clock. If the database already contains the target time but its history CSV is missing or empty, the script exports that time from the database and repairs the history file without reprocessing source data.
|
||||
|
||||
History retention reads the directory and file names, not file modification times. It keeps the latest 7 calendar days by default and deletes older date directories and result files from the file source. It runs after a new group has been stored; a failure there is written to the run log and does not fail the run. Set the retention days to 0 to keep everything.
|
||||
|
||||
Only the history CSV uses GBK without a UTF-8 BOM. Source non-breaking spaces (`U+00A0`) are normalized to ordinary spaces in this history file because GBK cannot encode them; other unsupported characters still fail visibly. The seven local converted CSV files and local merged summary remain UTF-8 with BOM, and `manifest.json` remains UTF-8 JSON.
|
||||
Only the final history CSV uploaded to Metrix Storage uses GBK without a UTF-8 BOM. Source non-breaking spaces (`U+00A0`) are normalized to ordinary spaces in this history file because GBK cannot encode them; other unsupported characters still fail visibly. The seven local converted CSV files and local merged summary remain UTF-8 with BOM, and `manifest.json` remains UTF-8 JSON.
|
||||
|
||||
CGI is generated with fixed rules:
|
||||
|
||||
- NR (`5G干扰监控`, `700M干扰监控`): `{gNBplmn}-{gNBId}-{cellId}`.
|
||||
- 4G (the other five source types): `460-00-{eNodeBID}-{小区ID}`, using each source schema's actual equivalent column names.
|
||||
|
||||
## Metrix hosted app
|
||||
The Metrix API address, API Token, and database connection ID are constants in `runtime_config.py`; they are not project environment variables. Copy `runtime_config.example.py` to `runtime_config.py` and fill in the actual Token and the `conn_id` of `ShareMySQL`. The fixed database is `interference_etl`, the fixed table is `interference_hourly_summary`, and the script creates both automatically when they do not exist.
|
||||
|
||||
InterferenceETL runs as one long-lived container in Metrix App Hosting. A FastAPI + NiceGUI admin page at `/admin` (Metrix account, app admin role only) edits every setting, shows the live log, keeps the run history and browses the summary table with server-side paging (`GET /api/data?page=&page_size=20|50|100&network=&q=&sort=`). The app has no user page: its manifest declares `user_auth: none`, so the hosting list shows only the admin entry and Metrix admits app admins only on every path.
|
||||
|
||||
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), parsed CellData in `/data/cache/cell-data/`.
|
||||
|
||||
The page content is sent over a live connection (WebSocket, with HTTP long-polling as the fallback). While that connection is being set up the page shows a connecting notice. If it stays there, something between the browser and Metrix is blocking the connection, for example a capture proxy set as the system proxy.
|
||||
|
||||
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-<version>.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.
|
||||
The five CellData directories are fixed in `CELL_DATA_DIRECTORIES`. In each directory, only XLSX files ending with a valid `YYYYMMDD.xlsx` date are considered, and the latest date is selected. CellData column `方向角` maps to summary/database column `azimuth`; an empty source value becomes `0`.
|
||||
|
||||
## Local development
|
||||
|
||||
```powershell
|
||||
python -m pip install -r requirements-app.txt
|
||||
python -m pip install -r requirements.txt
|
||||
python -m unittest discover -s tests -v
|
||||
$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.
|
||||
|
||||
To process a local copy of the source tree into CSV files without a database:
|
||||
|
||||
```powershell
|
||||
python main.py --source-dir C:\path\to\exported-tree --output-dir output
|
||||
python main.py --source-dir C:\path\to\mock-or-exported-tree --output-dir output --no-database
|
||||
```
|
||||
|
||||
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 Script Management
|
||||
|
||||
The target server is offline. Build the dependency image locally, then generate a self-contained Script Management upload ZIP:
|
||||
|
||||
```powershell
|
||||
docker build -t interference-etl-runtime:1.1 .
|
||||
python scripts\build_offline_package.py
|
||||
```
|
||||
|
||||
The generated `dist/InterferenceETL-offline-1.1.zip` contains `main.py`, `runtime_config.py`, a ZIP execution entry point, and a `vendor/` directory containing `openpyxl` and `et_xmlfile`. The builder verifies imports and ZIP execution using the standard `python:3.13.11-slim` image, so the uploaded workspace does not need an online `pip install` or a custom runtime image. The build fails when `runtime_config.py` is missing.
|
||||
|
||||
Create the project, then upload and extract the ZIP in its Script Management workspace. The normal file tree should contain `main.py` at `/workspace/main.py`. Use these project settings:
|
||||
|
||||
```text
|
||||
Name: InterferenceETL
|
||||
Language: python
|
||||
Base image: python:3.13.11-slim
|
||||
Network: bridge
|
||||
Run command: python main.py
|
||||
Timeout: 1800 seconds
|
||||
```
|
||||
|
||||
If the server keeps the ZIP as one file instead of extracting it, use `python InterferenceETL-offline-1.1.zip` as the run command. The ZIP contains `__main__.py` for this mode.
|
||||
|
||||
Configure only run-specific source and output settings in the project environment:
|
||||
|
||||
```json
|
||||
{
|
||||
"METRIX_STORAGE_ID": "stg_4d9a910d72",
|
||||
"INTERFERENCE_SOURCE_ROOT": "/网优日常优化数据文档/(勿删)干扰定时小时指标",
|
||||
"INTERFERENCE_OUTPUT_DIR": "/workspace/output",
|
||||
"INTERFERENCE_LOOKBACK_DAYS": "3"
|
||||
}
|
||||
```
|
||||
|
||||
Both storage reads and database writes use the Metrix API at `http://188.5.127.115:18271`. SSH remains the deployment and operational channel for uploading files, starting runs, and reading logs.
|
||||
|
||||
## CLI options
|
||||
|
||||
```text
|
||||
--source-dir PATH Read a local directory tree instead of Metrix API
|
||||
--output-dir PATH Output root, default output or INTERFERENCE_OUTPUT_DIR
|
||||
--window WINDOW Select the natural 15-minute group for a 16-digit source window
|
||||
--lookback-days N Number of newest date directories scanned, default 3
|
||||
--storage-id ID Metrix storage connection ID
|
||||
--root PATH Source directory in Metrix storage
|
||||
--no-database Generate CSV files without writing the database
|
||||
```
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
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"]
|
||||
@@ -0,0 +1,26 @@
|
||||
# Assumptions and pending decisions
|
||||
|
||||
## Implemented assumptions
|
||||
|
||||
- The source directory contains seven expected source types for each complete hour.
|
||||
- The newest usable hour is the newest 16-digit filename window for which all seven types exist. A newer incomplete hour is logged and skipped.
|
||||
- Each ZIP contains exactly one XLSX member. The member is selected by extension because the two 700M ZIP series use a legacy filename encoding.
|
||||
- Only `Sheet0` is converted and merged. The `指标(计数器)` sheet is metadata and is not included in the summary.
|
||||
- NR CGI is derived as `{gNBplmn}-{gNBId}-{cellId}`.
|
||||
- 4G CGI is derived as `460-00-{eNodeBID}-{小区ID}`, using the equivalent node and cell column names in each source schema.
|
||||
- Only history CSV files uploaded to Metrix Storage use GBK without a UTF-8 BOM. Local converted and summary CSV files remain UTF-8 with BOM; `manifest.json` remains UTF-8 JSON.
|
||||
- Source files are read-only. The script writes only below its configured output directory.
|
||||
- MySQL is the scheduled-run output. The table uses one `metric_time DATETIME` column containing the source KPI start time.
|
||||
- A successful run transactionally refreshes the selected hour and deletes rows for all other hours. A selected hour older than the newest database hour is rejected to prevent data rollback.
|
||||
|
||||
## Pending user decisions
|
||||
|
||||
- Whether the seven converted full CSV files must be retained after successful database import.
|
||||
- Whether the `指标(计数器)` metadata sheet must also be stored.
|
||||
- Schedule minute and expected source-file arrival delay. A safe initial suggestion is hourly at minute 20.
|
||||
- Historical backfill range and retention policy for generated CSV files.
|
||||
- Whether an incomplete newest hour should only warn, fail the run, or wait and retry.
|
||||
|
||||
## Mock boundary
|
||||
|
||||
Automated tests generate seven in-memory XLSX/ZIP sources plus a newer incomplete hour. The mock verifies both CGI rules, complete-hour fallback, schema validation, CSV conversion, summary merging, cross-midnight windows, transactional latest-hour replacement, and database rollback protection.
|
||||
@@ -1 +0,0 @@
|
||||
__version__ = "1.0.3"
|
||||
@@ -1,51 +0,0 @@
|
||||
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
|
||||
@@ -1,256 +0,0 @@
|
||||
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
|
||||
|
||||
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
|
||||
history_keep_days: int = 7
|
||||
|
||||
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),
|
||||
"history_keep_days": _int(merged, "history_keep_days", 0, 3650),
|
||||
}
|
||||
settings = Settings(**values)
|
||||
if settings.schedule_mode == "cron":
|
||||
# Imported here so the worker process, which only reads saved settings, does not load the scheduler.
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
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
|
||||
@@ -1,490 +0,0 @@
|
||||
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 delete(self, path: str) -> None:
|
||||
self._call("delete", path, lambda ftp: self._remove(ftp, 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 _remove(self, ftp: ftplib.FTP, path: str) -> None:
|
||||
children = self._children(ftp, path)
|
||||
if children is None:
|
||||
ftp.delete(path)
|
||||
return
|
||||
for name, is_dir in children:
|
||||
child = posixpath.join(path, name)
|
||||
if is_dir:
|
||||
self._remove(ftp, child)
|
||||
else:
|
||||
ftp.delete(child)
|
||||
ftp.rmd(path)
|
||||
|
||||
@staticmethod
|
||||
def _children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
|
||||
try:
|
||||
listed = list(ftp.mlsd(path))
|
||||
except ftplib.error_perm as exc:
|
||||
if str(exc).startswith(FTP_UNSUPPORTED_COMMAND_CODES):
|
||||
return FtpStorage._nlst_children(ftp, path)
|
||||
return None
|
||||
result: list[tuple[str, bool]] = []
|
||||
for name, facts in listed:
|
||||
if name in {".", ".."}:
|
||||
continue
|
||||
result.append((name, facts.get("type") == "dir"))
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def _nlst_children(ftp: ftplib.FTP, path: str) -> list[tuple[str, bool]] | None:
|
||||
try:
|
||||
names = ftp.nlst(path)
|
||||
except ftplib.error_perm:
|
||||
return None
|
||||
children: list[tuple[str, bool]] = []
|
||||
for name in names:
|
||||
base = posixpath.basename(name.rstrip("/"))
|
||||
if base in {"", ".", ".."}:
|
||||
continue
|
||||
child = name if name.startswith("/") else posixpath.join(path, base)
|
||||
try:
|
||||
ftp.cwd(child)
|
||||
ftp.cwd(path)
|
||||
children.append((base, True))
|
||||
except ftplib.error_perm:
|
||||
children.append((base, False))
|
||||
return children
|
||||
|
||||
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 delete(self, path: str) -> None:
|
||||
self._call("delete", path, lambda sftp: self._remove(sftp, 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 _remove(self, sftp: paramiko.SFTPClient, path: str) -> None:
|
||||
try:
|
||||
attrs = sftp.stat(path)
|
||||
except FileNotFoundError:
|
||||
return
|
||||
if stat.S_ISDIR(attrs.st_mode or 0):
|
||||
for item in sftp.listdir_attr(path):
|
||||
self._remove(sftp, posixpath.join(path, item.filename))
|
||||
sftp.rmdir(path)
|
||||
return
|
||||
sftp.remove(path)
|
||||
|
||||
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 select(self, sql: str, limit: int) -> list[dict[str, object]]:
|
||||
try:
|
||||
with self._connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql)
|
||||
names = [column[0] for column in cursor.description or ()]
|
||||
records = cursor.fetchmany(max(1, limit))
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL query failed: {exc}") from exc
|
||||
return [dict(zip(names, record, strict=True)) for record in records]
|
||||
|
||||
def _connection(self) -> Any:
|
||||
if not self._schema_ready:
|
||||
self._ensure_schema()
|
||||
return _Closing(self._open(database=self.database))
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
connection = self._open(database=None)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(main.create_database_sql(self.database))
|
||||
cursor.execute(f"USE `{self.database}`")
|
||||
cursor.execute(main.create_table_sql(self.table))
|
||||
cursor.execute(
|
||||
"SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
|
||||
(self.database, self.table),
|
||||
)
|
||||
existing = {str(row[0]) for row in cursor.fetchall()}
|
||||
for statement in main.column_migration_sql(self.table, existing):
|
||||
cursor.execute(statement)
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL schema check failed: {exc}") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
self._schema_ready = True
|
||||
|
||||
def _open(self, database: str | None) -> Any:
|
||||
try:
|
||||
return self._connect(
|
||||
host=self.host,
|
||||
port=self.port,
|
||||
user=self.username,
|
||||
password=self.password,
|
||||
database=database,
|
||||
charset="utf8mb4",
|
||||
autocommit=False,
|
||||
connect_timeout=CONNECT_TIMEOUT_SECONDS,
|
||||
read_timeout=TRANSFER_TIMEOUT_SECONDS,
|
||||
write_timeout=TRANSFER_TIMEOUT_SECONDS,
|
||||
)
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL connection failed: {exc}") from exc
|
||||
|
||||
|
||||
class _Closing:
|
||||
def __init__(self, connection: Any) -> None:
|
||||
self.connection = connection
|
||||
|
||||
def __enter__(self) -> Any:
|
||||
return self.connection
|
||||
|
||||
def __exit__(self, *exc_info: object) -> None:
|
||||
self.connection.close()
|
||||
|
||||
|
||||
def mysql_cell(value: object) -> str:
|
||||
if isinstance(value, Decimal):
|
||||
text = format(value, "f")
|
||||
return text.rstrip("0").rstrip(".") if "." in text else text
|
||||
return main.normalize_cell(value)
|
||||
|
||||
|
||||
def build_storage(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
||||
if settings.storage_mode == "metrix":
|
||||
assert client is not None
|
||||
return main.MetrixStorage(client, settings.metrix_storage_id)
|
||||
if settings.storage_mode == "sftp":
|
||||
return SftpStorage(settings.remote_host, settings.remote_port, settings.remote_username, settings.remote_password)
|
||||
return FtpStorage(
|
||||
settings.remote_host,
|
||||
settings.remote_port,
|
||||
settings.remote_username,
|
||||
settings.remote_password,
|
||||
settings.ftp_encoding,
|
||||
settings.ftp_passive,
|
||||
)
|
||||
|
||||
|
||||
def build_store(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
||||
if settings.database_mode == "metrix":
|
||||
assert client is not None
|
||||
return main.ApiSummaryStore(client, settings.metrix_database_id, settings.database_name, settings.table_name)
|
||||
return MySqlSummaryStore(
|
||||
settings.mysql_host,
|
||||
settings.mysql_port,
|
||||
settings.mysql_username,
|
||||
settings.mysql_password,
|
||||
settings.database_name,
|
||||
settings.table_name,
|
||||
)
|
||||
|
||||
|
||||
def build_client(settings: Settings) -> main.MetrixApiClient | None:
|
||||
if not settings.uses_metrix_api():
|
||||
return None
|
||||
return main.MetrixApiClient(settings.metrix_url, settings.metrix_token)
|
||||
|
||||
|
||||
def close_quietly(resource: object) -> None:
|
||||
close = getattr(resource, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
|
||||
|
||||
def check_storage(settings: Settings) -> dict[str, object]:
|
||||
storage = build_storage(settings, build_client(settings))
|
||||
try:
|
||||
source = main.StorageSource(storage, settings.source_root, settings.cell_data_directories)
|
||||
dates = source.date_directories()
|
||||
return {"count": len(dates), "latest": str(dates[-1]["name"]) if dates else "-"}
|
||||
finally:
|
||||
close_quietly(storage)
|
||||
|
||||
|
||||
def check_database(settings: Settings) -> dict[str, object]:
|
||||
store = build_store(settings, build_client(settings))
|
||||
latest = store.latest_metric_time()
|
||||
return {"latest": latest.strftime("%Y-%m-%d %H:%M:%S") if latest else "-"}
|
||||
|
||||
|
||||
def parse_list_line(line: str) -> tuple[str, bool, int] | None:
|
||||
text = line.rstrip()
|
||||
if not text or text.startswith("total "):
|
||||
return None
|
||||
if text[0] in "dl-" and len(text) >= 10:
|
||||
parts = text.split(maxsplit=8)
|
||||
if len(parts) < 9:
|
||||
return None
|
||||
name = parts[8]
|
||||
if text[0] == "l" and " -> " in name:
|
||||
name = name.split(" -> ", 1)[0]
|
||||
if name in (".", ".."):
|
||||
return None
|
||||
return name, text[0] == "d", _safe_int(parts[4])
|
||||
parts = text.split(maxsplit=3)
|
||||
if len(parts) == 4 and parts[0].count("-") == 2:
|
||||
is_dir = parts[2] == "<DIR>"
|
||||
return parts[3], is_dir, 0 if is_dir else _safe_int(parts[2])
|
||||
return None
|
||||
|
||||
|
||||
def _safe_int(value: str) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return 0
|
||||
-148
@@ -1,148 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
from dataclasses import dataclass, replace
|
||||
from datetime import datetime
|
||||
from decimal import Decimal, InvalidOperation
|
||||
from typing import Any
|
||||
|
||||
import main
|
||||
|
||||
from .config import Settings, SettingsStore
|
||||
from .connectors import build_client, build_store
|
||||
|
||||
NETWORK_TYPES = ("2.6G", "700M", "TDD", "FDD")
|
||||
PAGE_SIZES = (20, 50, 100)
|
||||
SORT_ORDERS = {
|
||||
"interference": "interference_dbm DESC, cgi",
|
||||
"rise": "(prev_interference_dbm IS NULL), (interference_dbm - prev_interference_dbm) DESC, interference_dbm DESC, cgi",
|
||||
"nearby": "nearby_count DESC, interference_dbm DESC, cgi",
|
||||
"cgi": "cgi, cell_name",
|
||||
}
|
||||
KEYWORD_LIMIT = 64
|
||||
CONTROL_RE = re.compile(r"[\x00-\x1f\x7f]")
|
||||
DECIMAL_RE = re.compile(r"-?\d+\.\d+")
|
||||
STORE_FIELDS = (
|
||||
"database_mode",
|
||||
"metrix_url",
|
||||
"metrix_token",
|
||||
"metrix_database_id",
|
||||
"mysql_host",
|
||||
"mysql_port",
|
||||
"mysql_username",
|
||||
"mysql_password",
|
||||
"database_name",
|
||||
"table_name",
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DataQuery:
|
||||
page: int = 1
|
||||
page_size: int = PAGE_SIZES[0]
|
||||
network: str = ""
|
||||
keyword: str = ""
|
||||
sort: str = "interference"
|
||||
|
||||
def normalized(self) -> DataQuery:
|
||||
return DataQuery(
|
||||
page=max(1, int(self.page or 1)),
|
||||
page_size=self.page_size if self.page_size in PAGE_SIZES else PAGE_SIZES[0],
|
||||
network=self.network if self.network in NETWORK_TYPES else "",
|
||||
keyword=CONTROL_RE.sub("", str(self.keyword or "")).strip()[:KEYWORD_LIMIT],
|
||||
sort=self.sort if self.sort in SORT_ORDERS else "interference",
|
||||
)
|
||||
|
||||
|
||||
def text_literal(value: str) -> str:
|
||||
return "'" + value.replace("\\", "\\\\").replace("'", "''") + "'"
|
||||
|
||||
|
||||
def where_clause(query: DataQuery) -> str:
|
||||
conditions: list[str] = []
|
||||
if query.network:
|
||||
conditions.append(f"network_type = {text_literal(query.network)}")
|
||||
if query.keyword:
|
||||
escaped = query.keyword.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
pattern = text_literal(f"%{escaped}%")
|
||||
conditions.append(f"(cgi LIKE {pattern} OR cell_name LIKE {pattern})")
|
||||
return f" WHERE {' AND '.join(conditions)}" if conditions else ""
|
||||
|
||||
|
||||
def cell(value: object) -> str:
|
||||
if value is None:
|
||||
return ""
|
||||
if isinstance(value, datetime):
|
||||
return value.strftime("%Y-%m-%d %H:%M:%S")
|
||||
if isinstance(value, (Decimal, float)):
|
||||
text = format(Decimal(str(value)), "f")
|
||||
return text.rstrip("0").rstrip(".") if "." in text else text
|
||||
text = str(value)
|
||||
if DECIMAL_RE.fullmatch(text):
|
||||
return text.rstrip("0").rstrip(".")
|
||||
if re.fullmatch(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.*", text):
|
||||
return text[:19].replace("T", " ")
|
||||
return text
|
||||
|
||||
|
||||
def difference(current: str, previous: str) -> str:
|
||||
try:
|
||||
delta = Decimal(current) - Decimal(previous)
|
||||
except (InvalidOperation, ValueError):
|
||||
return ""
|
||||
text = cell(delta)
|
||||
return f"+{text}" if delta > 0 else text
|
||||
|
||||
|
||||
class DataBrowser:
|
||||
def __init__(self, settings: SettingsStore) -> None:
|
||||
self.settings = settings
|
||||
self._lock = threading.Lock()
|
||||
self._key: tuple[Any, ...] | None = None
|
||||
self._store: Any = None
|
||||
|
||||
def browse(self, query: DataQuery) -> dict[str, Any]:
|
||||
query = query.normalized()
|
||||
store = self._store_for(self.settings.get())
|
||||
table = f"`{store.table}`"
|
||||
groups = store.select(
|
||||
f"SELECT network_type, COUNT(*) AS row_count, MAX(metric_time) AS latest FROM {table} GROUP BY network_type",
|
||||
len(NETWORK_TYPES) + 8,
|
||||
)
|
||||
networks = {cell(row.get("network_type")): int(row.get("row_count") or 0) for row in groups}
|
||||
metric_time = max((cell(row.get("latest")) for row in groups), default="")
|
||||
where = where_clause(query)
|
||||
if where:
|
||||
counted = store.select(f"SELECT COUNT(*) AS row_count FROM {table}{where}", 1)
|
||||
total = int(counted[0].get("row_count") or 0) if counted else 0
|
||||
else:
|
||||
total = sum(networks.values())
|
||||
pages = max(1, -(-total // query.page_size))
|
||||
query = replace(query, page=min(query.page, pages))
|
||||
items: list[dict[str, str]] = []
|
||||
if total:
|
||||
offset = (query.page - 1) * query.page_size
|
||||
records = store.select(
|
||||
f"SELECT {', '.join(main.SUMMARY_HEADER)} FROM {table}{where} "
|
||||
f"ORDER BY {SORT_ORDERS[query.sort]} LIMIT {query.page_size} OFFSET {offset}",
|
||||
query.page_size,
|
||||
)
|
||||
items = [{column: cell(record.get(column)) for column in main.SUMMARY_HEADER} for record in records]
|
||||
return {
|
||||
"items": items,
|
||||
"total": total,
|
||||
"page": query.page,
|
||||
"page_size": query.page_size,
|
||||
"pages": pages,
|
||||
"networks": networks,
|
||||
"metric_time": metric_time,
|
||||
}
|
||||
|
||||
def _store_for(self, settings: Settings) -> Any:
|
||||
key = tuple(getattr(settings, name) for name in STORE_FIELDS)
|
||||
with self._lock:
|
||||
if key != self._key:
|
||||
self._store = build_store(settings, build_client(settings))
|
||||
self._key = key
|
||||
return self._store
|
||||
-376
@@ -1,376 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
MESSAGES: dict[str, dict[str, str]] = {
|
||||
"zh": {
|
||||
"app.title": "干扰数据处理",
|
||||
"tab.overview": "概览",
|
||||
"tab.runs": "运行记录",
|
||||
"tab.data": "数据",
|
||||
"tab.settings": "设置",
|
||||
"header.scheduleOn": "定时运行中",
|
||||
"header.scheduleOff": "定时已暂停",
|
||||
"header.theme": "切换日夜间",
|
||||
"header.language": "English",
|
||||
"header.languageShort": "EN",
|
||||
"card.schedule": "定时任务",
|
||||
"card.current": "当前状态",
|
||||
"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": "汇总行数",
|
||||
"data.network.all": "全部",
|
||||
"data.search": "搜索 CGI 或小区名称",
|
||||
"data.sort.interference": "干扰电平从高到低",
|
||||
"data.sort.rise": "较上期升高最多",
|
||||
"data.sort.nearby": "邻近高干扰最多",
|
||||
"data.sort.cgi": "按 CGI 排序",
|
||||
"data.summary": "数据时段 {time} · 共 {total} 条",
|
||||
"data.matched": "筛选结果 {n} 条",
|
||||
"data.pageOf": "第 {page} / {pages} 页",
|
||||
"data.empty": "数据库中暂无数据",
|
||||
"data.noMatch": "没有符合条件的数据",
|
||||
"data.loading": "正在加载…",
|
||||
"data.error": "读取失败:{detail}",
|
||||
"data.pageSize": "每页",
|
||||
"data.col.network": "制式",
|
||||
"data.col.cgi": "CGI",
|
||||
"data.col.cell": "小区名称",
|
||||
"data.col.interference": "干扰 (dBm)",
|
||||
"data.col.prev": "上期 (dBm)",
|
||||
"data.col.change": "变化",
|
||||
"data.col.nearby": "邻近高干扰",
|
||||
"data.col.split": "邻近分布",
|
||||
"data.col.longitude": "经度",
|
||||
"data.col.latitude": "纬度",
|
||||
"data.col.azimuth": "方位角",
|
||||
"data.field.metric_time": "数据时间",
|
||||
"data.field.total": "合计",
|
||||
"data.field.current": "本期",
|
||||
"data.field.previous": "上期",
|
||||
"data.nearbyTitle": "1 公里内高干扰小区数",
|
||||
"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": "运行记录保留条数",
|
||||
"field.history_keep_days": "历史数据保留天数",
|
||||
"field.history_keep_days_hint": "按目录名 YYYY-MM-DD 和文件名中的日期计算,只保留最近这些天,更早的从文件来源删除。0 表示不删除。",
|
||||
"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": "只有应用管理员可以打开管理界面。",
|
||||
"connect.title": "正在连接…",
|
||||
"connect.slow": "连接时间比平时长。请检查浏览器代理或网络设置,然后刷新页面。",
|
||||
},
|
||||
"en": {
|
||||
"app.title": "Interference ETL",
|
||||
"tab.overview": "Overview",
|
||||
"tab.runs": "Runs",
|
||||
"tab.data": "Data",
|
||||
"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.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",
|
||||
"data.network.all": "All",
|
||||
"data.search": "Search CGI or cell name",
|
||||
"data.sort.interference": "Interference, high to low",
|
||||
"data.sort.rise": "Largest rise vs previous",
|
||||
"data.sort.nearby": "Most nearby cells",
|
||||
"data.sort.cgi": "By CGI",
|
||||
"data.summary": "Data time {time} · {total} rows",
|
||||
"data.matched": "{n} matching",
|
||||
"data.pageOf": "Page {page} of {pages}",
|
||||
"data.empty": "No data in the database yet",
|
||||
"data.noMatch": "No matching rows",
|
||||
"data.loading": "Loading…",
|
||||
"data.error": "Failed to load: {detail}",
|
||||
"data.pageSize": "Per page",
|
||||
"data.col.network": "Network",
|
||||
"data.col.cgi": "CGI",
|
||||
"data.col.cell": "Cell name",
|
||||
"data.col.interference": "Interference (dBm)",
|
||||
"data.col.prev": "Previous (dBm)",
|
||||
"data.col.change": "Change",
|
||||
"data.col.nearby": "Nearby",
|
||||
"data.col.split": "Nearby by network",
|
||||
"data.col.longitude": "Longitude",
|
||||
"data.col.latitude": "Latitude",
|
||||
"data.col.azimuth": "Azimuth",
|
||||
"data.field.metric_time": "Data time",
|
||||
"data.field.total": "Total",
|
||||
"data.field.current": "Current",
|
||||
"data.field.previous": "Previous",
|
||||
"data.nearbyTitle": "High-interference cells within 1 km",
|
||||
"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",
|
||||
"field.history_keep_days": "History kept (days)",
|
||||
"field.history_keep_days_hint": "Uses the YYYY-MM-DD directory name and the date in each file name. Older history is deleted from the file source. 0 keeps everything.",
|
||||
"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.",
|
||||
"connect.title": "Connecting…",
|
||||
"connect.slow": "This is taking longer than usual. Check the browser proxy or network settings, then refresh the 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
|
||||
@@ -1,223 +0,0 @@
|
||||
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.cache_dir = data_dir / "cache" / "cell-data"
|
||||
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:
|
||||
run_id = self._begin(trigger, dry_run)
|
||||
if run_id is None:
|
||||
return False
|
||||
threading.Thread(target=self._finish, args=(run_id, dry_run), name=f"etl-{trigger}", daemon=True).start()
|
||||
return True
|
||||
|
||||
def run(self, trigger: str, dry_run: bool = False) -> int | None:
|
||||
run_id = self._begin(trigger, dry_run)
|
||||
if run_id is None:
|
||||
return None
|
||||
self._finish(run_id, dry_run)
|
||||
return run_id
|
||||
|
||||
def _begin(self, trigger: str, dry_run: bool) -> int | None:
|
||||
if not self._lock.acquire(blocking=False):
|
||||
return None
|
||||
try:
|
||||
run_id = self.runs.create(trigger, dry_run)
|
||||
except BaseException:
|
||||
self._lock.release()
|
||||
raise
|
||||
self._current = {"id": run_id, "trigger": trigger, "dry_run": dry_run, "started_at": now_text()}
|
||||
return run_id
|
||||
|
||||
def _finish(self, run_id: int, dry_run: bool) -> None:
|
||||
try:
|
||||
self._execute(run_id, dry_run)
|
||||
except Exception as exc:
|
||||
# A record that never got its result would stay "running" until the next restart.
|
||||
record = self.runs.get(run_id)
|
||||
if record is not None and record["status"] == "running":
|
||||
self.runs.finish(
|
||||
run_id,
|
||||
status="failed",
|
||||
finished_at=now_text(),
|
||||
detail=f"{type(exc).__name__}: {exc}"[:DETAIL_LIMIT],
|
||||
)
|
||||
raise
|
||||
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, run_id: int, dry_run: bool) -> None:
|
||||
settings = self.settings_store.get()
|
||||
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),
|
||||
"--cache",
|
||||
str(self.cache_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)
|
||||
|
||||
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)
|
||||
-144
@@ -1,144 +0,0 @@
|
||||
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()
|
||||
@@ -1,48 +0,0 @@
|
||||
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")
|
||||
@@ -1,147 +0,0 @@
|
||||
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 JSONResponse, PlainTextResponse, RedirectResponse
|
||||
|
||||
from .auth import Identity, require_admin
|
||||
from .config import SettingsError, data_dir, public_view
|
||||
from .data import DataQuery
|
||||
from .service import EtlService
|
||||
|
||||
|
||||
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() -> RedirectResponse:
|
||||
# Relative on purpose: the app is served under a path prefix it does not know.
|
||||
return RedirectResponse("admin")
|
||||
|
||||
@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/data", response_model=None)
|
||||
def data(
|
||||
page: int = 1,
|
||||
page_size: int = 20,
|
||||
network: str = "",
|
||||
q: str = "",
|
||||
sort: str = "interference",
|
||||
_: Identity = Depends(require_admin),
|
||||
) -> Any:
|
||||
query = DataQuery(page=page, page_size=page_size, network=network, keyword=q, sort=sort)
|
||||
try:
|
||||
return service.data.browse(query)
|
||||
except Exception as exc:
|
||||
return JSONResponse(status_code=502, content={"error": "data_unavailable", "detail": str(exc)[:500]})
|
||||
|
||||
@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="干扰数据处理",
|
||||
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()
|
||||
@@ -1,75 +0,0 @@
|
||||
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 .data import DataBrowser
|
||||
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)
|
||||
self.data = DataBrowser(self.settings)
|
||||
|
||||
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]}
|
||||
@@ -1,11 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="InterferenceETL">
|
||||
<defs>
|
||||
<linearGradient id="etl-icon-bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="#2563eb"/>
|
||||
<stop offset="1" stop-color="#14b8a6"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="64" height="64" rx="16" fill="url(#etl-icon-bg)"/>
|
||||
<path d="M10 35h7l4.5-12 6 22 6-28 6 26 4.5-13 3 5H54" fill="none" stroke="#fff" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
<circle cx="54" cy="35" r="3.2" fill="#fff"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 570 B |
@@ -1,333 +0,0 @@
|
||||
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 = """
|
||||
<style>
|
||||
body {
|
||||
--etl-bg: #f4f7fb;
|
||||
--etl-panel: #ffffff;
|
||||
--etl-soft: #f8fafc;
|
||||
--etl-text: #1f2937;
|
||||
--etl-muted: #6b7280;
|
||||
--etl-border: #e5e7eb;
|
||||
--etl-primary: #2563eb;
|
||||
--etl-primary-soft: #eff6ff;
|
||||
--etl-on-primary: #ffffff;
|
||||
--etl-success: #16a34a;
|
||||
--etl-success-soft: #ecfdf3;
|
||||
--etl-warning: #d97706;
|
||||
--etl-warning-soft: #fffbeb;
|
||||
--etl-danger: #e11d48;
|
||||
--etl-danger-soft: #fff1f2;
|
||||
--etl-neutral: #475569;
|
||||
--etl-neutral-soft: #f1f5f9;
|
||||
--etl-shadow: 0 1px 2px rgba(15, 23, 42, 0.04), 0 6px 20px rgba(15, 23, 42, 0.04);
|
||||
--q-primary: #2563eb !important;
|
||||
background: var(--etl-bg) !important;
|
||||
color: var(--etl-text);
|
||||
font-family: Inter, "Segoe UI", "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
body.body--dark {
|
||||
--etl-bg: #101014;
|
||||
--etl-panel: #18181c;
|
||||
--etl-soft: #1f1f24;
|
||||
--etl-text: rgba(255, 255, 255, 0.86);
|
||||
--etl-muted: rgba(255, 255, 255, 0.52);
|
||||
--etl-border: rgba(255, 255, 255, 0.09);
|
||||
--etl-primary: #63e2b7;
|
||||
--etl-primary-soft: rgba(99, 226, 183, 0.14);
|
||||
--etl-on-primary: #0d2a20;
|
||||
--etl-success: #63e2b7;
|
||||
--etl-success-soft: rgba(99, 226, 183, 0.14);
|
||||
--etl-warning: #f2c97d;
|
||||
--etl-warning-soft: rgba(242, 201, 125, 0.14);
|
||||
--etl-danger: #fb7185;
|
||||
--etl-danger-soft: rgba(251, 113, 133, 0.14);
|
||||
--etl-neutral: rgba(255, 255, 255, 0.72);
|
||||
--etl-neutral-soft: rgba(255, 255, 255, 0.08);
|
||||
--etl-shadow: none;
|
||||
--q-primary: #63e2b7 !important;
|
||||
}
|
||||
@layer theme {
|
||||
.q-btn.bg-primary { color: var(--etl-on-primary) !important; }
|
||||
.etl-btn.q-btn--outline { color: var(--etl-text) !important; }
|
||||
.etl-btn-danger.q-btn--outline { color: var(--etl-danger) !important; }
|
||||
.etl-tool-btn { color: var(--etl-muted) !important; }
|
||||
.etl-segment .q-btn { color: var(--etl-muted) !important; }
|
||||
.etl-segment .q-btn.bg-primary { background: var(--etl-panel) !important; color: var(--etl-primary) !important; }
|
||||
}
|
||||
html, body { height: 100%; overflow: hidden; }
|
||||
.nicegui-content {
|
||||
height: 100vh; height: 100dvh; min-height: 0; overflow: hidden;
|
||||
display: flex; flex-direction: column;
|
||||
padding: 0 !important; gap: 0 !important; align-items: stretch !important;
|
||||
}
|
||||
.etl-muted { color: var(--etl-muted); }
|
||||
.etl-grow { flex: 1; }
|
||||
|
||||
.etl-shell { flex: 1; width: 100%; min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
|
||||
.etl-header {
|
||||
position: sticky; top: 0; z-index: 20;
|
||||
background: color-mix(in srgb, var(--etl-panel) 90%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
border-bottom: 1px solid var(--etl-border);
|
||||
}
|
||||
.etl-header-inner {
|
||||
max-width: 1240px; margin: 0 auto; height: 60px; padding: 0 24px;
|
||||
display: flex; align-items: center; gap: 32px;
|
||||
}
|
||||
.etl-brand { display: flex; align-items: center; gap: 12px; flex-shrink: 0; }
|
||||
.etl-brand-icon svg { width: 34px; height: 34px; display: block; }
|
||||
.etl-brand-title { font-size: 16px; font-weight: 600; line-height: 1.25; }
|
||||
.etl-tabs { flex: 1; min-width: 0; align-self: stretch; color: var(--etl-muted); }
|
||||
.etl-tabs .q-tabs__content { height: 60px; }
|
||||
.etl-tabs .q-tab { min-height: 60px; padding: 0 14px; }
|
||||
.etl-tabs .q-tab__label { font-size: 14px; font-weight: 500; }
|
||||
.etl-tabs .q-tab--active { color: var(--etl-primary); }
|
||||
.etl-tabs .q-tab--active .q-tab__label { font-weight: 600; }
|
||||
.etl-tabs .q-tab__indicator { height: 2px; border-radius: 2px 2px 0 0; }
|
||||
.etl-header-tools { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||
.etl-pill {
|
||||
display: inline-flex; align-items: center; gap: 7px; height: 28px; padding: 0 12px; margin-right: 6px;
|
||||
border-radius: 999px; font-size: 12.5px; font-weight: 500;
|
||||
color: var(--etl-muted); background: var(--etl-neutral-soft);
|
||||
}
|
||||
.etl-pill.is-on { color: var(--etl-success); background: var(--etl-success-soft); }
|
||||
.etl-pill-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
|
||||
.etl-pill.is-on .etl-pill-dot { box-shadow: 0 0 0 3px color-mix(in srgb, currentColor 24%, transparent); }
|
||||
.etl-tool-btn { min-width: 34px; min-height: 34px; font-weight: 600; font-size: 13px; }
|
||||
.etl-user { display: flex; align-items: center; gap: 8px; margin-left: 6px; padding-left: 14px; border-left: 1px solid var(--etl-border); }
|
||||
.etl-avatar {
|
||||
width: 30px; height: 30px; border-radius: 50%; display: grid; place-items: center;
|
||||
background: var(--etl-primary-soft); color: var(--etl-primary); font-size: 13px; font-weight: 600;
|
||||
}
|
||||
.etl-user-name { font-size: 13.5px; max-width: 140px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.etl-main {
|
||||
width: 100%; max-width: 1240px; margin: 0 auto; padding: 24px;
|
||||
flex: 1; min-height: 0; overflow: hidden; display: flex; flex-direction: column;
|
||||
}
|
||||
.etl-main.is-wide { max-width: none; }
|
||||
.etl-panels, .etl-panels .q-tab-panel { background: transparent !important; padding: 0 !important; color: inherit; }
|
||||
.etl-panels { width: 100%; flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
.etl-panels > .q-panel { flex: 1; min-height: 0; height: 100% !important; overflow: hidden !important; }
|
||||
.etl-panel {
|
||||
display: flex !important; flex-direction: column; align-items: stretch !important; gap: 16px !important;
|
||||
height: 100%; min-height: 0; overflow: auto; box-sizing: border-box;
|
||||
}
|
||||
.etl-panel.etl-panel-fit { overflow: hidden; }
|
||||
|
||||
.etl-card { background: var(--etl-panel); border: 1px solid var(--etl-border); border-radius: 12px; box-shadow: var(--etl-shadow); }
|
||||
.etl-card-head {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px;
|
||||
min-height: 52px; padding: 0 20px; border-bottom: 1px solid var(--etl-border);
|
||||
}
|
||||
.etl-card-title { display: flex; align-items: center; gap: 8px; font-size: 14.5px; font-weight: 600; }
|
||||
.etl-card-icon { font-size: 18px; color: var(--etl-muted); }
|
||||
|
||||
.etl-cards { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
|
||||
.etl-metric { padding: 18px 20px; display: flex; flex-direction: column; gap: 8px; min-height: 132px; }
|
||||
.etl-metric-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.etl-metric-title { font-size: 13px; color: var(--etl-muted); }
|
||||
.etl-metric-icon { font-size: 20px; color: var(--etl-muted); opacity: 0.6; flex-shrink: 0; }
|
||||
.etl-metric-value-row { display: flex; align-items: center; gap: 8px; min-height: 34px; min-width: 0; }
|
||||
.etl-metric-value { font-size: 22px; font-weight: 600; line-height: 1.35; overflow-wrap: break-word; }
|
||||
.etl-metric-value.is-muted { color: var(--etl-muted); }
|
||||
.etl-metric-value.tone-neutral { color: var(--etl-text); }
|
||||
.etl-metric-spinner { color: var(--etl-primary); flex-shrink: 0; }
|
||||
.etl-metric-sub { font-size: 12.5px; line-height: 1.45; color: var(--etl-muted); overflow-wrap: break-word; }
|
||||
|
||||
.tone-primary { color: var(--etl-primary); }
|
||||
.tone-success { color: var(--etl-success); }
|
||||
.tone-warning { color: var(--etl-warning); }
|
||||
.tone-danger { color: var(--etl-danger); }
|
||||
.tone-neutral { color: var(--etl-neutral); }
|
||||
|
||||
.etl-actions { padding: 14px 20px; display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; }
|
||||
.etl-actions-buttons { display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
.etl-btn { min-height: 36px; padding: 0 16px; border-radius: 8px; font-weight: 500; }
|
||||
.etl-btn .q-icon { font-size: 18px; }
|
||||
.etl-btn.q-btn--outline::before { border-color: var(--etl-border) !important; }
|
||||
.etl-btn.q-btn--outline:hover::before { border-color: color-mix(in srgb, var(--etl-primary) 45%, var(--etl-border)) !important; }
|
||||
.etl-btn-danger.q-btn--outline::before { border-color: color-mix(in srgb, var(--etl-danger) 40%, transparent) !important; }
|
||||
.etl-today { font-size: 13px; }
|
||||
|
||||
.etl-panel-fit > .etl-split { flex: 1 1 auto; min-height: 0; }
|
||||
.etl-split { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 16px; align-items: stretch; min-height: 0; }
|
||||
.etl-log-card, .etl-recent-card { display: flex; flex-direction: column; min-height: 0; overflow: hidden; }
|
||||
.etl-log {
|
||||
font-family: "Cascadia Mono", "JetBrains Mono", Consolas, "Microsoft YaHei", monospace;
|
||||
font-size: 12.5px; line-height: 1.7; white-space: pre-wrap; word-break: break-all; color: var(--etl-text);
|
||||
}
|
||||
.etl-log-card .etl-log, .etl-recent {
|
||||
flex: 1 1 auto; height: auto; min-height: 0; overflow: auto;
|
||||
}
|
||||
.etl-log-card .etl-log { padding: 14px 20px; background: var(--etl-soft); border-radius: 0 0 12px 12px; }
|
||||
.etl-log-meta { font-size: 12.5px; font-variant-numeric: tabular-nums; }
|
||||
.etl-recent { padding: 6px 8px 8px; }
|
||||
.etl-recent-item { display: flex; align-items: center; gap: 12px; padding: 9px 12px; border-radius: 8px; cursor: pointer; transition: background 0.15s; }
|
||||
.etl-recent-item:hover { background: var(--etl-soft); }
|
||||
.etl-dot { width: 8px; height: 8px; border-radius: 50%; background: currentColor; flex-shrink: 0; }
|
||||
.etl-recent-text { flex: 1; min-width: 0; }
|
||||
.etl-recent-status { font-size: 13.5px; font-weight: 500; }
|
||||
.etl-recent-detail { font-size: 12px; color: var(--etl-muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.etl-recent-time { font-size: 12px; color: var(--etl-muted); font-variant-numeric: tabular-nums; }
|
||||
.etl-link-btn { font-size: 13px; }
|
||||
.etl-empty { padding: 28px 12px; text-align: center; font-size: 13px; }
|
||||
|
||||
.etl-segment { border: 1px solid var(--etl-border); border-radius: 8px; padding: 2px; background: var(--etl-soft); box-shadow: none; }
|
||||
.etl-segment .q-btn { border-radius: 6px !important; padding: 0 12px; min-height: 30px; font-weight: 500; }
|
||||
.etl-segment .q-btn.bg-primary { box-shadow: 0 1px 2px rgba(15, 23, 42, 0.08), 0 0 0 1px var(--etl-border); }
|
||||
|
||||
.etl-runs-card { overflow: hidden; }
|
||||
.etl-runs-toolbar {
|
||||
display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap;
|
||||
padding: 12px 20px; border-bottom: 1px solid var(--etl-border);
|
||||
}
|
||||
.etl-runs-tools { display: flex; align-items: center; gap: 8px; font-size: 13px; }
|
||||
.etl-table { background: transparent !important; color: inherit !important; box-shadow: none !important; }
|
||||
.etl-table thead tr th {
|
||||
font-size: 12.5px; font-weight: 500; color: var(--etl-muted); background: var(--etl-soft);
|
||||
border-bottom: 1px solid var(--etl-border) !important; height: 40px;
|
||||
}
|
||||
.etl-table tbody td { font-size: 13px; height: 46px; border-color: var(--etl-border) !important; font-variant-numeric: tabular-nums; }
|
||||
.etl-table tbody tr { cursor: pointer; }
|
||||
.etl-table tbody tr:hover td { background: var(--etl-soft); }
|
||||
.etl-table .q-table__bottom { border-top: none; color: var(--etl-muted); font-size: 13px; }
|
||||
.etl-cell-detail { max-width: 360px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--etl-muted); }
|
||||
.etl-badge {
|
||||
display: inline-flex; align-items: center; height: 22px; padding: 0 8px; border-radius: 6px;
|
||||
font-size: 12px; font-weight: 500; white-space: nowrap;
|
||||
}
|
||||
.etl-badge.tone-primary { background: var(--etl-primary-soft); }
|
||||
.etl-badge.tone-success { background: var(--etl-success-soft); }
|
||||
.etl-badge.tone-warning { background: var(--etl-warning-soft); }
|
||||
.etl-badge.tone-danger { background: var(--etl-danger-soft); }
|
||||
.etl-badge.tone-neutral { background: var(--etl-neutral-soft); }
|
||||
.etl-runs-footer { display: flex; justify-content: flex-end; padding: 10px 16px; border-top: 1px solid var(--etl-border); }
|
||||
|
||||
.etl-data-tools { flex-wrap: wrap; justify-content: flex-end; }
|
||||
.etl-data-search { width: 260px; }
|
||||
.etl-data-sort { width: 200px; }
|
||||
.etl-data-summary {
|
||||
padding: 10px 20px; font-size: 13px; color: var(--etl-muted); border-bottom: 1px solid var(--etl-border);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.etl-data-summary.tone-danger { color: var(--etl-danger); }
|
||||
.etl-data-card { display: flex; flex-direction: column; flex: 1 1 auto; min-height: 0; }
|
||||
.etl-data-card > :not(.etl-data-table) { flex-shrink: 0; }
|
||||
.etl-data-table { flex: 1 1 auto; min-height: 0; }
|
||||
.etl-data-table .q-table__middle { flex: 1 1 auto; min-height: 0; overflow: auto; }
|
||||
.etl-data-table thead tr:first-child th { position: sticky; top: 0; z-index: 2; box-shadow: inset 0 -1px 0 var(--etl-border); }
|
||||
.etl-data-table tbody td { white-space: nowrap; }
|
||||
.etl-data-table td.etl-col-cell { width: 100%; max-width: 0; }
|
||||
.etl-cell-name { min-width: 180px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.etl-net {
|
||||
display: inline-flex; align-items: center; height: 22px; padding: 0 8px; border-radius: 6px;
|
||||
font-size: 12px; font-weight: 600; white-space: nowrap; background: var(--etl-neutral-soft); color: var(--etl-text);
|
||||
}
|
||||
.etl-net.net-26g { background: rgba(37, 99, 235, 0.12); color: #2563eb; }
|
||||
.etl-net.net-700m { background: rgba(124, 58, 237, 0.12); color: #7c3aed; }
|
||||
.etl-net.net-tdd { background: rgba(13, 148, 136, 0.13); color: #0d9488; }
|
||||
.etl-net.net-fdd { background: rgba(217, 119, 6, 0.13); color: #b45309; }
|
||||
.body--dark .etl-net.net-26g { color: #7aa7ff; }
|
||||
.body--dark .etl-net.net-700m { color: #b69cff; }
|
||||
.body--dark .etl-net.net-tdd { color: #5eead4; }
|
||||
.body--dark .etl-net.net-fdd { color: #fbbf24; }
|
||||
.etl-data-footer { justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
|
||||
.etl-data-size { display: flex; align-items: center; gap: 8px; font-size: 13px; }
|
||||
.etl-page-size { width: 84px; }
|
||||
.etl-dialog.etl-data-dialog { width: min(760px, 94vw); }
|
||||
.etl-detail { width: 100%; padding: 6px 20px 20px; }
|
||||
.etl-detail-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px 20px; padding: 12px 0 16px; }
|
||||
.etl-detail-grid .etl-meta-value { word-break: break-all; }
|
||||
.etl-detail-title { font-size: 13px; font-weight: 600; padding: 14px 0 10px; border-top: 1px solid var(--etl-border); }
|
||||
.etl-detail-matrix {
|
||||
display: grid; grid-template-columns: 72px repeat(5, minmax(0, 1fr)); gap: 10px 12px; align-items: center;
|
||||
padding: 12px 14px; border-radius: 8px; background: var(--etl-soft); font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.etl-dialog {
|
||||
width: min(960px, 94vw); max-width: none !important; padding: 0 !important; gap: 0 !important;
|
||||
border-radius: 12px !important; background: var(--etl-panel) !important; color: var(--etl-text);
|
||||
}
|
||||
.etl-dialog-head { display: flex; align-items: center; gap: 10px; width: 100%; padding: 12px 12px 12px 20px; border-bottom: 1px solid var(--etl-border); }
|
||||
.etl-dialog-title { font-size: 15px; font-weight: 600; }
|
||||
.etl-dialog-meta {
|
||||
display: grid; grid-template-columns: repeat(5, minmax(0, 1fr)); gap: 12px; width: 100%;
|
||||
padding: 14px 20px; border-bottom: 1px solid var(--etl-border);
|
||||
}
|
||||
.etl-meta-label { font-size: 12px; color: var(--etl-muted); }
|
||||
.etl-meta-value { font-size: 13px; font-variant-numeric: tabular-nums; }
|
||||
.etl-log-dialog { width: 100%; max-height: 56vh; min-height: 220px; overflow: auto; padding: 14px 20px; background: var(--etl-soft); }
|
||||
.etl-dialog-foot { display: flex; justify-content: flex-end; gap: 8px; width: 100%; padding: 12px 16px; border-top: 1px solid var(--etl-border); }
|
||||
|
||||
.etl-settings { width: 100%; max-width: 940px; margin: 0 auto; display: flex; flex-direction: column; gap: 16px; }
|
||||
.etl-section { padding: 4px 24px 6px; }
|
||||
.etl-section-title { font-size: 15px; font-weight: 600; padding: 16px 0 4px; }
|
||||
.etl-fields { display: flex; flex-direction: column; }
|
||||
.etl-field {
|
||||
display: grid; grid-template-columns: 200px minmax(0, 1fr); gap: 24px; align-items: center;
|
||||
padding: 12px 0; border-top: 1px solid var(--etl-border);
|
||||
}
|
||||
.etl-field:first-child { border-top: none; }
|
||||
.etl-field-label { display: flex; align-items: center; gap: 4px; min-width: 0; font-size: 13.5px; }
|
||||
.etl-field-label-text { min-width: 0; }
|
||||
.etl-hint { font-size: 16px; color: var(--etl-muted); cursor: help; flex-shrink: 0; }
|
||||
.etl-hint-tip { max-width: 280px; white-space: normal; line-height: 1.5; }
|
||||
.etl-field-control { min-width: 0; display: flex; align-items: center; }
|
||||
.etl-input { width: 100%; max-width: 520px; }
|
||||
.etl-input-short { max-width: 200px; }
|
||||
.etl-input.etl-textarea { max-width: none; }
|
||||
.etl-textarea textarea { font-family: "Cascadia Mono", Consolas, "Microsoft YaHei", monospace; font-size: 12.5px; line-height: 1.6; }
|
||||
.etl-save-bar {
|
||||
position: sticky; bottom: 0; z-index: 5; display: flex; align-items: center; gap: 10px;
|
||||
padding: 14px 0 18px; background: linear-gradient(to top, var(--etl-bg) 72%, transparent);
|
||||
}
|
||||
.etl-save-bar .q-btn { flex-shrink: 0; white-space: nowrap; }
|
||||
.etl-checks { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; }
|
||||
.etl-check { display: flex; align-items: center; gap: 6px; font-size: 13px; min-width: 0; }
|
||||
.etl-check .q-icon { font-size: 18px; }
|
||||
.etl-check.is-ok { color: var(--etl-success); }
|
||||
.etl-check.is-fail { color: var(--etl-danger); }
|
||||
.etl-check-name { font-weight: 600; flex-shrink: 0; }
|
||||
.etl-check-text { color: var(--etl-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
|
||||
.etl-connecting {
|
||||
flex: 1; width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center;
|
||||
gap: 12px; padding: 24px; text-align: center; color: var(--etl-muted);
|
||||
}
|
||||
.etl-connecting-spinner { color: var(--etl-primary); }
|
||||
.etl-connecting-title { font-size: 14px; }
|
||||
.etl-connecting-hint { max-width: 440px; font-size: 13px; line-height: 1.6; opacity: 0; animation: etl-reveal 0.3s ease 8s forwards; }
|
||||
@keyframes etl-reveal { to { opacity: 1; } }
|
||||
|
||||
.etl-forbidden { min-height: 100vh; width: 100%; display: grid; place-items: center; }
|
||||
.etl-forbidden-card { padding: 40px 56px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; }
|
||||
.etl-forbidden-icon { font-size: 40px; color: var(--etl-muted); }
|
||||
.etl-forbidden-title { font-size: 18px; font-weight: 600; }
|
||||
|
||||
@media (max-width: 1080px) {
|
||||
.etl-split { grid-template-columns: 1fr; }
|
||||
.etl-panel.etl-panel-fit { overflow: auto; }
|
||||
.etl-log-card .etl-log { min-height: 240px; }
|
||||
.etl-recent { min-height: 220px; }
|
||||
.etl-user-name { display: none; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.etl-header-inner { gap: 12px; padding: 0 12px; }
|
||||
.etl-pill { display: none; }
|
||||
.etl-main { padding: 16px 12px; }
|
||||
.etl-cards { grid-template-columns: 1fr; }
|
||||
.etl-field { grid-template-columns: 1fr; gap: 8px; }
|
||||
.etl-dialog-meta { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.etl-detail-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.etl-data-search, .etl-data-sort { width: 100%; }
|
||||
}
|
||||
</style>
|
||||
"""
|
||||
-1044
File diff suppressed because it is too large
Load Diff
@@ -1,69 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
import main
|
||||
|
||||
from .config import Settings, SettingsStore
|
||||
from .connectors import build_client, build_storage, build_store, close_quietly
|
||||
|
||||
|
||||
def run(settings_path: Path, output_dir: Path, dry_run: bool, cache_dir: Path | None = None) -> 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)
|
||||
cell_cache = main.CellDataCache(cache_dir) if cache_dir is not None else None
|
||||
output = main.process(
|
||||
source, output_dir, settings.lookback_days, store=store, history=history, cell_cache=cell_cache
|
||||
)
|
||||
if output is not None and not dry_run:
|
||||
prune_history(storage, settings)
|
||||
finally:
|
||||
close_quietly(storage)
|
||||
return 0
|
||||
|
||||
|
||||
def prune_history(storage: main.FileStorage, settings: Settings) -> None:
|
||||
"""Apply history retention after a new group was stored. The data is already saved, so a failure is only reported."""
|
||||
if settings.history_keep_days <= 0:
|
||||
return
|
||||
try:
|
||||
removed = main.StorageHistoryStore(storage, settings.history_root).prune(settings.history_keep_days)
|
||||
except Exception as exc:
|
||||
print(f"history_prune_error={type(exc).__name__}: {exc}")
|
||||
return
|
||||
for path in removed:
|
||||
print(f"history_removed={path}")
|
||||
|
||||
|
||||
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("--cache", type=Path, help="directory for parsed CellData workbooks")
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
return run(args.settings, args.output, args.dry_run, args.cache)
|
||||
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())
|
||||
@@ -9,7 +9,7 @@ import json
|
||||
import math
|
||||
import os
|
||||
from dataclasses import dataclass
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import posixpath
|
||||
import re
|
||||
@@ -22,7 +22,19 @@ from urllib.parse import quote, urlencode
|
||||
from urllib.request import ProxyHandler, Request, build_opener
|
||||
import warnings
|
||||
import zipfile
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
VENDOR_DIR = Path(__file__).resolve().parent / "vendor"
|
||||
sys.path.insert(0, str(VENDOR_DIR))
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
try:
|
||||
from runtime_config import METRIX_API_BASE_URL, METRIX_API_TOKEN, METRIX_DATABASE_CONNECTION_ID
|
||||
except ImportError:
|
||||
METRIX_API_BASE_URL = "http://188.5.127.115:18271"
|
||||
METRIX_API_TOKEN = ""
|
||||
METRIX_DATABASE_CONNECTION_ID = ""
|
||||
|
||||
|
||||
EXPECTED_TYPES = (
|
||||
@@ -78,19 +90,13 @@ CELL_DATA_DIRECTORIES = (
|
||||
)
|
||||
FILE_TIME_RE = re.compile(r"_(?P<window>\d{16})\.zip$", re.IGNORECASE)
|
||||
CELL_DATA_FILE_RE = re.compile(r"(?P<date>20\d{6})\.xlsx$", re.IGNORECASE)
|
||||
# Raise this when parse_cell_data_workbook changes what it returns, so older cache files are ignored.
|
||||
CELL_CACHE_VERSION = 1
|
||||
|
||||
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"
|
||||
HISTORY_DIRECTORY_DAY = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
|
||||
HISTORY_FILE_STAMP = re.compile(r"(?<!\d)(\d{4})(\d{2})(\d{2})\d{6}(?!\d)")
|
||||
HISTORY_FILE_DAY = re.compile(r"(?<!\d)(\d{4})-(\d{2})-(\d{2})(?!\d)")
|
||||
|
||||
HEADER_FDD = (
|
||||
"开始时间",
|
||||
@@ -204,48 +210,6 @@ 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
|
||||
|
||||
@@ -280,22 +244,10 @@ 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: ...
|
||||
|
||||
def delete(self, path: str) -> None: ...
|
||||
|
||||
|
||||
class MetrixApiClient:
|
||||
def __init__(self, base_url: str, token: str) -> None:
|
||||
if not token:
|
||||
raise ProcessingError("Metrix API token is required")
|
||||
raise ProcessingError("METRIX_API_TOKEN is required for Metrix API access")
|
||||
self.base_url = base_url.rstrip("/")
|
||||
self.token = token
|
||||
self.opener = build_opener(ProxyHandler({}))
|
||||
@@ -340,9 +292,6 @@ class MetrixApiClient:
|
||||
)
|
||||
)
|
||||
|
||||
def delete(self, endpoint: str, query: dict[str, object], timeout: int = 120) -> object:
|
||||
return self._decode_json(self._request("DELETE", endpoint, query=query, timeout=timeout))
|
||||
|
||||
def _request(
|
||||
self,
|
||||
method: str,
|
||||
@@ -384,33 +333,36 @@ class MetrixApiClient:
|
||||
|
||||
|
||||
class ApiSummaryStore:
|
||||
def __init__(
|
||||
self,
|
||||
client: MetrixApiClient,
|
||||
connection_id: str,
|
||||
database: str = DATABASE_NAME,
|
||||
table: str = DATABASE_TABLE,
|
||||
) -> None:
|
||||
def __init__(self, client: MetrixApiClient, connection_id: str) -> None:
|
||||
if not connection_id:
|
||||
raise ProcessingError("Metrix database connection ID is required")
|
||||
raise ProcessingError("METRIX_DATABASE_CONNECTION_ID is required for database output")
|
||||
self.client = client
|
||||
self.connection_id = connection_id
|
||||
self.database = sql_identifier(database, "database")
|
||||
self.table = sql_identifier(table, "table")
|
||||
self.table = DATABASE_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=self.database,
|
||||
database=DATABASE_NAME,
|
||||
)
|
||||
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]:
|
||||
metric_time = batch_metric_time(rows)
|
||||
ensure_not_newer(self.latest_metric_time(), metric_time)
|
||||
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_literal = f"'{metric_time:%Y-%m-%d %H:%M:%S}'"
|
||||
values = ",\n".join(self._row_values(metric_literal, row) for row in rows)
|
||||
@@ -421,13 +373,13 @@ class ApiSummaryStore:
|
||||
START TRANSACTION;
|
||||
DELETE FROM `{self.table}` WHERE metric_time = {metric_literal};
|
||||
INSERT INTO `{self.table}`
|
||||
({', '.join(SUMMARY_HEADER)})
|
||||
(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)
|
||||
VALUES
|
||||
{values};
|
||||
DELETE FROM `{self.table}` WHERE metric_time <> {metric_literal};
|
||||
COMMIT;
|
||||
""",
|
||||
"database": self.database,
|
||||
"database": DATABASE_NAME,
|
||||
"stop_on_error": True,
|
||||
"single_session": True,
|
||||
},
|
||||
@@ -462,7 +414,7 @@ class ApiSummaryStore:
|
||||
result: list[dict[str, str]] = []
|
||||
page = 1
|
||||
while True:
|
||||
payload = self._query(sql, database=self.database, page=page, page_size=1000)
|
||||
payload = self._query(sql, database=DATABASE_NAME, page=page, page_size=1000)
|
||||
rows = payload.get("rows", [])
|
||||
if not isinstance(rows, list):
|
||||
raise ProcessingError("Metrix Database API returned invalid rows")
|
||||
@@ -475,36 +427,77 @@ class ApiSummaryStore:
|
||||
return result
|
||||
page += 1
|
||||
|
||||
def select(self, sql: str, limit: int) -> list[dict[str, object]]:
|
||||
payload = self._query(sql, database=self.database, page=1, page_size=max(1, min(limit, 1000)), timeout=20)
|
||||
rows = payload.get("rows", [])
|
||||
if not isinstance(rows, list):
|
||||
raise ProcessingError("Metrix Database API returned invalid rows")
|
||||
return [row for row in rows if isinstance(row, dict)]
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
self._query(create_database_sql(self.database))
|
||||
self._query(create_table_sql(self.table), database=self.database)
|
||||
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,
|
||||
)
|
||||
columns = self.client.get_json(
|
||||
self._endpoint("columns"),
|
||||
{"database": self.database, "table": self.table},
|
||||
{"database": DATABASE_NAME, "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)}
|
||||
for statement in column_migration_sql(self.table, existing_columns):
|
||||
self._query(statement, database=self.database)
|
||||
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,
|
||||
)
|
||||
|
||||
def _endpoint(self, action: str) -> str:
|
||||
return f"/api/databases/{quote(self.connection_id, safe='')}/{action}"
|
||||
|
||||
def _query(
|
||||
self, sql: str, database: str = "", page: int = 1, page_size: int = 100, timeout: int = 120
|
||||
) -> dict[str, object]:
|
||||
def _query(self, sql: str, database: str = "", page: int = 1, page_size: int = 100) -> dict[str, object]:
|
||||
payload = self.client.post_json(
|
||||
self._endpoint("query"),
|
||||
{"sql": sql, "database": database, "page": page, "page_size": page_size},
|
||||
timeout=timeout,
|
||||
timeout=120,
|
||||
)
|
||||
if not isinstance(payload, dict):
|
||||
raise ProcessingError("Metrix Database API returned an invalid query result")
|
||||
@@ -537,179 +530,105 @@ class ApiSummaryStore:
|
||||
) + ")"
|
||||
|
||||
|
||||
class MetrixStorage:
|
||||
def __init__(self, client: MetrixApiClient, storage_id: str) -> None:
|
||||
if not storage_id:
|
||||
raise ProcessingError("Metrix storage ID is required")
|
||||
class ApiHistoryStore:
|
||||
def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None:
|
||||
self.client = client
|
||||
self.storage_id = storage_id
|
||||
|
||||
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 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 delete(self, path: str) -> None:
|
||||
self.client.delete(self._endpoint("files"), {"path": 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 "/"
|
||||
self.root = root.rstrip("/")
|
||||
|
||||
def exists(self, metric_time: datetime) -> bool:
|
||||
directory, filename = self.target(metric_time)
|
||||
if not self._has_directory(directory):
|
||||
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.storage.list_dir(directory)
|
||||
for item in self._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)
|
||||
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,
|
||||
)
|
||||
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 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 _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))
|
||||
def _endpoint(self, action: str) -> str:
|
||||
return f"/api/storages/{quote(self.storage_id, safe='')}/{action}"
|
||||
|
||||
def prune(self, keep_days: int, today: date | None = None) -> list[str]:
|
||||
"""Delete history older than the last keep_days calendar days.
|
||||
|
||||
A directory is dated only when its name is YYYY-MM-DD. A file is dated
|
||||
from YYYYMMDDHHMMSS in its name, or from YYYY-MM-DD if that is all it has.
|
||||
Modification times are not used.
|
||||
"""
|
||||
if keep_days <= 0:
|
||||
return []
|
||||
current = today or datetime.now(ZoneInfo(os.getenv("TZ") or "Asia/Shanghai")).date()
|
||||
cutoff = current - timedelta(days=keep_days - 1)
|
||||
removed: list[str] = []
|
||||
for item in self.storage.list_dir(self.root):
|
||||
name = str(item.get("name") or "")
|
||||
path = str(item.get("path") or "")
|
||||
if item.get("is_dir"):
|
||||
folder_day = directory_day(name)
|
||||
if folder_day is None:
|
||||
continue
|
||||
if folder_day < cutoff:
|
||||
self.storage.delete(path)
|
||||
removed.append(path)
|
||||
continue
|
||||
for child in self.storage.list_dir(path):
|
||||
if child.get("is_dir"):
|
||||
continue
|
||||
child_day = file_day(str(child.get("name") or ""))
|
||||
if child_day is not None and child_day < cutoff:
|
||||
child_path = str(child.get("path") or "")
|
||||
self.storage.delete(child_path)
|
||||
removed.append(child_path)
|
||||
continue
|
||||
named_day = file_day(name)
|
||||
if named_day is not None and named_day < cutoff:
|
||||
self.storage.delete(path)
|
||||
removed.append(path)
|
||||
return removed
|
||||
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 directory_day(name: str) -> date | None:
|
||||
match = HISTORY_DIRECTORY_DAY.fullmatch(name)
|
||||
return _calendar_day(match.groups()) if match else None
|
||||
|
||||
|
||||
def file_day(name: str) -> date | None:
|
||||
match = HISTORY_FILE_STAMP.search(name) or HISTORY_FILE_DAY.search(name)
|
||||
return _calendar_day(match.groups()) if match else None
|
||||
|
||||
|
||||
def _calendar_day(parts: tuple[str, ...]) -> date | None:
|
||||
try:
|
||||
return date(int(parts[0]), int(parts[1]), int(parts[2]))
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
|
||||
class StorageSource:
|
||||
def __init__(
|
||||
self,
|
||||
storage: FileStorage,
|
||||
root: str,
|
||||
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
|
||||
) -> None:
|
||||
self.storage = storage
|
||||
class ApiSource:
|
||||
def __init__(self, client: MetrixApiClient, storage_id: str, root: str) -> None:
|
||||
self.client = client
|
||||
self.storage_id = storage_id
|
||||
self.root = root.rstrip("/") or "/"
|
||||
self.cell_data_directories = tuple(cell_data_directories)
|
||||
|
||||
def candidates(self, lookback_days: int) -> list[Candidate]:
|
||||
date_dirs = self.date_directories()
|
||||
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"],
|
||||
)
|
||||
selected_dirs = date_dirs[-max(1, lookback_days) :]
|
||||
result: list[Candidate] = []
|
||||
for directory in selected_dirs:
|
||||
for item in self.storage.list_dir(str(directory["path"])):
|
||||
for item in self._list_dir(directory["path"]):
|
||||
if item.get("is_dir"):
|
||||
continue
|
||||
candidate = parse_candidate(str(item["path"]), int(item.get("size") or 0))
|
||||
candidate = parse_candidate(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:
|
||||
return self.storage.read_bytes(path)
|
||||
endpoint = f"/api/storages/{quote(self.storage_id, safe='')}/download"
|
||||
return self.client.get_bytes(endpoint, {"path": path}, timeout=120)
|
||||
|
||||
def cell_data_workbooks(self) -> list[tuple[str, bytes]]:
|
||||
workbooks: list[tuple[str, bytes]] = []
|
||||
for directory in self.cell_data_directories:
|
||||
item = select_latest_cell_data_file(self.storage.list_dir(directory), directory)
|
||||
for directory in CELL_DATA_DIRECTORIES:
|
||||
item = select_latest_cell_data_file(self._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 LocalSource:
|
||||
def __init__(
|
||||
self,
|
||||
root: Path,
|
||||
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
|
||||
) -> None:
|
||||
def __init__(self, root: Path) -> 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}")
|
||||
|
||||
@@ -726,12 +645,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 self.cell_data_directories]
|
||||
directories = [self.root / Path(directory.lstrip("/")) for directory in 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 configured directories")
|
||||
raise ProcessingError("Local CellData source must contain all five configured directories")
|
||||
workbooks: list[tuple[str, bytes]] = []
|
||||
for directory in directories:
|
||||
entries = [
|
||||
@@ -777,18 +696,11 @@ def select_latest_cell_data_file(entries: list[dict[str, object]], directory: st
|
||||
return max(dated_files, key=lambda entry: (entry[0], entry[1]))[2]
|
||||
|
||||
|
||||
def open_workbook(payload: bytes):
|
||||
# Imported here because most runs find nothing new and never open a workbook.
|
||||
from openpyxl import load_workbook
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", message="Workbook contains no default style")
|
||||
return load_workbook(io.BytesIO(payload), read_only=True, data_only=True)
|
||||
|
||||
|
||||
def parse_cell_data_workbook(raw_xlsx: bytes, path: str) -> dict[str, tuple[str, str, str]]:
|
||||
try:
|
||||
workbook = open_workbook(raw_xlsx)
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", message="Workbook contains no default style")
|
||||
workbook = load_workbook(io.BytesIO(raw_xlsx), read_only=True, data_only=True)
|
||||
except Exception as exc:
|
||||
raise ProcessingError(f"Invalid CellData workbook {path}: {exc}") from exc
|
||||
try:
|
||||
@@ -830,78 +742,14 @@ def parse_cell_data_workbook(raw_xlsx: bytes, path: str) -> dict[str, tuple[str,
|
||||
workbook.close()
|
||||
|
||||
|
||||
class CellDataCache:
|
||||
"""Parsed CellData workbooks kept on disk.
|
||||
|
||||
Parsing one workbook takes several seconds and the files change about once a day.
|
||||
An entry is named after the SHA-256 of the workbook bytes, so a changed file is always parsed again.
|
||||
"""
|
||||
|
||||
def __init__(self, directory: Path) -> None:
|
||||
self.directory = directory
|
||||
self.hits = 0
|
||||
self._used: set[str] = set()
|
||||
|
||||
def load(self, raw_xlsx: bytes, path: str) -> dict[str, tuple[str, str, str]]:
|
||||
name = f"{hashlib.sha256(raw_xlsx).hexdigest()}.v{CELL_CACHE_VERSION}.json"
|
||||
self._used.add(name)
|
||||
cached = self._read(self.directory / name)
|
||||
if cached is not None:
|
||||
self.hits += 1
|
||||
return cached
|
||||
cells = parse_cell_data_workbook(raw_xlsx, path)
|
||||
self._write(self.directory / name, cells)
|
||||
return cells
|
||||
|
||||
def prune(self) -> None:
|
||||
"""Remove entries the current run did not use."""
|
||||
if not self.directory.is_dir():
|
||||
return
|
||||
for item in self.directory.iterdir():
|
||||
if item.is_file() and item.name not in self._used:
|
||||
item.unlink(missing_ok=True)
|
||||
|
||||
@staticmethod
|
||||
def _read(path: Path) -> dict[str, tuple[str, str, str]] | None:
|
||||
try:
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
cells: dict[str, tuple[str, str, str]] = {}
|
||||
for cgi, value in payload.items():
|
||||
if not isinstance(value, list) or len(value) != 3 or not all(isinstance(item, str) for item in value):
|
||||
return None
|
||||
cells[cgi] = (value[0], value[1], value[2])
|
||||
return cells
|
||||
|
||||
@staticmethod
|
||||
def _write(path: Path, cells: dict[str, tuple[str, str, str]]) -> None:
|
||||
temp = path.with_name(f"{path.name}.tmp-{os.getpid()}")
|
||||
try:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp.write_text(json.dumps(cells, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
||||
os.replace(temp, path)
|
||||
except OSError as exc:
|
||||
temp.unlink(missing_ok=True)
|
||||
progress(f"cell data cache was not saved: {exc}")
|
||||
|
||||
|
||||
def load_cell_metadata(
|
||||
workbooks: list[tuple[str, bytes]],
|
||||
cache: CellDataCache | None = None,
|
||||
) -> dict[str, tuple[str, str, str]]:
|
||||
def load_cell_metadata(workbooks: list[tuple[str, bytes]]) -> dict[str, tuple[str, str, str]]:
|
||||
metadata: dict[str, tuple[str, str, str]] = {}
|
||||
for path, raw_xlsx in workbooks:
|
||||
cells = cache.load(raw_xlsx, path) if cache is not None else parse_cell_data_workbook(raw_xlsx, path)
|
||||
for cgi, value in cells.items():
|
||||
for cgi, value in parse_cell_data_workbook(raw_xlsx, path).items():
|
||||
existing = metadata.get(cgi)
|
||||
if existing is not None and existing != value:
|
||||
raise ProcessingError(f"Conflicting CellData metadata for {cgi} across workbooks")
|
||||
metadata[cgi] = value
|
||||
if cache is not None:
|
||||
cache.prune()
|
||||
return metadata
|
||||
|
||||
|
||||
@@ -953,7 +801,9 @@ def parse_workbook(raw_zip: bytes, source_type: str) -> tuple[tuple[str, ...], l
|
||||
except zipfile.BadZipFile as exc:
|
||||
raise ProcessingError("Invalid ZIP archive") from exc
|
||||
|
||||
workbook = open_workbook(workbook_bytes)
|
||||
with warnings.catch_warnings():
|
||||
warnings.filterwarnings("ignore", message="Workbook contains no default style")
|
||||
workbook = load_workbook(io.BytesIO(workbook_bytes), read_only=True, data_only=True)
|
||||
try:
|
||||
if "Sheet0" not in workbook.sheetnames:
|
||||
raise ProcessingError("Workbook does not contain Sheet0")
|
||||
@@ -978,10 +828,8 @@ def process(
|
||||
requested_window: str = "",
|
||||
store: SummaryStore | None = None,
|
||||
history: HistoryStore | None = None,
|
||||
cell_cache: CellDataCache | 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")
|
||||
@@ -1017,13 +865,9 @@ 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, cell_cache)
|
||||
reused = f", {cell_cache.hits} read from cache" if cell_cache is not None else ""
|
||||
progress(f"loaded {len(cell_data_workbooks)} cell data workbooks with {len(cell_metadata)} cells{reused}")
|
||||
cell_metadata = load_cell_metadata(cell_data_workbooks)
|
||||
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
|
||||
@@ -1043,8 +887,6 @@ 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):
|
||||
@@ -1071,17 +913,14 @@ 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(),
|
||||
@@ -1127,10 +966,6 @@ 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,
|
||||
@@ -1304,96 +1139,22 @@ 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 parse_decimal(value: str, field: str, nullable: bool = False) -> Decimal | None:
|
||||
def sql_decimal_literal(value: str, field: str, nullable: bool = False) -> str:
|
||||
normalized = value.strip()
|
||||
if not normalized and nullable:
|
||||
return None
|
||||
return "NULL"
|
||||
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 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")
|
||||
return format(number, "f")
|
||||
|
||||
|
||||
def write_csv(path: Path, header: tuple[str, ...], rows: list[tuple[object, ...]]) -> None:
|
||||
@@ -1430,18 +1191,39 @@ def ensure_scoped(root: Path, target: Path) -> None:
|
||||
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Process the newest complete time group of a local source tree into CSV files, without a database"
|
||||
parser = argparse.ArgumentParser(description="Process the latest complete interference KPI time group")
|
||||
parser.add_argument("--source-dir", type=Path, help="Use a local source tree instead of the Metrix storage API")
|
||||
parser.add_argument("--output-dir", type=Path, default=Path(os.getenv("INTERFERENCE_OUTPUT_DIR", "output")))
|
||||
parser.add_argument(
|
||||
"--window",
|
||||
default=os.getenv("INTERFERENCE_WINDOW", ""),
|
||||
help="Optional 16-digit source window used to select a natural 15-minute group",
|
||||
)
|
||||
parser.add_argument("--source-dir", type=Path, required=True, help="Local copy of the source tree")
|
||||
parser.add_argument("--output-dir", type=Path, default=Path("output"))
|
||||
parser.add_argument("--window", default="", help="16-digit source window that selects a natural 15-minute group")
|
||||
parser.add_argument("--lookback-days", type=int, default=int(os.getenv("INTERFERENCE_LOOKBACK_DAYS", "3")))
|
||||
parser.add_argument("--storage-id", default=os.getenv("METRIX_STORAGE_ID", DEFAULT_STORAGE_ID))
|
||||
parser.add_argument("--root", default=os.getenv("INTERFERENCE_SOURCE_ROOT", DEFAULT_ROOT))
|
||||
parser.add_argument("--no-database", action="store_true", help="Generate files without writing the database")
|
||||
return parser
|
||||
|
||||
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
process(LocalSource(args.source_dir), args.output_dir, lookback_days=1, requested_window=args.window)
|
||||
if args.lookback_days < 1:
|
||||
raise ProcessingError("lookback-days must be at least 1")
|
||||
client: MetrixApiClient | None = None
|
||||
if args.source_dir:
|
||||
source: Source = LocalSource(args.source_dir)
|
||||
else:
|
||||
client = MetrixApiClient(METRIX_API_BASE_URL, METRIX_API_TOKEN)
|
||||
source = ApiSource(client, args.storage_id, args.root)
|
||||
if args.no_database:
|
||||
store = None
|
||||
history = None
|
||||
else:
|
||||
client = client or MetrixApiClient(METRIX_API_BASE_URL, METRIX_API_TOKEN)
|
||||
store = ApiSummaryStore(client, METRIX_DATABASE_CONNECTION_ID)
|
||||
history = ApiHistoryStore(client, args.storage_id, f"{args.root.rstrip('/')}/干扰历史数据")
|
||||
process(source, args.output_dir, args.lookback_days, args.window, store=store, history=history)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
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
|
||||
@@ -0,0 +1 @@
|
||||
openpyxl==3.1.5
|
||||
@@ -0,0 +1,3 @@
|
||||
METRIX_API_BASE_URL = "http://188.5.127.115:18271"
|
||||
METRIX_API_TOKEN = "replace-with-metrix-api-token"
|
||||
METRIX_DATABASE_CONNECTION_ID = "replace-with-database-connection-id"
|
||||
@@ -0,0 +1,122 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_IMAGE = "interference-etl-runtime:1.1"
|
||||
DEFAULT_BASE_IMAGE = "python:3.13.11-slim"
|
||||
DEFAULT_OUTPUT = PROJECT_ROOT / "dist" / "InterferenceETL-offline-1.1.zip"
|
||||
PACKAGE_FILES = ("main.py", "requirements.txt", "README.md", "runtime_config.py")
|
||||
PACKAGE_ENTRYPOINT = "from main import main\nraise SystemExit(main())\n"
|
||||
|
||||
COPY_DEPENDENCIES = r"""
|
||||
from importlib.metadata import distribution
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
target = Path('/package/vendor')
|
||||
for name in ('openpyxl', 'et-xmlfile'):
|
||||
package = distribution(name)
|
||||
for item in package.files or ():
|
||||
if '__pycache__' in item.parts or item.suffix in ('.pyc', '.pyo'):
|
||||
continue
|
||||
source = Path(package.locate_file(item))
|
||||
if not source.is_file():
|
||||
continue
|
||||
destination = target / item
|
||||
destination.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(source, destination)
|
||||
"""
|
||||
|
||||
|
||||
def build(output: Path, runtime_image: str, base_image: str) -> Path:
|
||||
output = output.resolve()
|
||||
output.parent.mkdir(parents=True, exist_ok=True)
|
||||
missing = [name for name in PACKAGE_FILES if not (PROJECT_ROOT / name).is_file()]
|
||||
if missing:
|
||||
raise FileNotFoundError(f"Missing package files: {', '.join(missing)}")
|
||||
with tempfile.TemporaryDirectory(prefix="interference-etl-package-") as temp:
|
||||
staging = Path(temp)
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"-v",
|
||||
f"{staging}:/package",
|
||||
runtime_image,
|
||||
"python",
|
||||
"-c",
|
||||
COPY_DEPENDENCIES,
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
for name in PACKAGE_FILES:
|
||||
shutil.copy2(PROJECT_ROOT / name, staging / name)
|
||||
(staging / "__main__.py").write_text(PACKAGE_ENTRYPOINT, encoding="utf-8")
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"-e",
|
||||
"PYTHONDONTWRITEBYTECODE=1",
|
||||
"-v",
|
||||
f"{staging}:/workspace:ro",
|
||||
"-w",
|
||||
"/workspace",
|
||||
base_image,
|
||||
"python",
|
||||
"-c",
|
||||
"import main, openpyxl; print('offline_package_imports=ok')",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
if output.exists():
|
||||
output.unlink()
|
||||
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
|
||||
for path in sorted(staging.rglob("*")):
|
||||
if path.is_file():
|
||||
archive.write(path, path.relative_to(staging).as_posix())
|
||||
subprocess.run(
|
||||
[
|
||||
"docker",
|
||||
"run",
|
||||
"--rm",
|
||||
"-e",
|
||||
"PYTHONDONTWRITEBYTECODE=1",
|
||||
"-v",
|
||||
f"{output.parent}:/dist:ro",
|
||||
base_image,
|
||||
"python",
|
||||
f"/dist/{output.name}",
|
||||
"--help",
|
||||
],
|
||||
check=True,
|
||||
)
|
||||
return output
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Build a self-contained Metrix Script Management upload ZIP")
|
||||
parser.add_argument("--runtime-image", default=DEFAULT_IMAGE)
|
||||
parser.add_argument("--base-image", default=DEFAULT_BASE_IMAGE)
|
||||
parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT)
|
||||
args = parser.parse_args()
|
||||
output = build(args.output, args.runtime_image, args.base_image)
|
||||
digest = hashlib.sha256(output.read_bytes()).hexdigest().upper()
|
||||
print(f"output={output}")
|
||||
print(f"size={output.stat().st_size}")
|
||||
print(f"sha256={digest}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -1,131 +0,0 @@
|
||||
"""Build the InterferenceETL Metrix app bundle: dist/metrix/interference-etl-<version>.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,
|
||||
"description": {
|
||||
"zh-CN": "从 SFTP 读取小时干扰指标,汇总后写入数据库,并按日期归档历史结果。",
|
||||
"en-US": "Reads hourly interference metrics from SFTP, writes the summary to the database, and archives history by date.",
|
||||
},
|
||||
"user_auth": "none",
|
||||
"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())
|
||||
@@ -1,794 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import ftplib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
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.data import DataBrowser, DataQuery, cell, difference, where_clause
|
||||
from etl_app.i18n import MESSAGES
|
||||
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"))
|
||||
self.assertEqual(self.runner.current["trigger"], "manual")
|
||||
self.assertFalse(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_run_that_cannot_start_is_recorded_as_failed(self) -> None:
|
||||
with mock.patch.object(self.runner, "_execute", side_effect=OSError("disk full")):
|
||||
with self.assertRaises(OSError):
|
||||
self.runner.run("manual")
|
||||
|
||||
row = self.runs.latest_finished()
|
||||
assert row is not None
|
||||
self.assertEqual((row["status"], row["detail"]), ("failed", "OSError: disk full"))
|
||||
self.assertFalse(self.runner.busy())
|
||||
|
||||
def test_worker_receives_the_cell_data_cache_directory(self) -> None:
|
||||
self.mode_file.write_text("processed", encoding="utf-8")
|
||||
with mock.patch("etl_app.runner.subprocess.Popen", wraps=subprocess.Popen) as popen:
|
||||
self.runner.run("manual")
|
||||
|
||||
command = popen.call_args.args[0]
|
||||
self.assertEqual(command[command.index("--cache") + 1], str(Path(self.temp.name) / "cache" / "cell-data"))
|
||||
|
||||
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 TranslationTest(unittest.TestCase):
|
||||
def test_both_languages_define_the_same_keys(self) -> None:
|
||||
self.assertEqual(set(MESSAGES["zh"]), set(MESSAGES["en"]))
|
||||
|
||||
|
||||
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:
|
||||
root = client.get("/", follow_redirects=False)
|
||||
self.assertEqual((root.status_code, root.headers["location"]), (307, "admin"))
|
||||
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)
|
||||
|
||||
self.assertEqual(client.get("/api/data", headers=member).status_code, 403)
|
||||
with mock.patch.object(service.data, "browse", side_effect=main.ProcessingError("db down")):
|
||||
failed = client.get("/api/data", headers=admin)
|
||||
self.assertEqual((failed.status_code, failed.json()["detail"]), (502, "db down"))
|
||||
with mock.patch.object(service.data, "browse", return_value={"items": [], "total": 0}) as browse:
|
||||
client.get("/api/data?page=3&page_size=50&network=TDD&q=abc&sort=nearby", headers=admin)
|
||||
self.assertEqual(browse.call_args.args[0], DataQuery(3, 50, "TDD", "abc", "nearby"))
|
||||
|
||||
|
||||
class FakeSelectStore:
|
||||
table = "interference_hourly_summary"
|
||||
|
||||
def __init__(self, groups: list[dict[str, object]], filtered: int | None = None) -> None:
|
||||
self.groups = groups
|
||||
self.filtered = filtered
|
||||
self.statements: list[tuple[str, int]] = []
|
||||
|
||||
def select(self, sql: str, limit: int) -> list[dict[str, object]]:
|
||||
self.statements.append((sql, limit))
|
||||
if "GROUP BY network_type" in sql:
|
||||
return self.groups
|
||||
if sql.startswith("SELECT COUNT(*)"):
|
||||
return [{"row_count": self.filtered}]
|
||||
row = {column: "" for column in main.SUMMARY_HEADER}
|
||||
row.update(
|
||||
metric_time=datetime(2026, 11, 6, 16, 0),
|
||||
network_type="TDD",
|
||||
cgi="460-00-1-2",
|
||||
interference_dbm=Decimal("-100.500"),
|
||||
prev_interference_dbm=None,
|
||||
longitude=113.25,
|
||||
nearby_count=3,
|
||||
)
|
||||
return [row]
|
||||
|
||||
|
||||
class DataBrowserTest(unittest.TestCase):
|
||||
groups = [
|
||||
{"network_type": "2.6G", "row_count": 30, "latest": "2026-11-06T16:00:00"},
|
||||
{"network_type": "TDD", "row_count": 15, "latest": datetime(2026, 11, 6, 16, 0)},
|
||||
]
|
||||
|
||||
def browser(self, store: FakeSelectStore) -> DataBrowser:
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
settings = SettingsStore(Path(temp) / "settings.json")
|
||||
settings.update(complete_settings())
|
||||
browser = DataBrowser(settings)
|
||||
browser._store_for = lambda _settings: store # type: ignore[method-assign]
|
||||
return browser
|
||||
|
||||
def test_query_normalization_rejects_unknown_values(self) -> None:
|
||||
query = DataQuery(page=0, page_size=7, network="5G", keyword=" a\x00b ", sort="drop").normalized()
|
||||
self.assertEqual(query, DataQuery(1, 20, "", "ab", "interference"))
|
||||
self.assertEqual(len(DataQuery(keyword="x" * 200).normalized().keyword), 64)
|
||||
|
||||
def test_where_clause_escapes_quotes_and_wildcards(self) -> None:
|
||||
where = where_clause(DataQuery(network="TDD", keyword="a'b%_\\"))
|
||||
self.assertEqual(
|
||||
where,
|
||||
" WHERE network_type = 'TDD' AND (cgi LIKE '%a''b\\\\%\\\\_\\\\\\\\%' OR cell_name LIKE '%a''b\\\\%\\\\_\\\\\\\\%')",
|
||||
)
|
||||
self.assertEqual(where_clause(DataQuery()), "")
|
||||
|
||||
def test_unfiltered_page_uses_group_counts_and_offset(self) -> None:
|
||||
store = FakeSelectStore(self.groups)
|
||||
result = self.browser(store).browse(DataQuery(page=2, page_size=20, sort="nearby"))
|
||||
|
||||
self.assertEqual((result["total"], result["pages"], result["page"]), (45, 3, 2))
|
||||
self.assertEqual(result["networks"], {"2.6G": 30, "TDD": 15})
|
||||
self.assertEqual(result["metric_time"], "2026-11-06 16:00:00")
|
||||
self.assertEqual(len(store.statements), 2)
|
||||
page_sql, limit = store.statements[1]
|
||||
self.assertTrue(page_sql.endswith("ORDER BY nearby_count DESC, interference_dbm DESC, cgi LIMIT 20 OFFSET 20"))
|
||||
self.assertEqual(limit, 20)
|
||||
item = result["items"][0]
|
||||
self.assertEqual(
|
||||
(item["metric_time"], item["interference_dbm"], item["prev_interference_dbm"], item["longitude"], item["nearby_count"]),
|
||||
("2026-11-06 16:00:00", "-100.5", "", "113.25", "3"),
|
||||
)
|
||||
|
||||
def test_filtered_page_counts_matches_and_clamps_page(self) -> None:
|
||||
store = FakeSelectStore(self.groups, filtered=5)
|
||||
result = self.browser(store).browse(DataQuery(page=9, network="TDD"))
|
||||
|
||||
self.assertEqual((result["total"], result["pages"], result["page"]), (5, 1, 1))
|
||||
self.assertIn("WHERE network_type = 'TDD'", store.statements[1][0])
|
||||
self.assertTrue(store.statements[2][0].endswith("LIMIT 20 OFFSET 0"))
|
||||
|
||||
def test_empty_table_skips_page_query(self) -> None:
|
||||
store = FakeSelectStore([])
|
||||
result = self.browser(store).browse(DataQuery())
|
||||
self.assertEqual((result["items"], result["total"], result["pages"]), ([], 0, 1))
|
||||
self.assertEqual(len(store.statements), 1)
|
||||
|
||||
def test_difference_marks_rises(self) -> None:
|
||||
self.assertEqual(difference("-100.5", "-103"), "+2.5")
|
||||
self.assertEqual(difference("-104", "-103.25"), "-0.75")
|
||||
self.assertEqual(difference("-104", ""), "")
|
||||
|
||||
def test_cell_formats_api_and_driver_values_alike(self) -> None:
|
||||
self.assertEqual([cell("-81.480"), cell(Decimal("-81.480")), cell("-81.000")], ["-81.48", "-81.48", "-81"])
|
||||
self.assertEqual([cell("460-00-1-2"), cell("2026-11-06T16:00:00"), cell(None)], ["460-00-1-2", "2026-11-06 16:00:00", ""])
|
||||
|
||||
|
||||
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 <DIR> 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}"
|
||||
|
||||
def delete(self, path: str) -> None:
|
||||
target = self._path(path)
|
||||
if target.is_dir():
|
||||
shutil.rmtree(target)
|
||||
elif target.exists():
|
||||
target.unlink()
|
||||
|
||||
|
||||
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, history_keep_days=0)
|
||||
)
|
||||
store = RecordingStore()
|
||||
cache = Path(temp) / "cache"
|
||||
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, cache_dir=cache), 0)
|
||||
|
||||
self.assertIn("status=processed", output.getvalue())
|
||||
# The five test workbooks have identical bytes: one is parsed, the others reuse its entry.
|
||||
self.assertIn("4 read from cache", output.getvalue())
|
||||
self.assertEqual(len(store.rows), 2)
|
||||
archived = list((root / "history" / "2026-07-31").iterdir())
|
||||
self.assertEqual(len(archived), 1)
|
||||
self.assertEqual(len(list(cache.iterdir())), 1)
|
||||
|
||||
def test_history_retention_runs_only_after_a_group_is_stored(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)
|
||||
expired = root / "history" / "2020-01-01"
|
||||
expired.mkdir(parents=True)
|
||||
settings_path = Path(temp) / "settings.json"
|
||||
SettingsStore(settings_path).update(
|
||||
complete_settings(source_root="/source", history_root="/history", history_keep_days=7)
|
||||
)
|
||||
|
||||
def run(store: RecordingStore, dry_run: bool = False) -> str:
|
||||
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):
|
||||
worker.run(settings_path, Path(temp) / "output", dry_run=dry_run)
|
||||
return output.getvalue()
|
||||
|
||||
self.assertIn("status=processed", run(RecordingStore(), dry_run=True))
|
||||
self.assertIn("status=skipped", run(RecordingStore(datetime(2026, 8, 1))))
|
||||
self.assertTrue(expired.exists())
|
||||
|
||||
stored = run(RecordingStore())
|
||||
|
||||
self.assertIn("status=processed", stored)
|
||||
self.assertIn("history_removed=/history/2020-01-01", stored)
|
||||
self.assertFalse(expired.exists())
|
||||
|
||||
def test_failed_history_retention_keeps_the_run_successful(self) -> None:
|
||||
settings = Settings(history_keep_days=7)
|
||||
output = io.StringIO()
|
||||
with mock.patch.object(main.StorageHistoryStore, "prune", side_effect=OSError("connection lost")), contextlib.redirect_stdout(
|
||||
output
|
||||
):
|
||||
worker.prune_history(mock.Mock(), settings)
|
||||
|
||||
self.assertEqual(output.getvalue(), "history_prune_error=OSError: connection lost\n")
|
||||
|
||||
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()
|
||||
+1
-106
@@ -7,7 +7,6 @@ import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
import zipfile
|
||||
|
||||
import main
|
||||
@@ -227,51 +226,6 @@ class PipelineTest(unittest.TestCase):
|
||||
|
||||
self.assertEqual(metadata["460-00-200-1"], ("113.123456", "22.654321", "0"))
|
||||
|
||||
def test_cell_data_cache_parses_each_workbook_content_once(self) -> None:
|
||||
first = create_cell_data_workbook(longitude=113.1)
|
||||
changed = create_cell_data_workbook(longitude=113.2)
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp) / "cache"
|
||||
expected = main.parse_cell_data_workbook(first, "cell-data.xlsx")
|
||||
|
||||
cold = main.CellDataCache(directory)
|
||||
self.assertEqual(main.load_cell_metadata([("cell-data.xlsx", first)], cold), expected)
|
||||
self.assertEqual(cold.hits, 0)
|
||||
self.assertEqual(len(list(directory.iterdir())), 1)
|
||||
|
||||
warm = main.CellDataCache(directory)
|
||||
with mock.patch.object(main, "parse_cell_data_workbook", side_effect=AssertionError("parsed again")):
|
||||
self.assertEqual(main.load_cell_metadata([("renamed.xlsx", first)], warm), expected)
|
||||
self.assertEqual(warm.hits, 1)
|
||||
|
||||
updated = main.CellDataCache(directory)
|
||||
metadata = main.load_cell_metadata([("cell-data.xlsx", changed)], updated)
|
||||
self.assertEqual(metadata["460-00-200-1"][0], "113.2")
|
||||
self.assertEqual(updated.hits, 0)
|
||||
self.assertEqual(len(list(directory.iterdir())), 1)
|
||||
|
||||
def test_damaged_cell_data_cache_entry_is_parsed_again(self) -> None:
|
||||
raw = create_cell_data_workbook()
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp)
|
||||
main.load_cell_metadata([("cell-data.xlsx", raw)], main.CellDataCache(directory))
|
||||
(entry,) = directory.iterdir()
|
||||
for damaged in ("{not json", '{"460-00-200-1": ["113.1"]}', "[]"):
|
||||
entry.write_text(damaged, encoding="utf-8")
|
||||
cache = main.CellDataCache(directory)
|
||||
|
||||
metadata = main.load_cell_metadata([("cell-data.xlsx", raw)], cache)
|
||||
|
||||
self.assertEqual(metadata["460-00-200-1"], ("113.123456", "22.654321", "30"))
|
||||
self.assertEqual(cache.hits, 0)
|
||||
|
||||
def test_invalid_cell_data_workbook_is_not_cached(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
directory = Path(temp) / "cache"
|
||||
with self.assertRaisesRegex(main.ProcessingError, "Invalid CellData workbook"):
|
||||
main.load_cell_metadata([("bad.xlsx", b"not a workbook")], main.CellDataCache(directory))
|
||||
self.assertFalse(directory.exists())
|
||||
|
||||
def test_nearby_count_uses_high_interference_rows_with_coordinates(self) -> None:
|
||||
rows = [
|
||||
nearby_row("a", "113.000000", "22.000000", "2.6G"),
|
||||
@@ -446,7 +400,7 @@ class PipelineTest(unittest.TestCase):
|
||||
|
||||
def test_api_history_store_creates_date_directory_and_uploads_csv(self) -> None:
|
||||
client = FakeHistoryApiClient()
|
||||
history = main.StorageHistoryStore(main.MetrixStorage(client, "stg_test"), "/history")
|
||||
history = main.ApiHistoryStore(client, "stg_test", "/history")
|
||||
metric_time = datetime(2026, 8, 6, 12, 0)
|
||||
|
||||
self.assertFalse(history.exists(metric_time))
|
||||
@@ -457,65 +411,6 @@ class PipelineTest(unittest.TestCase):
|
||||
self.assertEqual(client.uploads, [("/history/2026-08-06", "干扰数据处理结果_20260806120000.csv", b"csv-data")])
|
||||
|
||||
|
||||
class MemoryHistoryStorage:
|
||||
def __init__(self) -> None:
|
||||
self.nodes: dict[str, dict[str, object]] = {"/history": {"dir": True}}
|
||||
|
||||
def add_dir(self, path: str) -> None:
|
||||
self.nodes[path] = {"dir": True}
|
||||
|
||||
def add_file(self, path: str) -> None:
|
||||
self.nodes[path] = {"dir": False}
|
||||
|
||||
def list_dir(self, path: str) -> list[dict[str, object]]:
|
||||
prefix = path.rstrip("/")
|
||||
result = []
|
||||
for item, node in self.nodes.items():
|
||||
parent, _, name = item.rpartition("/")
|
||||
if parent == prefix and name:
|
||||
result.append({"name": name, "path": item, "is_dir": node["dir"], "size": 1})
|
||||
return result
|
||||
|
||||
def delete(self, path: str) -> None:
|
||||
prefix = path.rstrip("/")
|
||||
for item in [key for key in self.nodes if key == prefix or key.startswith(prefix + "/")]:
|
||||
del self.nodes[item]
|
||||
|
||||
|
||||
class HistoryRetentionTest(unittest.TestCase):
|
||||
def test_prune_uses_directory_and_file_names(self) -> None:
|
||||
storage = MemoryHistoryStorage()
|
||||
storage.add_dir("/history/2026-11-01")
|
||||
storage.add_file("/history/2026-11-01/干扰数据处理结果_20261101080000.csv")
|
||||
storage.add_dir("/history/2026-11-09")
|
||||
storage.add_file("/history/2026-11-09/干扰数据处理结果_20261109100000.csv")
|
||||
storage.add_file("/history/2026-11-09/干扰数据处理结果_20261001120000.csv")
|
||||
storage.add_dir("/history/readme")
|
||||
storage.add_file("/history/notes.txt")
|
||||
history = main.StorageHistoryStore(storage, "/history")
|
||||
|
||||
removed = history.prune(7, today=datetime(2026, 11, 9).date())
|
||||
|
||||
self.assertEqual(
|
||||
removed,
|
||||
[
|
||||
"/history/2026-11-01",
|
||||
"/history/2026-11-09/干扰数据处理结果_20261001120000.csv",
|
||||
],
|
||||
)
|
||||
self.assertNotIn("/history/2026-11-01", storage.nodes)
|
||||
self.assertIn("/history/2026-11-09/干扰数据处理结果_20261109100000.csv", storage.nodes)
|
||||
self.assertIn("/history/readme", storage.nodes)
|
||||
self.assertIn("/history/notes.txt", storage.nodes)
|
||||
|
||||
def test_zero_keep_days_deletes_nothing(self) -> None:
|
||||
storage = MemoryHistoryStorage()
|
||||
storage.add_dir("/history/2020-01-01")
|
||||
history = main.StorageHistoryStore(storage, "/history")
|
||||
self.assertEqual(history.prune(0, today=datetime(2026, 11, 9).date()), [])
|
||||
self.assertIn("/history/2020-01-01", storage.nodes)
|
||||
|
||||
|
||||
class RecordingStore:
|
||||
def __init__(self, latest_time: datetime | None = None, stored_rows: list[dict[str, str]] | None = None) -> None:
|
||||
self.rows: list[dict[str, str]] = []
|
||||
|
||||
Reference in New Issue
Block a user