Files
mtusi2026lab5/scripts/bootstrap_broker.py

45 lines
1.7 KiB
Python

#!/usr/bin/env python3
"""Idempotently declare the durable processing queue via RabbitMQ management API."""
import base64
import json
import os
import time
from urllib.error import HTTPError, URLError
from urllib.parse import quote, unquote, urlsplit
from urllib.request import Request, urlopen
broker_url = open(os.environ.get("BROKER_URL_FILE", "/run/secrets/broker_url"), encoding="utf-8").read().strip()
parsed = urlsplit(broker_url)
if parsed.scheme != "amqp" or not parsed.username or not parsed.password:
raise SystemExit("Invalid broker URL file")
credentials = f"{unquote(parsed.username)}:{unquote(parsed.password)}".encode()
headers = {
"Authorization": "Basic " + base64.b64encode(credentials).decode("ascii"),
"Content-Type": "application/json",
}
url = "http://broker:15672/api/queues/%2F/" + quote("attachments.process", safe="")
body = json.dumps(
{"durable": True, "auto_delete": False, "arguments": {"x-queue-type": "quorum"}}
).encode()
for attempt in range(30):
try:
with urlopen(Request(url, data=body, headers=headers, method="PUT"), timeout=3):
pass
with urlopen(Request(url, headers=headers), timeout=3) as response:
queue = json.load(response)
if queue.get("type") != "quorum" or not queue.get("durable"):
raise SystemExit("Processing queue is not durable quorum")
print("Durable quorum queue attachments.process is ready")
break
except HTTPError as exc:
if exc.code in (400, 401, 403, 406):
raise SystemExit(f"RabbitMQ queue declaration failed (HTTP {exc.code})") from None
except URLError:
pass
if attempt == 29:
raise SystemExit("RabbitMQ management API did not become ready")
time.sleep(1)