Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rabbitmq event source #183

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions extensions/eda/plugins/event_source/rabbitmq.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""rabbitmq.py

An ansible-rulebook event source plugin for receiving events via a RabbitMQ queue.

Arguments:
---------
host: The host where rabbitmq is hosted
port: The port where the rabbitmq server is listening
queue: The queue name to listen for messages on
user: The username to use
password: The password to use
exchange: The exchange to use (optional)
routing_key: The routing key to use (optional)

"""

import asyncio
import aiorabbit
import json
import logging
from typing import Any


async def main(queue: asyncio.Queue, args: dict[str, Any]) -> None:
"""Receive events via a rabbitmq topic."""
logger = logging.getLogger()

host = args.get("host")
port = args.get("port")
user = args.get("user")
password = args.get("password")
queue_name = args.get("queue")
exchange = args.get("exchange")
routing_key = args.get("routing_key")

url = f"amqp://{user}:{password}@{host}:{port}"

async with aiorabbit.connect(url) as client:
await client.queue_declare(queue_name)
if exchange and routing_key:
# Bind to the exchange
await client.queue_bind(queue_name, exchange, routing_key)
logger.info('Consuming from %s', queue_name)
async for msg in client.consume(queue_name):
data = None
logger.debug('Received message published to %s: %r',
queue_name, msg.body)
try:
data = json.loads(msg.body)
except json.decoder.JSONDecodeError:
logger.exception("JSON parse error")

if data:
await queue.put({"body": data})
await client.basic_ack(msg.delivery_tag)
await asyncio.sleep(0)

if __name__ == "__main__":
"""MockQueue if running directly."""

class MockQueue:
"""A fake queue."""

async def put(self: "MockQueue", event: dict) -> None:
"""Print the event."""
print(event) # noqa: T201

asyncio.run(
main(
MockQueue(),
{"user": "guest", "password": "guest", "host": "localhost", "port": "5672", "queue": "test"},
),
)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ azure-servicebus
aiobotocore
aiohttp
aiokafka
aiorabbit
watchdog
systemd-python
dpath
Expand Down