-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.py
224 lines (170 loc) · 7.09 KB
/
watcher.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
"""
----------------- Prerequisites -----------------
1. Async lambda invocations
This service is designed to be used with AWS Lambda functions that are invoked asynchronously.
The async invocation requirement is present because Lambda completion messages can only be forwarded to
even processing systems like an EventBridge event bus when the invocation is asynchronous.
2. AWS CloudTrail
A CloudTrail trail must be set up to capture the invocations of the Lambda functions.
3. EventBridge rules
EventBridge rules must be set up to forward Lambda completion events and CloudTrail events for Lambda
invocations to an SQS queue for consumption by this service.
4. FIFO SQS queue
This service polls an SQS queue for messages and parses their contents to create flow runs and manage their state.
----------------- Limitations -----------------
This approach cannot capture the following:
- Logs and prints from the Lambda function
- Retries after a Lambda function fails
- Lambda functions that are invoked synchronously
"""
import abc
import asyncio
import json
from datetime import datetime
from enum import Enum
from uuid import UUID
from typing import Optional
import boto3
from prefect import flow, get_client
from prefect.states import Running, Completed, Failed
from pydantic import BaseModel, Field
class Invocation(BaseModel):
lambda_name: str = Field(...)
flow_run_id: Optional[UUID] = Field(default=None)
start_time: Optional[datetime] = Field(default=None)
end_time: Optional[datetime] = Field(default=None)
success: Optional[bool] = Field(default=None)
async def create_or_update_flow_run(self):
# we saw the invocation end after the start
if self.flow_run_id and self.end_time:
await self._set_terminal_state()
# we saw the invocation start before the end
elif self.start_time and not self.end_time:
flow_run = await self._create_run()
self.flow_run_id = flow_run.id
# we saw the invocation end before the start
elif self.start_time and self.end_time:
flow_run = await self._create_run()
self.flow_run_id = flow_run.id
await self._set_terminal_state()
async def _create_run(self):
return await get_client().create_flow_run(
flow=lambda_flow.with_options(name=self.lambda_name),
state=Running(timestamp=self.start_time),
)
async def _set_terminal_state(self):
await get_client().set_flow_run_state(
flow_run_id=self.flow_run_id,
state=Completed(timestamp=self.end_time)
if self.success
else Failed(timestamp=self.end_time),
)
class MessageType(Enum):
START = "AWS API Call via CloudTrail"
SUCCESS = "Lambda Function Invocation Result - Success"
FAILURE = "Lambda Function Invocation Result - Failure"
class LambdaMessage(BaseModel, abc.ABC):
message: dict
def get_timestamp(self) -> datetime:
return datetime.strptime(self.message["time"], "%Y-%m-%dT%H:%M:%SZ")
@abc.abstractmethod
def get_request_id(self) -> str: ...
@abc.abstractmethod
def get_lambda_name(self) -> str: ...
class StartMessage(LambdaMessage):
def get_request_id(self) -> str:
print(self.message)
return self.message["detail"]["requestID"]
def get_lambda_name(self) -> str:
return self.message["detail"]["requestParameters"]["functionName"].split(":")[
-1
]
class DestinationMessage(LambdaMessage):
def get_request_id(self) -> str:
print(self.message)
return self.message["detail"]["requestContext"]["requestId"]
def get_lambda_name(self) -> str:
return self.message["detail"]["requestContext"]["functionArn"].split(":")[-2]
class QueueWatcher:
def __init__(self, queue_url: str):
self.sqs = boto3.client("sqs")
self.queue_url = queue_url
self.invocations: dict[str, Invocation] = dict()
def _update_invocation(
self,
request_id: str,
message_type: MessageType,
timestamp: datetime,
) -> Invocation:
if message_type == MessageType.START:
self.invocations[request_id].start_time = timestamp
elif message_type == MessageType.SUCCESS or message_type == MessageType.FAILURE:
self.invocations[request_id].end_time = timestamp
self.invocations[request_id].success = message_type == MessageType.SUCCESS
return self.invocations[request_id]
def _add_invocation(
self,
request_id: str,
message_type: MessageType,
timestamp: datetime,
lambda_name: str,
) -> Invocation:
if message_type == MessageType.START:
self.invocations[request_id] = Invocation(
lambda_name=lambda_name, start_time=timestamp
)
elif message_type == MessageType.SUCCESS or message_type == MessageType.FAILURE:
self.invocations[request_id] = Invocation(
lambda_name=lambda_name,
end_time=timestamp,
success=message_type == MessageType.SUCCESS,
)
return self.invocations[request_id]
async def _handle_message(self, raw_message: dict):
message_type = MessageType(raw_message["detail-type"])
if message_type == MessageType.START:
message = StartMessage(message=raw_message)
elif message_type == MessageType.SUCCESS or message_type == MessageType.FAILURE:
message = DestinationMessage(message=raw_message)
request_id = message.get_request_id()
timestamp = message.get_timestamp()
lambda_name = message.get_lambda_name()
if request_id not in self.invocations:
invocation = self._add_invocation(
request_id, message_type, timestamp, lambda_name
)
else:
invocation = self._update_invocation(request_id, message_type, timestamp)
completed = await invocation.create_or_update_flow_run()
if completed:
finished_invocation = self.invocations.pop(request_id)
print(
f"Invocation {finished_invocation.lambda_name} with flow run {finished_invocation.flow_run_id} completed"
)
async def _receive_messages(self):
response = self.sqs.receive_message(
QueueUrl=self.queue_url,
AttributeNames=["SentTimestamp"],
MaxNumberOfMessages=10,
MessageAttributeNames=["All"],
WaitTimeSeconds=20,
)
messages = response.get("Messages", [])
for message in messages:
body = json.loads(message["Body"])
self.sqs.delete_message(
QueueUrl=self.queue_url, ReceiptHandle=message["ReceiptHandle"]
)
await self._handle_message(body)
async def run(self):
while True:
print("Checking for new messages...")
await self._receive_messages()
@flow
def lambda_flow():
pass
if __name__ == "__main__":
watcher = QueueWatcher(
queue_url="<your-sqs-queue-url>"
)
asyncio.run(watcher.run())