forked from mtusi2026/mtusi2026lab6
Implement lab6 OpenTelemetry observability stack
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
|
||||
import json
|
||||
import os
|
||||
import uuid
|
||||
|
||||
import pika
|
||||
|
||||
|
||||
RABBITMQ_HOST = os.getenv("RABBITMQ_HOST", "rabbitmq")
|
||||
RABBITMQ_USER = os.environ["RABBITMQ_USER"]
|
||||
RABBITMQ_PASSWORD = os.environ["RABBITMQ_PASSWORD"]
|
||||
RABBITMQ_QUEUE = os.getenv(
|
||||
"RABBITMQ_QUEUE",
|
||||
"image_jobs",
|
||||
)
|
||||
|
||||
|
||||
def connect():
|
||||
credentials = pika.PlainCredentials(
|
||||
RABBITMQ_USER,
|
||||
RABBITMQ_PASSWORD,
|
||||
)
|
||||
|
||||
parameters = pika.ConnectionParameters(
|
||||
host=RABBITMQ_HOST,
|
||||
port=5672,
|
||||
credentials=credentials,
|
||||
heartbeat=30,
|
||||
blocked_connection_timeout=15,
|
||||
connection_attempts=3,
|
||||
retry_delay=2,
|
||||
)
|
||||
|
||||
return pika.BlockingConnection(parameters)
|
||||
|
||||
|
||||
def declare_queue(channel):
|
||||
channel.queue_declare(
|
||||
queue=RABBITMQ_QUEUE,
|
||||
durable=True,
|
||||
arguments={
|
||||
"x-queue-type": "quorum",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def publish_job(job_id):
|
||||
connection = connect()
|
||||
|
||||
try:
|
||||
channel = connection.channel()
|
||||
declare_queue(channel)
|
||||
|
||||
# Wait for confirmation from RabbitMQ.
|
||||
channel.confirm_delivery()
|
||||
|
||||
payload = json.dumps({
|
||||
"job_id": str(uuid.UUID(str(job_id))),
|
||||
}).encode("utf-8")
|
||||
|
||||
channel.basic_publish(
|
||||
exchange="",
|
||||
routing_key=RABBITMQ_QUEUE,
|
||||
body=payload,
|
||||
properties=pika.BasicProperties(
|
||||
delivery_mode=2,
|
||||
content_type="application/json",
|
||||
message_id=str(job_id),
|
||||
),
|
||||
mandatory=True,
|
||||
)
|
||||
|
||||
finally:
|
||||
if connection.is_open:
|
||||
connection.close()
|
||||
|
||||
|
||||
def parse_job(body):
|
||||
payload = json.loads(body)
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
raise ValueError("Invalid job payload")
|
||||
|
||||
job_id = payload.get("job_id")
|
||||
|
||||
if not isinstance(job_id, str):
|
||||
raise ValueError("Missing job_id")
|
||||
|
||||
return str(uuid.UUID(job_id))
|
||||
Reference in New Issue
Block a user