现象:新建斗鱼任务报「斗鱼任务繁忙:当前有 10 个批次运行中,上限 10 个」。 根因:登录任务页(JOB_LOGIN_BATCH)和 CK 重登页(JOB_RELOGIN_BATCH)走 execution_jobs 的 auth lane,斗鱼履约/绑定批次(JOB_DOUYU_BATCH)走 fulfillment lane,但两条 lane 共用同一个 ThreadPoolExecutor(EXECUTION_WORKER_MAX_JOBS=2)。 斗鱼邮箱验证码是攒批投递的,等一封验证码最长 25 分钟/账号,登录批次长时间持槽, 履约批次被挤到排队,堆满 DOUYU_MAX_ACTIVE_BATCHES(10) 后新建任务直接被挡。 改动: - 执行 worker 改为 lane 隔离:每条 lane 独立线程池,总槽位不变,但 auth 最多 占 total-1、fulfillment 最多占 total,且履约优先领取 —— 登录再慢也饿不死履约 - 单个登录批次最多占槽 LOGIN_BATCH_MAX_SECONDS(默认 1800 秒):每个账号开始 执行前检查批次时长,超时后本轮剩余账号记「未执行」(不是失败),留待下一轮 - 新增 EXECUTION_WORKER_AUTH_JOBS / EXECUTION_WORKER_FULFILLMENT_JOBS 旋钮 验证:1732 passed / 6 skipped,pyright 生产代码 0 错误
380 lines
14 KiB
Python
380 lines
14 KiB
Python
"""持久执行任务的 worker 消费循环。"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import os
|
||
import threading
|
||
from concurrent.futures import 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 - 结果已落库,这里只消费异常
|
||
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:
|
||
break
|
||
self._inflight[lane] = self._inflight.get(lane, 0) + 1
|
||
futures[executor.submit(self._run_job, job.id)] = lane
|
||
slots -= len(jobs)
|
||
if futures:
|
||
wait(list(futures), timeout=poll_seconds)
|
||
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",
|
||
]
|