Files
mtusi2026lab7/broker.py

134 lines
7.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""RabbitMQ: подключение (lab7: AMQPS + mTLS, EXTERNAL), проверка топологии, публикация с publisher confirms.
Топология объявлена декларативно в definitions (secrets/rabbitmq_definitions.json, генерирует
scripts/init_secrets.py) и загружается брокером при каждом старте. У сервисов нет права configure:
они только проверяют её пассивным declare и не могут создать/удалить очередь.
exchange attachments (direct, durable)
--attachment.process.v1--> queue attachments.process.v1 (quorum, durable)
x-delivery-limit=20, dead-letter -> attachments.dlx (стратегия at-least-once),
x-max-length=100000 + x-overflow=reject-publish (переполнение -> nack издателю, не потеря)
exchange attachments.dlx (direct, durable)
--attachment.process.v1.dlq--> queue attachments.process.v1.dlq (classic, durable: просмотр в ops.py
через basic_get + nack не расходует delivery-limit)
Сообщения persistent (delivery_mode=2). Quorum queue пишет их в журнал Raft на диск (fsync) до
подтверждения издателю; при рестарте брокера с volume сообщения и неподтверждённые доставки сохраняются.
"""
import json
import logging
import pika
from pika.exceptions import AMQPError
import pipeline
import settings
import tlsutil
log = logging.getLogger("messenger.broker")
logging.getLogger("pika").setLevel(logging.WARNING) # pika пишет INFO на каждое соединение/канал
BrokerError = (AMQPError, OSError)
def parameters(url: str | None = None) -> pika.URLParameters:
"""lab7: amqps://rabbitmq:5671/messenger — TLS с проверкой CA и имени, клиентский сертификат сервиса,
вход механизмом EXTERNAL (пользователь брокера = CN сертификата: worker / dispatcher). Пароля нет."""
params = pika.URLParameters(url or settings.BROKER_URL)
host = params.host
params.ssl_options = pika.SSLOptions(tlsutil.client_context(), server_hostname=host)
params.credentials = pika.credentials.ExternalCredentials()
params.heartbeat = settings.BROKER_HEARTBEAT_SECONDS
params.blocked_connection_timeout = 30 # брокер в memory/disk alarm блокирует издателя: не ждать вечно
params.socket_timeout = 5
params.connection_attempts = 1
params.client_properties = {"connection_name": settings.INSTANCE_ID}
return params
def connect(url: str | None = None) -> pika.BlockingConnection:
return pika.BlockingConnection(parameters(url))
def check_topology(channel, need=("exchange", "queue", "dlq")) -> dict:
"""Пассивная проверка: exchange и очереди существуют. Возвращает число сообщений в очередях.
lab7: каждая проверка — на отдельном временном канале. RabbitMQ 4.2+ отвечает 403 на пассивный declare
ресурса, на который у пользователя нет НИКАКИХ прав (worker не видит DLQ и exchange, dispatcher — основную
очередь): такой ресурс помечается None, а рабочий канал вызывающего не закрывается. Прав не расширяем.
Если не виден ни один ресурс — это ошибка (нет топологии/прав вообще).
"""
connection = channel.connection
def passive(declare):
temp = connection.channel()
try:
return declare(temp)
except pika.exceptions.ChannelClosedByBroker as exc:
if exc.reply_code == 403:
return None
raise
finally:
if temp.is_open:
temp.close()
exchange = passive(lambda ch: ch.exchange_declare(pipeline.EXCHANGE, passive=True)) if "exchange" in need else None
main = passive(lambda ch: ch.queue_declare(pipeline.QUEUE, passive=True).method) if "queue" in need else None
dlq = passive(lambda ch: ch.queue_declare(pipeline.DLQ, passive=True).method) if "dlq" in need else None
if all(item is None for item in (exchange, main, dlq)):
raise pika.exceptions.ChannelClosedByBroker(403, "no broker resource is visible to this identity")
return {"queue": main.message_count if main else None, "consumers": main.consumer_count if main else None,
"dlq": dlq.message_count if dlq else None}
def properties(message: dict) -> pika.BasicProperties:
# W3C Trace Context в native headers AMQP (основной carrier для worker) и в теле (поле схемы).
headers = {key: message[key] for key in ("traceparent", "tracestate") if key in message}
return pika.BasicProperties(
delivery_mode=pika.DeliveryMode.Persistent,
content_type="application/json",
message_id=f"{message['job_id']}:{message['attempt']}",
type=message["type"],
headers=headers or None,
)
class Publisher:
"""Канал в режиме confirm: basic_publish возвращает управление только после ack брокера.
mandatory=True: если сообщение некуда положить (нет привязки), брокер вернёт его -> UnroutableError.
Nack (например, очередь переполнена и x-overflow=reject-publish) -> NackError. В обоих случаях
строка outbox остаётся неопубликованной и будет отправлена позже.
"""
def __init__(self):
self.connection = None
self.channel = None
def open(self):
if self.channel is None or self.channel.is_closed or self.connection.is_closed:
self.close()
self.connection = connect()
self.channel = self.connection.channel()
self.channel.confirm_delivery()
check_topology(self.channel)
log.info("connected to broker, publisher confirms enabled", extra={"event": "broker.connected"})
return self.channel
def publish(self, message: dict, exchange: str = pipeline.EXCHANGE, routing_key: str = pipeline.ROUTING_KEY):
body = json.dumps(message, separators=(",", ":")).encode("utf-8")
self.open().basic_publish(exchange, routing_key, body, properties(message), mandatory=True)
def pump(self):
if self.connection is not None and self.connection.is_open:
self.connection.process_data_events(time_limit=0) # heartbeat в паузах
def close(self):
try:
if self.connection is not None and self.connection.is_open:
self.connection.close()
except BrokerError:
pass
self.connection = None
self.channel = None