Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2eda0a0887 |
@@ -1,7 +1,3 @@
|
||||
*
|
||||
!Dockerfile
|
||||
!requirements.txt
|
||||
!requirements-app.txt
|
||||
!main.py
|
||||
!etl_app/
|
||||
etl_app/**/__pycache__
|
||||
|
||||
@@ -7,4 +7,3 @@ runtime_config.py
|
||||
output/
|
||||
dist/
|
||||
aidocs/
|
||||
Temp/
|
||||
|
||||
@@ -73,37 +73,6 @@ python main.py --source-dir C:\path\to\mock-or-exported-tree --output-dir output
|
||||
|
||||
Use `--window 2026073110001100` to select the natural 15-minute group containing that source start time. Without it, the newest observed source start time determines the group. Incomplete groups wait and never fall back.
|
||||
|
||||
## Metrix hosted app
|
||||
|
||||
The app mode runs InterferenceETL as one long-lived container in Metrix App Hosting. A FastAPI + NiceGUI admin page at `/admin` (Metrix account, admin role only) edits every setting, shows the live log, 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 schedule runs inside the same container with APScheduler (fixed interval in minutes or a 5-field cron expression, timezone `Asia/Shanghai`). Each run is a child Python process inside that container, so no extra containers are started; one run at a time, with a per-run timeout.
|
||||
|
||||
Settings live on the app data volume and are edited only through the admin page:
|
||||
|
||||
- Source storage: Metrix storage API, or direct FTP / SFTP (host, port, account, FTP encoding and passive mode).
|
||||
- Database: Metrix database connection API, or direct MySQL (host, port, account). Database and table names are configurable.
|
||||
- Metrix API address and token are required only when either side uses the Metrix API.
|
||||
- Source root, history CSV directory (optional), CellData directories, lookback days and retention.
|
||||
|
||||
Passwords and tokens are written to `/data/settings.json` (mode 0600) and never returned to the browser; a blank field keeps the saved value. Run records are in `/data/runs.db`, run logs in `/data/logs/`, local outputs in `/data/output/` (newest 48 kept by default).
|
||||
|
||||
Build the app bundle on a machine with docker, then upload it in App Hosting:
|
||||
|
||||
```powershell
|
||||
python scripts\package_metrix.py
|
||||
```
|
||||
|
||||
The bundle `dist/metrix/interference-etl-<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.
|
||||
|
||||
For local development of the app:
|
||||
|
||||
```powershell
|
||||
python -m pip install -r requirements-app.txt
|
||||
$env:METRIX_APP_DATA_DIR = "Temp\appdata"; $env:ETL_DEV_ADMIN = "1"; $env:PORT = "18090"
|
||||
python -m etl_app.server
|
||||
```
|
||||
|
||||
`ETL_DEV_ADMIN=1` grants admin access only when no Metrix proxy token is configured.
|
||||
|
||||
## Metrix Script Management
|
||||
|
||||
The target server is offline. Build the dependency image locally, then generate a self-contained Script Management upload ZIP:
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
# InterferenceETL project context
|
||||
|
||||
## 2026-07-31: Initial hourly interference pipeline
|
||||
|
||||
- This repository is developed as the `InterferenceETL` submodule under Metrix and is intended to run later in Metrix Script Management on an hourly schedule.
|
||||
- `main.py` reads the configured Metrix SFTP storage through Metrix API Token authentication or a local directory for tests. It selects the newest hour containing all seven known interference source types and falls back from a newer incomplete hour.
|
||||
- Each selected ZIP must contain exactly one XLSX. The script strictly validates the known `Sheet0` header, writes one full UTF-8-BOM CSV per source type, and writes one merged CSV containing only `hour_start`, `hour_end`, `cgi`, `cell_name`, and `interference_dbm`.
|
||||
- NR CGI uses `{gNBplmn}-{gNBId}-{cellId}`. All 4G sources use `460-00-{node}-{cell}`, mapped to the actual node and cell column names in each workbook schema.
|
||||
- Runs are idempotent at the output-window directory level. Generation happens in a scoped temporary directory, then replaces only the same window below the configured output root. Source storage is never modified.
|
||||
- `manifest.json` records input paths, sizes, SHA-256 hashes, row counts, warnings, generated files, and the database write result for ingestion auditing.
|
||||
- The Metrix script container needs `openpyxl==3.1.5`, bridge networking, and `python main.py`. Runtime-specific source and output settings may be injected through project environment settings.
|
||||
- Read-only validation against the current Metrix storage selected window `2026073110001100`, processed all seven source ZIP files, and produced 1,831 summary rows. Per-source row counts were `7 / 804 / 45 / 86 / 700 / 164 / 25` in `EXPECTED_TYPES` order; sampled CGI, cell name, and interference values matched the source workbooks.
|
||||
- `interference-etl-runtime:1.1` is now a local build helper only. Script projects use the standard `python:3.13.11-slim` image and upload `dist/InterferenceETL-offline-1.1.zip`, which vendors `openpyxl` and `et_xmlfile` at the workspace root.
|
||||
- Six Mock tests pass on Windows Python and inside the runtime image. They cover complete-hour fallback, strict schema rejection, summary extraction, cross-midnight window parsing, transactional database replacement, and rollback protection.
|
||||
|
||||
## 2026-07-31: Latest-hour MySQL retention
|
||||
|
||||
- Scheduled runs write to MySQL by default. File-only development runs must explicitly pass `--no-database`; the MySQL host, port, account, password, database, and table are constants at the top of `main.py`.
|
||||
- The fixed script-owned database is `interference_etl` and the fixed table is `interference_hourly_summary`. Its only time column is `metric_time DATETIME`, populated from the source KPI `开始时间`, so users can identify the hour represented by every row.
|
||||
- One transaction deletes the selected hour for idempotent refresh, inserts its complete batch, then deletes every other database hour. Any failure rolls back the data changes, and an older selected hour cannot replace a newer hour already stored.
|
||||
- Database retention never deletes or modifies Metrix Storage/SFTP source ZIP or XLSX files. Generated CSV retention remains a separate pending decision.
|
||||
|
||||
## 2026-07-31: Self-contained Script Management package
|
||||
|
||||
- `scripts/build_offline_package.py` copies the three runtime distributions from the verified dependency image, adds the application files and `__main__.py`, and creates a ZIP that Metrix can extract without preserving executable bits or symlinks. The archive can also run directly as `python InterferenceETL-offline-1.1.zip` when a Script Management server stores the upload without extracting it.
|
||||
- The builder runs an import check inside `python:3.13.11-slim`; the package therefore needs neither a custom server image nor online package installation.
|
||||
- The builder excludes bytecode caches, and the ignored `dist/` directory is the only location for this generated package.
|
||||
|
||||
## 2026-07-31: Fixed CGI and database configuration
|
||||
|
||||
- Replaced the NR `masterOperatorId` passthrough with `gNBplmn-gNBId-cellId`. The remaining five 4G sources use the fixed `460-00` prefix plus their schema-specific base-station and cell ID columns.
|
||||
- Removed CGI PLMN and MySQL connection command-line/environment options. Database configuration now lives as a small constant block at the top of `main.py`; the verified bridge-network address is `172.17.0.1:3306` because `ShareMySQL` DNS is unavailable from the default script network.
|
||||
- Read-only online validation selected complete window `2026073115001600` and checked all 2,275 generated CGI values against the seven converted source CSV files. Per-source row counts were `6 / 1,198 / 48 / 91 / 731 / 179 / 22` in `EXPECTED_TYPES` order.
|
||||
- Before the dedicated-database correction, a connection-only check returned the platform database `metrix`; that check did not create a table or modify data. Production use now targets only `interference_etl`.
|
||||
|
||||
## 2026-08-03: Dedicated database initialization
|
||||
|
||||
- InterferenceETL no longer writes into the Metrix platform database. Its fixed database is `interference_etl`, while the table remains `interference_hourly_summary`.
|
||||
- The default MySQL path first connects without selecting a database, runs `CREATE DATABASE IF NOT EXISTS interference_etl` with `utf8mb4`, then reconnects to that database and creates the table if needed. The configured account therefore needs database creation permission on first run.
|
||||
- Offline dependencies are stored below the workspace `vendor/` directory instead of separate package directories at the project root. `main.py` prepends this directory to `sys.path`, so the run command remains `python main.py`.
|
||||
- Summary CSV rows and database rows do not expose `source_type` or `source_path`. The database primary key is `(metric_time, cgi)`; the current online hour was checked for CGI uniqueness before migrating from the former source-aware key.
|
||||
|
||||
## 2026-08-03: CellData coordinate enrichment
|
||||
|
||||
- Each run selects the latest filename-dated XLSX from five fixed CellData directories for 5G, 700M, reverse-activated 5G, TDD LTE, and FDD LTE. The filename date must end in `YYYYMMDD.xlsx`; source files remain read-only.
|
||||
- CellData workbooks use sheet `小区信息表` and required columns `eNB/gNB`, `CI`, `经度`, and `纬度`. CellData CGI is always `460-00-{eNB/gNB}-{CI}` and conflicting coordinates for the same CGI stop the run instead of silently overwriting data.
|
||||
- The summary CSV now ends with `longitude,latitude`. The script-owned `interference_hourly_summary` table has nullable `DECIMAL(10,6)` columns with the same names; existing tables are migrated automatically and unmatched CGI values are stored as `NULL`.
|
||||
- Read-only validation of the five `20260728` workbooks produced 66,250 unique CGI coordinates with no conflicts. Against the sampled latest-hour summary, 1,529 of 1,539 rows matched (99.35%); the remaining 10 rows correctly stay empty.
|
||||
|
||||
## 2026-08-03: Metrix API database output
|
||||
|
||||
- Storage reads and database writes now share one API Token authenticated `MetrixApiClient`. Direct PyMySQL access, MySQL host/account/password constants, and the `PyMySQL` offline dependency were removed.
|
||||
- `ApiSummaryStore` creates the dedicated `interference_etl` database and `interference_hourly_summary` table through the Database API. It checks the latest stored hour, then uses `/run-script` with `single_session=true` and an explicit transaction to refresh one complete hour and delete all others.
|
||||
- API address, Token, and ShareMySQL `conn_id` are constants loaded from ignored `runtime_config.py`; the tracked `runtime_config.example.py` documents the required names. The current API address is `http://188.5.127.115:18271`.
|
||||
- Deployment remains SSH based. The Metrix Script Management API is not used for uploads, execution, or log inspection.
|
||||
- Eleven containerized unit tests cover the pipeline, CellData enrichment, API database transaction, newer-hour protection, decimal validation, and API failure propagation.
|
||||
- SSH deployment and a real Metrix runner execution succeeded with run `eead5c315fb04836a6327be201f561e6`. Window `2026080310001100` produced 1,991 rows, matched 1,977 coordinates, left 14 unmatched, and deleted 1,789 rows from the prior hour.
|
||||
- Final API verification found exactly one stored hour (`2026-08-03 10:00:00`) and exactly six columns: `metric_time`, `cgi`, `cell_name`, `interference_dbm`, `longitude`, and `latitude`. The obsolete online source backup and environment-level API URL/Token entries were removed after the successful run.
|
||||
|
||||
## 2026-08-03: CellData azimuth enrichment
|
||||
|
||||
- All five latest CellData workbooks expose direction angle through column `方向角`. CellData metadata now maps each `460-00-{eNB/gNB}-{CI}` to longitude, latitude, and azimuth.
|
||||
- Summary CSV and `interference_hourly_summary` add `azimuth`. The database type is `DECIMAL(6,2) NOT NULL DEFAULT 0`; existing tables add the column automatically. Empty CellData direction angles and unmatched CGI values both become `0`, while unmatched coordinates remain empty/NULL.
|
||||
- Real CellData validation loaded 66,524 CGI metadata rows: 54,129 non-zero azimuth values and 12,395 zero/default values. Full window `2026080313001400` produced 1,863 summary rows, including 1,677 non-zero azimuth values and 186 zero values.
|
||||
- SSH deployment run `e5462179fa8c4f9f9c2dfb2e4541e048` succeeded. Database API verification found exactly one hour (`2026-08-03 13:00:00`), 1,863 rows, and columns `metric_time,cgi,cell_name,interference_dbm,longitude,latitude,azimuth`.
|
||||
- Twelve containerized unit tests pass, including empty azimuth defaulting and CellData metadata conflict detection.
|
||||
|
||||
## 2026-08-05: Network type and high-interference filtering
|
||||
|
||||
- Summary CSV and `interference_hourly_summary` add `network_type`: the two `5G...` source types map to `2.6G`, the two `700M...` source types map to `700M`, and SDR FDD/TDD plus reverse-activated RD map to `4G`.
|
||||
- Only high-interference rows enter the summary and database. `2.6G` keeps values greater than or equal to `-107 dBm`; `700M` and `4G` keep values greater than or equal to `-110 dBm`. Values strictly below those thresholds are discarded; equal values remain.
|
||||
- The seven converted source CSV files remain unfiltered source conversions. `manifest.json` and stdout record `threshold_filtered_rows` for the summary filter.
|
||||
- Real read-only validation of window `2026080514001500` reduced 1,868 source rows to 1,109 summary rows: `2.6G=137`, `700M=108`, `4G=864`, with 759 lower-interference rows removed. Thirteen containerized unit tests pass.
|
||||
- SSH deployment run `98a44e88b3684bd1b9ad7edcb866fb17` succeeded for the same window. The database contains exactly one hour (`2026-08-05 14:00:00`) and 1,109 rows; grouped API verification found zero threshold violations and confirmed minimums `2.6G=-106.970`, `700M=-110.000`, and `4G=-109.996`.
|
||||
|
||||
## 2026-08-06: Nearby high-interference cell count
|
||||
|
||||
- Summary CSV and `interference_hourly_summary` add `nearby_count`, the number of other retained high-interference cells within 1 km during the same selected hour. Counts include all network types, exclude the row itself, include the exact 1 km boundary, and default to `0` when coordinates are unavailable.
|
||||
- Candidate lookup uses a dependency-free 1 km Earth-centered three-dimensional grid index. Only the current and 26 adjacent buckets are checked, then Haversine distance confirms the exact radius; this avoids a full all-pairs scan while preserving distance accuracy.
|
||||
- Unit tests pass in both the project virtual environment and `interference-etl-runtime:1.1` image. A read-only real run for window `2026080613001400` produced 1,116 rows, including 1,110 with coordinates, 925 with non-zero nearby counts, and a maximum count of 39. All 1,116 indexed results matched a separate brute-force comparison, which found 3,973 qualifying pairs.
|
||||
- SSH deployment and Metrix runner execution `8f2fd51d7de14c93b4b0eb9bee8fafa0` succeeded for the same window. Database API verification found only `2026-08-06 13:00:00`, with 1,116 rows, 925 non-zero counts, a maximum of 39, and 3,973 nearby pairs. All six rows without coordinates have count `0`.
|
||||
|
||||
## 2026-08-06: Adaptive source waiting and history export
|
||||
|
||||
- Source recognition now fixes only the seven known prefixes and final `_YYYYMMDDHHMMHHMM.zip`; middle text may change with provider granularity. The first 12 digits are rounded down to natural 15-minute boundaries, while the final four end-time digits do not participate in grouping.
|
||||
- Each run follows only the group containing the globally newest source start time. It does not fall back or backfill older groups. Missing sources or no matching files produce `status=waiting` and a successful exit; storage API failures remain task failures. Multiple files from one source in a group select the latest source start time.
|
||||
- All workbook row start times must round into the target group. Result CSV and database rows use one normalized `metric_time` and the database result columns only; `hour_start` and `hour_end` were removed from summary CSV output.
|
||||
- Database time is checked before source ZIP and CellData downloads. A newer or equal database time skips source processing. Successful database output is archived through the Storage API under `干扰历史数据/YYYY-MM-DD/干扰数据处理结果_YYYYMMDDHHMMSS.csv`; an equal database time with a missing/empty history file is exported from the database and repaired.
|
||||
- Nineteen tests pass on Windows and in the offline runtime image. Live read-only selection saw incomplete newest group `2026-08-06 15:00:00`, correctly waited for missing `5G下FDD干扰监控`, and did not produce output. Explicit read-only validation of complete group `2026-08-06 14:00:00` produced 1,092 rows with one normalized `metric_time` and the expected nine-column result schema.
|
||||
- SSH deployment run `7a7c0bba3a0c41f5a5a9e83ad25ff2fd` processed the completed `2026-08-06 15:00:00` group successfully. It retained 1,082 high-interference rows, removed 853 lower-interference rows, matched coordinates for 1,074 rows, left 8 unmatched, and replaced 1,116 rows from the previous database time.
|
||||
- Database verification found only `2026-08-06 15:00:00` and 1,082 rows. Of those, 887 have non-zero `nearby_count`, the maximum is 40, and all 8 rows without coordinates remain valid. The history CSV was uploaded with the expected nine columns and 1,082 rows to `干扰历史数据/2026-08-06/干扰数据处理结果_20260806150000.csv`.
|
||||
- A second run `e1c81ada63234b3c85a377e1b46a1370` returned success with `status=skipped`, confirming that an existing database time plus a non-empty history file avoids duplicate work.
|
||||
- `MetrixApiClient` uses a proxy-free opener because the API is an intranet service and the Windows system proxy previously converted direct requests into `502` responses. The verified Metrix API remains `http://188.5.127.115:18271`; external port `9082` currently serves CapacityReport and must not be used by this script.
|
||||
|
||||
## 2026-08-07: Previous-period comparison fields
|
||||
|
||||
- Summary CSV, database table, and history CSV add nullable previous-period fields: `prev_interference_dbm` and `prev_nearby_count`.
|
||||
- Before downloading source ZIP/XLSX files, the runner still checks the current database time. When a newer source group is being processed, it reads the currently retained database rows before replacement and maps them by CGI. The current row receives the previous row's `interference_dbm` and `nearby_count`; unmatched CGI values remain empty in CSV and `NULL` in the database.
|
||||
- On the first run, when the database has no previous group, both fields remain empty/NULL. Existing-table migration adds both columns automatically. Twenty containerized tests pass, including first-run empty values, CGI matching, and nullable column migration.
|
||||
- Offline package SHA-256 is `74EEA84058C5F14E7108B840561C070DC47752D67FEC68262F0CC6C78EE8EC0D`. SSH deployment run `984ffc6f98024a2d81b63d4359aabc71` processed `2026-08-07 07:00:00` with 820 rows and deleted 1,137 rows from the prior database time.
|
||||
- Production verification matched 616 current CGI values to the previous period and left both previous fields NULL for the remaining 204 CGI values. `prev_nearby_count` matched exactly; `prev_interference_dbm` uses the table's existing `DECIMAL(10,3)` precision. Repeat run `6b38030f6d9e4ab1a0ee6a4ba0dc5d6e` returned `status=skipped`.
|
||||
|
||||
## 2026-08-07: GBK Storage history output
|
||||
|
||||
- Only final history CSV files uploaded to Metrix Storage use GBK without a UTF-8 BOM, including database-based history repairs. The seven local source conversions and local merged summary remain UTF-8 with BOM; `manifest.json`, API JSON, and database character sets remain unchanged.
|
||||
- Production data contains non-breaking spaces (`U+00A0`), which Python's GBK codec cannot encode. History-output normalization converts them to ordinary spaces while keeping strict encoding for every other unsupported character.
|
||||
- Encoding behavior is separated through `LOCAL_CSV_ENCODING` and `HISTORY_CSV_ENCODING`; tests verify the local UTF-8 BOM and GBK history parsing independently.
|
||||
- Twenty-one containerized tests and offline-package execution pass. The deployed package SHA-256 is `11B0010E8FDFEC32058BC8B282E5A5608FC92C48572611A3F9F4632962C18D98`.
|
||||
- The current `2026-08-07 14:00:00` database result was exported directly through the history-only path and replaced in Storage as a verified GBK CSV: 1,082 rows, 150,251 bytes, no UTF-8 BOM, and the expected eleven columns. The temporary UTF-8 backup was deleted after validation.
|
||||
- The newer `2026-08-07 15:00:00` source group currently contains duplicate CGI rows, for example `460-00-122737-22`. Its database transaction rolled back on the existing `(metric_time, cgi)` primary key, so the retained `14:00` database and history result were not replaced. Duplicate-row selection requires a separate business rule.
|
||||
|
||||
## 2026-08-11: Per-network-type nearby counts
|
||||
|
||||
- Summary CSV, database table, and history CSV add `nearby_26g`, `nearby_700m`, `nearby_tdd`, and `nearby_fdd`: the same 1 km high-interference neighbors split by the neighbor's `network_type`. Each defaults to `0` and the four values always sum to `nearby_count`.
|
||||
- Previous-period fields `prev_nearby_26g`, `prev_nearby_700m`, `prev_nearby_tdd`, and `prev_nearby_fdd` follow the `prev_nearby_count` rules: matched by CGI from the previously retained database time, empty/`NULL` when unmatched or on the first run. On the first run after this upgrade the previous rows only have `NULL` in the new columns, so the previous split fields stay empty for that one period and self-heal afterwards.
|
||||
- Existing tables migrate automatically: current count columns are `INT NOT NULL DEFAULT 0`, previous count columns are `INT NULL`. The history export SELECT is now generated from `SUMMARY_HEADER`, so result columns stay in one place. Twenty-two tests pass locally and in the runtime image.
|
||||
- Deployed package SHA-256 is `638EEC791FACA55937FCF335402F40776B0749375216D27FBB9F8F1864007EBE`. A first run (`9ccdc7cba5bc48fd8c57a698de3dde84`) returned `status=skipped` and migrated the schema; all eight new columns were confirmed through the Database API.
|
||||
- Because the `16:00` sources were late, the user chose to truncate `interference_hourly_summary` and reprocess the `15:00` group instead of waiting. Run `23d870b5d1434a548520c7fc2413e2ba` inserted 1,062 rows (869 threshold-filtered, 0 duplicate CGI, 1,059 coordinates matched).
|
||||
- Production verification: every row satisfies `nearby_26g + nearby_700m + nearby_tdd + nearby_fdd = nearby_count` (totals 847/216/1,194/3,229 = 5,486); cross-type pair sums are symmetric; `network_type` contains only `2.6G=145`, `700M=68`, `TDD=206`, `FDD=643`. The history CSV was rewritten in GBK with the nineteen-column header and 1,062 rows.
|
||||
- The reprocessed batch has empty previous-period fields by design because the `14:00` data no longer existed; from the next group onward the previous fields, including the new splits, populate normally.
|
||||
|
||||
## 2026-08-11: Network type relabeled to 2.6G/700M/TDD/FDD
|
||||
|
||||
- `network_type` keeps its column name but now labels radio type per source prefix: `5G干扰监控` is `2.6G` (the user treats 2.6G as the unambiguous 5G label because 700M is also 5G), `700M干扰监控` is `700M`, `SDR_TDD干扰监控` and `反开RD干扰监控` are `TDD`, and the three FDD-schema sources (`SDR_FDD干扰监控`, `5G下FDD干扰监控`, `700M下FDD干扰监控`) are `FDD`. The old `2.6G/700M/4G` grouping is gone.
|
||||
- Real source filenames only carry these keywords in the fixed prefix; the middle text (for example `LWP_每小时_过滤110`) has no usable network keyword.
|
||||
- High-interference thresholds are unchanged and now keyed per source type through `MIN_INTERFERENCE_BY_SOURCE`: the two 5G-directory sources keep `-107` and the other five keep `-110`, so relabeling `5G下FDD干扰监控` to `FDD` does not change which rows are kept.
|
||||
- No database migration is needed: the column type stays `VARCHAR(16)` and old-label rows disappear on the next successful replacement run. Twenty-two tests pass locally.
|
||||
|
||||
## 2026-08-07: Duplicate CGI selection
|
||||
|
||||
- Retained high-interference rows are deduplicated by CGI before nearby counting and database insertion. When duplicates exist, the row with the numerically largest `interference_dbm` is kept; equal values keep the first encountered row. Converted source CSVs remain complete.
|
||||
- The deduplication count is recorded as `duplicate_cgi_rows` in `manifest.json` and stdout. This prevents the existing `(metric_time, cgi)` database primary key from failing and prevents duplicate source rows from inflating `nearby_count`.
|
||||
- Deployment package from commit `bb0e3d0` has SHA-256 `ED5B5C9A543C9E3283642D6A76D6693A200DA938B28449C09CEE2FBCED534121`. Successful run `068761c633634c4fb1a66aff921c62ed` processed `2026-08-07 15:00:00`: 895 rows filtered by threshold, 582 duplicate CGI rows removed, 1,197 rows inserted, and 1,082 old rows deleted.
|
||||
- Final Storage history verification found 1,197 rows, eleven expected columns, GBK encoding without a UTF-8 BOM, and one metric time `2026-08-07 15:00:00`. A subsequent manual run `fc38be72da6d496ca5e84e529f79ab53` returned `status=skipped`.
|
||||
@@ -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.0"
|
||||
@@ -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,253 +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
|
||||
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
|
||||
import main
|
||||
|
||||
TIMEZONE = os.getenv("TZ") or "Asia/Shanghai"
|
||||
SECRET_FIELDS = ("metrix_token", "remote_password", "mysql_password")
|
||||
STORAGE_MODES = ("metrix", "ftp", "sftp")
|
||||
DATABASE_MODES = ("metrix", "mysql")
|
||||
SCHEDULE_MODES = ("interval", "cron")
|
||||
FTP_ENCODINGS = ("utf-8", "gbk", "gb18030")
|
||||
DEFAULT_PORTS = {"ftp": 21, "sftp": 22}
|
||||
|
||||
|
||||
def data_dir() -> Path:
|
||||
return Path(os.getenv("METRIX_APP_DATA_DIR") or "data").resolve()
|
||||
|
||||
|
||||
@dataclass
|
||||
class Settings:
|
||||
schedule_enabled: bool = False
|
||||
schedule_mode: str = "interval"
|
||||
interval_minutes: int = 2
|
||||
cron_expression: str = "*/15 * * * *"
|
||||
timeout_minutes: int = 30
|
||||
|
||||
metrix_url: str = "http://188.5.127.115:18271"
|
||||
metrix_token: str = ""
|
||||
|
||||
storage_mode: str = "metrix"
|
||||
metrix_storage_id: str = main.DEFAULT_STORAGE_ID
|
||||
remote_host: str = ""
|
||||
remote_port: int = 21
|
||||
remote_username: str = ""
|
||||
remote_password: str = ""
|
||||
ftp_encoding: str = "utf-8"
|
||||
ftp_passive: bool = True
|
||||
|
||||
source_root: str = main.DEFAULT_ROOT
|
||||
history_enabled: bool = True
|
||||
history_root: str = main.DEFAULT_HISTORY_ROOT
|
||||
lookback_days: int = 3
|
||||
cell_data_directories: list[str] = field(default_factory=lambda: list(main.CELL_DATA_DIRECTORIES))
|
||||
|
||||
database_mode: str = "metrix"
|
||||
metrix_database_id: str = ""
|
||||
mysql_host: str = ""
|
||||
mysql_port: int = 3306
|
||||
mysql_username: str = ""
|
||||
mysql_password: str = ""
|
||||
database_name: str = main.DATABASE_NAME
|
||||
table_name: str = main.DATABASE_TABLE
|
||||
|
||||
keep_outputs: int = 48
|
||||
keep_runs: int = 2000
|
||||
|
||||
def uses_metrix_api(self) -> bool:
|
||||
return self.storage_mode == "metrix" or self.database_mode == "metrix"
|
||||
|
||||
|
||||
FIELD_NAMES = {item.name for item in fields(Settings)}
|
||||
|
||||
|
||||
class SettingsError(ValueError):
|
||||
def __init__(self, key: str, field_name: str = "", **params: object) -> None:
|
||||
super().__init__(f"{field_name}: {key}" if field_name else key)
|
||||
self.key = key
|
||||
self.field = field_name
|
||||
self.params = params
|
||||
|
||||
|
||||
def validate(data: dict[str, Any], current: Settings) -> Settings:
|
||||
merged = asdict(current)
|
||||
for name, value in data.items():
|
||||
if name not in FIELD_NAMES:
|
||||
continue
|
||||
if name in SECRET_FIELDS and (value is None or str(value) == ""):
|
||||
continue
|
||||
merged[name] = value
|
||||
values = {
|
||||
"schedule_enabled": _bool(merged["schedule_enabled"]),
|
||||
"schedule_mode": _choice(merged, "schedule_mode", SCHEDULE_MODES),
|
||||
"interval_minutes": _int(merged, "interval_minutes", 1, 1440),
|
||||
"cron_expression": _text(merged, "cron_expression"),
|
||||
"timeout_minutes": _int(merged, "timeout_minutes", 1, 1440),
|
||||
"metrix_url": _text(merged, "metrix_url").rstrip("/"),
|
||||
"metrix_token": _text(merged, "metrix_token"),
|
||||
"storage_mode": _choice(merged, "storage_mode", STORAGE_MODES),
|
||||
"metrix_storage_id": _text(merged, "metrix_storage_id"),
|
||||
"remote_host": _text(merged, "remote_host"),
|
||||
"remote_port": _int(merged, "remote_port", 1, 65535),
|
||||
"remote_username": _text(merged, "remote_username"),
|
||||
"remote_password": str(merged["remote_password"] or ""),
|
||||
"ftp_encoding": _choice(merged, "ftp_encoding", FTP_ENCODINGS),
|
||||
"ftp_passive": _bool(merged["ftp_passive"]),
|
||||
"source_root": _remote_path(merged, "source_root"),
|
||||
"history_enabled": _bool(merged["history_enabled"]),
|
||||
"history_root": _remote_path(merged, "history_root"),
|
||||
"lookback_days": _int(merged, "lookback_days", 1, 31),
|
||||
"cell_data_directories": _directories(merged["cell_data_directories"]),
|
||||
"database_mode": _choice(merged, "database_mode", DATABASE_MODES),
|
||||
"metrix_database_id": _text(merged, "metrix_database_id"),
|
||||
"mysql_host": _text(merged, "mysql_host"),
|
||||
"mysql_port": _int(merged, "mysql_port", 1, 65535),
|
||||
"mysql_username": _text(merged, "mysql_username"),
|
||||
"mysql_password": str(merged["mysql_password"] or ""),
|
||||
"database_name": _identifier(merged, "database_name"),
|
||||
"table_name": _identifier(merged, "table_name"),
|
||||
"keep_outputs": _int(merged, "keep_outputs", 1, 1000),
|
||||
"keep_runs": _int(merged, "keep_runs", 50, 100000),
|
||||
}
|
||||
settings = Settings(**values)
|
||||
if settings.schedule_mode == "cron":
|
||||
try:
|
||||
CronTrigger.from_crontab(settings.cron_expression, timezone=TIMEZONE)
|
||||
except ValueError as exc:
|
||||
raise SettingsError("invalidCron", "cron_expression") from exc
|
||||
if settings.uses_metrix_api():
|
||||
if not re.match(r"^https?://[^\s/]+", settings.metrix_url):
|
||||
raise SettingsError("invalidUrl", "metrix_url")
|
||||
_require(settings, "metrix_token")
|
||||
if settings.storage_mode == "metrix":
|
||||
_require(settings, "metrix_storage_id")
|
||||
else:
|
||||
_require(settings, "remote_host")
|
||||
if settings.database_mode == "metrix":
|
||||
_require(settings, "metrix_database_id")
|
||||
else:
|
||||
_require(settings, "mysql_host")
|
||||
_require(settings, "mysql_username")
|
||||
return settings
|
||||
|
||||
|
||||
def public_view(settings: Settings) -> dict[str, Any]:
|
||||
payload = asdict(settings)
|
||||
for name in SECRET_FIELDS:
|
||||
payload[f"has_{name}"] = bool(payload[name])
|
||||
payload[name] = ""
|
||||
return payload
|
||||
|
||||
|
||||
class SettingsStore:
|
||||
def __init__(self, path: Path) -> None:
|
||||
self.path = path
|
||||
self._lock = threading.Lock()
|
||||
self._settings = self._load()
|
||||
|
||||
def get(self) -> Settings:
|
||||
with self._lock:
|
||||
return replace(self._settings, cell_data_directories=list(self._settings.cell_data_directories))
|
||||
|
||||
def update(self, data: dict[str, Any]) -> Settings:
|
||||
with self._lock:
|
||||
settings = validate(data, self._settings)
|
||||
self._write(settings)
|
||||
self._settings = settings
|
||||
return replace(settings, cell_data_directories=list(settings.cell_data_directories))
|
||||
|
||||
def configured(self) -> bool:
|
||||
try:
|
||||
validate({}, self.get())
|
||||
except SettingsError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def _load(self) -> Settings:
|
||||
if not self.path.is_file():
|
||||
return Settings()
|
||||
raw = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
defaults = asdict(Settings())
|
||||
defaults.update({key: value for key, value in raw.items() if key in FIELD_NAMES})
|
||||
return Settings(**defaults)
|
||||
|
||||
def _write(self, settings: Settings) -> None:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temp = self.path.with_name(f".{self.path.name}.tmp")
|
||||
handle = os.open(temp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
||||
with os.fdopen(handle, "w", encoding="utf-8") as file:
|
||||
json.dump(asdict(settings), file, ensure_ascii=False, indent=2)
|
||||
file.write("\n")
|
||||
os.replace(temp, self.path)
|
||||
|
||||
|
||||
def _require(settings: Settings, name: str) -> None:
|
||||
if not getattr(settings, name):
|
||||
raise SettingsError("required", name)
|
||||
|
||||
|
||||
def _text(values: dict[str, Any], name: str) -> str:
|
||||
return str(values[name] or "").strip()
|
||||
|
||||
|
||||
def _bool(value: object) -> bool:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in ("1", "true", "yes", "on")
|
||||
return bool(value)
|
||||
|
||||
|
||||
def _choice(values: dict[str, Any], name: str, options: tuple[str, ...]) -> str:
|
||||
value = _text(values, name)
|
||||
if value not in options:
|
||||
raise SettingsError("invalidChoice", name)
|
||||
return value
|
||||
|
||||
|
||||
def _int(values: dict[str, Any], name: str, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
number = int(float(values[name]))
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise SettingsError("range", name, min=minimum, max=maximum) from exc
|
||||
if not minimum <= number <= maximum:
|
||||
raise SettingsError("range", name, min=minimum, max=maximum)
|
||||
return number
|
||||
|
||||
|
||||
def _remote_path(values: dict[str, Any], name: str) -> str:
|
||||
value = _text(values, name)
|
||||
if not value.startswith("/"):
|
||||
raise SettingsError("absolutePath", name)
|
||||
return value.rstrip("/") or "/"
|
||||
|
||||
|
||||
def _directories(value: object) -> list[str]:
|
||||
items = value.splitlines() if isinstance(value, str) else list(value or [])
|
||||
result: list[str] = []
|
||||
for item in items:
|
||||
path = str(item).strip()
|
||||
if not path:
|
||||
continue
|
||||
if not path.startswith("/"):
|
||||
raise SettingsError("absolutePath", "cell_data_directories")
|
||||
path = path.rstrip("/") or "/"
|
||||
if path not in result:
|
||||
result.append(path)
|
||||
if not result:
|
||||
raise SettingsError("required", "cell_data_directories")
|
||||
return result
|
||||
|
||||
|
||||
def _identifier(values: dict[str, Any], name: str) -> str:
|
||||
value = _text(values, name)
|
||||
if not main.SQL_IDENTIFIER_RE.fullmatch(value):
|
||||
raise SettingsError("invalidIdentifier", name)
|
||||
return value
|
||||
@@ -1,434 +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 close(self) -> None:
|
||||
ftp, self._ftp = self._ftp, None
|
||||
if ftp is None:
|
||||
return
|
||||
try:
|
||||
ftp.quit()
|
||||
except (OSError, EOFError, ftplib.Error):
|
||||
try:
|
||||
ftp.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _connect(self) -> ftplib.FTP:
|
||||
if self._ftp is None:
|
||||
ftp = self.factory()
|
||||
ftp.encoding = self.encoding
|
||||
try:
|
||||
ftp.connect(self.host, self.port, timeout=CONNECT_TIMEOUT_SECONDS)
|
||||
ftp.login(self.username, self.password)
|
||||
ftp.set_pasv(self.passive)
|
||||
if ftp.sock is not None:
|
||||
ftp.sock.settimeout(TRANSFER_TIMEOUT_SECONDS)
|
||||
except BaseException:
|
||||
try:
|
||||
ftp.close()
|
||||
except OSError:
|
||||
pass
|
||||
raise
|
||||
self._ftp = ftp
|
||||
return self._ftp
|
||||
|
||||
def _call(self, operation: str, path: str, action: Callable[[ftplib.FTP], T]) -> T:
|
||||
last_error: BaseException | None = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
return action(self._connect())
|
||||
except ftplib.error_perm as exc:
|
||||
raise main.ProcessingError(f"FTP {operation} {path} failed: {exc}") from exc
|
||||
except (ftplib.Error, OSError, EOFError) as exc:
|
||||
last_error = exc
|
||||
self.close()
|
||||
raise main.ProcessingError(f"FTP {operation} {path} failed: {last_error}")
|
||||
|
||||
|
||||
class SftpStorage:
|
||||
def __init__(self, host: str, port: int, username: str, password: str) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.password = password
|
||||
self._transport: paramiko.Transport | None = None
|
||||
self._sftp: paramiko.SFTPClient | None = None
|
||||
|
||||
def list_dir(self, path: str) -> list[dict[str, object]]:
|
||||
attrs = self._call("list", path, lambda sftp: sftp.listdir_attr(path))
|
||||
return [entry(path, item.filename, stat.S_ISDIR(item.st_mode or 0), int(item.st_size or 0)) for item in attrs]
|
||||
|
||||
def read_bytes(self, path: str) -> bytes:
|
||||
def action(sftp: paramiko.SFTPClient) -> bytes:
|
||||
buffer = io.BytesIO()
|
||||
sftp.getfo(path, buffer)
|
||||
return buffer.getvalue()
|
||||
|
||||
return self._call("download", path, action)
|
||||
|
||||
def make_dir(self, path: str) -> None:
|
||||
self._call("mkdir", path, lambda sftp: sftp.mkdir(path))
|
||||
|
||||
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str:
|
||||
path = posixpath.join(directory, filename)
|
||||
self._call("upload", path, lambda sftp: sftp.putfo(io.BytesIO(payload), path))
|
||||
return path
|
||||
|
||||
def close(self) -> None:
|
||||
transport, self._transport, self._sftp = self._transport, None, None
|
||||
if transport is not None:
|
||||
try:
|
||||
transport.close()
|
||||
except (OSError, EOFError, paramiko.SSHException):
|
||||
pass
|
||||
|
||||
def _connect(self) -> paramiko.SFTPClient:
|
||||
if self._sftp is None:
|
||||
sock = socket.create_connection((self.host, self.port), timeout=CONNECT_TIMEOUT_SECONDS)
|
||||
transport = paramiko.Transport(sock)
|
||||
try:
|
||||
transport.banner_timeout = CONNECT_TIMEOUT_SECONDS
|
||||
transport.connect(username=self.username, password=self.password)
|
||||
sftp = paramiko.SFTPClient.from_transport(transport)
|
||||
if sftp is None:
|
||||
raise paramiko.SSHException("SFTP channel unavailable")
|
||||
channel = sftp.get_channel()
|
||||
if channel is not None:
|
||||
channel.settimeout(TRANSFER_TIMEOUT_SECONDS)
|
||||
except BaseException:
|
||||
transport.close()
|
||||
raise
|
||||
self._transport, self._sftp = transport, sftp
|
||||
return self._sftp
|
||||
|
||||
def _call(self, operation: str, path: str, action: Callable[[paramiko.SFTPClient], T]) -> T:
|
||||
last_error: BaseException | None = None
|
||||
for _ in range(2):
|
||||
try:
|
||||
return action(self._connect())
|
||||
except (FileNotFoundError, PermissionError, paramiko.AuthenticationException) as exc:
|
||||
raise main.ProcessingError(f"SFTP {operation} {path} failed: {exc}") from exc
|
||||
except (OSError, EOFError, paramiko.SSHException) as exc:
|
||||
last_error = exc
|
||||
self.close()
|
||||
raise main.ProcessingError(f"SFTP {operation} {path} failed: {last_error}")
|
||||
|
||||
|
||||
class MySqlSummaryStore:
|
||||
def __init__(
|
||||
self,
|
||||
host: str,
|
||||
port: int,
|
||||
username: str,
|
||||
password: str,
|
||||
database: str = main.DATABASE_NAME,
|
||||
table: str = main.DATABASE_TABLE,
|
||||
connect: Callable[..., Any] | None = None,
|
||||
) -> None:
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.username = username
|
||||
self.password = password
|
||||
self.database = main.sql_identifier(database, "database")
|
||||
self.table = main.sql_identifier(table, "table")
|
||||
self._connect = connect or pymysql.connect
|
||||
self._schema_ready = False
|
||||
|
||||
def latest_metric_time(self) -> datetime | None:
|
||||
with self._connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(f"SELECT MAX(metric_time) FROM `{self.table}`")
|
||||
row = cursor.fetchone()
|
||||
value = row[0] if row else None
|
||||
if value is None:
|
||||
return None
|
||||
return value if isinstance(value, datetime) else datetime.fromisoformat(str(value))
|
||||
|
||||
def replace_latest(self, rows: list[dict[str, str]]) -> dict[str, object]:
|
||||
metric_time = main.batch_metric_time(rows)
|
||||
main.ensure_not_newer(self.latest_metric_time(), metric_time)
|
||||
params = [main.summary_row_params(row) for row in rows]
|
||||
metric_text = metric_time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
placeholders = ", ".join(["%s"] * len(main.SUMMARY_HEADER))
|
||||
insert_sql = f"INSERT INTO `{self.table}` ({', '.join(main.SUMMARY_HEADER)}) VALUES ({placeholders})"
|
||||
with self._connection() as connection:
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
refreshed = cursor.execute(f"DELETE FROM `{self.table}` WHERE metric_time = %s", (metric_text,))
|
||||
inserted = 0
|
||||
for start in range(0, len(params), INSERT_BATCH_SIZE):
|
||||
inserted += cursor.executemany(insert_sql, params[start : start + INSERT_BATCH_SIZE]) or 0
|
||||
deleted = cursor.execute(f"DELETE FROM `{self.table}` WHERE metric_time <> %s", (metric_text,))
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
connection.rollback()
|
||||
raise main.ProcessingError(f"MySQL write failed: {exc}") from exc
|
||||
return {
|
||||
"enabled": True,
|
||||
"table": self.table,
|
||||
"metric_time": metric_text,
|
||||
"inserted_rows": int(inserted),
|
||||
"refreshed_rows": int(refreshed),
|
||||
"old_rows_deleted": int(deleted),
|
||||
}
|
||||
|
||||
def rows_for_time(self, metric_time: datetime) -> list[dict[str, str]]:
|
||||
sql = (
|
||||
f"SELECT {', '.join(main.SUMMARY_HEADER)} FROM `{self.table}` "
|
||||
"WHERE metric_time = %s ORDER BY cgi, cell_name"
|
||||
)
|
||||
with self._connection() as connection, connection.cursor() as cursor:
|
||||
cursor.execute(sql, (metric_time.strftime("%Y-%m-%d %H:%M:%S"),))
|
||||
records = cursor.fetchall()
|
||||
return [
|
||||
{column: mysql_cell(value) for column, value in zip(main.SUMMARY_HEADER, record, strict=True)}
|
||||
for record in records
|
||||
]
|
||||
|
||||
def 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 ping(self) -> str:
|
||||
connection = self._open(database=None)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute("SELECT VERSION()")
|
||||
row = cursor.fetchone()
|
||||
return str(row[0]) if row else ""
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
def _connection(self) -> Any:
|
||||
if not self._schema_ready:
|
||||
self._ensure_schema()
|
||||
return _Closing(self._open(database=self.database))
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
connection = self._open(database=None)
|
||||
try:
|
||||
with connection.cursor() as cursor:
|
||||
cursor.execute(main.create_database_sql(self.database))
|
||||
cursor.execute(f"USE `{self.database}`")
|
||||
cursor.execute(main.create_table_sql(self.table))
|
||||
cursor.execute(
|
||||
"SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = %s AND TABLE_NAME = %s",
|
||||
(self.database, self.table),
|
||||
)
|
||||
existing = {str(row[0]) for row in cursor.fetchall()}
|
||||
for statement in main.column_migration_sql(self.table, existing):
|
||||
cursor.execute(statement)
|
||||
connection.commit()
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL schema check failed: {exc}") from exc
|
||||
finally:
|
||||
connection.close()
|
||||
self._schema_ready = True
|
||||
|
||||
def _open(self, database: str | None) -> Any:
|
||||
try:
|
||||
return self._connect(
|
||||
host=self.host,
|
||||
port=self.port,
|
||||
user=self.username,
|
||||
password=self.password,
|
||||
database=database,
|
||||
charset="utf8mb4",
|
||||
autocommit=False,
|
||||
connect_timeout=CONNECT_TIMEOUT_SECONDS,
|
||||
read_timeout=TRANSFER_TIMEOUT_SECONDS,
|
||||
write_timeout=TRANSFER_TIMEOUT_SECONDS,
|
||||
)
|
||||
except pymysql.MySQLError as exc:
|
||||
raise main.ProcessingError(f"MySQL connection failed: {exc}") from exc
|
||||
|
||||
|
||||
class _Closing:
|
||||
def __init__(self, connection: Any) -> None:
|
||||
self.connection = connection
|
||||
|
||||
def __enter__(self) -> Any:
|
||||
return self.connection
|
||||
|
||||
def __exit__(self, *exc_info: object) -> None:
|
||||
self.connection.close()
|
||||
|
||||
|
||||
def mysql_cell(value: object) -> str:
|
||||
if isinstance(value, Decimal):
|
||||
text = format(value, "f")
|
||||
return text.rstrip("0").rstrip(".") if "." in text else text
|
||||
return main.normalize_cell(value)
|
||||
|
||||
|
||||
def build_storage(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
||||
if settings.storage_mode == "metrix":
|
||||
assert client is not None
|
||||
return main.MetrixStorage(client, settings.metrix_storage_id)
|
||||
if settings.storage_mode == "sftp":
|
||||
return SftpStorage(settings.remote_host, settings.remote_port, settings.remote_username, settings.remote_password)
|
||||
return FtpStorage(
|
||||
settings.remote_host,
|
||||
settings.remote_port,
|
||||
settings.remote_username,
|
||||
settings.remote_password,
|
||||
settings.ftp_encoding,
|
||||
settings.ftp_passive,
|
||||
)
|
||||
|
||||
|
||||
def build_store(settings: Settings, client: main.MetrixApiClient | None) -> Any:
|
||||
if settings.database_mode == "metrix":
|
||||
assert client is not None
|
||||
return main.ApiSummaryStore(client, settings.metrix_database_id, settings.database_name, settings.table_name)
|
||||
return MySqlSummaryStore(
|
||||
settings.mysql_host,
|
||||
settings.mysql_port,
|
||||
settings.mysql_username,
|
||||
settings.mysql_password,
|
||||
settings.database_name,
|
||||
settings.table_name,
|
||||
)
|
||||
|
||||
|
||||
def build_client(settings: Settings) -> main.MetrixApiClient | None:
|
||||
if not settings.uses_metrix_api():
|
||||
return None
|
||||
return main.MetrixApiClient(settings.metrix_url, settings.metrix_token)
|
||||
|
||||
|
||||
def close_quietly(resource: object) -> None:
|
||||
close = getattr(resource, "close", None)
|
||||
if callable(close):
|
||||
close()
|
||||
|
||||
|
||||
def check_storage(settings: Settings) -> dict[str, object]:
|
||||
storage = build_storage(settings, build_client(settings))
|
||||
try:
|
||||
source = main.StorageSource(storage, settings.source_root, settings.cell_data_directories)
|
||||
dates = source.date_directories()
|
||||
return {"count": len(dates), "latest": str(dates[-1]["name"]) if dates else "-"}
|
||||
finally:
|
||||
close_quietly(storage)
|
||||
|
||||
|
||||
def check_database(settings: Settings) -> dict[str, object]:
|
||||
store = build_store(settings, build_client(settings))
|
||||
latest = store.latest_metric_time()
|
||||
return {"latest": latest.strftime("%Y-%m-%d %H:%M:%S") if latest else "-"}
|
||||
|
||||
|
||||
def parse_list_line(line: str) -> tuple[str, bool, int] | None:
|
||||
text = line.rstrip()
|
||||
if not text or text.startswith("total "):
|
||||
return None
|
||||
if text[0] in "dl-" and len(text) >= 10:
|
||||
parts = text.split(maxsplit=8)
|
||||
if len(parts) < 9:
|
||||
return None
|
||||
name = parts[8]
|
||||
if text[0] == "l" and " -> " in name:
|
||||
name = name.split(" -> ", 1)[0]
|
||||
if name in (".", ".."):
|
||||
return None
|
||||
return name, text[0] == "d", _safe_int(parts[4])
|
||||
parts = text.split(maxsplit=3)
|
||||
if len(parts) == 4 and parts[0].count("-") == 2:
|
||||
is_dir = parts[2] == "<DIR>"
|
||||
return parts[3], is_dir, 0 if is_dir else _safe_int(parts[2])
|
||||
return None
|
||||
|
||||
|
||||
def _safe_int(value: str) -> int:
|
||||
try:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
return 0
|
||||
-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
|
||||
-367
@@ -1,367 +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": "运行记录保留条数",
|
||||
"option.interval": "固定间隔",
|
||||
"option.cron": "Cron 表达式",
|
||||
"option.storageMetrix": "Metrix 存储",
|
||||
"option.databaseMetrix": "Metrix 数据库连接",
|
||||
"option.mysql": "MySQL 直连",
|
||||
"secret.saved": "已保存,留空则不修改",
|
||||
"secret.empty": "未设置",
|
||||
"check.storage": "文件来源",
|
||||
"check.database": "数据库",
|
||||
"check.storageOk": "找到 {count} 个日期目录,最新 {latest}",
|
||||
"check.databaseOk": "连接正常,最新数据 {latest}",
|
||||
"check.running": "正在测试连接…",
|
||||
"msg.saved": "设置已保存",
|
||||
"msg.started": "已开始运行",
|
||||
"msg.busy": "已有任务在运行",
|
||||
"msg.cancelled": "已发送停止指令",
|
||||
"msg.scheduleOn": "定时已启用",
|
||||
"msg.scheduleOff": "定时已暂停",
|
||||
"error.required": "请填写“{field}”",
|
||||
"error.range": "“{field}”应在 {min} 到 {max} 之间",
|
||||
"error.invalidChoice": "“{field}”取值无效",
|
||||
"error.invalidCron": "Cron 表达式无效",
|
||||
"error.invalidUrl": "接口地址需以 http:// 或 https:// 开头",
|
||||
"error.absolutePath": "“{field}”需要以 / 开头",
|
||||
"error.invalidIdentifier": "“{field}”只能包含字母、数字和下划线",
|
||||
"forbidden.title": "无权访问",
|
||||
"forbidden.body": "只有应用管理员可以打开管理界面。",
|
||||
},
|
||||
"en": {
|
||||
"app.title": "Interference ETL",
|
||||
"tab.overview": "Overview",
|
||||
"tab.runs": "Runs",
|
||||
"tab.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",
|
||||
"option.interval": "Interval",
|
||||
"option.cron": "Cron",
|
||||
"option.storageMetrix": "Metrix storage",
|
||||
"option.databaseMetrix": "Metrix connection",
|
||||
"option.mysql": "Direct MySQL",
|
||||
"secret.saved": "Saved; leave blank to keep",
|
||||
"secret.empty": "Not set",
|
||||
"check.storage": "File source",
|
||||
"check.database": "Database",
|
||||
"check.storageOk": "{count} date folders, latest {latest}",
|
||||
"check.databaseOk": "Connected, latest data {latest}",
|
||||
"check.running": "Testing connections…",
|
||||
"msg.saved": "Settings saved",
|
||||
"msg.started": "Run started",
|
||||
"msg.busy": "A run is already in progress",
|
||||
"msg.cancelled": "Stop requested",
|
||||
"msg.scheduleOn": "Schedule enabled",
|
||||
"msg.scheduleOff": "Schedule paused",
|
||||
"error.required": "{field} is required",
|
||||
"error.range": "{field} must be between {min} and {max}",
|
||||
"error.invalidChoice": "Invalid {field}",
|
||||
"error.invalidCron": "Invalid cron expression",
|
||||
"error.invalidUrl": "Base URL must start with http:// or https://",
|
||||
"error.absolutePath": "{field} must start with /",
|
||||
"error.invalidIdentifier": "{field} may only contain letters, digits and underscores",
|
||||
"forbidden.title": "Access denied",
|
||||
"forbidden.body": "Only app administrators can open this page.",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
class Translator:
|
||||
def __init__(self, lang: str) -> None:
|
||||
self.lang = lang if lang in MESSAGES else "zh"
|
||||
|
||||
def __call__(self, key: str, **params: object) -> str:
|
||||
text = MESSAGES[self.lang].get(key) or MESSAGES["zh"].get(key) or key
|
||||
return text.format(**params) if params else text
|
||||
@@ -1,209 +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.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)
|
||||
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),
|
||||
*(["--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,152 +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 HTMLResponse, JSONResponse, PlainTextResponse
|
||||
|
||||
from .auth import Identity, require_admin
|
||||
from .config import SettingsError, data_dir, public_view
|
||||
from .data import DataQuery
|
||||
from .service import EtlService
|
||||
|
||||
LANDING_HTML = """<!doctype html>
|
||||
<html><head><meta charset="utf-8"><title>InterferenceETL</title>
|
||||
<script>location.replace(location.pathname.replace(/\\/?$/, '/') + 'admin');</script>
|
||||
</head><body><a href="admin">InterferenceETL</a></body></html>
|
||||
"""
|
||||
|
||||
|
||||
def settings_error(exc: SettingsError) -> JSONResponse:
|
||||
return JSONResponse(status_code=422, content={"error": exc.key, "field": exc.field, "params": exc.params})
|
||||
|
||||
|
||||
def build_api(service: EtlService) -> FastAPI:
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI) -> AsyncIterator[None]:
|
||||
service.start()
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
service.stop()
|
||||
|
||||
api = FastAPI(title="InterferenceETL", lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None)
|
||||
|
||||
@api.get("/", include_in_schema=False)
|
||||
def landing() -> HTMLResponse:
|
||||
return HTMLResponse(LANDING_HTML)
|
||||
|
||||
@api.get("/healthz")
|
||||
def health() -> dict[str, bool]:
|
||||
return {"ok": True}
|
||||
|
||||
@api.get("/api/status")
|
||||
def status(_: Identity = Depends(require_admin)) -> dict[str, Any]:
|
||||
return service.status()
|
||||
|
||||
@api.get("/api/settings")
|
||||
def read_settings(_: Identity = Depends(require_admin)) -> dict[str, Any]:
|
||||
return public_view(service.settings.get())
|
||||
|
||||
@api.put("/api/settings", response_model=None)
|
||||
def write_settings(payload: dict[str, Any] = Body(...), _: Identity = Depends(require_admin)) -> Any:
|
||||
try:
|
||||
return public_view(service.update_settings(payload))
|
||||
except SettingsError as exc:
|
||||
return settings_error(exc)
|
||||
|
||||
@api.post("/api/checks", response_model=None)
|
||||
def checks(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> Any:
|
||||
try:
|
||||
return service.check_connections(payload)
|
||||
except SettingsError as exc:
|
||||
return settings_error(exc)
|
||||
|
||||
@api.get("/api/runs")
|
||||
def runs(page: int = 1, page_size: int = 20, status: str = "", _: Identity = Depends(require_admin)) -> dict[str, Any]:
|
||||
items, total = service.runs.page(max(1, page), min(max(1, page_size), 200), status)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
@api.post("/api/runs")
|
||||
def start_run(payload: dict[str, Any] | None = Body(None), _: Identity = Depends(require_admin)) -> dict[str, bool]:
|
||||
if not service.settings.configured():
|
||||
raise HTTPException(status_code=409, detail="not_configured")
|
||||
if not service.runner.start("manual", bool((payload or {}).get("dry_run"))):
|
||||
raise HTTPException(status_code=409, detail="busy")
|
||||
return {"started": True}
|
||||
|
||||
@api.post("/api/runs/cancel")
|
||||
def cancel_run(_: Identity = Depends(require_admin)) -> dict[str, bool]:
|
||||
return {"cancelled": service.runner.cancel()}
|
||||
|
||||
@api.get("/api/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="InterferenceETL",
|
||||
favicon=ICON_PATH,
|
||||
dark=None,
|
||||
language="zh-CN",
|
||||
reconnect_timeout=10,
|
||||
show_welcome_message=False,
|
||||
)
|
||||
return api
|
||||
|
||||
|
||||
class QuietSockets(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
message = record.getMessage()
|
||||
return not (message.startswith("connection ") or '"WebSocket ' in message)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
import uvicorn
|
||||
|
||||
config = uvicorn.Config(
|
||||
create_app(),
|
||||
host=os.getenv("HOST", "0.0.0.0"),
|
||||
port=int(os.getenv("PORT", "8080")),
|
||||
access_log=False,
|
||||
timeout_graceful_shutdown=15,
|
||||
)
|
||||
logging.getLogger("uvicorn.error").addFilter(QuietSockets())
|
||||
uvicorn.Server(config).run()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -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,306 +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; }
|
||||
}
|
||||
.nicegui-content { padding: 0 !important; gap: 0 !important; align-items: stretch !important; }
|
||||
.etl-muted { color: var(--etl-muted); }
|
||||
.etl-grow { flex: 1; }
|
||||
|
||||
.etl-shell { min-height: 100vh; width: 100%; 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-brand-sub { font-size: 12px; color: var(--etl-muted); 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; }
|
||||
.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%; }
|
||||
.etl-panel { display: flex !important; flex-direction: column; align-items: stretch !important; gap: 16px !important; }
|
||||
|
||||
.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-split { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 16px; align-items: start; }
|
||||
.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 { height: 380px; overflow: auto; 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; min-height: 420px;
|
||||
height: calc(100vh - 109px); height: calc(100dvh - 109px);
|
||||
}
|
||||
.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 { font-size: 13.5px; }
|
||||
.etl-field-hint { font-size: 12px; color: var(--etl-muted); margin-top: 2px; }
|
||||
.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-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-user-name, .etl-brand-sub { 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%; }
|
||||
.etl-data-card { height: calc(100vh - 93px); height: calc(100dvh - 93px); }
|
||||
}
|
||||
</style>
|
||||
"""
|
||||
-997
@@ -1,997 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import posixpath
|
||||
from collections.abc import Callable, Iterator
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import replace
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Request
|
||||
from nicegui import Client, background_tasks, run, ui
|
||||
from nicegui.element import Element
|
||||
from nicegui.elements.mixins.value_element import ValueElement
|
||||
|
||||
from . import __version__
|
||||
from .auth import Identity, identify
|
||||
from .config import SettingsError, public_view
|
||||
from .data import NETWORK_TYPES, PAGE_SIZES, SORT_ORDERS, DataQuery, difference
|
||||
from .i18n import Translator
|
||||
from .service import EtlService
|
||||
from .theme import ICON_SVG, STYLE
|
||||
|
||||
PREFS_JS = """
|
||||
return {
|
||||
lang: localStorage.getItem('interference-etl.lang') || localStorage.getItem('metrix.locale') || navigator.language || 'zh-CN',
|
||||
dark: localStorage.getItem('interference-etl.dark') ?? localStorage.getItem('metrix.dark')
|
||||
?? (window.matchMedia('(prefers-color-scheme: dark)').matches ? '1' : '0'),
|
||||
};
|
||||
"""
|
||||
|
||||
STATUS_TONES = {
|
||||
"running": "primary",
|
||||
"processed": "success",
|
||||
"history_repaired": "success",
|
||||
"skipped": "neutral",
|
||||
"waiting": "neutral",
|
||||
"failed": "danger",
|
||||
"timeout": "danger",
|
||||
"interrupted": "danger",
|
||||
"cancelled": "warning",
|
||||
}
|
||||
RUN_FILTERS = ("", "processed", "idle", "problem")
|
||||
PAGE_SIZE = 20
|
||||
LOG_TAIL_LINES = 300
|
||||
|
||||
|
||||
def register(service: EtlService) -> None:
|
||||
@ui.page("/admin", title="InterferenceETL", response_timeout=10)
|
||||
async def admin_page(request: Request, client: Client) -> None:
|
||||
ui.add_head_html(STYLE)
|
||||
identity = identify(request.headers)
|
||||
if identity is None or not identity.is_admin:
|
||||
accept = request.headers.get("accept-language", "").lower()
|
||||
render_forbidden(Translator("en" if accept.startswith("en") else "zh"))
|
||||
return
|
||||
await client.connected()
|
||||
prefs = await ui.run_javascript(PREFS_JS, timeout=5) or {}
|
||||
AdminPage(service, identity, prefs).build()
|
||||
|
||||
|
||||
def render_forbidden(t: Translator) -> None:
|
||||
with ui.element("div").classes("etl-forbidden"):
|
||||
with ui.element("div").classes("etl-card etl-forbidden-card"):
|
||||
ui.icon("lock").classes("etl-forbidden-icon")
|
||||
ui.label(t("forbidden.title")).classes("etl-forbidden-title")
|
||||
ui.label(t("forbidden.body")).classes("etl-muted")
|
||||
|
||||
|
||||
def tone_of(status: str) -> str:
|
||||
return STATUS_TONES.get(status, "neutral")
|
||||
|
||||
|
||||
def format_duration(milliseconds: int | None) -> str:
|
||||
if milliseconds is None:
|
||||
return ""
|
||||
seconds = milliseconds / 1000
|
||||
if seconds < 60:
|
||||
return f"{seconds:.1f}s"
|
||||
minutes, rest = divmod(int(seconds), 60)
|
||||
if minutes < 60:
|
||||
return f"{minutes}m {rest:02d}s"
|
||||
hours, minutes = divmod(minutes, 60)
|
||||
return f"{hours}h {minutes:02d}m"
|
||||
|
||||
|
||||
def elapsed_since(started_at: str) -> str:
|
||||
try:
|
||||
started = datetime.strptime(started_at, "%Y-%m-%d %H:%M:%S")
|
||||
except ValueError:
|
||||
return ""
|
||||
seconds = max(0, int((datetime.now() - started).total_seconds()))
|
||||
minutes, rest = divmod(seconds, 60)
|
||||
return f"{minutes:02d}:{rest:02d}"
|
||||
|
||||
|
||||
def short_time(value: str) -> str:
|
||||
return value[:16] if value else ""
|
||||
|
||||
|
||||
class AdminPage:
|
||||
def __init__(self, service: EtlService, identity: Identity, prefs: dict[str, Any]) -> None:
|
||||
self.service = service
|
||||
self.identity = identity
|
||||
lang = str(prefs.get("lang") or "zh").lower()
|
||||
self.t = Translator("en" if lang.startswith("en") else "zh")
|
||||
self.dark = ui.dark_mode(str(prefs.get("dark")) == "1")
|
||||
self.status: dict[str, Any] = {}
|
||||
self.conditional: list[tuple[Element, Callable[[dict[str, Any]], bool]]] = []
|
||||
self.secret_inputs: dict[str, Any] = {}
|
||||
self.log_key: tuple[Any, ...] | None = None
|
||||
self.recent_key: tuple[Any, ...] | None = None
|
||||
self.runs_key: tuple[Any, ...] | None = None
|
||||
self.runs_filter = ""
|
||||
self.runs_page = 1
|
||||
self.form: dict[str, Any] = {}
|
||||
self.inputs: dict[str, ValueElement] = {}
|
||||
self.data_query = DataQuery()
|
||||
self.data_seq = 0
|
||||
self.data_marker: Any = None
|
||||
self.data_items: list[dict[str, str]] = []
|
||||
|
||||
def build(self) -> None:
|
||||
self.status = self.service.status()
|
||||
with ui.element("div").classes("etl-shell"):
|
||||
self.build_header()
|
||||
with ui.element("main").classes("etl-main") as main:
|
||||
with ui.tab_panels(self.tabs, value="overview", animated=False).classes("etl-panels"):
|
||||
with ui.tab_panel("overview").classes("etl-panel"):
|
||||
self.build_overview()
|
||||
with ui.tab_panel("runs").classes("etl-panel"):
|
||||
self.build_runs()
|
||||
with ui.tab_panel("data").classes("etl-panel"):
|
||||
self.build_data()
|
||||
with ui.tab_panel("settings").classes("etl-panel"):
|
||||
self.build_settings()
|
||||
self.main = main
|
||||
self.build_log_dialog()
|
||||
self.build_data_dialog()
|
||||
self.refresh()
|
||||
ui.timer(2.0, self.refresh)
|
||||
|
||||
# Header
|
||||
|
||||
def build_header(self) -> None:
|
||||
t = self.t
|
||||
with ui.element("header").classes("etl-header"):
|
||||
with ui.element("div").classes("etl-header-inner"):
|
||||
with ui.element("div").classes("etl-brand"):
|
||||
ui.html(ICON_SVG, sanitize=False).classes("etl-brand-icon")
|
||||
with ui.element("div").classes("etl-brand-text"):
|
||||
ui.label(t("app.title")).classes("etl-brand-title")
|
||||
ui.label(f"InterferenceETL · v{__version__}").classes("etl-brand-sub")
|
||||
with ui.tabs(value="overview", on_change=self.change_tab).props(
|
||||
"no-caps dense align=left indicator-color=primary narrow-indicator"
|
||||
).classes("etl-tabs") as tabs:
|
||||
ui.tab("overview", label=t("tab.overview"))
|
||||
ui.tab("runs", label=t("tab.runs"))
|
||||
ui.tab("data", label=t("tab.data"))
|
||||
ui.tab("settings", label=t("tab.settings"))
|
||||
self.tabs = tabs
|
||||
with ui.element("div").classes("etl-header-tools"):
|
||||
with ui.element("div").classes("etl-pill") as pill:
|
||||
ui.element("span").classes("etl-pill-dot")
|
||||
self.pill_label = ui.label("")
|
||||
self.pill = pill
|
||||
ui.button(t("header.languageShort"), on_click=self.toggle_language).props(
|
||||
"flat dense no-caps"
|
||||
).classes("etl-tool-btn").tooltip(t("header.language"))
|
||||
self.theme_button = ui.button(icon="dark_mode", on_click=self.toggle_theme).props("flat dense round").classes(
|
||||
"etl-tool-btn"
|
||||
)
|
||||
self.theme_button.tooltip(t("header.theme"))
|
||||
with ui.element("div").classes("etl-user"):
|
||||
ui.label((self.identity.label or "?")[:1].upper()).classes("etl-avatar")
|
||||
ui.label(self.identity.label).classes("etl-user-name")
|
||||
|
||||
async def toggle_language(self) -> None:
|
||||
next_lang = "en-US" if self.t.lang == "zh" else "zh-CN"
|
||||
ui.run_javascript(f"localStorage.setItem('interference-etl.lang', '{next_lang}'); history.go(0);")
|
||||
|
||||
def toggle_theme(self) -> None:
|
||||
dark = not bool(self.dark.value)
|
||||
self.dark.set_value(dark)
|
||||
ui.run_javascript(f"localStorage.setItem('interference-etl.dark', '{1 if dark else 0}')")
|
||||
self.refresh_header()
|
||||
|
||||
# Overview
|
||||
|
||||
def build_overview(self) -> None:
|
||||
t = self.t
|
||||
with ui.element("div").classes("etl-cards"):
|
||||
self.card_schedule = self.metric_card("schedule", t("card.schedule"))
|
||||
self.card_current = self.metric_card("bolt", t("card.current"))
|
||||
self.card_latest = self.metric_card("storage", t("card.latestData"))
|
||||
|
||||
with ui.element("section").classes("etl-card etl-actions"):
|
||||
with ui.element("div").classes("etl-actions-buttons"):
|
||||
self.run_button = ui.button(t("action.run"), icon="play_arrow", on_click=lambda: self.start_run(False)).props(
|
||||
"unelevated no-caps color=primary"
|
||||
).classes("etl-btn etl-btn-primary")
|
||||
self.dry_button = ui.button(t("action.dryRun"), icon="science", on_click=lambda: self.start_run(True)).props(
|
||||
"outline no-caps"
|
||||
).classes("etl-btn")
|
||||
self.dry_button.tooltip(t("action.dryRunHint"))
|
||||
self.schedule_button = ui.button("", on_click=self.toggle_schedule).props("outline no-caps").classes("etl-btn")
|
||||
self.cancel_button = ui.button(t("action.cancel"), icon="stop", on_click=self.cancel_run).props(
|
||||
"outline no-caps"
|
||||
).classes("etl-btn etl-btn-danger")
|
||||
self.today_label = ui.label("").classes("etl-muted etl-today")
|
||||
|
||||
with ui.element("div").classes("etl-split"):
|
||||
with ui.element("section").classes("etl-card etl-log-card"):
|
||||
with ui.element("div").classes("etl-card-head"):
|
||||
with ui.element("div").classes("etl-card-title"):
|
||||
ui.icon("terminal").classes("etl-card-icon")
|
||||
ui.label(t("log.title"))
|
||||
self.log_meta = ui.label("").classes("etl-muted etl-log-meta")
|
||||
self.log_view = ui.label(t("log.empty")).classes("etl-log")
|
||||
with ui.element("section").classes("etl-card etl-recent-card"):
|
||||
with ui.element("div").classes("etl-card-head"):
|
||||
with ui.element("div").classes("etl-card-title"):
|
||||
ui.icon("history").classes("etl-card-icon")
|
||||
ui.label(t("recent.title"))
|
||||
ui.button(t("action.viewAll"), on_click=lambda: self.tabs.set_value("runs")).props(
|
||||
"flat dense no-caps color=primary"
|
||||
).classes("etl-link-btn")
|
||||
self.recent_box = ui.element("div").classes("etl-recent")
|
||||
|
||||
def metric_card(self, icon: str, title: str) -> dict[str, Any]:
|
||||
with ui.element("section").classes("etl-card etl-metric"):
|
||||
with ui.element("div").classes("etl-metric-head"):
|
||||
ui.label(title).classes("etl-metric-title")
|
||||
ui.icon(icon).classes("etl-metric-icon")
|
||||
with ui.element("div").classes("etl-metric-value-row"):
|
||||
spinner = ui.spinner(size="18px").classes("etl-metric-spinner")
|
||||
value = ui.label("").classes("etl-metric-value")
|
||||
sub = ui.label("").classes("etl-metric-sub")
|
||||
return {"value": value, "sub": sub, "spinner": spinner}
|
||||
|
||||
def set_notes(self, card: dict[str, Any], text: str = "") -> None:
|
||||
card["sub"].set_text(text)
|
||||
card["sub"].set_visibility(bool(text))
|
||||
|
||||
def refresh(self) -> None:
|
||||
self.status = self.service.status()
|
||||
self.refresh_header()
|
||||
self.refresh_cards()
|
||||
self.refresh_actions()
|
||||
self.refresh_log()
|
||||
self.refresh_recent()
|
||||
self.refresh_runs()
|
||||
if self.tabs.value == "data" and self.data_marker is not None and self.processed_marker() != self.data_marker:
|
||||
self.data_marker = self.processed_marker()
|
||||
background_tasks.create(self.load_data(), name="etl-data-refresh")
|
||||
|
||||
def processed_marker(self) -> Any:
|
||||
latest = self.status.get("last_processed") or {}
|
||||
return latest.get("id", 0)
|
||||
|
||||
async def change_tab(self, event: Any) -> None:
|
||||
self.main.classes(add="is-wide") if event.value == "data" else self.main.classes(remove="is-wide")
|
||||
if event.value == "data" and self.data_marker is None:
|
||||
await self.load_data()
|
||||
|
||||
def refresh_header(self) -> None:
|
||||
enabled = bool(self.status["schedule_enabled"])
|
||||
self.pill_label.set_text(self.t("header.scheduleOn" if enabled else "header.scheduleOff"))
|
||||
self.pill.classes(replace=f"etl-pill {'is-on' if enabled else 'is-off'}")
|
||||
self.theme_button.props(f"icon={'light_mode' if self.dark.value else 'dark_mode'}")
|
||||
|
||||
def refresh_cards(self) -> None:
|
||||
t, status = self.t, self.status
|
||||
card = self.card_schedule
|
||||
if not status["configured"]:
|
||||
card["value"].set_text(t("schedule.setup"))
|
||||
self.set_notes(card)
|
||||
elif not status["schedule_enabled"]:
|
||||
card["value"].set_text(t("schedule.paused"))
|
||||
self.set_notes(card, self.schedule_text())
|
||||
else:
|
||||
card["value"].set_text(self.schedule_text())
|
||||
next_run = status["next_run_at"]
|
||||
self.set_notes(card, t("schedule.next", time=next_run[11:19]) if next_run else "")
|
||||
card["value"].classes(replace="etl-metric-value" + ("" if status["schedule_enabled"] else " is-muted"))
|
||||
card["spinner"].set_visibility(False)
|
||||
|
||||
running = status["running"]
|
||||
card = self.card_current
|
||||
card["spinner"].set_visibility(bool(running))
|
||||
if running:
|
||||
card["value"].set_text(t("current.running"))
|
||||
self.set_notes(
|
||||
card,
|
||||
t(
|
||||
"current.elapsed",
|
||||
id=running["id"],
|
||||
trigger=self.trigger_text(running["trigger"], running["dry_run"]),
|
||||
elapsed=elapsed_since(running["started_at"]),
|
||||
),
|
||||
)
|
||||
else:
|
||||
last = status["last_run"]
|
||||
card["value"].set_text(t("current.idle"))
|
||||
finished = (last or {}).get("finished_at") or ""
|
||||
self.set_notes(card, t("current.lastFinished", time=finished[5:19]) if finished else "")
|
||||
card["value"].classes(replace="etl-metric-value" + (" tone-primary" if running else ""))
|
||||
|
||||
latest = status["last_processed"]
|
||||
card = self.card_latest
|
||||
card["spinner"].set_visibility(False)
|
||||
if latest:
|
||||
card["value"].set_text(short_time(latest["target_time"]) or t("empty.dash"))
|
||||
rows = latest.get("summary_rows")
|
||||
self.set_notes(
|
||||
card,
|
||||
t("latest.rows", rows=f"{rows:,}" if isinstance(rows, int) else "-", time=(latest["finished_at"] or "")[5:16]),
|
||||
)
|
||||
card["value"].classes(replace="etl-metric-value")
|
||||
else:
|
||||
card["value"].set_text(t("empty.never"))
|
||||
card["value"].classes(replace="etl-metric-value is-muted")
|
||||
self.set_notes(card)
|
||||
|
||||
def refresh_actions(self) -> None:
|
||||
running = bool(self.status["running"])
|
||||
configured = bool(self.status["configured"])
|
||||
self.run_button.set_enabled(not running and configured)
|
||||
self.dry_button.set_enabled(not running and configured)
|
||||
self.cancel_button.set_visibility(running)
|
||||
enabled = bool(self.status["schedule_enabled"])
|
||||
self.schedule_button.set_text(self.t("action.pause" if enabled else "action.resume"))
|
||||
self.schedule_button.props(f"icon={'pause' if enabled else 'schedule'}")
|
||||
self.schedule_button.set_enabled(configured or enabled)
|
||||
today = self.status["today"]
|
||||
processed = today.get("processed", 0) + today.get("history_repaired", 0)
|
||||
idle = today.get("skipped", 0) + today.get("waiting", 0)
|
||||
problem = sum(today.get(name, 0) for name in ("failed", "timeout", "interrupted", "cancelled"))
|
||||
self.today_label.set_text(
|
||||
self.t("today.summary", total=sum(today.values()), processed=processed, idle=idle, problem=problem)
|
||||
)
|
||||
|
||||
def refresh_log(self) -> None:
|
||||
running = self.status["running"]
|
||||
run = running or self.status["last_run"]
|
||||
if not run:
|
||||
return
|
||||
run_id = run["id"]
|
||||
log_text = self.service.runner.read_log(run_id, tail=LOG_TAIL_LINES)
|
||||
key = (run_id, bool(running), len(log_text), log_text[-64:])
|
||||
if key == self.log_key:
|
||||
return
|
||||
self.log_key = key
|
||||
status = self.t("status.running") if running else self.status_text(run)
|
||||
self.log_meta.set_text(f"#{run_id} · {status} · {run['started_at'][5:19]}")
|
||||
self.log_view.set_text(log_text or self.t("log.empty"))
|
||||
ui.run_javascript(f"const el = getHtmlElement({self.log_view.id}); if (el) el.scrollTop = el.scrollHeight;")
|
||||
|
||||
def refresh_recent(self) -> None:
|
||||
rows, _ = self.service.runs.page(1, 8)
|
||||
key = tuple((row["id"], row["status"]) for row in rows)
|
||||
if key == self.recent_key:
|
||||
return
|
||||
self.recent_key = key
|
||||
self.recent_box.clear()
|
||||
with self.recent_box:
|
||||
if not rows:
|
||||
ui.label(self.t("recent.empty")).classes("etl-muted etl-empty")
|
||||
for row in rows:
|
||||
with ui.element("div").classes("etl-recent-item").on("click", lambda _, run_id=row["id"]: self.open_log(run_id)):
|
||||
ui.element("span").classes(f"etl-dot tone-{tone_of(row['status'])}")
|
||||
with ui.element("div").classes("etl-recent-text"):
|
||||
ui.label(self.status_text(row)).classes("etl-recent-status")
|
||||
ui.label(self.detail_text(row) or self.trigger_text(row["trigger"], row["dry_run"])).classes(
|
||||
"etl-recent-detail"
|
||||
)
|
||||
ui.label(row["started_at"][11:19]).classes("etl-recent-time")
|
||||
|
||||
# Runs
|
||||
|
||||
def build_runs(self) -> None:
|
||||
t = self.t
|
||||
with ui.element("section").classes("etl-card etl-runs-card"):
|
||||
with ui.element("div").classes("etl-runs-toolbar"):
|
||||
ui.toggle(
|
||||
{key: t(f"runs.filter.{key or 'all'}") for key in RUN_FILTERS},
|
||||
value="",
|
||||
on_change=self.change_filter,
|
||||
).props("no-caps unelevated dense toggle-color=primary").classes("etl-segment")
|
||||
with ui.element("div").classes("etl-runs-tools"):
|
||||
self.runs_total = ui.label("").classes("etl-muted")
|
||||
ui.button(icon="refresh", on_click=lambda: self.refresh_runs(force=True)).props("flat round dense").tooltip(
|
||||
t("action.refresh")
|
||||
)
|
||||
columns = [
|
||||
{"name": "id", "label": t("runs.col.id"), "field": "id", "align": "left"},
|
||||
{"name": "started_at", "label": t("runs.col.started"), "field": "started_at", "align": "left"},
|
||||
{"name": "trigger", "label": t("runs.col.trigger"), "field": "trigger_text", "align": "left"},
|
||||
{"name": "status", "label": t("runs.col.status"), "field": "status_text", "align": "left"},
|
||||
{"name": "target_time", "label": t("runs.col.target"), "field": "target_text", "align": "left"},
|
||||
{"name": "summary_rows", "label": t("runs.col.rows"), "field": "rows_text", "align": "right"},
|
||||
{"name": "duration", "label": t("runs.col.duration"), "field": "duration_text", "align": "right"},
|
||||
{"name": "detail", "label": t("runs.col.detail"), "field": "detail_text", "align": "left"},
|
||||
]
|
||||
self.runs_table = ui.table(rows=[], columns=columns, row_key="id", pagination=0).props(
|
||||
"flat hide-pagination"
|
||||
).classes("etl-table")
|
||||
self.runs_table.props["no-data-label"] = t("runs.empty")
|
||||
self.runs_table.add_slot(
|
||||
"body-cell-status",
|
||||
'<q-td :props="props"><span :class="\'etl-badge tone-\' + props.row.tone">{{ props.value }}</span></q-td>',
|
||||
)
|
||||
self.runs_table.add_slot(
|
||||
"body-cell-detail",
|
||||
'<q-td :props="props"><div class="etl-cell-detail" :title="props.value">{{ props.value }}</div></q-td>',
|
||||
)
|
||||
self.runs_table.on("rowClick", lambda event: self.open_log(int(event.args[1]["id"])))
|
||||
with ui.element("div").classes("etl-runs-footer"):
|
||||
self.runs_pagination = ui.pagination(1, 1, direction_links=True, value=1, on_change=self.change_page).props(
|
||||
"max-pages=7 boundary-numbers flat active-design=unelevated active-color=primary"
|
||||
)
|
||||
|
||||
def change_filter(self, event: Any) -> None:
|
||||
self.runs_filter = event.value or ""
|
||||
self.runs_page = 1
|
||||
self.runs_pagination.set_value(1)
|
||||
self.refresh_runs(force=True)
|
||||
|
||||
def change_page(self, event: Any) -> None:
|
||||
self.runs_page = int(event.value or 1)
|
||||
self.refresh_runs(force=True)
|
||||
|
||||
def refresh_runs(self, force: bool = False) -> None:
|
||||
rows, total = self.service.runs.page(self.runs_page, PAGE_SIZE, self.runs_filter)
|
||||
key = (self.runs_filter, self.runs_page, total, tuple((row["id"], row["status"]) for row in rows))
|
||||
if key == self.runs_key and not force:
|
||||
return
|
||||
self.runs_key = key
|
||||
self.runs_table.rows = [self.table_row(row) for row in rows]
|
||||
self.runs_table.update()
|
||||
self.runs_total.set_text(self.t("runs.total", n=total))
|
||||
self.runs_pagination.max = max(1, (total + PAGE_SIZE - 1) // PAGE_SIZE)
|
||||
self.runs_pagination.update()
|
||||
|
||||
def table_row(self, row: dict[str, Any]) -> dict[str, Any]:
|
||||
rows = row.get("summary_rows")
|
||||
return {
|
||||
"id": row["id"],
|
||||
"started_at": row["started_at"],
|
||||
"trigger_text": self.trigger_text(row["trigger"], row["dry_run"]),
|
||||
"status_text": self.status_text(row),
|
||||
"tone": tone_of(row["status"]),
|
||||
"target_text": short_time(row.get("target_time") or ""),
|
||||
"rows_text": f"{rows:,}" if isinstance(rows, int) else "",
|
||||
"duration_text": format_duration(row.get("duration_ms")),
|
||||
"detail_text": self.detail_text(row),
|
||||
}
|
||||
|
||||
# Data
|
||||
|
||||
def build_data(self) -> None:
|
||||
t = self.t
|
||||
with ui.element("section").classes("etl-card etl-runs-card etl-data-card"):
|
||||
with ui.element("div").classes("etl-runs-toolbar"):
|
||||
ui.toggle(
|
||||
{"": t("data.network.all"), **{name: name for name in NETWORK_TYPES}},
|
||||
value="",
|
||||
on_change=lambda event: self.update_data_query(network=event.value or ""),
|
||||
).props("no-caps unelevated dense toggle-color=primary").classes("etl-segment")
|
||||
with ui.element("div").classes("etl-runs-tools etl-data-tools"):
|
||||
search = ui.input(
|
||||
placeholder=t("data.search"),
|
||||
on_change=lambda event: self.update_data_query(keyword=event.value or ""),
|
||||
).props("outlined dense clearable debounce=400").classes("etl-data-search")
|
||||
with search.add_slot("prepend"):
|
||||
ui.icon("search").classes("etl-muted")
|
||||
ui.select(
|
||||
{key: t(f"data.sort.{key}") for key in SORT_ORDERS},
|
||||
value=self.data_query.sort,
|
||||
on_change=lambda event: self.update_data_query(sort=event.value),
|
||||
).props("outlined dense options-dense").classes("etl-data-sort")
|
||||
ui.button(icon="refresh", on_click=self.load_data).props("flat round dense").tooltip(t("action.refresh"))
|
||||
self.data_summary = ui.label(t("data.loading")).classes("etl-data-summary")
|
||||
columns = [
|
||||
{"name": "network", "label": t("data.col.network"), "field": "network_type", "align": "left"},
|
||||
{"name": "cgi", "label": t("data.col.cgi"), "field": "cgi", "align": "left"},
|
||||
{"name": "cell", "label": t("data.col.cell"), "field": "cell_name", "align": "left", "classes": "etl-col-cell"},
|
||||
{"name": "interference", "label": t("data.col.interference"), "field": "interference_dbm", "align": "right"},
|
||||
{"name": "prev", "label": t("data.col.prev"), "field": "prev_interference_dbm", "align": "right"},
|
||||
{"name": "change", "label": t("data.col.change"), "field": "change", "align": "right"},
|
||||
{"name": "nearby", "label": t("data.col.nearby"), "field": "nearby_count", "align": "right"},
|
||||
{"name": "split", "label": t("data.col.split"), "field": "split", "align": "left"},
|
||||
{"name": "longitude", "label": t("data.col.longitude"), "field": "longitude", "align": "right"},
|
||||
{"name": "latitude", "label": t("data.col.latitude"), "field": "latitude", "align": "right"},
|
||||
{"name": "azimuth", "label": t("data.col.azimuth"), "field": "azimuth", "align": "right"},
|
||||
]
|
||||
self.data_table = ui.table(rows=[], columns=columns, row_key="key", pagination=0).props(
|
||||
"flat hide-pagination"
|
||||
).classes("etl-table etl-data-table")
|
||||
self.data_table.props["no-data-label"] = t("data.loading")
|
||||
self.data_table.add_slot(
|
||||
"body-cell-network",
|
||||
'<q-td :props="props"><span :class="\'etl-net net-\' + props.row.net">{{ props.value }}</span></q-td>',
|
||||
)
|
||||
self.data_table.add_slot(
|
||||
"body-cell-cell",
|
||||
'<q-td :props="props"><div class="etl-cell-name" :title="props.value">{{ props.value }}</div></q-td>',
|
||||
)
|
||||
self.data_table.add_slot(
|
||||
"body-cell-change",
|
||||
'<q-td :props="props"><span :class="props.row.change_tone">{{ props.value }}</span></q-td>',
|
||||
)
|
||||
self.data_table.add_slot(
|
||||
"body-cell-split",
|
||||
'<q-td :props="props"><span class="etl-muted">{{ props.value }}</span></q-td>',
|
||||
)
|
||||
self.data_table.on("rowClick", lambda event: self.open_data_detail(int(event.args[1]["key"])))
|
||||
with ui.element("div").classes("etl-runs-footer etl-data-footer"):
|
||||
with ui.element("div").classes("etl-data-size"):
|
||||
ui.label(t("data.pageSize")).classes("etl-muted")
|
||||
ui.select(
|
||||
{size: str(size) for size in PAGE_SIZES},
|
||||
value=self.data_query.page_size,
|
||||
on_change=lambda event: self.update_data_query(page_size=int(event.value)),
|
||||
).props("outlined dense options-dense").classes("etl-page-size")
|
||||
self.data_total = ui.label("").classes("etl-muted")
|
||||
self.data_pagination = ui.pagination(1, 1, direction_links=True, value=1, on_change=self.change_data_page).props(
|
||||
"max-pages=7 boundary-numbers flat active-design=unelevated active-color=primary"
|
||||
)
|
||||
|
||||
async def update_data_query(self, **changes: Any) -> None:
|
||||
self.data_query = replace(self.data_query, page=1, **changes)
|
||||
await self.load_data()
|
||||
|
||||
async def change_data_page(self, event: Any) -> None:
|
||||
page = int(event.value or 1)
|
||||
if page != self.data_query.page:
|
||||
self.data_query = replace(self.data_query, page=page)
|
||||
await self.load_data()
|
||||
|
||||
async def load_data(self) -> None:
|
||||
t = self.t
|
||||
self.data_seq += 1
|
||||
seq = self.data_seq
|
||||
self.data_marker = self.processed_marker()
|
||||
self.data_table.props("loading")
|
||||
try:
|
||||
result = await run.io_bound(self.service.data.browse, self.data_query)
|
||||
except Exception as exc:
|
||||
if seq == self.data_seq:
|
||||
self.data_table.props(remove="loading")
|
||||
self.data_items = []
|
||||
self.data_table.rows = []
|
||||
self.data_table.props["no-data-label"] = t("data.error", detail=str(exc)[:300])
|
||||
self.data_table.update()
|
||||
self.data_summary.set_text(t("data.error", detail=str(exc)[:300]))
|
||||
self.data_summary.classes(replace="etl-data-summary tone-danger")
|
||||
self.data_total.set_text("")
|
||||
return
|
||||
if seq != self.data_seq:
|
||||
return
|
||||
self.data_table.props(remove="loading")
|
||||
self.data_query = replace(self.data_query, page=result["page"])
|
||||
self.data_items = result["items"]
|
||||
self.data_table.rows = [self.data_row(index, item) for index, item in enumerate(self.data_items)]
|
||||
self.data_table.props["no-data-label"] = t("data.noMatch" if result["networks"] else "data.empty")
|
||||
self.data_table.update()
|
||||
self.data_table.client.run_javascript(
|
||||
f"document.querySelector('#{self.data_table.html_id} .q-table__middle')?.scrollTo(0, 0)"
|
||||
)
|
||||
self.data_pagination.max = result["pages"]
|
||||
self.data_pagination.value = result["page"]
|
||||
self.data_pagination.update()
|
||||
networks = result["networks"]
|
||||
if networks:
|
||||
parts = [t("data.summary", time=short_time(result["metric_time"]), total=f"{sum(networks.values()):,}")]
|
||||
parts += [f"{name} {networks[name]:,}" for name in NETWORK_TYPES if name in networks]
|
||||
self.data_summary.set_text(" · ".join(parts))
|
||||
else:
|
||||
self.data_summary.set_text(t("data.empty"))
|
||||
self.data_summary.classes(replace="etl-data-summary")
|
||||
filtered = self.data_query.network or self.data_query.keyword.strip()
|
||||
self.data_total.set_text(
|
||||
t("data.matched", n=f"{result['total']:,}") if filtered else t("data.pageOf", page=result["page"], pages=result["pages"])
|
||||
)
|
||||
|
||||
def data_row(self, index: int, item: dict[str, str]) -> dict[str, Any]:
|
||||
change = difference(item["interference_dbm"], item["prev_interference_dbm"])
|
||||
return {
|
||||
**item,
|
||||
"key": index,
|
||||
"net": item["network_type"].replace(".", "").lower(),
|
||||
"change": change,
|
||||
"change_tone": "tone-danger" if change.startswith("+") else ("tone-success" if change.startswith("-") else ""),
|
||||
"split": " · ".join(
|
||||
f"{label} {item[field]}"
|
||||
for label, field in zip(NETWORK_TYPES, ("nearby_26g", "nearby_700m", "nearby_tdd", "nearby_fdd"), strict=True)
|
||||
if item.get(field) not in ("", "0")
|
||||
),
|
||||
}
|
||||
|
||||
def build_data_dialog(self) -> None:
|
||||
with ui.dialog() as dialog, ui.card().classes("etl-dialog etl-data-dialog"):
|
||||
with ui.element("div").classes("etl-dialog-head"):
|
||||
self.data_dialog_title = ui.label("").classes("etl-dialog-title")
|
||||
self.data_dialog_badge = ui.label("").classes("etl-net")
|
||||
ui.element("div").classes("etl-grow")
|
||||
ui.button(icon="close", on_click=dialog.close).props("flat round dense")
|
||||
self.data_dialog_body = ui.element("div").classes("etl-detail")
|
||||
self.data_dialog = dialog
|
||||
|
||||
def open_data_detail(self, index: int) -> None:
|
||||
if not 0 <= index < len(self.data_items):
|
||||
return
|
||||
t, item = self.t, self.data_items[index]
|
||||
dash = t("empty.dash")
|
||||
self.data_dialog_title.set_text(item["cell_name"] or item["cgi"])
|
||||
self.data_dialog_badge.set_text(item["network_type"])
|
||||
self.data_dialog_badge.classes(replace=f"etl-net net-{item['network_type'].replace('.', '').lower()}")
|
||||
self.data_dialog_body.clear()
|
||||
with self.data_dialog_body:
|
||||
with ui.element("div").classes("etl-detail-grid"):
|
||||
for key, value in (
|
||||
("data.field.metric_time", short_time(item["metric_time"])),
|
||||
("data.col.cgi", item["cgi"]),
|
||||
("data.col.cell", item["cell_name"]),
|
||||
("data.col.interference", item["interference_dbm"]),
|
||||
("data.col.prev", item["prev_interference_dbm"]),
|
||||
("data.col.change", difference(item["interference_dbm"], item["prev_interference_dbm"])),
|
||||
("data.col.longitude", item["longitude"]),
|
||||
("data.col.latitude", item["latitude"]),
|
||||
("data.col.azimuth", item["azimuth"]),
|
||||
):
|
||||
with ui.element("div").classes("etl-meta-item"):
|
||||
ui.label(t(key)).classes("etl-meta-label")
|
||||
ui.label(value or dash).classes("etl-meta-value")
|
||||
ui.label(t("data.nearbyTitle")).classes("etl-detail-title")
|
||||
with ui.element("div").classes("etl-detail-matrix"):
|
||||
ui.label("")
|
||||
for label in (t("data.field.total"), *NETWORK_TYPES):
|
||||
ui.label(label).classes("etl-meta-label")
|
||||
for row_key, prefix in (("data.field.current", ""), ("data.field.previous", "prev_")):
|
||||
ui.label(t(row_key)).classes("etl-meta-label")
|
||||
for field in ("nearby_count", "nearby_26g", "nearby_700m", "nearby_tdd", "nearby_fdd"):
|
||||
ui.label(item.get(prefix + field) or dash).classes("etl-meta-value")
|
||||
self.data_dialog.open()
|
||||
|
||||
# Log dialog
|
||||
|
||||
def build_log_dialog(self) -> None:
|
||||
with ui.dialog() as dialog, ui.card().classes("etl-dialog"):
|
||||
with ui.element("div").classes("etl-dialog-head"):
|
||||
self.dialog_title = ui.label("").classes("etl-dialog-title")
|
||||
self.dialog_badge = ui.label("").classes("etl-badge")
|
||||
ui.element("div").classes("etl-grow")
|
||||
ui.button(icon="close", on_click=dialog.close).props("flat round dense")
|
||||
self.dialog_meta = ui.element("div").classes("etl-dialog-meta")
|
||||
self.dialog_log = ui.label("").classes("etl-log etl-log-dialog")
|
||||
with ui.element("div").classes("etl-dialog-foot"):
|
||||
ui.button(self.t("action.copy"), icon="content_copy", on_click=self.copy_log).props("flat no-caps")
|
||||
ui.button(self.t("action.close"), on_click=dialog.close).props("unelevated no-caps color=primary").classes(
|
||||
"etl-btn-primary"
|
||||
)
|
||||
self.dialog = dialog
|
||||
self.dialog_text = ""
|
||||
|
||||
def open_log(self, run_id: int) -> None:
|
||||
run_row = self.service.runs.get(run_id)
|
||||
if run_row is None:
|
||||
return
|
||||
t = self.t
|
||||
self.dialog_title.set_text(t("dialog.title", id=run_id))
|
||||
self.dialog_badge.set_text(self.status_text(run_row))
|
||||
self.dialog_badge.classes(replace=f"etl-badge tone-{tone_of(run_row['status'])}")
|
||||
self.dialog_meta.clear()
|
||||
rows = run_row.get("summary_rows")
|
||||
items = (
|
||||
("dialog.started", run_row["started_at"]),
|
||||
("dialog.finished", run_row.get("finished_at") or t("empty.dash")),
|
||||
("dialog.duration", format_duration(run_row.get("duration_ms")) or t("empty.dash")),
|
||||
("dialog.target", run_row.get("target_time") or t("empty.dash")),
|
||||
("dialog.rows", f"{rows:,}" if isinstance(rows, int) else t("empty.dash")),
|
||||
)
|
||||
with self.dialog_meta:
|
||||
for key, value in items:
|
||||
with ui.element("div").classes("etl-meta-item"):
|
||||
ui.label(t(key)).classes("etl-meta-label")
|
||||
ui.label(str(value)).classes("etl-meta-value")
|
||||
self.dialog_text = self.service.runner.read_log(run_id)
|
||||
self.dialog_log.set_text(self.dialog_text or t("log.empty"))
|
||||
self.dialog.open()
|
||||
|
||||
def copy_log(self) -> None:
|
||||
ui.clipboard.write(self.dialog_text)
|
||||
ui.notify(self.t("log.copied"), type="positive", position="top")
|
||||
|
||||
# Actions
|
||||
|
||||
def start_run(self, dry_run: bool) -> None:
|
||||
if self.service.runner.start("manual", dry_run):
|
||||
ui.notify(self.t("msg.started"), type="positive", position="top")
|
||||
else:
|
||||
ui.notify(self.t("msg.busy"), type="warning", position="top")
|
||||
ui.timer(0.4, self.refresh, once=True)
|
||||
|
||||
def cancel_run(self) -> None:
|
||||
if self.service.runner.cancel():
|
||||
ui.notify(self.t("msg.cancelled"), type="info", position="top")
|
||||
self.refresh()
|
||||
|
||||
def toggle_schedule(self) -> None:
|
||||
enabled = not bool(self.status["schedule_enabled"])
|
||||
try:
|
||||
settings = self.service.set_schedule_enabled(enabled)
|
||||
except SettingsError as exc:
|
||||
ui.notify(self.error_text(exc), type="negative", position="top")
|
||||
return
|
||||
self.set_form("schedule_enabled", settings.schedule_enabled)
|
||||
ui.notify(self.t("msg.scheduleOn" if enabled else "msg.scheduleOff"), type="positive", position="top")
|
||||
self.refresh()
|
||||
|
||||
# Settings
|
||||
|
||||
def build_settings(self) -> None:
|
||||
t = self.t
|
||||
self.load_form()
|
||||
with ui.element("div").classes("etl-settings"):
|
||||
with self.section("schedule", "section.schedule"):
|
||||
with self.field("field.schedule_enabled"):
|
||||
self.bind(ui.switch(), "schedule_enabled").props("color=primary")
|
||||
with self.field("field.schedule_mode"):
|
||||
self.segment({"interval": t("option.interval"), "cron": t("option.cron")}, "schedule_mode")
|
||||
with self.field("field.interval_minutes", when=lambda form: form["schedule_mode"] == "interval"):
|
||||
self.number("interval_minutes", 1, 1440)
|
||||
with self.field("field.cron_expression", "field.cron_hint", when=lambda form: form["schedule_mode"] == "cron"):
|
||||
self.text("cron_expression")
|
||||
with self.field("field.timeout_minutes"):
|
||||
self.number("timeout_minutes", 1, 1440)
|
||||
|
||||
with self.section(
|
||||
"metrix",
|
||||
"section.metrix",
|
||||
when=lambda form: form["storage_mode"] == "metrix" or form["database_mode"] == "metrix",
|
||||
):
|
||||
with self.field("field.metrix_url"):
|
||||
self.text("metrix_url")
|
||||
with self.field("field.metrix_token"):
|
||||
self.secret("metrix_token")
|
||||
|
||||
with self.section("source", "section.source"):
|
||||
with self.field("field.storage_mode"):
|
||||
self.segment(
|
||||
{"metrix": t("option.storageMetrix"), "ftp": "FTP", "sftp": "SFTP"},
|
||||
"storage_mode",
|
||||
self.change_storage_mode,
|
||||
)
|
||||
metrix = lambda form: form["storage_mode"] == "metrix" # noqa: E731
|
||||
remote = lambda form: form["storage_mode"] != "metrix" # noqa: E731
|
||||
with self.field("field.metrix_storage_id", when=metrix):
|
||||
self.text("metrix_storage_id")
|
||||
with self.field("field.remote_host", when=remote):
|
||||
self.text("remote_host")
|
||||
with self.field("field.remote_port", when=remote):
|
||||
self.number("remote_port", 1, 65535)
|
||||
with self.field("field.remote_username", when=remote):
|
||||
self.text("remote_username").props("autocomplete=off")
|
||||
with self.field("field.remote_password", when=remote):
|
||||
self.secret("remote_password")
|
||||
with self.field("field.ftp_encoding", when=lambda form: form["storage_mode"] == "ftp"):
|
||||
self.bind(ui.select({"utf-8": "UTF-8", "gbk": "GBK", "gb18030": "GB18030"}), "ftp_encoding").props(
|
||||
"outlined dense options-dense"
|
||||
).classes("etl-input etl-input-short")
|
||||
with self.field("field.ftp_passive", when=lambda form: form["storage_mode"] == "ftp"):
|
||||
self.bind(ui.switch(), "ftp_passive").props("color=primary")
|
||||
with self.field("field.source_root"):
|
||||
self.text("source_root")
|
||||
with self.field("field.lookback_days"):
|
||||
self.number("lookback_days", 1, 31)
|
||||
with self.field("field.cell_data_directories", "field.cell_data_hint"):
|
||||
self.bind(ui.textarea(), "cell_data_directories").props("outlined dense autogrow").classes(
|
||||
"etl-input etl-textarea"
|
||||
)
|
||||
|
||||
with self.section("history", "section.history"):
|
||||
with self.field("field.history_enabled"):
|
||||
self.bind(ui.switch(), "history_enabled", self.sync_visibility).props("color=primary")
|
||||
with self.field("field.history_root", when=lambda form: bool(form["history_enabled"])):
|
||||
self.text("history_root")
|
||||
|
||||
with self.section("database", "section.database"):
|
||||
with self.field("field.database_mode"):
|
||||
self.segment({"metrix": t("option.databaseMetrix"), "mysql": t("option.mysql")}, "database_mode")
|
||||
metrix_db = lambda form: form["database_mode"] == "metrix" # noqa: E731
|
||||
mysql = lambda form: form["database_mode"] == "mysql" # noqa: E731
|
||||
with self.field("field.metrix_database_id", when=metrix_db):
|
||||
self.text("metrix_database_id")
|
||||
with self.field("field.mysql_host", when=mysql):
|
||||
self.text("mysql_host")
|
||||
with self.field("field.mysql_port", when=mysql):
|
||||
self.number("mysql_port", 1, 65535)
|
||||
with self.field("field.mysql_username", when=mysql):
|
||||
self.text("mysql_username").props("autocomplete=off")
|
||||
with self.field("field.mysql_password", when=mysql):
|
||||
self.secret("mysql_password")
|
||||
with self.field("field.database_name"):
|
||||
self.text("database_name")
|
||||
with self.field("field.table_name"):
|
||||
self.text("table_name")
|
||||
|
||||
with self.section("retention", "section.retention"):
|
||||
with self.field("field.keep_outputs"):
|
||||
self.number("keep_outputs", 1, 1000)
|
||||
with self.field("field.keep_runs"):
|
||||
self.number("keep_runs", 50, 100000)
|
||||
|
||||
with ui.element("div").classes("etl-save-bar"):
|
||||
self.check_box = ui.element("div").classes("etl-checks")
|
||||
self.test_button = ui.button(t("action.test"), icon="lan", on_click=self.test_connections).props(
|
||||
"outline no-caps"
|
||||
).classes("etl-btn")
|
||||
ui.button(t("action.save"), icon="save", on_click=self.save_settings).props(
|
||||
"unelevated no-caps color=primary"
|
||||
).classes("etl-btn etl-btn-primary")
|
||||
self.sync_visibility()
|
||||
|
||||
def load_form(self) -> None:
|
||||
data = public_view(self.service.settings.get())
|
||||
data["cell_data_directories"] = "\n".join(data["cell_data_directories"])
|
||||
self.form.clear()
|
||||
self.form.update(data)
|
||||
|
||||
@contextmanager
|
||||
def section(self, name: str, title_key: str, when: Callable[[dict[str, Any]], bool] | None = None) -> Iterator[None]:
|
||||
with ui.element("section").classes(f"etl-card etl-section etl-section-{name}") as section:
|
||||
ui.label(self.t(title_key)).classes("etl-section-title")
|
||||
with ui.element("div").classes("etl-fields"):
|
||||
yield
|
||||
if when is not None:
|
||||
self.conditional.append((section, when))
|
||||
|
||||
@contextmanager
|
||||
def field(
|
||||
self,
|
||||
label_key: str,
|
||||
hint_key: str | None = None,
|
||||
when: Callable[[dict[str, Any]], bool] | None = None,
|
||||
) -> Iterator[None]:
|
||||
with ui.element("div").classes("etl-field") as row:
|
||||
with ui.element("div").classes("etl-field-label"):
|
||||
ui.label(self.t(label_key))
|
||||
if hint_key:
|
||||
ui.label(self.t(hint_key)).classes("etl-field-hint")
|
||||
with ui.element("div").classes("etl-field-control"):
|
||||
yield
|
||||
if when is not None:
|
||||
self.conditional.append((row, when))
|
||||
|
||||
def bind(self, element: ValueElement, name: str, after: Callable[[Any], None] | None = None) -> ValueElement:
|
||||
element.value = self.form[name]
|
||||
|
||||
def changed(event: Any) -> None:
|
||||
self.form[name] = event.value
|
||||
if after is not None:
|
||||
after(event.value)
|
||||
|
||||
element.on_value_change(changed)
|
||||
self.inputs[name] = element
|
||||
return element
|
||||
|
||||
def set_form(self, name: str, value: Any) -> None:
|
||||
self.form[name] = value
|
||||
if name in self.inputs:
|
||||
self.inputs[name].value = value
|
||||
|
||||
def text(self, name: str) -> ValueElement:
|
||||
return self.bind(ui.input(), name).props("outlined dense").classes("etl-input")
|
||||
|
||||
def segment(self, options: dict[str, str], name: str, after: Callable[[Any], None] | None = None) -> None:
|
||||
self.bind(ui.toggle(options), name, after or self.sync_visibility).props(
|
||||
"no-caps unelevated dense toggle-color=primary"
|
||||
).classes("etl-segment")
|
||||
|
||||
def number(self, name: str, minimum: int, maximum: int) -> None:
|
||||
self.bind(ui.number(min=minimum, max=maximum, precision=0, step=1), name).props("outlined dense").classes(
|
||||
"etl-input etl-input-short"
|
||||
)
|
||||
|
||||
def secret(self, name: str) -> None:
|
||||
field = self.bind(ui.input(password=True), name).props("outlined dense autocomplete=new-password")
|
||||
field.classes("etl-input")
|
||||
self.secret_inputs[name] = field
|
||||
self.update_secret_placeholder(name)
|
||||
|
||||
def update_secret_placeholder(self, name: str) -> None:
|
||||
saved = bool(self.form.get(f"has_{name}"))
|
||||
self.secret_inputs[name].props["placeholder"] = self.t("secret.saved" if saved else "secret.empty")
|
||||
|
||||
def change_storage_mode(self, mode: str) -> None:
|
||||
port = int(self.form.get("remote_port") or 0)
|
||||
if mode == "sftp" and port in (0, 21):
|
||||
self.set_form("remote_port", 22)
|
||||
elif mode == "ftp" and port in (0, 22):
|
||||
self.set_form("remote_port", 21)
|
||||
self.sync_visibility()
|
||||
|
||||
def sync_visibility(self, *_: Any) -> None:
|
||||
for element, predicate in self.conditional:
|
||||
element.set_visibility(predicate(self.form))
|
||||
|
||||
def collect_form(self) -> dict[str, Any]:
|
||||
payload = {key: value for key, value in self.form.items() if not key.startswith("has_")}
|
||||
payload["cell_data_directories"] = str(self.form.get("cell_data_directories") or "")
|
||||
return payload
|
||||
|
||||
def save_settings(self) -> None:
|
||||
try:
|
||||
settings = self.service.update_settings(self.collect_form())
|
||||
except SettingsError as exc:
|
||||
ui.notify(self.error_text(exc), type="negative", position="top")
|
||||
return
|
||||
data = public_view(settings)
|
||||
for name in self.secret_inputs:
|
||||
self.form[f"has_{name}"] = data[f"has_{name}"]
|
||||
self.set_form(name, "")
|
||||
self.update_secret_placeholder(name)
|
||||
ui.notify(self.t("msg.saved"), type="positive", position="top")
|
||||
self.refresh()
|
||||
|
||||
async def test_connections(self) -> None:
|
||||
self.test_button.props("loading")
|
||||
self.check_box.clear()
|
||||
with self.check_box:
|
||||
ui.label(self.t("check.running")).classes("etl-muted")
|
||||
try:
|
||||
result = await run.io_bound(self.service.check_connections, self.collect_form())
|
||||
except SettingsError as exc:
|
||||
self.check_box.clear()
|
||||
ui.notify(self.error_text(exc), type="negative", position="top")
|
||||
return
|
||||
finally:
|
||||
self.test_button.props(remove="loading")
|
||||
self.check_box.clear()
|
||||
with self.check_box:
|
||||
storage, database = result["storage"], result["database"]
|
||||
self.check_line(
|
||||
"check.storage",
|
||||
storage,
|
||||
self.t("check.storageOk", count=storage.get("count", 0), latest=storage.get("latest", "-")),
|
||||
)
|
||||
self.check_line("check.database", database, self.t("check.databaseOk", latest=database.get("latest", "-")))
|
||||
|
||||
def check_line(self, label_key: str, result: dict[str, Any], ok_text: str) -> None:
|
||||
ok = bool(result.get("ok"))
|
||||
with ui.element("div").classes(f"etl-check {'is-ok' if ok else 'is-fail'}"):
|
||||
ui.icon("check_circle" if ok else "error")
|
||||
ui.label(self.t(label_key)).classes("etl-check-name")
|
||||
text = ok_text if ok else str(result.get("detail") or "")
|
||||
detail = ui.label(text).classes("etl-check-text")
|
||||
detail.props["title"] = text
|
||||
|
||||
# Text helpers
|
||||
|
||||
def schedule_text(self) -> str:
|
||||
if self.status["schedule_mode"] == "cron":
|
||||
return self.t("schedule.cron", expr=self.status["cron_expression"])
|
||||
return self.t("schedule.every", n=self.status["interval_minutes"])
|
||||
|
||||
def status_text(self, row: dict[str, Any]) -> str:
|
||||
if row["status"] == "processed" and row.get("dry_run"):
|
||||
return self.t("status.dryRunDone")
|
||||
return self.t(f"status.{row['status']}")
|
||||
|
||||
def trigger_text(self, trigger: str, dry_run: Any) -> str:
|
||||
if dry_run:
|
||||
return self.t("trigger.dryRun")
|
||||
return self.t(f"trigger.{trigger}")
|
||||
|
||||
def detail_text(self, row: dict[str, Any]) -> str:
|
||||
status, detail = row["status"], str(row.get("detail") or "")
|
||||
if status == "waiting":
|
||||
if not detail or detail == "no_source_files":
|
||||
return self.t("detail.noFiles")
|
||||
sources = [item for item in detail.split(",") if item]
|
||||
separator = "、" if self.t.lang == "zh" else ", "
|
||||
return self.t("detail.missing", count=len(sources), sources=separator.join(sources))
|
||||
if status == "skipped":
|
||||
return self.t("detail.upToDate", time=short_time(detail)) if detail else ""
|
||||
if status == "timeout":
|
||||
return self.t("detail.timeout", n=detail)
|
||||
if status == "processed" and row.get("dry_run"):
|
||||
return self.t("detail.dryRunOutput")
|
||||
if status in ("processed", "history_repaired"):
|
||||
return posixpath.basename(detail.replace("\\", "/"))
|
||||
return detail
|
||||
|
||||
def error_text(self, exc: SettingsError) -> str:
|
||||
field = self.t(f"field.{exc.field}") if exc.field else ""
|
||||
return self.t(f"error.{exc.key}", field=field, **exc.params)
|
||||
@@ -1,50 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
import main
|
||||
|
||||
from .config import SettingsStore
|
||||
from .connectors import build_client, build_storage, build_store, close_quietly
|
||||
|
||||
|
||||
def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int:
|
||||
settings = SettingsStore(settings_path).get()
|
||||
print(f"storage_mode={settings.storage_mode}")
|
||||
print(f"database_mode={'none' if dry_run else settings.database_mode}")
|
||||
client = build_client(settings)
|
||||
storage = build_storage(settings, client)
|
||||
try:
|
||||
source = main.StorageSource(storage, settings.source_root, settings.cell_data_directories)
|
||||
store = None if dry_run else build_store(settings, client)
|
||||
history = None
|
||||
if store is not None and settings.history_enabled:
|
||||
history = main.StorageHistoryStore(storage, settings.history_root)
|
||||
main.process(source, output_dir, settings.lookback_days, store=store, history=history)
|
||||
finally:
|
||||
close_quietly(storage)
|
||||
return 0
|
||||
|
||||
|
||||
def entry(argv: list[str] | None = None) -> int:
|
||||
parser = argparse.ArgumentParser(description="Run one InterferenceETL pass with the saved app settings")
|
||||
parser.add_argument("--settings", type=Path, required=True)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
parser.add_argument("--dry-run", action="store_true")
|
||||
args = parser.parse_args(argv)
|
||||
try:
|
||||
return run(args.settings, args.output, args.dry_run)
|
||||
except main.ProcessingError as exc:
|
||||
print(f"error={exc}", file=sys.stderr, flush=True)
|
||||
return 1
|
||||
except Exception as exc:
|
||||
traceback.print_exc()
|
||||
print(f"error={type(exc).__name__}: {exc}", file=sys.stderr, flush=True)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(entry())
|
||||
@@ -94,7 +94,6 @@ CELL_DATA_FILE_RE = re.compile(r"(?P<date>20\d{6})\.xlsx$", re.IGNORECASE)
|
||||
LTE_PLMN = "460-00"
|
||||
DATABASE_NAME = "interference_etl"
|
||||
DATABASE_TABLE = "interference_hourly_summary"
|
||||
SQL_IDENTIFIER_RE = re.compile(r"[A-Za-z0-9_]{1,64}")
|
||||
DEFAULT_HISTORY_ROOT = f"{DEFAULT_ROOT}/干扰历史数据"
|
||||
LOCAL_CSV_ENCODING = "utf-8-sig"
|
||||
HISTORY_CSV_ENCODING = "gbk"
|
||||
@@ -211,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
|
||||
|
||||
@@ -287,16 +244,6 @@ class HistoryStore(Protocol):
|
||||
def upload(self, metric_time: datetime, payload: bytes) -> str: ...
|
||||
|
||||
|
||||
class FileStorage(Protocol):
|
||||
def list_dir(self, path: str) -> list[dict[str, object]]: ...
|
||||
|
||||
def read_bytes(self, path: str) -> bytes: ...
|
||||
|
||||
def make_dir(self, path: str) -> None: ...
|
||||
|
||||
def write_bytes(self, directory: str, filename: str, payload: bytes) -> str: ...
|
||||
|
||||
|
||||
class MetrixApiClient:
|
||||
def __init__(self, base_url: str, token: str) -> None:
|
||||
if not token:
|
||||
@@ -386,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 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)
|
||||
@@ -423,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,
|
||||
},
|
||||
@@ -464,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")
|
||||
@@ -477,42 +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 ping(self) -> str:
|
||||
payload = self.client.get_json(self._endpoint("server-info"))
|
||||
if not isinstance(payload, dict):
|
||||
raise ProcessingError("Metrix Database API returned invalid server info")
|
||||
return str(payload.get("version") or payload.get("server_version") or "")
|
||||
|
||||
def _ensure_schema(self) -> None:
|
||||
self._query(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")
|
||||
@@ -545,137 +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 _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 _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"]
|
||||
|
||||
|
||||
class ApiHistoryStore(StorageHistoryStore):
|
||||
def __init__(self, client: MetrixApiClient, storage_id: str, root: str = DEFAULT_HISTORY_ROOT) -> None:
|
||||
super().__init__(MetrixStorage(client, storage_id), root)
|
||||
|
||||
|
||||
class StorageSource:
|
||||
def __init__(
|
||||
self,
|
||||
storage: FileStorage,
|
||||
root: str,
|
||||
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
|
||||
) -> None:
|
||||
self.storage = storage
|
||||
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
|
||||
|
||||
|
||||
class ApiSource(StorageSource):
|
||||
def __init__(
|
||||
self,
|
||||
client: MetrixApiClient,
|
||||
storage_id: str,
|
||||
root: str,
|
||||
cell_data_directories: tuple[str, ...] | list[str] = CELL_DATA_DIRECTORIES,
|
||||
) -> None:
|
||||
super().__init__(MetrixStorage(client, storage_id), root, cell_data_directories)
|
||||
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}")
|
||||
|
||||
@@ -692,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 = [
|
||||
@@ -877,7 +830,6 @@ def process(
|
||||
history: HistoryStore | None = None,
|
||||
) -> Path | None:
|
||||
candidates = source.candidates(lookback_days)
|
||||
progress(f"scanned {len(candidates)} source archives")
|
||||
metric_time, selected, missing = select_window(candidates, requested_window)
|
||||
if metric_time is None:
|
||||
print("status=waiting")
|
||||
@@ -913,12 +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)
|
||||
progress(f"loaded {len(cell_data_workbooks)} cell data workbooks with {len(cell_metadata)} cells")
|
||||
output_key = metric_time.strftime("%Y%m%d%H%M%S")
|
||||
temp_dir = output_root.resolve() / f".{output_key}.tmp-{os.getpid()}"
|
||||
final_dir = output_root.resolve() / output_key
|
||||
@@ -938,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):
|
||||
@@ -966,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(),
|
||||
@@ -1022,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,
|
||||
@@ -1199,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:
|
||||
|
||||
@@ -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
|
||||
@@ -1,127 +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,
|
||||
"user_auth": "metrix",
|
||||
"admin_auth": "metrix",
|
||||
"admin_path": "/admin",
|
||||
"icon": "icon.svg",
|
||||
"services": [
|
||||
{"name": "web", "image": image, "image_file": "image.tar", "command": "", "port": WEB_PORT},
|
||||
],
|
||||
"data_dir": DATA_DIR,
|
||||
"env": {"TZ": "Asia/Shanghai"},
|
||||
}
|
||||
|
||||
|
||||
def _run(command: list[str]) -> None:
|
||||
print("+ " + " ".join(command), flush=True)
|
||||
subprocess.run(command, cwd=ROOT, check=True)
|
||||
|
||||
|
||||
def build_image(image: str, args: argparse.Namespace) -> None:
|
||||
command = ["docker", "build", "-f", "deploy/Dockerfile", "-t", image]
|
||||
for key, value in (("PYTHON_IMAGE", args.python_image), ("PIP_INDEX", args.pip_index)):
|
||||
if value:
|
||||
command += ["--build-arg", f"{key}={value}"]
|
||||
command.append(".")
|
||||
_run(command)
|
||||
|
||||
|
||||
def write_bundle(image: str, release: str, target: Path) -> None:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
partial = target.with_name(target.name + ".partial")
|
||||
with tempfile.TemporaryDirectory(prefix="interference-etl-pack-", dir=target.parent) as work:
|
||||
tar = Path(work) / "image.tar"
|
||||
_run(["docker", "save", "-o", str(tar), image])
|
||||
with zipfile.ZipFile(partial, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=6) as bundle:
|
||||
bundle.writestr("metrix-app.json", json.dumps(manifest(image, release), ensure_ascii=False, indent=2) + "\n")
|
||||
bundle.write(ROOT / "etl_app" / "static" / "icon.svg", "icon.svg")
|
||||
bundle.write(tar, "image.tar")
|
||||
os.replace(partial, target)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Build the InterferenceETL Metrix app bundle")
|
||||
parser.add_argument("--skip-build", action="store_true", help="package the existing local image of this version")
|
||||
parser.add_argument("--python-image", default=os.environ.get("ETL_PYTHON_IMAGE", ""), help="base Python image")
|
||||
parser.add_argument("--pip-index", default=os.environ.get("ETL_PIP_INDEX", ""), help="pip index URL")
|
||||
parser.add_argument("--output", default=str(ROOT / "dist" / "metrix"), help="output directory")
|
||||
args = parser.parse_args()
|
||||
|
||||
if shutil.which("docker") is None:
|
||||
print("docker not found", file=sys.stderr)
|
||||
return 1
|
||||
current = version()
|
||||
image = f"{SLUG}:{current}"
|
||||
if not args.skip_build:
|
||||
build_image(image, args)
|
||||
target = Path(args.output).resolve() / f"{SLUG}-{current}.zip"
|
||||
write_bundle(image, current, target)
|
||||
size = target.stat().st_size
|
||||
print(f"bundle: {target}")
|
||||
print(f"size: {size / 1024 / 1024:.1f} MB ({size} bytes)")
|
||||
print(f"image: {image}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -1,715 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import ftplib
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from unittest import mock
|
||||
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
import main
|
||||
from etl_app import auth, connectors, worker
|
||||
from etl_app.config import Settings, SettingsError, SettingsStore, public_view, validate
|
||||
from etl_app.data import DataBrowser, DataQuery, cell, difference, where_clause
|
||||
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_prune_keeps_latest_outputs(self) -> None:
|
||||
output = Path(self.temp.name) / "output"
|
||||
for name in ("20260731090000", "20260731100000", ".20260731110000.tmp-1"):
|
||||
(output / name).mkdir(parents=True)
|
||||
self.run_mode("processed")
|
||||
self.assertEqual(sorted(path.name for path in output.iterdir()), ["20260731100000"])
|
||||
|
||||
def test_parse_output_reads_last_values(self) -> None:
|
||||
self.assertEqual(parse_output("status=waiting\nnoise line\nstatus=processed\n"), {"status": "processed"})
|
||||
|
||||
|
||||
class SchedulerTest(unittest.TestCase):
|
||||
def test_apply_switches_triggers(self) -> None:
|
||||
scheduler = EtlScheduler(mock.Mock())
|
||||
scheduler.start(Settings())
|
||||
try:
|
||||
self.assertIsNone(scheduler.next_run_time())
|
||||
scheduler.apply(Settings(schedule_enabled=True, interval_minutes=5))
|
||||
first = scheduler.next_run_time()
|
||||
self.assertIsNotNone(first)
|
||||
scheduler.apply(Settings(schedule_enabled=True, schedule_mode="cron", cron_expression="0 3 * * *"))
|
||||
cron_next = scheduler.next_run_time()
|
||||
assert cron_next is not None
|
||||
self.assertEqual((cron_next.hour, cron_next.minute), (3, 0))
|
||||
scheduler.apply(Settings(schedule_enabled=False))
|
||||
self.assertIsNone(scheduler.next_run_time())
|
||||
finally:
|
||||
scheduler.shutdown()
|
||||
|
||||
|
||||
class AuthTest(unittest.TestCase):
|
||||
def test_identity_requires_matching_proxy_token(self) -> None:
|
||||
headers = {
|
||||
"x-metrix-proxy-token": "secret",
|
||||
"x-metrix-username": "admin",
|
||||
"x-metrix-display-name": "%E7%AE%A1%E7%90%86%E5%91%98",
|
||||
"x-metrix-app-role": "admin",
|
||||
}
|
||||
with mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "secret"}, clear=False):
|
||||
identity = auth.identify(headers)
|
||||
assert identity is not None
|
||||
self.assertTrue(identity.is_admin)
|
||||
self.assertEqual(identity.label, "管理员")
|
||||
self.assertIsNone(auth.identify({**headers, "x-metrix-proxy-token": "wrong"}))
|
||||
|
||||
def test_dev_identity_only_without_proxy_token(self) -> None:
|
||||
with mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "", "ETL_DEV_ADMIN": "1"}, clear=False):
|
||||
self.assertIsNotNone(auth.identify({}))
|
||||
with mock.patch.dict(os.environ, {"METRIX_APP_PROXY_TOKEN": "secret", "ETL_DEV_ADMIN": "1"}, clear=False):
|
||||
self.assertIsNone(auth.identify({}))
|
||||
|
||||
|
||||
class ApiTest(unittest.TestCase):
|
||||
def test_admin_api_requires_proxy_identity(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp, mock.patch.dict(
|
||||
os.environ, {"METRIX_APP_PROXY_TOKEN": "secret"}, clear=False
|
||||
):
|
||||
service = EtlService(Path(temp))
|
||||
with TestClient(build_api(service)) as client:
|
||||
self.assertEqual(client.get("/").status_code, 200)
|
||||
self.assertEqual(client.get("/api/status").status_code, 401)
|
||||
member = {"x-metrix-proxy-token": "secret", "x-metrix-app-role": "user"}
|
||||
self.assertEqual(client.get("/api/status", headers=member).status_code, 403)
|
||||
|
||||
admin = {"x-metrix-proxy-token": "secret", "x-metrix-app-role": "admin"}
|
||||
self.assertFalse(client.get("/api/status", headers=admin).json()["configured"])
|
||||
self.assertEqual(client.post("/api/runs", headers=admin).status_code, 409)
|
||||
invalid = client.put("/api/settings", headers=admin, json={"interval_minutes": 0})
|
||||
self.assertEqual(invalid.status_code, 422)
|
||||
self.assertEqual(invalid.json()["field"], "interval_minutes")
|
||||
|
||||
saved = client.put("/api/settings", headers=admin, json=complete_settings(schedule_enabled=True))
|
||||
self.assertEqual(saved.status_code, 200)
|
||||
self.assertEqual(saved.json()["metrix_token"], "")
|
||||
status = client.get("/api/status", headers=admin).json()
|
||||
self.assertTrue(status["schedule_enabled"])
|
||||
self.assertTrue(status["next_run_at"])
|
||||
self.assertEqual(client.get("/api/runs", headers=admin).json(), {"items": [], "total": 0})
|
||||
self.assertEqual(client.get("/api/runs/1/log", headers=admin).status_code, 404)
|
||||
|
||||
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}"
|
||||
|
||||
|
||||
class WorkerTest(unittest.TestCase):
|
||||
def test_worker_processes_with_configured_storage_and_store(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp) / "remote"
|
||||
create_archive_tree = root / "source"
|
||||
for source_type in main.EXPECTED_TYPES:
|
||||
create_archive(create_archive_tree, source_type, COMPLETE_WINDOW)
|
||||
create_cell_data_sources(root)
|
||||
(root / "history").mkdir()
|
||||
settings_path = Path(temp) / "settings.json"
|
||||
SettingsStore(settings_path).update(
|
||||
complete_settings(source_root="/source", history_root="/history", lookback_days=3)
|
||||
)
|
||||
store = RecordingStore()
|
||||
output = io.StringIO()
|
||||
with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object(
|
||||
worker, "build_store", return_value=store
|
||||
), contextlib.redirect_stdout(output):
|
||||
self.assertEqual(worker.run(settings_path, Path(temp) / "output", dry_run=False), 0)
|
||||
|
||||
self.assertIn("status=processed", output.getvalue())
|
||||
self.assertEqual(len(store.rows), 2)
|
||||
archived = list((root / "history" / "2026-07-31").iterdir())
|
||||
self.assertEqual(len(archived), 1)
|
||||
|
||||
def test_dry_run_skips_database_and_history(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp) / "remote"
|
||||
for source_type in main.EXPECTED_TYPES:
|
||||
create_archive(root / "source", source_type, COMPLETE_WINDOW)
|
||||
create_cell_data_sources(root)
|
||||
settings_path = Path(temp) / "settings.json"
|
||||
SettingsStore(settings_path).update(complete_settings(source_root="/source", history_root="/history"))
|
||||
build_store = mock.Mock()
|
||||
output = io.StringIO()
|
||||
with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object(
|
||||
worker, "build_store", build_store
|
||||
), contextlib.redirect_stdout(output):
|
||||
worker.run(settings_path, Path(temp) / "output", dry_run=True)
|
||||
|
||||
build_store.assert_not_called()
|
||||
self.assertIn("database_mode=none", output.getvalue())
|
||||
self.assertFalse((root / "history").exists())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user