-
Notifications
You must be signed in to change notification settings - Fork 69
/
content_artifacts_creator.py
1824 lines (1554 loc) · 65.1 KB
/
content_artifacts_creator.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 os
import re
import sys
import time
from concurrent.futures import as_completed
from contextlib import contextmanager
from shutil import make_archive, rmtree
from typing import Callable, Dict, List, Optional, Union
from packaging.version import parse
from pebble import ProcessFuture, ProcessPool
from wcmatch.pathlib import BRACE, EXTMATCH, NEGATE, NODIR, SPLIT, Path
from demisto_sdk.commands.common.constants import (
BASE_PACK,
CLASSIFIERS_DIR,
CONTENT_ITEMS_DISPLAY_FOLDERS,
CORRELATION_RULES_DIR,
DASHBOARDS_DIR,
DOCUMENTATION_DIR,
GENERIC_DEFINITIONS_DIR,
GENERIC_FIELDS_DIR,
GENERIC_MODULES_DIR,
GENERIC_TYPES_DIR,
INCIDENT_FIELDS_DIR,
INCIDENT_TYPES_DIR,
INDICATOR_FIELDS_DIR,
INDICATOR_TYPES_DIR,
INTEGRATIONS_DIR,
JOBS_DIR,
LAYOUT_RULES_DIR,
LAYOUTS_DIR,
LISTS_DIR,
MODELING_RULES_DIR,
PACKS_DIR,
PARSING_RULES_DIR,
PLAYBOOKS_DIR,
PRE_PROCESS_RULES_DIR,
RELEASE_NOTES_DIR,
REPORTS_DIR,
SCRIPTS_DIR,
TEST_PLAYBOOKS_DIR,
TOOLS_DIR,
TRIGGER_DIR,
WIDGETS_DIR,
WIZARDS_DIR,
XDRC_TEMPLATE_DIR,
XSIAM_DASHBOARDS_DIR,
XSIAM_REPORTS_DIR,
ContentItems,
FileType,
MarketplaceVersions,
)
from demisto_sdk.commands.common.content import (
Content,
ContentError,
ContentFactoryError,
Pack,
)
from demisto_sdk.commands.common.content.objects.abstract_objects.text_object import (
TextObject,
)
from demisto_sdk.commands.common.content.objects.pack_objects import (
JSONContentObject,
Script,
YAMLContentObject,
YAMLContentUnifiedObject,
)
from demisto_sdk.commands.common.logger import logger
from demisto_sdk.commands.common.tools import arg_to_list, open_id_set_file
from .artifacts_report import ArtifactsReport, ObjectReport
####################
# Global variables #
####################
FIRST_MARKETPLACE_VERSION = parse("6.0.0")
IGNORED_PACKS = ["ApiModules"]
IGNORED_TEST_PLAYBOOKS_DIR = "Deprecated"
ContentObject = Union[
YAMLContentUnifiedObject, YAMLContentObject, JSONContentObject, TextObject
]
EX_SUCCESS = 0
EX_FAIL = 1
XSOAR_MARKETPLACE_ITEMS_TO_DUMP = [
FileType.CLASSIFIER,
FileType.CONNECTION,
FileType.INCIDENT_FIELD,
FileType.INCIDENT_TYPE,
FileType.INDICATOR_FIELD,
FileType.INDICATOR_TYPE,
FileType.INTEGRATION,
FileType.JOB,
FileType.LAYOUT,
FileType.LISTS,
FileType.PLAYBOOK,
FileType.SCRIPT,
FileType.TEST_PLAYBOOK,
FileType.RELEASE_NOTES,
FileType.RELEASE_NOTES_CONFIG,
FileType.WIZARD,
FileType.DASHBOARD,
FileType.GENERIC_DEFINITION,
FileType.GENERIC_MODULE,
FileType.GENERIC_TYPE,
FileType.GENERIC_FIELD,
FileType.PRE_PROCESS_RULES,
FileType.REPORT,
FileType.WIDGET,
FileType.TOOL,
FileType.PACK_METADATA,
FileType.METADATA,
FileType.README,
FileType.AUTHOR_IMAGE,
]
XSIAM_MARKETPLACE_ITEMS_TO_DUMP = [
FileType.CLASSIFIER,
FileType.CONNECTION,
FileType.INCIDENT_FIELD,
FileType.INCIDENT_TYPE,
FileType.INDICATOR_FIELD,
FileType.INDICATOR_TYPE,
FileType.INTEGRATION,
FileType.JOB,
FileType.LAYOUT,
FileType.LISTS,
FileType.PLAYBOOK,
FileType.SCRIPT,
FileType.TEST_PLAYBOOK,
FileType.RELEASE_NOTES,
FileType.RELEASE_NOTES_CONFIG,
FileType.WIZARD,
FileType.PARSING_RULE,
FileType.MODELING_RULE,
FileType.CORRELATION_RULE,
FileType.XSIAM_DASHBOARD,
FileType.XSIAM_REPORT,
FileType.TRIGGER,
FileType.XDRC_TEMPLATE,
FileType.TOOL,
FileType.PACK_METADATA,
FileType.METADATA,
FileType.README,
FileType.AUTHOR_IMAGE,
FileType.LAYOUT_RULE,
]
XPANSE_MARKETPLACE_ITEMS_TO_DUMP = [
FileType.INCIDENT_FIELD,
FileType.INCIDENT_TYPE,
FileType.INTEGRATION,
FileType.PLAYBOOK,
FileType.SCRIPT,
FileType.RELEASE_NOTES,
FileType.RELEASE_NOTES_CONFIG,
FileType.PACK_METADATA,
FileType.METADATA,
FileType.README,
FileType.AUTHOR_IMAGE,
]
MARKETPLACE_TO_ITEMS_MAPPING = {
MarketplaceVersions.XSOAR.value: XSOAR_MARKETPLACE_ITEMS_TO_DUMP,
MarketplaceVersions.XSOAR_SAAS.value: XSOAR_MARKETPLACE_ITEMS_TO_DUMP,
MarketplaceVersions.MarketplaceV2.value: XSIAM_MARKETPLACE_ITEMS_TO_DUMP,
MarketplaceVersions.XPANSE.value: XPANSE_MARKETPLACE_ITEMS_TO_DUMP,
}
##############
# Main logic #
##############
class ArtifactsManager:
def __init__(
self,
artifacts_path: str,
zip: bool,
packs: bool,
content_version: str,
suffix: str,
cpus: int,
marketplace: str = MarketplaceVersions.XSOAR.value,
id_set_path: str = "",
pack_names: str = "all",
signature_key: str = "",
sign_directory: Path = None,
remove_test_playbooks: bool = True,
filter_by_id_set: bool = False,
alternate_fields: bool = False,
**kwargs,
):
"""Content artifacts configuration
Args:
artifacts_path: existing destination directory for creating artifacts.
zip: True for zip all content artifacts to 3 different zip files in same structure else False.
packs: create only content_packs artifacts if True.
content_version: release content version.
suffix: suffix to add all file we creates.
cpus: available cpus in the computer.
marketplace: The marketplace the artifacts are created for. deafults is xsoar marketplace.
id_set_path: the full path of id_set.json.
pack_names: Packs to create artifacts for.
signature_key: Base64 encoded signature key used for signing packs.
sign_directory: Path to the signDirectory executable file.
remove_test_playbooks: Should remove test playbooks from content packs or not.
"""
# options arguments
self.artifacts_path = Path(artifacts_path)
self.zip_artifacts = zip
self.only_content_packs = packs
self.content_version = content_version
self.suffix = suffix
self.cpus = cpus
self.id_set_path = id_set_path
self.id_set: dict = {}
self.signature_key = signature_key
self.signDirectory = sign_directory
self.remove_test_playbooks = remove_test_playbooks
self.marketplace = marketplace.lower()
self.filter_by_id_set = filter_by_id_set
self.pack_names = arg_to_list(pack_names)
self.packs_section_from_id_set: dict = {}
self.alternate_fields = alternate_fields
# run related arguments
self.content_new_path = self.artifacts_path / "content_new"
self.content_test_path = self.artifacts_path / "content_test"
self.content_packs_path = self.artifacts_path / "content_packs"
self.content_all_path = self.artifacts_path / "all_content"
self.content_uploadable_zips_path = self.artifacts_path / "uploadable_packs"
if self.filter_by_id_set or self.alternate_fields:
self.id_set = open_id_set_file(id_set_path)
# inits
self.content = Content.from_cwd()
self.execution_start = time.time()
self.packs = self.content.packs
self.exit_code = EX_SUCCESS
if self.filter_by_id_set:
self.packs_section_from_id_set = self.id_set.get("Packs", {})
if self.pack_names == ["all"]:
self.pack_names = list(self.packs_section_from_id_set.keys())
else:
self.pack_names = list(
set(self.packs_section_from_id_set.keys()).intersection(
set(self.pack_names)
)
)
def create_content_artifacts(self) -> int:
with ArtifactsDirsHandler(self), ProcessPoolHandler(self) as pool:
futures: List[ProcessFuture] = []
# content/Packs
futures.extend(dump_packs(self, pool))
# content/TestPlaybooks
if not self.remove_test_playbooks:
futures.append(pool.schedule(dump_tests_conditionally, args=(self,)))
# content/content-descriptor.json
futures.append(pool.schedule(dump_content_descriptor, args=(self,)))
# content/Documentation/doc-*.json
futures.append(pool.schedule(dump_content_documentations, args=(self,)))
# Wait for all futures to be finished
wait_futures_complete(futures, self)
# Add suffix
suffix_handler(self)
Path("keyfile").unlink(missing_ok=True)
logger.info(f"\nExecution time: {time.time() - self.execution_start} seconds")
return self.exit_code
def get_relative_pack_path(self, content_object: ContentObject):
"""
Args:
content_object: the object to get the relative path for
Returns:
the path of the given object relative from the pack directory, for example HelloWorld/Scripts/some_script
"""
return content_object.path.relative_to(self.content.path / PACKS_DIR)
def get_base_path(self) -> Path:
"""
Returns:
the path that all artifacts are relative to
"""
return self.content.path
def get_dir_to_delete(self):
"""
Returns:
list of directories to delete after artifacts was created
"""
return [
self.content_test_path,
self.content_new_path,
self.content_packs_path,
self.content_all_path,
]
class ContentItemsHandler:
def __init__(self, id_set=None, alternate_fields=False):
self.server_min_version = parse("1.0.0")
self.content_items: Dict[ContentItems, List] = {
ContentItems.SCRIPTS: [],
ContentItems.PLAYBOOKS: [],
ContentItems.INTEGRATIONS: [],
ContentItems.INCIDENT_FIELDS: [],
ContentItems.INCIDENT_TYPES: [],
ContentItems.DASHBOARDS: [],
ContentItems.INDICATOR_FIELDS: [],
ContentItems.REPORTS: [],
ContentItems.INDICATOR_TYPES: [],
ContentItems.LAYOUTS: [],
ContentItems.PRE_PROCESS_RULES: [],
ContentItems.JOB: [],
ContentItems.CLASSIFIERS: [],
ContentItems.WIDGETS: [],
ContentItems.GENERIC_FIELDS: [],
ContentItems.GENERIC_TYPES: [],
ContentItems.GENERIC_MODULES: [],
ContentItems.GENERIC_DEFINITIONS: [],
ContentItems.LISTS: [],
ContentItems.PARSING_RULES: [],
ContentItems.MODELING_RULES: [],
ContentItems.CORRELATION_RULES: [],
ContentItems.XSIAM_DASHBOARDS: [],
ContentItems.XSIAM_REPORTS: [],
ContentItems.TRIGGERS: [],
ContentItems.WIZARDS: [],
ContentItems.XDRC_TEMPLATE: [],
ContentItems.LAYOUT_RULES: [],
}
self.content_folder_name_to_func: Dict[str, Callable] = {
SCRIPTS_DIR: self.add_script_as_content_item,
PLAYBOOKS_DIR: self.add_playbook_as_content_item,
INTEGRATIONS_DIR: self.add_integration_as_content_item,
INCIDENT_FIELDS_DIR: self.add_incident_field_as_content_item,
INCIDENT_TYPES_DIR: self.add_incident_type_as_content_item,
DASHBOARDS_DIR: self.add_dashboard_as_content_item,
INDICATOR_FIELDS_DIR: self.add_indicator_field_as_content_item,
INDICATOR_TYPES_DIR: self.add_indicator_type_as_content_item,
REPORTS_DIR: self.add_report_as_content_item,
LAYOUTS_DIR: self.add_layout_as_content_item,
PRE_PROCESS_RULES_DIR: self.add_pre_process_rules_as_content_item,
LISTS_DIR: self.add_lists_as_content_item,
JOBS_DIR: self.add_jobs_as_content_item,
CLASSIFIERS_DIR: self.add_classifier_as_content_item,
WIDGETS_DIR: self.add_widget_as_content_item,
GENERIC_TYPES_DIR: self.add_generic_type_as_content_item,
GENERIC_FIELDS_DIR: self.add_generic_field_as_content_item,
GENERIC_MODULES_DIR: self.add_generic_module_as_content_item,
GENERIC_DEFINITIONS_DIR: self.add_generic_definition_as_content_item,
PARSING_RULES_DIR: self.add_parsing_rule_as_content_item,
MODELING_RULES_DIR: self.add_modeling_rule_as_content_item,
CORRELATION_RULES_DIR: self.add_correlation_rule_as_content_item,
XSIAM_DASHBOARDS_DIR: self.add_xsiam_dashboard_as_content_item,
XSIAM_REPORTS_DIR: self.add_xsiam_report_as_content_item,
TRIGGER_DIR: self.add_trigger_as_content_item,
WIZARDS_DIR: self.add_wizards_as_content_item,
XDRC_TEMPLATE_DIR: self.add_xdrc_template_as_content_item,
LAYOUT_RULES_DIR: self.add_layout_rule_as_content_item,
}
self.id_set = id_set
self.alternate_fields = alternate_fields
def handle_content_item(self, content_object: ContentObject):
"""Verifies the validity of the content object and parses it to the correct entities list.
Args:
content_object (ContentObject): The object to add to entities list.
"""
content_object_directory = content_object.path.parts[-3]
if content_object_directory not in self.content_folder_name_to_func.keys():
# In the case where the content object is nested directly in the entities directory (Playbooks for example).
content_object_directory = content_object.path.parts[-2]
if content_object.to_version < FIRST_MARKETPLACE_VERSION:
return
# skip content items that are not displayed in contentItems
if content_object_directory not in CONTENT_ITEMS_DISPLAY_FOLDERS:
return
self.server_min_version = max(
self.server_min_version, content_object.from_version
)
self.content_folder_name_to_func[content_object_directory](content_object)
def add_script_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.SCRIPTS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("comment", ""),
"tags": content_object.get("tags", []),
}
)
def add_playbook_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.PLAYBOOKS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_integration_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.INTEGRATIONS].append(
{
"name": content_object.get("display", ""),
"description": content_object.get("description", ""),
"category": content_object.get("category", ""),
"commands": [
{
"name": command.get("name", ""),
"description": command.get("description", ""),
}
for command in content_object.script.get("commands", [])
],
}
)
def add_incident_field_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.INCIDENT_FIELDS].append(
{
"name": content_object.get("name", ""),
"type": content_object.get("type", ""),
"description": content_object.get("description", ""),
}
)
def add_incident_type_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.INCIDENT_TYPES].append(
{
"name": content_object.get("name", ""),
"playbook": content_object.get("playbookId", ""),
"closureScript": content_object.get("closureScript", ""),
"hours": int(content_object.get("hours", 0)),
"days": int(content_object.get("days", 0)),
"weeks": int(content_object.get("weeks", 0)),
}
)
def add_dashboard_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.DASHBOARDS].append(
{"name": content_object.get("name", "")}
)
def add_indicator_field_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.INDICATOR_FIELDS].append(
{
"name": content_object.get("name", ""),
"type": content_object.get("type", ""),
"description": content_object.get("description", ""),
}
)
def add_indicator_type_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.INDICATOR_TYPES].append(
{
"details": content_object.get("details", ""),
"reputationScriptName": content_object.get("reputationScriptName", ""),
"enhancementScriptNames": content_object.get(
"enhancementScriptNames", []
),
}
)
def add_report_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.REPORTS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_layout_as_content_item(self, content_object: ContentObject):
if content_object.get("description") is not None:
self.content_items[ContentItems.LAYOUTS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description"),
}
)
else:
self.content_items[ContentItems.LAYOUTS].append(
{"name": content_object.get("name", "")}
)
def add_pre_process_rules_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.PRE_PROCESS_RULES].append(
{
"name": content_object.get("name") or content_object.get("id", ""),
"description": content_object.get("description", ""),
}
)
def add_jobs_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.JOB].append(
{
"name": content_object.get("name") or content_object.get("id", ""),
"details": content_object.get("details", ""),
}
)
def add_lists_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.LISTS].append(
{"name": content_object.get("name") or content_object.get("id", "")}
)
def add_classifier_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.CLASSIFIERS].append(
{
"name": content_object.get("name") or content_object.get("id", ""),
"description": content_object.get("description", ""),
}
)
def add_widget_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.WIDGETS].append(
{
"name": content_object.get("name", ""),
"dataType": content_object.get("dataType", ""),
"widgetType": content_object.get("widgetType", ""),
}
)
def add_generic_field_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.GENERIC_FIELDS].append(
{
"name": content_object.get("name", ""),
"type": content_object.get("type", ""),
"description": content_object.get("description", ""),
}
)
def add_generic_type_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.GENERIC_TYPES].append(
{
"name": content_object.get("name", ""),
"details": content_object.get("details", ""),
}
)
def add_generic_definition_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.GENERIC_DEFINITIONS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_generic_module_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.GENERIC_MODULES].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_parsing_rule_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.PARSING_RULES].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_modeling_rule_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.MODELING_RULES].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_correlation_rule_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.CORRELATION_RULES].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_xsiam_dashboard_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.XSIAM_DASHBOARDS].append(
{
"name": content_object["dashboards_data"][0].get("name", ""),
"description": content_object["dashboards_data"][0].get(
"description", ""
),
}
)
def add_xsiam_report_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.XSIAM_REPORTS].append(
{
"name": content_object["templates_data"][0].get("report_name", ""),
"description": content_object["templates_data"][0].get(
"report_description", ""
),
}
)
def add_trigger_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.TRIGGERS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_wizards_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.WIZARDS].append(
{
"name": content_object.get("name", ""),
"description": content_object.get("description", ""),
}
)
def add_xdrc_template_as_content_item(self, content_object: ContentObject):
self.content_items[ContentItems.XDRC_TEMPLATE].append(
{
"name": content_object.get("name", ""),
"os_type": content_object.get("os_type", ""),
"profile_type": content_object.get("profile_type", ""),
}
)
def add_layout_rule_as_content_item(self, content_object: ContentObject):
if content_object.get("description") is not None:
self.content_items[ContentItems.LAYOUT_RULES].append(
{
"name": content_object.get("rule_name", ""),
"description": content_object.get("description"),
}
)
else:
self.content_items[ContentItems.LAYOUT_RULES].append(
{"name": content_object.get("rule_name", "")}
)
@contextmanager
def ProcessPoolHandler(artifact_manager: ArtifactsManager) -> ProcessPool:
"""Process pool Handler which terminate all processes in case of Exception.
Args:
artifact_manager: Artifacts manager object.
Yields:
ProcessPool: Pebble process pool.
"""
global logger
with ProcessPool(max_workers=artifact_manager.cpus, initializer=child_mute) as pool:
try:
yield pool
except KeyboardInterrupt:
logger.info(
"\nCTRL+C Pressed!\nGracefully release all resources due to keyboard interrupt..."
)
pool.stop()
pool.join()
raise
except Exception as e:
logger.exception(e)
logger.error("Gracefully release all resources due to Error...")
pool.stop()
pool.join()
raise
else:
pool.close()
pool.join()
finally:
Path("keyfile").unlink(missing_ok=True)
def wait_futures_complete(
futures: List[ProcessFuture], artifact_manager: ArtifactsManager
):
"""Wait for all futures to complete, Raise exception if occured.
Args:
artifact_manager: Artifacts manager object.
futures: futures to wait for.
Raises:
Exception: Raise caught exception for further cleanups.
"""
global logger
for future in as_completed(futures):
try:
result = future.result()
if isinstance(result, ArtifactsReport):
logger.info(result.to_str(artifact_manager.get_base_path()))
except (ContentError, DuplicateFiles, ContentFactoryError) as e:
logger.error(e.msg)
raise
except Exception as e:
logger.exception(e)
raise
#####################################################
# Files include rules functions (Version, Type etc) #
#####################################################
def is_in_content_packs(content_object: ContentObject) -> bool:
"""Rules content_packs:
1. to_version >= First marketplace version.
Args:
content_object: Content object as specified in global variable - ContentObject.
Returns:
bool: True if object should be included in content_packs artifacts else False.
"""
return content_object.to_version >= FIRST_MARKETPLACE_VERSION
def is_in_content_test(
artifact_manager: ArtifactsManager, content_object: ContentObject
) -> bool:
"""Rules content_test:
1. flag of only packs is off.
2. Object located in TestPlaybooks directory (*/TestPlaybooks/*).
3. from_version < First marketplace version.
4. Path of object is not including global variable - IGNORED_TEST_PLAYBOOKS_DIR
Args:
artifact_manager: Artifacts manager object.
content_object: Content object as specified in global variable - ContentObject.
Returns:
bool: True if object should be included in content_test artifacts else False.
"""
return (
not artifact_manager.only_content_packs
and TEST_PLAYBOOKS_DIR in content_object.path.parts
and content_object.from_version < FIRST_MARKETPLACE_VERSION
and IGNORED_TEST_PLAYBOOKS_DIR not in content_object.path.parts
)
def is_in_content_new(
artifact_manager: ArtifactsManager, content_object: ContentObject
) -> bool:
"""Rules content_new:
1. flag of only packs is off.
2. Object not located in TestPlaybooks directory (*/TestPlaybooks/*).
3. from_version < First marketplace version
Args:
artifact_manager: Artifacts manager object.
content_object: Content object as specified in global variable - ContentObject.
Returns:
bool: True if object should be included in content_new artifacts else False.
"""
return (
not artifact_manager.only_content_packs
and TEST_PLAYBOOKS_DIR not in content_object.path.parts
and content_object.from_version < FIRST_MARKETPLACE_VERSION
)
def is_in_content_all(
artifact_manager: ArtifactsManager, content_object: ContentObject
) -> bool:
"""Rules content_all:
1. If in content_new or content_test.
Args:
artifact_manager: Artifacts manager object.
content_object: Content object as specified in global variable - ContentObject.
Returns:
bool: True if object should be included in content_all artifacts else False.
"""
return is_in_content_new(artifact_manager, content_object) or is_in_content_test(
artifact_manager, content_object
)
############################
# Documentations functions #
############################
def dump_content_documentations(artifact_manager: ArtifactsManager) -> ArtifactsReport:
"""Dumping Documentation/doc-*.json into:
1. content_new
2. content_all
Args:
artifact_manager: Artifacts manager object.
Returns:
ArtifactsReport: ArtifactsReport object.
"""
report = ArtifactsReport("Documentations:")
for documentation in artifact_manager.content.documentations:
object_report = ObjectReport(documentation, content_packs=True)
created_files = documentation.dump(
artifact_manager.content_packs_path / BASE_PACK / DOCUMENTATION_DIR
)
if not artifact_manager.only_content_packs:
object_report.set_content_new()
object_report.set_content_all()
for dest in [
artifact_manager.content_new_path,
artifact_manager.content_all_path,
]:
created_files = dump_link_files(
artifact_manager, documentation, dest, created_files
)
report.append(object_report)
return report
########################
# Descriptor functions #
########################
def dump_content_descriptor(artifact_manager: ArtifactsManager) -> ArtifactsReport:
"""Dumping content/content_descriptor.json into:
1. content_test
2. content_new
3. content_all
Args:
artifact_manager: Artifacts manager object.
Returns:
ArtifactsReport: ArtifactsReport object.
Notes:
1. content_descriptor.json created during build run time.
"""
report = ArtifactsReport("Content descriptor:")
if (
not artifact_manager.only_content_packs
and artifact_manager.content.content_descriptor
):
descriptor = artifact_manager.content.content_descriptor
object_report = ObjectReport(
descriptor, content_test=True, content_new=True, content_all=True
)
created_files: List[Path] = []
for dest in [
artifact_manager.content_test_path,
artifact_manager.content_new_path,
artifact_manager.content_all_path,
]:
created_files = dump_link_files(
artifact_manager, descriptor, dest, created_files
)
report.append(object_report)
return report
##################################
# Content Testplaybook functions #
##################################
def dump_tests_conditionally(artifact_manager: ArtifactsManager) -> ArtifactsReport:
"""Dump test scripts/playbooks conditionally into:
1. content_test
Args:
artifact_manager: Artifacts manager object.
Returns:
ArtifactsReport: ArtifactsReport object.
"""
report = ArtifactsReport("TestPlaybooks:")
for test in artifact_manager.content.test_playbooks:
object_report = ObjectReport(test)
if is_in_content_test(artifact_manager, test):
object_report.set_content_test()
test_created_files = dump_link_files(
artifact_manager, test, artifact_manager.content_test_path
)
dump_link_files(
artifact_manager,
test,
artifact_manager.content_all_path,
test_created_files,
)
report += object_report
return report
###########################
# Content packs functions #
###########################
def dump_packs(
artifact_manager: ArtifactsManager, pool: ProcessPool
) -> List[ProcessFuture]:
"""Create futures which dumps conditionally content/Packs.
Args:
artifact_manager: Artifacts manager object.
pool: Process pool to schedule new processes.
Returns:
List[ProcessFuture]: List of pebble futures to wait for.
"""
futures = []
if "all" in artifact_manager.pack_names:
for pack_name, pack in artifact_manager.packs.items():
if pack_name not in IGNORED_PACKS:
futures.append(pool.schedule(dump_pack, args=(artifact_manager, pack)))
else:
for pack_name in artifact_manager.pack_names:
if pack_name not in IGNORED_PACKS and pack_name in artifact_manager.packs:
futures.append(
pool.schedule(
dump_pack,
args=(artifact_manager, artifact_manager.packs[pack_name]),
)
)
return futures
def handle_incident_field(
content_items_handler, pack, pack_report, artifact_manager, **kwargs
):
for incident_field in pack.incident_fields:
content_items_handler.handle_content_item(incident_field)
pack_report += dump_pack_conditionally(artifact_manager, incident_field)
def handle_integration(
content_items_handler, pack, pack_report, artifact_manager, is_feed_pack, **kwargs
):
for integration in pack.integrations:
content_items_handler.handle_content_item(integration)
is_feed_pack = is_feed_pack or integration.is_feed
pack_report += dump_pack_conditionally(artifact_manager, integration)
def handle_playbook(
content_items_handler, pack, pack_report, artifact_manager, is_feed_pack, **kwargs
):
for playbook in pack.playbooks:
content_items_handler.handle_content_item(playbook)
is_feed_pack = is_feed_pack or playbook.get("name", "").startswith("TIM")
pack_report += dump_pack_conditionally(artifact_manager, playbook)
def handle_script(content_items_handler, pack, pack_report, artifact_manager, **kwargs):
for script in pack.scripts:
content_items_handler.handle_content_item(script)
pack_report += dump_pack_conditionally(artifact_manager, script)
def handle_release_notes(pack, pack_report, artifact_manager, **kwargs):
for release_note in pack.release_notes:
pack_report += ObjectReport(release_note, content_packs=True)
release_note.dump(
artifact_manager.content_packs_path / pack.id / RELEASE_NOTES_DIR
)
def handle_release_note_config(pack, pack_report, artifact_manager, **kwargs):
for release_note_config in pack.release_notes_config:
pack_report += ObjectReport(release_note_config, content_packs=True)
release_note_config.dump(
artifact_manager.content_packs_path / pack.id / RELEASE_NOTES_DIR
)
def handle_classifier(
content_items_handler, pack, pack_report, artifact_manager, **kwargs
):
for classifier in pack.classifiers: