feat: 只保留管理入口,缓存小区信息表解析,连接中显示提示,移除脚本管理打包方式
This commit is contained in:
@@ -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<window>\d{16})\.zip$", re.IGNORECASE)
|
||||
CELL_DATA_FILE_RE = re.compile(r"(?P<date>20\d{6})\.xlsx$", re.IGNORECASE)
|
||||
# Raise this when parse_cell_data_workbook changes what it returns, so older cache files are ignored.
|
||||
CELL_CACHE_VERSION = 1
|
||||
|
||||
LTE_PLMN = "460-00"
|
||||
DATABASE_NAME = "interference_etl"
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user