forked from localstack/localstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlambda_api.py
More file actions
2407 lines (2070 loc) · 87.2 KB
/
lambda_api.py
File metadata and controls
2407 lines (2070 loc) · 87.2 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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import base64
import functools
import hashlib
import importlib.machinery
import json
import logging
import os
import re
import sys
import threading
import time
import traceback
import uuid
from datetime import datetime
from io import StringIO
from threading import BoundedSemaphore
from typing import Any, Dict, List, Optional, Tuple, Type
from urllib.parse import urlparse
from flask import Flask, Response, jsonify, request
from localstack import config
from localstack.constants import APPLICATION_JSON, LAMBDA_TEST_ROLE, TEST_AWS_ACCOUNT_ID
from localstack.services.awslambda import lambda_executors
from localstack.services.awslambda.lambda_executors import InvocationResult, LambdaContext
from localstack.services.awslambda.lambda_utils import (
API_PATH_ROOT,
DOTNET_LAMBDA_RUNTIMES,
LAMBDA_DEFAULT_HANDLER,
LAMBDA_DEFAULT_RUNTIME,
LAMBDA_DEFAULT_STARTING_POSITION,
LAMBDA_RUNTIME_NODEJS14X,
ClientError,
error_response,
event_source_arn_matches,
get_handler_file_from_name,
get_lambda_runtime,
get_zip_bytes,
multi_value_dict_for_list,
)
from localstack.services.generic_proxy import RegionBackend
from localstack.services.install import INSTALL_DIR_STEPFUNCTIONS, install_go_lambda_runtime
from localstack.utils import bootstrap
from localstack.utils.analytics import event_publisher
from localstack.utils.aws import aws_stack
from localstack.utils.aws.aws_models import CodeSigningConfig, LambdaFunction
from localstack.utils.aws.aws_responses import ResourceNotFoundException
from localstack.utils.common import (
TMP_FILES,
empty_context_manager,
ensure_readable,
first_char_to_lower,
is_zip_file,
isoformat_milliseconds,
json_safe,
load_file,
long_uid,
mkdir,
now_utc,
parse_request_data,
run,
run_for_max_seconds,
safe_requests,
save_file,
short_uid,
start_worker_thread,
synchronized,
timestamp_millis,
to_bytes,
to_str,
unzip,
)
from localstack.utils.docker_utils import DOCKER_CLIENT
from localstack.utils.generic.singleton_utils import SubtypesInstanceManager
from localstack.utils.http_utils import canonicalize_headers, parse_chunked_data
from localstack.utils.run import FuncThread
# logger
LOG = logging.getLogger(__name__)
# name pattern of IAM policies associated with Lambda functions (name/qualifier)
LAMBDA_POLICY_NAME_PATTERN = "lambda_policy_{name}_{qualifier}"
# constants
APP_NAME = "lambda_api"
ARCHIVE_FILE_PATTERN = "%s/lambda.handler.*.jar" % config.dirs.tmp
LAMBDA_SCRIPT_PATTERN = "%s/lambda_script_*.py" % config.dirs.tmp
LAMBDA_ZIP_FILE_NAME = "original_lambda_archive.zip"
LAMBDA_JAR_FILE_NAME = "original_lambda_archive.jar"
# default timeout in seconds
LAMBDA_DEFAULT_TIMEOUT = 3
INVALID_PARAMETER_VALUE_EXCEPTION = "InvalidParameterValueException"
VERSION_LATEST = LambdaFunction.QUALIFIER_LATEST
FUNCTION_MAX_SIZE = 69905067
BATCH_SIZE_RANGES = {
"kafka": (100, 10000),
"kinesis": (100, 10000),
"dynamodb": (100, 1000),
"sqs": (10, 10),
}
DATE_FORMAT = "%Y-%m-%dT%H:%M:%S.%f+00:00"
app = Flask(APP_NAME)
# mutex for access to CWD and ENV
EXEC_MUTEX = threading.RLock()
# whether to use Docker for execution
DO_USE_DOCKER = None
# start characters indicating that a lambda result should be parsed as JSON
JSON_START_CHAR_MAP = {
list: ("[",),
tuple: ("[",),
dict: ("{",),
str: ('"',),
bytes: ('"',),
bool: ("t", "f"),
type(None): ("n",),
int: ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"),
float: ("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"),
}
POSSIBLE_JSON_TYPES = (str, bytes)
JSON_START_TYPES = tuple(set(JSON_START_CHAR_MAP.keys()) - set(POSSIBLE_JSON_TYPES))
JSON_START_CHARS = tuple(set(functools.reduce(lambda x, y: x + y, JSON_START_CHAR_MAP.values())))
# lambda executor instance
LAMBDA_EXECUTOR = lambda_executors.AVAILABLE_EXECUTORS.get(
config.LAMBDA_EXECUTOR, lambda_executors.DEFAULT_EXECUTOR
)
# IAM policy constants
IAM_POLICY_VERSION = "2012-10-17"
# Whether to check if the handler function exists while creating lambda function
CHECK_HANDLER_ON_CREATION = False
class LambdaRegion(RegionBackend):
# map ARN strings to lambda function objects
lambdas: Dict[str, LambdaFunction]
# map ARN strings to CodeSigningConfig object
code_signing_configs: Dict[str, CodeSigningConfig]
# list of event source mappings for the API
event_source_mappings: List[Dict]
def __init__(self):
self.lambdas = {}
self.code_signing_configs = {}
self.event_source_mappings = []
class EventSourceListener(SubtypesInstanceManager):
INSTANCES: Dict[str, "EventSourceListener"] = {}
@staticmethod
def source_type() -> str:
"""Type discriminator - to be implemented by subclasses."""
raise NotImplementedError
def start(self):
"""Start listener in the background (for polling mode) - to be implemented by subclasses."""
pass
def process_event(self, event: Any):
"""Process the given event (for reactive mode)"""
pass
@staticmethod
def start_listeners(event_source_mapping: Dict):
source_arn = event_source_mapping.get("EventSourceArn") or ""
parts = source_arn.split(":")
service_type = parts[2] if len(parts) > 2 else ""
if not service_type:
self_managed_endpoints = event_source_mapping.get("SelfManagedEventSource", {}).get(
"Endpoints", {}
)
if self_managed_endpoints.get("KAFKA_BOOTSTRAP_SERVERS"):
service_type = "kafka"
instance = EventSourceListener.get(service_type, raise_if_missing=False)
if instance:
instance.start()
@staticmethod
def process_event_via_listener(service_type: str, event: Any):
"""Process event for the given service type (for reactive mode)"""
instance = EventSourceListener.get(service_type, raise_if_missing=False)
if not instance:
return
def _process(*args):
instance.process_event(event)
# start processing in background
start_worker_thread(_process)
@classmethod
def impl_name(cls) -> str:
return cls.source_type()
@classmethod
def get_base_type(cls) -> Type:
return EventSourceListener
class EventSourceListenerSQS(EventSourceListener):
# SQS listener thread settings
SQS_LISTENER_THREAD: Dict = {}
SQS_POLL_INTERVAL_SEC: float = 1
# Whether to use polling via SQS API (or, alternatively, reactive mode with SQS updates received directly in-memory)
# Advantage of polling is that we can delete messages directly from the queue (via 'ReceiptHandle') after processing
USE_POLLING = True
@staticmethod
def source_type():
return "sqs"
def start(self):
if not self.USE_POLLING:
return
if self.SQS_LISTENER_THREAD:
return
LOG.debug("Starting SQS message polling thread for Lambda API")
self.SQS_LISTENER_THREAD["_thread_"] = thread = FuncThread(self._listener_loop)
thread.start()
def get_matching_event_sources(self) -> List[Dict]:
return get_event_sources(source_arn=r".*:sqs:.*")
def process_event(self, event: Any):
if self.USE_POLLING:
return
# feed message into the first listening lambda (message should only get processed once)
queue_url = event["QueueUrl"]
try:
queue_name = queue_url.rpartition("/")[2]
queue_arn = aws_stack.sqs_queue_arn(queue_name)
sources = get_event_sources(source_arn=queue_arn)
arns = [s.get("FunctionArn") for s in sources]
source = (sources or [None])[0]
if not source:
return False
LOG.debug(
"Found %s source mappings for event from SQS queue %s: %s",
len(arns),
queue_arn,
arns,
)
# TODO: support message BatchSize here, same as for polling mode below
messages = event["Messages"]
self._process_messages_for_event_source(source, messages)
except Exception:
LOG.exception(f"Unable to run Lambda function on SQS messages from queue {queue_url}")
def _listener_loop(self, *args):
while True:
try:
sources = self.get_matching_event_sources()
if not sources:
# Temporarily disable polling if no event sources are configured
# anymore. The loop will get restarted next time a message
# arrives and if an event source is configured.
self.SQS_LISTENER_THREAD.pop("_thread_")
return
unprocessed_messages = {}
for source in sources:
queue_arn = source["EventSourceArn"]
region_name = queue_arn.split(":")[3]
sqs_client = aws_stack.connect_to_service("sqs", region_name=region_name)
batch_size = max(min(source.get("BatchSize", 1), 10), 1)
try:
queue_url = aws_stack.sqs_queue_url_for_arn(queue_arn)
messages = unprocessed_messages.pop(queue_arn, None)
if not messages:
result = sqs_client.receive_message(
QueueUrl=queue_url,
AttributeNames=["All"],
MessageAttributeNames=["All"],
MaxNumberOfMessages=batch_size,
)
messages = result.get("Messages")
if not messages:
continue
res = self._process_messages_for_event_source(source, messages)
if not res:
unprocessed_messages[queue_arn] = messages
except Exception as e:
if "NonExistentQueue" not in str(e):
# TODO: remove event source if queue does no longer exist?
LOG.debug("Unable to poll SQS messages for queue %s: %s", queue_arn, e)
except Exception:
pass
finally:
time.sleep(self.SQS_POLL_INTERVAL_SEC)
def _process_messages_for_event_source(self, source, messages):
lambda_arn = source["FunctionArn"]
queue_arn = source["EventSourceArn"]
region_name = queue_arn.split(":")[3]
queue_url = aws_stack.sqs_queue_url_for_arn(queue_arn)
LOG.debug("Sending event from event source %s to Lambda %s", queue_arn, lambda_arn)
res = self._send_event_to_lambda(
queue_arn,
queue_url,
lambda_arn,
messages,
region=region_name,
)
return res
def _send_event_to_lambda(self, queue_arn, queue_url, lambda_arn, messages, region):
def delete_messages(result, func_arn, event, error=None, dlq_sent=None, **kwargs):
if error and not dlq_sent:
# Skip deleting messages from the queue in case of processing errors AND if
# the message has not yet been sent to a dead letter queue (DLQ).
# We'll pick them up and retry next time they become available on the queue.
return
region_name = queue_arn.split(":")[3]
sqs_client = aws_stack.connect_to_service("sqs", region_name=region_name)
entries = [
{"Id": r["receiptHandle"], "ReceiptHandle": r["receiptHandle"]} for r in records
]
try:
sqs_client.delete_message_batch(QueueUrl=queue_url, Entries=entries)
except Exception as e:
LOG.info(
"Unable to delete Lambda events from SQS queue "
+ "(please check SQS visibility timeout settings): %s - %s" % (entries, e)
)
records = []
for msg in messages:
message_attrs = message_attributes_to_lower(msg.get("MessageAttributes"))
records.append(
{
"body": msg.get("Body", "MessageBody"),
"receiptHandle": msg.get("ReceiptHandle"),
"md5OfBody": msg.get("MD5OfBody") or msg.get("MD5OfMessageBody"),
"eventSourceARN": queue_arn,
"eventSource": lambda_executors.EVENT_SOURCE_SQS,
"awsRegion": region,
"messageId": msg["MessageId"],
"attributes": msg.get("Attributes", {}),
"messageAttributes": message_attrs,
"md5OfMessageAttributes": msg.get("MD5OfMessageAttributes"),
"sqs": True,
}
)
event = {"Records": records}
# TODO implement retries, based on "RedrivePolicy.maxReceiveCount" in the queue settings
res = run_lambda(
func_arn=lambda_arn,
event=event,
context={},
asynchronous=True,
callback=delete_messages,
)
if isinstance(res, InvocationResult):
status_code = getattr(res.result, "status_code", 0)
if status_code >= 400:
return False
return True
def cleanup():
region = LambdaRegion.get()
region.lambdas = {}
region.event_source_mappings = []
LAMBDA_EXECUTOR.cleanup()
def func_arn(function_name, remove_qualifier=True):
parts = function_name.split(":function:")
if remove_qualifier and len(parts) > 1:
function_name = "%s:function:%s" % (parts[0], parts[1].split(":")[0])
return aws_stack.lambda_function_arn(function_name)
def func_qualifier(function_name, qualifier=None):
region = LambdaRegion.get()
arn = aws_stack.lambda_function_arn(function_name)
details = region.lambdas.get(arn)
if not details:
return details
if details.qualifier_exists(qualifier):
return "{}:{}".format(arn, qualifier)
return arn
def check_batch_size_range(source_arn, batch_size=None):
source = source_arn.split(":")[2].lower()
source = "kafka" if "secretsmanager" in source else source
batch_size_entry = BATCH_SIZE_RANGES.get(source)
if not batch_size_entry:
raise ValueError(INVALID_PARAMETER_VALUE_EXCEPTION, "Unsupported event source type")
batch_size = batch_size or batch_size_entry[0]
if batch_size > batch_size_entry[1]:
raise ValueError(
INVALID_PARAMETER_VALUE_EXCEPTION,
"BatchSize {} exceeds the max of {}".format(batch_size, batch_size_entry[1]),
)
return batch_size
def build_mapping_obj(data) -> Dict:
mapping = {}
function_name = data["FunctionName"]
enabled = data.get("Enabled", True)
batch_size = data.get("BatchSize")
mapping["UUID"] = str(uuid.uuid4())
mapping["FunctionArn"] = func_arn(function_name)
mapping["LastProcessingResult"] = "OK"
mapping["StateTransitionReason"] = "User action"
mapping["LastModified"] = format_timestamp_for_event_source_mapping()
mapping["State"] = "Enabled" if enabled in [True, None] else "Disabled"
mapping["ParallelizationFactor"] = data.get("ParallelizationFactor") or 1
mapping["Topics"] = data.get("Topics") or []
if "SelfManagedEventSource" in data:
source_arn = data["SourceAccessConfigurations"][0]["URI"]
mapping["SelfManagedEventSource"] = data["SelfManagedEventSource"]
mapping["SourceAccessConfigurations"] = data["SourceAccessConfigurations"]
else:
source_arn = data["EventSourceArn"]
mapping["EventSourceArn"] = source_arn
mapping["StartingPosition"] = LAMBDA_DEFAULT_STARTING_POSITION
batch_size = check_batch_size_range(source_arn, batch_size)
mapping["BatchSize"] = batch_size
return mapping
def format_timestamp(timestamp=None):
timestamp = timestamp or datetime.utcnow()
return isoformat_milliseconds(timestamp) + "+0000"
def format_timestamp_for_event_source_mapping():
# event source mappings seem to use a different time format (required for Terraform compat.)
return datetime.utcnow().timestamp()
def add_event_source(data):
region = LambdaRegion.get()
mapping = build_mapping_obj(data)
region.event_source_mappings.append(mapping)
EventSourceListener.start_listeners(mapping)
return mapping
def update_event_source(uuid_value, data):
region = LambdaRegion.get()
function_name = data.get("FunctionName") or ""
enabled = data.get("Enabled", True)
for mapping in region.event_source_mappings:
if uuid_value == mapping["UUID"]:
if function_name:
mapping["FunctionArn"] = func_arn(function_name)
batch_size = data.get("BatchSize")
if "SelfManagedEventSource" in mapping:
batch_size = check_batch_size_range(
mapping["SourceAccessConfigurations"][0]["URI"],
batch_size or mapping["BatchSize"],
)
else:
batch_size = check_batch_size_range(
mapping["EventSourceArn"], batch_size or mapping["BatchSize"]
)
mapping["State"] = "Enabled" if enabled in [True, None] else "Disabled"
mapping["LastModified"] = format_timestamp_for_event_source_mapping()
mapping["BatchSize"] = batch_size
if "SourceAccessConfigurations" in (mapping and data):
mapping["SourceAccessConfigurations"] = data["SourceAccessConfigurations"]
return mapping
return {}
def delete_event_source(uuid_value):
region = LambdaRegion.get()
for i, m in enumerate(region.event_source_mappings):
if uuid_value == m["UUID"]:
return region.event_source_mappings.pop(i)
return {}
@synchronized(lock=EXEC_MUTEX)
def use_docker():
global DO_USE_DOCKER
if DO_USE_DOCKER is None:
DO_USE_DOCKER = False
if "docker" in config.LAMBDA_EXECUTOR:
has_docker = DOCKER_CLIENT.has_docker()
if not has_docker:
LOG.warning(
(
"Lambda executor configured as LAMBDA_EXECUTOR=%s but Docker "
"is not accessible. Please make sure to mount the Docker socket "
"/var/run/docker.sock into the container."
),
config.LAMBDA_EXECUTOR,
)
DO_USE_DOCKER = has_docker
return DO_USE_DOCKER
def fix_proxy_path_params(path_params):
proxy_path_param_value = path_params.get("proxy+")
if not proxy_path_param_value:
return
del path_params["proxy+"]
path_params["proxy"] = proxy_path_param_value
def message_attributes_to_lower(message_attrs):
"""Convert message attribute details (first characters) to lower case (e.g., stringValue, dataType)."""
message_attrs = message_attrs or {}
for _, attr in message_attrs.items():
if not isinstance(attr, dict):
continue
for key, value in dict(attr).items():
attr[first_char_to_lower(key)] = attr.pop(key)
return message_attrs
# TODO - refactor to use ApiInvocationContext as input
def process_apigateway_invocation(
func_arn,
path,
payload,
stage,
api_id,
headers=None,
is_base64_encoded=False,
resource_path=None,
method=None,
path_params=None,
query_string_params=None,
stage_variables=None,
request_context=None,
event_context=None,
):
if path_params is None:
path_params = {}
if stage_variables is None:
stage_variables = {}
if request_context is None:
request_context = {}
if event_context is None:
event_context = {}
try:
resource_path = resource_path or path
event = construct_invocation_event(
method, path, headers, payload, query_string_params, is_base64_encoded
)
path_params = dict(path_params)
fix_proxy_path_params(path_params)
event["pathParameters"] = path_params
event["resource"] = resource_path
event["requestContext"] = request_context
if stage_variables:
event["stageVariables"] = stage_variables
LOG.debug(
"Running Lambda function %s from API Gateway invocation: %s %s",
func_arn,
method or "GET",
path,
)
asynchronous = not config.SYNCHRONOUS_API_GATEWAY_EVENTS
inv_result = run_lambda(
func_arn=func_arn,
event=event,
context=event_context,
asynchronous=asynchronous,
)
return inv_result.result
except Exception as e:
LOG.warning(
"Unable to run Lambda function on API Gateway message: %s %s", e, traceback.format_exc()
)
def construct_invocation_event(
method, path, headers, data, query_string_params=None, is_base64_encoded=False
):
query_string_params = query_string_params or parse_request_data(method, path, "")
# AWS canonicalizes header names, converting them to lower-case
headers = canonicalize_headers(headers)
event = {
"path": path,
"headers": dict(headers),
"multiValueHeaders": multi_value_dict_for_list(headers),
"body": data,
"isBase64Encoded": is_base64_encoded,
"httpMethod": method,
"queryStringParameters": query_string_params,
"multiValueQueryStringParameters": multi_value_dict_for_list(query_string_params),
}
return event
def process_sns_notification(
func_arn,
topic_arn,
subscription_arn,
message,
message_id,
message_attributes,
unsubscribe_url,
subject="",
):
event = {
"Records": [
{
"EventSource": "aws:sns",
"EventVersion": "1.0",
"EventSubscriptionArn": subscription_arn,
"Sns": {
"Type": "Notification",
"MessageId": message_id,
"TopicArn": topic_arn,
"Subject": subject,
"Message": message,
"Timestamp": timestamp_millis(),
"SignatureVersion": "1",
# TODO Add a more sophisticated solution with an actual signature
# Hardcoded
"Signature": "EXAMPLEpH+..",
"SigningCertUrl": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-000000000.pem",
"UnsubscribeUrl": unsubscribe_url,
"MessageAttributes": message_attributes,
},
}
]
}
inv_result = run_lambda(
func_arn=func_arn,
event=event,
context={},
asynchronous=not config.SYNCHRONOUS_SNS_EVENTS,
)
return inv_result.result
def process_kinesis_records(records, stream_name):
def chunks(lst, n):
# Yield successive n-sized chunks from lst.
for i in range(0, len(lst), n):
yield lst[i : i + n]
# feed records into listening lambdas
try:
stream_arn = aws_stack.kinesis_stream_arn(stream_name)
sources = get_event_sources(source_arn=stream_arn)
for source in sources:
arn = source["FunctionArn"]
for chunk in chunks(records, source["BatchSize"]):
shard_id = "shardId-000000000000"
event = {
"Records": [
{
"eventID": "{0}:{1}".format(shard_id, rec["sequenceNumber"]),
"eventSourceARN": stream_arn,
"eventSource": "aws:kinesis",
"eventVersion": "1.0",
"eventName": "aws:kinesis:record",
"invokeIdentityArn": "arn:aws:iam::{0}:role/lambda-role".format(
TEST_AWS_ACCOUNT_ID
),
"awsRegion": aws_stack.get_region(),
"kinesis": rec,
}
for rec in chunk
]
}
lock_discriminator = None
if not config.SYNCHRONOUS_KINESIS_EVENTS:
lock_discriminator = f"{stream_arn}/{shard_id}"
lambda_executors.LAMBDA_ASYNC_LOCKS.assure_lock_present(
lock_discriminator, BoundedSemaphore(source["ParallelizationFactor"])
)
run_lambda(
func_arn=arn,
event=event,
context={},
asynchronous=not config.SYNCHRONOUS_KINESIS_EVENTS,
lock_discriminator=lock_discriminator,
)
except Exception as e:
LOG.warning(
"Unable to run Lambda function on Kinesis records: %s %s", e, traceback.format_exc()
)
def get_event_sources(func_name=None, source_arn=None):
result = []
for region, details in LambdaRegion.regions().items():
for m in details.event_source_mappings:
if not func_name or (m["FunctionArn"] in [func_name, func_arn(func_name)]):
if event_source_arn_matches(mapped=m.get("EventSourceArn"), searched=source_arn):
result.append(m)
return result
def get_function_version(arn, version):
region = LambdaRegion.get()
func = region.lambdas.get(arn)
return format_func_details(func, version=version, always_add_version=True)
def publish_new_function_version(arn):
region = LambdaRegion.get()
lambda_function = region.lambdas.get(arn)
versions = lambda_function.versions
max_version_number = lambda_function.max_version()
next_version_number = max_version_number + 1
latest_hash = versions.get(VERSION_LATEST).get("CodeSha256")
max_version = versions.get(str(max_version_number))
max_version_hash = max_version.get("CodeSha256") if max_version else ""
if latest_hash != max_version_hash:
versions[str(next_version_number)] = {
"CodeSize": versions.get(VERSION_LATEST).get("CodeSize"),
"CodeSha256": versions.get(VERSION_LATEST).get("CodeSha256"),
"Function": versions.get(VERSION_LATEST).get("Function"),
"RevisionId": str(uuid.uuid4()),
}
max_version_number = next_version_number
return get_function_version(arn, str(max_version_number))
def do_list_versions(arn):
region = LambdaRegion.get()
versions = [
get_function_version(arn, version) for version in region.lambdas.get(arn).versions.keys()
]
return sorted(versions, key=lambda k: str(k.get("Version")))
def do_update_alias(arn, alias, version, description=None):
region = LambdaRegion.get()
new_alias = {
"AliasArn": arn + ":" + alias,
"FunctionVersion": version,
"Name": alias,
"Description": description or "",
"RevisionId": str(uuid.uuid4()),
}
region.lambdas.get(arn).aliases[alias] = new_alias
return new_alias
def run_lambda(
func_arn,
event,
context=None,
version=None,
suppress_output=False,
asynchronous=False,
callback=None,
lock_discriminator: str = None,
) -> InvocationResult:
if context is None:
context = {}
region_name = func_arn.split(":")[3]
region = LambdaRegion.get(region_name)
if suppress_output:
stdout_ = sys.stdout
stderr_ = sys.stderr
stream = StringIO()
sys.stdout = stream
sys.stderr = stream
try:
func_arn = aws_stack.fix_arn(func_arn)
lambda_function = region.lambdas.get(func_arn)
if not lambda_function:
LOG.debug("Unable to find details for Lambda %s in region %s", func_arn, region_name)
result = not_found_error(msg="The resource specified in the request does not exist.")
return InvocationResult(result)
context = LambdaContext(lambda_function, version, context)
result = LAMBDA_EXECUTOR.execute(
func_arn,
lambda_function,
event,
context=context,
version=version,
asynchronous=asynchronous,
callback=callback,
lock_discriminator=lock_discriminator,
)
return result
except Exception as e:
exc_type, exc_value, exc_traceback = sys.exc_info()
# TODO: wrong mapping
response = {
"errorType": str(exc_type.__name__),
"errorMessage": str(e),
"stackTrace": traceback.format_tb(exc_traceback),
}
LOG.info("Error executing Lambda function %s: %s %s", func_arn, e, traceback.format_exc())
log_output = e.log_output if isinstance(e, lambda_executors.InvocationException) else ""
return InvocationResult(Response(json.dumps(response), status=500), log_output)
finally:
if suppress_output:
sys.stdout = stdout_
sys.stderr = stderr_
def load_source(name, file):
return importlib.machinery.SourceFileLoader(name, file).load_module()
def exec_lambda_code(script, handler_function="handler", lambda_cwd=None, lambda_env=None):
# TODO: The code in this function is generally not thread-safe and potentially insecure
# (e.g., mutating environment variables, and globally loaded modules). Should be redesigned.
def _do_exec_lambda_code():
if lambda_cwd or lambda_env:
if lambda_cwd:
previous_cwd = os.getcwd()
os.chdir(lambda_cwd)
sys.path = [lambda_cwd] + sys.path
if lambda_env:
previous_env = dict(os.environ)
os.environ.update(lambda_env)
# generate lambda file name
lambda_id = "l_%s" % short_uid()
lambda_file = LAMBDA_SCRIPT_PATTERN.replace("*", lambda_id)
save_file(lambda_file, script)
# delete temporary .py and .pyc files on exit
TMP_FILES.append(lambda_file)
TMP_FILES.append("%sc" % lambda_file)
try:
pre_sys_modules_keys = set(sys.modules.keys())
# set default env variables required for most Lambda handlers
env_vars_before = lambda_executors.LambdaExecutorLocal.set_default_env_variables()
try:
handler_module = load_source(lambda_id, lambda_file)
module_vars = handler_module.__dict__
finally:
lambda_executors.LambdaExecutorLocal.reset_default_env_variables(env_vars_before)
# the above import can bring files for the function
# (eg settings.py) into the global namespace. subsequent
# calls can pick up file from another function, causing
# general issues.
post_sys_modules_keys = set(sys.modules.keys())
for key in post_sys_modules_keys:
if key not in pre_sys_modules_keys:
sys.modules.pop(key)
except Exception as e:
LOG.error("Unable to exec: %s %s", script, traceback.format_exc())
raise e
finally:
if lambda_cwd or lambda_env:
if lambda_cwd:
os.chdir(previous_cwd)
sys.path.pop(0)
if lambda_env:
os.environ = previous_env
return module_vars[handler_function]
lock = EXEC_MUTEX if lambda_cwd or lambda_env else empty_context_manager()
with lock:
return _do_exec_lambda_code()
def get_handler_function_from_name(handler_name, runtime=None):
runtime = runtime or LAMBDA_DEFAULT_RUNTIME
if runtime.startswith(tuple(DOTNET_LAMBDA_RUNTIMES)):
return handler_name.split(":")[-1]
return handler_name.split(".")[-1]
def get_java_handler(zip_file_content, main_file, lambda_function=None):
"""Creates a Java handler from an uploaded ZIP or JAR.
:type zip_file_content: bytes
:param zip_file_content: ZIP file bytes.
:type handler: str
:param handler: The lambda handler path.
:type main_file: str
:param main_file: Filepath to the uploaded ZIP or JAR file.
:returns: function or flask.Response
"""
if is_zip_file(zip_file_content):
def execute(event, context):
result = lambda_executors.EXECUTOR_LOCAL.execute_java_lambda(
event, context, main_file=main_file, lambda_function=lambda_function
)
return result
return execute
raise ClientError(
error_response(
"Unable to extract Java Lambda handler - file is not a valid zip/jar file (%s, %s bytes)"
% (main_file, len(zip_file_content or "")),
400,
error_type="ValidationError",
)
)
def set_archive_code(code: Dict, lambda_name: str, zip_file_content: bytes = None) -> Optional[str]:
region = LambdaRegion.get()
# get metadata
lambda_arn = func_arn(lambda_name)
lambda_details = region.lambdas[lambda_arn]
is_local_mount = code.get("S3Bucket") == config.BUCKET_MARKER_LOCAL
if is_local_mount and config.LAMBDA_REMOTE_DOCKER:
msg = 'Please note that Lambda mounts (bucket name "%s") cannot be used with LAMBDA_REMOTE_DOCKER=1'
raise Exception(msg % config.BUCKET_MARKER_LOCAL)
# Stop/remove any containers that this arn uses.
LAMBDA_EXECUTOR.cleanup(lambda_arn)
if is_local_mount:
# Mount or use a local folder lambda executors can reference
# WARNING: this means we're pointing lambda_cwd to a local path in the user's
# file system! We must ensure that there is no data loss (i.e., we must *not* add
# this folder to TMP_FILES or similar).
lambda_details.cwd = code.get("S3Key")
return code["S3Key"]
# get file content
zip_file_content = zip_file_content or get_zip_bytes(code)
if not zip_file_content:
return
# Save the zip file to a temporary file that the lambda executors can reference
code_sha_256 = base64.standard_b64encode(hashlib.sha256(zip_file_content).digest())
latest_version = lambda_details.get_version(VERSION_LATEST)
latest_version["CodeSize"] = len(zip_file_content)
latest_version["CodeSha256"] = code_sha_256.decode("utf-8")
tmp_dir = "%s/zipfile.%s" % (config.dirs.tmp, short_uid())
mkdir(tmp_dir)
tmp_file = "%s/%s" % (tmp_dir, LAMBDA_ZIP_FILE_NAME)
save_file(tmp_file, zip_file_content)
TMP_FILES.append(tmp_dir)
lambda_details.cwd = tmp_dir
return tmp_dir
def set_function_code(lambda_function: LambdaFunction):
def _set_and_configure():
do_set_function_code(lambda_function)
# initialize function code via plugins
for plugin in lambda_executors.LambdaExecutorPlugin.get_plugins():
plugin.init_function_code(lambda_function)
# unzipping can take some time - limit the execution time to avoid client/network timeout issues
run_for_max_seconds(config.LAMBDA_CODE_EXTRACT_TIME, _set_and_configure)
return {"FunctionName": lambda_function.name()}
def store_and_get_lambda_code_archive(
lambda_function: LambdaFunction, zip_file_content: bytes = None
) -> Optional[Tuple[str, str, bytes]]:
"""Store the Lambda code referenced in the LambdaFunction details to disk as a zip file,
and return the Lambda CWD, file name, and zip bytes content. May optionally return None
in case this is a Lambda with the special bucket marker __local__, used for code mounting."""
code_passed = lambda_function.code
is_local_mount = code_passed.get("S3Bucket") == config.BUCKET_MARKER_LOCAL
lambda_cwd = lambda_function.cwd
if code_passed:
lambda_cwd = lambda_cwd or set_archive_code(code_passed, lambda_function.name())
if not zip_file_content and not is_local_mount:
# Save the zip file to a temporary file that the lambda executors can reference
zip_file_content = get_zip_bytes(code_passed)
else:
lambda_details = LambdaRegion.get().lambdas[lambda_function.arn()]
lambda_cwd = lambda_cwd or lambda_details.cwd
if not lambda_cwd:
return
# construct archive name
archive_file = os.path.join(lambda_cwd, LAMBDA_ZIP_FILE_NAME)
if not zip_file_content:
zip_file_content = load_file(archive_file, mode="rb")