feat: Bootstrap durable RabbitMQ queue (U1)

This commit is contained in:
Самохвалов Андрей Ремович
2026-10-02 13:28:26 +03:00
parent a96711a51a
commit af7213900b
6 changed files with 153 additions and 0 deletions
+44
View File
@@ -0,0 +1,44 @@
#!/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)
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Create local RabbitMQ credentials without writing them to tracked files."""
from pathlib import Path
from secrets import token_hex
from urllib.parse import quote
root = Path(__file__).resolve().parents[1]
secret_dir = root / "secrets"
secret_dir.mkdir(mode=0o700, exist_ok=True)
secret_dir.chmod(0o700)
config = secret_dir / "rabbitmq.conf"
url_file = secret_dir / "broker_url"
username = "lab5_app"
if config.exists():
values = dict(
line.split(" = ", 1)
for line in config.read_text(encoding="utf-8").splitlines()
if " = " in line
)
if values.get("default_user") != username or not values.get("default_pass"):
raise SystemExit("Existing RabbitMQ config cannot be reused")
password = values["default_pass"]
else:
password = token_hex(24)
config.write_text(
f"default_user = {username}\ndefault_pass = {password}\n",
encoding="utf-8",
)
config.chmod(0o600)
url_file.write_text(
f"amqp://{username}:{quote(password, safe='')}@broker:5672/%2F\n",
encoding="utf-8",
)
url_file.chmod(0o600)
print("Local broker credentials are ready in ignored secrets/")