File size: 7,205 Bytes
2ed8996 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 | """
Celery worker configuration for AegisLM SaaS Backend.
Production-ready Celery setup with Redis broker,
task monitoring, and error handling.
"""
import os
from celery import Celery
from celery.signals import task_prerun, task_postrun, task_failure
from datetime import datetime
from core.config import settings
# Create Celery app
celery_app = Celery(
"aegislm_worker",
broker=settings.REDIS_URL,
backend=settings.REDIS_URL,
include=["tasks.evaluation_task"]
)
# Configure Celery
celery_app.conf.update(
# Task settings
task_serializer="json",
accept_content=["json"],
result_serializer="json",
timezone="UTC",
enable_utc=True,
# Worker settings - Optimized for concurrency control
worker_prefetch_multiplier=1,
task_acks_late=True,
worker_max_tasks_per_child=50, # Reduced for better memory management
worker_concurrency=getattr(settings, 'CELERY_WORKER_CONCURRENCY', 2), # Limited concurrency
# Rate limiting
task_default_rate_limit=getattr(settings, 'CELERY_TASK_RATE_LIMIT', '10/m'), # 10 tasks per minute
# Result settings
result_expires=3600, # 1 hour
result_backend_transport_options={
"master_name": "mymaster",
},
# Routing
task_routes={
"tasks.evaluation_task.run_evaluation_task": {"queue": "evaluation"},
"tasks.evaluation_task.run_benchmark_task": {"queue": "benchmark"},
},
# Queue settings
task_default_queue="default",
task_queues={
"default": {
"exchange": "default",
"routing_key": "default",
},
"evaluation": {
"exchange": "evaluation",
"routing_key": "evaluation",
},
"benchmark": {
"exchange": "benchmark",
"routing_key": "benchmark",
},
},
# Monitoring
worker_send_task_events=True,
task_send_sent_event=True,
# Error handling and retries
task_reject_on_worker_lost=True,
task_ignore_result=False,
task_default_retry_delay=60, # 1 minute
task_max_retries=3,
task_retry_backoff=True,
task_retry_backoff_max=300, # 5 minutes max
# Beat scheduler (if needed)
beat_schedule={
"cleanup-expired-results": {
"task": "tasks.evaluation_task.cleanup_expired_results",
"schedule": 3600.0, # Every hour
},
},
)
# Task monitoring signals
@task_prerun.connect
def task_prerun_handler(task_id, task, args, kwargs, **extras):
"""
Handle task pre-run signal.
Args:
task_id: Task ID
task: Task object
args: Task arguments
kwargs: Task keyword arguments
**extras: Extra arguments
"""
print(f"Task {task.name}[{task_id}] started at {datetime.utcnow()}")
# Update evaluation status to running
if task.name == "tasks.evaluation_task.run_evaluation_task":
# This would update the database status
pass
@task_postrun.connect
def task_postrun_handler(task_id, task, args, kwargs, retval, state, **extras):
"""
Handle task post-run signal.
Args:
task_id: Task ID
task: Task object
args: Task arguments
kwargs: Task keyword arguments
retval: Return value
state: Task state
**extras: Extra arguments
"""
print(f"Task {task.name}[{task_id}] completed with state {state} at {datetime.utcnow()}")
@task_failure.connect
def task_failure_handler(task_id, error, traceback, einfo, **kwargs):
"""
Handle task failure signal.
Args:
task_id: Task ID
error: Error object
traceback: Traceback
einfo: Exception info
**kwargs: Extra arguments
"""
print(f"Task {task_id} failed: {error}")
# Update evaluation status to failed
# This would update the database status
# Worker initialization
@celery_app.on_after_configure.connect
def setup_periodic_tasks(sender, **kwargs):
"""
Setup periodic tasks after Celery configuration.
Args:
sender: Celery app
**kwargs: Extra arguments
"""
# Add periodic tasks here if needed
pass
# Health check task
@celery_app.task(bind=True, name="tasks.health_check")
def health_check(self):
"""
Simple health check task.
Returns:
dict: Health status
"""
return {
"status": "healthy",
"timestamp": datetime.utcnow().isoformat(),
"worker_id": self.request.id
}
# Worker info task
@celery_app.task(bind=True, name="tasks.worker_info")
def worker_info(self):
"""
Get worker information.
Returns:
dict: Worker information
"""
return {
"worker_id": self.request.id,
"hostname": self.request.hostname,
"timestamp": datetime.utcnow().isoformat(),
"active_tasks": len(self.request.tasks),
}
# Task to cleanup expired results
@celery_app.task(name="tasks.cleanup_expired_results")
def cleanup_expired_results():
"""
Cleanup expired evaluation results.
Returns:
dict: Cleanup results
"""
# This would implement cleanup logic
return {
"status": "completed",
"timestamp": datetime.utcnow().isoformat(),
"cleaned_items": 0
}
# Custom task base class for evaluation tasks
class EvaluationTask(celery_app.Task):
"""
Custom task base class for evaluation tasks.
Provides common functionality for evaluation-related tasks.
"""
def on_success(self, retval, task_id, args, kwargs):
"""
Handle task success.
Args:
retval: Return value
task_id: Task ID
args: Task arguments
kwargs: Task keyword arguments
"""
super().on_success(retval, task_id, args, kwargs)
# Update evaluation status to completed
if self.name == "tasks.evaluation_task.run_evaluation_task":
# This would update the database status
pass
def on_failure(self, exc, task_id, args, kwargs, einfo):
"""
Handle task failure.
Args:
exc: Exception
task_id: Task ID
args: Task arguments
kwargs: Task keyword arguments
einfo: Exception info
"""
super().on_failure(exc, task_id, args, kwargs, einfo)
# Update evaluation status to failed
if self.name == "tasks.evaluation_task.run_evaluation_task":
# This would update the database status
pass
def on_retry(self, exc, task_id, args, kwargs, einfo):
"""
Handle task retry.
Args:
exc: Exception
task_id: Task ID
args: Task arguments
kwargs: Task keyword arguments
einfo: Exception info
"""
super().on_retry(exc, task_id, args, kwargs, einfo)
print(f"Task {task_id} retrying due to: {exc}")
# Register custom task base
celery_app.Task = EvaluationTask
# Worker startup
if __name__ == "__main__":
celery_app.start()
|