Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 73 additions & 5 deletions api/schedule/workflow_schedule_task.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import logging
from collections.abc import Generator
from contextlib import contextmanager
from typing import Any, cast

from celery import current_app, group, shared_task
from celery.app import backends
from celery.backends.asynchronous import geventDrainer
from celery.backends.redis import RedisBackend
from sqlalchemy import and_, select
from sqlalchemy.orm import Session, sessionmaker

Expand Down Expand Up @@ -101,12 +107,74 @@ def _process_schedules(session: Session, schedules: list[WorkflowSchedulePlan],

tasks_to_dispatch.append(schedule.id)

if tasks_to_dispatch:
with _dispatch_result_backend():
job = group(run_schedule_trigger.s(schedule_id) for schedule_id in tasks_to_dispatch)
job.apply_async(producer=producer)
job.apply_async(producer=producer, add_to_parent=False)
# 先提交定时计划、释放行锁,再等待结果消费者停止。
session.commit()

logger.debug("Dispatched %d tasks in parallel", len(tasks_to_dispatch))

session.commit()
logger.debug("Dispatched %d tasks in parallel", len(tasks_to_dispatch))

return len(tasks_to_dispatch)


@contextmanager
def _dispatch_result_backend() -> Generator[None]:
"""为每批只派发、不等待结果的 group 管理独立 Redis 结果消费者。

Celery 的 gevent drainer 会在轮询结束后继续持有协程局部 backend。
只清理本批独占的 backend,不断开进程共享 backend 或 broker 连接池。
"""
# Celery 的存根把 current_app 标为应用实例,运行时实际是代理。
app = cast(Any, current_app)._get_current_object()
if app._backend_cache is not None:
# 显式共享的 backend 也属于其他并发任务,不能在这里关闭。
yield
return

backend_class, _ = backends.by_url(app.backend_cls or app.conf.result_backend, app.loader)
if not issubclass(backend_class, RedisBackend):
yield
return

previous_backend = app._backend
backend = app._get_backend()
app._local.backend = backend
try:
yield
finally:
consumer = backend.result_consumer
try:
try:
# 未启动的 gevent drainer 不能调用 stop,否则会一直等待退出事件。
drainer = consumer.drainer
if isinstance(drainer, geventDrainer) and drainer._g is not None:
from gevent import with_timeout

drainer_greenlet = drainer._g
try:
with_timeout(2, drainer.stop, timeout_value=None)
finally:
if not drainer_greenlet.dead:
drainer_greenlet.kill(block=True, timeout=1)
finally:
try:
# 关闭独占 PubSub 会在本地清理所有订阅;显式 UNSUBSCRIBE
# 可能在 Redis 故障时触发重连,因此不再发送该命令。
consumer.stop()
finally:
# 防止 AsyncResult 延迟析构时重新打开已关闭的 PubSub。
consumer._pubsub = None
consumer.subscribed_to.clear()
for pending in backend._pending_results:
pending.clear()
# PubSub.close() 会断开订阅连接;再断开独占池中的其余连接。
client = backend.__dict__.get("client")
if client is not None:
client.connection_pool.disconnect()
except Exception:
# 已派发任务不能因清理失败而丢失定时计划提交;记录错误,
# 不覆盖原始派发异常。
logger.exception("Failed to close schedule dispatch Redis result backend")
finally:
app._local.backend = previous_backend
Loading