每个逻辑站点一个排队任务,与采集共用并行数量;工参按拆除前后规则取本系统快照,指标暂用模拟数据;全部站点结束后写频段清退、低效拆除两份结果表。去掉原来的通用导出任务。
327 lines
11 KiB
Python
327 lines
11 KiB
Python
"""采集任务和账号凭证刷新。采集和评估共用排队进程的并行数量。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
from datetime import date, timedelta
|
|
|
|
from sqlalchemy import select
|
|
|
|
from app.collect.accounts import AccountUnavailable, borrow_account, release_account
|
|
from app.collect.io import parse_upload
|
|
from app.collect.remote import fetch_nqi
|
|
from app.collect.schedule import next_run_at
|
|
from app.collect.store import replace_batch
|
|
from app.config import inline_worker_allowed, postgres_conninfo
|
|
from app.db import session_scope
|
|
from app.models import CellData, CollectionSource, NqiAccount, utcnow
|
|
from app.nqi.adhoc import export_table, time_window
|
|
from app.nqi.client import NqiAuthError, NqiClient, NqiError, NqiNetworkError
|
|
|
|
logger = logging.getLogger("decom")
|
|
MIN_CONCURRENCY = 1
|
|
MAX_CONCURRENCY = 32
|
|
DEFAULT_CONCURRENCY = 4
|
|
|
|
|
|
def check_period(days: int) -> int:
|
|
if days < 1 or days > 31:
|
|
raise ValueError("周期最短一天,最长一个月")
|
|
return days
|
|
|
|
|
|
def check_refresh(seconds: int) -> int:
|
|
if seconds < 60 or seconds > 24 * 60 * 60:
|
|
raise ValueError("刷新间隔需要在 1 分钟到 1 天之间")
|
|
return seconds
|
|
|
|
|
|
def check_concurrency(value: int) -> int:
|
|
if value < MIN_CONCURRENCY or value > MAX_CONCURRENCY:
|
|
raise ValueError("并行数量需要在 1 到 32 之间")
|
|
return value
|
|
|
|
|
|
def current_concurrency() -> int:
|
|
from app.config import installed
|
|
|
|
if not installed():
|
|
return DEFAULT_CONCURRENCY
|
|
from app.models import AppSetting
|
|
|
|
with session_scope() as session:
|
|
setting = session.get(AppSetting, 1)
|
|
if setting is None:
|
|
return DEFAULT_CONCURRENCY
|
|
try:
|
|
return check_concurrency(int(setting.worker_concurrency))
|
|
except (TypeError, ValueError):
|
|
return DEFAULT_CONCURRENCY
|
|
|
|
|
|
def upsert_rows(session, source: str, rows: list[dict]) -> int:
|
|
count = 0
|
|
for row in rows:
|
|
existing = session.scalar(
|
|
select(CellData).where(
|
|
CellData.cell_key == row["cell_key"],
|
|
CellData.observed_at == row["observed_at"],
|
|
CellData.source == source,
|
|
)
|
|
)
|
|
if existing is None:
|
|
session.add(
|
|
CellData(
|
|
cell_key=row["cell_key"],
|
|
observed_at=row["observed_at"],
|
|
source=source,
|
|
metrics=row["metrics"],
|
|
)
|
|
)
|
|
count += 1
|
|
else:
|
|
existing.metrics = row["metrics"]
|
|
return count
|
|
|
|
|
|
def execute_collection(source_id: int, force: bool = False) -> None:
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is None or (not source.enabled and not force):
|
|
return
|
|
kind = source.kind
|
|
config = dict(source.config or {})
|
|
source_name = source.name
|
|
if kind != "nqi":
|
|
_fail_collection(source_id, "未知的采集来源")
|
|
return
|
|
tried: set[int] = set()
|
|
while True:
|
|
borrowed = borrow_account(tried)
|
|
if borrowed is None:
|
|
_postpone_collection(source_id, "账号暂时都不能用,稍后再试")
|
|
return
|
|
account_id, cookies = borrowed
|
|
tried.add(account_id)
|
|
held = True
|
|
try:
|
|
if config.get("tables"):
|
|
_use_account(lambda: _save_nqi_tables(cookies, config, source_id, source_name))
|
|
else:
|
|
name, content = _use_account(lambda: _fetch_nqi_sync(cookies, config))
|
|
rows = parse_upload(name, content)
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is None:
|
|
return
|
|
upsert_rows(session, kind, rows)
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is not None:
|
|
source.last_error = ""
|
|
return
|
|
except AccountUnavailable as exc:
|
|
logger.info("账号 %s 不能完成本次采集: %s", account_id, exc)
|
|
release_account(account_id, invalid=exc.invalid)
|
|
held = False
|
|
except Exception as exc:
|
|
logger.info("采集失败: %s", exc)
|
|
_fail_collection(source_id, str(exc) or "采集失败")
|
|
return
|
|
finally:
|
|
if held:
|
|
release_account(account_id)
|
|
|
|
|
|
def _use_account(action):
|
|
try:
|
|
return action()
|
|
except AccountUnavailable:
|
|
raise
|
|
except NqiAuthError as exc:
|
|
raise AccountUnavailable("账号池凭证已失效", invalid=True) from exc
|
|
except NqiNetworkError as exc:
|
|
raise AccountUnavailable(str(exc) or "连接失败", invalid=False) from exc
|
|
except NqiError as exc:
|
|
text = str(exc)
|
|
if "凭证" in text or "登录" in text or "即席查询" in text:
|
|
raise AccountUnavailable(text or "账号不能用", invalid=True) from exc
|
|
raise
|
|
except ValueError as exc:
|
|
text = str(exc)
|
|
if "凭证" in text or "登录" in text:
|
|
raise AccountUnavailable(text, invalid=True) from exc
|
|
raise
|
|
|
|
|
|
def _postpone_collection(source_id: int, message: str) -> None:
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is None:
|
|
return
|
|
source.last_error = message
|
|
source.next_run_at = utcnow() + timedelta(seconds=60)
|
|
|
|
|
|
def _fail_collection(source_id: int, message: str) -> None:
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is not None:
|
|
source.last_error = message
|
|
|
|
|
|
def _save_nqi_tables(cookies: list, config: dict, source_id: int, source_name: str) -> None:
|
|
import asyncio
|
|
|
|
from app.db import engine
|
|
|
|
tables = list(config.get("tables") or [])
|
|
mode = str(config.get("timeMode") or "")
|
|
count = int(config.get("timeCount") or 1)
|
|
city = str(config.get("city") or "")
|
|
schedule = config.get("schedule") if isinstance(config.get("schedule"), dict) else {}
|
|
start, end = time_window(mode, count, date.today())
|
|
|
|
async def run() -> list[tuple[str, list[dict], list[dict]]]:
|
|
client = NqiClient()
|
|
try:
|
|
client.import_cookies(cookies)
|
|
try:
|
|
await client.current_user()
|
|
except NqiAuthError as exc:
|
|
raise ValueError("账号池凭证已失效") from exc
|
|
saved: list[tuple[str, list[dict], list[dict]]] = []
|
|
for table in tables:
|
|
tablename = str(table.get("tablename") or "")
|
|
_title, columns, rows = await export_table(client, tablename, start, end, city)
|
|
saved.append((tablename, columns, rows))
|
|
return saved
|
|
finally:
|
|
await client.aclose()
|
|
|
|
batches = asyncio.run(run())
|
|
with engine().begin() as connection:
|
|
for tablename, columns, rows in batches:
|
|
replace_batch(
|
|
connection,
|
|
tablename,
|
|
columns,
|
|
rows,
|
|
task_id=source_id,
|
|
task_name=source_name,
|
|
time_mode=mode,
|
|
time_count=count,
|
|
window_start=start,
|
|
window_end=end,
|
|
city=city,
|
|
schedule=schedule,
|
|
)
|
|
|
|
|
|
def _fetch_nqi_sync(cookies: list, config: dict) -> tuple[str, bytes]:
|
|
import asyncio
|
|
|
|
async def run() -> tuple[str, bytes]:
|
|
client = NqiClient()
|
|
try:
|
|
client.import_cookies(cookies)
|
|
try:
|
|
await client.current_user()
|
|
except NqiAuthError as exc:
|
|
raise ValueError("账号池凭证已失效") from exc
|
|
return await fetch_nqi(client, config)
|
|
finally:
|
|
await client.aclose()
|
|
|
|
return asyncio.run(run)
|
|
|
|
|
|
def enqueue_collection(source_id: int, *, force: bool = False) -> None:
|
|
if _defer("decom_collect", source_id=source_id, force=force):
|
|
return
|
|
if not inline_worker_allowed():
|
|
logger.info("没有排队数据库,任务 %s 留在排队中", source_id)
|
|
return
|
|
threading.Thread(target=execute_collection, args=(source_id, force), daemon=True).start()
|
|
|
|
|
|
def _run_inline(target, item_id: int) -> None:
|
|
if not inline_worker_allowed():
|
|
logger.info("没有排队数据库,任务 %s 留在排队中", item_id)
|
|
return
|
|
threading.Thread(target=target, args=(item_id,), daemon=True).start()
|
|
|
|
|
|
def _defer(name: str, **kwargs) -> bool:
|
|
if not postgres_conninfo():
|
|
return False
|
|
from app.tasks.queue import defer
|
|
|
|
defer(name, **kwargs)
|
|
return True
|
|
|
|
|
|
def scan_sources() -> None:
|
|
now = utcnow()
|
|
due_ids: list[int] = []
|
|
with session_scope() as session:
|
|
sources = session.scalars(select(CollectionSource).where(CollectionSource.enabled.is_(True))).all()
|
|
for source in sources:
|
|
if source.kind != "nqi":
|
|
source.enabled = False
|
|
source.last_error = "不再从 FTP 采集"
|
|
continue
|
|
schedule = (source.config or {}).get("schedule")
|
|
if not isinstance(schedule, dict) or not schedule.get("mode"):
|
|
if source.next_run_at is not None and source.next_run_at > now:
|
|
continue
|
|
source.next_run_at = now + timedelta(days=source.period_days)
|
|
due_ids.append(source.id)
|
|
continue
|
|
if source.next_run_at is None:
|
|
source.next_run_at = next_run_at(schedule, now)
|
|
continue
|
|
if source.next_run_at > now:
|
|
continue
|
|
source.next_run_at = next_run_at(schedule, now)
|
|
due_ids.append(source.id)
|
|
for source_id in due_ids:
|
|
enqueue_collection(source_id)
|
|
|
|
|
|
async def refresh_accounts() -> None:
|
|
with session_scope() as session:
|
|
accounts = session.scalars(select(NqiAccount)).all()
|
|
snapshots = [(item.id, list(item.cookies or [])) for item in accounts]
|
|
for account_id, cookies in snapshots:
|
|
if not cookies:
|
|
continue
|
|
outcome = await _touch(cookies)
|
|
with session_scope() as session:
|
|
account = session.get(NqiAccount, account_id)
|
|
if account is None or outcome is None:
|
|
continue
|
|
valid, user, refreshed = outcome
|
|
account.credential_valid = valid
|
|
if user is not None:
|
|
account.user_name = user.get("userName") or account.user_name
|
|
account.city_name = user.get("cityName") or account.city_name
|
|
account.org_name = user.get("orgName") or account.org_name
|
|
account.cookies = refreshed
|
|
account.saved_at = utcnow()
|
|
|
|
|
|
async def _touch(cookies: list):
|
|
client = NqiClient()
|
|
try:
|
|
client.import_cookies(cookies)
|
|
user = await client.touch_session()
|
|
return True, user, client.export_cookies()
|
|
except NqiAuthError:
|
|
return False, None, cookies
|
|
except (NqiError, OSError):
|
|
return None
|
|
finally:
|
|
await client.aclose()
|