-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathzappa.py
1803 lines (1518 loc) · 68.5 KB
/
zappa.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
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 boto3
import botocore
import json
import logging
import os
import random
import requests
import shutil
import string
import subprocess
import tarfile
import tempfile
import time
import zipfile
import troposphere
import troposphere.apigateway
from distutils.dir_util import copy_tree
from botocore.exceptions import ClientError
from lambda_packages import lambda_packages
from tqdm import tqdm
# Zappa imports
from util import copytree, add_event_source, remove_event_source
logging.basicConfig(format='%(levelname)s:%(message)s')
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
##
# Policies And Template Mappings
##
POST_TEMPLATE_MAPPING = """#set($rawPostData = $input.path("$"))
{
"body" : "$util.base64Encode($input.body)",
"headers": {
#foreach($header in $input.params().header.keySet())
"$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end
#end
},
"method": "$context.httpMethod",
"params": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
},
"query": {
#foreach($queryParam in $input.params().querystring.keySet())
"$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end
#end
}
}"""
FORM_ENCODED_TEMPLATE_MAPPING = """
{
"body" : "$util.base64Encode($input.body)",
"headers": {
#foreach($header in $input.params().header.keySet())
"$header": "$util.escapeJavaScript($input.params().header.get($header))" #if($foreach.hasNext),#end
#end
},
"method": "$context.httpMethod",
"params": {
#foreach($param in $input.params().path.keySet())
"$param": "$util.escapeJavaScript($input.params().path.get($param))" #if($foreach.hasNext),#end
#end
},
"query": {
#foreach($queryParam in $input.params().querystring.keySet())
"$queryParam": "$util.escapeJavaScript($input.params().querystring.get($queryParam))" #if($foreach.hasNext),#end
#end
}
}"""
ASSUME_POLICY = """{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "",
"Effect": "Allow",
"Principal": {
"Service": [
"apigateway.amazonaws.com",
"lambda.amazonaws.com",
"events.amazonaws.com"
]
},
"Action": "sts:AssumeRole"
}
]
}"""
ATTACH_POLICY = """{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"logs:*"
],
"Resource": "arn:aws:logs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"lambda:InvokeFunction"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"ec2:AttachNetworkInterface",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeInstances",
"ec2:DescribeNetworkInterfaces",
"ec2:DetachNetworkInterface",
"ec2:ModifyNetworkInterfaceAttribute",
"ec2:ResetNetworkInterfaceAttribute"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": "arn:aws:s3:::*"
},
{
"Effect": "Allow",
"Action": [
"sns:*"
],
"Resource": "arn:aws:sns:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"sqs:*"
],
"Resource": "arn:aws:sqs:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"dynamodb:*"
],
"Resource": "arn:aws:dynamodb:*:*:*"
},
{
"Effect": "Allow",
"Action": [
"route53:*"
],
"Resource": "*"
}
]
}"""
RESPONSE_TEMPLATE = """#set($inputRoot = $input.path('$'))\n$inputRoot.Content"""
ERROR_RESPONSE_TEMPLATE = """#set($_body = $util.parseJson($input.path('$.errorMessage'))['content'])\n$util.base64Decode($_body)"""
REDIRECT_RESPONSE_TEMPLATE = ""
API_GATEWAY_REGIONS = ['us-east-1', 'us-west-2', 'eu-west-1', 'eu-central-1', 'ap-northeast-1', 'ap-southeast-2']
LAMBDA_REGIONS = ['us-east-1', 'us-west-2', 'eu-west-1', 'eu-central-1', 'ap-northeast-1', 'ap-southeast-2']
ZIP_EXCLUDES = [
'*.exe', '*.DS_Store', '*.Python', '*.git', '.git/*', '*.zip', '*.tar.gz',
'*.hg', '*.egg-info', 'pip', 'docutils*', 'setuputils*'
]
##
# Classes
##
class Zappa(object):
"""
Zappa!
Makes it easy to run Python web applications on AWS Lambda/API Gateway.
"""
##
# Configurables
##
http_methods = [
'ANY'
]
parameter_depth = 8
integration_response_codes = [200, 201, 301, 400, 401, 403, 404, 405, 500]
integration_content_types = [
'text/html',
]
method_response_codes = [200, 201, 301, 400, 401, 403, 404, 405, 500]
method_content_types = [
'text/html',
]
method_header_types = [
'Content-Type',
'Location',
'Status',
'X-Frame-Options',
'Set-Cookie'
]
role_name = "ZappaLambdaExecution"
assume_policy = ASSUME_POLICY
attach_policy = ATTACH_POLICY
aws_region = 'us-east-1'
cloudwatch_log_levels = ['OFF', 'ERROR', 'INFO']
##
# Credentials
##
boto_session = None
credentials_arn = None
def __init__(self, boto_session=None, profile_name=None, aws_region=aws_region, load_credentials=True):
self.aws_region = aws_region
# Some common invokations, such as DB migrations,
# can take longer than the default.
# Note that this is set to 300s, but if connected to
# APIGW, Lambda will max out at 30s.
# Related: https://github.com/Miserlou/Zappa/issues/205
long_config_dict = {
'region_name': aws_region,
'connect_timeout': 5,
'read_timeout': 300
}
long_config = botocore.client.Config(**long_config_dict)
if load_credentials:
self.load_credentials(boto_session, profile_name)
self.s3_client = self.boto_session.client('s3')
self.lambda_client = self.boto_session.client('lambda', config=long_config)
self.events_client = self.boto_session.client('events')
self.apigateway_client = self.boto_session.client('apigateway')
self.logs_client = self.boto_session.client('logs')
self.iam_client = self.boto_session.client('iam')
self.iam = self.boto_session.resource('iam')
self.cloudwatch = self.boto_session.client('cloudwatch')
self.route53 = self.boto_session.client('route53')
self.cf_client = self.boto_session.client('cloudformation')
self.cf_template = troposphere.Template()
self.cf_api_resources = []
self.cf_parameters = {}
def cache_param(self, value):
'''Returns a troposphere Ref to a value cached as a parameter.'''
if value not in self.cf_parameters:
keyname = chr(ord('A') + len(self.cf_parameters))
param = self.cf_template.add_parameter(troposphere.Parameter(
keyname, Type="String", Default=value
))
self.cf_parameters[value] = param
return troposphere.Ref(self.cf_parameters[value])
##
# Packaging
##
def create_lambda_zip(self, prefix='lambda_package', handler_file=None,
minify=True, exclude=None, use_precompiled_packages=True, include=None, venv=None):
"""
Create a Lambda-ready zip file of the current virtualenvironment and working directory.
Returns path to that file.
"""
import pip
print("Packaging project as zip...")
if not venv:
if 'VIRTUAL_ENV' in os.environ:
venv = os.environ['VIRTUAL_ENV']
elif os.path.exists('.python-version'): # pragma: no cover
logger.debug("Pyenv's local virtualenv detected.")
try:
subprocess.check_output('pyenv', stderr=subprocess.STDOUT)
except OSError:
print("This directory seems to have pyenv's local venv"
"but pyenv executable was not found.")
with open('.python-version', 'r') as f:
env_name = f.read()[:-1]
logger.debug('env name = {}'.format(env_name))
bin_path = subprocess.check_output(['pyenv', 'which', 'python']).decode('utf-8')
venv = bin_path[:bin_path.rfind(env_name)] + env_name
logger.debug('env path = {}'.format(venv))
else: # pragma: no cover
print("Zappa requires an active virtual environment.")
quit()
cwd = os.getcwd()
zip_fname = prefix + '-' + str(int(time.time())) + '.zip'
zip_path = os.path.join(cwd, zip_fname)
# Files that should be excluded from the zip
if exclude is None:
exclude = list()
# Exclude the zip itself
exclude.append(zip_path)
def splitpath(path):
parts = []
(path, tail) = os.path.split(path)
while path and tail:
parts.append(tail)
(path, tail) = os.path.split(path)
parts.append(os.path.join(path, tail))
return map(os.path.normpath, parts)[::-1]
split_venv = splitpath(venv)
split_cwd = splitpath(cwd)
# Ideally this should be avoided automatically,
# but this serves as an okay stop-gap measure.
if split_venv[-1] == split_cwd[-1]: # pragma: no cover
print(
"Warning! Your project and virtualenv have the same name! You may want "
"to re-create your venv with a new name, or explicitly define a "
"'project_name', as this may cause errors."
)
# First, do the project..
temp_project_path = os.path.join(tempfile.gettempdir(), str(int(time.time())))
if minify:
excludes = ZIP_EXCLUDES + exclude + [split_venv[-1]]
copytree(cwd, temp_project_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes))
else:
copytree(cwd, temp_project_path, symlinks=False)
# Then, do the site-packages..
temp_package_path = os.path.join(tempfile.gettempdir(), str(int(time.time() + 1)))
if os.sys.platform == 'win32':
site_packages = os.path.join(venv, 'Lib', 'site-packages')
else:
site_packages = os.path.join(venv, 'lib', 'python2.7', 'site-packages')
if minify:
excludes = ZIP_EXCLUDES + exclude
copytree(site_packages, temp_package_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes))
else:
copytree(site_packages, temp_package_path, symlinks=False)
# We may have 64-bin specific packages too.
site_packages_64 = os.path.join(venv, 'lib64', 'python2.7', 'site-packages')
if os.path.exists(site_packages_64):
if minify:
excludes = ZIP_EXCLUDES + exclude
copytree(site_packages_64, temp_package_path, symlinks=False, ignore=shutil.ignore_patterns(*excludes))
else:
copytree(site_packages_64, temp_package_path, symlinks=False)
copy_tree(temp_package_path, temp_project_path, update=True)
# Then the pre-compiled packages..
if use_precompiled_packages:
installed_packages_name_set = {package.project_name.lower() for package in
pip.get_installed_distributions()}
for name, details in lambda_packages.items():
if name.lower() in installed_packages_name_set:
tar = tarfile.open(details['path'], mode="r:gz")
for member in tar.getmembers():
# If we can, trash the local version.
if member.isdir():
shutil.rmtree(os.path.join(temp_project_path, member.name), ignore_errors=True)
continue
tar.extract(member, temp_project_path)
# If a handler_file is supplied, copy that to the root of the package,
# because that's where AWS Lambda looks for it. It can't be inside a package.
if handler_file:
filename = handler_file.split(os.sep)[-1]
shutil.copy(handler_file, os.path.join(temp_project_path, filename))
# Then zip it all up..
try:
# import zlib
compression_method = zipfile.ZIP_DEFLATED
except ImportError: # pragma: no cover
compression_method = zipfile.ZIP_STORED
zipf = zipfile.ZipFile(zip_path, 'w', compression_method)
for root, dirs, files in os.walk(temp_project_path):
for filename in files:
# If there is a .pyc file in this package,
# we can skip the python source code as we'll just
# use the compiled bytecode anyway..
if filename[-3:] == '.py':
abs_filname = os.path.join(root, filename)
abs_pyc_filename = abs_filname + 'c'
if os.path.isfile(abs_pyc_filename):
# but only if the pyc is older than the py,
# otherwise we'll deploy outdated code!
py_time = os.stat(abs_filname).st_mtime
pyc_time = os.stat(abs_pyc_filename).st_mtime
if pyc_time > py_time:
continue
zipf.write(os.path.join(root, filename), os.path.join(root.replace(temp_project_path, ''), filename))
if '__init__.py' not in files:
tmp_init = os.path.join(temp_project_path, '__init__.py')
open(tmp_init, 'a').close()
zipf.write(tmp_init, os.path.join(root.replace(temp_project_path, ''), os.path.join(root.replace(temp_project_path, ''), '__init__.py')))
# And, we're done!
zipf.close()
# Trash the temp directory
shutil.rmtree(temp_project_path)
shutil.rmtree(temp_package_path)
# Warn if this is too large for Lambda.
file_stats = os.stat(zip_path)
if file_stats.st_size > 52428800: # pragma: no cover
print("\n\nWarning: Application zip package is likely to be too large for AWS Lambda.\n\n")
return zip_fname
##
# S3
##
def upload_to_s3(self, source_path, bucket_name):
r"""
Given a file, upload it to S3.
Credentials should be stored in environment variables or ~/.aws/credentials (%USERPROFILE%\.aws\credentials on Windows).
Returns True on success, false on failure.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError:
# This is really stupid S3 quirk. Technically, us-east-1 one has no S3,
# it's actually "US Standard", or something.
# More here: https://github.com/boto/boto3/issues/125
if self.aws_region == 'us-east-1':
self.s3_client.create_bucket(
Bucket=bucket_name,
)
else:
self.s3_client.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={'LocationConstraint': self.aws_region},
)
if not os.path.isfile(source_path) or os.stat(source_path).st_size == 0:
print("Problem with source file {}".format(source_path))
return False
dest_path = os.path.split(source_path)[1]
try:
source_size = os.stat(source_path).st_size
print("Uploading {0} ({1})...".format(dest_path, self.human_size(source_size)))
progress = tqdm(total=float(os.path.getsize(source_path)), unit_scale=True, unit='B')
# Attempt to upload to S3 using the S3 meta client with the progress bar.
# If we're unable to do that, try one more time using a session client,
# which cannot use the progress bar.
# Related: https://github.com/boto/boto3/issues/611
try:
self.s3_client.upload_file(
source_path, bucket_name, dest_path,
Callback=progress.update
)
except Exception as e: # pragma: no cover
self.s3_client.upload_file(source_path, bucket_name, dest_path)
progress.close()
except (KeyboardInterrupt, SystemExit): # pragma: no cover
raise
except Exception as e: # pragma: no cover
print(e)
return False
return True
def remove_from_s3(self, file_name, bucket_name):
"""
Given a file name and a bucket, remove it from S3.
There's no reason to keep the file hosted on S3 once its been made into a Lambda function, so we can delete it from S3.
Returns True on success, False on failure.
"""
try:
self.s3_client.head_bucket(Bucket=bucket_name)
except botocore.exceptions.ClientError as e: # pragma: no cover
# If a client error is thrown, then check that it was a 404 error.
# If it was a 404 error, then the bucket does not exist.
error_code = int(e.response['Error']['Code'])
if error_code == 404:
return False
try:
self.s3_client.delete_object(Bucket=bucket_name, Key=file_name)
return True
except botocore.exceptions.ClientError: # pragma: no cover
return False
##
# Lambda
##
def create_lambda_function(self, bucket, s3_key, function_name, handler, description="Zappa Deployment", timeout=30, memory_size=512, publish=True, vpc_config=None):
"""
Given a bucket and key of a valid Lambda-zip, a function name and a handler, register that Lambda function.
"""
if not vpc_config:
vpc_config = {}
if not self.credentials_arn:
self.get_credentials_arn()
response = self.lambda_client.create_function(
FunctionName=function_name,
Runtime='python2.7',
Role=self.credentials_arn,
Handler=handler,
Code={
'S3Bucket': bucket,
'S3Key': s3_key,
},
Description=description,
Timeout=timeout,
MemorySize=memory_size,
Publish=publish,
VpcConfig=vpc_config
)
return response['FunctionArn']
def update_lambda_function(self, bucket, s3_key, function_name, publish=True):
"""
Given a bucket and key of a valid Lambda-zip, a function name and a handler, update that Lambda function's code.
"""
print("Updating Lambda function code..")
response = self.lambda_client.update_function_code(
FunctionName=function_name,
S3Bucket=bucket,
S3Key=s3_key,
Publish=publish
)
return response['FunctionArn']
def update_lambda_configuration(self, lambda_arn, function_name, handler, description="Zappa Deployment", timeout=30, memory_size=512, publish=True, vpc_config=None):
"""
Given an existing function ARN, update the configuration variables.
"""
print("Updating Lambda function configuration..")
if not vpc_config:
vpc_config = {}
if not self.credentials_arn:
self.get_credentials_arn()
response = self.lambda_client.update_function_configuration(
FunctionName=function_name,
Runtime='python2.7',
Role=self.credentials_arn,
Handler=handler,
Description=description,
Timeout=timeout,
MemorySize=memory_size,
VpcConfig=vpc_config
)
return response['FunctionArn']
def invoke_lambda_function(self, function_name, payload, invocation_type='Event', log_type='Tail', client_context=None, qualifier=None):
"""
Directly invoke a named Lambda function with a payload.
Returns the response.
"""
return self.lambda_client.invoke(
FunctionName=function_name,
InvocationType=invocation_type,
LogType=log_type,
Payload=payload
)
def rollback_lambda_function_version(self, function_name, versions_back=1, publish=True):
"""
Rollback the lambda function code 'versions_back' number of revisions.
Returns the Function ARN.
"""
response = self.lambda_client.list_versions_by_function(FunctionName=function_name)
# Take into account $LATEST
if len(response['Versions']) < versions_back + 1:
print("We do not have {} revisions. Aborting".format(str(versions_back)))
return False
revisions = [int(revision['Version']) for revision in response['Versions'] if revision['Version'] != '$LATEST']
revisions.sort(reverse=True)
response = self.lambda_client.get_function(FunctionName='function:{}:{}'.format(function_name, revisions[versions_back]))
response = requests.get(response['Code']['Location'])
if response.status_code != 200:
print("Failed to get version {} of {} code".format(versions_back, function_name))
return False
response = self.lambda_client.update_function_code(FunctionName=function_name, ZipFile=response.content, Publish=publish) # pragma: no cover
return response['FunctionArn']
def get_lambda_function_versions(self, function_name):
"""
Simply returns the versions available for a Lambda function, given a function name.
"""
try:
response = self.lambda_client.list_versions_by_function(FunctionName=function_name)
return response.get('Versions', [])
except Exception:
return []
def delete_lambda_function(self, function_name):
"""
Given a function name, delete it from AWS Lambda.
Returns the response.
"""
print("Deleting Lambda function..")
return self.lambda_client.delete_function(
FunctionName=function_name,
)
##
# API Gateway
##
def create_api_gateway_routes(self, lambda_arn, api_name=None, api_key_required=False,
integration_content_type_aliases=None, authorization_type='NONE', authorizer=None):
"""
Create the API Gateway for this Zappa deployment.
Returns the new RestAPI CF resource.
"""
restapi = troposphere.apigateway.RestApi('Api')
restapi.Name = api_name or lambda_arn.split(':')[-1]
restapi.Description = 'Created automatically by Zappa.'
self.cf_template.add_resource(restapi)
root_id = troposphere.GetAtt(restapi, 'RootResourceId')
invocations_uri = 'arn:aws:apigateway:' + self.boto_session.region_name + ':lambda:path/2015-03-31/functions/' + lambda_arn + '/invocations'
##
# The Resources
##
authorizer_resource = None
if authorizer:
authorizer_lambda_arn = authorizer.get('arn', lambda_arn)
lambda_uri = 'arn:aws:apigateway:' + self.boto_session.region_name + ':lambda:path/2015-03-31/functions/' + authorizer_lambda_arn + '/invocations'
authorizer_resource = self.create_authorizer(restapi,
lambda_uri,
"method.request.header." + authorizer.get('token_header', 'Authorization'),
authorizer.get('result_ttl', 300),
authorizer.get('validation_expression', None))
self.create_and_setup_methods(restapi, root_id, api_key_required, invocations_uri,
integration_content_type_aliases, authorization_type, authorizer_resource, 0)
resource = troposphere.apigateway.Resource('ResourceAnyPathSlashed')
self.cf_api_resources.append(resource.title)
resource.RestApiId = troposphere.Ref(restapi)
resource.ParentId = root_id
resource.PathPart = "{proxy+}"
self.cf_template.add_resource(resource)
self.create_and_setup_methods(restapi, resource, api_key_required, invocations_uri,
integration_content_type_aliases, authorization_type, authorizer_resource, 1) # pragma: no cover
return restapi
def create_authorizer(self, restapi, uri, identity_source, authorizer_result_ttl, identity_validation_expression):
"""
Create Authorizer for API gateway
"""
if not self.credentials_arn:
self.get_credentials_arn()
authorizer_resource = troposphere.apigateway.Authorizer("Authorizer")
authorizer_resource.RestApiId = troposphere.Ref(restapi)
authorizer_resource.Name = "ZappaAuthorizer"
authorizer_resource.Type = 'TOKEN'
authorizer_resource.AuthorizerResultTtlInSeconds = authorizer_result_ttl
authorizer_resource.AuthorizerUri = uri
authorizer_resource.IdentitySource = identity_source
authorizer_resource.AuthorizerCredentials = self.credentials_arn
if identity_validation_expression:
authorizer_resource.IdentityValidationExpression = identity_validation_expression
self.cf_api_resources.append(authorizer_resource.title)
self.cf_template.add_resource(authorizer_resource)
return authorizer_resource
def create_and_setup_methods(self, restapi, resource, api_key_required, uri,
integration_content_type_aliases, authorization_type, authorizer_resource, depth):
"""
Set up the methods, integration responses and method responses for a given API Gateway resource.
"""
for method_name in self.http_methods:
method = troposphere.apigateway.Method(method_name + str(depth))
method.RestApiId = troposphere.Ref(restapi)
if type(resource) is troposphere.apigateway.Resource:
method.ResourceId = troposphere.Ref(resource)
else:
method.ResourceId = resource
method.HttpMethod = method_name.upper()
method.AuthorizationType = authorization_type
if authorizer_resource:
method.AuthorizerId = troposphere.Ref(authorizer_resource)
method.ApiKeyRequired = api_key_required
method.MethodResponses = []
self.cf_template.add_resource(method)
self.cf_api_resources.append(method.title)
# content_mapping_templates = {
# 'application/json': self.cache_param(POST_TEMPLATE_MAPPING),
# 'application/x-www-form-urlencoded': self.cache_param(POST_TEMPLATE_MAPPING),
# 'multipart/form-data': self.cache_param(FORM_ENCODED_TEMPLATE_MAPPING)
# }
# if integration_content_type_aliases:
# for content_type in content_mapping_templates.keys():
# aliases = integration_content_type_aliases.get(content_type, [])
# for alias in aliases:
# content_mapping_templates[alias] = self.cache_param(content_mapping_templates[content_type])
if not self.credentials_arn:
self.get_credentials_arn()
credentials = self.credentials_arn # This must be a Role ARN
integration = troposphere.apigateway.Integration()
integration.CacheKeyParameters = []
integration.CacheNamespace = 'none'
integration.Credentials = credentials
integration.IntegrationHttpMethod = 'POST'
integration.IntegrationResponses = []
integration.PassthroughBehavior = 'NEVER'
# integration.RequestParameters = {}
# integration.RequestTemplates = content_mapping_templates
integration.Type = 'AWS_PROXY'
integration.Uri = uri
method.Integration = integration
##
# Method Response
##
# for response_code in self.method_response_codes:
# status_code = str(response_code)
# response_parameters = {"method.response.header." + header_type: False for header_type in self.method_header_types}
# response_models = {content_type: 'Empty' for content_type in self.method_content_types}
# response = troposphere.apigateway.MethodResponse()
# response.ResponseModels = response_models
# response.ResponseParameters = response_parameters
# response.StatusCode = status_code
# method.MethodResponses.append(response)
##
# Integration Response
##
# for response in self.integration_response_codes:
# status_code = str(response)
# response_parameters = {
# "method.response.header." + header_type: self.cache_param("integration.response.body." + header_type)
# for header_type in self.method_header_types}
# # Error code matching RegEx
# # Thanks to @KevinHornschemeier and @jayway
# # for the discussion on this.
# if status_code == '200':
# response_templates = {content_type: self.cache_param(RESPONSE_TEMPLATE) for content_type in self.integration_content_types}
# elif status_code in ['301', '302']:
# response_templates = {content_type: REDIRECT_RESPONSE_TEMPLATE for content_type in self.integration_content_types}
# response_parameters["method.response.header.Location"] = self.cache_param("integration.response.body.errorMessage")
# else:
# response_templates = {content_type: self.cache_param(ERROR_RESPONSE_TEMPLATE) for content_type in self.integration_content_types}
# integration_response = troposphere.apigateway.IntegrationResponse()
# integration_response.ResponseParameters = response_parameters
# integration_response.ResponseTemplates = response_templates
# integration_response.SelectionPattern = self.selection_pattern(status_code)
# integration_response.StatusCode = status_code
# integration.IntegrationResponses.append(integration_response)
def deploy_api_gateway(self, api_id, stage_name, stage_description="", description="", cache_cluster_enabled=False, cache_cluster_size='0.5', variables=None,
cloudwatch_log_level='OFF', cloudwatch_data_trace=False, cloudwatch_metrics_enabled=False):
"""
Deploy the API Gateway!
Return the deployed API URL.
"""
print("Deploying API Gateway..")
self.apigateway_client.create_deployment(
restApiId=api_id,
stageName=stage_name,
stageDescription=stage_description,
description=description,
cacheClusterEnabled=cache_cluster_enabled,
cacheClusterSize=cache_cluster_size,
variables=variables or {}
)
if cloudwatch_log_level not in self.cloudwatch_log_levels:
cloudwatch_log_level = 'OFF'
self.apigateway_client.update_stage(
restApiId=api_id,
stageName=stage_name,
patchOperations=[
self.get_patch_op('logging/loglevel', cloudwatch_log_level),
self.get_patch_op('logging/dataTrace', cloudwatch_data_trace),
self.get_patch_op('metrics/enabled', cloudwatch_metrics_enabled),
]
)
return "https://{}.execute-api.{}.amazonaws.com/{}".format(api_id, self.boto_session.region_name, stage_name)
def get_api_keys(self, api_id, stage_name):
"""
Generator that allows to iterate per API keys associated to an api_id and a stage_name.
"""
response = self.apigateway_client.get_api_keys(limit=500)
stage_key = '{}/{}'.format(api_id, stage_name)
for api_key in response.get('items'):
if stage_key in api_key.get('stageKeys'):
yield api_key.get('id')
def create_api_key(self, api_id, stage_name):
"""
Create new API key and link it with an api_id and a stage_name
"""
response = self.apigateway_client.create_api_key(
name='{}_{}'.format(stage_name, api_id),
description='Api Key for {}'.format(api_id),
enabled=True,
stageKeys=[
{
'restApiId': '{}'.format(api_id),
'stageName': '{}'.format(stage_name)
},
]
)
print('Created a new x-api-key: {}'.format(response['id']))
def remove_api_key(self, api_id, stage_name):
"""
Remove a generated API key for api_id and stage_name
"""
response = self.apigateway_client.get_api_keys(
limit=1,
nameQuery='{}_{}'.format(stage_name, api_id)
)
for api_key in response.get('items'):
self.apigateway_client.delete_api_key(
apiKey="{}".format(api_key['id'])
)
def add_api_stage_to_api_key(self, api_key, api_id, stage_name):
"""
Add api stage to Api key
"""
self.apigateway_client.update_api_key(
apiKey=api_key,
patchOperations=[
{
'op': 'add',
'path': '/stages',
'value': '{}/{}'.format(api_id, stage_name)
}
]
)
def get_patch_op(self, keypath, value, op='replace'):
"""
Return an object that describes a change of configuration on the given staging.
Setting will be applied on all available HTTP methods.
"""
if isinstance(value, bool):
value = str(value).lower()
return {'op': op, 'path': '/*/*/{}'.format(keypath), 'value': value}
def get_rest_apis(self, project_name):
"""
Generator that allows to iterate per every available apis.
"""
all_apis = self.apigateway_client.get_rest_apis(
limit=500
)
for api in all_apis['items']:
if api['name'] != project_name:
continue
yield api
def undeploy_api_gateway(self, lambda_name, domain_name=None):
"""
Delete a deployed REST API Gateway.
"""
print("Deleting API Gateway..")
api_id = self.get_api_id(lambda_name)
if domain_name:
# XXX - Remove Route53 smartly here?
# XXX - This doesn't raise, but doesn't work either.
try:
self.apigateway_client.delete_base_path_mapping(
domainName=domain_name,
basePath='(none)'
)
except Exception as e:
# We may not have actually set up the domain.
pass
was_deleted = self.delete_stack(lambda_name, wait=True)
if not was_deleted:
# try erasing it with the older method
for api in self.get_rest_apis(lambda_name):
self.apigateway_client.delete_rest_api(
restApiId=api['id']
)
def update_stage_config(self, project_name, stage_name, cloudwatch_log_level, cloudwatch_data_trace,
cloudwatch_metrics_enabled):
"""
Update CloudWatch metrics configuration.
"""
if cloudwatch_log_level not in self.cloudwatch_log_levels:
cloudwatch_log_level = 'OFF'
for api in self.get_rest_apis(project_name):
self.apigateway_client.update_stage(
restApiId=api['id'],
stageName=stage_name,
patchOperations=[
self.get_patch_op('logging/loglevel', cloudwatch_log_level),
self.get_patch_op('logging/dataTrace', cloudwatch_data_trace),
self.get_patch_op('metrics/enabled', cloudwatch_metrics_enabled),
]
)
def delete_stack(self, name, wait=False):
"""
Delete the CF stack managed by Zappa.
"""
try:
stack = self.cf_client.describe_stacks(StackName=name)['Stacks'][0]
except: # pragma: no cover