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
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
|
package org.openecomp.sdc.be.model.jsontitan.operations;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ComponentInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.CompositionDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapCapabiltyProperty;
import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListCapabiltyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.JsonPresentationFields;
import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.CapabilityDefinition;
import org.openecomp.sdc.be.model.Component;
import org.openecomp.sdc.be.model.ComponentInstance;
import org.openecomp.sdc.be.model.ComponentInstanceInput;
import org.openecomp.sdc.be.model.ComponentInstanceProperty;
import org.openecomp.sdc.be.model.DistributionStatusEnum;
import org.openecomp.sdc.be.model.GroupDefinition;
import org.openecomp.sdc.be.model.GroupInstance;
import org.openecomp.sdc.be.model.RelationshipImpl;
import org.openecomp.sdc.be.model.RequirementAndRelationshipPair;
import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
import org.openecomp.sdc.be.model.Resource;
import org.openecomp.sdc.be.model.User;
import org.openecomp.sdc.be.model.jsontitan.datamodel.NodeType;
import org.openecomp.sdc.be.model.jsontitan.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsontitan.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsontitan.enums.JsonConstantKeysEnum;
import org.openecomp.sdc.be.model.jsontitan.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
import org.openecomp.sdc.common.util.ValidationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import fj.data.Either;
@org.springframework.stereotype.Component("node-template-operation")
public class NodeTemplateOperation extends BaseOperation {
private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
public static final String HEAT_ENV_NAME = "heatEnv";
public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
public static final String HEAT_ENV_SUFFIX = "env";
private static Integer defaultHeatTimeout;
public static final Integer NON_HEAT_TIMEOUT = 0;
private static Logger logger = LoggerFactory.getLogger(NodeTemplateOperation.class.getName());
public NodeTemplateOperation() {
defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
defaultHeatTimeout = 60;
}
}
public static Integer getDefaultHeatTimeout() {
return defaultHeatTimeout;
}
public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, String instanceNumberSuffix, ComponentInstance componentInstance,
boolean allowDeleted, User user) {
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceRes = null;
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId());
ComponentInstanceDataDefinition componentInstanceData = null;
Either<String, StorageOperationStatus> newInstanceNameRes = null;
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
if (result == null) {
newInstanceNameRes = buildValidateInstanceName(container, originToscaElement, componentInstance, instanceNumberSuffix);
if (newInstanceNameRes.isRight()) {
result = Either.right(newInstanceNameRes.right().value());
}
}
if (result == null) {
componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), newInstanceNameRes.left().value(), true, originToscaElement);
addComponentInstanceRes = addComponentInstanceToTopologyTemplate(container, originToscaElement, componentInstanceData, metadataVertex.left().value(), allowDeleted, user);
if (addComponentInstanceRes.isRight()) {
StorageOperationStatus status = addComponentInstanceRes.right().value();
if (status == StorageOperationStatus.NOT_FOUND) {
status = StorageOperationStatus.INVALID_ID;
}
result = Either.right(status);
}
}
if (result == null) {
result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId()));
}
return result;
}
private Either<String, StorageOperationStatus> buildValidateInstanceName(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance, String instanceNumberSuffix) {
Either<String, StorageOperationStatus> result = null;
String instanceName = componentInstance.getName();
if (StringUtils.isEmpty(instanceName) || instanceName.equalsIgnoreCase(originToscaElement.getName())) {
instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName);
} else if (!isUniqueInstanceName(container, componentInstance.getName())) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to create component instance with name {} on component container {}. The instance with the same name already exists. ", componentInstance.getName(), container.getName());
result = Either.right(StorageOperationStatus.ENTITY_ALREADY_EXISTS);
}
if (result == null) {
result = Either.left(instanceName);
}
return result;
}
public Either<TopologyTemplate, StorageOperationStatus> addComponentInstanceToTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex metadataVertex,
boolean allowDeleted, User user) {
Either<TopologyTemplate, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId);
String instOriginComponentId = componentInstance.getComponentUid();
Either<GraphVertex, TitanOperationStatus> updateElement = null;
Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED);
if (!allowDeleted && (isDeleted != null) && isDeleted) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId);
result = Either.right(StorageOperationStatus.INVALID_ID);
}
if (result == null) {
container.addComponentInstance(componentInstance);
metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll);
updateElement = titanDao.updateVertex(metadataVertex);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value(), user);
if (addToscaDataRes.isRight()) {
result = Either.right(addToscaDataRes.right().value());
}
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
if (result == null) {
result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value());
}
return result;
}
public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container, ToscaElement originToscaElement, ComponentInstance componentInstance) {
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId);
ComponentInstanceDataDefinition componentInstanceData = null;
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
if (result == null) {
componentInstanceData = buildComponentInstanceDataDefinition(componentInstance, container.getUniqueId(), componentInstance.getName(), false, originToscaElement);
container.addComponentInstance(componentInstanceData);
metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll);
Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value());
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstance.getName());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with updated component instance {}. ", container.getName(), componentInstance.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
if (result == null) {
result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceData.getUniqueId()));
}
return result;
}
public Either<TopologyTemplate, StorageOperationStatus> updateComponentInstanceMetadataOfTopologyTemplate(TopologyTemplate container) {
Either<TopologyTemplate, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId);
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
if (result == null) {
metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll);
Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(metadataVertex.left().value());
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName());
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {}. ", container.getName());
result = Either.right(updateContainerComponentRes.right().value());
}
}
if (result == null) {
result = Either.left((TopologyTemplate) updateContainerComponentRes.left().value());
}
return result;
}
public Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> deleteComponentInstanceFromTopologyTemplate(TopologyTemplate container, String componentInstanceId) {
Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
CommonUtility.addRecordToLog(logger, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId);
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(status));
}
GraphVertex containerV = null;
if (result == null) {
container.getComponentInstances().remove(componentInstanceId);
containerV = metadataVertex.left().value();
StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete relation for component instance {} in container. error {}", componentInstanceId, container.getUniqueId(), status);
result = Either.right(status);
}
containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(containerV, container, JsonParseFlagEnum.ParseAll);
Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instance {}. ", container.getName(), componentInstanceId);
result = Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status);
return Either.right(status);
}
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} after deleting the component instance {}. ", container.getName(), componentInstanceId);
result = Either.right(updateContainerComponentRes.right().value());
}
}
if (result == null) {
result = Either.left(new ImmutablePair<>((TopologyTemplate) updateContainerComponentRes.left().value(), componentInstanceId));
}
return result;
}
private StorageOperationStatus removeRelationsOfInstance(TopologyTemplate container, String ciToRemove, GraphVertex containerV) {
CompositionDataDefinition composition = container.getCompositions().get(JsonConstantKeysEnum.COMPOSITION.getValue());
if (composition != null) {
Map<String, RelationshipInstDataDefinition> relations = composition.getRelations();
if (MapUtils.isNotEmpty(relations)) {
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return capResult.right().value();
}
Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return capResult.right().value();
}
Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
return reqResult.right().value();
}
Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqResult.isRight()) {
return reqResult.right().value();
}
Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, RelationshipInstDataDefinition> relation = iterator.next();
RelationshipInstDataDefinition relationToDelete = relation.getValue();
if (relationToDelete.getFromId().equals(ciToRemove) || relationToDelete.getToId().equals(ciToRemove)) {
iterator.remove();
if (relationToDelete.getFromId().equals(ciToRemove)) {
updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, ciToRemove, relationToDelete);
updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete);
}
if (relationToDelete.getToId().equals(ciToRemove)) {
updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete);
updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete);
}
}
}
}
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus deleteComponentInstanceToscaDataFromContainerComponent(GraphVertex containerV, String componentInstanceId) {
StorageOperationStatus status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove calculated requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled capabilities for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove attributes for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove properties for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance inputs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove fullfilled requirement for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance deployment artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
return StorageOperationStatus.OK;
}
protected Either<GraphVertex, StorageOperationStatus> addComponentInstanceToscaDataToContainerComponent(ToscaElement originToscaElement, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user) {
Either<GraphVertex, StorageOperationStatus> result;
StorageOperationStatus status;
if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NodeType) {
status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex, user, HEAT_VF_ENV_NAME);
} else {
status = addComponentInstanceToscaDataToTopologyTemplateContainer((TopologyTemplate) originToscaElement, componentInstance, updatedContainerVertex);
}
if (status == StorageOperationStatus.OK) {
result = Either.left(updatedContainerVertex);
} else {
result = Either.right(status);
}
return result;
}
private StorageOperationStatus addComponentInstanceToscaDataToTopologyTemplateContainer(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
StorageOperationStatus status;
status = addCalculatedCapReqFromTopologyTemplate(originTopologyTemplate, componentInstance, updatedContainerVertex);
if (status != StorageOperationStatus.OK) {
return status;
}
MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs());
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instProperties, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
return status;
}
private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
Map<String, MapListCapabiltyDataDefinition> calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities();
if (calculatedCapabilities != null) {
MapListCapabiltyDataDefinition allCalculatedCap = new MapListCapabiltyDataDefinition();
calculatedCapabilities.entrySet().forEach(enntryPerInstance -> {
Map<String, ListCapabilityDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition();
mapByType.entrySet().forEach(entryPerType -> {
entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> {
cap.addToPath(componentInstance.getUniqueId());
allCalculatedCap.add(entryPerType.getKey(), cap);
});
});
});
StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap,
componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
MapListCapabiltyDataDefinition fullCalculatedCap = new MapListCapabiltyDataDefinition();
calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
Map<String, MapListRequirementDataDefinition> calculatedRequirements = originTopologyTemplate.getCalculatedRequirements();
if (calculatedRequirements != null) {
MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
calculatedRequirements.entrySet().forEach(enntryPerInstance -> {
Map<String, ListRequirementDataDefinition> mapByType = enntryPerInstance.getValue().getMapToscaDataDefinition();
mapByType.entrySet().forEach(entryPerType -> {
entryPerType.getValue().getListToscaDataDefinition().forEach(req -> {
req.addToPath(componentInstance.getUniqueId());
allCalculatedReq.add(entryPerType.getKey(), req);
});
});
});
StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq,
componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
Map<String, MapCapabiltyProperty> calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties();
Map<String, MapPropertiesDataDefinition> updateKeyMap = new HashMap<>();
if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) {
for (MapCapabiltyProperty map : calculatedCapabilitiesProperties.values()) {
for (Entry<String, MapPropertiesDataDefinition> entry : map.getMapToscaDataDefinition().entrySet()) {
String newKey = new String(componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey());
updateKeyMap.put(newKey, entry.getValue());
}
}
MapCapabiltyProperty mapCapabiltyProperty = new MapCapabiltyProperty(updateKeyMap);
StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabiltyProperty,
componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) {
MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(originNodeType.getProperties());
StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
MapPropertiesDataDefinition instAttributes = new MapPropertiesDataDefinition(originNodeType.getAttributes());
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
status = addInstanceDeploymentArtifacts(originNodeType, componentInstance, updatedContainerVertex, user, envType);
if (status != StorageOperationStatus.OK) {
return status;
}
return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex);
}
private StorageOperationStatus addInstanceDeploymentArtifacts(ToscaElement originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex, User user, String envType) {
Map<String, ArtifactDataDefinition> deploymentArtifacts = originNodeType.getDeploymentArtifacts();
MapArtifactDataDefinition instArtifacts = prepareInstDeploymentArtifactPerInstance(deploymentArtifacts, componentInstance.getUniqueId(), user, envType);
if (instArtifacts != null) {
StorageOperationStatus calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts,
componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
return StorageOperationStatus.OK;
}
public MapArtifactDataDefinition prepareInstDeploymentArtifactPerInstance(Map<String, ArtifactDataDefinition> deploymentArtifacts, String componentInstanceId, User user, String envType) {
if (deploymentArtifacts != null && envType.equals(HEAT_VF_ENV_NAME)) {
Map<String, ArtifactDataDefinition> instDeploymentArtifacts = new HashMap<>();
deploymentArtifacts.entrySet().forEach(e -> {
ArtifactDataDefinition artifact = e.getValue();
String type = artifact.getArtifactType();
if (!(type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()))) {
instDeploymentArtifacts.put(e.getKey(), artifact);
ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType);
instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv);
}
});
MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeploymentArtifacts);
return instArtifacts;
}
return null;
}
@SuppressWarnings({ "unchecked" })
private ArtifactDataDefinition createArtifactPlaceHolderInfo(ArtifactDataDefinition artifactHeat, String componentId, User user, String heatEnvType) {
Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
if (deploymentResourceArtifacts == null) {
logger.debug("no deployment artifacts are configured for generated artifacts");
return null;
}
Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(heatEnvType);
if (placeHolderData == null) {
logger.debug("no env type {} are configured for generated artifacts", heatEnvType);
return null;
}
String envLabel = (artifactHeat.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
ArtifactDataDefinition artifactInfo = new ArtifactDataDefinition();
String artifactName = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
String artifactType = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_TYPE);
String artifactDescription = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
artifactInfo.setArtifactDisplayName(artifactName);
artifactInfo.setArtifactLabel(envLabel);
artifactInfo.setArtifactType(artifactType);
artifactInfo.setDescription(artifactDescription);
artifactInfo.setArtifactGroupType(artifactHeat.getArtifactGroupType());
setDefaultArtifactTimeout(artifactHeat.getArtifactGroupType(), artifactInfo);
artifactInfo.setGeneratedFromId(artifactHeat.getUniqueId());
// clone heat parameters in case of heat env only not VF heat env
if (heatEnvType.equals(HEAT_ENV_NAME)) {
artifactInfo.setHeatParameters(artifactHeat.getHeatParameters());
}
setArtifactPlaceholderCommonFields(componentId, user, artifactInfo);
return artifactInfo;
}
public void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDataDefinition artifactInfo) {
if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
artifactInfo.setTimeout(defaultHeatTimeout);
} else {
artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
}
}
private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDataDefinition artifactInfo) {
String uniqueId = null;
if (resourceId != null) {
uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
artifactInfo.setUniqueId(uniqueId);
}
artifactInfo.setUserIdCreator(user.getUserId());
String fullName = user.getFullName();
artifactInfo.setUpdaterFullName(fullName);
long time = System.currentTimeMillis();
artifactInfo.setCreatorFullName(fullName);
artifactInfo.setCreationDate(time);
artifactInfo.setLastUpdateDate(time);
artifactInfo.setUserIdLastUpdater(user.getUserId());
artifactInfo.setMandatory(true);
}
/**
*
* @param originNodeType
* @param componentInstance
* @param updatedContainerVertex
* @return
*/
private StorageOperationStatus addCalculatedCapReqFromNodeType(NodeType originNodeType, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
Map<String, ListCapabilityDataDefinition> capabilities = originNodeType.getCapabilties();
MapListCapabiltyDataDefinition allCalculatedCap = prepareCalculatedCapabiltyForNodeType(capabilities, componentInstance);
StorageOperationStatus calculatedResult;
if (allCalculatedCap != null) {
calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
Map<String, MapPropertiesDataDefinition> capabiltiesProperties = originNodeType.getCapabiltiesProperties();
if (capabiltiesProperties != null) {
Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), e -> e.getValue()));
MapCapabiltyProperty mapCapabiltyProperty = new MapCapabiltyProperty(updateKeyMap);
calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabiltyProperty, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
MapListCapabiltyDataDefinition fullCalculatedCap = new MapListCapabiltyDataDefinition();
calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES, fullCalculatedCap, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
Map<String, ListRequirementDataDefinition> requirements = originNodeType.getRequirements();
MapListRequirementDataDefinition allCalculatedReq = prepareCalculatedRequirementForNodeType(requirements, componentInstance);
StorageOperationStatus status;
if (allCalculatedReq != null) {
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
}
MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS, fullCalculatedReq, componentInstance.getUniqueId());
return StorageOperationStatus.OK;
}
public static String createCapPropertyKey(String key, String instanceId) {
StringBuffer sb = new StringBuffer(instanceId);
sb.append(ModelConverter.CAP_PROP_DELIM).append(instanceId).append(ModelConverter.CAP_PROP_DELIM).append(key);
return sb.toString();
}
public MapListCapabiltyDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities, ComponentInstanceDataDefinition componentInstance) {
if (capabilities != null) {
MapListCapabiltyDataDefinition allCalculatedCap = new MapListCapabiltyDataDefinition();
capabilities.entrySet().forEach(e -> {
List<CapabilityDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition();
listCapabilities.forEach(cap -> {
cap.setSource(componentInstance.getComponentUid());
cap.addToPath(componentInstance.getUniqueId());
cap.setOwnerId(componentInstance.getUniqueId());
cap.setOwnerName(componentInstance.getName());
cap.setLeftOccurrences(cap.getMaxOccurrences());
allCalculatedCap.add(e.getKey(), cap);
});
});
return allCalculatedCap;
}
return null;
}
public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) {
if (requirements != null) {
MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
requirements.entrySet().forEach(e -> {
List<RequirementDataDefinition> listCapabilities = e.getValue().getListToscaDataDefinition();
listCapabilities.forEach(req -> {
req.setSource(componentInstance.getComponentUid());
req.addToPath(componentInstance.getUniqueId());
req.setOwnerId(componentInstance.getUniqueId());
req.setOwnerName(componentInstance.getName());
req.setLeftOccurrences(req.getMaxOccurrences());
allCalculatedReq.add(e.getKey(), req);
});
});
return allCalculatedReq;
}
return null;
}
public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstanceDataDefinition componentInstance, List<GroupDefinition> groups, Map<String, List<ArtifactDefinition>> groupInstancesArtifacts) {
StorageOperationStatus result = null;
Map<String, GroupInstanceDataDefinition> groupInstanceToCreate = new HashMap<>();
if (groupInstancesArtifacts != null && CollectionUtils.isNotEmpty(groups)) {
for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : groupInstancesArtifacts.entrySet()) {
Optional<GroupDefinition> groupOptional = groups.stream().filter(g -> g.getUniqueId().equals(groupArtifacts.getKey())).findFirst();
if (groupOptional.isPresent()) {
GroupInstanceDataDefinition groupInstance = buildGroupInstanceDataDefinition((GroupDataDefinition)groupOptional.get(), (ComponentInstanceDataDefinition)componentInstance);
groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(a -> a.getUniqueId()).collect(Collectors.toList()));
groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(a -> a.getArtifactUUID()).collect(Collectors.toList()));
groupInstanceToCreate.put(groupInstance.getName(), groupInstance);
}
}
}
if (MapUtils.isNotEmpty(groupInstanceToCreate)) {
result = addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS, new MapDataDefinition<>(groupInstanceToCreate), componentInstance.getUniqueId());
}
if (result == null) {
result = StorageOperationStatus.OK;
}
return result;
}
private ComponentInstanceDataDefinition buildComponentInstanceDataDefinition(ComponentInstance resourceInstance, String containerComponentId, String instanceNewName, boolean generateUid, ToscaElement originToscaElement) {
String ciOriginComponentUid = resourceInstance.getComponentUid();
if (!ValidationUtils.validateStringNotEmpty(resourceInstance.getCustomizationUUID())) {
resourceInstance.setCustomizationUUID(generateCustomizationUUID());
}
ComponentInstanceDataDefinition dataDefinition = new ComponentInstanceDataDefinition(resourceInstance);
Long creationDate = resourceInstance.getCreationTime();
if (creationDate == null) {
creationDate = System.currentTimeMillis();
}
dataDefinition.setComponentUid(ciOriginComponentUid);
dataDefinition.setCreationTime(creationDate);
dataDefinition.setModificationTime(creationDate);
if (StringUtils.isNotEmpty(instanceNewName)) {
dataDefinition.setName(instanceNewName);
resourceInstance.setName(instanceNewName);
}
if (StringUtils.isNotEmpty(dataDefinition.getName()))
dataDefinition.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(dataDefinition.getName()));
dataDefinition.setIcon(resourceInstance.getIcon());
if (generateUid) {
dataDefinition.setUniqueId(UniqueIdBuilder.buildResourceInstanceUniuqeId(containerComponentId, ciOriginComponentUid, dataDefinition.getNormalizedName()));
resourceInstance.setUniqueId(dataDefinition.getUniqueId());
}
if (StringUtils.isEmpty(dataDefinition.getComponentVersion()) && originToscaElement != null)
dataDefinition.setComponentVersion((String) originToscaElement.getMetadataValue(JsonPresentationFields.VERSION));
if (StringUtils.isEmpty(dataDefinition.getComponentName()) && originToscaElement != null)
dataDefinition.setComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.NAME));
if (StringUtils.isEmpty(dataDefinition.getToscaComponentName()) && originToscaElement != null)
dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
if (dataDefinition.getOriginType() == null && originToscaElement != null) {
ResourceTypeEnum resourceType = originToscaElement.getResourceType();
OriginTypeEnum originType = null;
switch (resourceType) {
case VF:
originType = OriginTypeEnum.VF;
break;
case VFC:
originType = OriginTypeEnum.VFC;
break;
case VL:
originType = OriginTypeEnum.VL;
break;
case CP:
originType = OriginTypeEnum.CP;
break;
default:
break;
}
dataDefinition.setOriginType(originType);
}
return dataDefinition;
}
private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) {
Boolean isUniqueName = true;
try {
isUniqueName = !container.getComponentInstances().values().stream().filter(ci -> ci.getName() != null && ci.getName().equals(instanceName)).findAny().isPresent();
} catch (Exception e) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Exception occured during fetching component instance with name {} from component container {}. {} ", instanceName, container.getName(), e.getMessage());
}
return isUniqueName;
}
private String buildComponentInstanceName(String instanceSuffixNumber, String instanceName) {
return instanceName + " " + (instanceSuffixNumber == null ? 0 : instanceSuffixNumber);
}
public Either<RequirementCapabilityRelDef, StorageOperationStatus> associateResourceInstances(String componentId, RequirementCapabilityRelDef relation) {
List<RequirementCapabilityRelDef> relations = new ArrayList<>();
relations.add(relation);
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(componentId, relations);
if (associateResourceInstances.isRight()) {
return Either.right(associateResourceInstances.right().value());
}
return Either.left(associateResourceInstances.left().value().get(0));
}
@SuppressWarnings({ "unchecked" })
public Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(String componentId, List<RequirementCapabilityRelDef> relations) {
Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
TitanOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
}
GraphVertex containerV = containerVEither.left().value();
List<RequirementAndRelationshipPair> relationshipsResult = new ArrayList<RequirementAndRelationshipPair>();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
StorageOperationStatus status;
List<RequirementCapabilityRelDef> relationsList = new ArrayList<>();
for (RequirementCapabilityRelDef relation : relations) {
String fromNode = relation.getFromNode();
String toNode = relation.getToNode();
List<RequirementAndRelationshipPair> relationships = relation.getRelationships();
if (relationships == null || relationships.isEmpty()) {
BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(TitanOperationStatus.ILLEGAL_ARGUMENT));
}
for (RequirementAndRelationshipPair immutablePair : relationships) {
String requirement = immutablePair.getRequirement();
Either<RelationshipInstDataDefinition, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, immutablePair, calculatedCapabilty, calculatedRequirement, fullFilledCapabilty, fullfilledRequirement,
compositionDataDefinition, containerV.getUniqueId());
if (associateRes.isRight()) {
status = associateRes.right().value();
BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
return Either.right(status);
}
RelationshipInstDataDefinition relationshipInstData = associateRes.left().value();
RelationshipImpl relationshipImplResult = new RelationshipImpl();
relationshipImplResult.setType(relationshipInstData.getType());
RequirementAndRelationshipPair requirementAndRelationshipPair = new RequirementAndRelationshipPair(requirement, relationshipImplResult);
requirementAndRelationshipPair.setCapability(immutablePair.getCapability());
requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
requirementAndRelationshipPair.setCapabilityUid(immutablePair.getCapabilityUid());
requirementAndRelationshipPair.setRequirementUid(immutablePair.getRequirementUid());
relationshipsResult.add(requirementAndRelationshipPair);
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
RequirementCapabilityRelDef capabilityRelDef = new RequirementCapabilityRelDef();
capabilityRelDef.setFromNode(fromNode);
capabilityRelDef.setToNode(toNode);
capabilityRelDef.setRelationships(relationshipsResult);
relationsList.add(capabilityRelDef);
}
// update metadata of container and composition json
status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
return Either.left(relationsList);
}
private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult,
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult,
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult) {
containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, TitanOperationStatus> updateElement = titanDao.updateVertex(containerV);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value());
}
// update cap/req jsons, fullfilled cap/req jsons!!!!!
Either<GraphVertex, TitanOperationStatus> status;
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (status.isRight()) {
TitanOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
}
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (status.isRight()) {
TitanOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
}
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (status.isRight()) {
TitanOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
}
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (status.isRight()) {
TitanOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertTitanStatusToStorageStatus(error);
}
return StorageOperationStatus.OK;
}
@SuppressWarnings({ "unchecked" })
public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
if (requirementDef.getRelationships() == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef);
return Either.right(StorageOperationStatus.BAD_REQUEST);
}
String fromResInstanceUid = requirementDef.getFromNode();
String toResInstanceUid = requirementDef.getToNode();
Either<GraphVertex, TitanOperationStatus> containerVEither = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
TitanOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch container vertex {} error {}", componentId, error);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
}
GraphVertex containerV = containerVEither.left().value();
// DE191707 - validatations
Map<String, CompositionDataDefinition> jsonComposition = (Map<String, CompositionDataDefinition>) containerV.getJson();
CompositionDataDefinition compositionDataDefinition = jsonComposition.get(JsonConstantKeysEnum.COMPOSITION.getValue());
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
ComponentInstanceDataDefinition ciFrom = componentInstances.get(fromResInstanceUid);
if (ciFrom == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "FROM instance {} isn't under container {}", fromResInstanceUid, componentId);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
ComponentInstanceDataDefinition ciTo = componentInstances.get(toResInstanceUid);
if (ciFrom == ciTo) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Map<String, RelationshipInstDataDefinition> relations = compositionDataDefinition.getRelations();
List<RequirementAndRelationshipPair> relationPairList = requirementDef.getRelationships();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty = capFullResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> calculatedRequirement = reqResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqResult.isRight()) {
return Either.right(reqResult.right().value());
}
Map<String, MapListRequirementDataDefinition> fullfilledRequirement = reqFullResult.left().value().getRight();
for (RequirementAndRelationshipPair relationPair : relationPairList) {
Iterator<Entry<String, RelationshipInstDataDefinition>> iterator = relations.entrySet().iterator();
boolean isDeleted = false;
while (iterator.hasNext()) {
Entry<String, RelationshipInstDataDefinition> entryInJson = iterator.next();
RelationshipInstDataDefinition relationInJson = entryInJson.getValue();
if (relationInJson.getFromId().equals(fromResInstanceUid) && relationInJson.getToId().equals(toResInstanceUid)) {
if (relationPair.equalsTo(relationInJson)) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Remove relation from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(),
relationInJson.getCapabilityOwnerId(), relationInJson.getRequirementOwnerId());
iterator.remove();
// update calculated cap/req
StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relationInJson);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, fromResInstanceUid, relationInJson);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
isDeleted = true;
}
}
}
if (isDeleted == false) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(),
relationPair.getCapabilityOwnerId(), relationPair.getRequirementOwnerId());
return Either.right(StorageOperationStatus.NOT_FOUND);
}
}
StorageOperationStatus status = updateCustomizationUUID(fromResInstanceUid, compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
status = updateCustomizationUUID(toResInstanceUid, compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
// update jsons
// update metadata of container and composition json
status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
return Either.left(requirementDef);
}
private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
RelationshipInstDataDefinition relation) {
StorageOperationStatus status;
MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid);
if (reqByInstance == null) {
// move from fullfilled
status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
} else {
ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
if (reqByType == null) {
// move from fullfilled
status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
} else {
Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
.filter(cap -> cap.getOwnerId().equals(relation.getRequirementOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getRequirementId())).findFirst();
if (requirementOptional.isPresent()) {
RequirementDataDefinition requirement = requirementOptional.get();
String leftOccurrences = requirement.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
requirement.setLeftOccurrences(String.valueOf(leftIntValue));
}
status = StorageOperationStatus.OK;
} else {
// move from fullfilled
status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation);
}
}
}
return status;
}
private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
RelationshipInstDataDefinition relation) {
StorageOperationStatus status;
MapListCapabiltyDataDefinition capByInstance = calculatedCapabilty.get(toResInstanceUid);
if (capByInstance == null) {
// move from fullfilled
status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
} else {
ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
if (capByType == null) {
// move from fullfilled
status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
} else {
Optional<CapabilityDataDefinition> capabiltyOptional = capByType.getListToscaDataDefinition().stream()
.filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabiltyId())).findFirst();
if (capabiltyOptional.isPresent()) {
CapabilityDataDefinition capability = capabiltyOptional.get();
String leftOccurrences = capability.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
capability.setLeftOccurrences(String.valueOf(leftIntValue));
}
status = StorageOperationStatus.OK;
} else {
// move from fullfilled
status = moveFromFullFilledCapabilty(calculatedCapabilty, fullFilledCapabilty, toResInstanceUid, relation);
}
}
}
return status;
}
private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListCapabiltyDataDefinition> fullFilledCapabilty, String toResInstanceUid,
RelationshipInstDataDefinition relation) {
MapListCapabiltyDataDefinition capByInstance = fullFilledCapabilty.get(toResInstanceUid);
if (capByInstance == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty in fullfilled list for instance {} ", toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
ListCapabilityDataDefinition capByType = capByInstance.findByKey(relation.getType());
if (capByType == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} in fullfilled list for instance {} ", relation.getType(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
CapabilityDataDefinition cap = iterator.next();
if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getName().equals(relation.getRequirement()) && cap.getUniqueId().equals(relation.getCapabiltyId())) {
found = true;
iterator.remove();
// return to calculated list
String leftOccurrences = cap.getLeftOccurrences();
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
cap.setLeftOccurrences(String.valueOf(leftIntValue));
MapListCapabiltyDataDefinition mapListCapaDataDef = calculatedCapabilty.get(toResInstanceUid);
if (mapListCapaDataDef == null) {
mapListCapaDataDef = new MapListCapabiltyDataDefinition();
}
ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(relation.getType());
if (findByKey == null) {
findByKey = new ListCapabilityDataDefinition();
mapListCapaDataDef.put(relation.getType(), findByKey);
}
findByKey.add(cap);
break;
}
}
if (found == false) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No capabilty type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus moveFromFullFilledRequirement(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
RelationshipInstDataDefinition relation) {
MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid);
if (reqByInstance == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
ListRequirementDataDefinition reqByType = reqByInstance.findByKey(relation.getType());
if (reqByType == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} in fullfilled list for instance {} ", relation.getType(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
Iterator<RequirementDataDefinition> iterator = reqByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
RequirementDataDefinition req = iterator.next();
if (req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.getUniqueId().equals(relation.getRequirementId())) {
found = true;
iterator.remove();
// return to calculated list
String leftOccurrences = req.getLeftOccurrences();
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
req.setLeftOccurrences(String.valueOf(leftIntValue));
MapListRequirementDataDefinition mapListReqDataDef = calculatedRequirement.get(fromResInstanceUid);
if (mapListReqDataDef == null) {
mapListReqDataDef = new MapListRequirementDataDefinition();
}
ListRequirementDataDefinition findByKey = mapListReqDataDef.findByKey(relation.getType());
if (findByKey == null) {
findByKey = new ListRequirementDataDefinition();
mapListReqDataDef.put(relation.getType(), findByKey);
}
findByKey.add(req);
break;
}
}
if (found == false) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fullfilled list for instance {} ", relation.getType(), relation.getCapabilityOwnerId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
return StorageOperationStatus.OK;
}
public StorageOperationStatus updateCustomizationUUID(String componentInstanceId, CompositionDataDefinition compositionDataDefinition) {
ComponentInstanceDataDefinition componentInstance = compositionDataDefinition.getComponentInstances().get(componentInstanceId);
if (componentInstance == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch component instance by id {} from map of instances ", componentInstanceId);
return StorageOperationStatus.NOT_FOUND;
}
UUID uuid = UUID.randomUUID();
componentInstance.setCustomizationUUID(uuid.toString());
return StorageOperationStatus.OK;
}
public Either<RelationshipInstDataDefinition, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RequirementAndRelationshipPair relationPair,
Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilty,
Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) {
String requirement = relationPair.getRequirement();
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Going to associate resource instance {} to resource instance {} under component {}. Requirement is {}.", fromResInstanceUid, toResInstanceUid, containerId, requirement);
ComponentInstanceDataDefinition fromResourceInstData = componentInstances.get(fromResInstanceUid);
if (fromResourceInstData == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find from resource instance {}.", fromResInstanceUid);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
ComponentInstanceDataDefinition toResourceInstData = componentInstances.get(toResInstanceUid);
if (toResourceInstData == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Either<RelationshipInstDataDefinition, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty,
fullfilledRequirement, containerId);
if (reqVsCap.isRight()) {
StorageOperationStatus status = reqVsCap.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
return Either.right(status);
}
RelationshipInstDataDefinition relation = reqVsCap.left().value();
// add to json new relations
compositionDataDefinition.addRelation(relation.getUniqueId(), relation);
return Either.left(relation);
}
private Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) {
Either<Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>>, TitanOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel);
if (calculatedCapabiltyEither.isRight()) {
TitanOperationStatus error = calculatedCapabiltyEither.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
}
Pair<GraphVertex, Map<String, MapListCapabiltyDataDefinition>> calculatedCapabilty = calculatedCapabiltyEither.left().value();
return Either.left(calculatedCapabilty);
}
private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedRequirement(GraphVertex containerV, EdgeLabelEnum reqLabel) {
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, TitanOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel);
if (calculatedRequirementEither.isRight()) {
TitanOperationStatus error = calculatedRequirementEither.right().value();
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error);
return Either.right(DaoStatusConverter.convertTitanStatusToStorageStatus(error));
}
Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>> calculatedRequirement = calculatedRequirementEither.left().value();
return Either.left(calculatedRequirement);
}
private Either<RelationshipInstDataDefinition, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance, RequirementAndRelationshipPair relationPair,
Map<String, MapListCapabiltyDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabiltyDataDefinition> fullfilledCapabilty,
Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) {
String type = relationPair.getRelationship().getType();
// capability
String toInstId = toResInstance.getUniqueId();
MapListCapabiltyDataDefinition mapListCapabiltyDataDefinition = calculatedCapabilty.get(toInstId);
if (mapListCapabiltyDataDefinition == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabiltyDataDefinition.getMapToscaDataDefinition().get(type);
if (listCapabilityDataDefinition == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
CapabilityDataDefinition capabiltyForRelation = null;
Iterator<CapabilityDataDefinition> iteratorCap = listCapabilityDataDefinition.getListToscaDataDefinition().iterator();
while (iteratorCap.hasNext()) {
CapabilityDataDefinition cap = iteratorCap.next();
if (cap.getUniqueId().equals(relationPair.getCapabilityUid()) && cap.getOwnerId().equals(relationPair.getCapabilityOwnerId())) {
capabiltyForRelation = cap;
String leftOccurrences = cap.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
--leftIntValue;
capabiltyForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
if (leftIntValue == 0) {
// remove from calculated
iteratorCap.remove();
// move to fullfilled
MapListCapabiltyDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId);
if (mapListCapabiltyFullFilledInst == null) {
mapListCapabiltyFullFilledInst = new MapListCapabiltyDataDefinition();
fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst);
}
ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type);
if (listCapabilityFull == null) {
listCapabilityFull = new ListCapabilityDataDefinition();
mapListCapabiltyFullFilledInst.put(type, listCapabilityFull);
}
listCapabilityFull.add(capabiltyForRelation);
}
break;
} else {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabiltyForRelation.getType(), toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
if (capabiltyForRelation == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch capabilty for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
// requirements
String fromInstId = fromResInstance.getUniqueId();
MapListRequirementDataDefinition mapListRequirementDataDefinition = calculatedRequirement.get(fromInstId);
if (mapListRequirementDataDefinition == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for instance {} in container {}.", fromInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
ListRequirementDataDefinition listRequirementDataDefinition = mapListRequirementDataDefinition.getMapToscaDataDefinition().get(type);
if (listRequirementDataDefinition == null) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for type {} for instance {} in container {}.", type, fromInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
RequirementDataDefinition requirementForRelation = null;
Iterator<RequirementDataDefinition> iteratorReq = listRequirementDataDefinition.getListToscaDataDefinition().iterator();
while (iteratorReq.hasNext()) {
RequirementDataDefinition req = iteratorReq.next();
if (req.getUniqueId().equals(relationPair.getRequirementUid()) && req.getOwnerId().equals(relationPair.getRequirementOwnerId())) {
requirementForRelation = req;
String leftOccurrences = req.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(RequirementDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
--leftIntValue;
req.setLeftOccurrences(String.valueOf(leftIntValue));
if (leftIntValue == 0) {
// remove from calculated
iteratorReq.remove();
// move to fullfilled
MapListRequirementDataDefinition mapListRequirementFullFilledInst = fullfilledRequirement.get(fromInstId);
if (mapListRequirementFullFilledInst == null) {
mapListRequirementFullFilledInst = new MapListRequirementDataDefinition();
fullfilledRequirement.put(fromInstId, mapListRequirementFullFilledInst);
}
ListRequirementDataDefinition listRequirementFull = mapListRequirementFullFilledInst.findByKey(type);
if (listRequirementFull == null) {
listRequirementFull = new ListRequirementDataDefinition();
mapListRequirementFullFilledInst.put(type, listRequirementFull);
}
listRequirementFull.add(requirementForRelation);
}
break;
} else {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
if (!capabiltyForRelation.getType().equals(requirementForRelation.getCapability())) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "No math for capabilty from type {} and requirement {} from {} to {} in container {}.", capabiltyForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair);
relationshipTypeData.setType(requirementForRelation.getRelationship());
return Either.left(relationshipTypeData);
}
private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RequirementAndRelationshipPair relationPair) {
RelationshipInstDataDefinition relationshipInstData = new RelationshipInstDataDefinition();
relationshipInstData.setUniqueId(UniqueIdBuilder.buildRelationsipInstInstanceUid(fromResInstanceUid, toInstId));
relationshipInstData.setType(relationPair.getRelationship().getType());
Long creationDate = System.currentTimeMillis();
relationshipInstData.setCreationTime(creationDate);
relationshipInstData.setModificationTime(creationDate);
relationshipInstData.setCapabilityOwnerId(relationPair.getCapabilityOwnerId());
relationshipInstData.setRequirementOwnerId(relationPair.getRequirementOwnerId());
relationshipInstData.setCapabiltyId(relationPair.getCapabilityUid());
relationshipInstData.setRequirementId(relationPair.getRequirementUid());
relationshipInstData.setFromId(fromResInstanceUid);
relationshipInstData.setToId(toInstId);
relationshipInstData.setRequirement(relationPair.getRequirement());
relationshipInstData.setCapability(relationPair.getCapability());
return relationshipInstData;
}
public StorageOperationStatus associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, Resource> resourcesInstancesMap, GraphVertex containerVertex, boolean allowDeleted) {
StorageOperationStatus result = null;
String containerId = containerComponent.getUniqueId();
Map<String, ComponentInstanceDataDefinition> instancesJsonData = null;
Either<GraphVertex, TitanOperationStatus> updateElement = null;
if (!validateInstanceNames(resourcesInstancesMap)) {
result = StorageOperationStatus.INCONSISTENCY;
}
if (result == null) {
if (!validateInstanceNames(resourcesInstancesMap)) {
result = StorageOperationStatus.INCONSISTENCY;
}
}
if (result == null && !allowDeleted) {
if (!validateDeletedResources(resourcesInstancesMap)) {
result = StorageOperationStatus.INCONSISTENCY;
}
}
if (result == null) {
instancesJsonData = convertToComponentInstanceDataDefinition(resourcesInstancesMap, containerId);
}
if (result == null && MapUtils.isNotEmpty(instancesJsonData)) {
containerVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Map<String, CompositionDataDefinition> compositions = new HashMap<>();
CompositionDataDefinition composition = new CompositionDataDefinition();
composition.setComponentInstances(instancesJsonData);
compositions.put(JsonConstantKeysEnum.COMPOSITION.getValue(), composition);
containerVertex.setJson(compositions);
updateElement = titanDao.updateVertex(containerVertex);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName());
result = DaoStatusConverter.convertTitanStatusToStorageStatus(updateElement.right().value());
}
}
if (result == null) {
result = StorageOperationStatus.OK;
}
return result;
}
private Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, Resource> resourcesInstancesMap, String containerId) {
Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>();
for (Entry<ComponentInstance, Resource> entry : resourcesInstancesMap.entrySet()) {
ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, true, ModelConverter.convertToToscaElement(entry.getValue()));
instances.put(instance.getUniqueId(), instance);
}
return instances;
}
private boolean validateDeletedResources(Map<ComponentInstance, Resource> resourcesInstancesMap) {
boolean result = true;
for (Resource resource : resourcesInstancesMap.values()) {
if (resource.getIsDeleted() != null && resource.getIsDeleted()) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", resource.getName());
result = false;
break;
}
}
return result;
}
private boolean validateInstanceNames(Map<ComponentInstance, Resource> resourcesInstancesMap) {
boolean result = true;
Set<String> names = new HashSet<>();
for (ComponentInstance instance : resourcesInstancesMap.keySet()) {
if (StringUtils.isEmpty(instance.getName())) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId());
result = false;
break;
} else if (names.contains(instance.getName())) {
CommonUtility.addRecordToLog(logger, LogLevelEnum.DEBUG, "Component instance with the name {} already exsists. Cannot add component instance. ", instance.getName());
result = false;
break;
} else {
names.add(instance.getName());
}
}
return result;
}
public StorageOperationStatus addDeploymentArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts);
return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, instArtifacts, instanceId);
}
@SuppressWarnings({ "unchecked" })
public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
Either<GraphVertex, TitanOperationStatus> metadataVertex = titanDao.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (metadataVertex.isRight()) {
TitanOperationStatus status = metadataVertex.right().value();
if (status == TitanOperationStatus.NOT_FOUND) {
status = TitanOperationStatus.INVALID_ID;
}
return DaoStatusConverter.convertTitanStatusToStorageStatus(status);
}
GraphVertex metaVertex = metadataVertex.left().value();
Map<String, CompositionDataDefinition> json = (Map<String, CompositionDataDefinition>) metaVertex.getJson();
CompositionDataDefinition compositionDataDefinition = json.get(JsonConstantKeysEnum.COMPOSITION.getValue());
StorageOperationStatus status = updateCustomizationUUID(instanceId, compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
logger.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status);
return status;
}
Either<GraphVertex, TitanOperationStatus> updateVertex = titanDao.updateVertex(metaVertex);
if (updateVertex.isRight()) {
logger.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value());
return DaoStatusConverter.convertTitanStatusToStorageStatus(updateVertex.right().value());
}
return StorageOperationStatus.OK;
}
public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
if (groupInstances != null) {
Either<Map<String, MapGroupsDataDefinition>, TitanOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS);
if (dataFromGraph.isRight()) {
return DaoStatusConverter.convertTitanStatusToStorageStatus(dataFromGraph.right().value());
}
MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId);
if (grInstPerInstance == null) {
logger.debug("No instance groups for instance {} in component {}", instanceId, componentId);
return StorageOperationStatus.NOT_FOUND;
}
for (String instGroupForUpdate : groupInstances) {
GroupInstanceDataDefinition groupInst = grInstPerInstance.findByKey(instGroupForUpdate);
if (groupInst == null) {
logger.debug("No group instance {} in group list for instance {} in component {}", instGroupForUpdate, instanceId, componentId);
continue;
}
UUID uuid = UUID.randomUUID();
groupInst.setCustomizationUUID(uuid.toString());
}
}
return StorageOperationStatus.OK;
}
public StorageOperationStatus addGroupInstancesToComponentInstance(Component containerComponent, ComponentInstance componentInstance, List<GroupInstance> groupInstances) {
return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_GROUPS, VertexTypeEnum.INST_GROUPS,
new MapDataDefinition<>(groupInstances.stream().collect(Collectors.toMap(gi -> gi.getName(), gi -> gi))), componentInstance.getUniqueId());
}
public StorageOperationStatus addDeploymentArtifactsToComponentInstance(Component containerComponent, ComponentInstance componentInstance, Map<String, ArtifactDefinition> deploymentArtifacts) {
return addToscaDataDeepElementsBlockToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS, new MapDataDefinition<>(deploymentArtifacts),
componentInstance.getUniqueId());
}
public StorageOperationStatus updateComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus addComponentInstanceProperty(Component containerComponent, String componentInstanceId, ComponentInstanceProperty property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus updateComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus addComponentInstanceInput(Component containerComponent, String componentInstanceId, ComponentInstanceInput property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, property, pathKeys, JsonPresentationFields.NAME);
}
}
|