Files
live-hub-py/web/backend/services/execution_worker.py
T

388 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""持久执行任务的 worker 消费循环。"""
from __future__ import annotations
import os
import threading
from concurrent.futures import FIRST_COMPLETED, Future, ThreadPoolExecutor, wait
from datetime import UTC, datetime
from typing import Any
from loguru import logger
from ..database import WorkerSessionLocal
from ..models import DouyuTask, ExecutionJob, ProxyConfig, User
from ..permissions import get_user_permissions
from .douyu_runner import DouyuBatchRunner
from .execution_jobs import (
JOB_DOUYU_BATCH,
JOB_DOUYU_BINDING,
JOB_LOGIN_BATCH,
JOB_RELOGIN_BATCH,
LANE_AUTH,
LANE_FULFILLMENT,
STATUS_CANCELLED,
STATUS_SUCCEEDED,
append_execution_event,
claim_execution_jobs,
execution_worker_owner,
fail_execution_job,
finish_execution_job,
heartbeat_execution_job,
)
from .login_service import LoginBatchRunner
DEFAULT_EXECUTION_WORKERS = 2
DEFAULT_POLL_SECONDS = 1
def _env_positive_int(name: str, default: int, minimum: int = 1) -> int:
try:
value = int(os.getenv(name, str(default)))
except ValueError:
return default
return max(minimum, value)
def _lane_scopes() -> tuple[str, ...]:
raw = os.getenv("EXECUTION_WORKER_LANES", "auth,fulfillment")
allowed = {LANE_AUTH, LANE_FULFILLMENT}
scopes = tuple(
item.strip().lower()
for item in raw.split(",")
if item.strip().lower() in allowed
)
return scopes or (LANE_AUTH, LANE_FULFILLMENT)
def _lane_slot_limits() -> dict[str, int]:
"""每条 lane 的槽位上限(总槽位不变,只做隔离)。
登录(auth)批次现在可能长时间持槽 —— 斗鱼邮箱验证码是攒批投递的,等一封
验证码最长 25 分钟。如果 auth 和履约(fulfillment)共用同一个线程池,
登录批次会把履约批次饿死:履约批次排队到 10 个之后,新建斗鱼任务直接
被「斗鱼任务繁忙」挡掉。
所以总槽位不变(``EXECUTION_WORKER_MAX_JOBS``),但给履约预留:auth 最多
占 total-1,fulfillment 最多占 total —— 履约永远至少有 1 个槽可用。
"""
total = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
auth_limit = _env_positive_int(
"EXECUTION_WORKER_AUTH_JOBS",
max(1, total - 1),
)
fulfillment_limit = _env_positive_int(
"EXECUTION_WORKER_FULFILLMENT_JOBS",
total,
)
limits: dict[str, int] = {}
for lane in _lane_scopes():
limits[lane] = auth_limit if lane == LANE_AUTH else fulfillment_limit
return limits
def _lane_claim_order() -> tuple[str, ...]:
"""领取顺序:履约优先,登录用剩余槽位。"""
lanes = _lane_scopes()
return tuple(
sorted(lanes, key=lambda lane: 0 if lane == LANE_FULFILLMENT else 1)
)
class ExecutionJobWorker:
def __init__(self) -> None:
self._stop = threading.Event()
self._thread: threading.Thread | None = None
self._lock = threading.Lock()
# 每条 lane 一个独立线程池:慢的 lane 再慢也吃不掉别的 lane 的槽位。
self._executors: dict[str, ThreadPoolExecutor] = {}
self._inflight: dict[str, int] = {}
self._owner = execution_worker_owner()
def start(self) -> bool:
with self._lock:
if self._thread is not None and self._thread.is_alive():
return False
self._stop.clear()
lane_limits = _lane_slot_limits()
self._executors = {
lane: ThreadPoolExecutor(
max_workers=limit,
thread_name_prefix=f"execution-job-{lane}",
)
for lane, limit in lane_limits.items()
}
self._inflight = {lane: 0 for lane in lane_limits}
self._thread = threading.Thread(
target=self._run,
name="execution-job-consumer",
daemon=True,
)
self._thread.start()
logger.info(
"执行任务 worker 已启动 lanes={} max_jobs={} lane_slots={}",
",".join(_lane_scopes()),
_env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
),
lane_limits,
)
return True
def stop(self) -> None:
self._stop.set()
with self._lock:
thread = self._thread
executors = list(self._executors.values())
self._thread = None
self._executors = {}
if thread is not None and thread.is_alive():
thread.join(timeout=5)
for executor in executors:
executor.shutdown(wait=True, cancel_futures=True)
def _run(self) -> None:
futures: dict[Future, str] = {}
max_jobs = _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
)
lane_limits = _lane_slot_limits()
poll_seconds = _env_positive_int(
"EXECUTION_WORKER_POLL_SECONDS",
DEFAULT_POLL_SECONDS,
)
while not self._stop.is_set():
# 回收已完成的 job,同时把 lane 的在途计数减回来。
for future in [item for item in futures if item.done()]:
lane = futures.pop(future)
self._inflight[lane] = max(0, self._inflight.get(lane, 0) - 1)
try:
future.result()
except Exception: # noqa: BLE001, S110 - 结果已落库,这里只消费异常
pass
executors = self._executors
if not executors:
break
slots = max_jobs - sum(self._inflight.values())
if slots > 0:
# 履约优先:先把 fulfillment 的槽填满,登录只用剩下的。
# 登录批次等邮箱验证码时可能持槽 25 分钟,绝不能把履约饿死。
for lane in _lane_claim_order():
lane_free = lane_limits.get(lane, 0) - self._inflight.get(
lane, 0
)
take = min(slots, lane_free)
if take <= 0:
continue
try:
jobs = claim_execution_jobs(
lane_scopes=(lane,),
owner=self._owner,
limit=take,
)
except Exception: # noqa: BLE001 - 消费循环必须存活
logger.exception("领取执行任务失败 lane={}", lane)
jobs = []
executor = executors.get(lane)
for job in jobs:
if executor is None or self._stop.is_set():
break
try:
future = executor.submit(self._run_job, job.id)
except RuntimeError:
break
self._inflight[lane] = self._inflight.get(lane, 0) + 1
futures[future] = lane
slots -= len(jobs)
if futures:
wait(
list(futures),
timeout=poll_seconds,
return_when=FIRST_COMPLETED,
)
else:
self._stop.wait(poll_seconds)
def _run_job(self, job_id: int) -> None:
db = WorkerSessionLocal()
job: ExecutionJob | None = None
runner: Any = None
cancelled = threading.Event()
heartbeat_stop = threading.Event()
try:
job = db.get(ExecutionJob, int(job_id))
if job is None or job.status != "running":
return
payload = dict(job.payload_json or {})
user = db.get(User, int(job.created_by))
if user is None:
raise RuntimeError("执行任务创建人不存在")
def log_sink(event: dict[str, Any]) -> None:
event_payload = dict(event)
level = str(event_payload.pop("level", "info") or "info")
message = str(event_payload.pop("message", "") or "")
append_execution_event(
job_id=int(job.id),
batch_id=job.batch_id,
level=level,
message=message,
payload=event_payload or None,
)
def heartbeat_loop() -> None:
while not heartbeat_stop.wait(5):
if self._stop.is_set():
cancelled.set()
if runner is not None:
runner.stop()
return
held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id),
owner=self._owner,
)
if not held:
cancelled.set()
return
if cancel_requested and not cancelled.is_set():
cancelled.set()
if runner is not None:
runner.stop()
log_sink(
{
"level": "warning",
"message": "收到停止请求,正在安全收尾",
}
)
heartbeat = threading.Thread(
target=heartbeat_loop,
name=f"execution-heartbeat-{job.id}",
daemon=True,
)
heartbeat.start()
summary: dict[str, Any] = {}
if job.job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}:
proxy = db.query(ProxyConfig).first()
runner = LoginBatchRunner(
db=db,
account_ids=[
int(value)
for value in payload.get("account_ids", [])
],
created_by=int(job.created_by),
creator_permissions=get_user_permissions(user),
max_login_retries=int(payload.get("max_login_retries", 0) or 0),
max_total_time=float(payload.get("max_total_time", 300) or 0),
proxy_config=proxy,
log_queue=None,
loop=None,
concurrency=int(payload.get("concurrency", 3) or 3),
api_strategy=str(payload.get("api_strategy", "wgapi") or "wgapi"),
mode=str(payload.get("mode", "login") or "login"),
trigger_source=str(payload.get("trigger_source", "manual") or "manual"),
batch_id=job.batch_id,
log_sink=log_sink,
)
runner.run()
elif job.job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}:
if int(job.attempt_count or 0) > 1:
# 进程中断会留下 pending/running 的初始任务;支付轮询有独立
# queue_lane,不能被重放。重试只重置尚无后置 lane 的行。
db.query(DouyuTask).filter(
DouyuTask.batch_id == job.batch_id,
DouyuTask.status.in_(("planned", "pending", "running")),
DouyuTask.queue_lane == "",
).update(
{
DouyuTask.status: "planned",
DouyuTask.message: "执行进程中断,已恢复排队",
},
synchronize_session=False,
)
db.commit()
runner = DouyuBatchRunner(
db=db,
batch_id=job.batch_id,
task_type=str(payload.get("task_type") or ""),
payload=dict(payload.get("payload") or {}),
log_queue=None,
loop=None,
concurrency=int(payload.get("concurrency", 3) or 3),
close_db=False,
log_sink=log_sink,
)
runner.run()
else:
raise RuntimeError(f"不支持的执行任务类型: {job.job_type}")
summary = {"finished_at": datetime.now(UTC).isoformat()}
held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id),
owner=self._owner,
)
if not held:
return
finish_execution_job(
job_id=int(job.id),
owner=self._owner,
status=(
STATUS_CANCELLED
if cancelled.is_set() or cancel_requested
else STATUS_SUCCEEDED
),
summary=summary,
)
except Exception as exc: # noqa: BLE001 - job 边界必须收口
logger.exception("执行任务失败 job_id={}", job_id)
append_execution_event(
job_id=int(job_id),
batch_id=str(job.batch_id) if job is not None else "",
level="error",
message=f"{type(exc).__name__}: {exc}",
)
fail_execution_job(
job_id=int(job_id),
owner=self._owner,
error=f"{type(exc).__name__}: {exc}",
)
finally:
heartbeat_stop.set()
db.close()
execution_job_worker = ExecutionJobWorker()
def start_execution_job_worker() -> bool:
return execution_job_worker.start()
def stop_execution_job_worker() -> None:
execution_job_worker.stop()
def execution_job_worker_status() -> dict[str, Any]:
thread = execution_job_worker._thread
return {
"running": bool(thread and thread.is_alive()),
"lanes": list(_lane_scopes()),
"lane_slots": _lane_slot_limits(),
"max_jobs": _env_positive_int(
"EXECUTION_WORKER_MAX_JOBS",
DEFAULT_EXECUTION_WORKERS,
),
"owner": execution_job_worker._owner,
}
__all__ = [
"execution_job_worker_status",
"start_execution_job_worker",
"stop_execution_job_worker",
]