UnisKB/apps/system_manage/management/commands/ai_hub_worker.py

66 lines
3.0 KiB
Python

import signal
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from django.core.management.base import BaseCommand
from django.db import close_old_connections
from django.utils import timezone
from system_manage.models.ai_hub import AITask
from system_manage.ai_hub_worker import claim, execute
from system_manage import mcp_scheduler
class Command(BaseCommand):
help = 'Run the isolated component/hub consumer; never consumes Celery queues or migrates.'
def add_arguments(self, parser):
parser.add_argument('--once', action='store_true')
parser.add_argument('--recover', action='store_true', help='Mark tasks without heartbeat for 30 minutes failed')
parser.add_argument('--concurrency', type=int, default=1)
def handle(self, *args, **options):
concurrency = options.get('concurrency', 1)
if not 1 <= concurrency <= 8:
raise ValueError('concurrency must be between 1 and 8')
if options.get('recover'):
mcp_scheduler.recover()
stop = threading.Event()
if threading.current_thread() is threading.main_thread():
signal.signal(signal.SIGTERM, lambda *_: stop.set())
next_cleanup = time.monotonic() + 86400
def run(task):
close_old_connections()
try:
return execute(task)
except Exception:
mcp_scheduler.finish(task, 'FAILED', error='执行器异常,请检查后重试')
finally:
close_old_connections()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
running = {}
while not stop.is_set() or running:
close_old_connections()
mcp_scheduler.heartbeat()
for future, task in list(running.items()):
if future.done():
future.result()
del running[future]
else:
AITask.objects.filter(pk=task.id, attempt=task.attempt, status='RUNNING').update(updated_at=timezone.now())
if not stop.is_set():
while len(running) < concurrency:
task = claim()
if not task: break
if stop.is_set():
AITask.objects.filter(pk=task.id, attempt=task.attempt, status='RUNNING').update(
status='PENDING', started_at=None, updated_at=timezone.now())
break
running[pool.submit(run, task)] = task
if options.get('once'): stop.set()
if time.monotonic() >= next_cleanup and not running:
from system_manage.ai_hub_assets import cleanup
try: cleanup(apply=True)
except Exception: self.stderr.write('图片缓存清理失败,将于下次重试')
next_cleanup = time.monotonic() + 86400
if running or not stop.is_set(): time.sleep(1)