forked from terraform-aws-modules/terraform-aws-lambda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
package.py
1841 lines (1571 loc) · 62.1 KB
/
package.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
# coding: utf-8
import sys
if sys.version_info < (3, 6):
raise RuntimeError("A python version 3.6 or newer is required")
import os
import re
import time
import stat
import json
import shlex
import shutil
import hashlib
import zipfile
import argparse
import datetime
import tempfile
import operator
import platform
import subprocess
from subprocess import check_call, check_output
from contextlib import contextmanager
from base64 import b64encode
import logging
PY38 = sys.version_info >= (3, 8)
PY37 = sys.version_info >= (3, 7)
PY36 = sys.version_info >= (3, 6)
WINDOWS = platform.system() == "Windows"
OSX = platform.system() == "Darwin"
################################################################################
# Logging
DEBUG2 = 9
DEBUG3 = 8
DUMP_ENV = 1
log_handler = None
log = logging.getLogger()
cmd_log = logging.getLogger("cmd")
def configure_logging(use_tf_stderr=False):
global log_handler
logging.addLevelName(DEBUG2, "DEBUG2")
logging.addLevelName(DEBUG3, "DEBUG3")
logging.addLevelName(DUMP_ENV, "DUMP_ENV")
class LogFormatter(logging.Formatter):
default_format = "%(message)s"
formats = {
"root": default_format,
"build": default_format,
"prepare": "[{}] %(name)s: %(message)s".format(os.getpid()),
"cmd": "> %(message)s",
"": "%(name)s: %(message)s",
}
def formatMessage(self, record):
prefix = record.name.rsplit(".")
self._style._fmt = self.formats.get(prefix[0], self.formats[""])
return super().formatMessage(record)
tf_stderr_fd = 5
log_stream = sys.stderr
if use_tf_stderr:
try:
if os.isatty(tf_stderr_fd):
log_stream = os.fdopen(tf_stderr_fd, mode="w")
except OSError:
pass
log_handler = logging.StreamHandler(stream=log_stream)
log_handler.setFormatter(LogFormatter())
log.addHandler(log_handler)
log.setLevel(logging.INFO)
def dump_env():
if log.isEnabledFor(DUMP_ENV):
log.debug("ENV: %s", json.dumps(dict(os.environ), indent=2))
################################################################################
# Backports
def shlex_join(split_command):
"""Return a shell-escaped string from *split_command*."""
return " ".join(shlex.quote(arg) for arg in split_command)
################################################################################
# Common functions
def abort(message):
"""Exits with an error message."""
log.error(message)
sys.exit(1)
@contextmanager
def cd(path, silent=False):
"""Changes the working directory."""
cwd = os.getcwd()
if not silent:
cmd_log.info("cd %s", shlex.quote(path))
try:
os.chdir(path)
yield
finally:
os.chdir(cwd)
@contextmanager
def tempdir(dir=None):
"""Creates a temporary directory and then deletes it afterwards."""
prefix = "terraform-aws-lambda-"
path = tempfile.mkdtemp(prefix=prefix, dir=dir)
abs_path = os.path.abspath(path)
cmd_log.info("mktemp -d %sXXXXXXXX # %s", prefix, shlex.quote(abs_path))
try:
yield abs_path
finally:
shutil.rmtree(abs_path)
def list_files(top_path, log=None):
"""
Returns a sorted list of all files in a directory.
"""
if log:
log = log.getChild("ls")
results = []
for root, dirs, files in os.walk(top_path, followlinks=True):
# Sort directories and files to ensure they are always processed in the same order
dirs.sort()
files.sort()
for file_name in files:
file_path = os.path.join(root, file_name)
relative_path = os.path.relpath(file_path, top_path)
results.append(relative_path)
if log:
log.debug(relative_path)
results.sort()
return results
def dataclass(name):
typ = type(
name,
(dict,),
{
"__getattr__": lambda self, x: self.get(x),
"__init__": lambda self, **k: self.update(k),
},
)
return typ
def datatree(name, **fields):
def decode_json(k, v):
if v and isinstance(v, str) and v[0] in '"[{':
try:
o = json.loads(v)
if isinstance(o, dict):
return dataclass(k)(**o)
return o
except json.JSONDecodeError:
pass
return v
return dataclass(name)(
**dict(
(
(k, datatree(k, **v) if isinstance(v, dict) else decode_json(k, v))
for k, v in fields.items()
)
)
)
def timestamp_now_ns():
timestamp = datetime.datetime.now().timestamp()
timestamp = int(timestamp * 10**7) * 10**2
return timestamp
def source_code_hash(bytes):
return b64encode(hashlib.sha256(bytes).digest()).decode()
def yesno_bool(val):
if val is None:
return
if isinstance(val, bool):
return val
if isinstance(val, int):
return bool(val)
if isinstance(val, str):
if val.isnumeric():
return bool(int(val))
val = val.lower()
if val in ("true", "yes", "y"):
return True
elif val in ("false", "no", "n"):
return False
else:
raise ValueError("Unsupported value: %s" % val)
return False
################################################################################
# Packaging functions
def emit_dir_content(base_dir):
for root, dirs, files in os.walk(base_dir, followlinks=True):
# Sort directories and files to ensure they are always processed in the same order
dirs.sort()
files.sort()
if root != base_dir:
yield os.path.normpath(root)
for name in files:
yield os.path.normpath(os.path.join(root, name))
def generate_content_hash(source_paths, hash_func=hashlib.sha256, log=None):
"""
Generate a content hash of the source paths.
"""
if log:
log = log.getChild("hash")
hash_obj = hash_func()
for source_path in source_paths:
if os.path.isdir(source_path):
source_dir = source_path
_log = log if log.isEnabledFor(DEBUG3) else None
for source_file in list_files(source_dir, log=_log):
update_hash(hash_obj, source_dir, source_file)
if log:
log.debug(os.path.join(source_dir, source_file))
else:
source_dir = os.path.dirname(source_path)
source_file = os.path.relpath(source_path, source_dir)
update_hash(hash_obj, source_dir, source_file)
if log:
log.debug(source_path)
return hash_obj
def update_hash(hash_obj, file_root, file_path):
"""
Update a hashlib object with the relative path and contents of a file.
"""
relative_path = os.path.join(file_root, file_path)
hash_obj.update(relative_path.encode())
try:
with open(relative_path, "rb") as open_file:
while True:
data = open_file.read(1024 * 8)
if not data:
break
hash_obj.update(data)
# ignore broken symlinks content to don't fail on `terraform destroy` command
except FileNotFoundError:
pass
class ZipWriteStream:
""""""
def __init__(
self,
zip_filename,
compress_type=zipfile.ZIP_DEFLATED,
compresslevel=None,
timestamp=None,
):
self.timestamp = timestamp
self.filename = zip_filename
if not (self.filename and isinstance(self.filename, str)):
raise ValueError("Zip file path must be provided")
self._tmp_filename = None
self._compress_type = compress_type
self._compresslevel = compresslevel
self._zip = None
self._log = logging.getLogger("zip")
def open(self):
if self._tmp_filename:
raise zipfile.BadZipFile("ZipStream object can't be reused")
self._ensure_base_path(self.filename)
self._tmp_filename = "{}.tmp".format(self.filename)
self._log.info("creating '%s' archive", self.filename)
self._zip = zipfile.ZipFile(self._tmp_filename, "w", self._compress_type)
return self
def close(self, failed=False):
self._zip.close()
self._zip = None
if not os.path.exists(self._tmp_filename):
return
if failed:
os.unlink(self._tmp_filename)
else:
os.replace(self._tmp_filename, self.filename)
def __enter__(self):
return self.open()
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is not None:
self._log.exception("Error during zip archive creation")
self.close(failed=True)
raise SystemExit(1)
self.close()
def _ensure_open(self):
if self._zip is not None:
return True
if self._tmp_filename:
raise zipfile.BadZipFile("ZipWriteStream object can't be reused")
raise zipfile.BadZipFile("ZipWriteStream should be opened first")
def _ensure_base_path(self, zip_filename):
archive_dir = os.path.dirname(zip_filename)
if archive_dir and not os.path.exists(archive_dir):
self._log.info("creating %s", archive_dir)
os.makedirs(archive_dir, exist_ok=True)
def write_dirs(self, *base_dirs, prefix=None, timestamp=None):
"""
Writes a directory content to a prefix inside of a zip archive
"""
self._ensure_open()
for base_dir in base_dirs:
self._log.info("adding content of directory: %s", base_dir)
for path in emit_dir_content(base_dir):
arcname = os.path.relpath(path, base_dir)
self._write_file(path, prefix, arcname, timestamp)
def write_files(self, files_stream, prefix=None, timestamp=None):
"""
Expects just files stream, directories will be created automatically
"""
self._ensure_open()
for file_path, arcname in files_stream:
self._write_file(file_path, prefix, arcname, timestamp)
def write_file(self, file_path, prefix=None, name=None, timestamp=None):
"""
Reads a file and writes it to a prefix
or a full qualified name in a zip archive
"""
self._ensure_open()
self._write_file(file_path, prefix, name, timestamp)
def _write_file(self, file_path, prefix=None, name=None, timestamp=None):
arcname = name if name else os.path.basename(file_path)
if prefix:
arcname = os.path.join(prefix, arcname)
zinfo = self._make_zinfo_from_file(file_path, arcname)
if zinfo.is_dir():
self._log.info("adding: %s/", arcname)
else:
self._log.info("adding: %s", arcname)
if timestamp is None:
timestamp = self.timestamp
date_time = self._timestamp_to_date_time(timestamp)
if date_time:
self._update_zinfo(zinfo, date_time=date_time)
self._write_zinfo(zinfo, file_path)
def write_file_obj(self, file_path, data, prefix=None, timestamp=None):
"""
Write a data to a zip archive by a full qualified archive file path
"""
self._ensure_open()
raise NotImplementedError
def _write_zinfo(self, zinfo, filename, compress_type=None, compresslevel=None):
self._ensure_open()
zip = self._zip
if not zip.fp:
raise ValueError("Attempt to write to ZIP archive that was already closed")
if zip._writing:
raise ValueError(
"Can't write to ZIP archive while an open writing handle exists"
)
if zinfo.is_dir():
zinfo.compress_size = 0
zinfo.CRC = 0
else:
if compress_type is not None:
zinfo.compress_type = compress_type
else:
zinfo.compress_type = self._compress_type
if PY37:
if compresslevel is not None:
zinfo._compresslevel = compresslevel
else:
zinfo._compresslevel = self._compresslevel
if zinfo.is_dir():
with zip._lock:
if zip._seekable:
zip.fp.seek(zip.start_dir)
zinfo.header_offset = zip.fp.tell() # Start of header bytes
if zinfo.compress_type == zipfile.ZIP_LZMA:
# Compressed data includes an end-of-stream (EOS) marker
zinfo.flag_bits |= 0x02
zip._writecheck(zinfo)
zip._didModify = True
zip.filelist.append(zinfo)
zip.NameToInfo[zinfo.filename] = zinfo
zip.fp.write(zinfo.FileHeader(False))
zip.start_dir = zip.fp.tell()
else:
with open(filename, "rb") as src, zip.open(zinfo, "w") as dest:
shutil.copyfileobj(src, dest, 1024 * 8)
def _make_zinfo_from_file(self, filename, arcname=None):
if PY38:
zinfo_func = zipfile.ZipInfo.from_file
strict_timestamps = self._zip._strict_timestamps
else:
zinfo_func = self._zinfo_from_file
strict_timestamps = True
return zinfo_func(filename, arcname, strict_timestamps=strict_timestamps)
@staticmethod
def _update_zinfo(zinfo, date_time):
zinfo.date_time = date_time
# Borrowed from python 3.8 zipfile.py library
# due to the need of strict_timestamps functionality.
@staticmethod
def _zinfo_from_file(filename, arcname=None, *, strict_timestamps=True):
"""Construct an appropriate ZipInfo for a file on the filesystem.
filename should be the path to a file or directory on the filesystem.
arcname is the name which it will have within the archive (by default,
this will be the same as filename, but without a drive letter and with
leading path separators removed).
"""
if isinstance(filename, os.PathLike):
filename = os.fspath(filename)
st = os.stat(filename)
isdir = stat.S_ISDIR(st.st_mode)
mtime = time.localtime(st.st_mtime)
date_time = mtime[0:6]
if strict_timestamps and date_time[0] < 1980:
date_time = (1980, 1, 1, 0, 0, 0)
elif strict_timestamps and date_time[0] > 2107:
date_time = (2107, 12, 31, 23, 59, 59)
# Create ZipInfo instance to store file information
if arcname is None:
arcname = filename
arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
while arcname[0] in (os.sep, os.altsep):
arcname = arcname[1:]
if isdir:
arcname += "/"
zinfo = zipfile.ZipInfo(arcname, date_time)
zinfo.external_attr = (st.st_mode & 0xFFFF) << 16 # Unix attributes
if isdir:
zinfo.file_size = 0
zinfo.external_attr |= 0x10 # MS-DOS directory flag
else:
zinfo.file_size = st.st_size
return zinfo
@staticmethod
def _timestamp_to_date_time(timestamp):
def str_int_to_timestamp(s):
min_zip_ts = datetime.datetime(1980, 1, 1).timestamp()
ts = int(s)
if ts < min_zip_ts:
return min_zip_ts
deg = len(str(int(s))) - 9
if deg < 0:
ts = ts * 10**deg
return ts
date_time = None
if timestamp is not None:
if isinstance(timestamp, str):
if timestamp.isnumeric():
timestamp = str_int_to_timestamp(timestamp)
else:
timestamp = float(timestamp)
elif isinstance(timestamp, int):
timestamp = str_int_to_timestamp(str(timestamp))
date_time = datetime.datetime.fromtimestamp(timestamp).timetuple()
date_time = date_time[:6]
if date_time[0] < 1980:
raise ValueError("ZIP does not support timestamps before 1980")
return date_time
################################################################################
# Building
def patterns_list(args, patterns):
_filter = str.strip
if args.pattern_comments:
def _filter(x):
x = x.strip()
p = re.search("^(.*?)[ \t]*(?:[ \t]{2}#.*)?$", x).group(1).rstrip()
if p.startswith("#"):
return
if p:
return p
if isinstance(patterns, str):
return list(filter(None, map(_filter, patterns.splitlines())))
return patterns
class ZipContentFilter:
""""""
def __init__(self, args):
self._args = args
self._rules = None
self._excludes = set()
self._log = logging.getLogger("zip")
def compile(self, patterns):
rules = []
for p in patterns_list(self._args, patterns):
self._log.debug("filter pattern: %s", p)
if p.startswith("!"):
r = re.compile(p[1:])
rules.append((operator.not_, r))
else:
r = re.compile(p)
rules.append((None, r))
self._rules = rules
def reset(self):
self._log.debug("reset filter patterns")
self._rules = None
def filter(self, path, prefix=None):
path = os.path.normpath(path)
if prefix:
prefix = os.path.normpath(prefix)
rules = self._rules
def norm_path(path, root, filename=None):
op = os.path.join(root, filename) if filename else root
p = os.path.relpath(root, path)
if prefix:
p = os.path.join(prefix, p)
if filename:
p = os.path.normpath(os.path.join(p, filename))
return op, p
return op, p + os.sep
def apply(path):
d = True
for r in rules:
op, regex = r
neg = op is operator.not_
m = regex.fullmatch(path)
if neg and m:
d = False
elif m:
d = True
if d:
return path
def emit_dir(dpath, opath):
if apply(dpath):
yield opath
else:
self._log.debug("skip: %s", dpath)
def emit_file(fpath, opath):
if apply(fpath):
yield opath
else:
self._log.debug("skip: %s", fpath)
if os.path.isfile(path):
name = os.path.basename(path)
if prefix:
name = os.path.join(prefix, name)
if apply(name):
yield path
else:
for root, dirs, files in os.walk(path, followlinks=True):
# Sort directories and files to ensure they are always processed in the same order
dirs.sort()
files.sort()
o, d = norm_path(path, root)
# log.info('od: %s %s', o, d)
if root != path:
yield from emit_dir(d, o)
for name in files:
o, f = norm_path(path, root, name)
# log.info('of: %s %s', o, f)
yield from emit_file(f, o)
def get_build_system_from_pyproject_toml(pyproject_file):
# Implement a basic TOML parser because python stdlib does not provide toml support and we probably do not want to add external dependencies
if os.path.isfile(pyproject_file):
with open(pyproject_file) as f:
bs = False
for line in f.readlines():
if line.startswith("[build-system]"):
bs = True
continue
if bs and line.startswith("build-backend") and "poetry" in line:
return "poetry"
class BuildPlanManager:
""""""
def __init__(self, args, log=None):
self._args = args
self._source_paths = None
self._log = log or logging.root
def hash(self, extra_paths):
if not self._source_paths:
raise ValueError("BuildPlanManager.plan() should be called first")
content_hash_paths = self._source_paths + extra_paths
# Generate a hash based on file names and content. Also use the
# runtime value, build command, and content of the build paths
# because they can have an effect on the resulting archive.
self._log.debug("Computing content hash on files...")
content_hash = generate_content_hash(content_hash_paths, log=self._log)
return content_hash
def plan(self, source_path, query):
claims = source_path
if not isinstance(source_path, list):
claims = [source_path]
source_paths = []
build_plan = []
def step(*x):
build_plan.append(x)
def hash(path):
source_paths.append(path)
def pip_requirements_step(path, prefix=None, required=False, tmp_dir=None):
command = runtime
requirements = path
if os.path.isdir(path):
requirements = os.path.join(path, "requirements.txt")
if not os.path.isfile(requirements):
if required:
raise RuntimeError("File not found: {}".format(requirements))
else:
if not query.docker and not shutil.which(command):
raise RuntimeError(
"Python interpreter version equal "
"to defined lambda runtime ({}) should be "
"available in system PATH".format(command)
)
step("pip", runtime, requirements, prefix, tmp_dir)
hash(requirements)
def poetry_install_step(
path, poetry_export_extra_args=[], prefix=None, required=False
):
pyproject_file = path
if os.path.isdir(path):
pyproject_file = os.path.join(path, "pyproject.toml")
if get_build_system_from_pyproject_toml(pyproject_file) != "poetry":
if required:
raise RuntimeError(
"poetry configuration not found: {}".format(pyproject_file)
)
else:
step("poetry", runtime, path, poetry_export_extra_args, prefix)
hash(pyproject_file)
pyproject_path = os.path.dirname(pyproject_file)
poetry_lock_file = os.path.join(pyproject_path, "poetry.lock")
if os.path.isfile(poetry_lock_file):
hash(poetry_lock_file)
poetry_toml_file = os.path.join(pyproject_path, "poetry.toml")
if os.path.isfile(poetry_toml_file):
hash(poetry_toml_file)
def npm_requirements_step(path, prefix=None, required=False, tmp_dir=None):
command = "npm"
requirements = path
if os.path.isdir(path):
requirements = os.path.join(path, "package.json")
if not os.path.isfile(requirements):
if required:
raise RuntimeError("File not found: {}".format(requirements))
else:
if not query.docker and not shutil.which(command):
raise RuntimeError(
"Nodejs package manager ({}) should be "
"available in system PATH".format(command)
)
step("npm", runtime, requirements, prefix, tmp_dir)
hash(requirements)
def commands_step(path, commands):
if not commands:
return
if isinstance(commands, str):
commands = map(str.strip, commands.splitlines())
if path:
path = os.path.normpath(path)
batch = []
for c in commands:
if isinstance(c, str):
if c.startswith(":zip"):
if path:
hash(path)
if batch:
step("sh", path, "\n".join(batch))
batch.clear()
c = shlex.split(c)
if len(c) == 3:
_, _path, prefix = c
prefix = prefix.strip()
_path = os.path.normpath(os.path.join(path, _path))
step("zip:embedded", _path, prefix)
elif len(c) == 2:
_, _path = c
prefix = None
_path = os.path.normpath(_path)
step("zip:embedded", _path, prefix)
elif len(c) == 1:
prefix = None
_path = None
step("zip:embedded", _path, prefix)
else:
raise ValueError(
":zip invalid call signature, use: "
"':zip [path [prefix_in_zip]]'"
)
else:
batch.append(c)
if batch:
step("sh", path, "\n".join(batch))
batch.clear()
step("reset:workdir")
for claim in claims:
if isinstance(claim, str):
path = claim
if not os.path.exists(path):
abort(
'Could not locate source_path "{path}". Paths are relative to directory where `terraform plan` is being run ("{pwd}")'.format(
path=path, pwd=os.getcwd()
)
)
runtime = query.runtime
if runtime.startswith("python"):
pip_requirements_step(os.path.join(path, "requirements.txt"))
poetry_install_step(path)
elif runtime.startswith("nodejs"):
npm_requirements_step(os.path.join(path, "package.json"))
step("zip", path, None)
hash(path)
elif isinstance(claim, dict):
path = claim.get("path")
patterns = claim.get("patterns")
commands = claim.get("commands")
if patterns:
step("set:filter", patterns_list(self._args, patterns))
if commands:
commands_step(path, commands)
else:
prefix = claim.get("prefix_in_zip")
pip_requirements = claim.get("pip_requirements")
poetry_install = claim.get("poetry_install")
poetry_export_extra_args = claim.get("poetry_export_extra_args", [])
npm_requirements = claim.get("npm_package_json")
runtime = claim.get("runtime", query.runtime)
if pip_requirements and runtime.startswith("python"):
if isinstance(pip_requirements, bool) and path:
pip_requirements_step(
path,
prefix,
required=True,
tmp_dir=claim.get("pip_tmp_dir"),
)
else:
pip_requirements_step(
pip_requirements,
prefix,
required=True,
tmp_dir=claim.get("pip_tmp_dir"),
)
if poetry_install and runtime.startswith("python"):
if path:
poetry_install_step(
path,
prefix=prefix,
poetry_export_extra_args=poetry_export_extra_args,
required=True,
)
if npm_requirements and runtime.startswith("nodejs"):
if isinstance(npm_requirements, bool) and path:
npm_requirements_step(
path,
prefix,
required=True,
tmp_dir=claim.get("npm_tmp_dir"),
)
else:
npm_requirements_step(
npm_requirements,
prefix,
required=True,
tmp_dir=claim.get("npm_tmp_dir"),
)
if path:
path = os.path.normpath(path)
step("zip", path, prefix)
if patterns:
# Take patterns into account when computing hash
pf = ZipContentFilter(args=self._args)
pf.compile(patterns)
for path_from_pattern in pf.filter(path, prefix):
hash(path_from_pattern)
else:
hash(path)
if patterns:
step("clear:filter")
else:
raise ValueError("Unsupported source_path item: {}".format(claim))
self._source_paths = source_paths
return build_plan
def execute(self, build_plan, zip_stream, query):
sh_log = logging.getLogger("sh")
tf_work_dir = os.getcwd()
zs = zip_stream
sh_work_dir = None
pf = None
for action in build_plan:
cmd = action[0]
if cmd.startswith("zip"):
ts = 0 if cmd == "zip:embedded" else None
source_path, prefix = action[1:]
if not sh_work_dir:
sh_work_dir = tf_work_dir
log.debug("WORKDIR: %s", sh_work_dir)
if source_path:
if not os.path.isabs(source_path):
source_path = os.path.normpath(
os.path.join(sh_work_dir, source_path)
)
else:
source_path = sh_work_dir
if os.path.isdir(source_path):
if pf:
self._zip_write_with_filter(
zs, pf, source_path, prefix, timestamp=ts
)
else:
zs.write_dirs(source_path, prefix=prefix, timestamp=ts)
else:
zs.write_file(source_path, prefix=prefix, timestamp=ts)
elif cmd == "pip":
runtime, pip_requirements, prefix, tmp_dir = action[1:]
with install_pip_requirements(query, pip_requirements, tmp_dir) as rd:
if rd:
if pf:
self._zip_write_with_filter(zs, pf, rd, prefix, timestamp=0)
else:
# XXX: timestamp=0 - what actually do with it?
zs.write_dirs(rd, prefix=prefix, timestamp=0)
elif cmd == "poetry":
(
runtime,
path,
poetry_export_extra_args,
prefix,
) = action[1:]
log.info("poetry_export_extra_args: %s", poetry_export_extra_args)
with install_poetry_dependencies(
query, path, poetry_export_extra_args
) as rd:
if rd:
if pf:
self._zip_write_with_filter(zs, pf, rd, prefix, timestamp=0)
else:
# XXX: timestamp=0 - what actually do with it?
zs.write_dirs(rd, prefix=prefix, timestamp=0)
elif cmd == "npm":
runtime, npm_requirements, prefix, tmp_dir = action[1:]
with install_npm_requirements(query, npm_requirements, tmp_dir) as rd:
if rd:
if pf:
self._zip_write_with_filter(zs, pf, rd, prefix, timestamp=0)
else:
# XXX: timestamp=0 - what actually do with it?
zs.write_dirs(rd, prefix=prefix, timestamp=0)
elif cmd == "sh":
with tempfile.NamedTemporaryFile(mode="w+t", delete=True) as temp_file:
path, script = action[1:]
if not path:
path = tf_work_dir
if not os.path.isabs(path):
path = os.path.normpath(os.path.join(tf_work_dir, path))
if log.isEnabledFor(DEBUG2):
log.debug("exec shell script ...")
for line in script.splitlines():
sh_log.debug(line)
script = "\n".join(
(
script,
# NOTE: Execute `pwd` to determine the subprocess shell's
# working directory after having executed all other commands.
"retcode=$?",
f"pwd >{temp_file.name}",
"exit $retcode",
)
)
p = subprocess.Popen(
script,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=path,
)
call_stdout, call_stderr = p.communicate()
exit_code = p.returncode
log.debug("exit_code: %s", exit_code)
if exit_code != 0:
raise RuntimeError(
"Script did not run successfully, exit code {}: {} - {}".format(
exit_code,
call_stdout.decode("utf-8").strip(),
call_stderr.decode("utf-8").strip(),
)
)