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

Events - send events to (subset of) targets #5169

Merged
Merged
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
2 changes: 2 additions & 0 deletions docs/docs/services/events.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
events
======

.. autoclass:: moto.events.models.EventsBackend

|start-h3| Example usage |end-h3|

.. sourcecode:: python
Expand Down
11 changes: 11 additions & 0 deletions moto/events/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -824,6 +824,9 @@ def __init__(self, raw_pattern, pattern):
self._raw_pattern = raw_pattern
self._pattern = pattern

def get_pattern(self):
return self._pattern

def matches_event(self, event):
if not self._pattern:
return True
Expand Down Expand Up @@ -921,6 +924,14 @@ def parse(self):


class EventsBackend(BaseBackend):
"""
When a event occurs, the appropriate targets are triggered for a subset of usecases.

Supported events: S3:CreateBucket

Supported targets: AWSLambda functions
"""

ACCOUNT_ID = re.compile(r"^(\d{1,12}|\*)$")
STATEMENT_ID = re.compile(r"^[a-zA-Z0-9-_]{1,64}$")
_CRON_REGEX = re.compile(r"^cron\(.*\)")
Expand Down
65 changes: 65 additions & 0 deletions moto/events/notifications.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import json


_EVENT_S3_OBJECT_CREATED = {
"version": "0",
"id": "17793124-05d4-b198-2fde-7ededc63b103",
"detail-type": "Object Created",
"source": "aws.s3",
"account": "123456789012",
"time": "2021-11-12T00:00:00Z",
"region": None,
"resources": [],
"detail": None,
}


def send_notification(source, event_name, region, resources, detail):
try:
_send_safe_notification(source, event_name, region, resources, detail)
except: # noqa
# If anything goes wrong, we should never fail
pass


def _send_safe_notification(source, event_name, region, resources, detail):
from .models import events_backends

event = None
if source == "aws.s3" and event_name == "CreateBucket":
event = _EVENT_S3_OBJECT_CREATED.copy()
event["region"] = region
event["resources"] = resources
event["detail"] = detail

if event is None:
return

for backend in events_backends.values():
applicable_targets = []
for rule in backend.rules.values():
if rule.state != "ENABLED":
continue
pattern = rule.event_pattern.get_pattern()
if source in pattern.get("source", []):
if event_name in pattern.get("detail", {}).get("eventName", []):
applicable_targets.extend(rule.targets)

for target in applicable_targets:
if target.get("Arn", "").startswith("arn:aws:lambda"):
_invoke_lambda(target.get("Arn"), event=event)


def _invoke_lambda(fn_arn, event):
from moto.awslambda import lambda_backends

lmbda_region = fn_arn.split(":")[3]

body = json.dumps(event)
lambda_backends[lmbda_region].invoke(
function_name=fn_arn,
qualifier=None,
body=body,
headers=dict(),
response_headers=dict(),
)
18 changes: 18 additions & 0 deletions moto/s3/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@
from .cloud_formation import cfn_to_api_encryption, is_replacement_update
from . import notifications
from .utils import clean_key_name, _VersionedKeyStore, undo_clean_key_name
from ..events.notifications import send_notification as events_send_notification
from ..settings import get_s3_default_key_buffer_size, S3_UPLOAD_PART_MIN_SIZE

MAX_BUCKET_NAME_LENGTH = 63
Expand Down Expand Up @@ -1463,6 +1464,23 @@ def create_bucket(self, bucket_name, region_name):
new_bucket = FakeBucket(name=bucket_name, region_name=region_name)

self.buckets[bucket_name] = new_bucket

notification_detail = {
"version": "0",
"bucket": {"name": bucket_name},
"request-id": "N4N7GDK58NMKJ12R",
"requester": get_account_id(),
"source-ip-address": "1.2.3.4",
"reason": "PutObject",
}
events_send_notification(
source="aws.s3",
event_name="CreateBucket",
region=region_name,
resources=[f"arn:aws:s3:::{bucket_name}"],
detail=notification_detail,
)

return new_bucket

def list_buckets(self):
Expand Down
Loading