229b25514d
CI/CD Pipeline / Check if frontend-only change (push) Has been skipped
CI/CD Pipeline / Frontend Lint (push) Successful in 42s
CI/CD Pipeline / Validate Code Quality And Tests (push) Successful in 2m42s
CI/CD Pipeline / Unit Tests (push) Successful in 2m48s
CI/CD Pipeline / Integration Tests (push) Successful in 1m21s
CI Build & Deploy Pipeline / Deploy Staging (Watchtower auto-deploy) (push) Successful in 1m5s
CI Build & Deploy Pipeline / Build Staging API Image (push) Successful in 5m14s
CI Build & Deploy Pipeline / Build Staging Web Image (push) Successful in 16s
CI Build & Deploy Pipeline / Build Staging Worker Image (push) Successful in 7m19s
CI Build & Deploy Pipeline / Build Production API Image (push) Has been skipped
CI Build & Deploy Pipeline / Build Production Web Image (push) Has been skipped
CI Build & Deploy Pipeline / Build Production Worker Image (push) Has been skipped
CI Build & Deploy Pipeline / Deploy Production (push) Has been skipped
CI Build & Deploy Pipeline / Production Browser E2E (push) Has been skipped
CI Build & Deploy Pipeline / Staging API Integration Tests (push) Successful in 3m48s
CI Build & Deploy Pipeline / Staging E2E Tests (push) Failing after 4m28s
Co-authored-by: xiaoxia <dev@xiaoxiajianji.com> Co-committed-by: xiaoxia <dev@xiaoxiajianji.com>
50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
"""Worker 启动时的初始化任务 — 孤儿任务清理等。"""
|
|
|
|
import logging
|
|
|
|
from celery.signals import worker_ready
|
|
from worker_app.db import SessionLocal
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
ORPHAN_TASK_TIMEOUT_MINUTES = 10
|
|
|
|
|
|
def cleanup_orphan_tasks(timeout_minutes: int = ORPHAN_TASK_TIMEOUT_MINUTES) -> int:
|
|
"""清理数据库中超时未更新的 running 任务。
|
|
|
|
worker 重启或崩溃后,之前处于 running 状态的任务会变成孤儿任务,
|
|
一直卡在 running 不动。通过 updated_at 超时判断并标记为 failed。
|
|
|
|
Args:
|
|
timeout_minutes: 超时时间(分钟),默认 10 分钟
|
|
|
|
Returns:
|
|
清理的任务数量
|
|
"""
|
|
from packages.adapters.sqlalchemy_impl.generation_task_repository import (
|
|
SQLAlchemyGenerationTaskRepository,
|
|
)
|
|
|
|
try:
|
|
session = SessionLocal()
|
|
repo = SQLAlchemyGenerationTaskRepository(session)
|
|
count = repo.cleanup_stale_running(timeout_minutes)
|
|
session.close()
|
|
if count > 0:
|
|
logger.warning("清理了 %d 个超时的孤儿 running 任务", count)
|
|
else:
|
|
logger.info("无孤儿 running 任务需要清理")
|
|
return count
|
|
except Exception as e:
|
|
logger.error("清理孤儿任务失败: %s", e, exc_info=True)
|
|
return 0
|
|
|
|
|
|
@worker_ready.connect
|
|
def _on_worker_ready(sender, **kwargs):
|
|
"""Worker 启动完成后执行 — 清理孤儿任务。"""
|
|
logger.info("Worker 启动完成,开始清理孤儿 running 任务...")
|
|
count = cleanup_orphan_tasks()
|
|
logger.info("Worker 启动清理完成,共清理 %d 个孤儿任务", count)
|