rabbitmq.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. # Copyright (C) 2014 Andrey Antukh <niwi@niwi.be>
  2. # This program is free software: you can redistribute it and/or modify
  3. # it under the terms of the GNU Affero General Public License as
  4. # published by the Free Software Foundation, either version 3 of the
  5. # License, or (at your option) any later version.
  6. #
  7. # This program is distributed in the hope that it will be useful,
  8. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. # GNU Affero General Public License for more details.
  11. #
  12. # You should have received a copy of the GNU Affero General Public License
  13. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. import json
  15. import logging
  16. from amqp import Connection as AmqpConnection
  17. from amqp.basic_message import Message as AmqpMessage
  18. from urllib.parse import urlparse
  19. from . import base
  20. log = logging.getLogger("tagia.events")
  21. def _make_rabbitmq_connection(url):
  22. parse_result = urlparse(url)
  23. # Parse host & user/password
  24. try:
  25. (authdata, host) = parse_result.netloc.split("@")
  26. except Exception as e:
  27. raise RuntimeError("Invalid url") from e
  28. try:
  29. (user, password) = authdata.split(":")
  30. except Exception:
  31. (user, password) = ("guest", "guest")
  32. vhost = parse_result.path
  33. return AmqpConnection(host=host, userid=user,
  34. password=password, virtual_host=vhost[1:])
  35. class EventsPushBackend(base.BaseEventsPushBackend):
  36. def __init__(self, url):
  37. self.url = url
  38. def emit_event(self, message:str, *, routing_key:str, channel:str="events"):
  39. connection = _make_rabbitmq_connection(self.url)
  40. try:
  41. rchannel = connection.channel()
  42. message = AmqpMessage(message)
  43. rchannel.exchange_declare(exchange=channel, type="topic", auto_delete=True)
  44. rchannel.basic_publish(message, routing_key=routing_key, exchange=channel)
  45. rchannel.close()
  46. except Exception:
  47. log.error("Unhandled exception", exc_info=True)
  48. finally:
  49. connection.close()