-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathcli.py
More file actions
executable file
·494 lines (399 loc) · 14.6 KB
/
Copy pathcli.py
File metadata and controls
executable file
·494 lines (399 loc) · 14.6 KB
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
#!/usr/bin/env python3
import argparse
import json
import logging
import os
import shutil
import subprocess
import sys
import time
import zipfile
from pathlib import Path
# Configure logging
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
try:
import boto3
from aws_durable_execution_sdk_python.lambda_service import LambdaClient
except ImportError:
sys.exit(1)
def load_catalog():
"""Load examples catalog."""
catalog_path = Path(__file__).parent / "examples-catalog.json"
with open(catalog_path) as f:
return json.load(f)
def build_examples():
"""Build examples with SDK dependencies."""
build_dir = Path(__file__).parent / "build"
src_dir = Path(__file__).parent / "src"
packages_dir = Path(__file__).parent.parent
logger.info("Building examples...")
# Clean and create build directory
if build_dir.exists():
logger.info("Cleaning existing build directory")
shutil.rmtree(build_dir)
build_dir.mkdir()
# Install local packages so their runtime dependencies are included in
# the Lambda deployment package.
runtime_packages = [
packages_dir / "aws-durable-execution-sdk-python",
packages_dir / "aws-durable-execution-sdk-python-otel",
packages_dir / "aws-durable-execution-sdk-python-testing",
]
try:
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"--upgrade",
"--target",
str(build_dir),
*[str(package) for package in runtime_packages],
],
check=True,
)
except subprocess.CalledProcessError:
logger.exception("Failed to install runtime dependencies")
return False
# Copy example functions
logger.info("Copying examples from %s", src_dir)
for file_path in src_dir.rglob("*"):
if file_path.is_file():
shutil.copy2(file_path, build_dir / file_path.name)
logger.info("Build completed successfully")
return True
def create_kms_key(kms_client, account_id):
"""Create KMS key for durable functions encryption."""
key_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Enable IAM User Permissions",
"Effect": "Allow",
"Principal": {"AWS": f"arn:aws:iam::{account_id}:root"},
"Action": "kms:*",
"Resource": "*",
},
{
"Sid": "Allow Lambda service",
"Effect": "Allow",
"Principal": {"Service": "lambda.amazonaws.com"},
"Action": ["kms:Decrypt", "kms:Encrypt", "kms:CreateGrant"],
"Resource": "*",
},
],
}
try:
response = kms_client.create_key(
Description="KMS key for Lambda Durable Functions environment variable encryption",
KeyUsage="ENCRYPT_DECRYPT",
KeySpec="SYMMETRIC_DEFAULT",
Policy=json.dumps(key_policy),
)
return response["KeyMetadata"]["Arn"]
except (kms_client.exceptions.ClientError, KeyError):
return None
def bootstrap_account():
"""Bootstrap account with necessary IAM role and KMS key."""
account_id = os.getenv("AWS_ACCOUNT_ID")
region = os.getenv("AWS_REGION", "us-west-2")
if not account_id:
return False
# Create KMS key first
kms_client = boto3.client("kms", region_name=region)
kms_key_arn = create_kms_key(kms_client, account_id)
if not kms_key_arn:
return False
iam_client = boto3.client("iam", region_name=region)
role_name = "DurableFunctionsIntegrationTestRole"
trust_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": ["lambda.amazonaws.com", "devo.lambda.aws.internal"]
},
"Action": "sts:AssumeRole",
}
],
}
lambda_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"lambda:CheckpointDurableExecution",
"lambda:GetDurableExecutionState",
],
"Resource": "*",
"Effect": "Allow",
}
],
}
logs_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
],
"Resource": "*",
"Effect": "Allow",
}
],
}
kms_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Action": ["kms:CreateGrant", "kms:Decrypt", "kms:Encrypt"],
"Resource": kms_key_arn,
"Effect": "Allow",
}
],
}
try:
iam_client.create_role(
RoleName=role_name,
AssumeRolePolicyDocument=json.dumps(trust_policy),
Description="Role for AWS Durable Functions integration testing",
)
iam_client.put_role_policy(
RoleName=role_name,
PolicyName="LambdaPolicy",
PolicyDocument=json.dumps(lambda_policy),
)
iam_client.put_role_policy(
RoleName=role_name,
PolicyName="LogsPolicy",
PolicyDocument=json.dumps(logs_policy),
)
iam_client.put_role_policy(
RoleName=role_name,
PolicyName="DurableFunctionsLambdaStagingKMSPolicy",
PolicyDocument=json.dumps(kms_policy),
)
except iam_client.exceptions.EntityAlreadyExistsException:
pass
except iam_client.exceptions.ClientError:
return False
else:
return True
return True
def create_deployment_package(example_name: str) -> Path:
"""Create deployment package for example."""
build_dir = Path(__file__).parent / "build"
if not build_dir.exists() and not build_examples():
msg = "Failed to build examples"
raise ValueError(msg)
zip_path = Path(__file__).parent / f"{example_name}.zip"
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
# Add SDK dependencies
for file_path in build_dir.rglob("*"):
if file_path.is_file() and not file_path.is_relative_to(build_dir / "src"):
zf.write(file_path, file_path.relative_to(build_dir))
# Add example files at root level
src_dir = build_dir / "src"
for file_path in src_dir.rglob("*"):
if file_path.is_file():
zf.write(file_path, file_path.relative_to(src_dir))
return zip_path
def get_aws_config():
"""Get AWS configuration from environment."""
config = {
"region": os.getenv("AWS_REGION", "us-west-2"),
"lambda_endpoint": os.getenv(
"LAMBDA_ENDPOINT", "https://lambda.us-west-2.amazonaws.com"
),
"account_id": os.getenv("AWS_ACCOUNT_ID"),
"kms_key_arn": os.getenv("KMS_KEY_ARN"),
}
if not config["account_id"]:
msg = "Missing AWS_ACCOUNT_ID"
raise ValueError(msg)
return config
def get_lambda_client():
"""Get configured Lambda client."""
config = get_aws_config()
return boto3.client(
"lambda",
endpoint_url=config["lambda_endpoint"],
region_name=config["region"],
config=boto3.session.Config(parameter_validation=False),
)
def retry_on_resource_conflict(func, *args, max_retries=5, **kwargs):
"""Retry function on ResourceConflictException."""
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
if (
hasattr(e, "response")
and e.response.get("Error", {}).get("Code")
== "ResourceConflictException"
and attempt < max_retries - 1
):
wait_time = 2**attempt # Exponential backoff
logger.info(
"ResourceConflictException on attempt %d, retrying in %ds...",
attempt + 1,
wait_time,
)
time.sleep(wait_time)
continue
raise
return None
def deploy_function(example_name: str, function_name: str | None = None):
"""Deploy function to AWS Lambda."""
catalog = load_catalog()
example_config = None
for example in catalog["examples"]:
if example["name"] == example_name:
example_config = example
break
if not example_config:
logger.error("Example not found: '%s'", example_name)
list_examples()
return False
if not function_name:
function_name = f"{example_name.replace(' ', '')}-Python"
handler_file = example_config["handler"].replace(".handler", "")
zip_path = create_deployment_package(handler_file)
config = get_aws_config()
lambda_client = get_lambda_client()
role_arn = (
f"arn:aws:iam::{config['account_id']}:role/DurableFunctionsIntegrationTestRole"
)
function_config = {
"FunctionName": function_name,
"Runtime": "python3.13",
"Role": role_arn,
"Handler": example_config["handler"],
"Description": example_config["description"],
"Timeout": 60,
"MemorySize": 128,
"Environment": {
"Variables": {"AWS_ENDPOINT_URL_LAMBDA": config["lambda_endpoint"]}
},
"DurableConfig": example_config["durableConfig"],
"LoggingConfig": example_config.get("loggingConfig", {}),
}
if config["kms_key_arn"]:
function_config["KMSKeyArn"] = config["kms_key_arn"]
with open(zip_path, "rb") as f:
zip_content = f.read()
try:
lambda_client.get_function(FunctionName=function_name)
retry_on_resource_conflict(
lambda_client.update_function_code,
FunctionName=function_name,
ZipFile=zip_content,
max_retries=8,
)
retry_on_resource_conflict(
lambda_client.update_function_configuration, **function_config
)
except lambda_client.exceptions.ResourceNotFoundException:
lambda_client.create_function(**function_config, Code={"ZipFile": zip_content})
logger.info("Function deployed successfully! %s", function_name)
return True
def invoke_function(function_name: str, payload: str = "{}"):
"""Invoke a deployed function."""
lambda_client = get_lambda_client()
try:
response = lambda_client.invoke(FunctionName=function_name, Payload=payload)
result = json.loads(response["Payload"].read())
if "DurableExecutionArn" in result:
pass
return result.get("DurableExecutionArn")
except lambda_client.exceptions.ClientError:
return None
def get_execution(execution_arn: str):
"""Get execution details."""
lambda_client = get_lambda_client()
try:
return lambda_client.get_durable_execution(DurableExecutionArn=execution_arn)
except lambda_client.exceptions.ClientError:
return None
def get_execution_history(execution_arn: str):
"""Get execution history."""
lambda_client = get_lambda_client()
try:
return lambda_client.get_durable_execution_history(
DurableExecutionArn=execution_arn
)
except lambda_client.exceptions.ClientError:
return None
def get_function_policy(function_name: str):
"""Get function resource policy."""
lambda_client = get_lambda_client()
try:
response = lambda_client.get_policy(FunctionName=function_name)
return json.loads(response["Policy"])
except lambda_client.exceptions.ResourceNotFoundException:
return None
except (lambda_client.exceptions.ClientError, json.JSONDecodeError):
return None
def list_examples():
"""List available examples."""
catalog = load_catalog()
logger.info("Available examples:")
for example in catalog["examples"]:
logger.info(" - %s: %s", example["name"], example["description"])
def main():
"""Main CLI function."""
parser = argparse.ArgumentParser(description="Durable Functions Examples CLI")
subparsers = parser.add_subparsers(dest="command", help="Available commands")
# Bootstrap command
subparsers.add_parser("bootstrap", help="Bootstrap account with necessary IAM role")
# Build command
subparsers.add_parser("build", help="Build examples with dependencies")
# List command
subparsers.add_parser("list", help="List available examples")
# Deploy command
deploy_parser = subparsers.add_parser("deploy", help="Deploy an example")
deploy_parser.add_argument("example_name", help="Name of example to deploy")
deploy_parser.add_argument("--function-name", help="Custom function name")
# Invoke command
invoke_parser = subparsers.add_parser("invoke", help="Invoke a deployed function")
invoke_parser.add_argument("function_name", help="Name of function to invoke")
invoke_parser.add_argument("--payload", default="{}", help="JSON payload to send")
# Get command
get_parser = subparsers.add_parser("get", help="Get execution details")
get_parser.add_argument("execution_arn", help="Execution ARN")
# Policy command
policy_parser = subparsers.add_parser("policy", help="Get function resource policy")
policy_parser.add_argument("function_name", help="Function name")
# History command
history_parser = subparsers.add_parser("history", help="Get execution history")
history_parser.add_argument("execution_arn", help="Execution ARN")
args = parser.parse_args()
if not args.command:
parser.print_help()
return
try:
if args.command == "bootstrap":
bootstrap_account()
elif args.command == "build":
build_examples()
elif args.command == "list":
list_examples()
elif args.command == "deploy":
deploy_function(args.example_name, args.function_name)
elif args.command == "invoke":
invoke_function(args.function_name, args.payload)
elif args.command == "policy":
get_function_policy(args.function_name)
elif args.command == "get":
get_execution(args.execution_arn)
elif args.command == "history":
get_execution_history(args.execution_arn)
except (KeyboardInterrupt, SystemExit):
sys.exit(1)
if __name__ == "__main__":
main()