-
Notifications
You must be signed in to change notification settings - Fork 163
/
project.py
1494 lines (1321 loc) · 56.1 KB
/
project.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
# pylint: disable=too-many-lines
import json
import logging
import os
import re
import shutil
import sys
import zipfile
from pathlib import Path
from tempfile import TemporaryFile
from typing import Any, Dict
from uuid import uuid4
import jsonpatch
import yaml
from botocore.exceptions import ClientError, WaiterError
from jinja2 import Environment, PackageLoader, select_autoescape
from jsonschema import Draft7Validator
from jsonschema.exceptions import ValidationError
from rpdk.core.fragment.generator import TemplateFragment
from rpdk.core.jsonutils.flattener import JsonSchemaFlattener
from . import __version__
from .boto_helpers import create_sdk_session
from .data_loaders import load_hook_spec, load_resource_spec, resource_json
from .exceptions import (
DownstreamError,
FragmentValidationError,
InternalError,
InvalidProjectError,
RPDKBaseException,
SpecValidationError,
)
from .fragment.module_fragment_reader import _get_fragment_file
from .jsonutils.pointer import fragment_decode, fragment_encode
from .jsonutils.utils import traverse
from .plugin_registry import load_plugin
from .type_name_resolver import TypeNameResolver
from .type_schema_loader import TypeSchemaLoader
from .upload import Uploader
LOG = logging.getLogger(__name__)
SETTINGS_FILENAME = ".rpdk-config"
SCHEMA_UPLOAD_FILENAME = "schema.json"
CONFIGURATION_SCHEMA_UPLOAD_FILENAME = "configuration-schema.json"
OVERRIDES_FILENAME = "overrides.json"
TARGET_INFO_FILENAME = "target-info.json"
INPUTS_FOLDER = "inputs"
EXAMPLE_INPUTS_FOLDER = "example_inputs"
TARGET_SCHEMAS_FOLDER = "target-schemas"
HOOK_ROLE_TEMPLATE_FILENAME = "hook-role.yaml"
RESOURCE_ROLE_TEMPLATE_FILENAME = "resource-role.yaml"
TYPE_NAME_RESOURCE_REGEX = "^[a-zA-Z0-9]{2,64}::[a-zA-Z0-9]{2,64}::[a-zA-Z0-9]{2,64}$"
TYPE_NAME_MODULE_REGEX = (
"^[a-zA-Z0-9]{2,64}::[a-zA-Z0-9]{2,64}::[a-zA-Z0-9]{2,64}::MODULE$"
)
TYPE_NAME_HOOK_REGEX = "^[a-zA-Z0-9]{2,64}::[a-zA-Z0-9]{2,64}::[a-zA-Z0-9]{2,64}$"
ARTIFACT_TYPE_RESOURCE = "RESOURCE"
ARTIFACT_TYPE_MODULE = "MODULE"
ARTIFACT_TYPE_HOOK = "HOOK"
TARGET_CANARY_ROOT_FOLDER = "canary-bundle"
TARGET_CANARY_FOLDER = "canary-bundle/canary"
RPDK_CONFIG_FILE = ".rpdk-config"
CANARY_FILE_PREFIX = "canary"
CANARY_FILE_CREATE_SUFFIX = "001"
CANARY_FILE_UPDATE_SUFFIX = "002"
CANARY_SUPPORTED_PATCH_INPUT_OPERATIONS = {"replace", "remove", "add"}
CREATE_INPUTS_KEY = "CreateInputs"
PATCH_INPUTS_KEY = "PatchInputs"
PATCH_VALUE_KEY = "value"
PATCH_OPERATION_KEY = "op"
CONTRACT_TEST_DEPENDENCY_FILE_NAME = "dependencies.yml"
CANARY_DEPENDENCY_FILE_NAME = "bootstrap.yaml"
CANARY_SETTINGS = "canarySettings"
TYPE_NAME = "typeName"
CONTRACT_TEST_FILE_NAMES = "contract_test_file_names"
INPUT1_FILE_NAME = "inputs_1.json"
CONTRACT_TEST_FOLDER = "contract-tests-artifacts"
CONTRACT_TEST_INPUT_PREFIX = "inputs_*"
CONTRACT_TEST_DEPENDENCY_FILE_NAME = "dependencies.yml"
TYPE_NAME = "typeName"
CONTRACT_TEST_FILE_NAMES = "contract_test_file_names"
FN_SUB = "Fn::Sub"
FN_IMPORT_VALUE = "Fn::ImportValue"
UUID = "uuid"
DYNAMIC_VALUES_MAP = {
"region": "${AWS::Region}",
"partition": "${AWS::Partition}",
"account": "${AWS::AccountId}",
}
DEFAULT_ROLE_TIMEOUT_MINUTES = 120 # 2 hours
# min and max are according to CreateRole API restrictions
# https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateRole.html
MIN_ROLE_TIMEOUT_SECONDS = 3600 # 1 hour
MAX_ROLE_TIMEOUT_SECONDS = 43200 # 12 hours
MAX_RPDK_CONFIG_LENGTH = 10 * 1024 # 10 KiB
MAX_CONFIGURATION_SCHEMA_LENGTH = 60 * 1024 # 60 KiB
PROTOCOL_VERSION_VALUES = frozenset({"1.0.0", "2.0.0"})
CFN_METADATA_FILENAME = ".cfn_metadata.json"
SETTINGS_VALIDATOR = Draft7Validator(
{
"properties": {
"artifact_type": {"type": "string"},
"language": {"type": "string"},
"typeName": {"type": "string", "pattern": TYPE_NAME_RESOURCE_REGEX},
"runtime": {"type": "string"},
"entrypoint": {"type": ["string", "null"]},
"testEntrypoint": {"type": ["string", "null"]},
"executableEntrypoint": {"type": ["string", "null"]},
"settings": {"type": "object"},
},
"required": ["language", "typeName", "runtime", "entrypoint"],
}
)
MODULE_SETTINGS_VALIDATOR = Draft7Validator(
{
"properties": {
"artifact_type": {"type": "string"},
"typeName": {"type": "string", "pattern": TYPE_NAME_MODULE_REGEX},
"settings": {"type": "object"},
},
"required": ["artifact_type", "typeName"],
}
)
HOOK_SETTINGS_VALIDATOR = Draft7Validator(
{
"properties": {
"artifact_type": {"type": "string"},
"language": {"type": "string"},
"typeName": {"type": "string", "pattern": TYPE_NAME_HOOK_REGEX},
"runtime": {"type": "string"},
"entrypoint": {"type": ["string", "null"]},
"testEntrypoint": {"type": ["string", "null"]},
"settings": {"type": "object"},
},
"required": ["language", "typeName", "runtime", "entrypoint"],
}
)
BASIC_TYPE_MAPPINGS = {
"string": "String",
"number": "Double",
"integer": "Integer",
"boolean": "Boolean",
}
MARKDOWN_RESERVED_CHARACTERS = frozenset({"^", "*", "+", ".", "(", "[", "{", "#"})
def escape_markdown(string):
"""Escapes the reserved Markdown characters."""
if not string:
return string
if string[0] in MARKDOWN_RESERVED_CHARACTERS:
return f"\\{string}"
return string
class Project: # pylint: disable=too-many-instance-attributes,too-many-public-methods
def __init__(self, overwrite_enabled=False, root=None):
self.overwrite_enabled = overwrite_enabled
self.root = Path(root) if root else Path.cwd()
self.settings_path = self.root / SETTINGS_FILENAME
self.type_info = None
self.artifact_type = None
self.language = None
self._plugin = None
self.settings = None
self.schema = None
self.configuration_schema = None
self._flattened_schema = None
self._marked_down_properties = {}
self.runtime = "noexec"
self.entrypoint = None
self.test_entrypoint = None
self.executable_entrypoint = None
self.fragment_dir = None
self.canary_settings = {}
self.target_info = {}
self.env = Environment(
trim_blocks=True,
lstrip_blocks=True,
keep_trailing_newline=True,
loader=PackageLoader(__name__, "templates/"),
autoescape=select_autoescape(["html", "htm", "xml", "md"]),
)
self.env.filters["escape_markdown"] = escape_markdown
LOG.debug("Root directory: %s", self.root)
@property
def type_name(self):
return "::".join(self.type_info)
@type_name.setter
def type_name(self, value):
self.type_info = tuple(value.split("::"))
@property
def hypenated_name(self):
return "-".join(self.type_info).lower()
@property
def hyphenated_name_case_sensitive(self):
return "-".join(self.type_info)
@property
def schema_filename(self):
return f"{self.hypenated_name}.json"
@property
def configuration_schema_filename(self):
return f"{self.hypenated_name}-configuration.json"
@property
def schema_path(self):
return self.root / self.schema_filename
@property
def overrides_path(self):
return self.root / OVERRIDES_FILENAME
@property
def inputs_path(self):
return self.root / INPUTS_FOLDER
@property
def example_inputs_path(self):
return self.root / EXAMPLE_INPUTS_FOLDER
@property
def target_schemas_path(self):
return self.root / TARGET_SCHEMAS_FOLDER
@property
def target_info_path(self):
return self.root / TARGET_INFO_FILENAME
@property
def target_canary_root_path(self):
return self.root / TARGET_CANARY_ROOT_FOLDER
@property
def target_canary_folder_path(self):
return self.root / TARGET_CANARY_FOLDER
@property
def rpdk_config(self):
return self.root / RPDK_CONFIG_FILE
@property
def file_generation_enabled(self):
if self.canary_settings == {}:
return False
return True
@property
def contract_test_file_names(self):
return self.canary_settings.get(CONTRACT_TEST_FILE_NAMES, [INPUT1_FILE_NAME])
@property
def target_contract_test_folder_path(self):
return self.root / CONTRACT_TEST_FOLDER
@staticmethod
def _raise_invalid_project(msg, e):
LOG.debug(msg, exc_info=e)
raise InvalidProjectError(msg) from e
def load_settings(self):
LOG.debug("Loading project file '%s'", self.settings_path)
try:
with self.settings_path.open("r", encoding="utf-8") as f:
raw_settings = json.load(f)
except json.JSONDecodeError as e:
self._raise_invalid_project(
f"Project file '{self.settings_path}' is invalid", e
)
# check size of RPDK config
if len(json.dumps(raw_settings).encode("utf-8")) > MAX_RPDK_CONFIG_LENGTH:
raise InvalidProjectError(
f"Project file '{self.settings_path}' exceeds maximum length of 10 KiB."
)
# validate protocol version, if specified
if "settings" in raw_settings and "protocolVersion" in raw_settings["settings"]:
protocol_version = raw_settings["settings"]["protocolVersion"]
if protocol_version not in PROTOCOL_VERSION_VALUES:
raise InvalidProjectError(
f"Invalid 'protocolVersion' settings in '{self.settings_path}"
)
else:
LOG.warning(
"No protovolVersion found: this will default to version 1.0.0 during registration. "
"Please consider upgrading to CFN-CLI 2.0 following the guide: "
"https://docs.aws.amazon.com/cloudformation-cli/latest/userguide/what-is-cloudformation-cli.html"
)
# backward compatible
if "artifact_type" not in raw_settings:
raw_settings["artifact_type"] = ARTIFACT_TYPE_RESOURCE
if raw_settings["artifact_type"] == ARTIFACT_TYPE_RESOURCE:
self.validate_and_load_resource_settings(raw_settings)
elif raw_settings["artifact_type"] == ARTIFACT_TYPE_HOOK:
self.validate_and_load_hook_settings(raw_settings)
else:
self.validate_and_load_module_settings(raw_settings)
def validate_and_load_hook_settings(self, raw_settings):
try:
HOOK_SETTINGS_VALIDATOR.validate(raw_settings)
except ValidationError as e:
self._raise_invalid_project(
f"Project file '{self.settings_path}' is invalid", e
)
self.type_name = raw_settings["typeName"]
self.artifact_type = raw_settings["artifact_type"]
self.language = raw_settings["language"]
self.runtime = raw_settings["runtime"]
self.entrypoint = raw_settings["entrypoint"]
self.test_entrypoint = raw_settings["testEntrypoint"]
self.executable_entrypoint = raw_settings.get("executableEntrypoint")
self._plugin = load_plugin(raw_settings["language"])
self.settings = raw_settings.get("settings", {})
def validate_and_load_module_settings(self, raw_settings):
try:
MODULE_SETTINGS_VALIDATOR.validate(raw_settings)
except ValidationError as e:
self._raise_invalid_project(
f"Project file '{self.settings_path}' is invalid", e
)
self.type_name = raw_settings["typeName"]
self.artifact_type = raw_settings["artifact_type"]
self.settings = raw_settings.get("settings", {})
def validate_and_load_resource_settings(self, raw_settings):
try:
SETTINGS_VALIDATOR.validate(raw_settings)
except ValidationError as e:
self._raise_invalid_project(
f"Project file '{self.settings_path}' is invalid", e
)
self.type_name = raw_settings["typeName"]
self.artifact_type = raw_settings["artifact_type"]
self.language = raw_settings["language"]
self.runtime = raw_settings["runtime"]
self.entrypoint = raw_settings["entrypoint"]
self.test_entrypoint = raw_settings["testEntrypoint"]
self.executable_entrypoint = raw_settings.get("executableEntrypoint")
self._plugin = load_plugin(raw_settings["language"])
self.settings = raw_settings.get("settings", {})
self.canary_settings = raw_settings.get("canarySettings", {})
def _write_example_schema(self):
self.schema = resource_json(
__name__, "data/examples/resource/initech.tps.report.v1.json"
)
self.schema["typeName"] = self.type_name
def _write(f):
json.dump(self.schema, f, indent=4)
f.write("\n")
self.safewrite(self.schema_path, _write)
def _write_example_hook_schema(self):
self.schema = resource_json(
__name__, "data/examples/hook/sse.verification.v1.json"
)
self.schema["typeName"] = self.type_name
def _write(f):
json.dump(self.schema, f, indent=4)
f.write("\n")
self.safewrite(self.schema_path, _write)
def _write_example_inputs(self):
shutil.rmtree(self.example_inputs_path, ignore_errors=True)
self.example_inputs_path.mkdir(exist_ok=True)
template = self.env.get_template("inputs.json")
properties = list(self.schema["properties"].keys())
for inputs_file in (
"inputs_1_create.json",
"inputs_1_update.json",
"inputs_1_invalid.json",
):
self.safewrite(
self.example_inputs_path / inputs_file,
template.render(
properties=properties[:-1], last_property=properties[-1]
),
)
def write_settings(self):
def _write_resource_settings(f):
executable_entrypoint_dict = (
{"executableEntrypoint": self.executable_entrypoint}
if self.executable_entrypoint
else {}
)
json.dump(
{
"artifact_type": self.artifact_type,
"typeName": self.type_name,
"language": self.language,
"runtime": self.runtime,
"entrypoint": self.entrypoint,
"testEntrypoint": self.test_entrypoint,
"settings": self.settings,
**executable_entrypoint_dict,
"canarySettings": self.canary_settings,
},
f,
indent=4,
)
f.write("\n")
def _write_module_settings(f):
json.dump(
{
"artifact_type": self.artifact_type,
"typeName": self.type_name,
"settings": self.settings,
},
f,
indent=4,
)
f.write("\n")
def _write_hook_settings(f):
executable_entrypoint_dict = (
{"executableEntrypoint": self.executable_entrypoint}
if self.executable_entrypoint
else {}
)
json.dump(
{
"artifact_type": self.artifact_type,
"typeName": self.type_name,
"language": self.language,
"runtime": self.runtime,
"entrypoint": self.entrypoint,
"testEntrypoint": self.test_entrypoint,
"settings": self.settings,
**executable_entrypoint_dict,
},
f,
indent=4,
)
f.write("\n")
if self.artifact_type == ARTIFACT_TYPE_RESOURCE:
self.overwrite(self.settings_path, _write_resource_settings)
elif self.artifact_type == ARTIFACT_TYPE_HOOK:
self.overwrite(self.settings_path, _write_hook_settings)
else:
self.overwrite(self.settings_path, _write_module_settings)
def init(self, type_name, language, settings=None):
self.artifact_type = ARTIFACT_TYPE_RESOURCE
self.type_name = type_name
self.language = language
self._plugin = load_plugin(language)
self.settings = settings or {}
self.canary_settings = {
CONTRACT_TEST_FILE_NAMES: [INPUT1_FILE_NAME],
}
self._write_example_schema()
self._write_example_inputs()
self._plugin.init(self)
self.write_settings()
def init_module(self, type_name):
self.artifact_type = ARTIFACT_TYPE_MODULE
self.type_name = type_name
self.settings = {}
self.write_settings()
def init_hook(self, type_name, language, settings=None):
self.artifact_type = ARTIFACT_TYPE_HOOK
self.type_name = type_name
self.language = language
self._plugin = load_plugin(language)
self.settings = settings or {}
self._write_example_hook_schema()
self._plugin.init(self)
self.write_settings()
def load_hook_schema(self):
if not self.type_info:
msg = "Internal error (Must load settings first)"
LOG.critical(msg)
raise InternalError(msg)
with self.schema_path.open("r", encoding="utf-8") as f:
self.schema = load_hook_spec(f)
def load_schema(self):
if not self.type_info:
msg = "Internal error (Must load settings first)"
LOG.critical(msg)
raise InternalError(msg)
with self.schema_path.open("r", encoding="utf-8") as f:
self.schema = load_resource_spec(f)
def load_configuration_schema(self):
if not self.schema:
msg = "Internal error (Must load type schema first)"
LOG.critical(msg)
raise InternalError(msg)
if "typeConfiguration" in self.schema:
configuration_schema = self.schema["typeConfiguration"]
configuration_schema["definitions"] = self.schema.get("definitions", {})
configuration_schema["typeName"] = self.type_name
self.configuration_schema = configuration_schema
def write_configuration_schema(self, path):
LOG.debug(
"Writing type configuration resource specification from resource"
" specification: %s",
path,
)
def _write(f):
json.dump(self.configuration_schema, f, indent=4)
f.write("\n")
self.overwrite(path, _write)
@staticmethod
def overwrite(path, contents):
LOG.debug("Overwriting '%s'", path)
with path.open("w", encoding="utf-8") as f:
if callable(contents):
contents(f)
else:
f.write(contents)
def safewrite(self, path, contents):
if self.overwrite_enabled:
self.overwrite(path, contents)
else:
try:
with path.open("x", encoding="utf-8") as f:
if callable(contents):
contents(f)
else:
f.write(contents)
except FileExistsError:
LOG.info("File already exists, not overwriting '%s'", path)
def generate(
self,
endpoint_url=None,
region_name=None,
local_only=False,
target_schemas=None,
profile_name=None,
): # pylint: disable=too-many-arguments
if self.artifact_type == ARTIFACT_TYPE_MODULE:
return # for Modules, the schema is already generated in cfn validate
# generate template for IAM role assumed by cloudformation
# to provision resources if schema has handlers defined
if "handlers" in self.schema:
handlers = self.schema["handlers"]
permission = "Allow"
if self.artifact_type == ARTIFACT_TYPE_HOOK:
template = self.env.get_template("hook-role.yml")
path = self.root / HOOK_ROLE_TEMPLATE_FILENAME
else:
template = self.env.get_template("resource-role.yml")
path = self.root / RESOURCE_ROLE_TEMPLATE_FILENAME
LOG.debug("Writing Execution Role CloudFormation template: %s", path)
actions = {
action
for handler in handlers.values()
for action in handler.get("permissions", [])
}
# calculate IAM role max session timeout based on highest handler timeout
# with some buffer (70 seconds per minute)
max_handler_timeout = max(
(
handler.get("timeoutInMinutes", DEFAULT_ROLE_TIMEOUT_MINUTES)
for operation, handler in handlers.items()
),
default=DEFAULT_ROLE_TIMEOUT_MINUTES,
)
# max role session timeout must be between 1 hour and 12 hours
role_session_timeout = min(
MAX_ROLE_TIMEOUT_SECONDS,
max(MIN_ROLE_TIMEOUT_SECONDS, 70 * max_handler_timeout),
)
# gets rid of any empty string actions.
# Empty strings cannot be specified as an action in an IAM statement
actions.discard("")
# Check if handler has actions
if not actions:
actions.add("*")
permission = "Deny"
contents = template.render(
type_name=self.hyphenated_name_case_sensitive,
actions=sorted(actions),
permission=permission,
role_session_timeout=role_session_timeout,
)
self.overwrite(path, contents)
self.target_info = self._load_target_info(
endpoint_url,
region_name,
type_schemas=target_schemas,
local_only=local_only,
profile_name=profile_name,
)
self._plugin.generate(self)
def load(self):
try:
self.load_settings()
except FileNotFoundError as e:
self._raise_invalid_project(
f"Project file {self.settings_path} not found. Have you run 'init' or"
" in a wrong directory?",
e,
)
if self.artifact_type == ARTIFACT_TYPE_MODULE:
self._load_modules_project()
elif self.artifact_type == ARTIFACT_TYPE_HOOK:
self._load_hooks_project()
else:
self._load_resources_project()
def _load_resources_project(self):
LOG.info("Validating your resource specification...")
try:
self.load_schema()
self.load_configuration_schema()
LOG.warning("Resource schema is valid.")
except FileNotFoundError as e:
self._raise_invalid_project("Resource schema not found.", e)
except SpecValidationError as e:
msg = "Resource schema is invalid: " + str(e)
self._raise_invalid_project(msg, e)
LOG.info("Validating your resource schema...")
def _load_modules_project(self):
LOG.info("Validating your module fragments...")
template_fragment = TemplateFragment(self.type_name, self.root)
try:
self._validate_fragments(template_fragment)
except FragmentValidationError as e:
msg = "Invalid template fragment: " + str(e)
self._raise_invalid_project(msg, e)
self.schema = template_fragment.generate_schema()
self.fragment_dir = template_fragment.fragment_dir
def _load_hooks_project(self):
LOG.info("Validating your hook specification...")
try:
self.load_hook_schema()
self.load_configuration_schema()
except FileNotFoundError as e:
self._raise_invalid_project("Hook specification not found.", e)
except SpecValidationError as e:
msg = "Hook specification is invalid: " + str(e)
self._raise_invalid_project(msg, e)
def _add_modules_content_to_zip(self, zip_file):
if not os.path.exists(self.root / SCHEMA_UPLOAD_FILENAME):
msg = "Module schema could not be found"
raise InternalError(msg)
zip_file.write(self.root / SCHEMA_UPLOAD_FILENAME, SCHEMA_UPLOAD_FILENAME)
file = _get_fragment_file(self.fragment_dir)
zip_file.write(
file,
arcname=file.replace(str(self.fragment_dir), "fragments/"),
)
@staticmethod
def _validate_fragments(template_fragment):
template_fragment.validate_fragments()
def submit(
self,
dry_run,
endpoint_url,
region_name,
role_arn,
use_role,
set_default,
profile_name,
): # pylint: disable=too-many-arguments
context_mgr = self._create_context_manager(dry_run)
with context_mgr as f:
# the default compression is ZIP_STORED, which helps with the
# file-size check on upload
args = {}
if sys.version_info >= (3, 8):
args = {"strict_timestamps": False}
with zipfile.ZipFile(f, mode="w", **args) as zip_file:
if self.configuration_schema:
with zip_file.open(
CONFIGURATION_SCHEMA_UPLOAD_FILENAME, "w"
) as configuration_file:
configuration_file.write(
json.dumps(self.configuration_schema, indent=4).encode(
"utf-8"
)
)
zip_file.write(self.settings_path, SETTINGS_FILENAME)
if self.artifact_type == ARTIFACT_TYPE_MODULE:
self._add_modules_content_to_zip(zip_file)
elif self.artifact_type == ARTIFACT_TYPE_HOOK:
self._add_hooks_content_to_zip(
zip_file, endpoint_url, region_name, profile_name
)
else:
self._add_resources_content_to_zip(zip_file)
self._add_overrides_file_to_zip(zip_file)
if dry_run:
LOG.error("Dry run complete: %s", self._get_zip_file_path().resolve())
else:
f.seek(0)
self._upload(
f,
endpoint_url,
region_name,
role_arn,
use_role,
set_default,
profile_name,
)
def _add_overrides_file_to_zip(self, zip_file):
try:
zip_file.write(self.overrides_path, OVERRIDES_FILENAME)
LOG.debug("%s found. Writing to package.", OVERRIDES_FILENAME)
except FileNotFoundError:
LOG.debug("%s not found. Not writing to package.", OVERRIDES_FILENAME)
def _add_resources_content_to_zip(self, zip_file):
zip_file.write(self.schema_path, SCHEMA_UPLOAD_FILENAME)
if os.path.isdir(self.inputs_path):
for filename in os.listdir(self.inputs_path):
absolute_path = self.inputs_path / filename
zip_file.write(absolute_path, INPUTS_FOLDER + "/" + filename)
LOG.debug("%s found. Writing to package.", filename)
else:
LOG.debug("%s not found. Not writing to package.", INPUTS_FOLDER)
self._plugin.package(self, zip_file)
cli_metadata = {}
try:
cli_metadata = self._plugin.get_plugin_information(self)
except AttributeError:
LOG.debug(
"Version info is not available for plugins, not writing to metadata"
" file"
)
cli_metadata["cli-version"] = __version__
zip_file.writestr(CFN_METADATA_FILENAME, json.dumps(cli_metadata))
def _add_hooks_content_to_zip(
self, zip_file, endpoint_url=None, region_name=None, profile_name=None
):
zip_file.write(self.schema_path, SCHEMA_UPLOAD_FILENAME)
if os.path.isdir(self.inputs_path):
for filename in os.listdir(self.inputs_path):
absolute_path = self.inputs_path / filename
zip_file.write(absolute_path, INPUTS_FOLDER + "/" + filename)
LOG.debug("%s found. Writing to package.", filename)
else:
LOG.debug("%s not found. Not writing to package.", INPUTS_FOLDER)
target_info = {}
try:
target_info = (
self.target_info
if self.target_info
else self._load_target_info(
endpoint_url, region_name, profile_name=profile_name
)
)
except RPDKBaseException as e:
LOG.warning("Failed to load target info, attempting local...", exc_info=e)
try:
target_info = self._load_target_info(None, None, local_only=True)
except RPDKBaseException as ex:
LOG.warning("Failed to load target info, ignoring...", exc_info=ex)
if target_info:
zip_file.writestr(TARGET_INFO_FILENAME, json.dumps(target_info, indent=4))
for target_name, info in target_info.items():
filename = f'{"-".join(s.lower() for s in target_name.split("::"))}.json'
content = json.dumps(info.get("Schema", {}), indent=4).encode("utf-8")
zip_file.writestr(TARGET_SCHEMAS_FOLDER + "/" + filename, content)
LOG.debug("%s found. Writing to package.", filename)
self._plugin.package(self, zip_file)
cli_metadata = {}
try:
cli_metadata = self._plugin.get_plugin_information(self)
except AttributeError:
LOG.debug(
"Version info is not available for plugins, not writing to metadata"
" file"
)
cli_metadata["cli-version"] = __version__
zip_file.writestr(CFN_METADATA_FILENAME, json.dumps(cli_metadata))
# pylint: disable=R1732
def _create_context_manager(self, dry_run):
# if it's a dry run, keep the file; otherwise can delete after upload
if dry_run:
return self._get_zip_file_path().open("wb")
return TemporaryFile("w+b")
def _get_zip_file_path(self):
return Path(f"{self.hypenated_name}.zip")
def generate_docs(self):
if self.artifact_type == ARTIFACT_TYPE_MODULE:
return
# generate the docs folder that contains documentation based on the schema
docs_path = self.root / "docs"
docs_attribute = (
self.configuration_schema
if self.artifact_type == ARTIFACT_TYPE_HOOK
else self.schema
)
if (
not self.type_info
or not docs_attribute
or "properties" not in docs_attribute
):
LOG.warning(
"Could not generate schema docs due to missing type info or schema"
)
return
target_names = (
self.target_info.keys()
if self.target_info
else (
{
target_name
for handler in self.schema.get("handlers", {}).values()
for target_name in handler.get("targetNames", [])
}
if self.artifact_type == ARTIFACT_TYPE_HOOK
else []
)
)
LOG.debug("Removing generated docs: %s", docs_path)
shutil.rmtree(docs_path, ignore_errors=True)
docs_path.mkdir(exist_ok=True)
LOG.debug("Writing generated docs")
# take care not to modify the master schema
docs_schema = json.loads(json.dumps(docs_attribute))
self._flattened_schema = JsonSchemaFlattener(
json.loads(json.dumps(docs_attribute))
).flatten_schema()
docs_schema["properties"] = {
name: self._set_docs_properties(name, value, (name,))
for name, value in self._flattened_schema[()]["properties"].items()
}
LOG.debug("Finished documenting nested properties")
ref = self._get_docs_primary_identifier(docs_schema)
getatt = self._get_docs_gettable_atts(docs_schema)
readme_path = docs_path / "README.md"
LOG.debug("Writing docs README: %s", readme_path)
readme_template = (
"hook-docs-readme.md"
if self.artifact_type == ARTIFACT_TYPE_HOOK
else "docs-readme.md"
)
template = self.env.get_template(readme_template)
contents = template.render(
type_name=self.type_name,
schema=docs_schema,
ref=ref,
getatt=getatt,
target_names=sorted(target_names),
)
self.safewrite(readme_path, contents)
def generate_image_build_config(self):
if not hasattr(self._plugin, "generate_image_build_config"):
raise InvalidProjectError(
f"Plugin for the {self.runtime} runtime does not support building an"
" image"
)
return self._plugin.generate_image_build_config(self)
@staticmethod
def _get_docs_primary_identifier(docs_schema):
try:
primary_id = docs_schema["primaryIdentifier"]
if len(primary_id) == 1:
# drop /properties
primary_id_path = fragment_decode(primary_id[0], prefix="")[1:]
# at some point, someone might use a nested primary ID
if len(primary_id_path) == 1:
return primary_id_path[0]
LOG.warning("Nested primaryIdentifier found")
except (KeyError, ValueError):
pass
return None
@staticmethod
def _get_docs_gettable_atts(docs_schema):
def _get_property_description(prop):
path = fragment_decode(prop, prefix="")
name = path[-1]
try:
desc, _resolved_path, _parent = traverse(
docs_schema, path + ("description",)
)
except (KeyError, IndexError, ValueError):
desc = f"Returns the <code>{name}</code> value."
return {"name": name, "description": desc}
return [
_get_property_description(prop)
for prop in docs_schema.get("readOnlyProperties", [])
]
def _set_docs_properties( # noqa: C901
self, propname, prop, proppath
): # pylint: disable=too-many-locals,too-many-statements
"""method sets markdown for each property;
1. Supports multiple types per property - done via flattened schema so `allOf`,
`anyOf`, `oneOf` combined into a collection then method iterates to reapply
itself to each type
2. Supports circular reference - done via pre calculating hypothetical .md file
path and name
which is reused once property is hit more than once
Args:
propname ([str]): property name
prop ([dict]): all the sub propeties
proppath ([tuple]): path of the property
Returns:
[dict]: modified sub dictionary with attached markdown
"""
types = ("jsontype", "yamltype", "longformtype")
jsontype, yamltype, longformtype = types
# reattach prop from reference
if "$ref" in prop:
ref = self._flattened_schema[prop["$ref"]]
propname = prop["$ref"][1]
# this is to tie object to a definition and not to a property
proppath = (propname,)
prop = ref
# this means method is traversing already visited property
if propname in self._marked_down_properties:
return {
property_item: markdown
for property_item, markdown in self._marked_down_properties[
propname
].items()
if property_item in types
} # returning already set markdown