From 1c5c32bfdc84c86a2f15e1899bd0ab18faab3d65 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Thu, 12 Nov 2026 11:53:12 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=8F=AA=E4=BF=9D=E7=95=99=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=85=A5=E5=8F=A3=EF=BC=8C=E7=BC=93=E5=AD=98=E5=B0=8F?= =?UTF-8?q?=E5=8C=BA=E4=BF=A1=E6=81=AF=E8=A1=A8=E8=A7=A3=E6=9E=90=EF=BC=8C?= =?UTF-8?q?=E8=BF=9E=E6=8E=A5=E4=B8=AD=E6=98=BE=E7=A4=BA=E6=8F=90=E7=A4=BA?= =?UTF-8?q?=EF=BC=8C=E7=A7=BB=E9=99=A4=E8=84=9A=E6=9C=AC=E7=AE=A1=E7=90=86?= =?UTF-8?q?=E6=89=93=E5=8C=85=E6=96=B9=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .dockerignore | 2 - Dockerfile | 8 -- README.md | 94 +++++------------- aidocs/project_context.md | 134 ------------------------- etl_app/config.py | 5 +- etl_app/connectors.py | 10 -- etl_app/i18n.py | 7 +- etl_app/runner.py | 14 +++ etl_app/server.py | 13 +-- etl_app/theme.py | 9 ++ etl_app/ui.py | 25 ++++- etl_app/worker.py | 35 ++++--- main.py | 165 +++++++++++++++++-------------- requirements.txt | 1 - runtime_config.example.py | 3 - scripts/build_offline_package.py | 122 ----------------------- scripts/package_metrix.py | 2 +- tests/test_app.py | 77 ++++++++++++++- tests/test_pipeline.py | 48 ++++++++- 19 files changed, 317 insertions(+), 457 deletions(-) delete mode 100644 Dockerfile delete mode 100644 aidocs/project_context.md delete mode 100644 requirements.txt delete mode 100644 runtime_config.example.py delete mode 100644 scripts/build_offline_package.py diff --git a/.dockerignore b/.dockerignore index b9d905c..47172bd 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,6 +1,4 @@ * -!Dockerfile -!requirements.txt !requirements-app.txt !main.py !etl_app/ diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 4edffa1..0000000 --- a/Dockerfile +++ /dev/null @@ -1,8 +0,0 @@ -FROM python:3.13.11-slim - -COPY requirements.txt /tmp/requirements.txt -RUN pip install --no-cache-dir -r /tmp/requirements.txt - -WORKDIR /workspace - -CMD ["python", "main.py"] diff --git a/README.md b/README.md index 0c6d62e..ee56226 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # InterferenceETL -InterferenceETL follows the newest interference KPI time group in Metrix storage. It reads seven ZIP/XLSX source types, converts each `Sheet0` to CSV, and creates one merged high-interference summary. +InterferenceETL follows the newest interference KPI time group in the configured file source. It reads seven ZIP/XLSX source types, converts each `Sheet0` to CSV, and creates one merged high-interference summary. It runs as a hosted app in Metrix App Hosting with an admin page at `/admin`. Source file names are identified by one of the seven fixed prefixes plus a final `_YYYYMMDDHHMMHHMM.zip`; text between the prefix and time is unrestricted. Only the first `YYYYMMDDHHMM` start time is used for grouping. Start times are rounded down to natural 15-minute boundaries, so `12:00` through `12:14` belong to `12:00`. This also works unchanged when all providers switch together to hourly or daily delivery. -Every run follows only the group containing the newest source start time. It never falls back or backfills an older group. If any source type is missing, the script prints `status=waiting` with the missing types and exits successfully. When one source has multiple files in the group, its latest start time wins. +Every run follows only the group containing the newest source start time. It never falls back or backfills an older group. If any source type is missing, the run reports `status=waiting` with the missing types and ends successfully. When one source has multiple files in the group, its latest start time wins. ## Output @@ -20,7 +20,9 @@ output/20260731100000/ └── manifest.json ``` -For every processed group, the script also reads the latest filename-dated XLSX from each configured CellData directory. It builds CellData CGI as `460-00-{eNB/gNB}-{CI}` and adds coordinates plus direction angle to matching interference rows. Unmatched rows keep empty coordinates and use `0` for azimuth. +For every processed group, the run also reads the latest filename-dated XLSX from each configured CellData directory. It builds CellData CGI as `460-00-{eNB/gNB}-{CI}` and adds coordinates plus direction angle to matching interference rows. Unmatched rows keep empty coordinates and use `0` for azimuth. + +In each CellData directory, only XLSX files ending with a valid `YYYYMMDD.xlsx` date are considered, and the latest date is selected. CellData column `方向角` maps to summary/database column `azimuth`; an empty source value becomes `0`. Parsing these workbooks is the slow part of a run, so the parsed result of each workbook is kept in `/data/cache/cell-data/`, named after the SHA-256 of the workbook bytes. A workbook is parsed again whenever its content changes; entries that the latest run did not use are removed. The summary columns are: @@ -40,44 +42,32 @@ When multiple retained source rows have the same CGI, the summary keeps the row `prev_interference_dbm`, `prev_nearby_count`, and the four `prev_nearby_26g/700m/tdd/fdd` fields come from the previously retained database time, matched by CGI before the current batch replaces old rows. They represent the same cell's previous-period interference value and nearby high-interference counts. On the first run, or when a CGI did not exist in the previous period, these fields are empty in CSV/history output and `NULL` in MySQL. -The script never modifies or deletes source storage files. Before downloading source ZIP files or CellData, it compares the normalized target time with the database. A target already present, or older than the database, is not processed again. +A run never modifies or deletes source ZIP or CellData files. Before downloading source ZIP files or CellData, it compares the normalized target time with the database. A target already present, or older than the database, is not processed again. -The database table contains normalized `metric_time DATETIME`, `network_type VARCHAR(16)`, `interference_dbm DECIMAL(10,3)`, nullable `prev_interference_dbm DECIMAL(10,3)`, nullable `longitude` and `latitude`, `azimuth DECIMAL(6,2) NOT NULL DEFAULT 0`, the five `NOT NULL DEFAULT 0` INT count columns (`nearby_count`, `nearby_26g`, `nearby_700m`, `nearby_tdd`, `nearby_fdd`), and the five nullable INT previous-period count columns (`prev_nearby_count`, `prev_nearby_26g`, `prev_nearby_700m`, `prev_nearby_tdd`, `prev_nearby_fdd`). A successful transaction replaces the target batch and deletes every other database time, so the table retains only the latest processed group. The previous-period values are read before this replacement transaction. +The database table contains normalized `metric_time DATETIME`, `network_type VARCHAR(16)`, `interference_dbm DECIMAL(10,3)`, nullable `prev_interference_dbm DECIMAL(10,3)`, nullable `longitude` and `latitude`, `azimuth DECIMAL(6,2) NOT NULL DEFAULT 0`, the five `NOT NULL DEFAULT 0` INT count columns (`nearby_count`, `nearby_26g`, `nearby_700m`, `nearby_tdd`, `nearby_fdd`), and the five nullable INT previous-period count columns (`prev_nearby_count`, `prev_nearby_26g`, `prev_nearby_700m`, `prev_nearby_tdd`, `prev_nearby_fdd`). A successful transaction replaces the target batch and deletes every other database time, so the table retains only the latest processed group. The previous-period values are read before this replacement transaction. The database and table are created automatically when they do not exist. -After the database succeeds, the same nineteen result columns are uploaded as GBK CSV to: +After the database succeeds, the same nineteen result columns are uploaded as GBK CSV to the history directory: ```text /网优日常优化数据文档/(勿删)干扰定时小时指标/干扰历史数据/YYYY-MM-DD/干扰数据处理结果_YYYYMMDDHHMMSS.csv - -History retention reads those names, not file modification times. It keeps the latest 7 calendar days by default and deletes older date directories and result files from the file source. Set the retention days to 0 to keep everything. ``` -The filename time comes from normalized `metric_time`, never the server clock. If the database already contains the target time but its history CSV is missing or empty, the script exports that time from the database and repairs the history file without reprocessing source data. +The filename time comes from normalized `metric_time`, never the server clock. If the database already contains the target time but its history CSV is missing or empty, the run exports that time from the database and repairs the history file without reprocessing source data. -Only the final history CSV uploaded to Metrix Storage uses GBK without a UTF-8 BOM. Source non-breaking spaces (`U+00A0`) are normalized to ordinary spaces in this history file because GBK cannot encode them; other unsupported characters still fail visibly. The seven local converted CSV files and local merged summary remain UTF-8 with BOM, and `manifest.json` remains UTF-8 JSON. +History retention reads the directory and file names, not file modification times. It keeps the latest 7 calendar days by default and deletes older date directories and result files from the file source. It runs after a new group has been stored; a failure there is written to the run log and does not fail the run. Set the retention days to 0 to keep everything. + +Only the history CSV uses GBK without a UTF-8 BOM. Source non-breaking spaces (`U+00A0`) are normalized to ordinary spaces in this history file because GBK cannot encode them; other unsupported characters still fail visibly. The seven local converted CSV files and local merged summary remain UTF-8 with BOM, and `manifest.json` remains UTF-8 JSON. CGI is generated with fixed rules: - NR (`5G干扰监控`, `700M干扰监控`): `{gNBplmn}-{gNBId}-{cellId}`. - 4G (the other five source types): `460-00-{eNodeBID}-{小区ID}`, using each source schema's actual equivalent column names. -The Metrix API address, API Token, and database connection ID are constants in `runtime_config.py`; they are not project environment variables. Copy `runtime_config.example.py` to `runtime_config.py` and fill in the actual Token and the `conn_id` of `ShareMySQL`. The fixed database is `interference_etl`, the fixed table is `interference_hourly_summary`, and the script creates both automatically when they do not exist. - -The five CellData directories are fixed in `CELL_DATA_DIRECTORIES`. In each directory, only XLSX files ending with a valid `YYYYMMDD.xlsx` date are considered, and the latest date is selected. CellData column `方向角` maps to summary/database column `azimuth`; an empty source value becomes `0`. - -## Local development - -```powershell -python -m pip install -r requirements.txt -python -m unittest discover -s tests -v -python main.py --source-dir C:\path\to\mock-or-exported-tree --output-dir output --no-database -``` - -Use `--window 2026073110001100` to select the natural 15-minute group containing that source start time. Without it, the newest observed source start time determines the group. Incomplete groups wait and never fall back. - ## Metrix 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. +InterferenceETL runs as one long-lived container in Metrix App Hosting. A FastAPI + NiceGUI admin page at `/admin` (Metrix account, app admin role only) edits every setting, shows the live log, keeps the run history and browses the summary table with server-side paging (`GET /api/data?page=&page_size=20|50|100&network=&q=&sort=`). The app has no user page: its manifest declares `user_auth: none`, so the hosting list shows only the admin entry and Metrix admits app admins only on every path. + +The schedule runs inside the same container with APScheduler (fixed interval in minutes or a 5-field cron expression, timezone `Asia/Shanghai`). Each run is a child Python process inside that container, so no extra containers are started; one run at a time, with a per-run timeout. Settings live on the app data volume and are edited only through the admin page: @@ -86,7 +76,9 @@ Settings live on the app data volume and are edited only through the admin page: - 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). +Passwords and tokens are written to `/data/settings.json` (mode 0600) and never returned to the browser; a blank field keeps the saved value. Run records are in `/data/runs.db`, run logs in `/data/logs/`, local outputs in `/data/output/` (newest 48 kept by default), parsed CellData in `/data/cache/cell-data/`. + +The page content is sent over a live connection (WebSocket, with HTTP long-polling as the fallback). While that connection is being set up the page shows a connecting notice. If it stays there, something between the browser and Metrix is blocking the connection, for example a capture proxy set as the system proxy. Build the app bundle on a machine with docker, then upload it in App Hosting: @@ -96,61 +88,21 @@ python scripts\package_metrix.py The bundle `dist/metrix/interference-etl-.zip` contains `metrix-app.json`, `icon.svg` and `image.tar` built from `deploy/Dockerfile`. `--pip-index` and `--python-image` override the package index and base image. The schedule starts paused; enable it from the overview page after the connection test passes. -For local development of the app: +## Local development ```powershell python -m pip install -r requirements-app.txt +python -m unittest discover -s tests -v $env:METRIX_APP_DATA_DIR = "Temp\appdata"; $env:ETL_DEV_ADMIN = "1"; $env:PORT = "18090" python -m etl_app.server ``` `ETL_DEV_ADMIN=1` grants admin access only when no Metrix proxy token is configured. -## Metrix Script Management - -The target server is offline. Build the dependency image locally, then generate a self-contained Script Management upload ZIP: +To process a local copy of the source tree into CSV files without a database: ```powershell -docker build -t interference-etl-runtime:1.1 . -python scripts\build_offline_package.py +python main.py --source-dir C:\path\to\exported-tree --output-dir output ``` -The generated `dist/InterferenceETL-offline-1.1.zip` contains `main.py`, `runtime_config.py`, a ZIP execution entry point, and a `vendor/` directory containing `openpyxl` and `et_xmlfile`. The builder verifies imports and ZIP execution using the standard `python:3.13.11-slim` image, so the uploaded workspace does not need an online `pip install` or a custom runtime image. The build fails when `runtime_config.py` is missing. - -Create the project, then upload and extract the ZIP in its Script Management workspace. The normal file tree should contain `main.py` at `/workspace/main.py`. Use these project settings: - -```text -Name: InterferenceETL -Language: python -Base image: python:3.13.11-slim -Network: bridge -Run command: python main.py -Timeout: 1800 seconds -``` - -If the server keeps the ZIP as one file instead of extracting it, use `python InterferenceETL-offline-1.1.zip` as the run command. The ZIP contains `__main__.py` for this mode. - -Configure only run-specific source and output settings in the project environment: - -```json -{ - "METRIX_STORAGE_ID": "stg_4d9a910d72", - "INTERFERENCE_SOURCE_ROOT": "/网优日常优化数据文档/(勿删)干扰定时小时指标", - "INTERFERENCE_OUTPUT_DIR": "/workspace/output", - "INTERFERENCE_LOOKBACK_DAYS": "3" -} -``` - -Both storage reads and database writes use the Metrix API at `http://188.5.127.115:18271`. SSH remains the deployment and operational channel for uploading files, starting runs, and reading logs. - -## CLI options - -```text ---source-dir PATH Read a local directory tree instead of Metrix API ---output-dir PATH Output root, default output or INTERFERENCE_OUTPUT_DIR ---window WINDOW Select the natural 15-minute group for a 16-digit source window ---lookback-days N Number of newest date directories scanned, default 3 ---storage-id ID Metrix storage connection ID ---root PATH Source directory in Metrix storage ---no-database Generate CSV files without writing the database -``` +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. diff --git a/aidocs/project_context.md b/aidocs/project_context.md deleted file mode 100644 index 45616cd..0000000 --- a/aidocs/project_context.md +++ /dev/null @@ -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`. diff --git a/etl_app/config.py b/etl_app/config.py index 9462550..6f1f679 100644 --- a/etl_app/config.py +++ b/etl_app/config.py @@ -8,8 +8,6 @@ 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" @@ -122,6 +120,9 @@ def validate(data: dict[str, Any], current: Settings) -> Settings: } settings = Settings(**values) if settings.schedule_mode == "cron": + # Imported here so the worker process, which only reads saved settings, does not load the scheduler. + from apscheduler.triggers.cron import CronTrigger + try: CronTrigger.from_crontab(settings.cron_expression, timezone=TIMEZONE) except ValueError as exc: diff --git a/etl_app/connectors.py b/etl_app/connectors.py index a7a1bd6..cae5a33 100644 --- a/etl_app/connectors.py +++ b/etl_app/connectors.py @@ -342,16 +342,6 @@ class MySqlSummaryStore: 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() diff --git a/etl_app/i18n.py b/etl_app/i18n.py index 435273d..a4b60a9 100644 --- a/etl_app/i18n.py +++ b/etl_app/i18n.py @@ -58,7 +58,8 @@ MESSAGES: dict[str, dict[str, str]] = { "trigger.schedule": "定时", "trigger.manual": "手动", "trigger.dryRun": "试运行", - "detail.missing": "缺少 {count} 类:{sources}", "detail.noFiles": "未找到源文件", + "detail.missing": "缺少 {count} 类:{sources}", + "detail.noFiles": "未找到源文件", "detail.upToDate": "数据库已是 {time}", "detail.timeout": "超过 {n} 分钟未完成", "detail.dryRunOutput": "结果保存在本地", @@ -179,6 +180,8 @@ MESSAGES: dict[str, dict[str, str]] = { "error.invalidIdentifier": "“{field}”只能包含字母、数字和下划线", "forbidden.title": "无权访问", "forbidden.body": "只有应用管理员可以打开管理界面。", + "connect.title": "正在连接…", + "connect.slow": "连接时间比平时长。请检查浏览器代理或网络设置,然后刷新页面。", }, "en": { "app.title": "Interference ETL", @@ -358,6 +361,8 @@ MESSAGES: dict[str, dict[str, str]] = { "error.invalidIdentifier": "{field} may only contain letters, digits and underscores", "forbidden.title": "Access denied", "forbidden.body": "Only app administrators can open this page.", + "connect.title": "Connecting…", + "connect.slow": "This is taking longer than usual. Check the browser proxy or network settings, then refresh the page.", }, } diff --git a/etl_app/runner.py b/etl_app/runner.py index 4936189..c9b0abd 100644 --- a/etl_app/runner.py +++ b/etl_app/runner.py @@ -46,6 +46,7 @@ class Runner: self.data_dir = data_dir self.output_dir = data_dir / "output" self.log_dir = data_dir / "logs" + self.cache_dir = data_dir / "cache" / "cell-data" self.command = command or [sys.executable, "-m", "etl_app.worker"] self.seconds_per_minute = 60.0 self._lock = threading.Lock() @@ -101,6 +102,17 @@ class Runner: def _finish(self, run_id: int, dry_run: bool) -> None: try: self._execute(run_id, dry_run) + except Exception as exc: + # A record that never got its result would stay "running" until the next restart. + record = self.runs.get(run_id) + if record is not None and record["status"] == "running": + self.runs.finish( + run_id, + status="failed", + finished_at=now_text(), + detail=f"{type(exc).__name__}: {exc}"[:DETAIL_LIMIT], + ) + raise finally: self._process = None self._current = None @@ -125,6 +137,8 @@ class Runner: str(self.settings_store.path), "--output", str(self.output_dir), + "--cache", + str(self.cache_dir), *(["--dry-run"] if dry_run else []), ] env = {key: value for key, value in os.environ.items() if key != "METRIX_APP_PROXY_TOKEN"} diff --git a/etl_app/server.py b/etl_app/server.py index ce3d02c..f8e2235 100644 --- a/etl_app/server.py +++ b/etl_app/server.py @@ -7,19 +7,13 @@ from contextlib import asynccontextmanager from typing import Any from fastapi import Body, Depends, FastAPI, HTTPException -from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse +from fastapi.responses import JSONResponse, PlainTextResponse, RedirectResponse from .auth import Identity, require_admin from .config import SettingsError, data_dir, public_view from .data import DataQuery from .service import EtlService -LANDING_HTML = """ -干扰数据处理 - -干扰数据处理 -""" - def settings_error(exc: SettingsError) -> JSONResponse: return JSONResponse(status_code=422, content={"error": exc.key, "field": exc.field, "params": exc.params}) @@ -37,8 +31,9 @@ def build_api(service: EtlService) -> FastAPI: 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) + def landing() -> RedirectResponse: + # Relative on purpose: the app is served under a path prefix it does not know. + return RedirectResponse("admin") @api.get("/healthz") def health() -> dict[str, bool]: diff --git a/etl_app/theme.py b/etl_app/theme.py index 10d14ab..3b6069b 100644 --- a/etl_app/theme.py +++ b/etl_app/theme.py @@ -298,6 +298,15 @@ html, body { height: 100%; overflow: hidden; } .etl-check-name { font-weight: 600; flex-shrink: 0; } .etl-check-text { color: var(--etl-text); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.etl-connecting { + flex: 1; width: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; + gap: 12px; padding: 24px; text-align: center; color: var(--etl-muted); +} +.etl-connecting-spinner { color: var(--etl-primary); } +.etl-connecting-title { font-size: 14px; } +.etl-connecting-hint { max-width: 440px; font-size: 13px; line-height: 1.6; opacity: 0; animation: etl-reveal 0.3s ease 8s forwards; } +@keyframes etl-reveal { to { opacity: 1; } } + .etl-forbidden { min-height: 100vh; width: 100%; display: grid; place-items: center; } .etl-forbidden-card { padding: 40px 56px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center; } .etl-forbidden-icon { font-size: 40px; color: var(--etl-muted); } diff --git a/etl_app/ui.py b/etl_app/ui.py index 1d7d495..0663959 100644 --- a/etl_app/ui.py +++ b/etl_app/ui.py @@ -50,12 +50,23 @@ def register(service: EtlService) -> None: async def admin_page(request: Request, client: Client) -> None: ui.add_head_html(STYLE) identity = identify(request.headers) + accept = request.headers.get("accept-language", "").lower() + fallback = Translator("en" if accept.startswith("en") else "zh") 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")) + render_forbidden(fallback) return + # The page is built over the live connection. Until it is up, show that instead of an empty page. + connecting = render_connecting(fallback) await client.connected() - prefs = await ui.run_javascript(PREFS_JS, timeout=5) or {} + if client.is_deleted: + return + try: + prefs = await ui.run_javascript(PREFS_JS, timeout=5) or {} + except TimeoutError: + prefs = {"lang": fallback.lang} + if client.is_deleted: + return + connecting.delete() AdminPage(service, identity, prefs, tab_from_request(request)).build() @@ -64,6 +75,14 @@ def tab_from_request(request: Request) -> str: return tab if tab in TABS else "overview" +def render_connecting(t: Translator) -> Element: + with ui.element("div").classes("etl-connecting") as box: + ui.spinner(size="28px").classes("etl-connecting-spinner") + ui.label(t("connect.title")).classes("etl-connecting-title") + ui.label(t("connect.slow")).classes("etl-connecting-hint") + return box + + def render_forbidden(t: Translator) -> None: with ui.element("div").classes("etl-forbidden"): with ui.element("div").classes("etl-card etl-forbidden-card"): diff --git a/etl_app/worker.py b/etl_app/worker.py index 08ee844..94bca45 100644 --- a/etl_app/worker.py +++ b/etl_app/worker.py @@ -7,11 +7,11 @@ from pathlib import Path import main -from .config import SettingsStore +from .config import Settings, SettingsStore from .connectors import build_client, build_storage, build_store, close_quietly -def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int: +def run(settings_path: Path, output_dir: Path, dry_run: bool, cache_dir: Path | None = None) -> int: settings = SettingsStore(settings_path).get() print(f"storage_mode={settings.storage_mode}") print(f"database_mode={'none' if dry_run else settings.database_mode}") @@ -23,28 +23,39 @@ def run(settings_path: Path, output_dir: Path, dry_run: bool) -> int: history = None if store is not None and settings.history_enabled: history = main.StorageHistoryStore(storage, settings.history_root) - if not dry_run and settings.history_keep_days > 0: - try: - removed = main.StorageHistoryStore(storage, settings.history_root).prune(settings.history_keep_days) - except main.ProcessingError as exc: - print(f"history_prune_error={exc}") - else: - for path in removed: - print(f"history_removed={path}") - main.process(source, output_dir, settings.lookback_days, store=store, history=history) + cell_cache = main.CellDataCache(cache_dir) if cache_dir is not None else None + output = main.process( + source, output_dir, settings.lookback_days, store=store, history=history, cell_cache=cell_cache + ) + if output is not None and not dry_run: + prune_history(storage, settings) finally: close_quietly(storage) return 0 +def prune_history(storage: main.FileStorage, settings: Settings) -> None: + """Apply history retention after a new group was stored. The data is already saved, so a failure is only reported.""" + if settings.history_keep_days <= 0: + return + try: + removed = main.StorageHistoryStore(storage, settings.history_root).prune(settings.history_keep_days) + except Exception as exc: + print(f"history_prune_error={type(exc).__name__}: {exc}") + return + for path in removed: + print(f"history_removed={path}") + + def entry(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Run one InterferenceETL pass with the saved app settings") parser.add_argument("--settings", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--cache", type=Path, help="directory for parsed CellData workbooks") parser.add_argument("--dry-run", action="store_true") args = parser.parse_args(argv) try: - return run(args.settings, args.output, args.dry_run) + return run(args.settings, args.output, args.dry_run, args.cache) except main.ProcessingError as exc: print(f"error={exc}", file=sys.stderr, flush=True) return 1 diff --git a/main.py b/main.py index 83209a9..6fa942f 100644 --- a/main.py +++ b/main.py @@ -25,19 +25,6 @@ import zipfile from zoneinfo import ZoneInfo -VENDOR_DIR = Path(__file__).resolve().parent / "vendor" -sys.path.insert(0, str(VENDOR_DIR)) - -from openpyxl import load_workbook - -try: - from runtime_config import METRIX_API_BASE_URL, METRIX_API_TOKEN, METRIX_DATABASE_CONNECTION_ID -except ImportError: - METRIX_API_BASE_URL = "http://188.5.127.115:18271" - METRIX_API_TOKEN = "" - METRIX_DATABASE_CONNECTION_ID = "" - - EXPECTED_TYPES = ( "5G下FDD干扰监控", "5G干扰监控", @@ -91,6 +78,8 @@ CELL_DATA_DIRECTORIES = ( ) FILE_TIME_RE = re.compile(r"_(?P\d{16})\.zip$", re.IGNORECASE) CELL_DATA_FILE_RE = re.compile(r"(?P20\d{6})\.xlsx$", re.IGNORECASE) +# Raise this when parse_cell_data_workbook changes what it returns, so older cache files are ignored. +CELL_CACHE_VERSION = 1 LTE_PLMN = "460-00" DATABASE_NAME = "interference_etl" @@ -306,7 +295,7 @@ class FileStorage(Protocol): class MetrixApiClient: def __init__(self, base_url: str, token: str) -> None: if not token: - raise ProcessingError("METRIX_API_TOKEN is required for Metrix API access") + raise ProcessingError("Metrix API token is required") self.base_url = base_url.rstrip("/") self.token = token self.opener = build_opener(ProxyHandler({})) @@ -403,7 +392,7 @@ class ApiSummaryStore: table: str = DATABASE_TABLE, ) -> None: if not connection_id: - raise ProcessingError("METRIX_DATABASE_CONNECTION_ID is required for database output") + raise ProcessingError("Metrix database connection ID is required") self.client = client self.connection_id = connection_id self.database = sql_identifier(database, "database") @@ -493,12 +482,6 @@ class ApiSummaryStore: 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) @@ -673,11 +656,6 @@ def _calendar_day(parts: tuple[str, ...]) -> date | None: return None -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, @@ -724,17 +702,6 @@ class StorageSource: 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) - - class LocalSource: def __init__( self, @@ -810,11 +777,18 @@ def select_latest_cell_data_file(entries: list[dict[str, object]], directory: st return max(dated_files, key=lambda entry: (entry[0], entry[1]))[2] +def open_workbook(payload: bytes): + # Imported here because most runs find nothing new and never open a workbook. + from openpyxl import load_workbook + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", message="Workbook contains no default style") + return load_workbook(io.BytesIO(payload), read_only=True, data_only=True) + + def parse_cell_data_workbook(raw_xlsx: bytes, path: str) -> dict[str, tuple[str, str, str]]: try: - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", message="Workbook contains no default style") - workbook = load_workbook(io.BytesIO(raw_xlsx), read_only=True, data_only=True) + workbook = open_workbook(raw_xlsx) except Exception as exc: raise ProcessingError(f"Invalid CellData workbook {path}: {exc}") from exc try: @@ -856,14 +830,78 @@ def parse_cell_data_workbook(raw_xlsx: bytes, path: str) -> dict[str, tuple[str, workbook.close() -def load_cell_metadata(workbooks: list[tuple[str, bytes]]) -> dict[str, tuple[str, str, str]]: +class CellDataCache: + """Parsed CellData workbooks kept on disk. + + Parsing one workbook takes several seconds and the files change about once a day. + An entry is named after the SHA-256 of the workbook bytes, so a changed file is always parsed again. + """ + + def __init__(self, directory: Path) -> None: + self.directory = directory + self.hits = 0 + self._used: set[str] = set() + + def load(self, raw_xlsx: bytes, path: str) -> dict[str, tuple[str, str, str]]: + name = f"{hashlib.sha256(raw_xlsx).hexdigest()}.v{CELL_CACHE_VERSION}.json" + self._used.add(name) + cached = self._read(self.directory / name) + if cached is not None: + self.hits += 1 + return cached + cells = parse_cell_data_workbook(raw_xlsx, path) + self._write(self.directory / name, cells) + return cells + + def prune(self) -> None: + """Remove entries the current run did not use.""" + if not self.directory.is_dir(): + return + for item in self.directory.iterdir(): + if item.is_file() and item.name not in self._used: + item.unlink(missing_ok=True) + + @staticmethod + def _read(path: Path) -> dict[str, tuple[str, str, str]] | None: + try: + payload = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not isinstance(payload, dict): + return None + cells: dict[str, tuple[str, str, str]] = {} + for cgi, value in payload.items(): + if not isinstance(value, list) or len(value) != 3 or not all(isinstance(item, str) for item in value): + return None + cells[cgi] = (value[0], value[1], value[2]) + return cells + + @staticmethod + def _write(path: Path, cells: dict[str, tuple[str, str, str]]) -> None: + temp = path.with_name(f"{path.name}.tmp-{os.getpid()}") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temp.write_text(json.dumps(cells, ensure_ascii=False, separators=(",", ":")), encoding="utf-8") + os.replace(temp, path) + except OSError as exc: + temp.unlink(missing_ok=True) + progress(f"cell data cache was not saved: {exc}") + + +def load_cell_metadata( + workbooks: list[tuple[str, bytes]], + cache: CellDataCache | None = None, +) -> dict[str, tuple[str, str, str]]: metadata: dict[str, tuple[str, str, str]] = {} for path, raw_xlsx in workbooks: - for cgi, value in parse_cell_data_workbook(raw_xlsx, path).items(): + cells = cache.load(raw_xlsx, path) if cache is not None else parse_cell_data_workbook(raw_xlsx, path) + for cgi, value in cells.items(): existing = metadata.get(cgi) if existing is not None and existing != value: raise ProcessingError(f"Conflicting CellData metadata for {cgi} across workbooks") metadata[cgi] = value + if cache is not None: + cache.prune() return metadata @@ -915,9 +953,7 @@ def parse_workbook(raw_zip: bytes, source_type: str) -> tuple[tuple[str, ...], l except zipfile.BadZipFile as exc: raise ProcessingError("Invalid ZIP archive") from exc - with warnings.catch_warnings(): - warnings.filterwarnings("ignore", message="Workbook contains no default style") - workbook = load_workbook(io.BytesIO(workbook_bytes), read_only=True, data_only=True) + workbook = open_workbook(workbook_bytes) try: if "Sheet0" not in workbook.sheetnames: raise ProcessingError("Workbook does not contain Sheet0") @@ -942,6 +978,7 @@ def process( requested_window: str = "", store: SummaryStore | None = None, history: HistoryStore | None = None, + cell_cache: CellDataCache | None = None, ) -> Path | None: candidates = source.candidates(lookback_days) progress(f"scanned {len(candidates)} source archives") @@ -984,8 +1021,9 @@ def process( 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") + cell_metadata = load_cell_metadata(cell_data_workbooks, cell_cache) + reused = f", {cell_cache.hits} read from cache" if cell_cache is not None else "" + progress(f"loaded {len(cell_data_workbooks)} cell data workbooks with {len(cell_metadata)} cells{reused}") 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 @@ -1392,39 +1430,18 @@ def ensure_scoped(root: Path, target: Path) -> None: def build_parser() -> argparse.ArgumentParser: - parser = argparse.ArgumentParser(description="Process the latest complete interference KPI time group") - parser.add_argument("--source-dir", type=Path, help="Use a local source tree instead of the Metrix storage API") - parser.add_argument("--output-dir", type=Path, default=Path(os.getenv("INTERFERENCE_OUTPUT_DIR", "output"))) - parser.add_argument( - "--window", - default=os.getenv("INTERFERENCE_WINDOW", ""), - help="Optional 16-digit source window used to select a natural 15-minute group", + parser = argparse.ArgumentParser( + description="Process the newest complete time group of a local source tree into CSV files, without a database" ) - parser.add_argument("--lookback-days", type=int, default=int(os.getenv("INTERFERENCE_LOOKBACK_DAYS", "3"))) - parser.add_argument("--storage-id", default=os.getenv("METRIX_STORAGE_ID", DEFAULT_STORAGE_ID)) - parser.add_argument("--root", default=os.getenv("INTERFERENCE_SOURCE_ROOT", DEFAULT_ROOT)) - parser.add_argument("--no-database", action="store_true", help="Generate files without writing the database") + parser.add_argument("--source-dir", type=Path, required=True, help="Local copy of the source tree") + parser.add_argument("--output-dir", type=Path, default=Path("output")) + parser.add_argument("--window", default="", help="16-digit source window that selects a natural 15-minute group") return parser def main(argv: list[str] | None = None) -> int: args = build_parser().parse_args(argv) - if args.lookback_days < 1: - raise ProcessingError("lookback-days must be at least 1") - client: MetrixApiClient | None = None - if args.source_dir: - source: Source = LocalSource(args.source_dir) - else: - client = MetrixApiClient(METRIX_API_BASE_URL, METRIX_API_TOKEN) - source = ApiSource(client, args.storage_id, args.root) - if args.no_database: - store = None - history = None - else: - client = client or MetrixApiClient(METRIX_API_BASE_URL, METRIX_API_TOKEN) - store = ApiSummaryStore(client, METRIX_DATABASE_CONNECTION_ID) - history = ApiHistoryStore(client, args.storage_id, f"{args.root.rstrip('/')}/干扰历史数据") - process(source, args.output_dir, args.lookback_days, args.window, store=store, history=history) + process(LocalSource(args.source_dir), args.output_dir, lookback_days=1, requested_window=args.window) return 0 diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 61d7845..0000000 --- a/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -openpyxl==3.1.5 diff --git a/runtime_config.example.py b/runtime_config.example.py deleted file mode 100644 index f4c48d2..0000000 --- a/runtime_config.example.py +++ /dev/null @@ -1,3 +0,0 @@ -METRIX_API_BASE_URL = "http://188.5.127.115:18271" -METRIX_API_TOKEN = "replace-with-metrix-api-token" -METRIX_DATABASE_CONNECTION_ID = "replace-with-database-connection-id" diff --git a/scripts/build_offline_package.py b/scripts/build_offline_package.py deleted file mode 100644 index 417655d..0000000 --- a/scripts/build_offline_package.py +++ /dev/null @@ -1,122 +0,0 @@ -from __future__ import annotations - -import argparse -import hashlib -from pathlib import Path -import shutil -import subprocess -import tempfile -import zipfile - - -PROJECT_ROOT = Path(__file__).resolve().parents[1] -DEFAULT_IMAGE = "interference-etl-runtime:1.1" -DEFAULT_BASE_IMAGE = "python:3.13.11-slim" -DEFAULT_OUTPUT = PROJECT_ROOT / "dist" / "InterferenceETL-offline-1.1.zip" -PACKAGE_FILES = ("main.py", "requirements.txt", "README.md", "runtime_config.py") -PACKAGE_ENTRYPOINT = "from main import main\nraise SystemExit(main())\n" - -COPY_DEPENDENCIES = r""" -from importlib.metadata import distribution -from pathlib import Path -import shutil - -target = Path('/package/vendor') -for name in ('openpyxl', 'et-xmlfile'): - package = distribution(name) - for item in package.files or (): - if '__pycache__' in item.parts or item.suffix in ('.pyc', '.pyo'): - continue - source = Path(package.locate_file(item)) - if not source.is_file(): - continue - destination = target / item - destination.parent.mkdir(parents=True, exist_ok=True) - shutil.copy2(source, destination) -""" - - -def build(output: Path, runtime_image: str, base_image: str) -> Path: - output = output.resolve() - output.parent.mkdir(parents=True, exist_ok=True) - missing = [name for name in PACKAGE_FILES if not (PROJECT_ROOT / name).is_file()] - if missing: - raise FileNotFoundError(f"Missing package files: {', '.join(missing)}") - with tempfile.TemporaryDirectory(prefix="interference-etl-package-") as temp: - staging = Path(temp) - subprocess.run( - [ - "docker", - "run", - "--rm", - "-v", - f"{staging}:/package", - runtime_image, - "python", - "-c", - COPY_DEPENDENCIES, - ], - check=True, - ) - for name in PACKAGE_FILES: - shutil.copy2(PROJECT_ROOT / name, staging / name) - (staging / "__main__.py").write_text(PACKAGE_ENTRYPOINT, encoding="utf-8") - subprocess.run( - [ - "docker", - "run", - "--rm", - "-e", - "PYTHONDONTWRITEBYTECODE=1", - "-v", - f"{staging}:/workspace:ro", - "-w", - "/workspace", - base_image, - "python", - "-c", - "import main, openpyxl; print('offline_package_imports=ok')", - ], - check=True, - ) - if output.exists(): - output.unlink() - with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive: - for path in sorted(staging.rglob("*")): - if path.is_file(): - archive.write(path, path.relative_to(staging).as_posix()) - subprocess.run( - [ - "docker", - "run", - "--rm", - "-e", - "PYTHONDONTWRITEBYTECODE=1", - "-v", - f"{output.parent}:/dist:ro", - base_image, - "python", - f"/dist/{output.name}", - "--help", - ], - check=True, - ) - return output - - -def main() -> int: - parser = argparse.ArgumentParser(description="Build a self-contained Metrix Script Management upload ZIP") - parser.add_argument("--runtime-image", default=DEFAULT_IMAGE) - parser.add_argument("--base-image", default=DEFAULT_BASE_IMAGE) - parser.add_argument("--output", type=Path, default=DEFAULT_OUTPUT) - args = parser.parse_args() - output = build(args.output, args.runtime_image, args.base_image) - digest = hashlib.sha256(output.read_bytes()).hexdigest().upper() - print(f"output={output}") - print(f"size={output.stat().st_size}") - print(f"sha256={digest}") - return 0 - - -if __name__ == "__main__": - raise SystemExit(main()) diff --git a/scripts/package_metrix.py b/scripts/package_metrix.py index 13c0e4e..ff9d17f 100644 --- a/scripts/package_metrix.py +++ b/scripts/package_metrix.py @@ -64,7 +64,7 @@ def manifest(image: str, release: str) -> dict: "zh-CN": "从 SFTP 读取小时干扰指标,汇总后写入数据库,并按日期归档历史结果。", "en-US": "Reads hourly interference metrics from SFTP, writes the summary to the database, and archives history by date.", }, - "user_auth": "metrix", + "user_auth": "none", "admin_auth": "metrix", "admin_path": "/admin", "icon": "icon.svg", diff --git a/tests/test_app.py b/tests/test_app.py index 6f11b93..5014dc3 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -6,6 +6,7 @@ import io import json import os import shutil +import subprocess import sys import tempfile import time @@ -22,6 +23,7 @@ import main from etl_app import auth, connectors, worker from etl_app.config import Settings, SettingsError, SettingsStore, public_view, validate from etl_app.data import DataBrowser, DataQuery, cell, difference, where_clause +from etl_app.i18n import MESSAGES from etl_app.runner import Runner, parse_output from etl_app.runs import RunStore from etl_app.scheduler import EtlScheduler @@ -212,6 +214,24 @@ class RunnerTest(unittest.TestCase): time.sleep(0.05) self.assertEqual(self.runs.latest_finished()["status"], "cancelled") + def test_run_that_cannot_start_is_recorded_as_failed(self) -> None: + with mock.patch.object(self.runner, "_execute", side_effect=OSError("disk full")): + with self.assertRaises(OSError): + self.runner.run("manual") + + row = self.runs.latest_finished() + assert row is not None + self.assertEqual((row["status"], row["detail"]), ("failed", "OSError: disk full")) + self.assertFalse(self.runner.busy()) + + def test_worker_receives_the_cell_data_cache_directory(self) -> None: + self.mode_file.write_text("processed", encoding="utf-8") + with mock.patch("etl_app.runner.subprocess.Popen", wraps=subprocess.Popen) as popen: + self.runner.run("manual") + + command = popen.call_args.args[0] + self.assertEqual(command[command.index("--cache") + 1], str(Path(self.temp.name) / "cache" / "cell-data")) + def test_prune_keeps_latest_outputs(self) -> None: output = Path(self.temp.name) / "output" for name in ("20260731090000", "20260731100000", ".20260731110000.tmp-1"): @@ -242,6 +262,11 @@ class SchedulerTest(unittest.TestCase): scheduler.shutdown() +class TranslationTest(unittest.TestCase): + def test_both_languages_define_the_same_keys(self) -> None: + self.assertEqual(set(MESSAGES["zh"]), set(MESSAGES["en"])) + + class AuthTest(unittest.TestCase): def test_identity_requires_matching_proxy_token(self) -> None: headers = { @@ -271,7 +296,8 @@ class ApiTest(unittest.TestCase): ): service = EtlService(Path(temp)) with TestClient(build_api(service)) as client: - self.assertEqual(client.get("/").status_code, 200) + root = client.get("/", follow_redirects=False) + self.assertEqual((root.status_code, root.headers["location"]), (307, "admin")) self.assertEqual(client.get("/api/status").status_code, 401) member = {"x-metrix-proxy-token": "secret", "x-metrix-app-role": "user"} self.assertEqual(client.get("/api/status", headers=member).status_code, 403) @@ -685,19 +711,64 @@ class WorkerTest(unittest.TestCase): (root / "history").mkdir() settings_path = Path(temp) / "settings.json" SettingsStore(settings_path).update( - complete_settings(source_root="/source", history_root="/history", lookback_days=3) + complete_settings(source_root="/source", history_root="/history", lookback_days=3, history_keep_days=0) ) store = RecordingStore() + cache = Path(temp) / "cache" output = io.StringIO() with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object( worker, "build_store", return_value=store ), contextlib.redirect_stdout(output): - self.assertEqual(worker.run(settings_path, Path(temp) / "output", dry_run=False), 0) + self.assertEqual(worker.run(settings_path, Path(temp) / "output", dry_run=False, cache_dir=cache), 0) self.assertIn("status=processed", output.getvalue()) + # The five test workbooks have identical bytes: one is parsed, the others reuse its entry. + self.assertIn("4 read from cache", output.getvalue()) self.assertEqual(len(store.rows), 2) archived = list((root / "history" / "2026-07-31").iterdir()) self.assertEqual(len(archived), 1) + self.assertEqual(len(list(cache.iterdir())), 1) + + def test_history_retention_runs_only_after_a_group_is_stored(self) -> None: + with tempfile.TemporaryDirectory() as temp: + root = Path(temp) / "remote" + for source_type in main.EXPECTED_TYPES: + create_archive(root / "source", source_type, COMPLETE_WINDOW) + create_cell_data_sources(root) + expired = root / "history" / "2020-01-01" + expired.mkdir(parents=True) + settings_path = Path(temp) / "settings.json" + SettingsStore(settings_path).update( + complete_settings(source_root="/source", history_root="/history", history_keep_days=7) + ) + + def run(store: RecordingStore, dry_run: bool = False) -> str: + output = io.StringIO() + with mock.patch.object(worker, "build_storage", return_value=LocalFileStorage(root)), mock.patch.object( + worker, "build_store", return_value=store + ), contextlib.redirect_stdout(output): + worker.run(settings_path, Path(temp) / "output", dry_run=dry_run) + return output.getvalue() + + self.assertIn("status=processed", run(RecordingStore(), dry_run=True)) + self.assertIn("status=skipped", run(RecordingStore(datetime(2026, 8, 1)))) + self.assertTrue(expired.exists()) + + stored = run(RecordingStore()) + + self.assertIn("status=processed", stored) + self.assertIn("history_removed=/history/2020-01-01", stored) + self.assertFalse(expired.exists()) + + def test_failed_history_retention_keeps_the_run_successful(self) -> None: + settings = Settings(history_keep_days=7) + output = io.StringIO() + with mock.patch.object(main.StorageHistoryStore, "prune", side_effect=OSError("connection lost")), contextlib.redirect_stdout( + output + ): + worker.prune_history(mock.Mock(), settings) + + self.assertEqual(output.getvalue(), "history_prune_error=OSError: connection lost\n") def test_dry_run_skips_database_and_history(self) -> None: with tempfile.TemporaryDirectory() as temp: diff --git a/tests/test_pipeline.py b/tests/test_pipeline.py index e0e14f9..7ead34d 100644 --- a/tests/test_pipeline.py +++ b/tests/test_pipeline.py @@ -7,6 +7,7 @@ import json from pathlib import Path import tempfile import unittest +from unittest import mock import zipfile import main @@ -226,6 +227,51 @@ class PipelineTest(unittest.TestCase): self.assertEqual(metadata["460-00-200-1"], ("113.123456", "22.654321", "0")) + def test_cell_data_cache_parses_each_workbook_content_once(self) -> None: + first = create_cell_data_workbook(longitude=113.1) + changed = create_cell_data_workbook(longitude=113.2) + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) / "cache" + expected = main.parse_cell_data_workbook(first, "cell-data.xlsx") + + cold = main.CellDataCache(directory) + self.assertEqual(main.load_cell_metadata([("cell-data.xlsx", first)], cold), expected) + self.assertEqual(cold.hits, 0) + self.assertEqual(len(list(directory.iterdir())), 1) + + warm = main.CellDataCache(directory) + with mock.patch.object(main, "parse_cell_data_workbook", side_effect=AssertionError("parsed again")): + self.assertEqual(main.load_cell_metadata([("renamed.xlsx", first)], warm), expected) + self.assertEqual(warm.hits, 1) + + updated = main.CellDataCache(directory) + metadata = main.load_cell_metadata([("cell-data.xlsx", changed)], updated) + self.assertEqual(metadata["460-00-200-1"][0], "113.2") + self.assertEqual(updated.hits, 0) + self.assertEqual(len(list(directory.iterdir())), 1) + + def test_damaged_cell_data_cache_entry_is_parsed_again(self) -> None: + raw = create_cell_data_workbook() + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) + main.load_cell_metadata([("cell-data.xlsx", raw)], main.CellDataCache(directory)) + (entry,) = directory.iterdir() + for damaged in ("{not json", '{"460-00-200-1": ["113.1"]}', "[]"): + entry.write_text(damaged, encoding="utf-8") + cache = main.CellDataCache(directory) + + metadata = main.load_cell_metadata([("cell-data.xlsx", raw)], cache) + + self.assertEqual(metadata["460-00-200-1"], ("113.123456", "22.654321", "30")) + self.assertEqual(cache.hits, 0) + + def test_invalid_cell_data_workbook_is_not_cached(self) -> None: + with tempfile.TemporaryDirectory() as temp: + directory = Path(temp) / "cache" + with self.assertRaisesRegex(main.ProcessingError, "Invalid CellData workbook"): + main.load_cell_metadata([("bad.xlsx", b"not a workbook")], main.CellDataCache(directory)) + self.assertFalse(directory.exists()) + def test_nearby_count_uses_high_interference_rows_with_coordinates(self) -> None: rows = [ nearby_row("a", "113.000000", "22.000000", "2.6G"), @@ -400,7 +446,7 @@ class PipelineTest(unittest.TestCase): def test_api_history_store_creates_date_directory_and_uploads_csv(self) -> None: client = FakeHistoryApiClient() - history = main.ApiHistoryStore(client, "stg_test", "/history") + history = main.StorageHistoryStore(main.MetrixStorage(client, "stg_test"), "/history") metric_time = datetime(2026, 8, 6, 12, 0) self.assertFalse(history.exists(metric_time))