#!/usr/bin/env python3 """Declare durable classic processing and dead-letter queues.""" 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 QUEUE = "attachments.process" DLQ = "attachments.dlq" DLX = "attachments.dlx" DLQ_ROUTING_KEY = "attachments.dead" 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", } api = "http://broker:15672/api" def request(method, resource, body=None): data = None if body is None else json.dumps(body).encode() req = Request(f"{api}/{resource}", data=data, headers=headers, method=method) with urlopen(req, timeout=3) as response: payload = response.read() return json.loads(payload) if payload else None def ensure_queue(name, arguments): resource = f"queues/%2F/{quote(name, safe='')}" expected = {"x-queue-type": "classic", **arguments} try: current = request("GET", resource) except HTTPError as exc: if exc.code != 404: raise request("PUT", resource, { "durable": True, "auto_delete": False, "arguments": expected, }) current = request("GET", resource) if (current.get("type") != "classic" or not current.get("durable") or current.get("arguments", {}) != expected): raise SystemExit( f"Queue {name} has incompatible settings; stop consumers, inspect and drain it, " "then delete and redeclare it" ) def main(): exchange_resource = f"exchanges/%2F/{quote(DLX, safe='')}" request("PUT", exchange_resource, { "type": "direct", "durable": True, "auto_delete": False, "internal": False, "arguments": {}, }) ensure_queue(DLQ, {}) binding_resource = f"bindings/%2F/e/{quote(DLX, safe='')}/q/{quote(DLQ, safe='')}" bindings = request("GET", binding_resource) or [] if not any(binding.get("routing_key") == DLQ_ROUTING_KEY and binding.get("arguments", {}) == {} for binding in bindings): request("POST", binding_resource, {"routing_key": DLQ_ROUTING_KEY, "arguments": {}}) ensure_queue(QUEUE, { "x-dead-letter-exchange": DLX, "x-dead-letter-routing-key": DLQ_ROUTING_KEY, }) print(f"Durable classic queue {QUEUE} and DLQ {DLQ} via {DLX} are ready") for attempt in range(30): try: main() break except HTTPError as exc: if exc.code in (400, 401, 403, 406): raise SystemExit(f"RabbitMQ topology 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)