-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue_worker_rabbitmq.py
More file actions
334 lines (287 loc) · 12 KB
/
queue_worker_rabbitmq.py
File metadata and controls
334 lines (287 loc) · 12 KB
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import os
import pika
import uuid
import json
import threading
import time
import logging
from typing import Any, Dict, Callable, Optional
import base64
from datetime import datetime
from model import ModelManager
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# RabbitMQ configuration
RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "team06-mq")
RABBITMQ_PORT = int(os.getenv("RABBITMQ_PORT", "5672"))
RABBITMQ_USER = os.getenv("RABBITMQ_USER", "admin")
RABBITMQ_PASS = os.getenv("RABBITMQ_PASS", "password123")
TASK_QUEUE = os.getenv("TASK_QUEUE", "team06_detection_tasks")
RESULT_QUEUE = os.getenv("RESULT_QUEUE", "team06_detection_results")
class TaskManager:
def __init__(self):
self.connection = None
self.channel = None
self.task_results = {} # In-memory storage for task results
self._connect()
def _connect(self):
"""Establish connection to RabbitMQ"""
try:
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
parameters = pika.ConnectionParameters(
host=RABBITMQ_HOST,
port=RABBITMQ_PORT,
credentials=credentials,
heartbeat=600,
blocked_connection_timeout=300
)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
# Declare queues
self.channel.queue_declare(queue=TASK_QUEUE, durable=True)
self.channel.queue_declare(queue=RESULT_QUEUE, durable=True)
logger.info(f"Connected to RabbitMQ at {RABBITMQ_HOST}:{RABBITMQ_PORT}")
except Exception as e:
logger.error(f"Failed to connect to RabbitMQ: {e}")
raise
def submit_detection_task(self, image_data: Any, image_type: str, text_queries: Any,
box_threshold: float, text_threshold: float,
return_visualization: bool, priority: int = 5) -> str:
"""Submit a detection task to the queue"""
task_id = str(uuid.uuid4())
# Handle image data serialization
if image_type == "bytes":
# Convert bytes to base64 for JSON serialization
image_data_serialized = base64.b64encode(image_data).decode('utf-8')
else:
# URL string
image_data_serialized = image_data
task = {
"task_id": task_id,
"image_data": image_data_serialized,
"image_type": image_type,
"text_queries": text_queries,
"box_threshold": box_threshold,
"text_threshold": text_threshold,
"return_visualization": return_visualization,
"priority": priority,
"timestamp": datetime.utcnow().isoformat()
}
try:
# Initialize task result status
self.task_results[task_id] = {
"status": "submitted",
"task_id": task_id,
"timestamp": datetime.utcnow().isoformat()
}
# Publish task to queue
self.channel.basic_publish(
exchange='',
routing_key=TASK_QUEUE,
body=json.dumps(task),
properties=pika.BasicProperties(
delivery_mode=2, # Make message persistent
priority=priority
)
)
logger.info(f"Task {task_id} submitted to queue")
return task_id
except Exception as e:
logger.error(f"Failed to submit task {task_id}: {e}")
self.task_results[task_id] = {
"status": "failed",
"task_id": task_id,
"error": str(e),
"timestamp": datetime.utcnow().isoformat()
}
raise
def get_task_result(self, task_id: str) -> Dict[str, Any]:
"""Get task result by task_id"""
if task_id in self.task_results:
return self.task_results[task_id]
else:
return {
"status": "not_found",
"task_id": task_id,
"error": "Task not found"
}
def cancel_task(self, task_id: str) -> Dict[str, Any]:
"""Cancel a task (mark as cancelled)"""
if task_id in self.task_results:
self.task_results[task_id]["status"] = "cancelled"
return {
"status": "cancelled",
"task_id": task_id,
"message": "Task marked as cancelled"
}
else:
return {
"status": "not_found",
"task_id": task_id,
"error": "Task not found"
}
def get_queue_status(self) -> Dict[str, Any]:
"""Get queue status and statistics"""
try:
# Get queue info
task_queue_info = self.channel.queue_declare(queue=TASK_QUEUE, passive=True)
task_count = task_queue_info.method.message_count
# Count task statuses
active_tasks = len([t for t in self.task_results.values() if t["status"] == "processing"])
completed_tasks = len([t for t in self.task_results.values() if t["status"] == "completed"])
failed_tasks = len([t for t in self.task_results.values() if t["status"] == "failed"])
return {
"status": "ok",
"active_tasks": active_tasks,
"scheduled_tasks": task_count,
"reserved_tasks": 0,
"completed_tasks": completed_tasks,
"failed_tasks": failed_tasks,
"workers": ["consumer-1"], # Placeholder
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
logger.error(f"Failed to get queue status: {e}")
return {
"status": "error",
"error": str(e),
"timestamp": datetime.utcnow().isoformat()
}
def update_task_result(self, task_id: str, result: Dict[str, Any]):
"""Update task result (called by consumer)"""
self.task_results[task_id] = result
def close(self):
"""Close connection"""
if self.connection and not self.connection.is_closed:
self.connection.close()
# Consumer class for processing tasks
class DetectionConsumer:
def __init__(self):
self.connection = None
self.channel = None
self.model_manager = ModelManager()
self.task_manager = TaskManager()
self._connect()
def _connect(self):
"""Establish connection to RabbitMQ"""
try:
credentials = pika.PlainCredentials(RABBITMQ_USER, RABBITMQ_PASS)
parameters = pika.ConnectionParameters(
host=RABBITMQ_HOST,
port=RABBITMQ_PORT,
credentials=credentials,
heartbeat=600,
blocked_connection_timeout=300
)
self.connection = pika.BlockingConnection(parameters)
self.channel = self.connection.channel()
# Declare queues
self.channel.queue_declare(queue=TASK_QUEUE, durable=True)
self.channel.queue_declare(queue=RESULT_QUEUE, durable=True)
logger.info("Consumer connected to RabbitMQ")
except Exception as e:
logger.error(f"Failed to connect to RabbitMQ: {e}")
raise
def process_task(self, task_data: Dict[str, Any]) -> Dict[str, Any]:
"""Process a detection task"""
task_id = task_data["task_id"]
try:
logger.info(f"Processing task {task_id}")
# Update task status
self.task_manager.update_task_result(task_id, {
"status": "processing",
"task_id": task_id,
"stage": "loading_model",
"timestamp": datetime.utcnow().isoformat()
})
# Get model
model = self.model_manager.get_model()
# Update task status
self.task_manager.update_task_result(task_id, {
"status": "processing",
"task_id": task_id,
"stage": "processing_image",
"timestamp": datetime.utcnow().isoformat()
})
# Prepare image data
image_data = task_data["image_data"]
image_type = task_data["image_type"]
if image_type == "bytes":
# Decode base64 back to bytes
image_source = base64.b64decode(image_data)
else:
# URL string
image_source = image_data
# Process detection
result = model.process_detection(
image_source=image_source,
text_queries=task_data["text_queries"],
box_threshold=task_data["box_threshold"],
text_threshold=task_data["text_threshold"],
return_visualization=task_data["return_visualization"]
)
# Update task with result
if result["success"]:
self.task_manager.update_task_result(task_id, {
"status": "completed",
"task_id": task_id,
"result": result,
"timestamp": datetime.utcnow().isoformat()
})
logger.info(f"Task {task_id} completed successfully")
else:
self.task_manager.update_task_result(task_id, {
"status": "failed",
"task_id": task_id,
"error": result.get("error", "Unknown error"),
"timestamp": datetime.utcnow().isoformat()
})
logger.error(f"Task {task_id} failed: {result.get('error')}")
return result
except Exception as e:
logger.error(f"Task {task_id} failed with exception: {e}")
self.task_manager.update_task_result(task_id, {
"status": "failed",
"task_id": task_id,
"error": str(e),
"timestamp": datetime.utcnow().isoformat()
})
return {"success": False, "error": str(e)}
def callback(self, ch, method, properties, body):
"""RabbitMQ callback function"""
try:
task_data = json.loads(body)
self.process_task(task_data)
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception as e:
logger.error(f"Failed to process message: {e}")
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
def start_consuming(self):
"""Start consuming tasks from the queue"""
try:
logger.info("Loading Grounding DINO model...")
self.model_manager.get_model()
logger.info("Model loaded successfully!")
self.channel.basic_qos(prefetch_count=1)
self.channel.basic_consume(queue=TASK_QUEUE, on_message_callback=self.callback)
logger.info(f"[*] Consumer waiting for messages on queue: {TASK_QUEUE}")
logger.info("To exit press CTRL+C")
self.channel.start_consuming()
except KeyboardInterrupt:
logger.info("Consumer stopped by user")
self.channel.stop_consuming()
self.connection.close()
except Exception as e:
logger.error(f"Consumer error: {e}")
raise
def close(self):
"""Close connection"""
if self.connection and not self.connection.is_closed:
self.connection.close()
# Initialize task manager
task_manager = TaskManager()
if __name__ == "__main__":
# Run consumer
consumer = DetectionConsumer()
consumer.start_consuming()