| 1 |
"""Ansible-rulebook event source plugin for Azure Service Bus. |
| 2 |
|
| 3 |
This module provides asynchronous consumers for Azure Service Bus to feed |
| 4 |
events into Ansible EDA rulebooks. |
| 5 |
""" |
| 6 |
|
| 7 |
import asyncio |
| 8 |
import contextlib |
| 9 |
import json |
| 10 |
import logging |
| 11 |
from typing import Any |
| 12 |
|
| 13 |
from azure.servicebus.aio import ServiceBusClient |
| 14 |
|
| 15 |
DOCUMENTATION = r""" |
| 16 |
--- |
| 17 |
short_description: Receive events from an Azure service bus. |
| 18 |
description: |
| 19 |
- An ansible-rulebook event source module for receiving events from an Azure service bus. |
| 20 |
- In order to get the service bus and the connection string, refer to |
| 21 |
https://learn.microsoft.com/en-us/azure/service-bus-messaging/service-bus-python-how-to-use-queues?tabs=passwordless |
| 22 |
options: |
| 23 |
conn_str: |
| 24 |
description: |
| 25 |
- The connection string to connect to the Azure service bus. |
| 26 |
type: str |
| 27 |
required: true |
| 28 |
queue_name: |
| 29 |
description: |
| 30 |
- The name of the queue to pull messages from. |
| 31 |
type: str |
| 32 |
required: true |
| 33 |
logging_enable: |
| 34 |
description: |
| 35 |
- Whether to turn on logging. |
| 36 |
type: bool |
| 37 |
default: true |
| 38 |
feedback: |
| 39 |
type: bool |
| 40 |
default: false |
| 41 |
description: |
| 42 |
- Should the source plugin wait for feedback before |
| 43 |
processing the next event from the Azure Event Hub |
| 44 |
This flag allows ansible rulebook to pass in an asyncio |
| 45 |
queue which is passed in the args['eda_feedback_queue'] |
| 46 |
The source plugin should wait for the response to come |
| 47 |
back on this queue before it picks the next event from |
| 48 |
Azure Event Hub. |
| 49 |
feedback_timeout: |
| 50 |
type: int |
| 51 |
default: 120 |
| 52 |
description: |
| 53 |
- Timeout in seconds to wait for feedback from the rule engine |
| 54 |
before raising an exception. Only applies when feedback is enabled. |
| 55 |
eda_feedback_queue: |
| 56 |
description: |
| 57 |
- Provided automatically by ansible-rulebook when the feedback parameter |
| 58 |
is enabled, this parameter utilizes an asyncio.Queue. It allows the |
| 59 |
system to wait for confirmation that an event has been safely persisted |
| 60 |
in the database before removing it from the event bus. Users do not need |
| 61 |
to provide a value for this manually. |
| 62 |
""" |
| 63 |
|
| 64 |
EXAMPLES = r""" |
| 65 |
- azure.azcollection.azure_service_bus: |
| 66 |
conn_str: "{{connection_str}}" |
| 67 |
queue_name: "{{queue_name}}" |
| 68 |
""" |
| 69 |
|
| 70 |
DEFAULT_FEEDBACK_TIMEOUT = 120 |
| 71 |
|
| 72 |
logger = logging.getLogger() |
| 73 |
|
| 74 |
|
| 75 |
async def receive_events( |
| 76 |
queue: asyncio.Queue[Any], |
| 77 |
args: dict[str, Any], |
| 78 |
) -> None: |
| 79 |
"""Receive events from service bus asynchronously.""" |
| 80 |
feedback_enabled = args.get("feedback", False) |
| 81 |
eda_feedback_queue = args.get("eda_feedback_queue") |
| 82 |
feedback_timeout = int(args.get("feedback_timeout", DEFAULT_FEEDBACK_TIMEOUT)) |
| 83 |
|
| 84 |
if feedback_enabled and eda_feedback_queue is None: |
| 85 |
msg = ( |
| 86 |
"feedback: true was set but no feedback queue was provided. " |
| 87 |
"This requires a compatible version of ansible-rulebook that " |
| 88 |
"supports the feedback mechanism." |
| 89 |
) |
| 90 |
raise ValueError(msg) |
| 91 |
servicebus_client = ServiceBusClient.from_connection_string( |
| 92 |
conn_str=args["conn_str"], |
| 93 |
logging_enable=bool(args.get("logging_enable", True)), |
| 94 |
) |
| 95 |
|
| 96 |
async with servicebus_client: |
| 97 |
receiver = servicebus_client.get_queue_receiver(queue_name=args["queue_name"]) |
| 98 |
async with receiver: |
| 99 |
async for msg in receiver: |
| 100 |
meta = {"message_id": msg.message_id, "event": {}} |
| 101 |
meta["event"]["uuid"] = msg.message_id |
| 102 |
if msg.enqueued_time_utc: |
| 103 |
meta["event"]["produced_at"] = msg.enqueued_time_utc.isoformat() |
| 104 |
|
| 105 |
body = str(msg) |
| 106 |
with contextlib.suppress(json.JSONDecodeError): |
| 107 |
body = json.loads(body) |
| 108 |
|
| 109 |
await queue.put({"body": body, "meta": meta}) |
| 110 |
|
| 111 |
if feedback_enabled and eda_feedback_queue: |
| 112 |
try: |
| 113 |
await asyncio.wait_for( |
| 114 |
eda_feedback_queue.get(), |
| 115 |
timeout=feedback_timeout, |
| 116 |
) |
| 117 |
await receiver.complete_message(msg) |
| 118 |
except asyncio.TimeoutError: |
| 119 |
logger.exception("Timed out waiting for feedback") |
| 120 |
raise |
| 121 |
else: |
| 122 |
await receiver.complete_message(msg) |
| 123 |
|
| 124 |
|
| 125 |
async def main( |
| 126 |
queue: asyncio.Queue[Any], |
| 127 |
args: dict[str, Any], |
| 128 |
) -> None: |
| 129 |
"""Receive events from service bus in a loop.""" |
| 130 |
await receive_events(queue, args) |
| 131 |
|
| 132 |
|
| 133 |
if __name__ == "__main__": |
| 134 |
|
| 135 |
|
| 136 |
class MockQueue(asyncio.Queue[Any]): |
| 137 |
"""A fake queue.""" |
| 138 |
|
| 139 |
async def put(self: "MockQueue", event: dict[str, Any]) -> None: |
| 140 |
"""Print the event.""" |
| 141 |
print(event) |
| 142 |
|
| 143 |
args = { |
| 144 |
"conn_str": "Endpoint=sb://foo.servicebus.windows.net/", |
| 145 |
"queue_name": "eda-queue", |
| 146 |
} |
| 147 |
asyncio.run(main(MockQueue(), args)) |