-
Notifications
You must be signed in to change notification settings - Fork 363
/
core.py
3604 lines (3224 loc) · 133 KB
/
core.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
"""
Zappa core library. You may also want to look at `cli.py` and `util.py`.
"""
##
# Imports
##
import getpass
import glob
import hashlib
import json
import logging
import os
import random
import re
import shutil
import string
import subprocess
import tarfile
import tempfile
import time
import uuid
import zipfile
from builtins import bytes, int
from distutils.dir_util import copy_tree
from io import open
import boto3
import botocore
import requests
import troposphere
import troposphere.apigateway
from botocore.exceptions import ClientError
from setuptools import find_packages
from tqdm import tqdm
from .utilities import (
add_event_source,
conflicts_with_a_neighbouring_module,
contains_python_files_or_subdirs,
copytree,
get_topic_name,
get_venv_from_python_version,
human_size,
remove_event_source,
)
##
# Logging Config
##
logging.basicConfig(format="%(levelname)s:%(message)s")
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
##
# Policies And Template Mappings
##
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": [
"xray:PutTraceSegments",
"xray:PutTelemetryRecords"
],
"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": [
"kinesis:*"
],
"Resource": "arn:aws:kinesis:*:*:*"
},
{
"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": "*"
}
]
}"""
# Latest list: https://docs.aws.amazon.com/general/latest/gr/rande.html#apigateway_region
API_GATEWAY_REGIONS = [
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
"eu-central-1",
"eu-north-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"eu-north-1",
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
"ap-southeast-1",
"ap-southeast-2",
"ap-east-1",
"ap-south-1",
"ca-central-1",
"cn-north-1",
"cn-northwest-1",
"sa-east-1",
"us-gov-east-1",
"us-gov-west-1",
]
# Latest list: https://docs.aws.amazon.com/general/latest/gr/rande.html#lambda_region
LAMBDA_REGIONS = [
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
"eu-central-1",
"eu-north-1",
"eu-west-1",
"eu-west-2",
"eu-west-3",
"eu-north-1",
"ap-northeast-1",
"ap-northeast-2",
"ap-northeast-3",
"ap-southeast-1",
"ap-southeast-2",
"ap-east-1",
"ap-south-1",
"ca-central-1",
"cn-north-1",
"cn-northwest-1",
"sa-east-1",
"us-gov-east-1",
"us-gov-west-1",
]
# We never need to include these.
# Related: https://github.com/Miserlou/Zappa/pull/56
# Related: https://github.com/Miserlou/Zappa/pull/581
ZIP_EXCLUDES = [
"*.exe",
"*.DS_Store",
"*.Python",
"*.git",
".git/*",
"*.zip",
"*.tar.gz",
"*.hg",
"pip",
"docutils*",
"setuputils*",
"__pycache__/*",
]
# When using ALB as an event source for Lambdas, we need to create an alias
# to ensure that, on zappa update, the ALB doesn't lose permissions to access
# the Lambda.
# See: https://github.com/Miserlou/Zappa/pull/1730
ALB_LAMBDA_ALIAS = "current-alb-version"
##
# Classes
##
class Zappa:
"""
Zappa!
Makes it easy to run Python web applications on AWS Lambda/API Gateway.
"""
##
# Configurables
##
http_methods = ["ANY"]
role_name = "ZappaLambdaExecution"
extra_permissions = None
assume_policy = ASSUME_POLICY
attach_policy = ATTACH_POLICY
apigateway_policy = None
cloudwatch_log_levels = ["OFF", "ERROR", "INFO"]
xray_tracing = False
##
# Credentials
##
boto_session = None
credentials_arn = None
def __init__(
self,
boto_session=None,
profile_name=None,
aws_region=None,
load_credentials=True,
desired_role_name=None,
desired_role_arn=None,
runtime="python3.6", # Detected at runtime in CLI
tags=(),
endpoint_urls={},
xray_tracing=False,
):
"""
Instantiate this new Zappa instance, loading any custom credentials if necessary.
"""
# Set aws_region to None to use the system's region instead
if aws_region is None:
# https://github.com/Miserlou/Zappa/issues/413
self.aws_region = boto3.Session().region_name
logger.debug("Set region from boto: %s", self.aws_region)
else:
self.aws_region = aws_region
if desired_role_name:
self.role_name = desired_role_name
if desired_role_arn:
self.credentials_arn = desired_role_arn
self.runtime = runtime
if self.runtime == "python3.6":
self.manylinux_suffix_start = "cp36m"
elif self.runtime == "python3.7":
self.manylinux_suffix_start = "cp37m"
else:
# The 'm' has been dropped in python 3.8+ since builds with and without pymalloc are ABI compatible
# See https://github.com/pypa/manylinux for a more detailed explanation
self.manylinux_suffix_start = "cp38"
# AWS Lambda supports manylinux1/2010 and manylinux2014
manylinux_suffixes = ("2014", "2010", "1")
self.manylinux_wheel_file_match = re.compile(
f'^.*{self.manylinux_suffix_start}-manylinux({"|".join(manylinux_suffixes)})_x86_64.whl$'
)
self.manylinux_wheel_abi3_file_match = re.compile(
f'^.*cp3.-abi3-manylinux({"|".join(manylinux_suffixes)})_x86_64.whl$'
)
self.endpoint_urls = endpoint_urls
self.xray_tracing = xray_tracing
# Some common invocations, 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)
# Initialize clients
self.s3_client = self.boto_client("s3")
self.lambda_client = self.boto_client("lambda", config=long_config)
self.elbv2_client = self.boto_client("elbv2")
self.events_client = self.boto_client("events")
self.apigateway_client = self.boto_client("apigateway")
# AWS ACM certificates need to be created from us-east-1 to be used by API gateway
east_config = botocore.client.Config(region_name="us-east-1")
self.acm_client = self.boto_client("acm", config=east_config)
self.logs_client = self.boto_client("logs")
self.iam_client = self.boto_client("iam")
self.iam = self.boto_resource("iam")
self.cloudwatch = self.boto_client("cloudwatch")
self.route53 = self.boto_client("route53")
self.sns_client = self.boto_client("sns")
self.cf_client = self.boto_client("cloudformation")
self.dynamodb_client = self.boto_client("dynamodb")
self.cognito_client = self.boto_client("cognito-idp")
self.sts_client = self.boto_client("sts")
self.tags = tags
self.cf_template = troposphere.Template()
self.cf_api_resources = []
self.cf_parameters = {}
def configure_boto_session_method_kwargs(self, service, kw):
"""Allow for custom endpoint urls for non-AWS (testing and bootleg cloud) deployments"""
if service in self.endpoint_urls and not "endpoint_url" in kw:
kw["endpoint_url"] = self.endpoint_urls[service]
return kw
def boto_client(self, service, *args, **kwargs):
"""A wrapper to apply configuration options to boto clients"""
return self.boto_session.client(
service, *args, **self.configure_boto_session_method_kwargs(service, kwargs)
)
def boto_resource(self, service, *args, **kwargs):
"""A wrapper to apply configuration options to boto resources"""
return self.boto_session.resource(
service, *args, **self.configure_boto_session_method_kwargs(service, kwargs)
)
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, tags=self.tags
)
)
self.cf_parameters[value] = param
return troposphere.Ref(self.cf_parameters[value])
##
# Packaging
##
def copy_editable_packages(self, egg_links, temp_package_path):
""" """
for egg_link in egg_links:
with open(egg_link, "rb") as df:
egg_path = df.read().decode("utf-8").splitlines()[0].strip()
pkgs = set(
[
x.split(".")[0]
for x in find_packages(egg_path, exclude=["test", "tests"])
]
)
for pkg in pkgs:
copytree(
os.path.join(egg_path, pkg),
os.path.join(temp_package_path, pkg),
metadata=False,
symlinks=False,
)
if temp_package_path:
# now remove any egg-links as they will cause issues if they still exist
for link in glob.glob(os.path.join(temp_package_path, "*.egg-link")):
os.remove(link)
def get_deps_list(self, pkg_name, installed_distros=None):
"""
For a given package, returns a list of required packages. Recursive.
"""
# https://github.com/Miserlou/Zappa/issues/1478. Using `pkg_resources`
# instead of `pip` is the recommended approach. The usage is nearly
# identical.
import pkg_resources
deps = []
if not installed_distros:
installed_distros = pkg_resources.WorkingSet()
for package in installed_distros:
if package.project_name.lower() == pkg_name.lower():
deps = [(package.project_name, package.version)]
for req in package.requires():
deps += self.get_deps_list(
pkg_name=req.project_name, installed_distros=installed_distros
)
return list(set(deps)) # de-dupe before returning
def create_handler_venv(self):
"""
Takes the installed zappa and brings it into a fresh virtualenv-like folder. All dependencies are then downloaded.
"""
import subprocess
# We will need the currenv venv to pull Zappa from
current_venv = self.get_current_venv()
# Make a new folder for the handler packages
ve_path = os.path.join(os.getcwd(), "handler_venv")
if os.sys.platform == "win32":
current_site_packages_dir = os.path.join(
current_venv, "Lib", "site-packages"
)
venv_site_packages_dir = os.path.join(ve_path, "Lib", "site-packages")
else:
current_site_packages_dir = os.path.join(
current_venv, "lib", get_venv_from_python_version(), "site-packages"
)
venv_site_packages_dir = os.path.join(
ve_path, "lib", get_venv_from_python_version(), "site-packages"
)
if not os.path.isdir(venv_site_packages_dir):
os.makedirs(venv_site_packages_dir)
# Copy zappa* to the new virtualenv
zappa_things = [
z for z in os.listdir(current_site_packages_dir) if z.lower()[:5] == "zappa"
]
for z in zappa_things:
copytree(
os.path.join(current_site_packages_dir, z),
os.path.join(venv_site_packages_dir, z),
)
# Use pip to download zappa's dependencies. Copying from current venv causes issues with things like PyYAML that installs as yaml
zappa_deps = self.get_deps_list("zappa")
pkg_list = ["{0!s}=={1!s}".format(dep, version) for dep, version in zappa_deps]
# Need to manually add setuptools
pkg_list.append("setuptools")
command = [
"pip",
"install",
"--quiet",
"--target",
venv_site_packages_dir,
] + pkg_list
# This is the recommended method for installing packages if you don't
# to depend on `setuptools`
# https://github.com/pypa/pip/issues/5240#issuecomment-381662679
pip_process = subprocess.Popen(command, stdout=subprocess.PIPE)
# Using communicate() to avoid deadlocks
pip_process.communicate()
pip_return_code = pip_process.returncode
if pip_return_code:
raise EnvironmentError("Pypi lookup failed")
return ve_path
# staticmethod as per https://github.com/Miserlou/Zappa/issues/780
@staticmethod
def get_current_venv():
"""
Returns the path to the current virtualenv
"""
if "VIRTUAL_ENV" in os.environ:
venv = os.environ["VIRTUAL_ENV"]
elif os.path.exists(".python-version"): # pragma: no cover
try:
subprocess.check_output(["pyenv", "help"], 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:
# minor fix in how .python-version is read
# Related: https://github.com/Miserlou/Zappa/issues/921
env_name = f.readline().strip()
bin_path = subprocess.check_output(["pyenv", "which", "python"]).decode(
"utf-8"
)
venv = bin_path[: bin_path.rfind(env_name)] + env_name
else: # pragma: no cover
return None
return venv
def create_lambda_zip(
self,
prefix="lambda_package",
handler_file=None,
slim_handler=False,
minify=True,
exclude=None,
exclude_glob=None,
use_precompiled_packages=True,
include=None,
venv=None,
output=None,
disable_progress=False,
archive_format="zip",
):
"""
Create a Lambda-ready zip file of the current virtualenvironment and working directory.
Returns path to that file.
"""
# Validate archive_format
if archive_format not in ["zip", "tarball"]:
raise KeyError(
"The archive format to create a lambda package must be zip or tarball"
)
# Pip is a weird package.
# Calling this function in some environments without this can cause.. funkiness.
import pip
if not venv:
venv = self.get_current_venv()
build_time = str(int(time.time()))
cwd = os.getcwd()
if not output:
if archive_format == "zip":
archive_fname = prefix + "-" + build_time + ".zip"
elif archive_format == "tarball":
archive_fname = prefix + "-" + build_time + ".tar.gz"
else:
archive_fname = output
archive_path = os.path.join(cwd, archive_fname)
# Files that should be excluded from the zip
if exclude is None:
exclude = list()
if exclude_glob is None:
exclude_glob = list()
# Exclude the zip itself
exclude.append(archive_path)
# Make sure that 'concurrent' is always forbidden.
# https://github.com/Miserlou/Zappa/issues/827
if not "concurrent" in exclude:
exclude.append("concurrent")
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 list(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 = tempfile.mkdtemp(prefix="zappa-project")
if not slim_handler:
# Slim handler does not take the project files.
if minify:
# Related: https://github.com/Miserlou/Zappa/issues/744
excludes = ZIP_EXCLUDES + exclude + [split_venv[-1]]
copytree(
cwd,
temp_project_path,
metadata=False,
symlinks=False,
ignore=shutil.ignore_patterns(*excludes),
)
else:
copytree(cwd, temp_project_path, metadata=False, symlinks=False)
for glob_path in exclude_glob:
for path in glob.glob(os.path.join(temp_project_path, glob_path)):
try:
os.remove(path)
except OSError: # is a directory
shutil.rmtree(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))
# Create and populate package ID file and write to temp project path
package_info = {}
package_info["uuid"] = str(uuid.uuid4())
package_info["build_time"] = build_time
package_info["build_platform"] = os.sys.platform
package_info["build_user"] = getpass.getuser()
# TODO: Add git head and info?
# Ex, from @scoates:
# def _get_git_branch():
# chdir(DIR)
# out = check_output(['git', 'rev-parse', '--abbrev-ref', 'HEAD']).strip()
# lambci_branch = environ.get('LAMBCI_BRANCH', None)
# if out == "HEAD" and lambci_branch:
# out += " lambci:{}".format(lambci_branch)
# return out
# def _get_git_hash():
# chdir(DIR)
# return check_output(['git', 'rev-parse', 'HEAD']).strip()
# def _get_uname():
# return check_output(['uname', '-a']).strip()
# def _get_user():
# return check_output(['whoami']).strip()
# def set_id_info(zappa_cli):
# build_info = {
# 'branch': _get_git_branch(),
# 'hash': _get_git_hash(),
# 'build_uname': _get_uname(),
# 'build_user': _get_user(),
# 'build_time': datetime.datetime.utcnow().isoformat(),
# }
# with open(path.join(DIR, 'id_info.json'), 'w') as f:
# json.dump(build_info, f)
# return True
package_id_file = open(
os.path.join(temp_project_path, "package_info.json"), "w"
)
dumped = json.dumps(package_info, indent=4)
try:
package_id_file.write(dumped)
except TypeError: # This is a Python 2/3 issue. TODO: Make pretty!
package_id_file.write(str(dumped))
package_id_file.close()
# Then, do site site-packages..
egg_links = []
temp_package_path = tempfile.mkdtemp(prefix="zappa-packages")
if os.sys.platform == "win32":
site_packages = os.path.join(venv, "Lib", "site-packages")
else:
site_packages = os.path.join(
venv, "lib", get_venv_from_python_version(), "site-packages"
)
egg_links.extend(glob.glob(os.path.join(site_packages, "*.egg-link")))
if minify:
excludes = ZIP_EXCLUDES + exclude
copytree(
site_packages,
temp_package_path,
metadata=False,
symlinks=False,
ignore=shutil.ignore_patterns(*excludes),
)
else:
copytree(site_packages, temp_package_path, metadata=False, symlinks=False)
# We may have 64-bin specific packages too.
site_packages_64 = os.path.join(
venv, "lib64", get_venv_from_python_version(), "site-packages"
)
if os.path.exists(site_packages_64):
egg_links.extend(glob.glob(os.path.join(site_packages_64, "*.egg-link")))
if minify:
excludes = ZIP_EXCLUDES + exclude
copytree(
site_packages_64,
temp_package_path,
metadata=False,
symlinks=False,
ignore=shutil.ignore_patterns(*excludes),
)
else:
copytree(
site_packages_64, temp_package_path, metadata=False, symlinks=False
)
if egg_links:
self.copy_editable_packages(egg_links, temp_package_path)
copy_tree(temp_package_path, temp_project_path, update=True)
# Then the pre-compiled packages..
if use_precompiled_packages:
print("Downloading and installing dependencies..")
installed_packages = self.get_installed_packages(
site_packages, site_packages_64
)
try:
for (
installed_package_name,
installed_package_version,
) in installed_packages.items():
cached_wheel_path = self.get_cached_manylinux_wheel(
installed_package_name,
installed_package_version,
disable_progress,
)
if cached_wheel_path:
# Otherwise try to use manylinux packages from PyPi..
# Related: https://github.com/Miserlou/Zappa/issues/398
shutil.rmtree(
os.path.join(temp_project_path, installed_package_name),
ignore_errors=True,
)
with zipfile.ZipFile(cached_wheel_path) as zfile:
zfile.extractall(temp_project_path)
except Exception as e:
print(e)
# XXX - What should we do here?
# Cleanup
for glob_path in exclude_glob:
for path in glob.glob(os.path.join(temp_project_path, glob_path)):
try:
os.remove(path)
except OSError: # is a directory
shutil.rmtree(path)
# Then archive it all up..
if archive_format == "zip":
print("Packaging project as zip.")
try:
compression_method = zipfile.ZIP_DEFLATED
except ImportError: # pragma: no cover
compression_method = zipfile.ZIP_STORED
archivef = zipfile.ZipFile(archive_path, "w", compression_method)
elif archive_format == "tarball":
print("Packaging project as gzipped tarball.")
archivef = tarfile.open(archive_path, "w|gz")
for root, dirs, files in os.walk(temp_project_path):
for filename in files:
# Skip .pyc files for Django migrations
# https://github.com/Miserlou/Zappa/issues/436
# https://github.com/Miserlou/Zappa/issues/464
if filename[-4:] == ".pyc" and root[-10:] == "migrations":
continue
# 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" and root[-10:] != "migrations":
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
# Make sure that the files are all correctly chmodded
# Related: https://github.com/Miserlou/Zappa/issues/484
# Related: https://github.com/Miserlou/Zappa/issues/682
os.chmod(os.path.join(root, filename), 0o755)
if archive_format == "zip":
# Actually put the file into the proper place in the zip
# Related: https://github.com/Miserlou/Zappa/pull/716
zipi = zipfile.ZipInfo(
os.path.join(
root.replace(temp_project_path, "").lstrip(os.sep), filename
)
)
zipi.create_system = 3
zipi.external_attr = 0o755 << int(16) # Is this P2/P3 functional?
with open(os.path.join(root, filename), "rb") as f:
archivef.writestr(zipi, f.read(), compression_method)
elif archive_format == "tarball":
tarinfo = tarfile.TarInfo(
os.path.join(
root.replace(temp_project_path, "").lstrip(os.sep), filename
)
)
tarinfo.mode = 0o755
stat = os.stat(os.path.join(root, filename))
tarinfo.mtime = stat.st_mtime
tarinfo.size = stat.st_size
with open(os.path.join(root, filename), "rb") as f:
archivef.addfile(tarinfo, f)
# Create python init file if it does not exist
# Only do that if there are sub folders or python files and does not conflict with a neighbouring module
# Related: https://github.com/Miserlou/Zappa/issues/766
if not contains_python_files_or_subdirs(root):
# if the directory does not contain any .py file at any level, we can skip the rest
dirs[:] = [d for d in dirs if d != root]
else:
if (
"__init__.py" not in files
and not conflicts_with_a_neighbouring_module(root)
):
tmp_init = os.path.join(temp_project_path, "__init__.py")
open(tmp_init, "a").close()
os.chmod(tmp_init, 0o755)
arcname = os.path.join(
root.replace(temp_project_path, ""),
os.path.join(
root.replace(temp_project_path, ""), "__init__.py"
),
)
if archive_format == "zip":
archivef.write(tmp_init, arcname)
elif archive_format == "tarball":
archivef.add(tmp_init, arcname)
# And, we're done!
archivef.close()
# Trash the temp directory
shutil.rmtree(temp_project_path)
shutil.rmtree(temp_package_path)
if os.path.isdir(venv) and slim_handler:
# Remove the temporary handler venv folder
shutil.rmtree(venv)
return archive_fname
@staticmethod
def get_installed_packages(site_packages, site_packages_64):
"""
Returns a dict of installed packages that Zappa cares about.
"""
import pkg_resources
package_to_keep = []
if os.path.isdir(site_packages):
package_to_keep += os.listdir(site_packages)
if os.path.isdir(site_packages_64):
package_to_keep += os.listdir(site_packages_64)
package_to_keep = [x.lower() for x in package_to_keep]
installed_packages = {
package.project_name.lower(): package.version
for package in pkg_resources.WorkingSet()
if package.project_name.lower() in package_to_keep
or package.location.lower()
in [site_packages.lower(), site_packages_64.lower()]
}
return installed_packages
@staticmethod
def download_url_with_progress(url, stream, disable_progress):
"""
Downloads a given url in chunks and writes to the provided stream (can be any io stream).
Displays the progress bar for the download.
"""
resp = requests.get(
url, timeout=float(os.environ.get("PIP_TIMEOUT", 2)), stream=True
)
resp.raw.decode_content = True
progress = tqdm(
unit="B",
unit_scale=True,
total=int(resp.headers.get("Content-Length", 0)),
disable=disable_progress,
)
for chunk in resp.iter_content(chunk_size=1024):
if chunk:
progress.update(len(chunk))
stream.write(chunk)
progress.close()
def get_cached_manylinux_wheel(
self, package_name, package_version, disable_progress=False
):
"""
Gets the locally stored version of a manylinux wheel. If one does not exist, the function downloads it.
"""
cached_wheels_dir = os.path.join(tempfile.gettempdir(), "cached_wheels")
if not os.path.isdir(cached_wheels_dir):
os.makedirs(cached_wheels_dir)
else:
# Check if we already have a cached copy
wheel_name = re.sub("[^\w\d.]+", "_", package_name, re.UNICODE)
wheel_file = f"{wheel_name}-{package_version}-*_x86_64.whl"
wheel_path = os.path.join(cached_wheels_dir, wheel_file)
for pathname in glob.iglob(wheel_path):
if re.match(self.manylinux_wheel_file_match, pathname) or re.match(
self.manylinux_wheel_abi3_file_match, pathname
):
print(
f" - {package_name}=={package_version}: Using locally cached manylinux wheel"
)
return pathname
# The file is not cached, download it.
wheel_url, filename = self.get_manylinux_wheel_url(
package_name, package_version
)
if not wheel_url:
return None
wheel_path = os.path.join(cached_wheels_dir, filename)
print(f" - {package_name}=={package_version}: Downloading")
with open(wheel_path, "wb") as f:
self.download_url_with_progress(wheel_url, f, disable_progress)
if not zipfile.is_zipfile(wheel_path):
return None
return wheel_path
def get_manylinux_wheel_url(self, package_name, package_version):
"""
For a given package name, returns a link to the download URL,
else returns None.
Related: https://github.com/Miserlou/Zappa/issues/398
Examples here: https://gist.github.com/perrygeo/9545f94eaddec18a65fd7b56880adbae
This function downloads metadata JSON of `package_name` from Pypi
and examines if the package has a manylinux wheel. This function
also caches the JSON file so that we don't have to poll Pypi
every time.
"""