249 lines
8.5 KiB
Python
249 lines
8.5 KiB
Python
"""用户任务只读库里已有的数据,再写成表格。采集另走自己的队列。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
import threading
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
from sqlalchemy import select
|
|
|
|
from app.collect.io import parse_upload, write_table
|
|
from app.collect.remote import fetch_ftp, fetch_nqi
|
|
from app.config import postgres_conninfo, result_dir
|
|
from app.db import session_scope
|
|
from app.models import CellData, CollectionSource, ExportTask, NqiAccount, utcnow
|
|
from app.nqi.client import NqiAuthError, NqiClient, NqiError
|
|
|
|
logger = logging.getLogger("decom")
|
|
_pool = threading.Semaphore(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 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 query_cells(session, params: dict) -> list[dict]:
|
|
statement = select(CellData).order_by(CellData.observed_at, CellData.cell_key)
|
|
cell_key = str(params.get("cellKey") or "").strip()
|
|
if cell_key:
|
|
statement = statement.where(CellData.cell_key == cell_key)
|
|
start = _optional_time(params.get("start"))
|
|
end = _optional_time(params.get("end"))
|
|
if start is not None:
|
|
statement = statement.where(CellData.observed_at >= start)
|
|
if end is not None:
|
|
statement = statement.where(CellData.observed_at <= end)
|
|
rows = session.scalars(statement).all()
|
|
return [
|
|
{"cell_key": row.cell_key, "observed_at": row.observed_at, "metrics": row.metrics or {}}
|
|
for row in rows
|
|
]
|
|
|
|
|
|
def _optional_time(value) -> datetime | None:
|
|
if not value:
|
|
return None
|
|
text = str(value).replace("/", "-").replace("T", " ")
|
|
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M", "%Y-%m-%d"):
|
|
try:
|
|
return datetime.strptime(text, fmt).replace(tzinfo=timezone.utc)
|
|
except ValueError:
|
|
continue
|
|
return None
|
|
|
|
|
|
def execute_export(task_id: int) -> None:
|
|
with _pool:
|
|
with session_scope() as session:
|
|
task = session.get(ExportTask, task_id)
|
|
if task is None or task.status not in {"queued", "running"}:
|
|
return
|
|
task.status = "running"
|
|
params = dict(task.params or {})
|
|
file_format = task.file_format
|
|
try:
|
|
with session_scope() as session:
|
|
rows = query_cells(session, params)
|
|
name, content = write_table(file_format, rows)
|
|
result_dir().mkdir(parents=True, exist_ok=True)
|
|
path = result_dir() / f"{task_id}-{name}"
|
|
path.write_bytes(content)
|
|
with session_scope() as session:
|
|
task = session.get(ExportTask, task_id)
|
|
if task is None:
|
|
return
|
|
task.status = "done"
|
|
task.result_name = path.name
|
|
task.finished_at = utcnow()
|
|
except Exception as exc:
|
|
logger.info("导出失败: %s", exc)
|
|
with session_scope() as session:
|
|
task = session.get(ExportTask, task_id)
|
|
if task is None:
|
|
return
|
|
task.status = "failed"
|
|
task.error = str(exc) or "导出失败"
|
|
task.finished_at = utcnow()
|
|
|
|
|
|
def execute_collection(source_id: int) -> None:
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is None or not source.enabled:
|
|
return
|
|
kind = source.kind
|
|
config = dict(source.config or {})
|
|
account = None
|
|
if kind == "nqi":
|
|
account = session.scalar(
|
|
select(NqiAccount).where(NqiAccount.credential_valid.is_(True)).order_by(NqiAccount.saved_at.desc())
|
|
)
|
|
cookies = list(account.cookies or []) if account is not None else []
|
|
else:
|
|
cookies = []
|
|
try:
|
|
if kind == "ftp":
|
|
name, content = fetch_ftp(config)
|
|
elif kind == "nqi":
|
|
if not cookies:
|
|
raise ValueError("账号池里没有可用凭证")
|
|
name, content = _fetch_nqi_sync(cookies, config)
|
|
else:
|
|
raise ValueError("未知的采集来源")
|
|
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)
|
|
source.last_error = ""
|
|
except Exception as exc:
|
|
logger.info("采集失败: %s", exc)
|
|
with session_scope() as session:
|
|
source = session.get(CollectionSource, source_id)
|
|
if source is not None:
|
|
source.last_error = str(exc) or "采集失败"
|
|
|
|
|
|
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_export(task_id: int) -> None:
|
|
if _defer("decom_export", task_id=task_id):
|
|
return
|
|
threading.Thread(target=execute_export, args=(task_id,), daemon=True).start()
|
|
|
|
|
|
def enqueue_collection(source_id: int) -> None:
|
|
if _defer("decom_collect", source_id=source_id):
|
|
return
|
|
threading.Thread(target=execute_collection, args=(source_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.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)
|
|
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 valid and 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()
|