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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
|
/*
* Copyright © 2016-2018 European Support Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openecomp.sdc.translator.services.heattotosca;
import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FilenameUtils;
import org.onap.sdc.tosca.datatypes.model.AttributeDefinition;
import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
import org.onap.sdc.tosca.datatypes.model.Import;
import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
import org.onap.sdc.tosca.datatypes.model.NodeType;
import org.onap.sdc.tosca.datatypes.model.ParameterDefinition;
import org.onap.sdc.tosca.datatypes.model.PropertyDefinition;
import org.onap.sdc.tosca.datatypes.model.PropertyType;
import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
import org.onap.sdc.tosca.datatypes.model.Template;
import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
import org.onap.sdc.tosca.services.YamlUtil;
import org.openecomp.core.translator.api.HeatToToscaTranslator;
import org.openecomp.core.translator.datatypes.TranslatorOutput;
import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory;
import org.openecomp.core.utilities.file.FileContentHandler;
import org.openecomp.core.utilities.file.FileUtils;
import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
import org.openecomp.core.validation.util.MessageContainerUtil;
import org.openecomp.sdc.common.errors.CoreException;
import org.openecomp.sdc.common.togglz.ToggleableFeature;
import org.openecomp.sdc.common.utils.SdcCommon;
import org.openecomp.sdc.datatypes.error.ErrorLevel;
import org.openecomp.sdc.datatypes.error.ErrorMessage;
import org.openecomp.sdc.heat.datatypes.HeatBoolean;
import org.openecomp.sdc.heat.datatypes.manifest.FileData;
import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
import org.openecomp.sdc.heat.datatypes.model.Resource;
import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions;
import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
import org.openecomp.sdc.heat.services.HeatConstants;
import org.openecomp.sdc.heat.services.tree.HeatTreeManager;
import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil;
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType;
import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType;
import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
import org.openecomp.sdc.tosca.services.DataModelUtil;
import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
import org.openecomp.sdc.tosca.services.ToscaConstants;
import org.openecomp.sdc.tosca.services.ToscaUtil;
import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal;
import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId;
import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType;
import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext;
import org.openecomp.sdc.translator.datatypes.heattotosca.to.FileDataCollection;
import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo;
import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder;
import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator;
import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper;
import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator;
import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase;
import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter;
/**
* The type Heat to tosca util.
*/
public class HeatToToscaUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HeatToToscaUtil.class);
private static final String FQ_NAME = "fq_name";
private static final String GET_PARAM = "get_param";
private static final String GET_ATTR = "get_attr";
private static final String GET_RESOURCE = "get_resource";
private static final String UNDERSCORE = "_";
private static final String WORDS_REGEX = "(\\w+)";
private static final String PORT_RESOURCE_ID_REGEX_SUFFIX = "(_\\d+)*";
private static final String PORT_RESOURCE_ID_REGEX_PREFIX =
WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX;
private static final String PORT_INT_RESOURCE_ID_REGEX_PREFIX = PORT_RESOURCE_ID_REGEX_PREFIX
+ UNDERSCORE + "int_"+ WORDS_REGEX + UNDERSCORE;
private static final String SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX =
PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + "subint_"+ WORDS_REGEX + UNDERSCORE;
private static final String SUB_INTERFACE_REGEX = WORDS_REGEX + PORT_RESOURCE_ID_REGEX_SUFFIX
+ "_subint_(\\w_+)*vmi" + PORT_RESOURCE_ID_REGEX_SUFFIX;
/**
* Load and translate template data translator output.
*
* @param fileNameContentMap the file name content map
* @return the translator output
*/
public static TranslatorOutput loadAndTranslateTemplateData(
FileContentHandler fileNameContentMap) {
HeatToToscaTranslator heatToToscaTranslator =
HeatToToscaTranslatorFactory.getInstance().createInterface();
try (InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME)) {
heatToToscaTranslator
.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
} catch (IOException e) {
throw new RuntimeException("Failed to read manifest", e);
}
fileNameContentMap.getFileList().stream()
.filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))).forEach(
fileName -> heatToToscaTranslator
.addFile(fileName, FileUtils.toByteArray
(fileNameContentMap.getFileContent(fileName))));
Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate();
if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) {
TranslatorOutput translatorOutput = new TranslatorOutput();
translatorOutput.setErrorMessages(errors);
return translatorOutput;
}
try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) {
heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
return heatToToscaTranslator.translate();
} catch (IOException e) {
// rethrow as a RuntimeException to keep the signature backward compatible
throw new RuntimeException("Failed to read Heat template tree", e);
}
}
private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) {
HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap);
heatTreeManager.createTree();
HeatStructureTree tree = heatTreeManager.getTree();
ValidationStructureList validationStructureList = new ValidationStructureList(tree);
return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON);
}
/**
* Build list of files to search optional.
*
* @param heatFileName the heat file name
* @param filesDataList the files data list
* @param types the types
* @return the optional
*/
public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName,
List<FileData> filesDataList,
FileData.Type... types) {
List<FileData> list = new ArrayList<>(filesDataList);
Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList);
if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) {
list.addAll(resourceFileData.get().getData());
}
return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
}
/**
* Gets filtered list of file data by types.
*
* @param filesToSearch the files to search
* @param types the types
* @return the filtered list of file data by types
*/
public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch,
FileData.Type... types) {
return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types))
.collect(Collectors.toList());
}
/**
* Gets file data from the list according to the input heat file name.
*
* @param heatFileName the heat file name
* @param fileDataList the file data list
* @return the file data
*/
public static Optional<FileData> getFileData(String heatFileName,
Collection<FileData> fileDataList) {
for (FileData file : fileDataList) {
if (file.getFile().equals(heatFileName)) {
return Optional.of(file);
}
}
return Optional.empty();
}
/**
* Gets file data which is supported by the translator, from the context according the input heat
* file name.
*
* @param heatFileName the heat file name
* @param context the translation context
* @return the file data
*/
public static FileData getFileData(String heatFileName, TranslationContext context) {
List<FileData> fileDataList = context.getManifest().getContent().getData();
for (FileData fileData : fileDataList) {
if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType())
&& fileData.getFile().equals(heatFileName)) {
return fileData;
}
}
return null;
}
static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList,
Set<FileData.Type> typeFilter,
TranslationContext translationContext) {
FileDataCollection fileDataCollection = new FileDataCollection();
Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter);
Set<String> referenced = new HashSet<>();
for (FileData fileData : filteredFiles.values()) {
String fileName = fileData.getFile();
if (FileData.isHeatFile(fileData.getType())) {
if (fileData.getBase() != null && fileData.getBase()) {
fileDataCollection.addBaseFiles(fileData);
}
HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil()
.yamlToObject(translationContext.getFileContent(fileName),
HeatOrchestrationTemplate.class);
if (MapUtils.isNotEmpty(heatOrchestrationTemplate.getResources())) {
applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext,
fileDataCollection, filteredFiles, referenced);
}
} else {
fileDataCollection.addArtifactFiles(fileData);
filteredFiles.remove(fileData.getFile());
}
}
referenced.forEach(filteredFiles::remove);
if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
for (FileData fileData : fileDataCollection.getBaseFile()) {
filteredFiles.remove(fileData.getFile());
}
}
fileDataCollection.setAddOnFiles(filteredFiles.values());
return fileDataCollection;
}
private static void applyFilterOnFileCollection(
HeatOrchestrationTemplate heatOrchestrationTemplate,
TranslationContext translationContext,
FileDataCollection fileDataCollection, Map<String, FileData> filteredFiles,
Set<String> referenced) {
List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values());
for (Resource resource : heatOrchestrationTemplate.getResources().values()) {
if (filenames.contains(resource.getType())) {
handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced,
resource.getType());
} else if (resource.getType()
.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
handleResourceGrpNestedFile(resource, translationContext, fileDataCollection,
filteredFiles, filenames, referenced);
}
}
}
private static void handleResourceGrpNestedFile(Resource resource,
TranslationContext translationContext,
FileDataCollection fileDataCollection,
Map<String, FileData> filteredFiles,
List<String> filenames,
Set<String> referenced) {
Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
Object innerTypeDef = ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
if (innerTypeDef instanceof String) {
String internalResourceType = (String) innerTypeDef;
if (filenames.contains(internalResourceType)) {
handleNestedFile(translationContext, fileDataCollection, filteredFiles,
referenced, internalResourceType);
}
}
}
private static void handleNestedFile(TranslationContext translationContext,
FileDataCollection fileDataCollection,
Map<String, FileData> filteredFiles, Set<String> referenced,
String nestedFileName) {
referenced.add(nestedFileName);
fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
translationContext.getNestedHeatsFiles().add(nestedFileName);
}
private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList,
Set<FileData.Type> typesToGet) {
Map<String, FileData> filtered = new HashMap<>();
fileDataList.stream().filter(file -> typesToGet.contains(file.getType()))
.forEach(file -> filtered.put(file.getFile(), file));
return filtered;
}
private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
}
/**
* Extract attached resource id optional.
*
* @param translateTo the translate to
* @param propertyName the property name
* @return the optional
*/
public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo,
String propertyName) {
Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
if (propertyValue == null) {
return Optional.empty();
}
return extractAttachedResourceId(translateTo.getHeatFileName(),
translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue);
}
/**
* Extract attached resource id optional.
*
* @param heatFileName the heat file name
* @param heatOrchestrationTemplate the heat orchestration template
* @param context the context
* @param propertyValue the property value
* @return the optional
*/
public static Optional<AttachedResourceId> extractAttachedResourceId(
String heatFileName,
HeatOrchestrationTemplate heatOrchestrationTemplate,
TranslationContext context,
Object propertyValue) {
Object entity;
Object translatedId;
if (Objects.isNull(propertyValue)) {
return Optional.empty();
}
ReferenceType referenceType = ReferenceType.OTHER;
if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
Map<String, Object> propMap = (Map) propertyValue;
Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
entity = entry.getValue();
String key = entry.getKey();
referenceType = getReferenceTypeFromAttachedResouce(key);
if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
translatedId = null;
} else {
FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(null, null,
heatFileName, heatOrchestrationTemplate, context), null, entry.getValue(), null);
translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get()
.translateFunction(functionTranslator);
}
if (translatedId instanceof String
&& !new FunctionTranslator().isResourceSupported((String) translatedId)) {
translatedId = null;
}
} else {
translatedId = propertyValue;
entity = propertyValue;
}
return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
}
private static ReferenceType getReferenceTypeFromAttachedResouce(String key) {
ReferenceType referenceType;
switch (key) {
case GET_RESOURCE:
referenceType = ReferenceType.GET_RESOURCE;
break;
case GET_PARAM:
referenceType = ReferenceType.GET_PARAM;
break;
case GET_ATTR:
referenceType = ReferenceType.GET_ATTR;
break;
default:
referenceType = ReferenceType.OTHER;
break;
}
return referenceType;
}
/**
* Gets contrail attached heat resource id.
*
* @param attachedResource the attached resource
* @return the contrail attached heat resource id
*/
public static Optional<String> getContrailAttachedHeatResourceId(
AttachedResourceId attachedResource) {
if (attachedResource == null) {
return Optional.empty();
}
if (attachedResource.isGetResource()) {
return Optional.of((String) attachedResource.getEntityId());
}
if (attachedResource.isGetAttr()) {
return getResourceId(attachedResource.getEntityId());
}
return Optional.empty();
}
/**
* Extract property optional.
*
* @param propertyValue the property value
* @return the optional
*/
private static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
Object attachedPropertyVal;
if (Objects.isNull(propertyValue)) {
return Optional.empty();
}
ReferenceType referenceType = ReferenceType.OTHER;
if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
Map<String, Object> propMap = (Map) propertyValue;
Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
attachedPropertyVal = entry.getValue();
String key = entry.getKey();
switch (key) {
case GET_RESOURCE:
referenceType = ReferenceType.GET_RESOURCE;
break;
case GET_PARAM:
referenceType = ReferenceType.GET_PARAM;
break;
case GET_ATTR:
referenceType = ReferenceType.GET_ATTR;
break;
default:
break;
}
} else {
attachedPropertyVal = propertyValue;
}
return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
}
/**
* Map boolean.
*
* @param nodeTemplate the node template
* @param propertyKey the property key
*/
public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
Object value = nodeTemplate.getProperties().get(propertyKey);
if (value != null && !(value instanceof Map)) {
nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
}
}
/**
* Map boolean list.
*
* @param nodeTemplate the node template
* @param propertyListKey the property list key
*/
public static void mapBooleanList(NodeTemplate nodeTemplate, String propertyListKey) {
Object listValue = nodeTemplate.getProperties().get(propertyListKey);
if (listValue instanceof List) {
List booleanList = (List) listValue;
for (int i = 0; i < booleanList.size(); i++) {
Object value = booleanList.get(i);
if (value != null && !(value instanceof Map)) {
booleanList.set(i, HeatBoolean.eval(value));
}
}
}
}
/**
* Is yml file type boolean.
*
* @param filename the filename
* @return the boolean
*/
public static boolean isYmlFileType(String filename) {
String extension = FilenameUtils.getExtension(filename);
return "yaml".equalsIgnoreCase(extension)
|| "yml".equalsIgnoreCase(extension);
}
/**
* Is nested resource boolean.
*
* @param resource the resource
* @return the boolean
*/
public static boolean isNestedResource(Resource resource) {
String resourceType = resource.getType();
if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
if (!(((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) instanceof
String)) {
//currently only resource group which is poinitng to nested heat file is supported
//dynamic type is currently not supported
return false;
}
String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants
.RESOURCE_DEF_TYPE_PROPERTY_NAME);
if (isYamlFile(internalResourceType)) {
return true;
}
} else if (isYamlFile(resourceType)) {
return true;
}
return false;
}
/**
* Checks if the current HEAT resource if of type sub interface.
*
* @param resource the resource
* @return true if the resource is of sub interface type and false otherwise
*/
public static boolean isSubInterfaceResource(Resource resource, TranslationContext context) {
if (!ToggleableFeature.VLAN_TAGGING.isActive()) {
//Remove this once feature is stable and moved to production
return false;
}
//Check if resource group is a nested resource
if (!isNestedResource(resource)) {
return false;
}
Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
return nestedHeatFileName.filter(fileName ->
isNestedVlanResource(fileName, context)).isPresent();
}
private static boolean isNestedVlanResource(String nestedHeatFileName,
TranslationContext translationContext) {
HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
.yamlToObject(translationContext.getFileContent(nestedHeatFileName),
HeatOrchestrationTemplate.class);
return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())
&& nestedHeatOrchestrationTemplate.getResources().values().stream()
.anyMatch(new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource);
}
public static Optional<String> getSubInterfaceParentPortNodeTemplateId(
TranslateTo subInterfaceTo) {
String subInterfaceResourceType = getSubInterfaceResourceType(subInterfaceTo.getResource());
HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
.yamlToObject(subInterfaceTo.getContext().getFileContent(subInterfaceResourceType),
HeatOrchestrationTemplate.class);
if (Objects.isNull(nestedHeatOrchestrationTemplate.getResources())) {
return Optional.empty();
}
for (Map.Entry<String, Resource> resourceEntry : nestedHeatOrchestrationTemplate
.getResources().entrySet()) {
Resource resource = resourceEntry.getValue();
if (isVmiRefsPropertyExists(resource)) {
Object toscaPropertyValue =
TranslatorHeatToToscaPropertyConverter
.getToscaPropertyValue(subInterfaceTo.getServiceTemplate(),
resourceEntry.getKey(), HeatConstants.VMI_REFS_PROPERTY_NAME,
resource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME),
resource.getType(), subInterfaceResourceType, nestedHeatOrchestrationTemplate,
null, subInterfaceTo.getContext());
return getParentNodeTemplateIdFromPropertyValue(toscaPropertyValue, subInterfaceTo);
}
}
return Optional.empty();
}
private static boolean isVmiRefsPropertyExists(Resource resource) {
return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE
.getHeatResource().equals(resource.getType())
&& MapUtils.isNotEmpty(resource.getProperties())
&& resource.getProperties().containsKey(HeatConstants.VMI_REFS_PROPERTY_NAME);
}
public static String getSubInterfaceResourceType(Resource resource) {
if (!HeatToToscaUtil.isYamlFile(resource.getType())) {
return ((Map) resource.getProperties()
.get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
.get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME)
.toString();
}
return resource.getType();
}
private static Optional<String> getParentNodeTemplateIdFromPropertyValue(
Object toscaPropertyValue,
TranslateTo subInterfaceTo) {
if (toscaPropertyValue instanceof List
&& ((List) toscaPropertyValue).get(0) instanceof Map) {
Resource subInterfaceResource = subInterfaceTo.getResource();
Map<String, String> toscaPropertyValueMap = (Map) ((List) toscaPropertyValue).get(0);
String parentPortPropertyInput = toscaPropertyValueMap.get(ToscaFunctions.GET_INPUT
.getDisplayName());
Map<String, Object> resourceDefPropertiesMap;
if (!isYamlFile(subInterfaceResource.getType())) {
resourceDefPropertiesMap = (Map) ((Map) subInterfaceResource
.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
.get(HeatConstants.RESOURCE_DEF_PROPERTIES);
} else {
resourceDefPropertiesMap = subInterfaceResource.getProperties();
}
Object parentPortObj = resourceDefPropertiesMap.get(parentPortPropertyInput);
if (parentPortObj instanceof Map) {
Map<String, String> parentPortPropertyValue = (Map) parentPortObj;
if (parentPortPropertyValue.keySet().contains(ResourceReferenceFunctions
.GET_RESOURCE.getFunction())) {
return ResourceTranslationBase.getResourceTranslatedId(subInterfaceTo.getHeatFileName(),
subInterfaceTo.getHeatOrchestrationTemplate(),
parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()),
subInterfaceTo.getContext());
}
}
}
return Optional.empty();
}
/**
* Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at
* least one or more compute nodes).
*
* @param resource the resource
* @param context the context
* @return true if the resource represents a VFC and false otherwise.
*/
public static boolean isNestedVfcResource(Resource resource, TranslationContext context) {
Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
.yamlToObject(context.getFileContent(nestedHeatFileName.get()),
HeatOrchestrationTemplate.class);
if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) {
for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) {
if (ConsolidationDataUtil
.isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) {
return true;
}
}
}
return false;
}
/**
* Get nested heat file name in case of nested resource.
*
* @param resource the resource
* @return the nested heat file name
*/
private static Optional<String> getNestedHeatFileName(Resource resource) {
if (!isNestedResource(resource)) {
return Optional.empty();
}
String resourceType = resource.getType();
if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants
.RESOURCE_DEF_TYPE_PROPERTY_NAME);
return Optional.of(internalResourceType);
}
return Optional.of(resourceType);
}
/**
* Gets nested file.
*
* @param resource the resource
* @return the nested file
*/
public static Optional<String> getNestedFile(Resource resource) {
if (!isNestedResource(resource)) {
return Optional.empty();
}
String resourceType = resource.getType();
if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
String internalResourceType = (String) ((Map) resourceDef).get(HeatConstants
.RESOURCE_DEF_TYPE_PROPERTY_NAME);
return Optional.of(internalResourceType);
} else {
return Optional.of(resourceType);
}
}
public static boolean isYamlFile(String fileName) {
return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
}
/**
* Gets resource.
*
* @param heatOrchestrationTemplate the heat orchestration template
* @param resourceId the resource id
* @param heatFileName the heat file name
* @return the resource
*/
public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate,
String resourceId, String heatFileName) {
Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
if (resource == null) {
throw new CoreException(
new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
}
return resource;
}
/**
* Get resource type.
*
* @param resourceId the resource id
* @param heatOrchestrationTemplate heat orchestration template
* @param heatFileName heat file name
* @return resource type
*/
public static String getResourceType(String resourceId,
HeatOrchestrationTemplate heatOrchestrationTemplate,
String heatFileName) {
return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName)
.getType();
}
/**
* Is heat file nested boolean.
*
* @param translateTo the translate to
* @param heatFileName the heat file name
* @return the boolean
*/
public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
return isHeatFileNested(translateTo.getContext(), heatFileName);
}
public static boolean isHeatFileNested(TranslationContext context, String heatFileName) {
return context.getNestedHeatsFiles().contains(heatFileName);
}
/**
* Extract contrail get resource attached heat resource id optional.
*
* @param propertyValue the property value
* @return the optional
*/
public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(
Object propertyValue) {
if (propertyValue instanceof Map) {
if (((Map) propertyValue).containsKey(GET_ATTR)) {
return getResourceId(((Map) propertyValue).get(GET_ATTR));
} else if (((Map) propertyValue).containsKey(GET_RESOURCE)) {
return getHeatResourceIdFromResource((Map) propertyValue);
} else {
Collection valCollection = ((Map) propertyValue).values();
return evaluateHeatResourceId(valCollection);
}
} else if (propertyValue instanceof List) {
return evaluateHeatResourceId((List) propertyValue);
}
return Optional.empty();
}
private static Optional<String> getResourceId(Object data) {
if (data instanceof List && CollectionUtils.size(data) > 1
&& FQ_NAME.equals(((List) data).get(1))
&& ((List) data).get(0) instanceof String) {
return Optional.of((String) ((List) data).get(0));
} else {
LOGGER.warn("invalid format of 'get_attr' function - " + data.toString());
return Optional.empty();
}
}
private static Optional<String> getHeatResourceIdFromResource(Map propertyValue) {
Object value = propertyValue.get(GET_RESOURCE);
if (value instanceof String) {
return Optional.of((String) value);
} else {
LOGGER.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
return Optional.empty();
}
}
private static Optional<String> evaluateHeatResourceId(Collection propertyValue) {
for (Object prop : propertyValue) {
Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
if (ret.isPresent()) {
return ret;
}
}
return Optional.empty();
}
/**
* Gets tosca service model.
*
* @param context translation context
* @return the tosca service model
*/
public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
Map<String, String> metadata = new HashMap<>();
metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
return getToscaServiceModel(context, metadata);
}
/**
* Gets tosca service model.
*
* @param context translation context
* @param entryDefinitionMetadata template name of the entry definition servie template
* @return the tosca service model
*/
private static ToscaServiceModel getToscaServiceModel(
TranslationContext context,
Map<String, String> entryDefinitionMetadata) {
Map<String, ServiceTemplate> serviceTemplates =
new HashMap<>(context.getGlobalServiceTemplates());
Collection<ServiceTemplate> tmpServiceTemplates =
context.getTranslatedServiceTemplates().values();
for (ServiceTemplate serviceTemplate : tmpServiceTemplates) {
ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
}
return new ToscaServiceModel(null, serviceTemplates,
ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
}
/**
* Gets service template from context.
*
* @param serviceTemplateFileName the service template file name
* @param context the context
* @return the service template from context
*/
public static Optional<ServiceTemplate> getServiceTemplateFromContext(
String serviceTemplateFileName, TranslationContext context) {
for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
return Optional.of(serviceTemplate);
}
}
return Optional.empty();
}
/**
* Adding link requerment from port node template to network node template.
*
* @param portNodeTemplate port node template
* @param networkTranslatedId network node template id
*/
public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
String networkTranslatedId) {
RequirementAssignment requirement = new RequirementAssignment();
requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE);
requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO);
requirement.setNode(networkTranslatedId);
DataModelUtil.addRequirementAssignment(portNodeTemplate,
ToscaConstants.LINK_REQUIREMENT_ID, requirement);
return requirement;
}
/**
* Adding binding requerment from sub interface node template to interface (port) node template.
*
* @param subInterfaceNodeTemplate sub interface template
* @param interfaceTranslatedId interface node template id
*/
public static void addBindingReqFromSubInterfaceToInterface(
NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) {
RequirementAssignment requirement = new RequirementAssignment();
requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
requirement.setNode(interfaceTranslatedId);
DataModelUtil
.addRequirementAssignment(subInterfaceNodeTemplate,
ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
}
/**
* Get property Parameter Name Value.
*
* @param property property
* @return Parameter name in case the property include "get_param" function
*/
public static Optional<String> getPropertyParameterNameValue(Object property) {
if (Objects.isNull(property)) {
return Optional.empty();
}
Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
if (extractedProperty.isPresent()) {
return getParameterName(extractedProperty.get());
}
return Optional.empty();
}
private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
if (!extractedProperty.isGetParam()) {
return Optional.empty();
}
Object getParamFuncValue = extractedProperty.getPropertyValue();
if (getParamFuncValue instanceof String) {
return Optional.of((String) getParamFuncValue);
} else {
return Optional.of((String) ((List) getParamFuncValue).get(0));
}
}
public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
String heatPropertyName) {
return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
}
/**
* Gets tosca property name.
*
* @param translateTo the translate to
* @param heatPropertyName the heat property name
* @return the tosca property name
*/
public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
return translateTo.getContext()
.getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
}
/**
* Gets tosca attribute name.
*
* @param context the context
* @param heatResourceType the heat resource type
* @param heatAttrName the heat attr name
* @return the tosca attribute name
*/
public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
String heatAttrName) {
return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
}
/**
* Gets tosca attribute name.
*
* @param translateTo the translate to
* @param heatAttrName the heat attr name
* @return the tosca attribute name
*/
public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
return translateTo.getContext()
.getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
}
/**
* Create init substitution service template service template.
*
* @param templateName the template name
* @return the service template
*/
public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) {
ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate();
Map<String, String> templateMetadata = new HashMap<>();
templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
nestedSubstitutionServiceTemplate.setMetadata(templateMetadata);
nestedSubstitutionServiceTemplate
.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate());
List<Map<String, Import>> globalTypesImportList =
GlobalTypesGenerator.getGlobalTypesImportList();
globalTypesImportList.addAll(
HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
nestedSubstitutionServiceTemplate.setImports(globalTypesImportList);
return nestedSubstitutionServiceTemplate;
}
/**
* Create init global substitution service template service template.
*
* @return the service template
*/
private static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() {
ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate();
Map<String, String> templateMetadata = new HashMap<>();
templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME,
Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
globalSubstitutionServiceTemplate.setMetadata(templateMetadata);
globalSubstitutionServiceTemplate
.setImports(GlobalTypesGenerator.getGlobalTypesImportList());
globalSubstitutionServiceTemplate
.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
return globalSubstitutionServiceTemplate;
}
/**
* Create substitution node type node type.
*
* @param substitutionServiceTemplate the substitution service template
* @return the node type
*/
public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
NodeType substitutionNodeType = new NodeType();
substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
substitutionNodeType
.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
substitutionNodeType
.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
return substitutionNodeType;
}
private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(
ServiceTemplate substitutionServiceTemplate) {
Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
Map<String, ParameterDefinition> properties =
substitutionServiceTemplate.getTopology_template().getInputs();
if (properties == null) {
return null;
}
PropertyDefinition propertyDefinition;
String toscaPropertyName;
for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
toscaPropertyName = entry.getKey();
propertyDefinition = new PropertyDefinition();
ParameterDefinition parameterDefinition =
substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
propertyDefinition.setType(parameterDefinition.getType());
propertyDefinition.setDescription(parameterDefinition.getDescription());
propertyDefinition.setRequired(parameterDefinition.getRequired());
propertyDefinition.set_default(parameterDefinition.get_default());
propertyDefinition.setConstraints(parameterDefinition.getConstraints());
propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
propertyDefinition.setStatus(parameterDefinition.getStatus());
substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
}
return substitutionNodeTypeProperties;
}
private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(
ServiceTemplate substitutionServiceTemplate) {
Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
Map<String, ParameterDefinition> attributes =
substitutionServiceTemplate.getTopology_template().getOutputs();
if (attributes == null) {
return null;
}
AttributeDefinition attributeDefinition;
String toscaAttributeName;
for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
attributeDefinition = new AttributeDefinition();
toscaAttributeName = entry.getKey();
ParameterDefinition parameterDefinition =
substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
attributeDefinition.setType(parameterDefinition.getType());
} else {
attributeDefinition.setType(PropertyType.STRING.getDisplayName());
}
attributeDefinition.setDescription(parameterDefinition.getDescription());
attributeDefinition.set_default(parameterDefinition.get_default());
attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
attributeDefinition.setStatus(parameterDefinition.getStatus());
substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
}
return substitutionNodeTypeAttributes;
}
/**
* .
* Create and add substitution mapping to the nested substitution service template, and update
* the subtitution node type accordingly with the exposed requerments and capabilities
*
* @param context the translation context
* @param substitutionNodeTypeKey the substitution node type key
* @param nestedSubstitutionServiceTemplate the nested substitution service template
* @param substitutionNodeType the substitution node type
*/
public static void handleSubstitutionMapping(
TranslationContext context,
String substitutionNodeTypeKey,
ServiceTemplate nestedSubstitutionServiceTemplate,
NodeType substitutionNodeType) {
Map<String, Map<String, List<String>>> substitutionMapping =
getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType,
nestedSubstitutionServiceTemplate, context);
//add substitution mapping after capability and requirement expose calculation
nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(
DataModelUtil.createSubstitutionTemplateSubMapping(substitutionNodeTypeKey,
substitutionNodeType, substitutionMapping));
}
/**
* Gets node type with flat hierarchy.
*
* @param nodeTypeId the node type id
* @param serviceTemplate the service template
* @param context the context
* @return the node type with flat hierarchy
*/
public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId,
ServiceTemplate serviceTemplate,
TranslationContext context) {
ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
ToscaServiceModel toscaServiceModel = HeatToToscaUtil
.getToscaServiceModel(context, serviceTemplate.getMetadata());
return (NodeType) toscaAnalyzerService
.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel);
}
/**
* Create substitution node template node template.
*
* @param translateTo the translate to
* @param templateName the template name
* @param substitutionNodeTypeKey the substitution node type key
* @return the node template
*/
public NodeTemplate createSubstitutionNodeTemplate(TranslateTo translateTo, String templateName,
String substitutionNodeTypeKey) {
NodeTemplate substitutionNodeTemplate = new NodeTemplate();
List<String> directiveList = new ArrayList<>();
directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
substitutionNodeTemplate.setDirectives(directiveList);
substitutionNodeTemplate.setType(substitutionNodeTypeKey);
substitutionNodeTemplate.setProperties(
managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
templateName));
return substitutionNodeTemplate;
}
/**
* Create abstract substitution node template.
*
* @param translateTo the translate to
* @param templateName the template name
* @param substitutionNodeTypeKey the substitution node type key
* @return the abstract substitute node template
*/
public static NodeTemplate createAbstractSubstitutionNodeTemplate(
TranslateTo translateTo,
String templateName,
String substitutionNodeTypeKey) {
NodeTemplate substitutionNodeTemplate = new NodeTemplate();
List<String> directiveList = new ArrayList<>();
directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
substitutionNodeTemplate.setDirectives(directiveList);
substitutionNodeTemplate.setType(substitutionNodeTypeKey);
substitutionNodeTemplate.setProperties(
managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate,
templateName));
return substitutionNodeTemplate;
}
/**
* Checks if the source and target resource is a valid candidate for adding tosca dependency
* relationship.
*
* @param sourceResource the source resource
* @param targetResource the target resource
* @param dependencyEntity the dependency entity
* @return true if the candidate resources are a valid combination for the dependency relationship
* and false otherwise
*/
public static boolean isValidDependsOnCandidate(Resource sourceResource,
Resource targetResource,
ConsolidationEntityType dependencyEntity,
TranslationContext context) {
dependencyEntity.setEntityType(sourceResource, targetResource, context);
ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
return ConsolidationTypesConnectivity
.isDependsOnRelationshipValid(sourceEntityType, targetEntityType);
}
private static Map<String, Object> managerSubstitutionNodeTemplateProperties(
TranslateTo translateTo,
Template template,
String templateName) {
Map<String, Object> substitutionProperties = new HashMap<>();
Map<String, Object> heatProperties = translateTo.getResource().getProperties();
if (Objects.nonNull(heatProperties)) {
for (Map.Entry<String, Object> entry : heatProperties.entrySet()) {
Object property = TranslatorHeatToToscaPropertyConverter
.getToscaPropertyValue(translateTo.getServiceTemplate(),
translateTo.getTranslatedId(), entry.getKey(),
entry.getValue(), null, translateTo.getHeatFileName(),
translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext());
substitutionProperties.put(entry.getKey(), property);
}
}
return addAbstractSubstitutionProperty(templateName, substitutionProperties);
}
private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
Map<String, Object>
substitutionProperties) {
Map<String, Object> innerProps = new HashMap<>();
innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME,
ToscaUtil.getServiceTemplateFileName(templateName));
substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
return substitutionProperties;
}
private static Map<String, Map<String, List<String>>>
getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
ServiceTemplate substitutionServiceTemplate,
TranslationContext context) {
Map<String, NodeTemplate> nodeTemplates =
substitutionServiceTemplate.getTopology_template().getNode_templates();
String nodeTemplateId;
NodeTemplate nodeTemplate;
String nodeType;
Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
if (nodeTemplates == null) {
return substitutionMapping;
}
Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
substitutionMapping.put("capability", capabilitySubstitutionMapping);
substitutionMapping.put("requirement", requirementSubstitutionMapping);
List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition =
new HashMap<>();
Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
nodeTemplateId = entry.getKey();
nodeTemplate = entry.getValue();
nodeType = nodeTemplate.getType();
// get requirements
nodeTypeRequirementsDefinition =
getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate,
requirementSubstitutionMapping, context);
nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
//set substitution node type requirements
exposedRequirementsDefinition =
toscaAnalyzerService.calculateExposedRequirements(nodeTypeRequirementsDefinition,
nodeTemplateRequirementsAssignment);
DataModelUtil
.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
nodeTemplateId);
//get capabilities
addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition,
capabilitySubstitutionMapping, nodeType,
nodeTemplateId, substitutionServiceTemplate, context);
}
exposedCapabilitiesDefinition =
toscaAnalyzerService.calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
fullFilledRequirementsDefinition);
DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
return substitutionMapping;
}
private static void addNodeTypeCapabilitiesToSubMapping(
Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
Map<String, List<String>> capabilitySubstitutionMapping, String type, String templateName,
ServiceTemplate serviceTemplate, TranslationContext context) {
NodeType flatNodeType =
getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
if (flatNodeType.getCapabilities() != null) {
flatNodeType.getCapabilities()
.entrySet()
.stream()
.forEach(capabilityNodeEntry ->
addCapabilityToSubMapping(
templateName, capabilityNodeEntry, nodeTypeCapabilitiesDefinition,
capabilitySubstitutionMapping));
}
}
public static boolean shouldAnnotationsToBeAdded() {
return ToggleableFeature.ANNOTATIONS.isActive();
}
private static void addCapabilityToSubMapping(String templateName,
Map.Entry<String, CapabilityDefinition> capabilityNodeEntry,
Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
Map<String, List<String>> capabilitySubstitutionMapping) {
String capabilityKey;
List<String> capabilityMapping;
capabilityKey = capabilityNodeEntry.getKey() + UNDERSCORE + templateName;
nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
capabilityMapping = new ArrayList<>();
capabilityMapping.add(templateName);
capabilityMapping.add(capabilityNodeEntry.getKey());
capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
}
private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(
String type,
String templateName,
ServiceTemplate serviceTemplate,
Map<String, List<String>> requirementSubstitutionMapping,
TranslationContext context) {
List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
List<String> requirementMapping;
if (flatNodeType.getRequirements() == null) {
return requirementList;
}
for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap
.entrySet()) {
ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil
.yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
RequirementDefinition.class);
if (Objects.isNull(requirementNodeEntryValue.getOccurrences())) {
requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
}
Map<String, RequirementDefinition> requirementDef = new HashMap<>();
requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
DataModelUtil.addRequirementToList(requirementList, requirementDef);
requirementMapping = new ArrayList<>();
requirementMapping.add(templateName);
requirementMapping.add(requirementNodeEntry.getKey());
requirementSubstitutionMapping
.put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping);
if (Objects.isNull(requirementNodeEntryValue.getNode())) {
requirementNodeEntryValue.setOccurrences(new Object[]{1, 1});
}
}
}
return requirementList;
}
/**
* Fetch global substitution service template service template.
*
* @param serviceTemplate the service template
* @param context the context
* @return the service template
*/
public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(
ServiceTemplate serviceTemplate,
TranslationContext context) {
ServiceTemplate globalSubstitutionServiceTemplate =
context.getTranslatedServiceTemplates()
.get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
if (globalSubstitutionServiceTemplate == null) {
globalSubstitutionServiceTemplate =
HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate();
context.getTranslatedServiceTemplates()
.put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME,
globalSubstitutionServiceTemplate);
}
boolean isImportAddedToServiceTemplate =
DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants
.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
if (!isImportAddedToServiceTemplate) {
serviceTemplate.getImports()
.addAll(
HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
}
return globalSubstitutionServiceTemplate;
}
public static List<Map<String, Import>> createImportList(String templateName) {
List<Map<String, Import>> imports = new ArrayList<>();
Map<String, Import> importsMap = new HashMap<>();
importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName));
imports.add(importsMap);
return imports;
}
/**
* Create service template import import.
*
* @param serviceTemplate the service template
* @return the import
*/
public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
Import serviceTemplateImport = new Import();
serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
return serviceTemplateImport;
}
/**
* Create service template import import.
*
* @param metadataTemplateName the service template name
* @return the import
*/
private static Import createServiceTemplateImport(String metadataTemplateName) {
Import serviceTemplateImport = new Import();
serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
return serviceTemplateImport;
}
public static ToscaServiceModel createToscaServiceModel(ServiceTemplate
entryDefinitionServiceTemplate,
TranslationContext translationContext) {
return new ToscaServiceModel(getCsarArtifactFiles(translationContext),
getServiceTemplates(translationContext),
ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
}
private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
FileContentHandler artifactFiles = new FileContentHandler();
artifactFiles.setFiles(translationContext.getFiles());
artifactFiles.setFiles(translationContext.getExternalArtifacts());
HeatTreeManager heatTreeManager =
HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles());
heatTreeManager.createTree();
ValidationStructureList validationStructureList =
new ValidationStructureList(heatTreeManager.getTree());
byte[] validationStructureFile =
FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON);
artifactFiles.addFile("HEAT.meta", validationStructureFile);
return artifactFiles;
}
private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext
translationContext) {
List<ServiceTemplate> serviceTemplates = new ArrayList<>();
serviceTemplates.addAll(GlobalTypesGenerator
.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP).values());
serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values());
Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>();
for (ServiceTemplate template : serviceTemplates) {
serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
}
return serviceTemplatesMap;
}
public static String getNestedResourceTypePrefix(TranslateTo translateTo) {
if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext())
&& isSubInterfaceBoundToPort(translateTo)) {
return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX;
}
return ToscaNodeType.NESTED_HEAT_RESOURCE_TYPE_PREFIX;
}
private static boolean isSubInterfaceBoundToPort(TranslateTo translateTo) {
return HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(translateTo).isPresent();
}
//Method evaluate the network role from sub interface node template id, designed considering
// only single sub interface present in nested file else it will return null
public static Optional<String> getNetworkRoleFromSubInterfaceId(Resource resource,
TranslationContext translationContext) {
Optional<String> networkRole = Optional.empty();
Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
if (!nestedHeatFileName.isPresent()) {
return networkRole;
}
HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil()
.yamlToObject(translationContext.getFileContent(nestedHeatFileName.get()),
HeatOrchestrationTemplate.class);
if (MapUtils.isNotEmpty(nestedHeatOrchestrationTemplate.getResources())) {
ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper =
new ContrailV2VirtualMachineInterfaceHelper();
Optional<Map.Entry<String, Resource>> vlanSubInterfaceResource =
nestedHeatOrchestrationTemplate
.getResources().entrySet().stream()
.filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper
.isVlanSubInterfaceResource(resourceEntry.getValue()))
.findFirst();
if (vlanSubInterfaceResource.isPresent()) {
Map.Entry<String, Resource> vlanSubInterfaceResourceEntry = vlanSubInterfaceResource.get();
networkRole = extractNetworkRoleFromSubInterfaceId(vlanSubInterfaceResourceEntry.getKey(),
vlanSubInterfaceResourceEntry.getValue().getType());
}
}
return networkRole;
}
public static Optional<String> evaluateNetworkRoleFromResourceId(String resourceId,
String resourceType) {
Optional<PortType> portType = getPortType(resourceType);
if (portType.isPresent()) {
String portResourceIdRegex =
PORT_RESOURCE_ID_REGEX_PREFIX + UNDERSCORE + WORDS_REGEX + UNDERSCORE
+ portType.get().getPortTypeName() + PORT_RESOURCE_ID_REGEX_SUFFIX;
String portIntResourceIdRegex =
PORT_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
+ PORT_RESOURCE_ID_REGEX_SUFFIX;
String portNetworkRole = getNetworkRole(resourceId, portResourceIdRegex);
String portIntNetworkRole = getNetworkRole(resourceId, portIntResourceIdRegex);
return Optional.ofNullable(Objects.nonNull(portNetworkRole)
? portNetworkRole : portIntNetworkRole);
}
return Optional.empty();
}
private static Optional<PortType> getPortType(String resourceType) {
if (resourceType.equals(
HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource())) {
return Optional.of(PortType.VMI);
} else if (resourceType.equals(
HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) {
return Optional.of(PortType.PORT);
}
return Optional.empty();
}
public static Optional<String> extractNetworkRoleFromSubInterfaceId(String resourceId,
String resourceType) {
Optional<PortType> portType = getPortType(resourceType);
if (portType.isPresent()) {
String subInterfaceResourceIdRegex =
SUB_INTERFACE_INT_RESOURCE_ID_REGEX_PREFIX + portType.get().getPortTypeName()
+ PORT_RESOURCE_ID_REGEX_SUFFIX;
return Optional.ofNullable(getNetworkRole(resourceId, subInterfaceResourceIdRegex));
}
return Optional.empty();
}
private enum PortType {
PORT("port"),
VMI("vmi");
private String portTypeName;
PortType(String portTypeName) {
this.portTypeName = portTypeName;
}
public String getPortTypeName() {
return portTypeName;
}
}
private static String getNetworkRole(String portResourceId, String portIdRegex) {
Pattern pattern = Pattern.compile(portIdRegex);
Matcher matcher = pattern.matcher(portResourceId);
if (matcher.matches()) {
String networkRole = matcher.group(3);
//Assuming network role will not contain ONLY digits
if (!networkRole.matches("\\d+")) {
return matcher.group(3);
}
}
return null;
}
}
|