Debian Codegraph @

ansible_collections/azure/azcollection/extensions/eda/plugins/event_source/azure_event_hub.py

raw symbols SCIP
1 """Ansible-rulebook event source plugin for Azure Event Hub.
2
3 This module provides asynchronous consumers for Azure Event Hub to feed
4 events into Ansible EDA rulebooks.
5 """
6
7 import asyncio
8 import json
9 import logging
10 from typing import Any
11
12 from azure.eventhub import EventData
13 from azure.eventhub.aio import EventHubConsumerClient, PartitionContext
14 from azure.identity.aio import ClientSecretCredential
15
16 DOCUMENTATION = r"""
17 ---
18 short_description: Receive events via a Azure Event Hub
19 description:
20 - An ansible-rulebook event source plugin for receiving events
21 via Azure Event Hub
22 options:
23 azure_tenant_id:
24 description:
25 - The azure tenant id
26 type: str
27 required: true
28 azure_client_id:
29 description:
30 - The azure client id
31 type: str
32 required: true
33 azure_client_secret:
34 description:
35 - The azure client secret
36 type: str
37 required: true
38 azure_namespace:
39 description:
40 - The azure event hub namespace which includes the host name
41 type: str
42 example: "test.servicebus.windows.net"
43 required: true
44 azure_event_hub_name:
45 description:
46 - The azure event hub name
47 type: str
48 required: true
49 azure_starting_position:
50 description:
51 - The starting position
52 type: str
53 default: "-1"
54 azure_consumer_group:
55 description:
56 - The name of the consumer group
57 type: str
58 default: "$Default"
59 feedback:
60 type: bool
61 default: false
62 description:
63 - Should the source plugin wait for feedback before
64 processing the next event from the Azure Event Hub
65 This flag allows ansible rulebook to pass in an asyncio
66 queue which is passed in the args['eda_feedback_queue']
67 The source plugin should wait for the response to come
68 back on this queue before it picks the next event from
69 Azure Event Hub.
70 feedback_timeout:
71 type: int
72 default: 120
73 description:
74 - Timeout in seconds to wait for feedback from the rule engine
75 before raising an exception. Only applies when feedback is enabled.
76 eda_feedback_queue:
77 description:
78 - Provided automatically by ansible-rulebook when the feedback parameter
79 is enabled, this parameter utilizes an asyncio.Queue. It allows the
80 system to wait for confirmation that an event has been safely persisted
81 in the database before removing it from the event bus. Users do not need
82 to provide a value for this manually.
83 """
84
85 EXAMPLES = r"""
86 - azure.azcollection.azure_event_hub:
87 "azure_tenant_id": "your_tenant_id"
88 "azure_client_id": "your_client_id"
89 "azure_client_secret": "your_client_secret"
90 "azure_namespace": "example.servicebus.windows.net"
91 "azure_event_hub_name": "your_hub_name"
92 "azure_starting_position": "-1"
93 """
94
95 logger = logging.getLogger()
96
97
98 REQUIRED_ARGS = [
99 "azure_tenant_id",
100 "azure_client_id",
101 "azure_client_secret",
102 "azure_namespace",
103 "azure_event_hub_name",
104 ]
105
106 DEFAULT_FEEDBACK_TIMEOUT = 120
107
108
109 class AzureHubConsumer:
110 """Azure Hub Consumer."""
111
112 def __init__(self, queue: asyncio.Queue[Any], args: dict[str, Any]) -> None:
113 """Initialize Hub Consumer."""
114 self.queue = queue
115 tenant_id = args.get("azure_tenant_id")
116 client_id = args.get("azure_client_id")
117 client_secret = args.get("azure_client_secret")
118
119 self.event_hub_namespace = args.get("azure_namespace")
120 self.event_hub_name = args.get("azure_event_hub_name")
121
122 self.consumer_group = args.get("azure_consumer_group", "$Default")
123 self.starting_position = int(args.get("azure_starting_position", "-1"))
124 self.feedback_timeout = int(args.get("feedback_timeout", DEFAULT_FEEDBACK_TIMEOUT))
125 self.feedback = args.get("feedback", False)
126 self.eda_feedback_queue = args.get("eda_feedback_queue")
127
128 if self.feedback and self.eda_feedback_queue is None:
129 msg = (
130 "feedback: true was set but no feedback queue was provided. "
131 "This requires a compatible version of ansible-rulebook that "
132 "supports the feedback mechanism."
133 )
134 raise ValueError(msg)
135
136 self.credential = ClientSecretCredential(
137 tenant_id=tenant_id,
138 client_id=client_id,
139 client_secret=client_secret,
140 )
141
142 async def on_event(
143 self, partition_context: PartitionContext, event: EventData,
144 ) -> None:
145 """Receiving event data."""
146 if event:
147 meta = {}
148 msg_id = (
149 event.message_id
150 or event.correlation_id
151 or f"{partition_context.partition_id}:{event.sequence_number}"
152 )
153
154 meta["event"] = {"uuid": msg_id}
155 if event.enqueued_time:
156 meta["event"]["produced_at"] = event.enqueued_time.isoformat()
157 # Process message body
158 try:
159 value = event.body_as_str()
160 logger.debug(
161 "Received event from partition %s: %s",
162 str(partition_context.partition_id),
163 value,
164 )
165 except UnicodeError:
166 logger.exception("Unicode error while decoding message body")
167 data = None
168 else:
169 try:
170 data = json.loads(value)
171 except json.decoder.JSONDecodeError:
172 logger.info("JSON decode error, storing raw value")
173 data = value
174
175 # Add data to the event and put it into the queue
176 if data:
177 await self.queue.put({"body": data, "meta": meta})
178
179 if self.feedback and self.eda_feedback_queue:
180 try:
181 await asyncio.wait_for(
182 self.eda_feedback_queue.get(),
183 timeout=self.feedback_timeout,
184 )
185 await partition_context.update_checkpoint(event)
186 except asyncio.TimeoutError:
187 logger.exception("Timed out waiting for feedback")
188 raise
189 else:
190 await partition_context.update_checkpoint(event)
191
192 await asyncio.sleep(0)
193
194 async def start_receiving(self) -> None:
195 """Start receiving data."""
196 client = EventHubConsumerClient(
197 fully_qualified_namespace=self.event_hub_namespace,
198 eventhub_name=self.event_hub_name,
199 consumer_group=self.consumer_group,
200 credential=self.credential,
201 )
202 async with client:
203 await client.receive(self.on_event)
204
205
206 # Usage
207 async def main( # pylint: disable=R0914
208 queue: asyncio.Queue[Any],
209 args: dict[str, Any],
210 ) -> None:
211 """Entry Point."""
212 for key in REQUIRED_ARGS:
213 if key not in args:
214 msg = f"Please provide {key} it is a required argument."
215 raise ValueError(msg)
216
217 consumer = AzureHubConsumer(queue, args)
218 await consumer.start_receiving()
219
220
221 if __name__ == "__main__":
222
223 class MockQueue(asyncio.Queue[Any]):
224 """A fake queue."""
225
226 async def put(self: "MockQueue", event: dict[str, Any]) -> None:
227 """Print the event."""
228 print(event) # noqa: T201
229
230 test_args = {
231 "azure_tenant_id": "your_tenant_id",
232 "azure_client_id": "your_client_id",
233 "azure_client_secret": "your_client_secret",
234 "azure_namespace": "example.servicebus.windows.net",
235 "azure_event_hub_name": "your_hub_name",
236 "azure_starting_position": "-1",
237 }
238
239 asyncio.run(
240 main(
241 MockQueue(),
242 test_args,
243 ),
244 )