| 1 |
import asyncio |
| 2 |
import json |
| 3 |
import logging |
| 4 |
from typing import Any |
| 5 |
from typing import TypedDict |
| 6 |
|
| 7 |
import botocore.exceptions |
| 8 |
from aiobotocore.session import get_session |
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
--- |
| 12 |
short_description: Receive events via an AWS SQS queue |
| 13 |
description: |
| 14 |
- An ansible-rulebook event source plugin for receiving events via an AWS SQS queue. |
| 15 |
- > |
| 16 |
This supports all the authentication methods supported by boto3 library: |
| 17 |
U(https://boto3.amazonaws.com/v1/documentation/api/latest/guide/credentials.html). |
| 18 |
options: |
| 19 |
access_key: |
| 20 |
description: |
| 21 |
- Optional AWS access key ID. |
| 22 |
type: str |
| 23 |
secret_key: |
| 24 |
description: |
| 25 |
- Optional AWS secret access key. |
| 26 |
type: str |
| 27 |
session_token: |
| 28 |
description: |
| 29 |
- Optional STS session token for use with temporary credentials. |
| 30 |
type: str |
| 31 |
endpoint_url: |
| 32 |
description: |
| 33 |
- Optional URL to connect to instead of the default AWS endpoints. |
| 34 |
type: str |
| 35 |
queue_owner_aws_account_id: |
| 36 |
description: |
| 37 |
- > |
| 38 |
Optional The Amazon Web Services account ID of the account that |
| 39 |
created the queue. This is only required when you are attempting |
| 40 |
to access a queue owned by another Amazon Web Services account. |
| 41 |
type: str |
| 42 |
region: |
| 43 |
description: |
| 44 |
- Optional AWS region to use. |
| 45 |
type: str |
| 46 |
name: |
| 47 |
description: |
| 48 |
- Name of the queue. |
| 49 |
type: str |
| 50 |
required: true |
| 51 |
delay_seconds: |
| 52 |
description: |
| 53 |
- The SQS long polling duration. |
| 54 |
- Set to V(0) to disable. |
| 55 |
type: int |
| 56 |
default: 2 |
| 57 |
max_number_of_messages: |
| 58 |
description: |
| 59 |
- > |
| 60 |
Optional The maximum number of messages to return. Amazon SQS |
| 61 |
never returns more messages than this value (however, fewer |
| 62 |
messages might be returned). Valid values are V(1) to V(10). |
| 63 |
type: int |
| 64 |
default: 1 |
| 65 |
feedback: |
| 66 |
type: bool |
| 67 |
default: false |
| 68 |
description: |
| 69 |
- Should the source plugin wait for feedback before |
| 70 |
processing the next event from SQS Queue. |
| 71 |
This flag allows ansible rulebook to pass in an asyncio |
| 72 |
queue which is passed in the O(eda_feedback_queue). |
| 73 |
The source plugin should wait for the response to come |
| 74 |
back on this queue before it picks the next event from |
| 75 |
SQS queue. |
| 76 |
version_added: 11.3.0 |
| 77 |
feedback_timeout: |
| 78 |
type: int |
| 79 |
default: 120 |
| 80 |
description: |
| 81 |
- Timeout in seconds to wait for feedback from the rule engine |
| 82 |
before raising an exception. Only applies when feedback is enabled. |
| 83 |
version_added: 11.3.0 |
| 84 |
eda_feedback_queue: |
| 85 |
description: |
| 86 |
- Provided automatically by ansible-rulebook when the feedback |
| 87 |
parameter is enabled, this parameter utilizes an asyncio.Queue. |
| 88 |
It allows the system to wait for confirmation that an event has |
| 89 |
been safely persisted in the database before removing it from the |
| 90 |
event queue. Users do not need to provide a value for this manually. |
| 91 |
version_added: 11.3.0 |
| 92 |
""" |
| 93 |
|
| 94 |
EXAMPLES = r""" |
| 95 |
- amazon.aws.aws_sqs_queue: |
| 96 |
region: us-east-1 |
| 97 |
name: eda |
| 98 |
delay_seconds: 10 |
| 99 |
""" |
| 100 |
|
| 101 |
|
| 102 |
DEFAULT_FEEDBACK_TIMEOUT = 120 |
| 103 |
|
| 104 |
|
| 105 |
class DeleteMessageBatchRequestEntryTypeDef(TypedDict): |
| 106 |
"""Custom TypedDict for Delete Message Batch Request Entry.""" |
| 107 |
|
| 108 |
Id: str |
| 109 |
ReceiptHandle: str |
| 110 |
|
| 111 |
|
| 112 |
class MessageDeletionException(Exception): |
| 113 |
pass |
| 114 |
|
| 115 |
|
| 116 |
class QueueConfig(TypedDict): |
| 117 |
"""Configuration extracted from arguments.""" |
| 118 |
|
| 119 |
queue_name: str |
| 120 |
wait_seconds: int |
| 121 |
max_number_of_messages: int |
| 122 |
queue_owner_aws_account_id: str | None |
| 123 |
feedback_enabled: bool |
| 124 |
feedback_timeout: int |
| 125 |
eda_feedback_queue: asyncio.Queue[Any] | None |
| 126 |
|
| 127 |
|
| 128 |
def _validate_and_extract_config(args: dict[str, Any]) -> QueueConfig: |
| 129 |
"""Validate arguments and extract configuration. |
| 130 |
|
| 131 |
Args: |
| 132 |
args: Dictionary of arguments |
| 133 |
|
| 134 |
Returns: |
| 135 |
QueueConfig with validated configuration |
| 136 |
|
| 137 |
Raises: |
| 138 |
ValueError: If required arguments are missing or invalid |
| 139 |
""" |
| 140 |
if "name" not in args: |
| 141 |
msg = "Missing queue name" |
| 142 |
raise ValueError(msg) |
| 143 |
|
| 144 |
feedback_enabled = args.get("feedback", False) |
| 145 |
eda_feedback_queue = args.get("eda_feedback_queue", None) |
| 146 |
|
| 147 |
if feedback_enabled and eda_feedback_queue is None: |
| 148 |
msg = ( |
| 149 |
"feedback: true was set but no feedback queue was provided. " |
| 150 |
"This requires a compatible version of ansible-rulebook that " |
| 151 |
"supports the feedback mechanism." |
| 152 |
) |
| 153 |
raise ValueError(msg) |
| 154 |
|
| 155 |
return QueueConfig( |
| 156 |
queue_name=str(args.get("name")), |
| 157 |
wait_seconds=int(args.get("delay_seconds", 2)), |
| 158 |
max_number_of_messages=int(args.get("max_number_of_messages", 1)), |
| 159 |
queue_owner_aws_account_id=args.get("queue_owner_aws_account_id"), |
| 160 |
feedback_enabled=feedback_enabled, |
| 161 |
feedback_timeout=int(args.get("feedback_timeout", DEFAULT_FEEDBACK_TIMEOUT)), |
| 162 |
eda_feedback_queue=eda_feedback_queue, |
| 163 |
) |
| 164 |
|
| 165 |
|
| 166 |
async def _get_queue_url( |
| 167 |
client, |
| 168 |
queue_name: str, |
| 169 |
queue_owner_aws_account_id: str | None, |
| 170 |
) -> str: |
| 171 |
"""Retrieve the SQS queue URL. |
| 172 |
|
| 173 |
Args: |
| 174 |
client: AWS SQS client |
| 175 |
queue_name: Name of the queue |
| 176 |
queue_owner_aws_account_id: Optional account ID of queue owner |
| 177 |
|
| 178 |
Returns: |
| 179 |
Queue URL |
| 180 |
|
| 181 |
Raises: |
| 182 |
ValueError: If queue does not exist |
| 183 |
""" |
| 184 |
queue_args = {"QueueName": queue_name} |
| 185 |
if queue_owner_aws_account_id: |
| 186 |
queue_args["QueueOwnerAWSAccountId"] = queue_owner_aws_account_id |
| 187 |
|
| 188 |
try: |
| 189 |
response = await client.get_queue_url(**queue_args) |
| 190 |
except botocore.exceptions.ClientError as err: |
| 191 |
if err.response["Error"]["Code"] == "AWS.SimpleQueueService.NonExistentQueue": |
| 192 |
msg = f"Queue {queue_name} does not exist" |
| 193 |
raise ValueError(msg) from None |
| 194 |
raise |
| 195 |
|
| 196 |
return response["QueueUrl"] |
| 197 |
|
| 198 |
|
| 199 |
def _parse_message_body(entry: dict[str, Any]) -> Any: |
| 200 |
"""Parse the message body from JSON. |
| 201 |
|
| 202 |
Args: |
| 203 |
entry: SQS message entry |
| 204 |
|
| 205 |
Returns: |
| 206 |
Parsed message body or raw body if parsing fails |
| 207 |
""" |
| 208 |
logger = logging.getLogger() |
| 209 |
|
| 210 |
try: |
| 211 |
return json.loads(entry["Body"]) |
| 212 |
except json.JSONDecodeError: |
| 213 |
logger.error("JSON decode error, storing raw value") |
| 214 |
return entry["Body"] |
| 215 |
except UnicodeError: |
| 216 |
logger.exception("Unicode error while decoding message body") |
| 217 |
return None |
| 218 |
|
| 219 |
|
| 220 |
async def _handle_feedback_and_delete( |
| 221 |
client, |
| 222 |
queue_url: str, |
| 223 |
delete_entry: DeleteMessageBatchRequestEntryTypeDef, |
| 224 |
config: QueueConfig, |
| 225 |
) -> None: |
| 226 |
"""Handle feedback mechanism and message deletion. |
| 227 |
|
| 228 |
Args: |
| 229 |
client: AWS SQS client |
| 230 |
queue_url: Queue URL |
| 231 |
delete_entry: Message deletion entry |
| 232 |
config: Queue configuration |
| 233 |
|
| 234 |
Raises: |
| 235 |
asyncio.TimeoutError: If feedback timeout is exceeded |
| 236 |
MessageDeletionException: If message deletion fails |
| 237 |
""" |
| 238 |
logger = logging.getLogger() |
| 239 |
|
| 240 |
if config["feedback_enabled"] and config["eda_feedback_queue"]: |
| 241 |
try: |
| 242 |
await asyncio.wait_for( |
| 243 |
config["eda_feedback_queue"].get(), |
| 244 |
timeout=config["feedback_timeout"], |
| 245 |
) |
| 246 |
if not await _delete_messages(client, queue_url, [delete_entry]): |
| 247 |
logger.exception("Failed to delete messages, exiting") |
| 248 |
raise MessageDeletionException("Messages could not be deleted") |
| 249 |
except asyncio.TimeoutError: |
| 250 |
logger.exception("Timed out waiting for feedback") |
| 251 |
raise |
| 252 |
else: |
| 253 |
await _delete_messages(client, queue_url, [delete_entry]) |
| 254 |
|
| 255 |
|
| 256 |
async def _process_message( |
| 257 |
entry: dict[str, Any], |
| 258 |
queue: asyncio.Queue[Any], |
| 259 |
client, |
| 260 |
queue_url: str, |
| 261 |
config: QueueConfig, |
| 262 |
) -> None: |
| 263 |
"""Process a single SQS message. |
| 264 |
|
| 265 |
Args: |
| 266 |
entry: SQS message entry |
| 267 |
queue: Queue to put processed events |
| 268 |
client: AWS SQS client |
| 269 |
queue_url: Queue URL |
| 270 |
config: Queue configuration |
| 271 |
|
| 272 |
Raises: |
| 273 |
ValueError: If message format is invalid |
| 274 |
""" |
| 275 |
if not isinstance(entry, dict) or "MessageId" not in entry: # pragma: no cover |
| 276 |
err_msg = f"Unexpected response {entry}, missing MessageId." |
| 277 |
raise ValueError(err_msg) |
| 278 |
|
| 279 |
delete_entry = DeleteMessageBatchRequestEntryTypeDef( |
| 280 |
Id=entry["MessageId"], |
| 281 |
ReceiptHandle=entry["ReceiptHandle"], |
| 282 |
) |
| 283 |
|
| 284 |
meta = { |
| 285 |
"MessageId": entry["MessageId"], |
| 286 |
"event": {"uuid": entry["MessageId"]}, |
| 287 |
} |
| 288 |
|
| 289 |
msg_body = _parse_message_body(entry) |
| 290 |
|
| 291 |
await queue.put({"body": msg_body, "meta": meta}) |
| 292 |
await _handle_feedback_and_delete(client, queue_url, delete_entry, config) |
| 293 |
await asyncio.sleep(0) |
| 294 |
|
| 295 |
|
| 296 |
async def _delete_messages(client, queue_url, entries) -> bool: |
| 297 |
result = False |
| 298 |
logger = logging.getLogger() |
| 299 |
# Need to remove msg from queue or else it'll reappear |
| 300 |
delete_results = await client.delete_message_batch( |
| 301 |
QueueUrl=queue_url, |
| 302 |
Entries=entries, |
| 303 |
) |
| 304 |
|
| 305 |
# Check if the deletion was successful |
| 306 |
if "Successful" in delete_results: |
| 307 |
result = True |
| 308 |
for item in delete_results["Successful"]: |
| 309 |
logger.debug( |
| 310 |
"Message with ID %s deleted successfully", |
| 311 |
item["Id"], |
| 312 |
) |
| 313 |
# Log a error if any message failed deletions |
| 314 |
if "Failed" in delete_results: |
| 315 |
result = False |
| 316 |
for item in delete_results["Failed"]: |
| 317 |
logger.error( |
| 318 |
"Error deleting message with ID : %s Error Code: %s Error Message: %s SenderFault: %s", |
| 319 |
item["Id"], |
| 320 |
item["Code"], |
| 321 |
item["Message"], |
| 322 |
str(item["SenderFault"]), |
| 323 |
) |
| 324 |
|
| 325 |
return result |
| 326 |
|
| 327 |
|
| 328 |
async def main( |
| 329 |
queue: asyncio.Queue[Any], |
| 330 |
args: dict[str, Any], |
| 331 |
) -> None: |
| 332 |
"""Receive events via an AWS SQS queue.""" |
| 333 |
logger = logging.getLogger() |
| 334 |
|
| 335 |
# Validate arguments and extract configuration |
| 336 |
config = _validate_and_extract_config(args) |
| 337 |
|
| 338 |
session = get_session() |
| 339 |
|
| 340 |
async with session.create_client("sqs", **connection_args(args)) as client: |
| 341 |
# Get the queue URL |
| 342 |
queue_url = await _get_queue_url( |
| 343 |
client, |
| 344 |
config["queue_name"], |
| 345 |
config["queue_owner_aws_account_id"], |
| 346 |
) |
| 347 |
|
| 348 |
# Main message processing loop |
| 349 |
while True: |
| 350 |
# This loop won't spin really fast as there is |
| 351 |
# essentially a sleep in the receive_message call |
| 352 |
response_msg = await client.receive_message( |
| 353 |
QueueUrl=queue_url, |
| 354 |
WaitTimeSeconds=config["wait_seconds"], |
| 355 |
MaxNumberOfMessages=config["max_number_of_messages"], |
| 356 |
) |
| 357 |
|
| 358 |
if "Messages" in response_msg: |
| 359 |
for entry in response_msg["Messages"]: |
| 360 |
await _process_message(entry, queue, client, queue_url, config) |
| 361 |
else: |
| 362 |
logger.debug("No messages in queue") |
| 363 |
|
| 364 |
|
| 365 |
def connection_args(args: dict[str, Any]) -> dict[str, Any]: |
| 366 |
"""Provide connection arguments to AWS SQS queue.""" |
| 367 |
selected_args = {} |
| 368 |
|
| 369 |
# Best Practice: get credentials from ~/.aws/credentials or the environment |
| 370 |
# However the following method are still possible |
| 371 |
if "access_key" in args: |
| 372 |
selected_args["aws_access_key_id"] = args["access_key"] |
| 373 |
if "secret_key" in args: |
| 374 |
selected_args["aws_secret_access_key"] = args["secret_key"] |
| 375 |
if "session_token" in args: |
| 376 |
selected_args["aws_session_token"] = args["session_token"] |
| 377 |
|
| 378 |
if "endpoint_url" in args: |
| 379 |
selected_args["endpoint_url"] = args["endpoint_url"] |
| 380 |
if "region" in args: |
| 381 |
selected_args["region_name"] = args["region"] |
| 382 |
|
| 383 |
return selected_args |
| 384 |
|
| 385 |
|
| 386 |
if __name__ == "__main__": |
| 387 |
# MockQueue if running directly |
| 388 |
|
| 389 |
class MockQueue(asyncio.Queue[Any]): |
| 390 |
"""A fake queue.""" |
| 391 |
|
| 392 |
async def put(self: "MockQueue", event: dict[str, Any]) -> None: |
| 393 |
"""Print the event.""" |
| 394 |
print(event) # noqa: T201 |
| 395 |
|
| 396 |
asyncio.run(main(MockQueue(), {"region": "us-east-1", "name": "eda"})) |