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
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
|
/*-
* ============LICENSE_START=======================================================
* SDC
* ================================================================================
* Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
* ================================================================================
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ============LICENSE_END=========================================================
*/
package org.openecomp.sdc.be.model.jsonjanusgraph.operations;
import fj.data.Either;
import java.io.IOException;
import java.util.ArrayList;
import java.util.EnumMap;
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.function.BiConsumer;
import java.util.function.BiPredicate;
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.janusgraph.core.JanusGraphVertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.ConfigurationManager;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
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.EdgePropertyEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
import org.openecomp.sdc.be.dao.jsongraph.utils.JsonParserUtils;
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.InterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListCapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.ListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapAttributesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapCapabilityProperty;
import org.openecomp.sdc.be.datatypes.elements.MapDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapGroupsDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapInterfaceDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListCapabilityDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapListRequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.MapPropertiesDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.OperationInputDefinition;
import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RelationshipInstDataDefinition;
import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.GraphPropertyEnum;
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.datatypes.tosca.ToscaDataDefinition;
import org.openecomp.sdc.be.model.*;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.NodeType;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElementTypeEnum;
import org.openecomp.sdc.be.model.jsonjanusgraph.enums.JsonConstantKeysEnum;
import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
import org.openecomp.sdc.be.model.operations.StorageException;
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.be.ui.model.OperationUi;
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.log.elements.LoggerSupportability;
import org.openecomp.sdc.common.log.enums.LogLevel;
import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
import org.openecomp.sdc.common.log.enums.StatusCode;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.openecomp.sdc.common.util.ValidationUtils;
@org.springframework.stereotype.Component("node-template-operation")
public class NodeTemplateOperation extends BaseOperation {
private static final String FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR = "Failed to fetch container vertex {} error {}";
private static final String FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE = "Failed to update topology template {} with new component instance {}. ";
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";
static final String HEAT_ENV_NAME = "heatEnv";
static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
static final String HEAT_ENV_SUFFIX = "env";
private static Integer defaultHeatTimeout;
public static final Integer NON_HEAT_TIMEOUT = 0;
private static final Logger log = Logger.getLogger(NodeTemplateOperation.class.getName());
private static final LoggerSupportability loggerSupportability=LoggerSupportability.getLogger(NodeTemplateOperation.class.getName());
public NodeTemplateOperation() {
defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getDefaultMinutes();
if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
defaultHeatTimeout = 60;
}
}
public static Integer getDefaultHeatTimeout() {
return defaultHeatTimeout;
}
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(log, LogLevelEnum.DEBUG, "Going to create component instance {} in component {}", componentInstance, container.getUniqueId());
ComponentInstanceDataDefinition componentInstanceData = null;
Either<String, StorageOperationStatus> newInstanceNameRes = null;
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseJson);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(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 (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
TopologyTemplate updatedContainer = addComponentInstanceRes.left().value();
result = addCapAndReqToProxyServiceInstance(updatedContainer, componentInstance, componentInstanceData);
if(result.isRight()) {
return result;
}
result = addServiceInstancePropertiesToProxyServiceInstance(updatedContainer, componentInstance);
if(result.isRight()) {
return result;
}
result = addServiceInstanceInputsToProxyServiceInstance(updatedContainer, componentInstance);
if(result.isRight()) {
return result;
}
result = addServiceInstanceInterfacesToProxyServiceInstance(updatedContainer, componentInstance);
if(result.isRight()) {
return result;
}
}
}
if (result == null) {
result = Either.left(new ImmutablePair<>(addComponentInstanceRes.left().value(), componentInstanceData.getUniqueId()));
}
return result;
}
private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addCapAndReqToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance,
ComponentInstanceDataDefinition componentInstanceData) {
Map<String, MapListCapabilityDataDefinition> calcCap = updatedContainer.getCalculatedCapabilities();
Map<String, MapListRequirementDataDefinition> calcReg = updatedContainer.getCalculatedRequirements();
Map<String, MapCapabilityProperty> calcCapProp = updatedContainer.getCalculatedCapabilitiesProperties();
Map<String, List<CapabilityDefinition>> additionalCap = componentInstance.getCapabilities();
Map<String, List<RequirementDefinition>> additionalReq = componentInstance.getRequirements();
MapListCapabilityDataDefinition allCalculatedCap = calcCap == null || !calcCap.containsKey(componentInstanceData.getUniqueId()) ? new MapListCapabilityDataDefinition() : calcCap.get(componentInstanceData.getUniqueId());
/******** capability ****************************/
StorageOperationStatus status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, componentInstanceData.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
return Either.right(status);
}
if (additionalCap != null && !additionalCap.isEmpty()) {
Map<String, ListCapabilityDataDefinition> serverCap = additionalCap.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, en -> new ListCapabilityDataDefinition(en.getValue().stream().map(CapabilityDataDefinition::new).collect(Collectors.toList()))));
serverCap.entrySet().forEach(entryPerType -> entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> {
cap.addToPath(componentInstance.getUniqueId());
allCalculatedCap.add(entryPerType.getKey(), cap);
}));
addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES, allCalculatedCap, componentInstance.getUniqueId());
/******** capability property ****************************/
status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, componentInstanceData.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated capabilty properties for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
return Either.right(status);
}
MapCapabilityProperty allCalculatedCapProp = calcCapProp == null || !calcCapProp.containsKey(componentInstanceData.getUniqueId()) ? new MapCapabilityProperty() : calcCapProp.get(componentInstanceData.getUniqueId());
additionalCap.forEach(new BiConsumer<String, List<CapabilityDefinition>>() {
@Override
public void accept(String s, List<CapabilityDefinition> caps) {
if (caps != null && !caps.isEmpty()) {
MapPropertiesDataDefinition dataToCreate;
for (CapabilityDefinition cap : caps) {
dataToCreate = new MapPropertiesDataDefinition();
List<ComponentInstanceProperty> capPrps = cap.getProperties();
if (capPrps != null) {
for (ComponentInstanceProperty cip : capPrps) {
dataToCreate.put(cip.getName(), new PropertyDataDefinition(cip));
}
StringBuilder sb = new StringBuilder(componentInstance.getUniqueId());
sb.append(ModelConverter.CAP_PROP_DELIM);
sb.append(cap.getOwnerId());
sb.append(ModelConverter.CAP_PROP_DELIM).append(s).append(ModelConverter.CAP_PROP_DELIM).append(cap.getName());
allCalculatedCapProp.put(sb.toString(), dataToCreate);
}
}
}
}
});
addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, allCalculatedCapProp, componentInstance.getUniqueId());
}
/******** Requirements property ****************************/
if (additionalReq != null && !additionalReq.isEmpty()) {
MapListRequirementDataDefinition allCalculatedReq = calcReg == null || !calcReg.containsKey(componentInstanceData.getUniqueId()) ? new MapListRequirementDataDefinition() : calcReg.get(componentInstanceData.getUniqueId());
status = deleteToscaDataDeepElementsBlockOfToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, componentInstanceData.getUniqueId());
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove calculated Requirements for instance {} in container {}. error {] ", componentInstanceData.getUniqueId(), updatedContainer.getUniqueId(), status);
return Either.right(status);
}
Map<String, ListRequirementDataDefinition> serverReq = additionalReq.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, en -> new ListRequirementDataDefinition(en.getValue().stream().map(RequirementDataDefinition::new).collect(Collectors.toList()))));
serverReq.entrySet().forEach(entryPerType -> entryPerType.getValue().getListToscaDataDefinition().forEach(cap -> {
cap.addToPath(componentInstance.getUniqueId());
allCalculatedReq.add(entryPerType.getKey(), cap);
}));
addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(), EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS, allCalculatedReq, componentInstance.getUniqueId());
}
Either<ToscaElement, StorageOperationStatus> updatedComponentInstanceRes = topologyTemplateOperation.getToscaElement(updatedContainer.getUniqueId());
if (updatedComponentInstanceRes.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch updated topology template {} with new component instance {}. ", updatedContainer.getName(), componentInstance.getName());
Either.right(updatedComponentInstanceRes.right().value());
}
return Either.left(new ImmutablePair<>((TopologyTemplate) updatedComponentInstanceRes.left().value(), componentInstanceData.getUniqueId()));
}
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()) || componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy || componentInstance.getOriginType() == OriginTypeEnum.ServiceSubstitution) {
instanceName = buildComponentInstanceName(instanceNumberSuffix, instanceName);
} else if (!isUniqueInstanceName(container, componentInstance.getName())) {
CommonUtility.addRecordToLog(log, 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;
}
private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstancePropertiesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
List<PropertyDefinition> propertiesList = componentInstance.getProperties();
if (propertiesList != null && !propertiesList.isEmpty()) {
Map<String, PropertyDataDefinition> propertiesMap = propertiesList.stream().map(PropertyDataDefinition::new)
.collect(Collectors.toMap(
PropertyDataDefinition::getName, i -> i));
MapPropertiesDataDefinition instProperties = new MapPropertiesDataDefinition(propertiesMap);
Map<String, MapPropertiesDataDefinition> instPropertiesMap = new HashMap<>();
instPropertiesMap.put(componentInstance.getUniqueId(), instProperties);
updatedContainer.setInstProperties(instPropertiesMap);
Either<GraphVertex, JanusGraphOperationStatus> getToscaElementRes = janusGraphDao
.getVertexById(updatedContainer.getUniqueId(), JsonParseFlagEnum.NoParse);
if(getToscaElementRes.isLeft()){
deleteToscaDataDeepElementsBlockToToscaElement(getToscaElementRes.left().value(), EdgeLabelEnum.INST_PROPERTIES,
VertexTypeEnum.INST_PROPERTIES, componentInstance.getUniqueId());
}
StorageOperationStatus status = addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, instProperties,
componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId()));
}
private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstanceInputsToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
List<InputDefinition> inputsList = componentInstance.getInputs();
if (CollectionUtils.isNotEmpty(inputsList)) {
Map<String, PropertyDataDefinition> inputsMap = inputsList.stream().map(
PropertyDataDefinition::new).collect(Collectors.toMap(PropertyDataDefinition::getName, i -> i));
MapPropertiesDataDefinition instInputs = new MapPropertiesDataDefinition(inputsMap);
Map<String, MapPropertiesDataDefinition> instInputsMap = new HashMap<>();
instInputsMap.put(componentInstance.getUniqueId(), instInputs);
updatedContainer.setInstInputs(instInputsMap);
StorageOperationStatus status =
addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputs,
componentInstance.getUniqueId());
if(status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId()));
}
private Either<ImmutablePair<TopologyTemplate, String>, StorageOperationStatus> addServiceInstanceInterfacesToProxyServiceInstance(TopologyTemplate updatedContainer, ComponentInstance componentInstance) {
Map<String, Object> interfaces = componentInstance.getInterfaces();
if(MapUtils.isNotEmpty(interfaces)){
Map<String, InterfaceDataDefinition> interfacesMap = interfaces.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> (InterfaceDataDefinition) e.getValue()));
MapInterfaceDataDefinition instInterfaces = new MapInterfaceDataDefinition(interfacesMap);
Map<String, MapInterfaceDataDefinition> instInterfacesMap = new HashMap<>();
instInterfacesMap.put(componentInstance.getUniqueId(), instInterfaces);
updatedContainer.setComponentInstInterfaces(instInterfacesMap);
StorageOperationStatus status =
addToscaDataDeepElementsBlockToToscaElement(updatedContainer.getUniqueId(),
EdgeLabelEnum.INST_INTERFACES, VertexTypeEnum.INST_INTERFACES, instInterfaces,
componentInstance.getUniqueId());
if(status != StorageOperationStatus.OK) {
return Either.right(status);
}
}
return Either.left(new ImmutablePair<>(updatedContainer, componentInstance.getUniqueId()));
}
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(log, LogLevelEnum.TRACE, "Going to create component instance {} in component {}", componentInstance, containerComponentId);
String instOriginComponentId = componentInstance.getComponentUid();
Either<GraphVertex, JanusGraphOperationStatus> updateElement = null;
Boolean isDeleted = (Boolean) originToscaElement.getMetadataValue(JsonPresentationFields.IS_DELETED);
if (!allowDeleted && (isDeleted != null) && isDeleted) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance", instOriginComponentId);
result = Either.right(StorageOperationStatus.INVALID_ID);
}
Boolean isArchived = originToscaElement.isArchived();
if (isArchived != null && isArchived) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to create instance {}. Origin {} component is archived . ", componentInstance.getName(), originToscaElement.getName());
result = Either.right(StorageOperationStatus.COMPONENT_IS_ARCHIVED);
}
if (result == null) {
container.addComponentInstance(componentInstance);
metadataVertex.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex, container, JsonParseFlagEnum.ParseAll);
updateElement = janusGraphDao.updateVertex(metadataVertex);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
Either<GraphVertex, StorageOperationStatus> addToscaDataRes = addComponentInstanceToscaDataToContainerComponent(originToscaElement, componentInstance, updateElement.left().value());
if (addToscaDataRes.isRight()) {
result = Either.right(addToscaDataRes.right().value());
}
}
if (result == null) {
StorageOperationStatus createInstanceEdge = createInstanceEdge(metadataVertex, componentInstance);
result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge);
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, 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(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstance, containerComponentId);
ComponentInstanceDataDefinition componentInstanceData = null;
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(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, JanusGraphOperationStatus> updateElement = janusGraphDao
.updateVertex(metadataVertex.left().value());
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstance.getName());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, 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, ComponentParametersView filter) {
Either<TopologyTemplate, StorageOperationStatus> result = null;
Either<ToscaElement, StorageOperationStatus> updateContainerComponentRes = null;
String containerComponentId = container.getUniqueId();
CommonUtility.addRecordToLog(log, LogLevelEnum.TRACE, "Going to update component instance metadata of container component {}", containerComponentId);
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
if (result == null) {
metadataVertex.left().value().setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
topologyTemplateOperation.fillToscaElementVertexData(metadataVertex.left().value(), container, JsonParseFlagEnum.ParseAll);
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao
.updateVertex(metadataVertex.left().value());
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {}. ", container.getName());
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId, filter);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, 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(log, LogLevelEnum.TRACE, "Going to update component instance metadata {} of container component {}", componentInstanceId, containerComponentId);
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(container.getUniqueId(), JsonParseFlagEnum.ParseMetadata);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
}
GraphVertex containerV = null;
ComponentInstanceDataDefinition removedComponentInstance = null;
if (result == null) {
removedComponentInstance = container.getComponentInstances().remove(componentInstanceId);
containerV = metadataVertex.left().value();
StorageOperationStatus status = removeRelationsOfInstance(container, componentInstanceId, containerV);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, 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, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_UPDATE_TOPOLOGY_TEMPLATE_WITH_NEW_COMPONENT_INSTANCE, container.getName(), componentInstanceId);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (result == null) {
StorageOperationStatus status = deleteComponentInstanceToscaDataFromContainerComponent(containerV, componentInstanceId);
if (status != StorageOperationStatus.OK) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to delete data for instance {} in container {}. error {] ", componentInstanceId, container.getUniqueId(), status);
return Either.right(status);
}
ComponentInstance componentInstance = new ComponentInstance(removedComponentInstance);
StorageOperationStatus createInstanceEdge = removeInstanceEdge(containerV, componentInstance);
result = createInstanceEdge == StorageOperationStatus.OK ? null : Either.right(createInstanceEdge);
}
if (result == null) {
updateContainerComponentRes = topologyTemplateOperation.getToscaElement(containerComponentId);
if (updateContainerComponentRes.isRight()) {
CommonUtility.addRecordToLog(log, 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, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return capResult.right().value();
}
Map<String, MapListCapabilityDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capFullResult.isRight()) {
return capFullResult.right().value();
}
Map<String, MapListCapabilityDataDefinition> 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, null);
updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, relationToDelete.getToId(), relationToDelete, null);
}
if (relationToDelete.getToId().equals(ciToRemove)) {
updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fullfilledRequirement, relationToDelete.getFromId(), relationToDelete, null);
updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapabilty, fullFilledCapabilty, ciToRemove, relationToDelete, null);
}
}
}
return updateAllAndCalculatedCapReqOnGraph(container.getUniqueId(), containerV, capResult, capFullResult, reqResult, reqFullResult);
}
}
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(log, 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(log, 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(log, 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(log, 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(log, 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(log, 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(log, 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(log, 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(log, 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(log, 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(log, LogLevelEnum.DEBUG, "Failed to remove instance artifacts for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.EXTERNAL_REFS, VertexTypeEnum.EXTERNAL_REF, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to remove instance external refs for instance {} in container {}. error {] ", componentInstanceId, containerV.getUniqueId(), status);
return status;
}
status = deleteToscaDataDeepElementsBlockToToscaElement(containerV, EdgeLabelEnum.INST_INTERFACES,
VertexTypeEnum.INST_INTERFACES, componentInstanceId);
if (status != StorageOperationStatus.OK && status != StorageOperationStatus.NOT_FOUND) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Failed to remove service instance interfaces 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) {
Either<GraphVertex, StorageOperationStatus> result;
StorageOperationStatus status;
if (originToscaElement.getToscaType() == ToscaElementTypeEnum.NODE_TYPE) {
status = addComponentInstanceToscaDataToNodeTypeContainer((NodeType) originToscaElement, componentInstance, updatedContainerVertex);
} 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 instInputs = new MapPropertiesDataDefinition(originTopologyTemplate.getInputs());
MapPropertiesDataDefinition instInputsAsProperties = turnInputsIntoProperties(instInputs);
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, instInputsAsProperties, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
return status;
}
private MapPropertiesDataDefinition turnInputsIntoProperties(MapPropertiesDataDefinition instInput) {
if (instInput.getMapToscaDataDefinition() != null) {
for (PropertyDataDefinition currProp : instInput.getMapToscaDataDefinition().values()) {
String temp = currProp.getValue();
currProp.setValue(currProp.getDefaultValue());
currProp.setDefaultValue(temp);
}
}
return instInput;
}
private MapListCapabilityDataDefinition prepareCalculatedCapabiltyForTopologyTemplate(
Map<String, ListCapabilityDataDefinition> capabilities,
ComponentInstanceDataDefinition componentInstance,
MapListCapabilityDataDefinition calculatedCap) {
MapListCapabilityDataDefinition allCalculatedCap =
new MapListCapabilityDataDefinition(calculatedCap);
populateCapability(capabilities, componentInstance, allCalculatedCap);
return allCalculatedCap;
}
private void populateCapability(Map<String, ListCapabilityDataDefinition> capabilities,
ComponentInstanceDataDefinition componentInstance,
MapListCapabilityDataDefinition allCalculatedCap) {
capabilities.forEach((key, value) -> {
List<CapabilityDataDefinition> listCapabilities = value.getListToscaDataDefinition()
.stream().map(CapabilityDataDefinition::new).collect(Collectors.toList());
listCapabilities.forEach(cap -> {
cap.setSource(componentInstance.getComponentUid());
cap.addToPath(componentInstance.getUniqueId());
log.debug("enter populateCapability,get Capability OwnerId:{},get componentInstance UniqueId:{}",
cap.getOwnerId(), componentInstance.getUniqueId());
cap.setOwnerId(componentInstance.getUniqueId());
log.debug("enter populateCapability,get Capability OwnerName:{},get componentInstance Name:{}",
cap.getOwnerName(), componentInstance.getName());
if (cap.getOwnerName() == null || cap.getOwnerName().isEmpty()) {
cap.setOwnerName(componentInstance.getName());
}
cap.setLeftOccurrences(cap.getMaxOccurrences());
allCalculatedCap.add(key, cap);
});
});
}
private MapListRequirementDataDefinition prepareCalculatedRequirementForTopologyTemplate(
Map<String, ListRequirementDataDefinition> requirements,
ComponentInstanceDataDefinition componentInstance,
MapListRequirementDataDefinition calculatedReqs) {
MapListRequirementDataDefinition allCalculatedReq =
new MapListRequirementDataDefinition(calculatedReqs);
populateRequirement(requirements, componentInstance, allCalculatedReq);
return allCalculatedReq;
}
private void populateRequirement(Map<String, ListRequirementDataDefinition> requirements,
ComponentInstanceDataDefinition componentInstance,
MapListRequirementDataDefinition allCalculatedReq) {
requirements.forEach((key, value) -> {
List<RequirementDataDefinition> listRequirements = value.getListToscaDataDefinition()
.stream().map(RequirementDataDefinition::new).collect(Collectors.toList());
listRequirements.forEach(req -> {
req.setSource(componentInstance.getComponentUid());
req.addToPath(componentInstance.getUniqueId());
log.debug("enter populateRequirement,get init Requirements OwnerId:{},get componentInstance UniqueId:{}",
req.getOwnerId(), componentInstance.getUniqueId());
if (req.getOwnerId() == null || req.getOwnerId().isEmpty()) {
req.setOwnerId(componentInstance.getUniqueId());
}
log.debug("enter populateRequirement,get init Requirements OwnerName:{}", req.getOwnerName());
if (req.getOwnerName() == null || req.getOwnerName().isEmpty()) {
req.setOwnerName(componentInstance.getName());
}
req.setLeftOccurrences(req.getMaxOccurrences());
allCalculatedReq.add(key, req);
});
});
}
private StorageOperationStatus addCalculatedCapReqFromTopologyTemplate(TopologyTemplate originTopologyTemplate, ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
Map<String, MapListCapabilityDataDefinition> calculatedCapabilities = originTopologyTemplate.getCalculatedCapabilities();
MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition();
if (calculatedCapabilities != null) {
calculatedCapabilities.forEach((key1, value1) -> {
Map<String, ListCapabilityDataDefinition> mapByType = value1.getMapToscaDataDefinition();
mapByType.forEach((key, value) -> value.getListToscaDataDefinition().forEach(cap -> {
cap.addToPath(componentInstance.getUniqueId());
allCalculatedCap.add(key, cap);
}));
});
}
MapListCapabilityDataDefinition allCaps;
Map<String, ListCapabilityDataDefinition> capabilities = originTopologyTemplate.getCapabilities();
if (MapUtils.isNotEmpty(capabilities)) {
allCaps = prepareCalculatedCapabiltyForTopologyTemplate(capabilities, componentInstance,
allCalculatedCap);
} else {
allCaps = new MapListCapabilityDataDefinition(allCalculatedCap);
}
if(!allCaps.isEmpty()) {
StorageOperationStatus calculatedCapabilitiesResult =
addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
EdgeLabelEnum.CALCULATED_CAPABILITIES, VertexTypeEnum.CALCULATED_CAPABILITIES,
allCaps, componentInstance.getUniqueId());
if (calculatedCapabilitiesResult != StorageOperationStatus.OK) {
return calculatedCapabilitiesResult;
}
MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition();
calculatedCapabilitiesResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
EdgeLabelEnum.FULLFILLED_CAPABILITIES, VertexTypeEnum.FULLFILLED_CAPABILITIES,
fullCalculatedCap, componentInstance.getUniqueId());
if (calculatedCapabilitiesResult != StorageOperationStatus.OK) {
return calculatedCapabilitiesResult;
}
}
Map<String, MapListRequirementDataDefinition> calculatedRequirements =
originTopologyTemplate.getCalculatedRequirements();
MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
if (calculatedRequirements != null) {
calculatedRequirements.forEach((key, value) -> {
Map<String, ListRequirementDataDefinition> mapByType =
value.getMapToscaDataDefinition();
mapByType.forEach((key1, value1) -> value1.getListToscaDataDefinition().stream()
.filter(RequirementDataDefinition::isExternal).forEach(req -> {
req.addToPath(componentInstance.getUniqueId());
req.setExternal(false);
allCalculatedReq.add(key1, req);
}));
});
}
MapListRequirementDataDefinition allReqs;
Map<String, ListRequirementDataDefinition> requirements = originTopologyTemplate.getRequirements();
if (MapUtils.isNotEmpty(requirements)) {
allReqs = prepareCalculatedRequirementForTopologyTemplate(requirements,
componentInstance, allCalculatedReq);
} else
allReqs = new MapListRequirementDataDefinition(allCalculatedReq);
if(!allReqs.isEmpty()) {
StorageOperationStatus calculatedRequirementResult =
addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
EdgeLabelEnum.CALCULATED_REQUIREMENTS, VertexTypeEnum.CALCULATED_REQUIREMENTS,
allReqs, componentInstance.getUniqueId());
if (calculatedRequirementResult != StorageOperationStatus.OK) {
return calculatedRequirementResult;
}
MapListRequirementDataDefinition fullCalculatedReq = new MapListRequirementDataDefinition();
calculatedRequirementResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
EdgeLabelEnum.FULLFILLED_REQUIREMENTS, VertexTypeEnum.FULLFILLED_REQUIREMENTS,
fullCalculatedReq,
componentInstance.getUniqueId());
if (calculatedRequirementResult != StorageOperationStatus.OK) {
return calculatedRequirementResult;
}
}
Map<String, MapCapabilityProperty> calculatedCapabilitiesProperties = originTopologyTemplate.getCalculatedCapabilitiesProperties();
Map<String, MapPropertiesDataDefinition> updateKeyMap = new HashMap<>();
if (calculatedCapabilitiesProperties != null && !calculatedCapabilitiesProperties.isEmpty()) {
for (MapCapabilityProperty map : calculatedCapabilitiesProperties.values()) {
for (Entry<String, MapPropertiesDataDefinition> entry : map.getMapToscaDataDefinition().entrySet()) {
String newKey = (componentInstance.getUniqueId() + ModelConverter.CAP_PROP_DELIM + entry.getKey());
updateKeyMap.put(newKey, entry.getValue());
}
}
}
Map<String, MapPropertiesDataDefinition> capabilitiesProperties =
originTopologyTemplate.getCapabilitiesProperties();
Map<String, MapPropertiesDataDefinition> updateKeyMapCapabilitiesProperties;
if (MapUtils.isNotEmpty(capabilitiesProperties)) {
updateKeyMapCapabilitiesProperties = capabilitiesProperties.entrySet().stream()
.collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(),
componentInstance.getUniqueId()), Entry::getValue));
}
else {
updateKeyMapCapabilitiesProperties = new HashMap<>();
}
updateKeyMap.putAll(updateKeyMapCapabilitiesProperties);
MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap);
if(MapUtils.isNotEmpty(capabilitiesProperties) || MapUtils.isNotEmpty(calculatedCapabilitiesProperties )) {
StorageOperationStatus calculatedResult =
addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex,
EdgeLabelEnum.CALCULATED_CAP_PROPERTIES,
VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty,
componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
return StorageOperationStatus.OK;
}
public StorageOperationStatus updateComponentInstanceRequirement(String componentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition) {
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
return StorageOperationStatus.GENERAL_ERROR;
}
GraphVertex containerV = containerVEither.left().value();
return updateComponentInstanceRequirement(componentId, componentInstanceUniqueId, requirementDataDefinition, containerV);
}
private StorageOperationStatus updateComponentInstanceRequirement(String componentId, String componentInstanceUniqueId, RequirementDataDefinition requirementDataDefinition, GraphVertex containerV) {
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> existingReqs = getCalculatedRequirements(componentId);
if (existingReqs.isRight()) {
return existingReqs.right().value();
}
MapListRequirementDataDefinition componentInstanceRequirementsMap = existingReqs.left().value().getRight().get(componentInstanceUniqueId);
if (componentInstanceRequirementsMap == null) {
return StorageOperationStatus.NOT_FOUND;
}
ListRequirementDataDefinition listRequirementDataDefinition = componentInstanceRequirementsMap.getMapToscaDataDefinition().get(requirementDataDefinition.getCapability());
listRequirementDataDefinition.getListToscaDataDefinition().stream()
.filter(e -> requirementDataDefinition.getOwnerId().equals(e.getOwnerId()) && requirementDataDefinition.getName().equals(e.getName()))
.forEach(r -> r.setExternal(requirementDataDefinition.isExternal()));
return updateCalculatedReqOnGraph(componentId, containerV, existingReqs);
}
private Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> getCalculatedRequirements(String componentId) {
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> result = null;
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
if (result == null) {
GraphVertex containerV = containerVEither.left().value();
result = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
}
return result;
}
private StorageOperationStatus updateCalculatedReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqResult
) {
containerV.setJsonMetadataField(JsonPresentationFields.LAST_UPDATE_DATE, System.currentTimeMillis());
Either<GraphVertex, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value());
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId());
Either<GraphVertex, JanusGraphOperationStatus> status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
return StorageOperationStatus.OK;
}
private StorageOperationStatus addComponentInstanceToscaDataToNodeTypeContainer(NodeType originNodeType,
ComponentInstanceDataDefinition componentInstance, GraphVertex updatedContainerVertex) {
StorageOperationStatus status;
if(MapUtils.isNotEmpty(originNodeType.getProperties())){
MapPropertiesDataDefinition instProperties =
new MapPropertiesDataDefinition(originNodeType.getProperties());
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_PROPERTIES,
VertexTypeEnum.INST_PROPERTIES, instProperties, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
}
if(MapUtils.isNotEmpty(originNodeType.getAttributes())){
MapAttributesDataDefinition instAttributes =
new MapAttributesDataDefinition(originNodeType.getAttributes());
status = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.INST_ATTRIBUTES,
VertexTypeEnum.INST_ATTRIBUTES, instAttributes, componentInstance.getUniqueId());
if (status != StorageOperationStatus.OK) {
return status;
}
}
return addCalculatedCapReqFromNodeType(originNodeType, componentInstance, updatedContainerVertex);
}
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())) {
ArtifactDataDefinition artifactEnv = createArtifactPlaceHolderInfo(artifact, componentInstanceId, user, envType);
instDeploymentArtifacts.put(artifactEnv.getArtifactLabel(), artifactEnv);
}
});
deploymentArtifacts.putAll(instDeploymentArtifacts);
return new MapArtifactDataDefinition(deploymentArtifacts);
}
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) {
log.debug("no deployment artifacts are configured for generated artifacts");
return null;
}
Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(heatEnvType);
if (placeHolderData == null) {
log.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.getCapabilities();
MapListCapabilityDataDefinition 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.getCapabilitiesProperties();
if (capabiltiesProperties != null) {
Map<String, MapPropertiesDataDefinition> updateKeyMap = capabiltiesProperties.entrySet().stream().collect(Collectors.toMap(e -> createCapPropertyKey(e.getKey(), componentInstance.getUniqueId()), Entry::getValue));
MapCapabilityProperty mapCapabilityProperty = new MapCapabilityProperty(updateKeyMap);
calculatedResult = addToscaDataDeepElementsBlockToToscaElement(updatedContainerVertex, EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, mapCapabilityProperty, componentInstance.getUniqueId());
if (calculatedResult != StorageOperationStatus.OK) {
return calculatedResult;
}
}
MapListCapabilityDataDefinition fullCalculatedCap = new MapListCapabilityDataDefinition();
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();
}
/**
* Prepares a map of capabilities lists Produces a deep copy of the received map of capabilities Sets values to the specific fields according to received component instance
*
* @param capabilities
* @param componentInstance
* @return
*/
public MapListCapabilityDataDefinition prepareCalculatedCapabiltyForNodeType(Map<String, ListCapabilityDataDefinition> capabilities, ComponentInstanceDataDefinition componentInstance) {
if (capabilities != null) {
MapListCapabilityDataDefinition allCalculatedCap = new MapListCapabilityDataDefinition();
populateCapability(capabilities, componentInstance, allCalculatedCap);
return allCalculatedCap;
}
return null;
}
/**
* Prepares a map of requirements lists Produces a deep copy of the received map of requirements Sets values to the specific fields according to received component instance
*
* @param requirements
* @param componentInstance
* @return
*/
public MapListRequirementDataDefinition prepareCalculatedRequirementForNodeType(Map<String, ListRequirementDataDefinition> requirements, ComponentInstanceDataDefinition componentInstance) {
if (requirements != null) {
MapListRequirementDataDefinition allCalculatedReq = new MapListRequirementDataDefinition();
populateRequirement(requirements, componentInstance, allCalculatedReq);
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, null);
groupInstance.setGroupInstanceArtifacts(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::getUniqueId).collect(Collectors.toList()));
groupInstance.setGroupInstanceArtifactsUuid(groupArtifacts.getValue().stream().map(ArtifactDataDefinition::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();
Long modificationTime;
if (creationDate == null) {
creationDate = System.currentTimeMillis();
modificationTime = creationDate;
} else {
modificationTime = System.currentTimeMillis();
}
dataDefinition.setComponentUid(ciOriginComponentUid);
dataDefinition.setCreationTime(creationDate);
dataDefinition.setModificationTime(modificationTime);
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 (originToscaElement != null && dataDefinition.getToscaComponentName() == null)
dataDefinition.setToscaComponentName((String) originToscaElement.getMetadataValue(JsonPresentationFields.TOSCA_RESOURCE_NAME));
if (dataDefinition.getOriginType() == null && originToscaElement != null) {
ResourceTypeEnum resourceType = originToscaElement.getResourceType();
OriginTypeEnum originType = OriginTypeEnum.findByValue(resourceType.name());
dataDefinition.setOriginType(originType);
}
if (dataDefinition.getOriginType() == OriginTypeEnum.ServiceProxy)
dataDefinition.setIsProxy(true);
return dataDefinition;
}
private Boolean isUniqueInstanceName(TopologyTemplate container, String instanceName) {
Boolean isUniqueName = true;
try {
isUniqueName = !container.getComponentInstances().values().stream().anyMatch(ci -> ci.getName() != null && ci.getName().equals(instanceName));
} catch (Exception e) {
CommonUtility.addRecordToLog(log, 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(Component component, String componentId, RequirementCapabilityRelDef relation) {
List<RequirementCapabilityRelDef> relations = new ArrayList<>();
relations.add(relation);
Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances = associateResourceInstances(component, componentId, relations);
if (associateResourceInstances.isRight()) {
return Either.right(associateResourceInstances.right().value());
}
return Either.left(associateResourceInstances.left().value().get(0));
}
@SuppressWarnings({"unchecked"})
public <T extends ToscaDataDefinition> Either<List<RequirementCapabilityRelDef>, StorageOperationStatus> associateResourceInstances(Component component, String componentId, List<RequirementCapabilityRelDef> relations) {
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
GraphVertex containerV = containerVEither.left().value();
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabilityDataDefinition> calculatedCapabilty = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabilityDataDefinition> 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) {
List<CapabilityRequirementRelationship> relationshipsResult = new ArrayList<>();
String fromNode = relation.getFromNode();
String toNode = relation.getToNode();
List<CapabilityRequirementRelationship> relationships = relation.getRelationships();
if (relationships == null || relationships.isEmpty()) {
BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement definition sent in order to set the relation between {} to {}", fromNode, toNode);
loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATION.getName(),"componentId: "+componentId+" No requirement definition sent in order to set the relation between: "+fromNode+" to: "+toNode);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT));
}
for (final CapabilityRequirementRelationship relationship : relationships) {
final String requirement = relationship.getRelation().getRequirement();
Either<Map<JsonPresentationFields, T>, StorageOperationStatus> associateRes = connectInstancesInContainer(fromNode, toNode, relationship.getRelation(), relation.isOriginUI(), calculatedCapabilty, calculatedRequirement,
fullFilledCapabilty, fullfilledRequirement, compositionDataDefinition, containerV.getUniqueId());
if (associateRes.isRight()) {
status = associateRes.right().value();
BeEcompErrorManager.getInstance().logBeFailedAddingResourceInstanceError("AssociateResourceInstances - missing relationship", fromNode, componentId);
loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),
StatusCode.ERROR,"missing relationship: "+fromNode,"ComopnentId: "+componentId);
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to associate resource instance {} to resource instance {}. status is {}", fromNode, toNode, status);
return Either.right(status);
}
final Map<JsonPresentationFields, T> relationshipFieldsMap = associateRes.left().value();
final RelationshipInstDataDefinition relationshipInstData =
(RelationshipInstDataDefinition) relationshipFieldsMap.get(JsonPresentationFields.RELATIONSHIP);
createRelationshipInterfaces(relationship.getOperations()).ifPresent(relationshipInstData::setInterfaces);
RelationshipImpl relationshipImplResult = new RelationshipImpl();
relationshipImplResult.setType(relationshipInstData.getType());
RelationshipInfo requirementAndRelationshipPair = new RelationshipInfo(requirement, relationshipImplResult);
requirementAndRelationshipPair.setCapability(relationship.getRelation().getCapability());
requirementAndRelationshipPair.setRequirement(relationship.getRelation().getRequirement());
requirementAndRelationshipPair.setCapabilityOwnerId(relationshipInstData.getCapabilityOwnerId());
requirementAndRelationshipPair.setRequirementOwnerId(relationshipInstData.getRequirementOwnerId());
requirementAndRelationshipPair.setCapabilityUid(relationship.getRelation().getCapabilityUid());
requirementAndRelationshipPair.setRequirementUid(relationship.getRelation().getRequirementUid());
requirementAndRelationshipPair.setId(relationshipInstData.getUniqueId());
CapabilityRequirementRelationship capReqRel = new CapabilityRequirementRelationship();
capReqRel.setRelation(requirementAndRelationshipPair);
capReqRel.setCapability((CapabilityDataDefinition) relationshipFieldsMap.get(JsonPresentationFields.CAPABILITY));
capReqRel.setRequirement((RequirementDataDefinition) relationshipFieldsMap.get(JsonPresentationFields.REQUIREMENT));
capReqRel.setOperations(relationship.getOperations());
relationshipsResult.add(capReqRel);
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "update customization UUID for from CI {} and to CI {}", relation.getFromNode(), relation.getToNode());
status = updateCustomizationUUID(relation.getFromNode(), compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),StatusCode.ERROR,"ERROR while update customization UUID for from CI "+relation.getFromNode()+" and to CI: "+relation.getToNode());
return Either.right(status);
}
status = updateCustomizationUUID(relation.getToNode(), compositionDataDefinition);
if (status != StorageOperationStatus.OK) {
loggerSupportability.log(LogLevel.INFO,LoggerSupportabilityActions.CREATE_RELATIONS.name(),StatusCode.ERROR,"ERROR while update customization UUID for from CI "+relation.getFromNode()+" and to CI: "+relation.getToNode());
return Either.right(status);
}
}
RequirementCapabilityRelDef reqCapRelDef = new RequirementCapabilityRelDef(relation);
reqCapRelDef.setRelationships(relationshipsResult);
relationsList.add(reqCapRelDef);
}
status = updateAllAndCalculatedCapReqOnGraph(componentId, containerV, capResult, capFullResult, reqResult, reqFullResult);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
return Either.left(relationsList);
}
private Optional<ListDataDefinition<InterfaceDataDefinition>> createRelationshipInterfaces(
final List<OperationUi> operationList) {
if (CollectionUtils.isEmpty(operationList)) {
return Optional.empty();
}
final ListDataDefinition<InterfaceDataDefinition> interfaceList = new ListDataDefinition<>();
final Map<String, List<OperationUi>> operationByInterfaceType = operationList.stream()
.collect(Collectors.groupingBy(OperationUi::getInterfaceType));
for (final Entry<String, List<OperationUi>> interfaceEntry : operationByInterfaceType.entrySet()) {
interfaceList.add(createInterface(interfaceEntry.getKey(), interfaceEntry.getValue()));
}
return Optional.of(interfaceList);
}
private InterfaceDataDefinition createInterface(final String interfaceType, final List<OperationUi> operationList) {
final InterfaceDataDefinition interfaceDataDefinition = new InterfaceDataDefinition();
interfaceDataDefinition.setType(interfaceType);
if (CollectionUtils.isNotEmpty(operationList)) {
final Map<String, OperationDataDefinition> operationMap =
operationList.stream().collect(Collectors.toMap(OperationUi::getOperationType, this::createOperation));
interfaceDataDefinition.setOperations(operationMap);
}
return interfaceDataDefinition;
}
private OperationDataDefinition createOperation(final OperationUi operation) {
final OperationDataDefinition operationDataDefinition = new OperationDataDefinition();
operationDataDefinition.setName(operation.getOperationType());
operationDataDefinition.setUniqueId(UUID.randomUUID().toString());
final ArtifactDataDefinition implementation = new ArtifactDataDefinition();
implementation.setArtifactName(operation.getImplementation());
operationDataDefinition.setImplementation(implementation);
if (CollectionUtils.isNotEmpty(operation.getInputs())) {
final ListDataDefinition<OperationInputDefinition> inputs = new ListDataDefinition<>();
operation.getInputs().forEach(input -> {
final OperationInputDefinition operationInputDefinition = new OperationInputDefinition();
operationInputDefinition.setLabel(input.getName());
operationInputDefinition.setType(input.getType());
operationInputDefinition.setValue(input.getValue());
inputs.add(operationInputDefinition);
});
operationDataDefinition.setInputs(inputs);
}
return operationDataDefinition;
}
private StorageOperationStatus updateAllAndCalculatedCapReqOnGraph(String componentId, GraphVertex containerV, Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult,
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, 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, JanusGraphOperationStatus> updateElement = janusGraphDao.updateVertex(containerV);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new relations error {}. ", componentId, updateElement.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value());
}
// update cap/req jsons, fulfilled cap/req jsons!!!!!
Either<GraphVertex, JanusGraphOperationStatus> status;
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated capabilty for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update calculated requirement for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(reqResult.left().value().getLeft(), containerV, EdgeLabelEnum.CALCULATED_REQUIREMENTS);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update calculated requiremnt for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled capabilty for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(capFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled capabilty for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Update fullfilled requirement for container {}", containerV.getUniqueId());
status = updateOrCopyOnUpdate(reqFullResult.left().value().getLeft(), containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (status.isRight()) {
JanusGraphOperationStatus error = status.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update fullfilled requirement for container {} error {}", containerV.getUniqueId(), error);
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error);
}
return StorageOperationStatus.OK;
}
@SuppressWarnings({"unchecked"})
public Either<RequirementCapabilityRelDef, StorageOperationStatus> dissociateResourceInstances(String componentId, RequirementCapabilityRelDef requirementDef) {
if (requirementDef.getRelationships() == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation pair in request [ {} ]", requirementDef);
return Either.right(StorageOperationStatus.BAD_REQUEST);
}
String fromResInstanceUid = requirementDef.getFromNode();
String toResInstanceUid = requirementDef.getToNode();
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
GraphVertex containerV = containerVEither.left().value();
// DE191707 - validations
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(log, 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(log, LogLevelEnum.DEBUG, "TO instance {} isn't under container {}", toResInstanceUid, componentId);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Map<String, RelationshipInstDataDefinition> relations = compositionDataDefinition.getRelations();
List<CapabilityRequirementRelationship> relationPairList = requirementDef.getRelationships();
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.CALCULATED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabilityDataDefinition> calculatedCapability = capResult.left().value().getRight();
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capResult.isRight()) {
return Either.right(capResult.right().value());
}
Map<String, MapListCapabilityDataDefinition> fulfilledCapability = 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> fulfilledRequirement = reqFullResult.left().value().getRight();
for (CapabilityRequirementRelationship 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) && relationInJson.getUniqueId().equals(relationPair.getRelation().getId())) {
if (relationPair.getRelation().equalsTo(relationInJson)) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Remove relation from {} to {} capability {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationInJson.getType(), relationInJson.getCapabilityOwnerId(),
relationInJson.getRequirementOwnerId());
iterator.remove();
// update calculated cap/req
StorageOperationStatus status = updateCalculatedCapabiltyAfterDeleteRelation(calculatedCapability, fulfilledCapability, toResInstanceUid, relationInJson, relationPair);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
status = updateCalculatedRequirementsAfterDeleteRelation(calculatedRequirement, fulfilledRequirement, fromResInstanceUid, relationInJson, relationPair);
if (status != StorageOperationStatus.OK) {
return Either.right(status);
}
isDeleted = true;
}
}
}
if (!isDeleted) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No relation to delete from {} to {} capabilty {} capOwnerId {} reqOwnerId {} ", toResInstanceUid, componentId, relationPair.getCapability(),
relationPair.getRelation().getCapabilityOwnerId(), relationPair.getRelation().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);
}
/**
* Retrieves fulfilled requirement according to relation and received predicate
*
* @param componentId
* @param instanceId
* @param foundRelation
* @param predicate
* @return
*/
public Either<RequirementDataDefinition, StorageOperationStatus> getFulfilledRequirementByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation,
BiPredicate<RelationshipInfo, RequirementDataDefinition> predicate) {
Either<RequirementDataDefinition, StorageOperationStatus> result = null;
Either<Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>>, StorageOperationStatus> reqFullResult = null;
MapListRequirementDataDefinition reqMapOfLists = null;
Optional<RequirementDataDefinition> foundRequirement;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
if (result == null) {
GraphVertex containerV = containerVEither.left().value();
reqFullResult = fetchContainerCalculatedRequirement(containerV, EdgeLabelEnum.FULLFILLED_REQUIREMENTS);
if (reqFullResult.isRight()) {
result = Either.right(reqFullResult.right().value());
}
}
if (result == null) {
Map<String, MapListRequirementDataDefinition> fulfilledRequirement = reqFullResult.left().value().getRight();
reqMapOfLists = fulfilledRequirement.get(instanceId);
if (reqMapOfLists == null) {
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
if (result == null && reqMapOfLists != null) {
for (ListRequirementDataDefinition requirements : reqMapOfLists.getMapToscaDataDefinition().values()) {
foundRequirement = requirements.getListToscaDataDefinition().stream().filter(req -> predicate.test(relationshipInfo, req)).findFirst();
if (foundRequirement.isPresent()) {
result = Either.left(foundRequirement.get());
}
}
}
return result;
}
/**
* Retrieves fulfilled capability according to relation and received predicate
*
* @param componentId
* @param instanceId
* @param foundRelation
* @param predicate
* @return
*/
public Either<CapabilityDataDefinition, StorageOperationStatus> getFulfilledCapabilityByRelation(String componentId, String instanceId, RequirementCapabilityRelDef foundRelation,
BiPredicate<RelationshipInfo, CapabilityDataDefinition> predicate) {
Either<CapabilityDataDefinition, StorageOperationStatus> result = null;
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> capFullResult = null;
MapListCapabilityDataDefinition capMapOfLists = null;
Optional<CapabilityDataDefinition> foundRequirement;
RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
Either<GraphVertex, JanusGraphOperationStatus> containerVEither = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (containerVEither.isRight()) {
JanusGraphOperationStatus error = containerVEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, FAILED_TO_FETCH_CONTAINER_VERTEX_ERROR, componentId, error);
result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
if (result == null) {
GraphVertex containerV = containerVEither.left().value();
capFullResult = fetchContainerCalculatedCapability(containerV, EdgeLabelEnum.FULLFILLED_CAPABILITIES);
if (capFullResult.isRight()) {
result = Either.right(capFullResult.right().value());
}
}
if (result == null) {
Map<String, MapListCapabilityDataDefinition> fulfilledCapability = capFullResult.left().value().getRight();
capMapOfLists = fulfilledCapability.get(instanceId);
if (capMapOfLists == null) {
result = Either.right(StorageOperationStatus.NOT_FOUND);
}
}
if (result == null && capMapOfLists != null) {
for (ListCapabilityDataDefinition capabilities : capMapOfLists.getMapToscaDataDefinition().values()) {
foundRequirement = capabilities.getListToscaDataDefinition().stream().filter(cap -> predicate.test(relationshipInfo, cap)).findFirst();
if (foundRequirement.isPresent()) {
result = Either.left(foundRequirement.get());
}
}
}
return result;
}
private StorageOperationStatus updateCalculatedRequirementsAfterDeleteRelation(Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListRequirementDataDefinition> fullFilledRequirement, String fromResInstanceUid,
RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) {
StorageOperationStatus status;
String hereIsTheKey = null;
MapListRequirementDataDefinition reqByInstance = calculatedRequirement.get(fromResInstanceUid);
if (reqByInstance == null || reqByInstance.findKeyByItemUidMatch(relation.getRequirementId()) == null) {
// move from fulfilled
status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship);
} else {
hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
Optional<RequirementDataDefinition> requirementOptional = reqByType.getListToscaDataDefinition().stream()
.filter(req -> req.getOwnerId().equals(relation.getRequirementOwnerId()) && req.getName().equals(relation.getRequirement()) && req.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));
}
if (relationship != null) {
relationship.setRequirement(requirement);
}
status = StorageOperationStatus.OK;
} else {
// move from fulfilled
status = moveFromFullFilledRequirement(calculatedRequirement, fullFilledRequirement, fromResInstanceUid, relation, hereIsTheKey, relationship);
}
}
return status;
}
private StorageOperationStatus updateCalculatedCapabiltyAfterDeleteRelation(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid,
RelationshipInstDataDefinition relation, CapabilityRequirementRelationship relationship) {
StorageOperationStatus status;
String hereIsTheKey = null;
MapListCapabilityDataDefinition capByInstance = calculatedCapability.get(toResInstanceUid);
if (capByInstance == null || capByInstance.findKeyByItemUidMatch(relation.getCapabilityId()) == null) {
// move from fulfilled
status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship);
} else {
hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
Optional<CapabilityDataDefinition> capabilityOptional = capByType.getListToscaDataDefinition().stream().filter(cap -> cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId()))
.findFirst();
if (capabilityOptional.isPresent()) {
CapabilityDataDefinition capability = capabilityOptional.get();
String leftOccurrences = capability.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
capability.setLeftOccurrences(String.valueOf(leftIntValue));
}
if (relationship != null) {
relationship.setCapability(capability);
}
status = StorageOperationStatus.OK;
} else {
// move from fulfilled
status = moveFromFullFilledCapabilty(calculatedCapability, fullFilledCapability, toResInstanceUid, relation, hereIsTheKey, relationship);
}
}
return status;
}
private StorageOperationStatus moveFromFullFilledCapabilty(Map<String, MapListCapabilityDataDefinition> calculatedCapability, Map<String, MapListCapabilityDataDefinition> fullFilledCapability, String toResInstanceUid,
RelationshipInstDataDefinition relation, String hereIsTheKey, CapabilityRequirementRelationship relationship) {
MapListCapabilityDataDefinition capByInstance = fullFilledCapability.get(toResInstanceUid);
if (capByInstance == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability in fulfilled list for instance {} ", toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
if (null == hereIsTheKey)
hereIsTheKey = capByInstance.findKeyByItemUidMatch(relation.getCapabilityId());
if (null == hereIsTheKey) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability with id {} in fulfilled list for instance {} ", relation.getCapabilityId(), toResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
ListCapabilityDataDefinition capByType = capByInstance.findByKey(hereIsTheKey);
Iterator<CapabilityDataDefinition> iterator = capByType.getListToscaDataDefinition().iterator();
boolean found = false;
while (iterator.hasNext()) {
CapabilityDataDefinition cap = iterator.next();
if (cap.getOwnerId().equals(relation.getCapabilityOwnerId()) && cap.getUniqueId().equals(relation.getCapabilityId())) {
found = true;
iterator.remove();
// return to calculated list
String leftOccurrences = cap.getLeftOccurrences();
Integer leftIntValue = Integer.parseInt(leftOccurrences);
++leftIntValue;
cap.setLeftOccurrences(String.valueOf(leftIntValue));
MapListCapabilityDataDefinition mapListCapaDataDef = calculatedCapability.get(toResInstanceUid);
if (mapListCapaDataDef == null) {
mapListCapaDataDef = new MapListCapabilityDataDefinition();
}
ListCapabilityDataDefinition findByKey = mapListCapaDataDef.findByKey(hereIsTheKey);
if (findByKey == null) {
findByKey = new ListCapabilityDataDefinition();
mapListCapaDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(cap);
if (relationship != null)
relationship.setCapability(cap);
break;
}
}
if (!found) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No capability type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, 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, String hereIsTheKey, CapabilityRequirementRelationship relationship) {
MapListRequirementDataDefinition reqByInstance = fullFilledRequirement.get(fromResInstanceUid);
if (reqByInstance == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement in fullfilled list for instance {} ", fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
if (null == hereIsTheKey)
hereIsTheKey = reqByInstance.findKeyByItemUidMatch(relation.getRequirementId());
if (null == hereIsTheKey) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement with id {} in fulfilled list for instance {} ", relation.getRequirementId(), fromResInstanceUid);
return StorageOperationStatus.GENERAL_ERROR;
}
ListRequirementDataDefinition reqByType = reqByInstance.findByKey(hereIsTheKey);
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(hereIsTheKey);
if (findByKey == null) {
findByKey = new ListRequirementDataDefinition();
mapListReqDataDef.put(hereIsTheKey, findByKey);
}
findByKey.add(req);
if (relationship != null)
relationship.setRequirement(req);
break;
}
}
if (!found) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No requirement type {} with ownerId {} in fulfilled list for instance {} ", hereIsTheKey, relation.getRequirementOwnerId(), 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(log, 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 <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectInstancesInContainer(String fromResInstanceUid, String toResInstanceUid, RelationshipInfo relationPair, boolean originUI,
Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement, Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty,
Map<String, MapListRequirementDataDefinition> fullfilledRequirement, CompositionDataDefinition compositionDataDefinition, String containerId) {
String requirement = relationPair.getRequirement();
Map<String, ComponentInstanceDataDefinition> componentInstances = compositionDataDefinition.getComponentInstances();
CommonUtility.addRecordToLog(log, 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(log, 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(log, LogLevelEnum.DEBUG, "Failed to find to resource instance {}.", toResInstanceUid);
return Either.right(StorageOperationStatus.NOT_FOUND);
}
Either<Map<JsonPresentationFields, T>, StorageOperationStatus> reqVsCap = connectRequirementVsCapability(fromResourceInstData, toResourceInstData, relationPair, originUI, calculatedCapabilty, calculatedRequirement, fullfilledCapabilty,
fullfilledRequirement, containerId);
if (reqVsCap.isRight()) {
StorageOperationStatus status = reqVsCap.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to connect requirement {} between resource instance {} to resource instance {}. status is {}", requirement, fromResInstanceUid, toResInstanceUid, status);
return Either.right(status);
}
Map<JsonPresentationFields, T> relationship = reqVsCap.left().value();
// add to json new relations
compositionDataDefinition.addRelation(((RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP)).getUniqueId(), (RelationshipInstDataDefinition) relationship.get(JsonPresentationFields.RELATIONSHIP));
return Either.left(relationship);
}
private Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, StorageOperationStatus> fetchContainerCalculatedCapability(GraphVertex containerV, EdgeLabelEnum capLabel) {
Either<Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>>, JanusGraphOperationStatus> calculatedCapabiltyEither = getDataAndVertexFromGraph(containerV, capLabel);
if (calculatedCapabiltyEither.isRight()) {
JanusGraphOperationStatus error = calculatedCapabiltyEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilties for container {}.", containerV.getUniqueId(), error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
Pair<GraphVertex, Map<String, MapListCapabilityDataDefinition>> 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>>, JanusGraphOperationStatus> calculatedRequirementEither = getDataAndVertexFromGraph(containerV, reqLabel);
if (calculatedRequirementEither.isRight()) {
JanusGraphOperationStatus error = calculatedRequirementEither.right().value();
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated requirements for container {}.", containerV.getUniqueId(), error);
return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(error));
}
Pair<GraphVertex, Map<String, MapListRequirementDataDefinition>> calculatedRequirement = calculatedRequirementEither.left().value();
return Either.left(calculatedRequirement);
}
@SuppressWarnings("unchecked")
private <T extends ToscaDataDefinition> Either<Map<JsonPresentationFields, T>, StorageOperationStatus> connectRequirementVsCapability(ComponentInstanceDataDefinition fromResInstance, ComponentInstanceDataDefinition toResInstance,
RelationshipInfo relationPair, boolean originUI, Map<String, MapListCapabilityDataDefinition> calculatedCapabilty, Map<String, MapListRequirementDataDefinition> calculatedRequirement,
Map<String, MapListCapabilityDataDefinition> fullfilledCapabilty, Map<String, MapListRequirementDataDefinition> fullfilledRequirement, String containerId) {
String type = relationPair.getRelationship().getType();
// capability
String toInstId = toResInstance.getUniqueId();
MapListCapabilityDataDefinition mapListCapabilityDataDefinition = calculatedCapabilty.get(toInstId);
Map<JsonPresentationFields, T> capReqRelationship = new EnumMap<>(JsonPresentationFields.class);
if (mapListCapabilityDataDefinition == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for instance {} in container {}.", toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
ListCapabilityDataDefinition listCapabilityDataDefinition = mapListCapabilityDataDefinition.getMapToscaDataDefinition().get(type);
if (listCapabilityDataDefinition == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch calculated capabilities for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
CapabilityDataDefinition capabilityForRelation = 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())) {
capabilityForRelation = cap;
capReqRelationship.put(JsonPresentationFields.CAPABILITY, (T) capabilityForRelation);
String leftOccurrences = cap.getLeftOccurrences();
if (leftOccurrences != null && !leftOccurrences.equals(CapabilityDataDefinition.MAX_OCCURRENCES)) {
Integer leftIntValue = Integer.parseInt(leftOccurrences);
if (leftIntValue > 0) {
--leftIntValue;
capabilityForRelation.setLeftOccurrences(String.valueOf(leftIntValue));
if (leftIntValue == 0) {
// remove from calculated
iteratorCap.remove();
// move to fulfilled
MapListCapabilityDataDefinition mapListCapabiltyFullFilledInst = fullfilledCapabilty.get(toInstId);
if (mapListCapabiltyFullFilledInst == null) {
mapListCapabiltyFullFilledInst = new MapListCapabilityDataDefinition();
fullfilledCapabilty.put(toInstId, mapListCapabiltyFullFilledInst);
}
ListCapabilityDataDefinition listCapabilityFull = mapListCapabiltyFullFilledInst.findByKey(type);
if (listCapabilityFull == null) {
listCapabilityFull = new ListCapabilityDataDefinition();
mapListCapabiltyFullFilledInst.put(type, listCapabilityFull);
}
listCapabilityFull.add(capabilityForRelation);
}
break;
} else {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No left occurrences capabilty {} to {} in container {}.", capabilityForRelation.getType(), toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
if (capabilityForRelation == null) {
CommonUtility.addRecordToLog(log, 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(log, 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(log, 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;
capReqRelationship.put(JsonPresentationFields.REQUIREMENT, (T) requirementForRelation);
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 fulfilled
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(log, LogLevelEnum.DEBUG, "No left occurrences requirement {} from {} to {} in container {}.", requirementForRelation.getCapability(), fromInstId, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
}
}
}
if (requirementForRelation == null) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to fetch requirement for type {} for instance {} in container {}.", type, toInstId, containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
if (!capabilityForRelation.getType().equals(requirementForRelation.getCapability())) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "No macth for capability from type {} and requirement {} from {} to {} in container {}.", capabilityForRelation.getType(), requirementForRelation.getCapability(), fromInstId, toInstId,
containerId);
return Either.right(StorageOperationStatus.MATCH_NOT_FOUND);
}
RelationshipInstDataDefinition relationshipTypeData = buildRelationshipInstData(fromInstId, toInstId, relationPair, originUI);
if (requirementForRelation.getRelationship() != null)
relationshipTypeData.setType(requirementForRelation.getRelationship());
capReqRelationship.put(JsonPresentationFields.RELATIONSHIP, (T) relationshipTypeData);
return Either.left(capReqRelationship);
}
private RelationshipInstDataDefinition buildRelationshipInstData(String fromResInstanceUid, String toInstId, RelationshipInfo relationPair, boolean originUI) {
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.setCapabilityId(relationPair.getCapabilityUid());
relationshipInstData.setRequirementId(relationPair.getRequirementUid());
relationshipInstData.setFromId(fromResInstanceUid);
relationshipInstData.setToId(toInstId);
relationshipInstData.setRequirement(relationPair.getRequirement());
relationshipInstData.setCapability(relationPair.getCapability());
relationshipInstData.setOriginUI(originUI);
return relationshipInstData;
}
public <T extends Component> Map<String, ComponentInstanceDataDefinition> associateComponentInstancesToComponent(Component containerComponent, Map<ComponentInstance, T> componentInstanceTMap, GraphVertex containerVertex, boolean allowDeleted, boolean isUpdateCsar) {
String containerId = containerComponent.getUniqueId();
Map<String, ComponentInstanceDataDefinition> instancesJsonData;
Either<GraphVertex, JanusGraphOperationStatus> updateElement = null;
if (!validateInstanceNames(componentInstanceTMap)) {
throw new StorageException(StorageOperationStatus.INCONSISTENCY);
}
if (!allowDeleted) {
if (!validateDeletedResources(componentInstanceTMap)) {
throw new StorageException(StorageOperationStatus.INCONSISTENCY);
}
}
instancesJsonData = convertToComponentInstanceDataDefinition(componentInstanceTMap, containerId, isUpdateCsar);
if (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 = janusGraphDao.updateVertex(containerVertex);
if (updateElement.isRight()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update topology template {} with new component instances. ", containerComponent.getName());
throw new StorageException(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateElement.right().value()));
}
}
if (updateElement != null) {
GraphVertex vertexC = updateElement.left().value();
instancesJsonData.entrySet().forEach(i -> createInstanceEdge(vertexC, i.getValue()));
}
return instancesJsonData;
}
private <T extends Component> Map<String, ComponentInstanceDataDefinition> convertToComponentInstanceDataDefinition(Map<ComponentInstance, T> componentInstanceTMap, String containerId, boolean isUpdateCsar) {
Map<String, ComponentInstanceDataDefinition> instances = new HashMap<>();
for (Entry<ComponentInstance, T> entry : componentInstanceTMap.entrySet()) {
ComponentInstanceDataDefinition instance = buildComponentInstanceDataDefinition(entry.getKey(), containerId, null, !isUpdateCsar || entry.getKey().isCreatedFromCsar(), ModelConverter.convertToToscaElement(entry.getValue()));
instances.put(instance.getUniqueId(), instance);
}
return instances;
}
private <T extends Component> boolean validateDeletedResources(Map<ComponentInstance, T> resourcesInstancesMap) {
boolean result = true;
for (Component component : resourcesInstancesMap.values()) {
if (component.getIsDeleted() != null && component.getIsDeleted()) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Component {} is already deleted. Cannot add component instance. ", component.getName());
result = false;
break;
}
}
return result;
}
private <T extends Component> boolean validateInstanceNames(Map<ComponentInstance, T> resourcesInstancesMap) {
boolean result = true;
Set<String> names = new HashSet<>();
for (ComponentInstance instance : resourcesInstancesMap.keySet()) {
if (StringUtils.isEmpty(instance.getName())) {
CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
"Component instance {} name is empty. Cannot add component instance. ", instance.getUniqueId());
result = false;
break;
} else if (names.contains(instance.getName())) {
CommonUtility.addRecordToLog(log, 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) {
return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INST_DEPLOYMENT_ARTIFACTS, VertexTypeEnum.INST_DEPLOYMENT_ARTIFACTS);
}
public StorageOperationStatus addInformationalArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts) {
return addArtifactsToInstance(toscaElementId, instanceId, instDeplArtifacts, EdgeLabelEnum.INSTANCE_ARTIFACTS, VertexTypeEnum.INSTANCE_ARTIFACTS);
}
public StorageOperationStatus addArtifactsToInstance(String toscaElementId, String instanceId, Map<String, ArtifactDataDefinition> instDeplArtifacts, EdgeLabelEnum edgeLabel, VertexTypeEnum vertexType) {
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(toscaElementId, JsonParseFlagEnum.NoParse);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status);
}
MapArtifactDataDefinition instArtifacts = new MapArtifactDataDefinition(instDeplArtifacts);
return addToscaDataDeepElementsBlockToToscaElement(metadataVertex.left().value(), edgeLabel, vertexType, instArtifacts, instanceId);
}
@SuppressWarnings({"unchecked"})
public StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId) {
Either<GraphVertex, JanusGraphOperationStatus> metadataVertex = janusGraphDao
.getVertexById(componentId, JsonParseFlagEnum.ParseAll);
if (metadataVertex.isRight()) {
JanusGraphOperationStatus status = metadataVertex.right().value();
if (status == JanusGraphOperationStatus.NOT_FOUND) {
status = JanusGraphOperationStatus.INVALID_ID;
}
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(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) {
log.debug("Failed to update customization UUID for instance {} in component {} error {}", instanceId, componentId, status);
return status;
}
Either<GraphVertex, JanusGraphOperationStatus> updateVertex = janusGraphDao.updateVertex(metaVertex);
if (updateVertex.isRight()) {
log.debug("Failed to update vertex of component {} error {}", componentId, updateVertex.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updateVertex.right().value());
}
return StorageOperationStatus.OK;
}
public StorageOperationStatus generateCustomizationUUIDOnInstanceGroup(String componentId, String instanceId, List<String> groupInstances) {
if (groupInstances != null) {
Either<Map<String, MapGroupsDataDefinition>, JanusGraphOperationStatus> dataFromGraph = getDataFromGraph(componentId, EdgeLabelEnum.INST_GROUPS);
if (dataFromGraph.isRight()) {
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(dataFromGraph.right().value());
}
MapGroupsDataDefinition grInstPerInstance = dataFromGraph.left().value().get(instanceId);
if (grInstPerInstance == null) {
log.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) {
log.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(GroupInstanceDataDefinition::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 updateComponentInstanceCapabilityProperty(Component containerComponent, String componentInstanceId, String capabilityPropertyKey, ComponentInstanceProperty property) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
pathKeys.add(capabilityPropertyKey);
return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, VertexTypeEnum.CALCULATED_CAP_PROPERTIES, property, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus overrideComponentCapabilitiesProperties(Component containerComponent, Map<String, MapCapabilityProperty> capabilityPropertyMap) {
return overrideToscaDataOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.CALCULATED_CAP_PROPERTIES, capabilityPropertyMap);
}
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 updateComponentInstanceProperties(Component containerComponent, String componentInstanceId, List<ComponentInstanceProperty> properties) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_PROPERTIES, VertexTypeEnum.INST_PROPERTIES, properties, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus updateComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute property){
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return updateToscaDataDeepElementOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, property, pathKeys, JsonPresentationFields.NAME);
}
public StorageOperationStatus addComponentInstanceAttribute(Component containerComponent, String componentInstanceId, ComponentInstanceAttribute attribute){
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return addToscaDataDeepElementToToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_ATTRIBUTES, VertexTypeEnum.INST_ATTRIBUTES, attribute, 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 updateComponentInstanceInputs(Component containerComponent, String componentInstanceId, List<ComponentInstanceInput> properties) {
List<String> pathKeys = new ArrayList<>();
pathKeys.add(componentInstanceId);
return updateToscaDataDeepElementsOfToscaElement(containerComponent.getUniqueId(), EdgeLabelEnum.INST_INPUTS, VertexTypeEnum.INST_INPUTS, properties, 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);
}
public StorageOperationStatus createInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) {
String instUniqueId = componentInstance.getUniqueId();
// create edge between container and origin ( in case of proxy this edge will be to ProxyService node type)
StorageOperationStatus result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId).either(v -> StorageOperationStatus.OK,
DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (result == StorageOperationStatus.OK && componentInstance.getIsProxy()) {
// create edge between container and service origin
result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId)
.either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
return result;
}
public StorageOperationStatus createAllottedOfEdge(String componentId, String instanceId, String serviceUUID) {
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentId);
if (vertexById.isRight()) {
log.debug("Failed to fetch component metadata vertex for id {} error {}", componentId, vertexById.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexById.right().value());
}
GraphVertex metadataVertex = vertexById.left().value();
EnumMap<GraphPropertyEnum, Object> props = new EnumMap<>(GraphPropertyEnum.class);
props.put(GraphPropertyEnum.UUID, serviceUUID);
props.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
EnumMap<GraphPropertyEnum, Object> hasNot = new EnumMap<>(GraphPropertyEnum.class);
hasNot.put(GraphPropertyEnum.IS_DELETED, true);
Either<List<GraphVertex>, JanusGraphOperationStatus> byCriteria = janusGraphDao
.getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, props,hasNot, JsonParseFlagEnum.ParseMetadata );
if (byCriteria.isRight()) {
log.debug("Failed to fetch vertex by criteria {} error {}", props, byCriteria.right().value());
return DaoStatusConverter.convertJanusGraphStatusToStorageStatus(byCriteria.right().value());
}
List<GraphVertex> vertecies = byCriteria.left().value();
StorageOperationStatus result = StorageOperationStatus.OK;
if (vertecies != null) {
GraphVertex serviceVertex = vertecies.get(0);
//remove previous edges
log.debug("Try to create or update edge between resource {} and service {} ", metadataVertex, serviceVertex.getUniqueId());
// create edge between container and service reference
result = createOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.ALLOTTED_OF, serviceVertex.getUniqueId(), instanceId).either(v -> StorageOperationStatus.OK,
DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
return result;
}
public StorageOperationStatus removeInstanceEdge(GraphVertex metadataVertex, ComponentInstanceDataDefinition componentInstance) {
String instUniqueId = componentInstance.getUniqueId();
// create edge between container and origin ( in case of proxy this edge will be to ProxyService node type)
StorageOperationStatus result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.INSTANCE_OF, componentInstance.getComponentUid(), instUniqueId)
.either(v -> StorageOperationStatus.OK,
DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
if (componentInstance.getIsProxy()) {
// create edge between container and service origin
result = removeOrUpdateInstanceEdge(metadataVertex, EdgeLabelEnum.PROXY_OF, componentInstance.getSourceModelUid(), instUniqueId)
.either(v -> StorageOperationStatus.OK, DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
}
return result;
}
private Either<GraphVertex, JanusGraphOperationStatus> createOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) {
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid);
return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties)
.left()
.bind(v -> addInstanceToPropertyOnEdge(instUniqueId, v, metadataVertex))
.right()
.bind(s -> createInstanceEdge(metadataVertex, edgeLabel, componentUid, instUniqueId, s));
}
private Either<GraphVertex, JanusGraphOperationStatus> removeOrUpdateInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId) {
Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
properties.put(GraphPropertyEnum.UNIQUE_ID, componentUid);
return janusGraphDao.getEdgeByChildrenVertexProperties(metadataVertex, edgeLabel, properties).left().bind(v -> removeInstanceFromPropertyOnEdge(instUniqueId, v, metadataVertex)).right()
.map(err -> removeInstanceEdgeLogError(metadataVertex, edgeLabel, componentUid, err));
}
private Either<GraphVertex, JanusGraphOperationStatus> addInstanceToPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) {
// edge exist need to add instance id to list on edge's property
List<String> property = (List<String>) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES);
if (property == null) {
property = new ArrayList<>();
}
Optional<String> findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst();
if (!findFirst.isPresent()) {
property.add(instUniqueId);
}
try {
String jsonArr = JsonParserUtils.toJson(property);
log.debug("Update INSTANCES edge property with value {} ", jsonArr);
edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr);
} catch (IOException e) {
log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e);
return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
}
return Either.left(metadataVertex);
}
private Either<GraphVertex, JanusGraphOperationStatus> removeInstanceFromPropertyOnEdge(String instUniqueId, Edge edge, GraphVertex metadataVertex) {
// edge exist need to add instance id to list on edge's property
List<String> property = (List<String>) janusGraphDao.getProperty(edge, EdgePropertyEnum.INSTANCES);
if (property == null) {
property = new ArrayList<>();
}
Optional<String> findFirst = property.stream().filter(a -> a.equals(instUniqueId)).findFirst();
if (findFirst.isPresent()) {
property.remove(instUniqueId);
}
if (property.isEmpty()) {
// For last instance need to remove edge
edge.remove();
} else {
try {
String jsonArr = JsonParserUtils.toJson(property);
edge.property(EdgePropertyEnum.INSTANCES.getProperty(), jsonArr);
} catch (IOException e) {
log.debug("Failed to convert INSTANCES edge property to json for container {}", metadataVertex.getUniqueId(), e);
return Either.right(JanusGraphOperationStatus.GENERAL_ERROR);
}
}
return Either.left(metadataVertex);
}
private Either<GraphVertex, JanusGraphOperationStatus> createInstanceEdge(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, String instUniqueId, JanusGraphOperationStatus retrieveEdgeStatus) {
if (retrieveEdgeStatus == JanusGraphOperationStatus.NOT_FOUND) {
// create new edge
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(componentUid);
if (vertexById.isRight()) {
return vertexById;
}
GraphVertex originVertex = vertexById.left().value();
Map<EdgePropertyEnum, Object> edgeProps = new EnumMap<>(EdgePropertyEnum.class);
List<String> instList = new ArrayList<>();
instList.add(instUniqueId);
edgeProps.put(EdgePropertyEnum.INSTANCES, instList);
log.debug("Create new edge {} between {} and {} and properties {} ", edgeLabel, metadataVertex.getUniqueId(), originVertex.getUniqueId(), edgeProps);
JanusGraphOperationStatus
edgeResult = janusGraphDao
.createEdge(metadataVertex, originVertex, edgeLabel, edgeProps);
return edgeResult == JanusGraphOperationStatus.OK ? Either.left(metadataVertex) : Either.right(edgeResult);
}
// error
log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus);
return Either.right(retrieveEdgeStatus);
}
private JanusGraphOperationStatus removeInstanceEdgeLogError(GraphVertex metadataVertex, EdgeLabelEnum edgeLabel, String componentUid, JanusGraphOperationStatus retrieveEdgeStatus) {
if (retrieveEdgeStatus == JanusGraphOperationStatus.NOT_FOUND) {
log.debug("No edge {} to remove between container {} and origin {}", edgeLabel, metadataVertex.getUniqueId(), componentUid);
} else {
// error
log.debug("Failed to fetch edge with label {} and to vertex with id {} error {} ", edgeLabel, componentUid, retrieveEdgeStatus);
}
return retrieveEdgeStatus;
}
public void removeAllAllotedEdges(String uniqueId) {
Either<GraphVertex, JanusGraphOperationStatus> vertexById = janusGraphDao.getVertexById(uniqueId);
if (vertexById.isLeft()) {
GraphVertex originVertex = vertexById.left().value();
JanusGraphVertex vertex = originVertex.getVertex();
Iterator<Edge> edges = vertex.edges(Direction.OUT, EdgeLabelEnum.ALLOTTED_OF.name());
while (edges != null && edges.hasNext()) {
Edge edge = edges.next();
edge.remove();
}
}
}
}
|